Why are WR in the slot covered by non-CBs in American football?

Question: It's College Bowl season and I'm seeing/hearing some things from the announcers that I need some clarification on.  Please note, I have never played any organized football before so all I know is from watching with my dad and friends.
There was a WR who multiple times lined up either in the backfield, in the slot, or what looks like as a wing back (and motioned out to the slot area).  The defense for some reason played him with a LB or Safety and have gotten torched multiple times because of the speed mismatch (huge gains of 20+ yds, TD catch, etc).  Why can't the defense leave a CB to shadow the guy, even if he's in the backfield, slot, wingback position?
For each of the plays where he torched them, I don't know the offensive personnel package but in general the personnel package shouldn't be the problem.  If for example I see 3 WR and 2 RB, I'll have my nickel package to defend so the personnel match up shouldn't be the issue.
UPDATE: The game I am referring to is the Southern Miss vs. Univ Louisiana Lafayette game in the 2016 New Orleans Bowl.  The WR is on the Southern Miss team.  His name is Allenzae Staggers.  He's their #1 WR in all the passing categories (recs, yds, TDs, YAC) and doesn't seem like a possession receiver or 3rd string WR.  The highlights they played in the game during breaks showed he was beating man to man coverage.
I have seen and heard before on tv from many other announcers after a big play that it was a mismatch b/c so-and-so WR on (insert NFL or college team) was being defended by a LB or Safety and torched the defense.  I don't know what the offensive personnel was at the time for any of these plays were either but my guess is they had at least 3 WRs if some non-CB had to guard a WR but if as a defensive coordinator you see 3 WR running out, why wouldn't you trot out your nickel defense?
Answer: First lets make sure that most reading this get the general "standard" football formation on offense and defense, set up across from each other here (from womensfootballguide.files.wordpress.com):

With some insight from this Dummies.com article, each positions is quite adapted to play certain roles:

Generally safeties have player molds emphasizing flexibility, with moderate speed, good ability to change direction, and fair strength.  This allows them to help in coverage on a wide range of pass routes, adjust to follow plays as they shift around, and yet also be able to track up inside to slow/stop running backs that break their runs through the first tier of the defense.  So, it's important to note, to fit this dynamicism, you'd generally want them to line up towards the center of the field with a large cushion to allow them to manage so many things.
Generally linebackers have player molds that are a bit more bruising, with pretty decent strength and size, but also some speed.  These guys are regularly important in stopping runs or blitzing the quarterback.  They don't usually have the speed to cover the fastest guys for longer routes without help, so you'd also tend to want them to stay towards the middle of the formation where there is more protection.
Generally cornerbacks are have player molds emphasizing speed, span, and are ideally fairly tall as well.  All this is to match up with the best receivers the other team can throw at them.  They need to be able to stick with the receivers making quick moves when playing man-to-man coverage, or roam a lot of space when playing zones.  Given that safeties and linebackers are both patterned to play the middle, and that the speediest wide receivers often play the edges since that gives them the greatest danger of breaking the other 9 guys, cornerbacks are predominantly found at the edges as well.

So, what is the best way to respond if the offense elects to go to a 3 wide receiver set (replacing the fullback with a third receiver, usually lined up in the slot [somewhere inward from one of the other two wide receivers])?
Pulling one of the cornerbacks in to cover the slot receiver leaves a big question mark of how to cover the receiver he is leaving.  It is unlikely anyone else on the team can match up with that receiver one-on-one.
Pulling a safety in leaves less protection and more room for the primary receivers or running backs to bust huge plays.
Linemen are usually too big and slow to be much help on a receiver.
So as I understand it, that often leaves the linebackers as often the best option.
Usually the matchup doesn't work out to be too bad.  Because unlike the two standard receiver positions... the weak-side receiver (which generally has little focus on strength, since most runs are to the other side [where the tight end is] means this receiver rarely has to get involved in blocking)... and the flanking receiver (who usually has a lot of reliance put on size, working to give him dominance even in the tightest coverage by his single defender), the slot receiver is usually built to be pretty tough and physical.  This is so that he can take the punishment he'll often get, since he generally attempts to catch balls in the intermediate region between the line and secondary... meaning many guys will often be nearby to quickly unload big hits as soon as he catches the ball.  If somebody too light and athletic plays the slot, the general thinking is be quite prone to injury.  And also may struggle to keep possession after the catch without the strength to face the hits and hold onto the ball.
So usually a linebacker will at least line up fairly with a slot receiver.  Whereas diverting a cornerback (or safety) to cover him usually risks big play touchdowns.
Now, all this isn't to say the matchup is always great.  Indeed, just because it can lead to more injuries doesn't mean a team won't play such a formation!
And, as noted, linebackers really tend to be built a bit more towards dealing with the bigger guys inside and making lots of tackles.  Just a bit of a speed edge might be enough for the slot guy to reap great rewards.  Plus, the linebackers also must often help cover the tight end and running backs coming out on passing routes as well, plus contain mobile quarterbacks.
This high quality Denver Post explanation and this equally high quality post on FieldGulls.com go into a lot more detail breaking down some of the different positions and matchups within the receivers and secondary.
The troubles often really are more indicative of the overall team skill as well.  If you have cornerbacks that can be relied upon to hold single coverage with the main wide receivers, then your safeties can play up more.  Or if your defensive linemen can really occupy the offensive line, you can drop more linebackers into coverage, giving less room for the extra receivers.  But if those guys are struggling, more attention needs to be paid in those other areas.
Now, as you hint at, the best response often actually ends up being switching out one (nickle) or two (dime) of the linebackers for more of those faster secondary players.  If you have the preparedness and players to make those switches.
But this may expose other problems as well.
I'm certainly no football mastermind... but maybe the offense was running the ball well with the RBs or QB, preventing the defense from making a LB-to-DB switch, which would further reduce their effectiveness against the run (or that making the switch would fairly obviously set matchups that would unlock a previously contained run game).  Or perhaps the slot receiver was just a bit too physical for a safety or cornerback, and a bit too fast for the linebacker, given the amount of time and room he was getting to operate (in other words, the play calling was giving the QB and slot WR too much time to operate).  Maybe they just thought that the linebacker they'd take off would cost them more overall than the DB they'd put on.
Who knows!  But the defense was most likely making changes they thought would help contain the slot receiver, they just weren't working.  But indeed, mismatches often do seem like one of those things commentators like to obsessively harp on... even though they often really don't know the complexity behind them!  These coaches certainly weren't born yesterday, they've probably been facing slot receivers for decades!  It just didn't work out that the coaches choices or the personnel they used were as sharp as they have been on other days, and they came up against a coach/team/player that really showed it up!
Comment: I mean, if the offense trots out 4 WR, I assume you're not going to stay in your base defense to defend them.  I think this is why there's a rule (at least in college) that says if the offense subs out ppl, you have to give the defense a chance to sub too.  Same here, if I see 3 WRs, and I were a DC I'd make sure we had our nickel package to defend.
Comment: I just looked at the season stats. The WR who was put in the slot, backfield, wingback position was their #1 WR in all receiving categories (rec, yds, TDs, YPC) so this is not your usual 3rd string WR. This was their best guy who they moved around within the formation and didn't line up in the typical WR positions as shown in your diagram. I will admit, maybe the announcers were just blowing hot air but I think most sports commentators are knowledgable and/or are former coaches/players so they should have some knowledge of what's going on.
Comment: Keeping in mind that the 3rd and 4th WR are probably not of the talent of the 1st and 2nd in most circumstances, I'd think you might, if you thought you could match up with them enough.  It's really about what those WR are like, really.  If they're big guys pretending to not be tight ends, your linebackers are probably perfect for them.  If they're fast speedsters, then probably bring in DBs (though you could also try to check them at the line, or perhaps use your safeties at times in certain situations [like nearer the endzone?]).
Comment: Or maybe they're just a brutal combination of strong and fast, and maybe there's no one you can truly guard them with.  And your best bet is devote multiple resources to them as possible.  I don't know.  I just expect it's rather complex more than just playing a simple personnel matching game, or teams would always do it indeed.
Comment: And you're right, I'm sorry, I'm not really suggesting most commentators are knowledgeless and inexperienced.  Indeed most of the commentators know quite a bit these days.  It's just that there are still some that do become obsessed with one point.  There's also a reason they're not on the sidelines coaching!  And maybe it's from having a one-track response to certain situations.  Or maybe not!  Everything's more complex than it seems, really :-)


Collision Detection between a line and a circle in python(tkinter)

Question: I writing a python program in which a circle bounces off of user drawn lines. There are multiple circles that bounce off the wall. For each one, the shortest distance from the center of the circle and the ball should be calculated. I would prefer if this code was very efficient because my current algorithm lags the computer a lot. If point a is the starting point ,and point b is the end point, and point c is the center, and r is the radius, how would I calculate the shortest distance between the ball? This algorithm should also work if the X coordinate of the ball is out of range of x coordinates in segment AB.
Please post python code
Any help would be appreciated!
Here's what I have so far:
lineList is a list with 4 values that contains beginning and end coordinates of the user drawn lines
center is the center of the ball
global lineList, numobjects
        if not(0 in lineList):

            beginCoord = [lineList[0],lineList[1]]

            endCoord = [lineList[2]-500,lineList[3]-500]

            center = [xCoordinate[i],yCoordinate[i]+15]

            distance1 = math.sqrt((lineList[1] - center[1])**2 + (lineList[0] - center[0])**2)

            slope1 = math.tan((lineList[1] - lineList[3]) / (lineList[0] - lineList[2]))

            try:
                slope2 = math.tan((center[1] - beginCoord[1])/(center[0]-beginCoord[0]))

                angle1 = slope2 + slope1

                circleDistance = distance1 * math.sin(angle1)

            except:

                #If the circle is directly above beginCoord
                circleDistance = center[1] - lineList[1]

            global numbounces

            if circleDistance < 2 and circleDistance > -2:

                print(circleDistance)

                b = False

                b2=False

                if xCoordinate[i] < 0:

                    xCoordinate[i] += 1

                    speed1[i] *= -1

                    b=True

                elif xCoordinate[i] > 0:

                    xCoordinate[i] -= 1

                    speed1[i] *= -1

                    b=True

                if yCoordinate[i] < 0:

                    yCoordinate[i] += 1

                    speed2[i] *= -1

                    b2=True

                elif yCoordinate[i] > 0:

                    yCoordinate[i] -= 1

                    speed2[i] *= -1

                    b2=True

                if b and b2:

                 #Only delete the line if the ball reversed directions

                    numbounces += 1

                    #Add a ball after 5 bounces

                    if numbounces % 5 == 0 and numbounces != 0:

                        numobjects = 1

                        getData(numobjects)
                    canvas.delete("line")

                    lineList = [0,0,0,0]

Comment: "Please post python code..." yes, please do post some code!
Comment: You could show what you have tried. Also this looks more like a math problem rather than a programming one.
Answer: To be correct we are not speaking not about lines, but rather segments.
I would suggest the following idea:
Since the ball is moving in some direction, the only points that might collide with something lie on a 180° arc - the part that is moving forward. Meaning at some point of time when you check for collision you have to check whether any of those points collided with something. The more points you check, the better the precision of the collision in time, but worse the complexity.
Checking the collision: you check whether any of the points is in between the extremes of the segment. You can do this by first checking the coordinates (example is given looking at your drawn line, meaning A.x  B.y) if (A.x <= point.x <= B.x && A.y >= point.y >= B.y if the condition satisfies, you check whether the 3 points form a line. Since you have already the coordinates of A and B you can deduce the equation of the line and check whether the point satisfies it.
In short: you check if the point satisfies the equation of the line and is inside the rectangle defined by the 2 points.
How to get the points you have to check: assuming 2k+1 is the number of points you want to check at some time, C is your center r the radius and V the vector of motion. Then the number of points from the left side of the direction vector and from the right side will be equal and be k (+1 point at the intersection of the circle and the motion vector). Then 90° / k is one angular division. Since you know the motion vector, you can calculate the angle between it and the horizontal line (let it be angle). You keep adding to go left and decrementing to go right from the motion vector the value of 90° / k exactly k times (let us denote this value by i) and calculate the position of the point by point.x = C.x + sin(i) * r and point.y = C.y + cos(i) * r.
Sry, I don't know python.
Answer: The shortest distance from a circle to a line is the shortest distance from its center to that line, minus the radius of the circle.  If the distance from the center to the line is less than the radius, the line passes through the circle.
Finding the distance from a point to a line is documented many places, including here.
Sorry for not posting Python code, but it is pretty basic.


uwsgi working with nginx, systemd emperor not working with same configs and setup

Question: The issue here is that everything is configured, and runs without error, and yet I do not know why it is not working. As you'll see I get no app can't load error, I get no errors at all, in fact it's the most complete without errors I've had since I started. And yet, 500 response. Alot of this is here for completeness as I'll explain. If I take emperor out of the mix, it works, just fine.
I have been trying to deploy an opensource flask app ceph-dash for monitoring via uwsgi/nginx. I succeeded eventually albeit painfully. I have written a gist about my success https://gist.github.com/Lighiche/a6aec14166d62b4f8f013415a2c1f757
Howver, since there's no daemon management and the likes I thought it best to add to what I've done by using uwsgi emperor and I followed this guide to the letter
https://chriswarrick.com/blog/2016/02/10/deploying-python-web-apps-with-nginx-and-uwsgi-emperor/
I am on Centos 7. I have successful run and tested the app on this implementation as you can see in the gist, I actually went out of my way to discover how to configure uwsgi under different scenarios.
However with the emperor implementation of wsgi and all it's config files. I am getting a 500 response internal server error. And I think it's to do with the hand off between nginx and emperor or emperor itself. As when I stop the uwsgi service I get a 502. So nginx at least sees the socket file.
WSGI server start log, all green
*** Starting uWSGI 184.108.40.206 (64bit) on [Thu Sep  1 11:16:24 2016] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-4) on 02 August 2016 21:07:54
os: Linux-3.10.0-327.28.3.el7.x86_64 #1 SMP Thu Aug 18 19:05:49 UTC 2016
nodename: prdceph-mon00
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 2
current working directory: /etc/uwsgi.d
detected binary path: /usr/sbin/uwsgi
chdir() to /etc/nginx/sites-enabled/ceph-dash
your processes number limit is 7282
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /var/run/uwsgi/ceph-dash.sock fd 6
Python version: 2.7.5 (default, Aug 18 2016, 15:58:25)  [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)]
Python main interpreter initialized at 0xee1030
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 363840 bytes (355 KB) for 4 cores
*** Operational MODE: preforking ***
WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0xee1030 pid: 3236 (default app)
mountpoint  already configured. skip.
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 3236)
spawned uWSGI worker 1 (pid: 3241, cores: 1)
spawned uWSGI worker 2 (pid: 3242, cores: 1)
spawned uWSGI worker 3 (pid: 3243, cores: 1)
spawned uWSGI worker 4 (pid: 3244, cores: 1)
[pid: 3243|app: 0|req: 1/1] 127.0.0.1 () {34 vars in 429 bytes} [Thu Sep  1 11:17:31 2016] GET / => generated 291 bytes in 77 msecs (HTTP/1.1 500) 2 headers in 84 bytes (1 switches on core 0)
announcing my loyalty to the Emperor...

WSGI service start log, all green
 uwsgi.service - uWSGI Emperor Service
   Loaded: loaded (/usr/lib/systemd/system/uwsgi.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2016-09-01 11:16:24 BST; 2s ago
  Process: 3231 ExecStartPre=/bin/chown uwsgi:uwsgi /run/uwsgi (code=exited, status=0/SUCCESS)
  Process: 3229 ExecStartPre=/bin/mkdir -p /run/uwsgi (code=exited, status=0/SUCCESS)
 Main PID: 3234 (uwsgi)
   Status: "The Emperor is governing 1 vassals"
   CGroup: /system.slice/uwsgi.service
           ├─3234 /usr/sbin/uwsgi --ini /etc/uwsgi.ini
           ├─3235 /usr/sbin/uwsgi --ini /etc/uwsgi.ini
           ├─3236 /usr/sbin/uwsgi --ini cephdash.ini
           ├─3241 /usr/sbin/uwsgi --ini cephdash.ini
           ├─3242 /usr/sbin/uwsgi --ini cephdash.ini
           ├─3243 /usr/sbin/uwsgi --ini cephdash.ini
           └─3244 /usr/sbin/uwsgi --ini cephdash.ini

Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: thunder lock: disabled (you can enable it with --thunder-lock)
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: your mercy for graceful operations on workers is 60 seconds
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: *** Operational MODE: no-workers ***
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: spawned uWSGI master process (pid: 3234)
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: *** Stats server enabled on /run/uwsgi/stats.sock fd: 7 ***
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: *** starting uWSGI Emperor ***
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: *** has_emperor mode detected (fd: 7) ***
Sep 01 11:16:24 prdceph-mon00 uwsgi[3234]: [uWSGI] getting INI configuration from cephdash.ini
Sep 01 11:16:25 prdceph-mon00 uwsgi[3234]: Thu Sep  1 11:16:25 2016 - [emperor] vassal cephdash.ini has been spawned
Sep 01 11:16:25 prdceph-mon00 uwsgi[3234]: Thu Sep  1 11:16:25 2016 - [emperor] vassal cephdash.ini is ready to accept requests

WSGI server response 500
[pid: 3243|app: 0|req: 1/1] 127.0.0.1 () {34 vars in 429 bytes} [Thu Sep  1 11:17:31 2016] GET / => generated 291 bytes in 77 msecs (HTTP/1.1 500) 2 headers in 84 bytes (1 switches on core 0)

NGINX server response 500
<ip> - - [01/Sep/2016:11:14:16 +0100] "GET / HTTP/1.1" 500 291 "http://<ip>/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36" "<my ip>, <ip>"
127.0.0.1 - - [01/Sep/2016:11:17:31 +0100] "GET / HTTP/1.1" 500 291 "-" "Python-urllib/2.7"

cat /etc/uwsgi.ini
[uwsgi]
uid = uwsgi
gid = nginx
pidfile = /run/uwsgi/uwsgi.pid
emperor = /etc/uwsgi.d
stats = /run/uwsgi/stats.sock
#emperor-tyrant = true
cap = setgid,setuid

cat /etc/uwsgi.d/cephdash.ini (this is a symlink to the wsgi.ini for the app)
[uwsgi]
chdir           = /etc/nginx/sites-enabled/ceph-dash
wsgi-file       = /etc/nginx/sites-enabled/ceph-dash/contrib/wsgi/cephdash.wsgi
module          = ceph-dash:app
enable-threads  = true
master          = true
processes       = 4
socket          = /var/run/uwsgi/ceph-dash.sock
chmod-socket    = 777
vacuum          = true
uid             = uwsgi
gid             = nginx
daemonize       = /tmp/ceph-dash.log
plugins         = python,logfile
logger          = file:/tmp/myappuwsgi.log

cat /etc/nginx/conf.d/cephdash.conf
upstream uwsgi {
    server unix:///var/run/uwsgi/ceph-dash.sock;
}

server {
    listen 5000;
    server_name <hostname>
    charset     utf-8;

    location / {
        uwsgi_pass  uwsgi;
        include     /etc/nginx/sites-enabled/ceph-dash/contrib/nginx/uwsgi_params;
    }
}

I have uninstalled the uwsgi that I installed via pip. I appear still to have a /sbin/uwsgi (linked from /usr/sbin) which looks to be the one installed for systemd and a /usr/bin/uwsgi I don't know how that happened. I changed the .service file to use /usr/bin and have the same error. However the binary from the rpm does not have the plugsin installed and the one in /usr/bin does. systemd uwsgi now starts with /usr/bin/uwsgi and as you can see below that binary loads the plugins required but I get the same internal server error, and the same messaged from systemd and startup logs no errors, no failures. Just a 500.
rpm -ql uwsgi
/etc/uwsgi.d
/etc/uwsgi.ini
/run/uwsgi
/usr/lib/systemd/system/uwsgi.service
/usr/sbin/uwsgi
/usr/share/doc/uwsgi-220.127.116.11
/usr/share/doc/uwsgi-188.8.131.52/CHANGELOG
/usr/share/doc/uwsgi-126.96.36.199/README
/usr/share/doc/uwsgi-188.8.131.52/README.Fedora
/usr/share/licenses/uwsgi-188.8.131.52
/usr/share/licenses/uwsgi-18.104.22.168/LICENSE

python --version
Python 2.7.5
uwsgi --version
18.104.22.168
which uwsgi (POINTING TO THE RIGHT PLACE but systemd is now loading /usr/bin)
/sbin/uwsgi

uwsgi --plugins-list (DOES NOT SHOW THE PLUGINS LOADED)

*** uWSGI loaded generic plugins ***
corerouter

*** uWSGI loaded request plugins ***
100: ping
101: echo
--- end of plugins list ---

*** Starting uWSGI 126.96.36.199 (64bit) on [Thu Sep  8 09:58:40 2016] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-4) on 02 August 2016 21:07:54
os: Linux-3.10.0-327.28.3.el7.x86_64 #1 SMP Thu Aug 18 19:05:49 UTC 2016
nodename: prdceph-mon00
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 2
current working directory: /tmp
detected binary path: /usr/sbin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 7282
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
The -s/--socket option is missing and stdin is not a socket.

/usr/bin/uwsgi --plugins-list
DOES SHOW THE PLUGINS LOADED
*** uWSGI loaded generic plugins ***
gevent
nagios
rrdtool
carbon
corerouter
fastrouter
http
ugreen
syslog
rsyslog
logsocket
router_uwsgi
router_redirect
router_basicauth
zergpool
redislog
mongodblog
router_rewrite
router_http
logfile
router_cache
rawrouter
router_static
sslrouter
cheaper_busyness
transformation_tofile
transformation_gzip
transformation_chunked
transformation_offload
router_memcached
router_redis
router_hash
router_expires
router_metrics
transformation_template
stats_pusher_socket

*** uWSGI loaded request plugins ***
0: python
17: spooler
18: symcall
100: ping
110: signal
111: cache
173: rpc
--- end of plugins list ---

*** Starting uWSGI 126.96.36.199 (64bit) on [Thu Sep  8 09:58:50 2016] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-4) on 29 August 2016 09:55:26
os: Linux-3.10.0-327.28.3.el7.x86_64 #1 SMP Thu Aug 18 19:05:49 UTC 2016
nodename: prdceph-mon00
machine: x86_64
clock source: unix
detected number of CPU cores: 2
current working directory: /tmp
detected binary path: /usr/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 7282
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
The -s/--socket option is missing and

Comment: Can you show exactly how are you running uWSGI server when it's working?
Comment: First off, excellent Witcher reference. The commands and configuration for the working uwsgi server are in the gist I posted above. That's what I have working.
Comment: But I need all the steps that you're doing from starting shell to executing your `uwsgi` server. I need to know if you're enabling any virtualenv and if uwsgi binary is same as for emperor process.
Comment: That info is in the gist. Commands I used to get it working, and config files. After that I followed the second link instructions for centos. I'm not running any virtualenvs. I got it working with uwsgi from pip. Then installed uwsgi with yum for emperor to work. As per the guide. At this point I'm sshing into a box and uwsgi is managed by systemd to start automatically. I can stop it and run any of the commands in the gist and it will work. Through systemd it does not.
Answer: uWSGI installed by yum and by pip are different. Systemd will probably use one installed by yum. When you're SSH'ing and running uWSGI by yourself, system will use one installed by pip by default.
Main difference between that uWSGI versions is: lack of python support in one installed by yum, because it tends to be modular. You can install it, probably by using yum install uwsgi-python (check your distribution repositories for specific package name). Be aware that different python plugins are needed for different python versions (2.7 will require different plugin than 3.5) and adjust package name to be installed accordingly.
After installation of python plugin check that's plugin name (visible for uWSGI) and adjust value in plugins in your .ini file. That name will probably match installed package name without uwsgi- prefix.
Comment: hey, I was aware of the difference, and the python plugin is installed and loaded in the /etc/uwsgi.d/whatvermyappis.ini. I've also checked by running /usr/bin/uwsgi directly with the --plugins python flag, in fact it doesn't work without it as it can't use --wsgi-file arg. Still can't figure out why it won't serve or why I have no errors.
Comment: Make sure that python plugin you've installed is for correct python version. Some very strange issues may occur if version does not match.
Comment: Also, from your uWSGI log file: `detected binary path: /usr/sbin/uwsgi`. That means, uWSGI from emperor is running from `/usr/sbin/uwsgi`. Try to change it to `/usr/bin/uwsgi` in system.d config.
Comment: I've added some extra notes, what do you think?
Comment: It is possible that 500 error is returned from your WSGI app for some reason, not from uWSGI server by itself. Depending on configuration and application architecture, 500 error log won't appear in uWSGI log. Try to add logging of errors from your application and check for errors there.
Answer: For me, I tried to restart nginx but it kept giving an error. I found the problem to be an extra .conf file in sitesavailable folder.


Must an admin theme be enabled to be used?

Question: I've created a sub-theme of the admin theme, Seven, in order to override some CSS used to display date combo inputs on a node edit form. The info file lists a new style sheet and the regions that are defined in the original Seven info file.
Everything seems to work fine if I select this sub theme as the Admin without even enabling it. I can easily override the CSS.
However, if I also enable the sub theme, blocks suddenly appear inside the admin theme whenever it's invoked*. I believe this is because the new sub theme has different (default?) settings for active blocks in the block table. (rfay has a solution for this problem here: http://randyfay.com/content/changing-theme-name-or-adding-subtheme-without-losing-block-and-theme-settings)
My question: Is it necessary to enable a theme/sub theme that will only be used as an Admin theme? If so, is there any way to avoid the block problem, or is that just the way it goes?
* Edit: A lot of blocks appear in the new admin theme when it is enabled. Below is a visualization of the blocks table. Before the custom theme is enabled, it does not appear in the block table, so there are no blocks at all. After it is it enabled, the 12 blocks from the main theme ("custom" in the table) are all placed into the content area. Blocks might end up in the Content region because regions in the enabled theme don't exist in the customized seven theme? In any case, it's just a nuisance really, and can be easily fixed using the SQL at the link above. However, if there is no downside in using an admin theme that is not enabled, the block clean up wouldn't be needed.
Comment: "blocks suddenly appear inside the admin theme whenever it's invoked." Well, that's what blocks are for, aren't they? ;) But where do they appear, exactly? and why don't you want them to?
Comment: I added more detail to the question. In this case 12 blocks appear in the content region at the moment the custom seven theme is enabled.
Answer: No, it's not needed to enable theme to use it as an admin theme. You only need to enable it if you want to alter it's settings, both the ones in "appearance" section, and blocks. Just go to http://example.org/admin/structure/block/list/seven and http://example.org/admin/structure/block/list/your-seven-subtheme and set up the blocks the way you want them, that's all.
Comment: I guess the question is really: For a custom version of Seven, running in "overlay" mode, is there anything I'm really giving up, or any problems I might run into later if I don't enable the theme? Of course I can adjust settings for each of the 12 blocks in this case, but it does seem kind of pointless.


How does 3G/Mobile phones get allocated an IP address? Does this mess with Google Analytics?

Question: This question is in two parts.
Q1.
How does a mobile phone get an IP address over 3G? Like, would it get the same IP for a shortish period of time (Eg. 1 day, etc)? Because my phone is constantly going in and out of buildings and underground car parks, i'm jumping between cell hotspots/receiver towers, so would I be getting a new IP each and every time? I feel like this is back to the old modem days -> every time i 'ring in/jump onto the interwebs' I get allocated a new number.
Or does it have some mac address and the Telco's mobile phone DHCP server keeps reusing the last IP based on the mac, for a specific perioud of time (eg. TTL for an IP, like a normal DHCP which has an expiry setting for the allocated IP).
Q2.
If the previous answer is that mobile's keep getting different IP's, does this mess with google analytics and the unique visitor's value? So if i'm getting 5 IP's for a day on my mobile, would that mean i'm 5 unique visitor's for the website i'm tracking?
Answer:
How does a mobile phone get an IP address over 3G?

I'm going to guess that this all depends on your provider. I'm with Optus in Australia and my IP changes fairly frequently, but I've never really looked into "why".

Does this mess with google analytics and the unique visitor's value

Unique Visitors is determined by a cookie. If you turn on HTTP Headers in your favourite FireFox plugin you should be able to see it being sent. It usually looks something like __utma=(long string). So movement of IPs should not affect this. Especially as you can also have thousands of users represented by one public IP it would not be fair to use the IP for tracking uniqueness.
Answer: Q1: Most 3G mobile providers uses a DHCP pools of private addresses and a NATed Internet access (for IPv4, this is the most flexible way to control the address allocation and Internet flows). Some corporate solutions can offer a pool a public addresses.
Q2: Google Analytics does not rely entirely on the IP address to collect statistics. It also uses User-Agent, cookies, etc.
Comment: I assumed that phones get their IPs from PPP not DHCP.  Otherwise, as you say, google has ways of knowing.


Nesting random effect within fixed effect, with additional nested random effect. Nominal logistic

Question: Very new to R so please pardon my naivety.
I am trying to run a sort of mixed effects nominal logistic regression model with my insect response data.
I have 2 rearing treatments (hot and cold) and 3 replicates within each treatment (1,2,3,4,5,6) with data (1/0) for both males and females. Each individual was tested at up to 5 different temperatures. To start I am trying to compare responses by Sex, so comparing females across the 2 treatments.
Currently I have this:
RandomFemales<-glmer(Called~ Treatment + Temp + Temp*Temp + Temp*Treatment + Temp*Temp*Treatment + DaysFromEclose + Temp*DaysFromEclose +Temp*Temp*DaysFromEclose + (1|Treatment/Rep) + (1|Rep/ID), data = Females, family=binomial, control = glmerControl(optimizer = "bobyqa"))

where temp*temp accounts for the quadratic shape of their activity curves across temperatures. DaysFromEclose is more or less time, since individuals were tested across several days.
Replicates are specific to the treatments (ie, 2,4,6 are Hot, 1,3,5 are Cold), so I assumed replicate would have to be nested within treatment, and individual ID nested within replicate to account for differences in individual response rate.
The problem is that now it seems that Treatment is being treated as a random effect which it is not.
Any thoughts? thank you!
Update RE warnings:
 `Warning messages:
1: In optwrap(optimizer, devfun, start, rho$lower, control = control,  :
  convergence code 1 from bobyqa: bobyqa -- maximum number of function evaluations exceeded
2: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge with max|grad| = 0.235779 (tol = 0.002, component 1)
3: In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model is nearly unidentifiable: very large eigenvalue
 - Rescale variables?;Model is nearly unidentifiable: large eigenvalue ratio
 - Rescale variables?`

Comment: Does that model converge without warnings ? The random structure does not makes sense. If `ID` is nested in `Rep` and `Rep` is nested in `Treatment` then you probably want `Treatment/Rep/ID` unless there is crossing . But then you have `Treatment` as a fixed effect, so that looks like a problem. I don't see why `Treatment` should be random, nor `Rep` for that matter, though I'm happy to be convinced otherwise :)
Comment: sorry for confusion! Treatment should not be random! Replicate should be because each replicate was from a different rearing incubator where there may have been influences we could not account for. I have updated the original post with the warnings
Comment: *"Replicate should be [random] because each replicate was from a different rearing incubator where there may have been influences we could not account for"*. I need convincing that that is a reason for it to be random and not fixed. That reason might be applied to it being a fixed factor, particularly when you have only 3 of them. Also, do the warnings come from the model with or without `Treatment` as random ?
Answer: Since there is interest in the association of Treatment with the outcome, it should be a fixed factor.
There are repeated measures per subject, and no interest in subject-specific associations with the outcome, so ID should be specified as a random intercept.
By similar reasoning, replicate could also be considered random, however, with only 3 replicates per treatment, the software can't be expected to estimate a variance for it with any reliability.
It is important to note that, when controlling for non-independence of observations within a factor, eg repeated measures and nesting, there is almost always the option to treat the factor as fixed instead. When there are very few levels of it, or if there are problems with model convergence that appear to be related to the random structure, for example a singular fit, these are very good reasons to treat the factor as fixed.
So in this case I would suggest trying both: one model with replicate as fixed and one with it as random. If they both converge then hopefully they will both produce similar answers to the research question(s).
Finally you might want to consider splines, which are far more flexible than quadratic terms, for handling non-linearities.


How to Solder Twin Core Guitar Cable To Mono Guitar Jack

Question: I have a braided 25ft Ernie Ball cable that I decided was just too long for what I needed, so I cut it and made it into two cables using REAN silent jacks. The cable is a twin core cable with a braided shield - this is the closest image I can find.
After soldering, the cable is noticeably lacking volume and high-end. Before I take it apart and try something different, is there any advice on what the correct way to connect the two cores?
I haven't found any information about soldering dual core cables to guitar jacks- all the information I've found is for single core cables. I had found someone else that had done this, as described in this comment on Amazon https://www.amazon.co.uk/gp/customer-reviews/RSIPNZK0HCXC3/ref=cm_cr_arp_d_rvw_ttl?ie=UTF8&ASIN=B07N6V5WRG

I bought the 25ft version and a pair of Rean NYS224S silent jacks for
a fiver on eBay, cut the cable into a 10ft and 15ft section and
soldered the new jacks on the ends. For £30 I now have two fantastic
quality cables both of which allow silent instrument changes. Highly
recommended!
Note that these cables are twin core shielded and one of the cores is
connected to ground with the shielding so you'll need a multimeter to
know which core to connect to the tip and which one goes to the sleeve
of the jacks.

I did what is described in the comment, found the core carrying the signal and soldered it to the tip, and soldered the other to the sleeve with the shielding. I'm wondering whether this is creating a ground loop or something, but want to understand why it's happening and how to fix it before pulling it all apart again.
Thanks in advance.
Comment: On the assumption you connected each end of the cable in the same way each end was originally connected - as in if all 3 wires were connected at both ends of the original, the same happened with both altered cables -  you either didn't do a good soldering job (dry joint/short) or a plug is faulty.
Comment: Assuming that you do have a multimeter at hand make sure that both tips and both sleeves are well connected, as well as there should be no connection between tip and sleeve.
Answer: In a directional guitar cable:

core carrying signal is connected to the tip on both plugs
core carrying ground is connected to the sleeve on both plugs
shield is connected to the sleeve only on one of the plugs – the one going into input of the amp or an effect.

If you cut such cable, you get two different halves, which needs to be treated differently.
What follows:

on both of them you need to connect signal core to the tip of the new plug and ground core to the sleeve.
on the cable that has the shield already connected, don't connect the shield to the new plug, and use the new plug to connect into output of the instrument (or an effect). However, if you do connect the shield, you basically obtain a regular concentric guitar cable, which should work as well.
on the cable that doesn't have shield connected, connect shield to the new plug, and use the new plug to connect into input of the amp or effect. If you do not connect the shield, you get a cable with floating shield. This cable would still work (via two core conductors), but might be more prone to interference. This is not exactly what you describe, but it's still something to check.

The symptoms you describe may suggest there is some parasitic connection between signal and ground. Maybe the new plug is faulty, or was damaged during soldering, or something else didn't work out. Another possibility is a bad contact of one of the new connections.
Comment: So, put basically, the shield (outer braiding) only gets connected to the jack that goes into the amp, etc (i.e. *not* the silent jack) - which I've used for years and love them! Great in a teaching environment! That's a new one on me, is there anything I can read up from?
Comment: @Tim you may want to ask on electronics SE for details. Directional cable is supposed to reduce noise picked up by the cable. It won't help for the noise picked up by the guitar itself. It also won't make a difference when the noise picked up by a normal cable is already low enough...
Comment: Thank you for the response. I haven't yet had chance to go back in and try the changes, but will do so. As you mentioned, I would have expected one of the cables to be 'right', if the jacks were wired differently (unless my soldering really does suck! :) ). The factory ends have heatshrink, and I was trying to avoid damaging it, but it may be the best way to get a solid cable out of it.


clear boost cached pages as the content is changed

Question: I am using boost with Maximum Cache Lifetime = 1 Day and Maximum Cache Lifetime = 0 Sec
If i do update some content / banners, i have to clear caches at

/admin/config/development/performance

Is this the only way? There is no way that changed nodes/frontPage cache will be automatically cleared instantly ? and all users will see new content instead of asking them to use Ctrl + f5.
any clues
thanks
Answer: You can use the Cache Expiration module to expire caches when content is updated.
The expire module provides the events that fire when content is updated and other caching modules hook into those events and clear their caches.
The boost module supports the expire module's events.
Once installed, you can configure the module at admin/config/system/expire.
Answer: You can use drush as well. If you have drush aliases configured, just do this:
    drush @name_of_alias cc all
I'm using Drush 8 and Drupal 7, but this also worked on my earlier versions.
Answer: If I understand correct, I had a similar issue once: It's a known problem; The fact the Drush's cache isn't separate and being cleared in any general cache-clearing is problematic especially in sites where there are only tens or hundreds of users daily (and not thousands or much more) because than you need to wait everyone to rebuild the cache for you.
The solution I had in the time is pretty lame: If you site doesn't have more than some thousands of users a day - Just don't use Boost. It's a heavy module designed in the time only or mostly for large-scale sites by terms of users, so I stopped using it at the time.
We can hope that in Drupal 8 the Boost's caching system will be totally or partly separated from the general caching system...

If you actually meant to ask what is the fastest way to clear cache than instead navigation to the address you posted (with or without a browser bookmark) you could install Admin_menu for Drupal 7 or Admin_toolbar for Drupal 8 and they would not only give you a cool icon to clear cache instantly on every page but a comfortable management menu on top of your browsers fold.
In Drush master you could do "drush cr" (this stands for drush cache rebuild).
That's aside of using cache expiration mentioned in other comments.


What is the function of this diminished 7th chord in KV 332?

Question: Consider the following cadence from the 3rd movement of Mozart's piano sonata KV 332:

What is the function of the diminished 7th chord B D F Ab?
Answer: I would offer a slightly different analysis than Aaron's.
This is a B fully diminished seventh chord. In tonal music, we typically encounter fully diminished seventh chords as viio7 chords, so let's try and understand how this particular harmony can function as a viio7.
Thinking through this, B is the leading tone (that is, vii) of C. As such, this chord is viio7 of C; we say that it is "viio7 of V" (labelled viio7/V) because V in F is C.
The extra tricky bit here is that this chord doesn't immediately resolve to V as we might expect, but to this six-four chord. But in music of this style, we understand that this "I64" chord is really a V chord with two non-chord tones up on top, and thus this chord actually does resolve to V. For more on this issue, see Analyzing an unfamiliar Roman numeral analysis: Cm/G-G notated as V6/4-5/3?.
Answer: This is a common-tone diminished seventh chord. Although spelled like a B diminished chord — to illuminate the chromatic, ascending bass line — but its function is to reinforce F, both in the following 6-4 chord and, eventually, the resolution to the I chord.
In light of Richard's viio7/V interpretation — valuable to understand — it's worth mentioning why I choose the c.t. diminished chord interpretation instead. Mozart establishes the pitch F in the initial measure of the excerpt, and every chord in the passage until the arrival on V7 contains that pitch. My feeling is that the primary function of the diminished chord is to prolong the F rather than to reinforce the arrival of C.
For more on c.t. diminished chords, see A chord progression from Leavitt: how to analyze the diminished chord
Comment: I almost always agree with you, but I'd just call it vii°7 of V, given the spelling and the bass line.  I don't feel it particularly reinforces the tonic.
Comment: @Bennyboy1973 viio7/V is a good interpretation. My feeling is that the chord's primary purpose is to prolong the (pitch) F from the previous several bars into the next.
Comment: Yeah, I'd say the fact that the chord is immediately preceded by a IV chord with D in the melody wipes out any idea that the chord prolongs the tonic note when it's already deceptively hard to hear in the preceding chord.


Hockey Stick Identity Summation Proof

Question: I'm working on a math problem that asks us to prove the following: $$ \text{For all $j,n \in \mathbb{N},$} \sum_{k=0}^n {k \choose j}(n-k) = {{n+1}\choose{j+2}} $$
It is a spinoff of the hockey stick identity: $$ \sum_{k=0}^n {k \choose j} = {{n+1} \choose {j+1}}$$
I am attempting to do this by induction, but have hit a roadblock in my reasoning:
Base Case $\left(j,n =0\right)$
\begin{gather}
        \sum_{k=0}^0 {0\choose 0} (0-0) = {{0+1} \choose {0+2}} \\
        0 = {1 \choose 2} \\
        0 = 0
    \end{gather}
Inductive Case $\left(n \longrightarrow n+1\right)$
\begin{gather}
    \sum_{k=0}^{n+1} {k \choose j}(n-k)\\
    \sum_{k=0}^{n} {k \choose j}(n-k) + {{k+1} \choose {j+1}}({n+1}-{k+1}) \\
    {{n+1}\choose{j+2}} + {{k+1} \choose {j+1}}((n+1)-(k+1)) \\
    {{n+1}\choose{j+2}} + {{k+1} \choose {j+1}}(n-k) \\
    \end{gather}
Is an inductive proof really the best way to go about this, or are there other, better ways? Any help would be appreciated.
Answer: I would rewrite the sum as
$$
   \sum_{k=0}^n (n+1) \binom kj - \sum_{k=0}^n (k+1) \binom kj
$$
and replace $(k+1) \binom kj$ by the equivalent $(j+1)\binom{k+1}{j+1}$. This lets you use the ordinary hockey-stick identity to simplify both sums.
Comment: shouldn't k=j instead of k=0 in the summation, for both the identities posted by OP? For example in the hockey stick identity that OP posted,  if j=4, then the first summand would become 0C4, which is undefined.
Comment: By convention, $\binom nk = 0$ if $k<0$ or if $k>n$.
Answer: There is a fairly straightforward combinatorial proof; I'll point you in the right direction. (In general I find combinatorial proofs more informative and more intuitive than computational proofs.)
First notice that $\binom{n+1}{j+2}$ is the number of ways to choose $j+2$ elements of the set $[n+1]=\{1,2,\ldots,n+1\}$; we'd like to relate that to the sum on the lefthand side.
Suppose that $A$ is a subset of $[n+1]$ with $j+2$ elements. Let $m=\max A$, and let $\ell=\max(A\setminus\{m\})$, so that $\ell$ is the second-largest element of $A$. Let $k=\ell-1$, and let $A_0=A\cap[k]=\{a\in A:a\le k\}$; then $A_0$ is a $j$-element subset of $[k]$, and $m$ is one of the $(n+1)-\ell=n-(\ell-1)=n-k$ elements of $[n+1]$ that are bigger than $\ell$. Can you see how to put these pieces together to show that the sum on the lefthand side also gives the number of ways to choose $j+2$ elements of $[n+1]$.
Answer: \begin{gather}
    \sum_{k=0}^{n+1} {k \choose j}(n-k)\\
    \sum_{k=0}^{n} {k \choose j}(n-k) + {\color{red}{n+1} \choose {j+1}}({n+1}-{k+1}) \\
    {{n+1}\choose{j+2}} + {\color{red}{n+1} \choose {j+1}}((n+1)-(k+1)) \\
    {{n+1}\choose{j+2}} + {\color{red}{n+1} \choose {j+1}}(n-k) \\
    \end{gather}

Hockey Stick Identity Summation Proof


How to load balance sftp instances on AWS

Question: I like to know is it possible to load balance sftp servers in AWS.  I have 2 servers, and each of my servers are using s3fs-fuse to mount the same S3 bucket onto a mount point.  Both of my ec2 instances are able to read/write to their mount points, and from S3, I can see the files from both servers.
What I am looking for is having SFTP to transfer files and using Amazon S3 to store my files.  Files would be uploaded and download daily.
https://github.com/s3fs-fuse/s3fs-fuse
As for my next step, I like to know how can I load balance my sftp servers, so that when a user connects to a specific IP address, it will redirect them to one of my sftp servers.  I took a look at elastic load balancers, but they seem to only permit specific ports.  I have also investigated HAProxy, but I am unsure how secure that solution will be.  I have to take HIPAA compliance into consideration. The load balancer must be a static IP address as our vendors does not support DNS hostnames.
Comment: I have never wanted to set myself on fire so much as I do now.
Comment: TBH, using s3fs-fuse for PHI seems quite foolish.
Comment: For the record, ELBs do nowadays support all ports (1-65535): https://aws.amazon.com/blogs/aws/elastic-load-balancing-update-more-ports-additional-fields-in-access-logs/. But, ELBs also require clients to use the AWS-generated DNS name (which also points to two public IP addresses, which can change).
Comment: The biggest question is though, why do you want to load balance? If it's for HA, you will still have a SPoF in your haproxy. If it's for cpu requirements of ssh, that would be hard to believe, but a valid reason.
Comment: Also, did you consider asking your vendor to support encrypted S3 uploads? Not hard at all…
Comment: I'm not sure what folks like @w00t are so surprised about -- there's plenty of reasons for wanting to load balance an SFTP server, mainly for HA and SPoF reasons. For some businesses (Health care!) SFTP is the defacto way of moving info and if your SFTP goes down you're screwed. If you've gone to immutable infrastructure (and you should) then you'll need a way to keep the service running while you swap in new machines.
Comment: @rusty in this design there is still a SPoF in Haproxy. You need to failover an IP to fix that, and then you can just as well run a hot standby.
Comment: @w00t Not commenting on a design, just surprised at the reactions I see from the concept of the question. Re: HAProxy the OP says they were investigating it, not settled on it.
Answer: My comment could probably use some clarification. I spouted off with the eloquence of an inebriated yak:

I have never wanted to set myself on fire so much as I do now.

Why? Why would I say such a thing? Mostly because I'm an awful person. However, aside from that, I can explain my outburst by going over the original post piecemeal:

I like to know is it possible to load balance sftp servers in AWS.

Yes. Impossible is nothing. But know that unless you get a special SFTP package, the load balancing will be entirely up to you to build. The service being SFTP and being hosted in AWS is inconsequential.

I have 2 servers, and each of my servers are using s3fs-fuse to mount
  the same S3 bucket onto a mount point. Both of my ec2 instances are
  able to read/write to their mount points, and from S3, I can see the
  files from both servers.

You're off to a good start with a shared file system, the performance and reliability of the setup notwithstanding.

As for my next step, I like to know how can I load balance my sftp
  servers, so that when a user connects to a specific IP address, it
  will redirect them to one of my sftp servers.

The question is now: Why do you want to load balance. There is a fantastic amount of throughput and processing power afforded to the Amazon instance catalog and the need to load balance SFTP would mean you're approaching porn levels of network activity. Keep it simple, repeatable, and resilient wherever possible. Get an i2.xlarge with an SFTP daemon running on it and you should be fine no matter what. Build it with Puppet/Chef/$trendy-config-management-tool and you're in business. Moving on however...

I took a look at elastic load balancers, but they seem to only permit specific ports. I have
  also investigated HAProxy, but I am unsure how secure that solution
  will be.

HAproxy is exactly the kind of tool you need. Your uncertainty about security is easily dispelled with just a few hours of reading. My desire to self immolate is rising from this point on. If you're unsure about something, go become sure about it. HAProxy is the choice for many financial institutions, hospitals, and governments.

I have to take HIPAA compliance into consideration.

Totally understood, but compliance is not primarily the role of tools. You'll need to understand the concepts behind the HIPAA compliance requirements, and see how HAproxy can fulfill them. HAProxy is neither HIPAA compliant nor HIPAA non-compliant. No matter which tool you use, you'll need to independently verify the underlying assumptions and requirements of your compliance and regulatory needs. In fact, if anything, S3 and the use of Amazon instances should be inspected more carefully than the use of HAproxy.

The load balancer must be a static ip address as our vendors does not
  support DNS hostnames

This. This did it. Your vendor is bad and should feel bad. Now I want to jump into lava. Not supporting something basic like DNS resolution is entirely unrelated, but also it's like saying "A car must have an engine for me to use it." Well of course. Of course a load balancer is going to have the ability to use a static IP address. There are many more considerations that you need to be thinking about above simple static IP addresses.
TL;DR
Yes you can load balance SFTP with HAproxy. HIPAA compliance is up to you to discern and tool choice will not check boxes. You have some Googling to do and documentation to read.
I have some flames to put out.
Comment: This is my favorite answer on SF in quite some time. <3
Comment: Thanks for the honest feedback and suggestions. I will look through them, but this will give me a start.
Comment: Netscaler also has an SFTP mode for virtual servers, might want to consider that as well. An EC2-instance-backed Netscaler appliance (with different bandwidth options) is available through the AWS marketplace. Costs money though.
Comment: After working in healthcare IT for near on a decade, 3rd party vendors being unable to support dns lookups, using domains that are not inter-system accessible, and other levels of odd which fly in the face of accepted standards are not particularly surprising and occur much more often than anyone would like. For example, several years ago, a vendor told me they couldn't support ssh public key authentication because it didn't use passwords that could be rotated every 30 days. HIPAA seems to cause a certain amount of hyper-paranoia and confusion. I'm surprised that AWS is willing to be a BA.
Answer: Yes. It is possible by using AWS Load Balancer.

Create a Load Balancer with Listener on port 22.
Create a Target Group by having 2 of your SFTP Instance.
Properly align your SGs on both Instance and Load balancer.


encoding error with read_html

Question: I am trying to web scrape a page. I thought of using the package rvest.
However, I'm stuck in the first step, which is to use read_html to read the content.
Here´s my code:
library(rvest)
url <- "http://simec.mec.gov.br/painelObras/recurso.php?obra=17956"
obra_caridade <- read_html(url,
                        encoding = "ISO-8895-1")

And I got the following error:
Error in doc_parse_raw(x, encoding = encoding, base_url = base_url, as_html = as_html,  :
  Input is not proper UTF-8, indicate encoding !
Bytes: 0xE3 0x6F 0x20 0x65 [9]

I tried using what similar questions had as answers, but it did not solve my issue:
obra_caridade <- read_html(iconv(url, to = "UTF-8"),
                        encoding = "UTF-8")

obra_caridade <- read_html(iconv(url, to = "ISO-8895-1"),
                        encoding = "ISO-8895-1")

Both attempts returned a similar error.
Does anyone has any suggestion about how to solve this issue?
Here's my session info:
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=Portuguese_Brazil.1252  LC_CTYPE=Portuguese_Brazil.1252
[3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C
[5] LC_TIME=Portuguese_Brazil.1252

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

other attached packages:
[1] rvest_0.3.2 xml2_1.1.1

loaded via a namespace (and not attached):
[1] httr_1.2.1   magrittr_1.5 R6_2.2.1     tools_3.3.1  curl_2.6     Rcpp_0.12.11

Comment: Try `encoding = "latin1"`
Comment: It worked, Thank you? Woul you like to provide as a proper answer, also explaining why using latin1 works, but not ISO-8895-1 (which is the char set as in the source code of the page)?
Answer: What's the issue?
Your issue here is in correctly determining the encoding of the webpage.
The good news
Your approach looks like a good one to me since you looked at the source code and found the Meta charset, given as ISO-8895-1. It is certainly ideal to be told the encoding, rather than have to resort to guess-work.
The bad news
I don't believe that encoding exists. Firstly, when I search for it online the results tend to look like typos. Secondly, R provides you with a list of supported encodings via iconvlist(). ISO-8895-1 is not in the list, so entering it as an argument to read_html isn't useful. I think it'd be nice if entering a non-supported encoding threw a warning, but this doesn't seem to happen.
Quick solution
As suggested by @MrFlick in a comment, using encoding = "latin1" appears to work.
I suspect the Meta charset has a typo and it should read ISO-8859-1 (which is the same thing as latin1).

Tips on guessing an encoding
What is your browser doing?
When loading the page in a browser, you can see what encoding it is using to read the page. If the page looks right, this seems like a sensible guess. In this instance, Firefox uses Western encoding (i.e. ISO-8859-1).
Guessing with R

rvest::guess_encoding is a nice, user-friendly function which can give a quick estimate. You can provide the function with a url e.g. guess_encoding(url), or copy in phrases with more complex characters e.g. guess_encoding("Situação do Termo/Convênio:").
One thing to note about this function is it can only detect from 30 of the more common encodings, but there are many more possibilities.
As mentioned earlier, iconvlist() provides a list of supported encodings. By looping through these encodings and examining some text in the page to see if it's what we expect, we should end up with a shortlist of possible encodings (and rule many encodings out).
Sample code can be found at the bottom of this answer.

Final comments
All the above points towards ISO-8859-1 being a sensible guess for the encoding.
The page url contains a .br extension indicating it's Brazilian, and - according to Wikipedia - this encoding has complete language coverage for Brazilian Portuguese, which suggests it might not be a crazy choice for whoever created the webpage. I believe this is also a reasonably common encoding type.

Code
Sample code for 'Guessing with R' point 2 (using iconvlist()):
library(rvest)
url <- "http://simec.mec.gov.br/painelObras/recurso.php?obra=17956"

# 1. See which encodings don't throw an error
read_page <- lapply(unique(iconvlist()), function(encoding_attempt) {

  # Optional print statement to show progress to 1 since this can take some time
  print(match(encoding_attempt, iconvlist()) / length(iconvlist()))

  read_attempt <- tryCatch(expr=read_html(url, encoding=encoding_attempt),
                           error=function(condition) NA,
                           warning=function(condition) message(condition))
  return(read_attempt)
})

names(read_page) <- unique(iconvlist())

# 2. See which encodings correctly display some complex characters
read_phrase <- lapply(x, function(encoded_page)
  if(!is.na(encoded_page))
    html_text(html_nodes(encoded_page, ".dl-horizontal:nth-child(1) dt")))

# We've ended up with 27 encodings which could be sensible...
encoding_shortlist <- names(read_phrase)[read_phrase == "Situação:"]

encoding error with read_html


Unexpected identifier in async awaitCurrentBlock () while running my .js file

Question: I am facing an issue while running my compile.js file using node compile.js .
My code:
const async = require('asyncawait/async');
const await = require('asyncawait/await');

const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode } = require('./compile');

const provider = new HDWalletProvider(
    'nut plug quality level uncle jeans retire guide eagle gossip cluster sudden',
    'https://rinkeby.infura.io/v3/37097b2064214600912ad8a746ff433a'
);

const web3 = new Webs(provider);

const deploy = async (() => {
    const accounts = await (web3.eth.Accounts());
    console.log('Attempting to deploy from account', accounts[0]);

    const result = await(new web3.eth.Contract(JSON.parse(interface))
    .deploy({ data: bytecode, arguments: ['Hi there!'] })
    .send({gas: '1000000', from: accounts[0]})
    );

    console.log('contract deployed to', result.options.address);
});

deploy();

After running : node compile.js
Error log:
/home/edureka/sankalp_practice/inbox/node_modules/eth-block-tracker/src/index.js:38
async awaitCurrentBlock () {
        ^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected token function
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/edureka/sankalp_practice/inbox/node_modules/web3-provider-engine/index.js:4:25)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)

I did my analysis and it seems that "const HDWalletProvider = require('truffle-hdwallet-provider');" is calling for function async awaitCurrentBlock () in /home/edureka/sankalp_practice/inbox/node_modules/eth-block-tracker/src/index.js.
So please let me know how to resolve it.
system: Ubuntu
version of node: v6.11.4
version of npm : 5.4.2
Comment: Your node version is to old to support native `async`/`await`
Comment: Possible duplicate of [SyntaxError: Unexpected token function - Async Await Nodejs](https://stackoverflow.com/questions/37815790/syntaxerror-unexpected-token-function-async-await-nodejs)
Answer: your dependency uses "async awaitCurrentBlock" that looks like node 8.* in which case you're simply using too old version of node. You want that dependency, then you have to update, but that will break your code in another way -> you're importing dependencies "async" and "await" which are reserved keywords in Node 8, so you'll have to update your syntax too
Comment: Yes, it is older version. Actually I had to import async and await as I had to use these functions for my purpose.
Is there any other way so that I can use "async awaitCurrentBlock" which is in another file in node_module.
I tried with modifying the index.js but its throwing a different error.


Redirecionamento dinâmico com Switch Case PHP

Question: Estou apanhando e não sei porque, pois é a primeira vez que tento fazer algo parecido, tenho um menu assim:

Clientes:

        Cadastrar
        Editar
        Listar

Como pode ver ele redireciona para uma page, lá embaixo eu tenho
  <?php switch($_GET['page']){

        case 'home': include 'home.php';
        case 'cadastro_cliente': include 'cadastro_cliente.php';
        case 'categorias': include 'categorias.php';

      } ?>

O que acontece é que se eu entro na página home.php ele lista embaixo a página cadastro_cliente e categorias, se eu entro no cadastro_cliente ele abre categorias logo embaixo, o que eu preciso fazer para abrir somente a página do case?
Abraço
Answer: No switch, é necessário terminar cada bloco case com um break. Caso contrário, o PHP vai continuar executando as declarações seguintes. Ficaria desse jeito:
 <?php switch($_GET['page']){

        case 'home':
            include 'home.php';
            break;
        case 'cadastro_cliente':
            include 'cadastro_cliente.php';
            break;
        case 'categorias':
            include 'categorias.php'
            break;
  } ?>

Comment: Nem sempre "é necessário" . Tem muitas situações em que é desejável o efeito cascata. Obviamente não é o caso do autor, mas tem que tomar cuidado pra não generalizar.
Answer: Veja que o erro inicial está na omissão da declaração break. Veja o que diz o manual do PHP sobre isso:

É importante entender como a declaração switch é executada a fim de
  evitar enganos. A declação switch executa linha por linha (na verdade,
  declaração por declaração). No início nenhum código é executado.
  Somente quando uma declaração case é encontrada com um valores
  correspondente ao valor da expressão do switch, o PHP começará a
  executar a declaração. O PHP continuará a executar a declaração até o
  fim do bloco switch, ou até a primeira declaração break encontrada. Se
  não for escrita uma declaração break ao final da lista de declarações
  do case, o PHP continuará executando as declarações dos próximos
  cases.

Fonte: Manual do PHP
Sobre o código, é importante tratar a requisição e definir a "home" como página padrão, se nenhum valor for passado e no switch, também realizar um tratamento. Definir um case default, um padrão que corresponde a tudo que não foi correspondido pelos outros cases. Um exemplo no seu caso, uma pagina de erro 404.
<?php

if (isset($_GET['page'])) {
    $requisicao = $_GET['page'];
} else {
    $requisicao = 'home';
}

switch($requisicao) {
    case "home":
        include(__DIR__."/home.php");
        break;
    case "cadastro_cliente":
        include(__DIR__."/cadastro_cliente.php");
        break;
    case "categorias":
        include(__DIR__."/categorias.php");
        break;
    default:
      include(__DIR__."/404.php");
}

A nível de informação e curiosidade, vale a pena falar aqui que este é o básico sobre o Padrão de Projeto Front Controller.


Searchingthe polar form of $z = 2+i(1+\sqrt{3})$

Question: Find the polar form of:
$$z = 2+i(1+\sqrt{3})$$
Is there any other way to solve that in different way than by finding $|z|$ that is really "ugly" ($|z| = \sqrt{8+2\sqrt{3}}$)?
Comment: Well if $|z|$ is ugly, it is ugly. No other methods will find a nice one instead...
Answer: For finding polar form of any complex number, you can't refrain from calculating its magnitude.
$$x+iy= r (\cos \theta + i \sin \theta) =r e^{i \theta}$$
You'll always need to find $r$ and $\theta $.
Answer: Yes it is correct $z=\rho \cdot e^{i\cdot \theta}$ with
$$\rho=|z| = \sqrt{8+2\sqrt{3}}$$
and
$$\theta=\arg (z)=\arctan\left(\frac{1 + \sqrt3}{2}\right)$$
Answer: you are right  $z=\rho \cdot e^{i\cdot \theta}$ with  $\rho=|z| = \sqrt{8+2\sqrt{3}}$. But Note that  $$ \frac{1 + \sqrt3}{2} = \cos\frac{π}{3}+\sin\frac{π}{3}=\sqrt2\cos(\frac{π}{3}-\frac{π}{4} )=\sqrt2\cos\frac{π}{12}$$
and then ,
$$\theta=\arg (z)=\arctan\left(\frac{1 + \sqrt3}{2}\right)=\color{red}{\arctan\left(\sqrt2\cos\frac{π}{12}\right)}$$


Heap de memória Java

Question: Gostaria de uma explicação de forma simples o que é o heap de memória da JVM? Eu pesquisei no Google porém não tinha nenhuma resposta clara o suficiente.
Comment: Eu já expliquei sobre o Heap e o Perm Heap [nessa resposta](http://pt.stackoverflow.com/questions/30221/mensagem-could-not-reserve-enough-space-for-object-heap-no-jvm).
Comment: Não é específico para o Java, mas já vai ajudar. As diferenças não são grandes: http://pt.stackoverflow.com/questions/3797/o-que-s%c3%a3o-e-onde-est%c3%a3o-o-stack-e-heap e http://pt.stackoverflow.com/q/14490/101
Comment: mas no caso do java isso seria o lugar onde fica de fato guardado os objetos?
Comment: Os objetos criados à partir de classes, sim. Os objetos primitivos não, estes ficam no *stack*. Mais links http://www.infoq.com/br/articles/intro-memoria-JVM e http://www.ibm.com/developerworks/br/library/j-codetoheap/
Comment: @user16049 Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Primeiro entenda que estamos falando de um conceito abstrato. É um nome só para facilitar nosso entendimento. Não existe um componente de hardware chamado heap localizado na memória. Nem mesmo uma área específica da memória onde "fica" o heap. Ele está espalhado por toda a memória.
Heap
De forma simples o heap é a área da memória em que os objetos da sua aplicação são armazenados. Mas não é qualquer tipo de objeto que é guardado lá, apenas aqueles criados à partir de classes, ou seja, os objetos com semântica de referência.
Nele são alocados objetos que são referenciados em algum lugar, por isso são chamados objetos por referência. Java, hoje, incentiva muito que a maioria das alocações ocorram desta forma.
É uma área de memória gerenciada pelo garbage colector. Ela vai ocupando espaços conforme a necessidade e o GC, em algum momento futuro, vai liberando os espaços quando os dados contidos em uma determinada porção não são mais necessários. A liberação não é feita logo após o objeto não ser mais necessário.
Esta área não precisa ser contínua, ela é apenas uma porção, um monte da memória alocada para sua aplicação. E estamos falando da memória virtual que pode ser RAM, disco ou outra forma que o sistema operacional disponibilize.
A forma como ele é usado é sob demanda, ou seja, vai alocando espaços específicos conforme a necessidade. No caso da JVM boa parte desta alocação já é reservada com antecedência pelo GC. Ele tenta administrar a memória da melhor forma possível. Mas você precisa enxergar este tipo de alocação como sob demanda, que ela vai sendo usada conforme a necessidade.
Stack
Objetos curtos e de curta duração que são armazenados diretamente com seu valor ficam na stack (alguma otimização pode fazer isso com tipo por referência). Este é o caso dos objetos de tipos primitivos e será quando a linguagem tiver outros tipos que não são nem primitivos e nem criados com classes. Algumas pessoas esquecem que os dados primitivos também são objetos (e nem é porque Java é orientada a objeto, na verdade é um outro conceito de objeto). Talvez até porque Java não costume usar o termo objeto para estes dados. Mas eles são objetos. Em C que não é nada orientada a objeto você os chama de objetos.
O funcionamento desta área é semelhante a uma pilha, daí o nome. É uma área de tamanho fixo de memória, normalmente contínua em que os dados vão sendo empilhados conforme eles precisam ser alocados e desempilhados quando não mais são necessários. E a ordem de desempilhamento deve ser obrigatoriamente inversa ao empilhamento. Isto torna esta área muito rápida. Mas sua limitação é que tem um espaço que não pode crescer e que não pode destruir dados de forma aleatória. Você não pode, por exemplo, deixar um dado alocado recentemente ainda em uso e destruir outros não necessários que foram alocados antes.
Mais detalhadamente
Para entender melhor sobre stack e heap veja minha resposta genérica sobre o assunto. A explicação não é tão simples mas não é tão complexa quanto o assunto realmente é. Também esclareço sobre a diferença entre tipos por valor e por referência nessa outra resposta sobre o C#. A maior diferença é que o Java não permite criar tipos por valor, pelo menos até o Java 12 (está previsto no Java 13 ou depois), só os tipos primitivos são por valor.
Coloquei no GitHub para referência futura.
Answer: Todo mundo sabe que computadores são máquinas que trabalham com código binário. Tudo com que um computador lida são zeros e uns.
Então, quando você tem um dado no seu programa, você tem um conjunto de zeros e uns. Mas esse conjunto não pode simplesmente ficar solto no espaço - ele tem que estar bem localizado na memória RAM. Caso contrário, seu programa não saberia distinguir a folha de pagamento que você implementou de fotos de gatinhos carregadas numa aba aberta do seu navegador.
Em geral, runtimes como o do C++, e das plataformas Java e .NET, separam dois espaços na memória RAM (literalmente algo do tipo "do byte de número X até o byte de número Y") para cada programa que estiverem rodando. Esses dois espaços são geralmente chamados de Stack e Heap, mas esses nomes são arbitrários e convenções humanas, não de máquina.
Todos os objetos que você instancia em seu programa é alocado e endereçado na memória, em um desses dois espaços. Se ele vai para o Stack ou para o Heap depende de como o objeto é criado.
Objetos ditos por valor (em geral, os primitivos como int, bool, double etc.), bem como as referências declaradas dentro de um método, são alocados no Stack. Objetos por referência vão pro Heap.
E qual a diferença? Stack significa pilha. O Stack é feito de células, ou contextos... Toda vez que você chama um método, uma nova célula ou contexto é empilhada no stack, com as informações daquele método. Essa célula ou contexto existe enquanto o método não chegar ao seu fim, e todas as variáveis que o método precisa são alocadas nessa célula. Então, se temos algo como:
public void Foo() {
    int a = 0;
    boolean b = false;
    Bar();
}

public void Bar() {
    int b = 1;
    Ni();
}

public void Ni() {
    int c = 2;
}

Teremos um stack assim que cresce assim:
Foo -> |a == 0, b == false|

Bar -> |b == 1|
Foo -> |a == 0, b == false|

Ni  -> |c == 2|
Bar -> |b == 1|
Foo -> |a == 0, b == false|

Note que há dois objetos chamados b, com tipos e valores diferentes. Não tem problema. O programa "enxerga" apenas o contexto ou célula atual, que é a que estiver no topo a cada momento.
O Garbage Collector não tem poder nenhum aqui. Ele nunca vai desalocar e devorar os objetos na stack. No entanto, quando um método acaba, sua célula no Stack é desempilhada e destruída, levando todos os objetos alocados dentro daquela célula pro inferno dos objetos, o que acaba desalocando tudo que estiver lá.
Já no Heap não existe pilha. Heap significa montinho, e lá os objetos são alocados na base do "vai do jeito que encaixar". Os objetos sobrevivem entre chamadas de métodos, e ficam a mercê do Garbage Collector. Eles morrem quando o GC achar que eles devem morrer (o algoritmo de juízo final mecanismo do GC, no entanto, é tópico para outra pergunta).
Quando você instancia algo de uma classe, tipo:
ArrayList l1 = new ArrayList();

Você tem na verdade dois objetos. l1 é uma referência ou ponteiro, e vai viver no Stack. Sua única função é informar ao programa em que endereço no Heap se encontra a lista que você criou com o comando new List(). Essa lista sobreviverá ao fim do escopo onde foi declarada.
Por isso, é mais rápido alocar e desalocar objetos no stack, mas eles só vão existir dentro do escopo de um método. Já no Heap existe gerenciamento de memória. É mais lento alocar e desalocar, mas os objetos sobrevivem ao método e morrem apenas quando não são mais necessários.
P.S.: um motivo pelo qual é bom ter objetos no Heap é que você não precisa copiar eles inteiros de uma chamada de método para outra. Se você tiver uma lista de um mega, coisas como:
Foo(l1); // aproveitando a que criamos mais acima

Você está trabalhando com um objeto que ocupa um mega na memória. Se lista fosse por valor ao invés de ser por referência, uma nova cópia da lista seria gerada toda vez que ela fosse passada como parâmetro, então só aqui seria o dobro de memória consumida. No final das contas, trabalhar com referências economiza memória na maioria dos casos.
Comment: Não sei se isso é óbvio pra todo mundo ou não, mas não custa frisar: "Objetos ditos por valor (...), bem como as referências declaradas dentro de um método, são alocados no Stack..." *...quando* os mesmos são declarados em um método. Se uma classe possui um campo (atributo) esse campo faz parte dos dados dos seus objetos - e portanto ocupam espaço no *heap* (ainda que sejam tipos primitivos ou referências a outros objetos).
Comment: @Maniero valeu! Faz tanto tempo que eu não toco em Java que eu já tinha esquecido XD

Heap de memória Java