Setting up simple sandboxed sftp for one user

Question: I'm building a UVPS for myself, just to use as a simple playground.  The user I need to have sftp access authenticates but get's booted.  I believe it's due to my hardening, but it could be something I just am oblivious to or don't know.  Can anyone help using the following info?
I've installed Ubuntu 10.04 and hardened it up pretty well (for my non sys admin knowledge-base), but I am having trouble connecting via SFTP via a limited user setup to be the only SFTP user (will also likely be used for rsync/git/hg access but one thing at a time).  I want this user restricted to it's home - so I've put that in the sshd_config.
The configuration consists exclusively of a Sudo user we'll call sudouser and a sftp user we'll call sftpuser.
Obfuscated sshd_config file:
Port 22

Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
UsePrivilegeSeparation yes

KeyRegenerationInterval 3600
ServerKeyBits 768

SyslogFacility AUTH
LogLevel INFO

LoginGraceTime 120
PermitRootLogin no
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes

IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication yes

X11Forwarding no
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes

AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

UsePAM yes
UseDNS no

AllowUsers sudouser sftpuser

Match User sftpuser
    ChrootDirectory %h
    ForceCommand /usr/lib/openssh/sftp-server
    AllowTcpForwarding no

I have generated a rsa key pair for sftpuser placed it's public in ~sftpuser/.ssh/ with sftpuser having 700 on it's .ssh directory and 600 on it's public key.
When attempting to connect via sftp in Netbeans, I get the following message:
Host '123.45.678.910' is known and mathces the RSA host key
SSH_MSG_NEWKEYS sent
SSH_MSG_NEWKEYS received
SSH_MSG_SERVICE_REQUEST sent
SSH_MSG_SERVICE_ACCEPT received
Authentications that can continue: publickey,keyboard-interactive,password
Next authentication method: publickey
Authentication succeeded (publickey).
Caught an exception, leaving main loop due to Connection reset
Disconnecting from 123.45.678.910 port 22
QUIT
Goodbye

It also connects with cyberduck, but immediately disconnects.
Some other details for anyone who might be interested in helping.
iptable rules:
*filter
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT

-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

-A INPUT -j REJECT
-A FORWARD -j REJECT

COMMIT

Misc Hardening
dpkg-statoverride --update --add root sudoers 4750 /bin/su
sudo sysctl -w net.ipv4.conf.all.accept_source_route=0
sudo sysctl -w net.ipv4.conf.default.accept_source_route=0

============================================================

EDIT01:  Response to poisonbit and Gilles (since there's overlap)
In the logs I do see it's an ownership issue.  My understanding (or lack there of) is that when I adduser as root, the permissions and files created from /etc/skeleton should be right… for this - but now I'm confused.
This was all done as root.
/usr/sbin/groupadd sudoers
/usr/sbin/adduser sudouser
mkdir ~sudouser/.ssh
mv /tmp/uploadpackage/sudouser.pub ~sudouser/.ssh/authorized_keys
chown -R sudouser:sudouser ~sudouser/.ssh
chmod 700 ~sudouser/.ssh
chmod 600 ~sudouser/.ssh/authorized_keys
/usr/sbin/usermod -a -G sudoers sudouser

:modified visudo:

/usr/sbin/adduser sftpuser
mkdir ~sftpuser/.ssh
mv /tmp/uploadpackage/sftpuser.pub ~sftpuser/.ssh/authorized_keys
chown -R sftpuser:sftpuser ~sftpuser/.ssh
chmod 700 ~sftpuser/.ssh
chmod 600 ~sftpuser/.ssh/authorized_keys

Examining the permissions, here's what I see:
sudouser@uvps:~$ sudo ls -l /
<snip>
drwxr-xr-x  4 root root   4096 Apr 10 16:39 home
<snip>

sudouser@uvps:~$ ls -l /home
drwxr-xr-x  4 sftpuser sftpuser 4096 Apr 10 17:03 sftpuser
drwxr-xr-x  4 sudouser sudouser 4096 Apr 10 16:58 sudouser

Should these be owned by root?
Are there files/folders that are not created by adduser that are needed to make a basic user?
I do apologize, I'm capable as a basic user of linux... but while most things are logical once you "get it" I feel like I'm always reading explanations of minutia/quirks in the manpages or google results when doing simple things.

============================================================

EDIT02:  Relevant /var/log/auth.log entries.
Apr 11 00:18:22 uvps sshd[8694]: Accepted publickey for sftpuser from 109.87.654.321 port 55555 ssh2
Apr 11 00:18:22 uvps sshd[8694]: pam_env(sshd:setcred): Unable to open env file: /etc/default/locale: No such file or directory
Apr 11 00:18:22 uvps sshd[8694]: pam_unix(sshd:session): session opened for user sftpuser by (uid=0)
Apr 11 00:18:22 uvps sshd[8706]: pam_env(sshd:setcred): Unable to open env file: /etc/default/locale: No such file or directory
Apr 11 00:18:22 uvps sshd[8706]: fatal: bad ownership or modes for chroot directory "/home/sftpuser"
Apr 11 00:18:22 uvps sshd[8694]: pam_unix(sshd:session): session closed for user sftpuser
Apr 11 00:18:22 uvps sshd[8694]: pam_env(sshd:setcred): Unable to open env file: /etc/default/locale: No such file or directory

The pam messages seem related to a bug Ubuntu Bug #155794 and likely aren't contributing - the fatal entry on the other hand :p

============================================================

EDIT03:  Update.
Changing the owner of ~sftpuser recursively caused authentication to fail.  By returning ownership of ~sftpuser/.ssh (-R) to sftpuser the sftp client could connect.  The new log entries were:
Apr 11 01:02:36 uvps sshd[8745]: Accepted publickey for sftpuser from 109.87.654.321 port 55555 ssh2
Apr 11 01:02:36 uvps sshd[8745]: pam_env(sshd:setcred): Unable to open env file: /etc/default/locale: No such file or directory
Apr 11 01:02:36 uvps sshd[8745]: pam_unix(sshd:session): session opened for user sftpuser by (uid=0)
Apr 11 01:02:36 uvps sshd[8756]: pam_env(sshd:setcred): Unable to open env file: /etc/default/locale: No such file or directory
Apr 11 01:02:36 uvps sshd[8756]: subsystem request for sftp
Apr 11 01:02:36 uvps sshd[8745]: pam_unix(sshd:session): session closed for user sftpuser
Apr 11 01:02:36 uvps sshd[8745]: pam_env(sshd:setcred): Unable to open env file: /etc/default/locale: No such file or directory

So perhaps the PAM bug (or the default config as provided by ubuntu) is in need of some love.  I'm reading about PAM, and it's so much more than I was hoping to get into just to get a simple sandboxed sftp operator in place.  Hmmm.

============================================================

EDIT04:  Reasonable confirmation.
Disabling PAM in the sshd_config file made it work.  So at this point anyone who follows this as reference in the future should be able to get this going w/o PAM.  As to PAM, I need to evaluate why I may/not need it and if/when I wrap my head around it and determine if it being on offers any substantial benefit for my uses, I'll update this.
Many thanks to the people that contributed... you led me to the problem and made it clear I really need to get better at logging, and analyzing the logs.  Frankly using ubuntudesktop/osx/windows has never really caused me need to spend a great deal of time in the logs.  Configuring even a simple server however...  Who can I credit the answer with?  Everyone helped.

============================================================

EDIT05:  Quirk?.
Re-enabled PAM to do the deeper logging that was recommended and reloaded SSH... and everything continued to work as it did with PAM disabled.  o.O
Comment: What is in the server logs? Are you sure you've created all the necessary files in the chroot?
Comment: Edited a response (in the main question) to both you and poisonbit and reviewing the logs points to an ownership issue.  I appreciate the response.
Comment: If you don't post the logs, we can't help you read them. The permissions look right for functionality, but `/home/sftpuser`, `/home/sftpuser/.ssh` and `/home/sftpuser/.ssh/*` should be owned by root, otherwise the SFTP user will be able to write to them and may be able to gain shell access (I'm not sure about that).
Comment: I agree with Gilles. For what it's worth, `adduser`'s default permissions are fine for normal login users, but do not work well with `sftp`.
Comment: Added relevant logs in main question
Comment: Hi @Cor I've find same problem, trying to fix UMASK option on internal-sftp sshd server directive.
infact this one, dosen't support umask. I've asked similar question here:
http://serverfault.com/questions/257396/sftp-chrooted-dosent-work-with-some-sftp-client-cyberduck check it out I've read all your question with attached solution, I will try on my env as soon as possible.
For me Cyberduck (and I thin yours netbeans) logon issue could be this openssh behaviour
http://www.openssh.org/faq.html#2.9 Let me now it could helpful for you.
Comment: Ah interesting will investigate this more.
Answer: Authentication succeeded (publickey). So it should be something after that... lets check:
ChrootDirectory
         Specifies the pathname of a directory to chroot(2) to after
         authentication.  All components of the pathname must be root-
         owned directories that are not writable by any other user or
         group.  After the chroot, sshd(8) changes the working directory
         to the user's home directory.

...

Is the home of the sftpuser user (and parent paths) owned by root and 700 (drwx------) ?
If owners of directories are ok, and write perms too, you can search for more info in /var/log on the ssh server, or try the sftp client from command line, adding the -v option, and send us the output.
Comment: Edited a response to both you and Gilles (in the main question) and reviewing the logs points to an ownership issue.  I appreciate the response.  Any thoughts on where my efforts are breaking down?  I'm googling how to connect to sftp from the shell right now (and will dump a -v if it turns out that the permissions are appropriate.)
Comment: Okay so I have re-read this answer and run chown -R on ~sftpuser and the authorization fails.  By making ~sftpuser/.ssh owned by sftpuser again I can authorize and I get a new log saying "subsystem request for sftp"!!! but then pam ends the session again.  Progress ;p
Answer: Under Subsystem and ForceCommand change
Subsystem sftp /usr/lib/openssh/sftp-server

to
Subsystem       sftp    internal-sftp

and change
ForceCommand /usr/lib/openssh/sftp-server

to
ForceCommand internal-sftp

Comment: Thanks.  Just tried... exact same result as the latest logs (EDIT03 above).  Definitely worth a try.
Comment: Before I move on, you did restart ssh after changing correct?
Comment: Yes... and I even meant to mention that - long day.  /etc/init.d/ssh reload
Comment: What is your log verbosity set to? If it's not set to debug please do so, and try logging in again and posting the results.
Comment: Just tried disabling PAM in the sshd_config and was able to gain access.  So it looks like a misconfigured PAM is the culprit (or the bug I noted above).  Don't know that I actually need PAM... but at least there's some clear and apparent cause here.  Thanks again for responding.  Off to update the main question.
Comment: We can work through pam as well if you'd like, the relelvant pam.d should sshd...also, I highly recommend upping your verbosity level to debug while troubleshooting, as well as trying to locally login using sftp -v
Comment: That's quite kind rfelsburg.  Will simply setting loglevel in the sshd_config do it, or is there another loglevel you are referring to?  Also I guess after reading up on PAM for a half hour, I'm wondering if I'll be using it in any worthwhile way for this endeavor.  Any thoughts on that for a one person LAPPP stack (Lin/Apache/Postgres/Php/Python) playground?
Comment: yes: loglevel debug will do it. In my opinion removing a layer of security due to some feature not working is always a bad idea unless you fully understand exactly what is happening and why you are disabling it. Also trying to manually login via the cli with 'sftp -v' will shed light as well.
Comment: It seems (from skimming the docs for PAM) that it adds all kinds of features securely, not really adds security to normal authentication - and my impression on running a server is that you only add what you must.  Please do correct me if I'm wrong on either count.  I have to relocate from work to home in a second, when I get home i will sftp from cli w/ -v flag and we'll take a look at PAM if your still up for that...  Again I really do appreciate you taking the time.
Comment: Assuming I'm still up, I'd be more than happy to help. As far as using PAM, any mechanism that will allow me to make my system is more secure is good. PAM is extremely powerful, and when utilized properly is quite a help to sysadmins.
Comment: Okay just to be difficult, the server decided that PAM was now okay to use.  Very bizarre.  I re-enabled it in the sshd_config file (along with LogLevel DEBUG3), reloaded ssh Cyberduck and Netbeans can negotiate it.  So essentially, WTF?!?!  Looking through the DEBUG log, lots of info makes sense... very useful.  Does PAM have a "reload" like feature that Disabling/Enabling it in sshd_config could trigger?
Comment: Just a followup to this.  I rebuilt the uvps (twice to confirm-confirm) incorporating the change (internal-sftp), ~sftpuser owned by root, and even properly set the locale [facepalm]... with PAM enabled on first try, no joy.  with PAM disabled on next try, no joy.  with PAM re-enabled, it works.  I haven't found any references to this, and really don't know what to make of it - but hey, I have chrooted sftp working consistently - and I suppose this will probably help someone someday.
Comment: Missed edit window:  PAM disabled on next try, no joy.  Should be PAM disabled on next try, it works.
Comment: Perhaps, pam disabled, pam enabled is being cached, and so it looks like pam enabled is working?

I'm not sure, but it's worth following up on. I'll see if I can duplicate on my end.


Point dns to vps - How dns works

Question: I'm moving from a sharedhosting to a VPS and I'm struggling with DNS'. My hosting company only provides me my VPS' IP, and my domain, say mydomain.com is registered a registrar called  bookmyname.com. This registrar seems to provide me with 3 DNS called nsa.bookmyname.com (and nsb, nsc).
After contacting my hosting company, they told me I had to run my own dns server because they didn't provide one for the basic VPS solution I have. I also read about setting up bind9 on my server, but I'm not sure if it's what I'm supposed to do in this case. How could I host the dns server on the same server that runs the web server.
Isn't the DNS supposed to make the connection between the client and the web server? I think I'm missing something fundamental here about how DNS works, what is it?
Answer: Basically your hosting provider does the initial DNS for your domain.
i.e. your registrar holds the details of your DNS Server settings and tells the world what they are and where to go.
If you arent't that technically minded and don't know how DNS works in the first place, I would use a third party because if your vps goes down or get's DOS'd then your dns goes down and if you haven't set up a backup dns server then you'll lose it all!
I use entrydns.net those guys have done well and love the simple admin interface. oh and it's free! Basically log in to your registrar control panel change DNS servers to entrydns.net ones (you'll be told them when you sign up). Then create a root A record pointing to your new VPS server and away you go :)
Answer: Well, talk to your registrar - where you registered bookmyname.com. They normally offer DNS servers as service for their customers. Otherwise use a free DNS service, or a cheap paid one.
Do NOT put up your own DNS. Regulations say your domain must have 2 DNS servers in TWO DIFFERENT NETWORKS - your VPN will be not following regulations.
And othewise - yes, there is a reason people get paid for administering machines. Consider hiring someone.
Comment: I agree, in general, that an amateur shouldn't run their own DNS when perfectly good services exist, but "not following regulations" is a little silly. No one's going to enforce it, and if you're running a single VPS as a novice sysadmin it probably doesn't much matter if your DNS isn't properly redundant.
Comment: @francoisr Seriously, I dont care what you think. Like the rules or not - they are here. I did not make them, you agreed to them. Follow them. "Novice question" is a reason to close. Don't like that - tell the people that should care (the admins) and see you get this changed. Being nice is not elitist. Ignoring the rules is rude.
Comment: bookmyname.com is my registrar, I edited my post to make this clearer.   What I don't understand is how do I get nsa.bookmyname.com to know that mydomain.com should point to my IP. I don't want to hire someone as I consider making things by myself highly educational.
Comment: Well, then start reading a book. How DNS works. If you do not even know the basics - then a short question wont help. THis is like going to a kitchen and asking for a shotcut to become a good cook. DNS is well documented. And you get nsa.bookmyname.com to know your domain name by WHATEVER MEANS THE REGISTRAR PROVIDES. THis is not even a DNS question - they likely have a web portal that you have to use. As such, it is customer support, off topic here. Contact their support. https://www.bookmyname.com/manager.cgi seems to allow to log into their management website.
Comment: Btw., from the FAQ: Novice questions are off topic here.
Comment: @TomTom Being a member of other StackExchange sites, I understand my question is on the limit of what is acceptable to ask here. However, I don't think it's a good thing to be that ellitist, I'm an enthusiast who likes to better himself trying new things. I'm pretty sure you've also been a beginner one day, just like I am. Hopefully I'll end up as qualified as you seem to be, but I hope I won't be as bitter.
Comment: Yes and no. A stupid little issue takes down your whole site - nice. Been there. Seen that. Not anymore. I use a third party service now, keeps everything running without problems.
Answer: Typically the registrar provides a 'primary' DNS entry that points to the DNS servers. The DNS servers provide the DNS records. Among other things, the DNS records include IP address or addresses of the server for various domain configurations, such as example.com, www.example.com, forums.example.com, etc. It also includes MX records, telling mail servers where to go, anti-spam entries, and several other records for varying purposes.
If your VPS provider does not provide DNS management service, I would recommend using a different provider. Rackspace, Linode, DigitalOcean, and many others offer easy to use DNS management tools as a part of their VPS/cloud server service.

Point dns to vps - How dns works


Not able to set a registry value in C#

Question: I have a windows form app called system_module. And I want it to startup with windows. Here is my code for that.
private void Form1_Load(object sender, EventArgs e)
    {

        string keyName = @"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
        {
            if (key == null)
            {
                // Key doesn't exist.
                key.SetValue("system_module", "Application Location");
            }
            else { }
        }
    }

But this is not creating a value in run/
I have searched the whole registry and found nothing referring to system_module except some irrelevant values.
P.S I do not know much about registry things. Sorry if my terminology is wrong. Hope you understand what I am trying to to.
I found the above code in some other question in this site. I don't know why this is not working.
Comment: `if (key == null) { key.SetValue ... }` is a bad idea. If it doesn't exist you add it, you don't set the value of the non-existing key.
Comment: It will throw a NullReferenceException instead since you can't call a method of an object that doesn't exist.
Comment: I thought Setvalue will create the key if it does not exist. Thank you very much.
Answer: You are not using the SetValue() - because the "Run"-Key exists
use:
if (key != null)
        {
            // Key doesn't exist.
            key.SetValue("system_module", "Application Location");
        }

and handle the key == null too to add the Run key (by default this key exists)
if you dont want to modify the key if your "system_module","Application Location" already exists you have to query the values beneath the "key"
Comment: Okay. I see now. Thanks. I have one other question. Does the setvalue() update the values if it exists?
Comment: @EmpereurAiman - Yes SetValue() updates the value! - btw: plz mark this answer as solution if it helped you

Not able to set a registry value in C#


How does a pipe organist deal with latency or delay?

Question: I've seen church setups (choir loft in back) where the organ console is 30 Meters or more away from the pipes.  That implies that there would be a minimum of 100 milliseconds from pipe sounds back to the organist's ears.  That would introduce around a 16th note or more late delay, depending on the tempo.  Also, an ensemble, choir or conductor may be near the organist, and thus far from the pipes.
So how does the organist play in time with the nearby conductor, choir or ensemble with that much delay from keyboard to sound?  (and unlike a piano, when the sound source is just a meter or few away from all the musicians).
If this is a learned performance skill, I'm wondering whether a similar skill is what allows keyboardist to perform using iPad apps (where delays can range from 50 to 100 mS between touch and audio).
One do any (newer?) church organists use headsets or monitor speakers to relay sound near instantaneously from the pipes to help play in time?
Comment: Here's an analogy:  I'm a big pinball fan.  Pin sims on a computer w/ a keyboard have near-instant response to keyboard inputs (for flippers, e.g.).  Pin sims on a touch screen have noticeable lag.  After a few hours' practice, I learned to flip early to get the proper in-game action.
Comment: Microphones and headsets are actually quite common, although not all organists like them. In some churches the Choir organ (located at the front) can be played from the console of the Main organ (at the back) which would be close to impossible without a monitoring system.
Comment: Related: http://music.stackexchange.com/questions/30323/when-does-audio-latency-matter-and-not-matter
Answer: Your suspicion that this is a learned skill is correct -- and this even applies when performing as a soloist! The organist must learn to disregard the timing information coming to their ears, and execute playing technique all relative to what their internalized musical image (and fingers and feet) are telling them.
Also consider that (especially with antique organs), there may be quite a lot of places where latency is introduced even before the sound is actually produced. Mechanical linkages, pneumatics, all the size of a building instead of the size of a desk, like the mechanics of a piano. Modern organs do away with much of this through the use of digital technology and electric linkages where they can, but of course the speed of sound is still more or less significant depending on the size of the room.
When performing in an ensemble, problems are solved in rehearsal and by the organist's familiarity with the instrument, room, and conductor. Generally the organ pipes and choir are situated at the same end of the room, so as long as the organ and choir are playing in time, the music will be correct for all of the listeners. This may be accomplished by the conductor simply following the timing of the organ accompaniment, rather than the organist following the conductor in some cases; in others the organist may have to "guess" where to place the next note based on what happened in rehearsal.
I have never heard of an acoustic organist using a monitoring system -- keep in mind this would probably require a full organ synthesizer be involved to actually generate the monitored sound if it were happening synchronously with the keys and asynchronously from the pipes. And any pickup-based monitoring would either be late, coming from a centrally-located room mic, or completely impractical due to the sheer number of close-mic pickups you would need to effectively monitor an instrument consisting of up to tens of thousands of pipes.
The iPad item is kind of a different question, but I would consider this kind of latency to be unacceptable in digital audio for most applications. Professional audio iPad (and other computer) applications should not have noticeable latency.
Comment: As my teacher explained: you just play, the choir and congregation follow. The worse I have experienced is having one particular *note* with an extra lag. Trying to play that one note 'early' was... challenging :)
Comment: Not sure about the latest iPads.  But with previous iOS models, the electronics seemed to take about 1 video frame time (16.7mS) to verify and locate the touch, and the OS took about 1 frame time to deliver a touch event to the app's run loop.  That's 33 mS.  Then there's another app-to-audio-DAC buffering latency of (2 or 3) * 5.8 mS added to the response.  So, on the order of 50 mS for any app, given the hardware available, even for Pro apps and perfect touch.
Comment: Actually, organs with mechanical action have the lowest delay. Key motion translates directly to valve motion (where else would the movement be "stored" on the way?). (Electro-)Pneumatic organs are notoriously slow because air is compressible and "buffers" energy inserted into the system. Electric action can be fast, but I have played several instruments that weren't. Mostly due to aging of components, or due to a time-consuming digital encoding-decoding process.
Comment: A quick comment about iPads, this is assuming of course that every touch of the iPad is a *perfect* touch and there is nothing inhibiting the screen.  It also depends a bit on the quality of the coding.
Answer: Large pipe organs with pneumatic action can take half a second until the air pressure gets to the pipe valves through bundles of lead pipelets.  Current-day organs tend to use mechanical action for the main console, but large organs with electromechnical action also introduced significant delay even if not as much as their pneumatic cousins.
Organists learn to compensate.  It's an acquired skill that the "house organist" of a particularly laggy organ might master better than visitors, and often it's the house organist's task to introduce instrument and player.
Note that there are also conductors who have mastered the skill of conducting a whole measure in advance, in order for the orchestra to properly anticipate.  It's a somewhat related skill.
Answer: Another interesting point to consider, is that some instruments of several manuals, have different actions (especially where refurbishments have been done at different times, where finances allow). For example, I recently played a Victorian 3-manual with the console some 50m from the pipes. The Choir organ had electric action, the Great organ Electropneumatic, the Swell organ Electric action, the Pedal organ had Electropneumatic action and the Swell Pedals were both poorly-balanced Machanical action, with the linkages beneath the floor, all the way to the swell boxes some 30ft up the wall in addition to the 50ft from the console. The micro-differences in latency from console to pipe was incredibly confusing and took me over half an hour to 're-tune' my latency responses! Having everything coupled to the Great and Pedals was an interesting symphonic experience though! I also adored the chiffing and creaking you only get with the character of pipes and action. I'm going back next week just for the sake of it!


Evaluating improper integrals using laplace transform

Question: I want to calculate the following improper integral using Laplace and transforms (and laplace transforms only).
$$\int_0^{\infty} x e^{-3x} \sin{x}\, dx$$
I propose the following method. I plan to use $\mathcal{L}(\int_0^x f(t) dt)=\frac{\mathcal{L}(f)(s)}{s}$.
So, first I need to find out the laplace transform of the integrand, which can be done using $\mathcal{L}({xf})=-\frac{dL(f)}{ds}=-\frac{d}{ds}(e^{-3x} \sin{x})=-\frac{d}{ds}(\frac{1}{(s+3)^2+1})=\frac{2(s+3)}{((s+3)^2)+1)^2}$
So, my first formula for the transform of an integral means I have to calculate the inverse transform of $\frac{2(s+3)}{s((s+3)^2)+1)^2}=2[\frac{1}{((s+3)^2)+1)^2}+\frac{3}{s((s+3)^2)+1)^2}]$. I am stuck after this. How do I calculate this inverse transform?
Is this the right method I am using? If yes, how do I calculate the inverse transform w/o using the bromwich integral.
Answer: Hint: Consider the more general integral

$$ \int_{0}^{\infty} x\sin(x) e^{-sx} dx $$

which is the Laplace transform of $x\sin(x)$. You need to use the following property

$$ L(xf(x))= -F'(s). $$

So, basically, you need to find only the Laplace transform of $\sin(x)$
Comment: Awesome! Thanks.
Comment: @ramanujan_dirac: You are welcome. By the way, do not forget to subs $s=3$ at the end.


RangeError (RangeError (index): Invalid value: Only valid value is 0: 1)

Question: I defined a nested Map object like following:
  late Map<String, dynamic> book = {
    'storeId': '',
    'title': '',
    'images': [image]
  };

   Map<String, dynamic> image = {
    'imageUrl': '',

  };

then tried to add 2 new images like following:
book['images'][0] = 'url-to-image';
book['images'][1] = 'url-to-image2'; // Error happens here

And supposed the [image] list inside the Mapwill act like aList images`, But I encountered this error:

RangeError (RangeError (index): Invalid value: Only valid value is 0:
1)

Why this happened as I declared 'images': [image] as a List?  Does that mean if I want to have a List of image I should do something like below?
  late Map<String, dynamic> book = {
    'storeId': '',
    'title': '',
    'images': [image, image]
  };

What if I don't know the number of images and want the user to be able to add as much as they want?
Does it mean a list inside a Map doesn't behave like a List object like below?
List<image> images;
images[0] = 'url';
images[1] = 'url2'; //No Error

With no need to any initialization like:
List<image> images = [ image1, image2];

Comment: In dart, array indexes start at 0. So your first image is `book['images'][0]`
Comment: "Why this happened as I declared 'images': [image] as a List? In your own words, if the list is `[image]`, how many things do you think it contains? What do you think are the valid indices for the list? What do you think you should get if you use the index `1` into that list?
Comment: @KarlKnechtel: I wanted to add a variable to index 1 like what I can do with `List` with no need to initialize it beforehand.
Comment: In your own words, why do you think you are adding it to index 1? (hint: if the error message says `RangeError (index)`, that means it's telling you that the index is wrong, yeah? If it says "Only valid value is 0", what do you suppose it means is the thing that can only be 0? The index, perhaps?)
Comment: @KarlKnechtel: I am new to Flutter and wanted to make sure if I can do what I can do with `List`s by `Map`s or not. I added more detail to my question.
Comment: I've never used Flutter; but in **most** programming languages, anything that calls itself a "list", "array", "vector" etc. that you *index into* by using *integers*, will expect you to start counting at **0, not 1**. It seems like the error message is already explaining this quite clearly.
Comment: @KarlKnechtel: I think we are not in a same page! I know the indices start from 0. I am asking a different question!
Comment: @KarlKnechtel: I added more information to the question hope help you understand what I am asking.
Answer: Only valid value is 0: 1 means it contains a single element on index 0, where you are trying to get index 1. Which is out of range. A safe case I prefer checking the length before accessing index.
book['images'].length>1? book['images'][1]: yourDefaultValue


Flush cache on specific drupal 8 page/route

Question: I am building a CRUD form in Drupal 8. Users get navigated to it from a list that shows the entities they are editing. After an edit or add they get redirected to the list again. The list is generated in a twig template that is being cached. It's a custom route/controller.
How do i invalidate/delete the cache on that specific list page/route after an edit/add of an entity?
The data in the list is build in custom action, it's no view, and as far as drupal knows, there are no nodes shown in the template. So no default cache functions are triggered.
Answer: AFAIK, cache invalidation should not depend on the page or route. When an entity (eg. node #5) is changed, it should in validate all caches tagged with "node:5". If the list of entities is correctly tagged with its cache dependencies, you should be fine.
I realize this answer is rather theoretical and not very specific. Hopefully other answers will be more detailed.
Comment: What kind of page is it? Is it a view (as generated by the Views module) or custom code? The Views module should add the appropriate cache tags automatically. If it's a custom module, it is your (the developer's) task to add the [cache tags](https://www.drupal.org/developing/api/8/cache/tags). A node's cache tags can be retrieved using `$node->getCacheTags()`. You can get the entity type's "list cache tag" (which is cleared when new entities are added) using the `EntityType::getListCacheTags()` method on an entity type object.
Comment: So Drupal invalidates the cache based on what node or user is being shown. But on my list pages, drupal doesn't know what node or user is being shown.
Comment: Thanks! Great read. But i found no solution. I took a look at the cache tables and found entry's in the dynamic_page table. Removing these solved my problem. Then i checked the tags on these entry's, they had the tag:rendered. Now on each add & edit action, i do Cache::invalidateTags(array('rendered'));. But later on i will have more custom pages with this tag that don't need new cache files in these situations. Is there a way to add a specific tag to a route/url? I can't find anything related to it. Only some documentation about the cache context that comes close to it, but that's not suffice


How fast does a circular disc of spilled oil spread?

Question:
An open can of oil is accidently dropped into a lake; assume the oil spreads over the surface as a circular disc of uniform thickness whose radius increases steadily at the rate of 10 cm/sec. At the moment when the radius is 1 m, the thickness of the oil slick is decreasing at the rate of 4 mm/sec. How fast is it decreasing when the radius is 2 m?

As the volume of the open can is fixed (let us say $V$), let the radius of the circular disc in lake be $r$ and the thickness of the circular disc be $h$.
$$V=\pi r^2h$$
$$\frac{dr}{dt}=\frac{10}{100}$$
$$\frac{dV}{dt}=0=\pi(r^2\frac{dh}{dt}+2rh\frac{dr}{dt}).........(1)$$
$$r^2\frac{dh}{dt}+2rh\frac{dr}{dt}=0$$
When $r=1,\frac{dh}{dt}=\frac{-4}{1000}$ and when $r=2,\frac{dh}{dt}=?$
$$(1)^2\times \frac{-4}{1000}+2(1)h\times \frac{10}{100}=0$$
$$h=\frac{2}{100}$$
When $r=2,$
$$(2)^2\frac{dh}{dt}+2(2)(\frac{2}{100})(\frac{10}{100})=0$$
$$\frac{dh}{dt}=-0.002 \mathrm{m/sec}$$
But the answer given in my book is $-0.0005$ m/sec.
Comment: How did I manage to misspell *does* as *dis*?
Answer: The error in your method is that you found the height at the moment when $r=1$ and used it to find the change in height when $r=2$, however since the height is changing this doesn't work. It's easier to find a fixed value, i.e. the volume, as I've done below. We have
$$ h = \frac{V}{\pi r^2} \implies \frac{dh}{dt} = -\frac{2V}{\pi r^3} \frac{dr}{dt} $$
substitute in $r=1$ and $\frac{dh}{dt} = -0.004$
$$ -0.004 = -\frac{2V}{\pi (1)^3} 0.1 \implies \frac{2V}{\pi} = 0.04 $$
now use this volume when $r=2$
$$ \frac{dh}{dt} = -\frac{2V}{8 \pi } 0.1 = -\frac{2( 0.02\pi )}{8\pi}0.1 = -0.0005 $$
Answer: The problem is that you took the thickness at r=1m and considered it the thickness at r=2m.
You need to calculate the new thickness at r=2m from the volume.
Comment: Why make everyone turn their head/computer/tablet/phone sideways to read what you wrote when there is [a perfectly functional equation formatting system (MathJax)](https://math.stackexchange.com/help/notation) available?
Comment: I have to say this is marvelous handwriting, at least compared to my scrawl.
Comment: xD thanks you I guess. Are you interested in a question about directional derivatives? I posted it a couple of days ago but got nothing.
Comment: I'm using my phone and I couldn't use MathJax before but I did today after this post, sorry for the picture being sideways, I'll edit it.
Answer: After I fixed a mistake in my computations, I got $-0.0005$m/sec.
Since $r'(t)=\frac1{10}$ and $r(0)=1$ we get $r(t)=\frac1{10}t+1$. Using $V=\pi r^2(t)h(t)$ we get
$$
h(t)=\frac{V}{\pi r^2(t)}\text{ and }h'(t)=-\frac{2Vr'(t)}{\pi r^3(t)}=-\frac{V}{5\pi \left(\frac1{10}t+1\right)^3}.
$$
Since
$$
-\frac4{1000}=h'(0)=-\frac{V}{5\pi \left(\frac1{10}\cdot 0+1\right)^3}=-\frac{V}{5\pi}
$$
we get $V=\frac{2\pi}{100}$ and therefore
$$
h'(t)=-\frac{4}{1000\left(\frac1{10}t+1\right)^3}.
$$
Now consider $2=r(t)$ iff $t=10$ and we get
$$
h'(10)=-\frac{4}{1000\left(\frac1{10}\cdot 10+1\right)^3}=-\frac{4}{8000}=-0.0005.
$$
Answer: You have that $h$ changes so $h$ at $r=1$ is not the same as $h$ at $r=2$.
You have that at $r=1$ that $$V=\pi\frac{2}{100}=\frac{\pi}{50}$$
And since $V$ doesn't change for  $r=2$ $$\frac{\pi}{50}=2^2h\pi=4h\pi\\\frac{1}{200}=h$$
Now plugging in your formula
$$2^2\frac{dh}{dt}+2(2)\left(\frac1{200}\right)\frac{10}{100}=0$$
From this follows that
$$\frac{dh}{dt}=-0.0005\frac{m}{\sec}$$


Create pinnable shortcut on desktop C# - .website extension

Question: Trying to create a .website shortcut (pinnable shortcut) on the desktop via a button click (C#).
I have the existing code (that works - but the browser opens and immediately closes)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ShortcutUpdater
{
    public partial class UserControl1 : UserControl
    {

    private void urlShortcutToDesktop(string linkName, string linkUrl)
    {
        string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

        using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".website"))
        {
            writer.WriteLine("[InternetShortcut]");
            writer.WriteLine("URL=" + linkUrl);
            writer.Flush();
        }
    }

        public UserControl1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string linkName = "My Site";
            string linkUrl = "https://Asite.org";
            urlShortcutToDesktop(linkName, linkUrl);
        }

The file created looks like this when opened in Notepad:
[InternetShortcut]
URL=https://Asite.org

If I create a pinnable shortcut by dragging the icon to my desktop from the browser and then open it with Notepad, it looks like this (and is what I want to achieve so it won't just open then close the browser):
[{000214A0-0000-0000-C000-000000000046}]
Prop4=31,asite.org
Prop3=19,11
[{A7AF692E-098D-4C08-A225-D433CA835ED0}]
Prop5=3,0
Prop9=19,0
[InternetShortcut]
URL=https://asite.org/
IDList=
IconFile=https://asite.org/favicon.ico
IconIndex=1
[{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}]
Prop5=8,Microsoft.Website.50DFA192.38C0BBDC

What is the best way to accomplish this?
Comment: May not be your code that is causing this to happen. It may be a Windows security prohibiting application to access certain threads or functionality on your computer (i.e internet)
Comment: So I should not be trying to recreate the "Prop4=blah blah, Prop2=blah blah" stuff?

I am not sure what those are - or how to access/create them.
Comment: Have you tried to right click the pinnable shortcut and seen the access properties it has? Maybe needs admin?
Comment: When I click on the properties of each - they are utterly identical in the 'General tab', the 'Security Tab', and the 'Details Tab'. Quite literally the only difference is all those lines that say "Prop4=blahblah"
Comment: I created multiple shortcuts and the Prop numbers are always the same but the long strings in brackets change.
Answer: There is in fact an official programming interface to create internet shortcuts. Unfortunately, the interfaces aren't readily available to .NET programs, and there is no type library either for use with Tlbimp.exe (Type Library Importer). That leaves only two options: Trying to replicate the interface definitions in C#, or using a native implementation.
I'll propose going with a native implementation, specifically, a C++/CLI Class Library, that can be immediately consumed1 by .NET code. The implementation consists of 2 types: A native implementation class (InternetShortcutImpl) and a proxy to expose the functionality to managed code, implemented as a ref class (InternetShortcut). Both classes can be placed in the same file.
This is the implementation of the native access class:
#pragma once

#include <comip.h>
#include <comdef.h>
#include <IntShCut.h>
#include <ShObjIdl.h>
#include <string>

using namespace System::Runtime::InteropServices;

_COM_SMARTPTR_TYPEDEF( IUniformResourceLocatorW, __uuidof( IUniformResourceLocatorW ) );
_COM_SMARTPTR_TYPEDEF( IPersistFile, __uuidof( IPersistFile ) );
_COM_SMARTPTR_TYPEDEF( IShellLinkW, __uuidof( IShellLinkW ) );
class InternetShortcutImpl
{
public:
    InternetShortcutImpl()
    {
        HRESULT hr = ::CoCreateInstance( CLSID_InternetShortcut, nullptr,
                                         CLSCTX_INPROC_SERVER,
                                         IID_IUniformResourceLocatorW,
                                         (void**)&m_spURL );
        if ( FAILED( hr ) ) {
            throw gcnew ExternalException( nullptr, hr );
        }
    }

    void SetURL( const std::wstring& url ) {
        HRESULT hr = m_spURL->SetURL( url.c_str(), 0x0 );
        if ( FAILED( hr ) ) {
            throw gcnew ExternalException( nullptr, hr );
        }
    }

    void SetIconLocation( const std::wstring& iconpath, int index ) {
        IShellLinkWPtr spLink;
        HRESULT hr = m_spURL->QueryInterface( IID_PPV_ARGS( &spLink ) );
        if ( SUCCEEDED( hr ) ) {
            hr = spLink->SetIconLocation( iconpath.c_str(), index );
        }
        if ( FAILED( hr ) ) {
            throw gcnew ExternalException( nullptr, hr );
        }
    }

    void Save( const std::wstring& pathname, bool remember ) {
        IPersistFilePtr spFile;
        HRESULT hr = m_spURL->QueryInterface( IID_PPV_ARGS( &spFile ) );
        if SUCCEEDED( hr ) {
            hr = spFile->Save( pathname.c_str(), remember ? TRUE : FALSE );
        }
        if ( FAILED( hr ) ) {
            throw gcnew ExternalException( nullptr, hr );
        }
    }
private:
    IUniformResourceLocatorWPtr m_spURL;
};

And this is the proxy class, that essentially only forwards calls from .NET to the native class, which it contains as a member:
#include <msclr\marshal_cppstd.h>

using namespace System;

namespace ShortcutInteropLib {
#pragma warning(push)
#pragma warning(disable : 4461)  // "this class has a finalizer but no destructor"
    public ref class InternetShortcut
    {
    public:
        InternetShortcut() {
            m_pImpl = new InternetShortcutImpl();
        }

        void SetURL( String^ url ) {
            m_pImpl->SetURL( msclr::interop::marshal_as<std::wstring>( url ) );
        }

        void SetIconLocation( String^ iconpath, int index ) {
            m_pImpl->SetIconLocation( msclr::interop::marshal_as<std::wstring>( iconpath ),
                                      index );
        }

        void Save( String^ pathname, bool remember ) {
            m_pImpl->Save( msclr::interop::marshal_as<std::wstring>( pathname ),
                           remember );
        }

        !InternetShortcut() {
            delete m_pImpl;
        }

    private:
        InternetShortcutImpl* m_pImpl;
    };
#pragma warning(pop)
}

This forms the entire library, which can be referenced from a .NET assembly. The calling code is trivially easy:
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var shortcut = new InternetShortcut();
        shortcut.SetURL(@"http://www.example.com");
        //shortcut.SetIconLocation(@"http://www.example.com/favicon", 1);
        shortcut.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
                      + @"\MyShortCut.url", false);
    }
}

This creates a shortcut to http://www.example.com on the desktop. Note that while I implemented a SetIconLocation, I don't know how to use it with URLs. While the icon index is properly stored in the resulting MyShortCut.url file, the path is interpreted as a path into the local filesystem2.
The code produces the following internet shortcut on my system:

[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
[InternetShortcut]
IDList=
URL=http://www.example.com/

1 Since a C++/CLI class library contains native code, you'll have to select a target architecture. Client code must reference the appropriate assembly.
2 I don't know if there is a special syntax that allows to pass a URL, and not have the system interpret the argument as a local filesystem path. If anyone knows, I would be happy to hear about it.


Increasing timeout for mod_proxy_ajp connections

Question: I've got my apache (2.2.3) talking to tomcat 6.something through mod_proxy_ajp.
I have some ridiculously long lived requests (2-6 minutes) and I think we're hitting some default timeout somewhere... where is the correct place to bump that up?
here is my proxy def:
<Location /blah>
  ProxyPass ajp://localhost:8010/blah
  ProxyPassReverse ajp://localhost:8010/blah
</Location>

Answer: I can't say I've tried this, but I was interested in the question, so I did a bit of googling around and found this:

ProxyTimeout directive
This directive allows a user to specifiy a timeout on proxy requests. This is useful when you have a slow/buggy appserver which hangs, and you would rather just return a timeout and fail gracefully instead of waiting however long it takes the server to return.

The default value is the value of the Timeout directive, which in turn defaults to 300 seconds.  So try bumping up ProxyTimeout and see if it helps.
P.S.  Keep in mind that Tomcat might have its own timeout(s), too.  This document has some more information (although, keep in mind, I don't have personal experience with these settings).
Answer: If you'd like to change the timeout just for the ajp proxy and not globally you can add the "timeout" parameter, like so:
<Location /blah>
  ProxyPass ajp://localhost:8010/blah timeout=600
  ProxyPassReverse ajp://localhost:8010/blah
</Location>


pandas aggregate column doesnt exist?

Question: Currently i have a dataframe that i am preforming a group by on with aggregate functions. these are the functions
<code>            aggregation_functions = {
            '12_months': 'sum',
            '24_months': 'sum',
            '36_months': 'sum',
            'number_36_months': 'sum'
            }
</code>
when i do the group by it is dropping an ID column that is classed as a "nuisance"
but when i add the aggregate function for this ID column im getting the error:
<code>[ERROR] 03/25/2022 12:24:44 PM - Column(s) ['id'] do not exist
</code>
this is the aggregation im trying to add and this is the group by
<code>'id': 'nunique'
final_df = df.groupby(['buy_country', 'buy_activity', 'vd_country', 'vd_activity'], as_index=False).aggregate(aggregation_functions)
</code>
the column does exist in the data frame df
does anyone know why it thinks the column doesnt exist or how to get the aggregate function for this column to work ?
example of the data:

id
buy_country
buy_activity
vd_country
vd_activity
number_of_buyers
36_months
24_months
12_months
number_36_months

000002
GB
Not Matched
GB
Not Matched
1
0
0
0
1

000002
GB
Not Matched
GB
Not Matched
1
0
0
0
4

000002
GB
Not Matched
GB
Not Matched
1
0
0
0
2

000002
GB
Not Matched
GB
Not Matched
1
0
0
0
1
Comment: Please can you provide the output of `print(df.head(5))`
Comment: @Corralien the table looks fine in the preview but then prints horribly sorry
Comment: managed to fix the table was a spacing issue
Answer: Are you sure that id is a column and not an index?
You could try resetting the index of your DataFrame before you groupby:
<code>df = df.reset_index()
final_df = df.groupby(['buy_country', 'buy_activity', 'vd_country', 'vd_activity'], as_index=False).aggregate(aggregation_functions)
</code>
Comment: it was used in as an index in a join before the group by thank you

pandas aggregate column doesnt exist?


Displaying arbitrarily nested JSON via angular controller

Question: Here is a function I'm trying to use to be able to display JSON to a page. I know that I'm declaring elements over and over again, but I can't seem to get anything to work. Any help is vastly appreciated. Thanks!
bubbleController.controller('jsonDisplay', ['$scope',   function($scope) {
    this.list = $scope.json;
    this.doc = angular.element(document);
    this.curr = null;

    this.printList = function(item) {
        if (this.curr == null){
            this.curr = this.doc;
        }
        temp = angular.element("
");
        this.curr.append(temp);
        this.curr = temp;
        for (key in item){
            if (typeof item[key] === 'object'){
                this.printList(item[key]);
            }
            else{
                temp = angular.element("
");
                this.curr.append(temp);
                this.curr = temp;
                temp = angular.element("item[key]");
                this.curr.append(temp);
                this.curr = temp;
                temp = angular.element("
");
                this.curr.append(temp);
                this.curr = temp;
            }
        }
        temp = angular.element("
");
        this.curr.append(temp);
        this.curr = temp;
    }

}]);

Here is the example JSON I'm using
{
    "firstName": "Johnny",
    "lastName": "Cage",
    "women": [
        {
            "True": "Sonya"
        },
        {
            "False": "Mileena"
        }
    ]
}

Comment: can you show your template file? Why are you trying to build HTML from the controller?
Answer: It is no problem nesting templates recursively with the ng-include directive.
###########################
# controller.js
###########################
module.controller(function($scope) {
    // this controller uses  "template.html"
    $scope.data = {
        field1: "hello",
        field2: {
            field3: "world"
        }
    }

    $scope.canRecurse = function(v) {
        return Array.isArray(v) || typeof v == 'object';
    };
});

###########################
# template.html
###########################

###########################
# template-helper.html
###########################

{{key}}

{{value}}

Comment: i edited my answer. This could be done better with a ng-switch
Comment: This somewhat works, but doesn't recurse with nested arrays


Marginal distribution for a set of discrete events in continuous time

Question: Assume we have a set of four events $\{(k_1,t_1),...,(k_4,t_4)\}$ where the $k_i$ label the type of event from a finite set of possible events, and the $t_i$ their respective times, with $t_i < t_{i+1}$. Let us define $P(\{(k_1,t_1),...,(k_4,t_4)\})$ as the probability of this set of events happening within intervals $dt_i$ around the times $t_i$.
Now we would like to know the marginal distribution of only the first and fourth event which should be
$$
P(\{(k_1,t_1),(k_4,t_4)\}) = \sum_{k_2,k_3}\int_{t_1}^{t_3}dt_2\int_{t_2}^{t_4}dt_3 P(\{(k_1,t_1),...,(k_4,t_4)\}).
$$
The sums are fine, but the integrals seem problematic due to their limits. We know the first event happens before the second one, so $t_1$ is the lower limit for the $t_2$ integral. That's fine. But similarly since we know the third event happens after the second, $t_3$ is the upper limit of that integral. But for the same reason $t_2$ is also the lower limit for the $t_3$ integral. So we have a double integral where one of the limits of the first integral is the integration variable of the second integral and vice versa.
If on the other hand we were looking for say $P(\{(k_1,t_1),(k_3,t_3)\})$ this should be much more straight forward since each marginalised event is separated by a non-marginalised event, so the integration limits are well defined.
Is there something wrong with the definition of this marginal? If not, how can such an integral be evaluated?
Answer: The double integral is nested, and you cannot "separate" them. Since $t_1 < t_2 < t_3 < t_4$, to obtain the joint pdf of $(t_1, t_4)$, we can integrate by
$$ \int_{t_1}^{t_4}\int_{t_2}^{t_4} f(t_1, t_2, t_3, t_4) dt_3dt_2
= \int_{t_1}^{t_4}\int_{t_1}^{t_3} f(t_1, t_2, t_3, t_4) dt_2dt_3 $$
So the limits depends on the order of integration. If you integrate with respect to $t_3$ first, then the "tightest" bound would be $(t_2, t_4)$, and after $t_3$ is integrated out, the remaining bound for $t_2$ will be $(t_1, t_4)$.


Make WPF TextBox Margins Clickable/Selectable

Question: I have a WPF TextBox with a white background. I've given it some Padding so that the text has a "margin" around it (akin to the margins in, say, MS Word).
<TextBox x:Name="MyTextBox" Padding="25" />

Unlike in Word, however, this blank area around the text is not "active" (see color-coded illustration below). Clicking within it (the red section) doesn't move the textbox's caret, nor will it begin a selection. Note, however, that the entire green area is active - even the blank space below the text (meaning you can click within it to move the caret or start a selection)...

So, my question is this: Is there any way to add space around aTextBox that is blank but is also part of the editable area (so that it will react to clicks/selections, like the blank area of the green section does)?
Thanks!
p.s. The closest I've come in my search for an answer was this: How to set the margin on a internal TextBoxView in wpf... However, while increasing the Margin of the inner TextBoxView does increase the space around the text, that space still doesn't seem to be "active" in any way... And it seems like the TextBoxView doesn't have a Padding property, so I can't try that (though I imagine Padding is more likely to be the solution than a Margin)...
Comment: Upvoted this. I'm trying to figure out the exact same thing!
Answer: I'm really confused why it's not a popular question. The TextBox has a counterintuitive Padding behavior for sure.
Looked at Microsoft referencesourece for TextBox selection code but it turns out too complicated to inject a fix. So Behavior attached property seems to be a simplest way to achieve this.
xaml:
<TextBox Padding="24 0" local:TextBoxSelectionBehavior.IsEnabled="True"/>

c#:
public static class TextBoxSelectionBehavior
{
    public const double MAX_DISTANCE = 10;
    private static TextBox control;
    private static Point pos;
    private static int start;
    private static int cur;
    private static double right;
    private static bool drag;
    private const double MAXDRAG = 12;

    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(TextBoxSelectionBehavior), new UIPropertyMetadata(false, IsEnabledChanged));
    public static bool GetIsEnabled(FrameworkElement obj) => (bool)obj.GetValue(IsEnabledProperty);
    public static void SetIsEnabled(FrameworkElement obj, bool value) => obj.SetValue(IsEnabledProperty, value);
    private static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var v = (TextBox)d;
        if ((bool)e.NewValue)
        {
            v.PreviewMouseDown += V_PreviewMouseDown;
            v.PreviewMouseUp += V_PreviewMouseUp;
            v.PreviewMouseMove += V_PreviewMouseMove;
            v.LostFocus += V_LostFocus;
            v.IsKeyboardFocusedChanged += V_IsKeyboardFocusedChanged;
        }
        else
        {
            v.PreviewMouseDown -= V_PreviewMouseDown;
            v.PreviewMouseUp -= V_PreviewMouseUp;
            v.PreviewMouseMove -= V_PreviewMouseMove;
            v.LostFocus -= V_LostFocus;
            v.IsKeyboardFocusedChanged -= V_IsKeyboardFocusedChanged;
        }
    }

    public static readonly DependencyProperty ClickSelectsProperty = DependencyProperty.RegisterAttached("ClickSelects", typeof(bool), typeof(TextBoxSelectionBehavior), new UIPropertyMetadata(true));
    public static bool GetClickSelects(FrameworkElement obj) => (bool)obj.GetValue(ClickSelectsProperty);
    public static void SetClickSelects(FrameworkElement obj, bool value) => obj.SetValue(ClickSelectsProperty, value);

    private static void V_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (e.ChangedButton != MouseButton.Left) return;
        if (control != null) { control.ReleaseMouseCapture(); control = null; }
        if (e.OriginalSource is Grid g && (System.Windows.Media.VisualTreeHelper.GetParent(g) as FrameworkElement)?.Name == "PART_ContentHost")
        {
            control = (TextBox)sender;
            pos = e.GetPosition(control);
            var r = control.FindChild<ScrollContentPresenter>().Content as FrameworkElement;
            right = r.TranslatePoint(new Point(r.ActualWidth, 0), control).X;
            cur = start = control.GetCharacterIndexFromPoint(pos, true) + (pos.X >= right ? 1 : 0);
            control.SelectionStart = start;
            control.SelectionLength = 0;
            control.Focus();
            control.CaptureMouse();
            drag = false;
            e.Handled = true;
        }
    }
    private static void V_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (control == null) return;
        var p = e.GetPosition(control);
        cur = control.GetCharacterIndexFromPoint(p, true);
        control.SelectionStart = Math.Min(start, cur);
        control.SelectionLength = Math.Abs(cur - start) + (p.X >= right ? pos.X >= right ? -1 : 1 : 0);
        if (!drag) drag = Math.Max(Math.Abs(pos.X - p.X), Math.Abs(pos.Y - p.Y)) > MAXDRAG;
        e.Handled = true;
    }
    private static void V_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (control == null) return;
        control.ReleaseMouseCapture();
        if (!drag && GetClickSelects(control)) control.SelectAll();
        e.Handled = true;
        control = null;
    }
    private static void V_LostFocus(object sender, RoutedEventArgs e)
    {
        if (control != null && control != sender) return;
        if (control != null) control.ReleaseMouseCapture();
        control = null;
    }
    private static void V_IsKeyboardFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (control != null && control != sender) return;
        if ((bool)e.NewValue) return;
        if (control != null) control.ReleaseMouseCapture();
        control = null;
    }
}

And this attached property could be easily assigned globally by a general Style setter for a TextBoxes.


iptables SNAT not working for GRE packets

Question: I am trying to apply SNAT to a PPTP client.  The TCP/1723 packets are being SNATed properly but not the GRE ones.  Can anyone spot what's wrong?
I have the following iptables configuration:
$ sudo iptables -t nat -L POSTROUTING -v -n
Chain POSTROUTING (policy ACCEPT 616 packets, 37030 bytes)
pkts bytes target     prot opt in     out     source               destination
   0     0 SNAT       47   --  *      *       $internal_ip         0.0.0.0/0            to:$external_ip

When inspecting outgoing traffic on the egress interface using tcpdump, I see the following:
<timestamp> IP $internal_ip > $target_ip: GREv1, call 31607, seq 1, length 36: LCP, Conf-Request (0x01), id 1, length 22

... instead of the expected $external_ip > so clearly the SNAT translation isn't working (as is clear from the 0 pkts 0 bytes).
I have the following modules loaded (among others):
nf_nat_proto_gre
nf_conntrack_proto_gre
nf_conntrack_pptp
nf_nat_pptp

A few notes in case this is relevant:

The routing is happening upstream using a 3rd party firewall (so the outgoing packets are already on the correct egress interface).
The firewall is actually running in a VM (the above iptables listing is from its hypervisor), bridged to the egress interface.
The TCP/1723 packets are being SNATed by the firewall (but not the GRE ones); I'm effectively trying to use IPTables as a workaround to the firewall shortcoming.  Presumably IPTables doesn't care about how the packets got there?
The egress interface/bridge has a static IP which is different from $external_ip (albeit on the same subnet)

This is a Ubuntu 14.04 server running 3.13.0-123-generic
Answer: First of all your iptables command missing -t nat part. But this should generate an error as no POSTROUTING table exists in filter table by default. Make sure you are adding this to a correct table. This is very similar to this question: NAT GRE (IP protocol 47) over Linux router
Next, make sure your are specified correct $internal_ip and that one matches the one you see on your tcpdump. Sometimes a simple typo slides out of sight and makes things look complicated.
Also check your iptables rules doesn't have any preceding rule which triggers before your SNAT rule. Netfilter will trigger only first match on that occasion. Your note that TCP/1723 are natted actually means that you have other rules there.
If this doesn't helps, make sure to check & post your detailed configuration with iptables -t nat -L -v -n and things like ip rule ls && ip route ls. With -v switch with iptables you can actually see how much packets was triggered with each of your rules.
You are running inside VM. Check your host node iptables rules also! Your rule might worked but host node firewall has overwritten packed source IP coming from your VM back to your internal ip. As seems like you are inspecting packets somewhere else, i.e. not directly on your VM.
Comment: Hi there, you're right, my `iptables` rule output above was missing a `-t nat` because I posted `iptables -S -t nat` (which omits the table); so the rule is in the correct table.  Thanks for `iptables -v`; this does show that 0 pkts/bytes match my rule (although the count on the `POSTROUTING` chain does tick up nicely).  My gut feel is that it's something to do with GRE and/or the pre-routing that happens in the firewall and yes I did check over a dozen related other questions... I have revised my OP to clarify and include few more details...


"public://" is not resolved correctly to the full path

Question: In my script, public:// resolves to http://./sites/default/files/test.txt
This is the code I used to get the actual value for public://:
$path = file_create_url('public://test.txt');

$GLOBALS['base_url'] is also resolving to http://.
Any idea why the domain is missing from the public://?
Thanks
Comment: What's the context? Are you executing the script in Drush?
Comment: This is a script I'm running from the command line. It's in the root and Drupal bootstrap has loaded.
Answer: The reason there's no $base_url is because the script you're running isn't in a HTTP context; when Drupal bootstraps, unless you've specified a $base_url in settings.php, it retrieves this value from $_SERVER['HTTP_HOST'] which doesn't exist in the command line context.
To remedy this, you can set the $base_url in your settings.php or, if you're running Drush, use the --uri argument.
drush scr --uri="http://www.example.com" my_script.php


How to dynamically call data from an API when option is selected

Question: Suppose there are two hotels in my options in select tags and I want my h1 to change when I select one of the options. How do I achieve this
I am using POST method to authorize and call data in my reservationCtrl and display the hotel_name in my select tags.

                Select a Hotel:
                <select class="form-control" id="sel1">
                    <option ng-repeat="x in hotels.data">{{x.hotel_name}}</option>
                </select>

And I am using GET method to call data from another API to display the hotel_name.

{{x.hotel_name}}

Here is my showController and I want my hotel id to change like from 72 to 35 when I click one of the options so that it will call data from a different API and display a different name in the headers.
(function(){
    angular
        .module("reservationModule")
        .controller("showCtrl", function($http, $scope, $log){

                    $http({
                            method: 'GET',
                            url: '&hotel_id=72'})
                        .then(function (response) {
                            $scope.hotel = response.data;
                        }, function (reason){
                            $scope.error = reason.data;
                            $log.info(reason);
                        });
         });

})();

Here is the reservationController
(function(){
    angular
        .module("reservationModule")
        .controller("reservationCtrl", function($http, $scope, $log){

             $http({
        url: '',
        method: "POST",
        data: 'postData',
        headers:{ 'Authorization': 'value'}
    })
    .then(function(response) {
            $scope.hotels = response.data;
        }
    );
         });

})();

Comment: you can do this onChange event of select option
Answer: Yes you can add ng-change and achieve your functionality as below
JS code
  var app = angular.module('myApp', []);

  app.controller('ctrl1', function($scope) {
    $scope.hotels = [{
      name: 'Taj',
      id: 1
    }, {
      name: 'Royal',
      id: 2
    }];
    $scope.hotelInfo = {};
    $scope.fetchData = function() {
      // here call service which will fetch data and assign to hotel data
      $scope.hotelInfo = {
        address: 'London'
      };
    }

  });

  app.controller('ctrl2', function($scope) {
    $scope.data = ''

  });

HTML code

      <select ng-options='item as item.name for item in hotels' ng-model='hotel' ng-change='fetchData()'>
      </select>
      {{hotel}} - {{hotelInfo}}

Here is the link Jsfiddle demo
Answer: You need to call event on the select box which will call simple function which return the data like following
    <select ng-options="size as size.name for size in sizes"
   ng-model="item" ng-change="update()"></select>

write javascript code on the update function
Answer: Your can use ng-change on select of particular hotel.

In congroller :

$scope.showHotel = function(hotelName){
   $scope.selectedHotel = hotelName;
}

{{x.hotel_name}}

In view you you can edit like this if you have to display only one hotel name instead of ng-repeat:

{{selectedHotel}}


Is there a dissection proof of the Pythagorean Theorem for tetrahedra?

Question: Of the many nice proofs of the Pythagorean theorem, one large class  is the "dissection" proofs, where the sum of the areas of the squares on the two legs is shown to be the same as the area of the square on the hypotenuse.  For example:

One generalization of the Pythagorean theorem is De Gua's Theorem, which concerns right-angled tetrhaedra:

For such a tetrahedron, the areas $A,B,C$ of the three "legs" are related to the area $D$ of the "hypotenuse" by the formula
$$
A^2 + B^2 + C^2 = D^2.
$$
See here for a simple proof of this theorem.  Note that both sides of this equation have units of area-squared, i.e. four-dimensional volume.
My question is:

Is it possible to prove De Gua's Theorem using a "dissection" in four dimensions?

There's no reason to be strict about the definition of a "dissection" -- any proof involving four-dimensional volume would be welcome.  For example, it would certainly be interesting to have a proof of De Gua's Theorem that involves shearing in four dimensions.
Comment: If I interpret your question as "is there a scissors congruence between the four dimensional polytopes $D^2$ and $A^2 \sqcup B^2 \sqcup C^2$", the answer is yes. I can take every step of the proof at cut-the-knot and replace the equality between areas by a scissors congruence and scissors congruence is an equivalence relation.  (Every step is either of the form "triangle with base $b$ and height $h$ = rectangle with base $b$ and height $h/2$" or is the Pythagorean theorem, and those both have decomposition proofs.) Is that an answer to your question, or do you require something more?
Comment: [Hilbert's 3rd Problem](http://en.wikipedia.org/wiki/Hilbert's_third_problem) asked  whether two polyhedra of equal volume are "equidecomposable" into the same sets of pieces. The analogous (true) result for polygons guarantees the existence of dissection proofs of the Pythagorean Theorem. I don't know the status of the 4d counterpart; of course, even if the result isn't true *generally*, it could hold specifically for the "squares" of faces of a right-corner tetrahedron ... for an appropriate definition of "square". (I actually toyed with this very same idea decades ago, but got nowhere.)
Comment: Incidentally, the tetrahedral result follows immediately from Heron's Formula for the area of the "hypotenuse face", wherein the square of the length of each bounding edge is replaced by the sum of squares of lengths of legs from the appropriate "leg face".
Comment: @Blue One possible definition of "square" is the Cartesian product of each right-triangle face with itself, which would be a 4-dimensional polytope.  Alternatively, you could complete each right triangle into a rectangle, and then "square" this to get a 4-dimensional box whose volume is four times the square of the area of the original triangle.
Comment: This is the Pythagorean theorem in a dual space, and scissors congruence arguments seem like they would transpose correctly.  If compatibility with congruence arguments can be shown then you don't need a new proof, just a generalization of the 2-d Pythagoras to 3-d.
Comment: Hey, I learned a new word: [Duoprism](http://en.wikipedia.org/wiki/Duoprism) for the Cartesian product of two polytopes. :)
Comment: Look at this: http://i.stack.imgur.com/Wjxmq.png Then add - in addition to b+a and a+b - an additional height a+b ;)
Comment: @Adobe Your comment does not make sense to me.  Can you elaborate?
Comment: @JimBelk I'll try to show what I mean using a 3D soft.
Comment: To prove pythagora's theorem geometrically, 2D figures are used to view relations between squares of lengths (1D objects). I think that if we want to view geometrically relations between squares of areas we need to go to four dimensions so a drawing would not be possible.
Comment: @BeniBogosel I agree.
Comment: @DavidSpeyer This is an excellent point, and I think it roughly answers my question.  Perhaps you should post this as an answer?
Answer: Reposting my comment as an answer:
If I interpret your question as "is there a scissors congruence between the four dimensional polytopes $D^2$ and $A^2 \sqcup B^2 \sqcup C^2$", the answer is yes.
I can take every step of the proof at cut-the-knot and replace the equality between volumes by a scissors congruence. Roughly speaking, every step in the argument either replaces a triangle with base $b$ and height $h$ by a $b \times (h/2)$ rectangle, or replaces the square on the hypotenuse of a right triangle by the union of the two squares on the sides. (More precisely, it does these things and then does some algebra, which can be interpreted as taking the products and disjoint unions with some other polytopes.)
Both replacing a triangle with base $b$ and height $h$ by a $b \times (h/2)$ rectangle, and replacing the square on the hypotenuse of a right triangle by the union of the two squares on the sides, have decomposition proofs. Compose all of those decompositions and you'll get a proof of this result.
Comment: Thanks for this elegant answer!  This doesn't quite deliver the insight I was fishing for (a unified proof for the Pythagorean theorem and De Gua's theorem), but it nicely answers the question that I asked, and clarifies the fact that the algebraic relationship between the two theorems is also a geometric relationship.
Comment: I'll leave the question open for another day in case anyone else wants to answer.  I'm not averse to awarding multiple bounties on this problem.


Rails 1.2 "service is deprecated"

Question: My app is on rails 1.2.6 and I wish to upgrade it to 2.2
I see this warning in the logs:
DEPRECATION WARNING: service is deprecated and will be removed from Rails 2.0  See http://www.rubyonrails.org/deprecation for details. (called from .... application.rb:14)
The line is question is
service :notification
Can somebody tell me what service does as I can't find any documentation on this.
Answer: service was a way of specifying controller dependencies.  Dependency loading got moved into ActiveSupport.
From the 1.2.0 code:
  # Specifies a variable number of services that this controller depends on.
  # Services are normally singletons or factories, like
  # Action Mailer service or a Payment Gateway service.
  def service(*services)
    require_dependencies(:service, services)
    depend_on(:service, services)
  end
  deprecate :service

Comment: So I simply remove this line and it will work or do I need to do something extra?
Comment: I believe just removing it will work.  But I can't make any promises w/o seeing more of your code.

Rails 1.2 "service is deprecated"


need return after navigation.goback()?

Question: With React Navigation 5.x, shall return be used after navigation.goBack() in the code snippet below?
if (condition_met) {
    setTimeout(()=> {
     navigation.goBack();
     return;  //<<==needed after navigation or useless/never executed?
   }, 1000);
 }
 //do something else if above condition not met.

Answer: The function called by setTimeout is executed after // do something else.
Move the return statement outside of setTimeout
if (condition_met) {
  setTimeout(()=> {
    navigation.goBack();
  }, 1000);

  return;  //condition met stop executing code further
}

//do something else if above condition not met.

Answer: It is normally advised to handle such effects in the return function of a useEffect as that is called when a component is being closed.
    useEffect(() => {
    return () => {
      // cleanup code codes here
    };
  },[]);

This will work after the navigation.goBack() closes the screen component.

need return after navigation.goback()?


Enabling aggregate and compress CSS files caused error on site access

Question: I set this tick box in the performance area, and on clicking Save I now cannot access the site, even the performance area to disable this! any one know if I can directly change this in the DatabasE?
EDIT:
I have refreshed the Database, thankfully no updates since it went live. This does raise the question though as I'm not the only one who has had problems with these performance tick boxes, how do you back out of an error?
I would still like the answer cause i'm trying to get to the bottom of these performance settings.
thanks for any replies.
Answer: I found this from http://drupal.org/node/782510
In your settings.php file, add
<code>$conf['preprocess_css'] = CACHE_DISABLED;
</code>
Seemed to work for me on a quick test
Comment: thanks. I have such a hard time finding anything of use in the Drupal forums/posts, so I spend most of my time here. now off to find out why these settings keep breaking my sites!
Answer: If you're looking for a good alternative for core's preprocessing of CSS/JS check out the Advanced CSS/JS Aggregation module
Answer: I believe this setting is stored in the variable table as preprocess_css
<code>UPDATE variable
SET value = 'i:0;'
WHERE name = 'preprocess_css'
</code>
and then clearing cache should do the trick.  I am also pretty certain just deleting that row should do the same thing, as the default value is 0, and variables not in the table take on their default value via variable_get().
I should add, that if you can't clear the caches from the site itself, nor via drush, you can go in any manually clear out these tables.


Can Microsoft Sync framework for ado.net work with Java?

Question: I am planning to use the following architecture for one of the applications:
Client: Java based application, which will use a MySQL database
Server: Will be C# based and the database will be SQL Server
Now is it possible to use Microsoft Sync Framework in Java? (Probably by implementing some interfaces?). I want the data from Java client to be synced to the server and vice versa. IS this possible?
If not, then can you suggest some other Sync framework.
Answer: First off, I'm not familiar with Sync, but a quick read of the overview suggests that your client will need to provide either a web service or RSS feed in order for the Sync runtime to obtain the data to be sync'd from the Java process.
The problems I see with your design is that there's typically more than one client but, semantically, a single backend - the MySQL database in this case.  I suspect this would lead to Sync thinking there are conflicts when multiple clients are running, but I could be wrong.
Anyway, that aside I assume your goal is to keep the MySQL and MSSQL databases in Sync?  If this is the case then why not run a server-side process in front of the MySQL database that becomes the Sync participant.  If you've got alread .Net on the server-side you could even write it in C#, which is bound to ease the interop issues.
If you are set on the client being the Sync participant then take a look at Jakarta Commons, which I think has the code you're need to turn you client into a simple web-server that'll be needed for it to act as a web-service or RSS feed.
Answer: You will need to find some "glue" between the Java and the Sync framework. The Java Native Interface will get you a good start.
Answer: You could have the "client" part of the Sync Framework be a separate C#.NET application or service. This means deploying the sync client and the .NET framework to the client machines. You would also have to build out a MySQL client provider for the Sync Framework (although you can probably find or adapt something from codeplex).
If you can't install .NET on the client machines, you may need to look at utilizing a sync system built on the Java stack and use that. Something like one of the solutions suggested here: Open source framework à la Microsoft Sync Framework suggestions?. At least some of the suggestions there can talk to both MSSQL and MySQL.
Answer: Actually you can use change tracking direct from SQL server.
http://msdn.microsoft.com/en-us/library/cc280462(SQL.100).aspx


How do I center align the components in a Java GUI?

Question: I am a beginner programmer and I'm currently working on a project by making a simple Login screen layout using Java. So far I'm doing pretty good, but is there any way to center-align all the objects I created rather than setting them individually?

So far this is my current code:
package com.main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LoginScreen extends JFrame {

JLabel lblIntro, lblregister, lblAsGuest;
JTextField txtUsername;
JPasswordField jpfPassword;
JButton btnLogin, btnRegister, btnAsGuest;
public LoginScreen(){
    super("List n\' Go");
    setLayout(null);

    lblIntro = new JLabel("Welcome to List n\' Go");
    lblregister = new JLabel("Dont have an account yet?");
    lblAsGuest = new JLabel("or continue as Guest");
    txtUsername = new JTextField("Username");
    jpfPassword = new JPasswordField("Password");
    btnLogin = new JButton("Login");
    btnRegister =new JButton("Register");

    lblIntro.setBounds(100,50, 250,40);
    txtUsername.setBounds(50, 150, 300, 40);
    jpfPassword.setBounds(50, 200, 300,  40);
    btnLogin.setBounds(125, 250, 150, 40);
    lblregister.setBounds(125, 350,150, 12);
    btnRegister.setBounds(125, 365, 150, 40);
    lblAsGuest.setBounds(135, 415, 150, 12);

    lblIntro.setFont(new Font("Serif",Font.BOLD, 20));

    add(lblIntro);
    add(txtUsername);
    add(jpfPassword);
    add(btnLogin);
    add(lblregister);
    add(btnRegister);
    add(lblAsGuest);
    addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent exit){
            System.exit(0);
        }
    });

    setSize(400,600);
    setVisible(true);
    setResizable(false);
}
public static void main(String [] args){
    LoginScreen login = new LoginScreen();
}
}

Comment: *"..is there any way to center-align all the objects I created rather than setting them individually?"* Yes. Use layout managers to handle component positioning.
Comment: [Laying Out Components Within a Container](https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html)
Answer: You need to look into Layouts.  You should never manually set a components bounds or size.  Sometimes you need to nest layouts to get the effect your looking for:
public static void main(String[] args) {
    JFrame frame = new JFrame();

    Insets insets = new Insets(4, 4, 4, 4);
    JPanel inputPanel = new JPanel(new GridBagLayout());
    inputPanel.add(new JLabel("Username: "), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0));
    inputPanel.add(new JTextField(), new GridBagConstraints(1, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    inputPanel.add(new JLabel("Password: "), new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, insets, 0, 0));
    inputPanel.add(new JPasswordField(), new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    JPanel buttonPanel = new JPanel(new GridBagLayout());
    buttonPanel.add(new JButton("Register"), new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets, 0, 0));
    buttonPanel.add(new JButton("Log In"), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, insets, 0, 0));

    frame.setLayout(new GridBagLayout());
    frame.add(new JLabel("Welcome to List"), new GridBagConstraints(0, 0, 2, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    frame.add(inputPanel, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));
    frame.add(buttonPanel, new GridBagConstraints(0, 2, 1, 1, 0, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}


Branch cut and branch points

Question: Recently I am studying branch points and branch cuts in complex analysis.
If there is a function like $f(z)=\sqrt{(z-1)(z-2)}$, then the algebraic branch points are $1$ and $2$ and the branch cut is the interval $[1 , 2]$.
One can ask a natural question: Let $f(z)=\sqrt{(z-a) (z-b) (z-c)}$ where $a, b, c$ are three different non zero complex numbers. How to find the branch points and branch cut?
Comment: Welcome to math StackExchange,  this is not the correct way of asking the question here, please give some more information about what is your efforts.
Comment: Is it a square root or a cubic root ?
Comment: Square root, Thanks for asking
Answer: Let $s(z):=\sqrt{z}$. Then if $g(z):=(z-a)(z-b)(z-c)$ you have that $g$ is a polynomial, so it is an entire function, however you must choose a branch of the function $s$, as it is not continuous in the whole $\mathbb{C}$.
Choosing a branch of $s$ is the same thing than choosing a branch of the complex logarithm, as we generally defines $\sqrt{z}:=\exp\left(\frac1{2}\log z\right)$ for some branch of the complex logarithm. Setting some branch of the logarithm we will have a domain $D$ where our logarithm is analytic, therefore the domain of $s\circ g$ will be $\{z\in \mathbb{C}:g(z)\in D\}=g^{-1}(D)$.
Comment: @TOTANGHOSH There isn't an analytic branch in the exterior of $\triangle abc$, because $\infty$ is also a branch point of $\sqrt {(z - a) (z - b) (z - c)}$.
Comment: 1st of all thanks for looked onto it.
Comment: But my question is what is the branch cut? I mean here the algebraic branch points are $a,b,c$ but is the branch cut? Is the function is analytic on $\mathbb{C}-$the triangle formed by the points $a, b, c$
Comment: @TOTAN take a look [here](https://math.stackexchange.com/questions/245579/how-does-a-branch-cut-define-a-branch) to understand the concept of branch cut. For your second comment, please read again my answer.
Comment: Yess, I got it, ... Thanks again
Comment: Note that not all branches can be constructed in that way. As a simpler example, an analytic branch of $\sqrt {z^2 - 1}$ on $|z| > 1$ is an odd function, so it cannot be written as $(z \mapsto \sqrt z) \circ (z \mapsto z^2 - 1)$ for any choice of $\sqrt z$.

Branch cut and branch points


Hessian with JRockit Compatibility

Question: Has anyone run into this exception when running hessian on a JRockit VM?
Caused by: java.lang.ArrayIndexOutOfBoundsException: -418
        at com.caucho.hessian.util.IdentityIntMap.put(IdentityIntMap.java:141)
        at com.caucho.hessian.io.Hessian2Output.addRef(Hessian2Output.java:1285)
        at com.caucho.hessian.io.UnsafeSerializer.writeObject(UnsafeSerializer.java:157)
        at com.caucho.hessian.io.Hessian2Output.writeObject(Hessian2Output.java:421)
        at com.caucho.hessian.io.CollectionSerializer.writeObject(CollectionSerializer.java:102)
        at com.caucho.hessian.io.Hessian2Output.writeObject(Hessian2Output.java:421)
        at com.caucho.hessian.io.UnsafeSerializer$ObjectFieldSerializer.serialize(UnsafeSerializer.java:293)
        ... 34 more

I spent over a week troubleshooting this problem only to find out that hessian works fine with the HotSpot VM but consistently fails serializing certain objects using the JRockit VM.  I actually came up with a simple fix but it required modifying the IdentityIntMap.java code and update the hessian jar file.
Comment: If you have a fix, can you please post it here (as an answer), so people can find it.
Answer: Here is the fix that I came up with. I couldn't figure out how to notify the maintainers of the Hessian code so I'm posting it here. Modify the file:
com.caucho.hessian.util.IdentityIntMap.java starting at line 112:
public final int get(Object key)
{
  int prime = _prime;
  // int hash = System.identityHashCode(key) % prime;
  int hash = System.identityHashCode(key);
  // JRockit VMs can return a negative number which will cause this method to throw an exception
  if (hash < 0)
    hash = -hash;
  hash = hash % prime;
  ...

Also change the code in the next method starting at line 135:
public final int put(Object key, int value, boolean isReplace)
{
  int prime = _prime;
  // int hash = System.identityHashCode(key) % prime;
  int hash = System.identityHashCode(key);
  // JRockit VMs can return a negative number which will cause this method to throw an exception
  if (hash < 0)
    hash = -hash;
  hash = hash % prime;
  ...

Hessian with JRockit Compatibility


heatmaply color when all elements are the same value

Question: I'm using heatmaply to generate "heatmaps" of binary matrices, where each value in the matrix is a 1 or a 0. I've set 1 to red and 0 to gray, and it works fine. The code looks like so:
library(tidyverse)
library(heatmaply)
dummy_data <- replicate(10, ifelse(rnorm(20)>0,1,0))
uniform_data <- replicate(10, replicate(20,1))
heatmaply(
        dummy_data,
        dendrogram = 'none',
        Rowv = FALSE,
        Colv = FALSE,
        col = c("#C0C0C0","red"),
        hide_colorbar = TRUE,
        file='./heatmap-dummy.html',
        grid_gap = 1)
heatmaply(
        uniform_data,
        dendrogram = 'none',
        Rowv = FALSE,
        Colv = FALSE,
        col = c("#C0C0C0","red"),
        hide_colorbar = TRUE,
        file='./heatmap-uniform.html',
        grid_gap = 1)

This works fine for the first case (where dummy_data contains both 1s and 0s). However, uniform_data has only 1s, and the code generates a heatmap of all grays.
I'd like for the heatmap to be all reds. How can I make that happen? I've tried changing to color to c("red", "#C0C0C0"), c("red","red") and c("red"), but that has no effect.
My sessioninfo:
R> sessionInfo()
R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin17.5.0 (64-bit)
Running under: macOS High Sierra 10.13.5

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib

locale:
[1] en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] heatmaply_0.15.0   viridis_0.5.1      viridisLite_0.3.0  plotly_188.8.131.5200
 [5] forcats_0.3.0      stringr_1.3.1      dplyr_0.7.5        purrr_0.2.5
 [9] readr_1.1.1        tidyr_0.8.1        tibble_1.4.2       ggplot2_184.108.40.20600
[13] tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] nlme_3.1-137       bitops_1.0-6       lubridate_1.7.4    webshot_0.5.0
 [5] RColorBrewer_1.1-2 httr_1.3.1         prabclus_2.2-6     tools_3.5.0
 [9] R6_2.2.2           KernSmooth_2.23-15 lazyeval_0.2.1     colorspace_1.3-2
[13] trimcluster_0.1-2  nnet_7.3-12        withr_2.1.2        tidyselect_0.2.4
[17] gridExtra_2.3      mnormt_1.5-5       compiler_3.5.0     cli_1.0.0
[21] rvest_0.3.2        Cairo_1.5-9        TSP_1.1-6          xml2_1.2.0
[25] diptest_0.75-7     caTools_1.17.1     scales_0.5.0       DEoptimR_1.0-8
[29] mvtnorm_1.0-8      psych_1.8.4        robustbase_0.93-0  digest_0.6.15
[33] foreign_0.8-70     pkgconfig_2.0.1    htmltools_0.3.6    htmlwidgets_1.2
[37] rlang_0.2.1        readxl_1.1.0       rstudioapi_0.7     shiny_1.1.0
[41] bindr_0.1.1        jsonlite_1.5       crosstalk_1.0.0    mclust_5.4
[45] gtools_3.5.0       dendextend_1.8.0   magrittr_1.5       modeltools_0.2-21
[49] Rcpp_0.12.17       munsell_0.5.0      yaml_2.1.19        stringi_1.2.3
[53] whisker_0.3-2      MASS_7.3-50        flexmix_2.3-14     gplots_3.0.1
[57] plyr_1.8.4         grid_3.5.0         promises_1.0.1     parallel_3.5.0
[61] gdata_2.18.0       crayon_1.3.4       lattice_0.20-35    haven_1.1.1
[65] hms_0.4.2          pillar_1.2.3       fpc_2.1-11         reshape2_1.4.3
[69] codetools_0.2-15   stats4_3.5.0       glue_1.2.0         gclus_1.3.1
[73] data.table_1.11.4  modelr_0.1.2       httpuv_1.4.3       foreach_1.4.4
[77] cellranger_1.1.0   gtable_0.2.0       kernlab_0.9-26     assertthat_0.2.0
[81] mime_0.5           xtable_1.8-2       broom_0.4.4        later_0.7.3
[85] class_7.3-14       seriation_1.2-3    iterators_1.0.9    registry_0.5
[89] bindrcpp_0.2.2     cluster_2.0.7-1

Comment: Will do in a minute.
Comment: labels are not essential to the minimal reproducible example, so I've removed that customization.
Comment: Indeed, I'll add those too. Apologies for all the back and forth!
Comment: Here's a hack: change one of the values to `0.99` and use `col=c("red","red")`. heatmaply's limitation is the number of unique values to render, not the number of unique colors to render :-)
Answer: this seems to be a bug in plotly. See the following code that (very roughly) represents what happens within heatmaply:
library(ggplot2)
x <- rep(1, 10)
g <- ggplot(data.frame(x), aes(x=x, y=x, fill=x)) +
    geom_tile() +
    scale_fill_viridis(limits = c(0, 1))
g

ggplotly(g)

Comment: I have opened a new issue in ropensci/plotly: https://github.com/ropensci/plotly/issues/1295 @aocall
Comment: I tried looking at issues in the heatmaply git repo as well. I guess I just have to open a new issue.
Comment: It's not a heatmaply issue, it's a plotly issue.
Comment: Thanks! Carson (the maintainer) is quite helpful, though as with all maintainers the speed depends on his workload :)


Stop log off when disconnected from RDP session

Question: I don't want my VPS to log off disconnected sessions. It's really annoying because some programs freeze then. OS is Windows Server 2008 R2.
How do I prevent disconnected sessions from being logged off?
I have tryed pepoluan, rayan ries and Simon L answers
Comment: You've tried all of our suggestions and still your disconnected RDP sessions are being disconnected? Are you sure the server's not completely rebooting while you're away?
Answer: By default, a standalone Windows installation will not logoff disconnected RDP sessions.
So your installation must have been customized for it to be logging off disconnected RDP sessions.
Start MMC.
Load the Group Policy Object Editor snapin. It will be targeting the Local Computer.
Drill down to Computer Configuration -> Administrative Templates -> Windows Components -> Remote Desktop Services -> Remote Desktop Session Host -> Session Time Limits
Verify that the setting "Set time limit for disconnected sessions" is either Not Configured, or Enabled, but with a setting of Never.
Comment: I tried it on Google VM of Windows and it doesn't seem to work. Any idea?
Comment: I've seen where "Not Configured" doesn't do anything, but "Enabled" with a limit of "Never" works.
Comment: Didn't work even after a reboot.
Comment: This worked perfectly fine on Windows 10, after messing around with the settings to fix a problem. The problem was using the default RDP port which causes disconnections.
Answer: To add what @Ryan wrote, if the Local Security Policy is "Not Configured", next you must check the Terminal Services Configuration / Remote Desktop Configuration. Right-click the "Connection", choose "Properties", and check that there are no "Force Disconnect" option being enforced.
(I don't have access to a Windows Server 2008 R2 machine at the moment; I'll update/fix my answer when I regain access)
Erratum: The location is Start > Administrative Tools > Remote Desktop Services > Remote Desktop Session Host Configuration. Double-click on "RDP-Tcp", and go to the "Sessions" tab.
Edit to add: Do note, though, that without limiting sessions with forced logoffs, you will sooner or later run into the hard-coded 2 RDP sessions limitations (including 'console' sessions), necessitating a Forced Logoff after all.
Comment: There is "Override user settings" and all set to "Never"
Answer: The GPO answers work as well, i just wanted to add to the answers.
This is as Ryan says, out of the ordinary, since by default your sessions can idle for as long as they want.
You can however customize the disconnect time with the policy mentioned.
The registry key involved with this policy, should you need to configure this on a single server is

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services

Create or update a DWORD called MaxDisconnectionTime
Now set the amount of time a user can be disconnected in miliseconds.
EG : 1209600000 for 14 days and so on.
If you want the disconnect to be unlimited you can delete the value.
Comment: None of GPO settings work on Windows 10 host. Let's try the registry hack.
Comment: Neither answer helped me. AWS EC2 Win10 machine. Closing a remote desktop session directly kills all running process (verified by trying to connect to a DB that's hosted inside).


How to enable NTFS folder compression on Windows Server Core?

Question: I want to enable NTFS compression on a specific folder, in my case: C:\inetpub\logs.
This is easily done in Windows Server with Desktop Experience, but in Server Core how this can be achieved?
To be precise I just want the equivalent of checking the box "Compress contents to save disk space".
Comment: As an alternative, you could write a utility to zip up all the logs for a month and perhaps migrate them to yearly folders, and run it as a scheduled task.
Answer: There is the compact utility that can change compression attribute from the command line. For example to set compression for the c:\docs directory and all files in it:
> compact /c /s:c:\docs *

A good description of the compact command is here:
Compressing a File or Folder
You should be aware of the limitations of NTFS compression before deciding to use it. Please see Understanding NTFS Compression.
Comment: Thanks! With this command, new created files will be automatically compressed too?
Comment: Yes, the new files created in the directory and its subdirectories later on will be compressed also