unison / rsync getting copies of changed files

Question: So the place where I'm working at has a nifty little Red Hat Enterprise server and a tape backup system that they want me to get working backing up the large amounts of video content and resources produced by the company.
The desired situation would be to keep a local copy of all the data on said Red Hat server and then copy all changed files to tapes which will then be sent offsite.  I know that I can use either unison or rsync for the initial local data backup but what I need to know is if there is a way to get a list of only the changed files which will then be copied (in full) to the tape.
I've found several possible solutions through auditing software but they all seem to require a kernel recompile (which is not feasible right now).  I also was promised that unison could do this "out of the box" but I haven't figured out how.
Is there a solution to my presented question or am I going about this at a fundamentally wrong way?  Any help/advice would be appreciated!
Cheers!
-Russell C
Answer: I would use a backup program like Bacula to do this. It keeps a database of your backups so it don't need to compare file sizes and time stamps against already backed up files like rsync.
If you want to use rsync, you could use find to find files changed after your last backup, write this to a file and read the file names to copy from this file with rsync's --files-from option. This opens timing issues, though.
Comment: Bacula looks really cool but it may be a bit much for a single junior engineer like me to set up without support from anyone else here. :(  I'll look into it some more anyways.
Comment: Granted, Bacula is not the easiest software, but it's quite powerful. But beside Bacula, there are other possibilites like Amanda, basic tools like tar (which stands for tape archiver), commercial packages like Arkeia or BRU and countless other options.
Comment: But one comment which I hope you don't take personal: If you think Bacula is over your head and you are just a lone beginner with no support from colleagues, things are seriously wrong at your company: Backup is **extremely** important, it's among the most important tasks for a system adminstrator,  very difficult to get right and test and really nothing you would give a junior admin to "do it somehow". I would really recommend that you ask more senior colleagues to do this together with them, so you get it right and don't learn you missed a small, but important bit after disaster struck.
Comment: Yup, I'm actually at a small startup that's fairly new and still hiring people (we're on the lookout for an actual IT guy now).  Technically I'm more supposed to be a scripting guy but I said I'd give a crack at this anyway.  They have a series of drive mirroring on the server but want some offsite backups, too.  Hopefully we can get this working before we actually have anything important to back up.
Comment: I also know that I'll be using tar quite a bit because of the tap backups. I may start another thread later about some specifics of tar if I can't find answers already here or on stack overflow.
Answer: Whats wrong with the normal rsync output?
/tmp # ls -l ra
total 8
-rw-r--r-- 1 phemmer unix  5 2011/02/09-16:42:49 adsf
-rw-r--r-- 1 phemmer unix 29 2011/02/09-16:49:41 date

/tmp # date > ra/date

/tmp # rsync -Haxv  ra rb
building file list ... done
ra/date

sent 180 bytes  received 42 bytes  444.00 bytes/sec
total size is 34  speedup is 0.15

Just pipe rsync out somewhere rsync ... 1>/path/to/log and then parse through the log for the list of files changed
P.S. You do not want to use unison for this. Unison is a 2-way rsync, for backups you want 1-way.
Comment: I was just wondering if there was a simpler way to redirect the files instead of having to parse an additional file.  I guess I must have also missed the fact that I could capture the simplified output to a file with a simple redirection.
Comment: But if you store your backup data on a tape, there is no easy/fast way for rsync to access the files on the tape to make the comparison, this only works if you have a normal tree of files which rsync can access.
Comment: @russel you could use something like unionfs and get exactly what you want in 1 step, but that'd be even more complex than parsing a log file
Comment: @svenw, he stated that he was going to be keeping a copy of the files on the local machine, so it would work fine. the only way to do it if all the files were on tape would be to generate checksums of the files before they got sent to tape, and then re-checksum every file to see if its change. which isnt what he's doing.
Comment: The way I understood the question is that the local copy is the primary data/backup source, so there is no easy way for rsync to do a comparison. In this case, tar is a better tool anyway, with either the -g or the -N options.


How to improve Ubuntu performance on netbook

Question: Most recent Ubuntu 12.04 seems to be quite nice and Unity (3D/2D) works fine for me, however not on my old Acer Aspire One any more.
There was a times, when I switched from Windows XP to Ubuntu and was happy about system looks, effects and speed... now I attend to think that XP was really great comparing with 12.04.
I have found similar questions here but no reasonable answer: how to lower CPU usage for Unity (3D/2D) and memory consumption for Ubuntu 12.04.
With new interface I could not find how to disable background services...
It's Linux, it's should be the way to optimize without buying new PC... Please share your recipe!
Answer: I know this is an old question, but I had similar problems on my Samsung netbook and maybe the described steps will be useful to someone.
My netbook is an old machine and Ubuntu 12.04 was too slow to be useful. I tried several tweaks, which improved things, but not enough.
I didn't feel like replacing Ubuntu with Lubuntu and then installing all the software that I like in Ubuntu.
So I did the following:

installed the lxde core desktop - this installs the desktop, but not all the other software - I used these instructions: http://complete-concrete-concise.com/ubuntu-2/ubuntu-12-04/ubuntu-12-04-how-to-install-the-lxde-core-desktop
installed lxterminal (so that I can start the terminal with ctrl+alt+t shortcut, there is a way to map the shortcut to point at the Ubuntu terminal, but I found this solution to be simpler)
installed "synaptic package manager" (it's much faster then Ubuntu software center)
installed "synapse" as the launcher, so I can use it instead of the searching in dash
moved the window close, maximise and minimise buttons to the left according to the instructions here: http://www.lubuntutips.com/2012/07/moving-close-maximize-and-minimize.html#.UI09auBuHXY

I really like Unity and I use it on my desktop computer. And while the above doesn't allow you to use some cool features such as the global menu and HUD, I find it's a very good compromise. Everything now works really, really fast.
Comment: One more thing that I forgot, sorry: when installing the LXDE core on top of Ubuntu 12.04 all the icons disappear (at least that is what always happened to me). This can be corrected by installing LXAppearance, running it and selecting one of the listed icon themes. (sudo apt-get lxappearance)
Answer: First thing to do to lower memory consumption is to stop using applications that are memory hogs. The applications that I had to switch away from were Banshee, Evolution, Liferea, and Tomboy. The applications which I switched to respectively were Rhythmbox, Thunderbird, Google Reader and none (graduated from school so no longer need a note taking application).
Second thing to do is to make Firefox more friendly. In Preferences » General uncheck the Don't load tabs until selected checkbox and set the When Firefox starts option to Show my windows and tabs from last time. Whenever my computer gets slow, I close Firefox and re-open it which causes all tabs to not be loaded except for the one that I am currently using. If you have flash installed then the Flashblock plugin is necessary. Firefox tabs in the background that are using flash are very demanding and Flashblock helps you stay aware when Flash is in use. AdBlock will also help keep Firefox more resource friendly if you are desperate.
That is all the advice that I have for you. I have found the Unity 3D interface to be very usable on my older netbook (Intel Atom N270 with GMA 950). My computer does get slow at times but that is almost exclusively a Firefox problem but I tend to open up a lot of tabs so that is easily fixed.
Answer: You can try zRamswap which is a program that create a compressed RAM block and make it act as a swap disk. Basically, this program increase performances by using a small amount of RAM as a swap area (instead of swap disk which is slow compared to RAM).
You can install this program by adding this ppa to your software sources:
 sudo apt-add-repository ppa:shnatsel/zram
 sudo apt-get update
 sudo apt-get install zramswap-enabler

Comment: Please note that with precise pangolin there's no longer the need for that ppa. Simply type **sudo apt-get install zram-config** in a terminal, wait for the installation to finish and reboot. There's no need for further configuration.
Answer: I would install Lubuntu or Xubuntu as it has lower requirements. In a terminal, execute:
sudo apt-get install xubuntu-desktop

or
sudo apt-get install lubuntu-desktop

I personally use Lubuntu, but you can use either.
Comment: Doesn't really answer the question though.
Comment: 100% I'd like to have Ubuntu look and feel on my netbook. I believe there is some capacity in it to run 12.04 smoothly. I just haven't found it (yet :)
Comment: Using LXDE to make your computer faster is like replacing your car with a skateboard to save on gas. You're not wrong...but this is not a solution anyone wants.
Answer: I am using a pretty smooth 14.04 on my samsung nc10 plus. maybe it will help you out on 12.04 too:
First of all i deactivated the effects in unity using unity tweak tool and compiz config:
sudo apt-get install unity-tweak-tool compizconfig-settings-manager

I also set the swap usage to a more reasonable level:
open sysctl.conf gksudo gedit /etc/sysctl.conf and add vm.swappiness=10 to the file, then reboot.
Last of all I deleted all unity-lenses exept the applicaion- and the files-lense:
sudo apt-get autoremove --purge unity-lens-music unity-lens-video unity-lens-photos unity-lens-gwibber unity-lens-shopping

After doing that, my netbook runs pretty smooth and good runing unity. If you are only concerned abou the look, try installing the gnome flashback session:
sudo apt-get install gnome-session-flashback

That's all I can do to provide some help. Cheers.


Stop and continue 3D printing

Question: How to successfully pause 3D printing and turn off the printer and the next day, continue to print the model?
Comment: Do you know when you want to pause it when you start the print?
I completed a failed print once by measuring its height and removing all already printed segments from the g-code file. Worked reasonably well.
Comment: You could use an M0, M1, or G4 command after a non-printing move (preferably just after a layer change and move to home) if your setup allows.
Answer: I recommend that you don't turn off the printer and resume the next day. If the heat bed cools down the part could become unstuck. The printer must be kept hot for the entire time that you need to print; unless it's PLA which tends to be more forgiving. Also Turning off the printer and turning it back on will cause it to loose it's position. Each time you home the axis of the printer it could home in a slightly different location. If you resumed the print under those conditions it would leave a clear line on the outer walls that is indicative of the layers not lining up properly. Lastly, if you let the nozzle ooze for period of time, you will have to purge the nozzle before you could print again. In this regard be prepared for some air printing for the first few movements. Depending on what you are printing, this could result in a build failure.
Needless to say, people have been able to recover a print under power off/failure conditions, but that's not a strategy to 3d printing. Those were mitigation efforts to exception cases.
Answer: If you enable M413 in Marlin firmware, the printer will write a resume printing file to SD card e.g. every layer.
From M413 - Power-loss Recovery documentation I quote:

Enable or disable the Power-loss Recovery feature. When this feature is enabled, the state of the current print job (SD card only) will be saved to a file on the SD card. If the machine crashes or a power outage occurs, the firmware will present an option to Resume the interrupted print job. In Marlin 2.0 the POWER_LOSS_RECOVERY option must be enabled.
This feature operates without a power-loss detection circuit by writing to the recovery file periodically (e.g., once per layer), or if a POWER_LOSS_PIN is configured then it will write the recovery info only when a power-loss is detected. The latter option is preferred, since constant writing to the SD card can shorten its life, and the print will be resumed where it was interrupted rather than repeating the last layer. (Future implementations may allow use of the EEPROM or the on-board SD card.)

This means if you cut the power you can resume the print layer, the only problem is that the part must remain attached to the plate, if it comes loose it is hard to resume printing. This feature is now commonly found on printers these days.
The regular pause and resume functionality of the printer will not work when the power is cut over night, i.e. no recovery file is written in such a case.
Comment: I have never understood the votes cast on this sub. IMO This is the perfect answer, all the others are just tinkering (mine included)!
Comment: Yeah guys, vote, but when you downvote, also tell why or it only comes off as an angry down-vote spree.
Comment: @TDHofstetter  Left that place for Lemmy some time ago already ;-)
Comment: @Valmond, unfortunately... that is the nature of man. If you doubt that, become a member of Reddit and watch as people downvote you to infinity at first, until you establish you credibility.
Comment: @Valmond, thanks, remember voting is key! Top answers will float to the top. Note that this answer, although it works, it is not perfect, this is not what the resume on power outage has been designed for. There is just no alternative if it has to include a shutdown as per request of the OP, this is the best answer I could think of including powering down.
Comment: This functionality has a lot of negative side effects (like putting warts all over your print), and should not be used. It also does not resume at the point you left off, only at the start of the layer. This means some parts will be re-printed, producing collisions between the nozzle and the part and likely knocking it off the bed.
Answer: Set up your printer to be controlled by an outside source via USB or other protocol. Now set up a PC / a Pi / a Beaglebone / an Arduino / etc ... to feed GCode to your printer from MicroSD. I personally like the "an Arduino" option here because it's super-low-power and gives you tons of control over what you're doing... so I'll continue along the Arduino vein here.
Power your Arduino from a battery-backed wallwart. That'll give it plenty of guts to hurriedly write a record to a special file on MicroSD maintained for that express purpose. Or heck, write that record to EEPROM, which should be good for a hundred thousand power outages.
Next, rig up something that permits your Arduino to sense a complete power failure at the wall. You'll want a current transformer, perhaps, and little to no filtering so you get notified within 1/50 or 1/60 of a second when you detect a missing power excursion. Your Arduino should stop sending and record that record when it detects a power drop.
At power-up, your Arduino should detect that it wrote a power-off record and offer to resume pumping GCode to your printer after it sends the appropriate warm-up sequence to the printer. It should offer you the option of bagging the print or trying a resume. If you try the resume, it should seek() to the file position corresponding to the first GCode command after the last Z increment that was not a "Z hop". It should then step through all the G1 commands since that position, but traverse only, do not extrude, until it reaches the last command it had sent. It cannot know where along that G1 the printer paused, so it should repeat that one G1 line with extrusion active. You should get exactly one partially extra-fat line of filament at that one point in your print, but otherwise the stitching should be very good.
Provided, of course, that you've been ensuring exceptional print adhesion. The whole nine. Don't risk poor adhesion with a stunt like this, give yourself good adhesion. Really, your print should not pop off the build surface upon cooling. If it does, then you aren't doing enough to keep it there.
Comment: The majority of my edits were in accordance with the Meta post [Useful things to check for when cleaning up posts](https://3dprinting.meta.stackexchange.com/questions/500/useful-things-to-check-for-when-cleaning-up-posts). Please don't roll back useful edits.
Comment: @agarza Too many of your edits were arbitrary. For example, you changed "wallwart" to "wall-wart", despite the worldwide standard usage of "wallwart" as a single unhyphenated word. Please don't make arbitrary "corrections". Useful edits (or suggestions) are welcome.

After your whole packet of "corrections", my answer no longer read like MY answer... and I couldn't roll back each arbitrary edit invidually.

And... frankly... I don't see where :any: of your edits were in confornity with the "Useful Things...Posts" guideline.

I removed "So... ". Nothing else is incorrect.
Answer: 1) Cut the model up in several parts and print one each day. Remove each part every day and in the end, glue them all together.
2) Cut the model up in several parts and each day, add a G-code to the file to be printed so it lowers the heat-bed and thus starts to print on top of yesterdays print. This cannot be used when the printer is auto-calibrating as the printer-head would crash into the already printed part. It would probably be tricky.
3) Pause the printer in the evening, then resume next day (don't forget to lower temperatures and rise them again tomorrow).
Answer: Some printers have built-in functionality for resume after power-loss. I believe this is a standard part of the Marlin firmware now; I know the Creality Ender 3 has it and I don't believe it was a nonstandard addition (and if it was, their source was released in accordance with the GPL anyway, so it could be merged). So if you printer doesn't already have the functionality, but is amenable to a firmware upgrade/replacement to a version of Marlin that does, it should be possible to get it.
I have an Ender 3, but I haven't tried this feature so I can't speak to how well it actually works.
Answer: I already answered once more directly, but I think a better answer might be a frame challenge: design your model to avoid extremely long print times. Even if you didn't have all the problems of pausing and resuming to deal with, which include:

warping and detachment from bed due to loss of bed heat
possible motion of stepper motors while unpowered
extrusion problems due to loss of material to oozing
...

you still have the fundamental risk that something goes wrong during the print, which increases significantly with the overall print duration.
There are lots of ways to design your model to be printed in multiple parts that don't amount to just "cut it at height intervals and glue the result". Glue isn't a terribly good solution, at least not by itself; it's hard to ensure perfect alignment, and creates points with different thermal and mechanical properties that are likely to break. Other options include:

Snap fits, either reversible or permanent.
Peg/hole press fit.
Slide-in tension fit.
Threaded interfaces. These can easily be directly between your parts if the parts are rotationally symmetric or orientation doesn't matter. If it does matter, you can design the threads to stop at the right point but it's more work.
Threaded holes in one part, metal or 3D-printed bolts through the other to attach it.

In addition to letting you print the object in steps rather than all at once to reduce the chance/cost of failure, these techniques also allow you to print different parts of the object in different orientations, taking advantage of the orientation for ease of printing without supports, or for obtaining stength in the directions your object will be subjected to stresses in.
Most (really all) of the above can also be made permanent with glue, if you desire.

Stop and continue 3D printing


get IPv4 address into a variable

Question: Is there an easy way in PowerShell 3.0 on Windows 7 to get the local computer's IPv4 address into a variable?
Answer: Here is another solution:
$env:HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress

Comment: This does *not* work on Windows 7 as the OP required.  The cmdlet was not introduced until Server 2012/Windows 8.
Comment: This works well, but it is slow, took 3981ms seconds to run on my laptop (i5-7th-gen/12GBRM)
Comment: I get no output on Windows 10 PS 5, but splitting it like this it works: `$i=Get-NetIPConfiguration|Where-Object{$_.ipv4defaultgateway -ne $null};$i.IPv4Address.ipaddress`
Comment: Get-NetIPConfiguration is not currently available in Powershell Core under Linux.
Comment: On windows 10 this was pretty snappy; only took about a second to run the first time (didn't really notice it) and after that just ran with no noticeable delay.  -- And it returns the correct IP address.  Nice work.
Comment: `$i=Get-NetIPConfiguration|Where-Object{$_.ipv4defaultgateway -ne $null};$i.IPv4Address.ipaddress` Works for me in PS7 Windows 10
Answer: How about this? (not my real IP Address!)
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select IPV4Address

PS C:\> $ipV4

IPV4Address
-----------
192.0.2.0

Note that using localhost would just return and IP of 127.0.0.1
PS C:\> $ipV4 = Test-Connection -ComputerName localhost -Count 1  | Select IPV4Address

PS C:\> $ipV4

IPV4Address
-----------
127.0.0.1

The IP Address object has to be expanded out to get the address string
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1  | Select -ExpandProperty IPV4Address

PS C:\> $ipV4

Address            : 556228818
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 192.0.2.0

PS C:\> $ipV4.IPAddressToString
192.0.2.0

Comment: This work well, thank you. To sum up all advice, THIS is the most elegant solution:

`$ipv4 = (Test-Connection -ComputerName $env:ComputerName -Count 1).IPV4Address.IPAddressToString`  I tested this on a system when connected to a wired network, and it shows that IPv4. When not connected to any network it shows home (127.0.0.1), and when connected to wireless it shows that IPv4.
Comment: There are IP Addresses specifically reserved for examples / documentation ( 192.0.2.0/24, 198.51.100.0/24,203.0.113.0/24) https://tools.ietf.org/html/rfc5737
Comment: You can avoid calling an external utility with `(hostname)` by using the  `$env:COMPUTERNAME` environment variable, i.e. `Test-Connection $env:COMPUTERNAME -Count 1 | Select IPV4Address`.
Comment: `$ip = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString`
Comment: How can I get the wifi ipv4 address? It shows my eth0 address which in my case is my wsl network down the road.
Comment: PWS 7.3.X slightly changed it to `echo (Test-Connection -ComputerName $Env:Computername -IPv4 -Count 1).Address.IPAddressToString`
Comment: This does not work with certain virtual machine software installed.  In particular, if VirtualBox is installed it returns the default IP of the VirtualBox Host-Only Network (192.168.56.1).
Answer:

Here are three methods using windows powershell and/or powershell core, listed from fastest to slowest.
You can assign it to a variable of your choosing.

Method 1: (this method is the fastest and works in both windows powershell and powershell core)

$ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress

Method 2: (this method is as fast as method 1 but it does not work with powershell core)

$ipAddress = (Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPv4Address).IPAddressToString

Method 3: (although the slowest, it works on both windows powershell and powershell core)

$ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress
Comment: This is not available on some systems:  Get-NetIPConfiguration
Answer: If I use the machine name this works. But is kind of like a hack (because I am just picking the first value of ipv4 address that I get.)
$ipaddress=([System.Net.DNS]::GetHostAddresses('PasteMachineNameHere')|Where-Object {$_.AddressFamily -eq "InterNetwork"}   |  select-object IPAddressToString)[0].IPAddressToString

Note that you have to replace the value PasteMachineNameHere in the above expression
This works too
$localIpAddress=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

Comment: The second expression gave me the error below: `Program 'ipconfig.exe' failed to run: The directory name is invalidAt line:1 char:20 $localIpAddress=(( ipconfig | findstr [0-9].\.)[0]).Split()[-1]
+                    ~~~~~~~~.
At line:1 char:1
+ $localIpAddress=(( ipconfig | findstr [0-9].\.)[0]).Split()[-1]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed`
Answer: Here is what I ended up using
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])

which breaks down as

execute ipconfig command - get all the network interface information
use powershell's where filter with a regular expression
regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3  digits separated by periods, i.e. a v4 IP address
disregard the output by piping it to null
finally get the first matched group as defined by the brackets in the regular expression.
catch that output in $ipaddress for later use.
Comment: ugly, but works well and way faster than accepted answer
Answer: (Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress

Comment: This worked.  Seems less elegant than the excepted answer though.
Comment: This is not correct. You may also need to include `DHCPEnabled=True`. The output of this command isn't the same as provided by @Lucas (`Get-NetIPConfiguration`).
Answer: This one liner gives you the IP address:
(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

Include it in a Variable?
$IPV4=(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

Answer: Another variant using $env environment variable to grab hostname:
Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address

or if you just want the IP address returned without the property header
(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring

Comment: **BEWARE, THIS IS DANGEROUSLY WRONG**. It returns some IP address, but if you have virtual adapters (e.g. for VPN, Hyper-V, Docker, etc.), it may not be the one externally visible.
Comment: This definitely does not return the correct IP address on my machine.
Answer: tldr;
I used this command to get the ip address of my Ethernet network adapter into a variable called IP.
for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

For those who are curious to know what all that means, read on
Most commands using ipconfig for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.
You can see your list of network adapters by using the netsh interface ipv4 show interfaces command. Most people need Wi-Fi or Ethernet.
You'll see a table like so in the output to the command prompt:
Idx     Met         MTU          State                Name
---  ----------  ----------  ------------  ---------------------------
  1          75  4294967295  connected     Loopback Pseudo-Interface 1
 15          25        1500  connected     Ethernet
 17        5000        1500  connected     vEthernet (Default Switch)
 32          15        1500  connected     vEthernet (DockerNAT)

In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).
As mentioned, I was interested in Ethernet in my case.
To get the IP for that adapter we can use the netsh command:
netsh interface ip show config name="Ethernet"
This gives us this output:
Configuration for interface "Ethernet"
    DHCP enabled:                         Yes
    IP Address:                           22.214.171.124
    Subnet Prefix:                        184.108.40.206/16 (mask 255.255.0.0)
    InterfaceMetric:                      25
    DNS servers configured through DHCP:  None
    Register with which suffix:           Primary only
    WINS servers configured through DHCP: None

(I faked the actual IP number above for security reasons )
I can further specify which line I want using the findstr command in the ms-dos command prompt.
Here I want the line containing the string IP Address.
netsh interface ip show config name="Ethernet" | findstr "IP Address"

This gives the following output:
 IP Address:                           126.96.36.199

I can then use the for command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.
Note that I am looking for the third item (tokens=3) and that I am using the space character and : as my delimiters (delims=: ).
for /f "tokens=3 delims=: " %i  in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i

Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the | and = using a ^
At the end of the for command you can specify a command to run with the content that is returned. In this case I am using set to assign the value to an environment variable called IP. If you want you could also just echo the value or what ever you like.
With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?
If you have any ideas for improving please leave a comment.
Answer: I was looking for the same thing and figured this out:
$ip = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile | Select-Object -ExpandProperty InterfaceIndex) | Select-Object -ExpandProperty IPAddress

This filters out both the loopback address and some virtual networks I have.
Comment: Awesome, other solutions were returning HyperV/VMWare etc, but this one does just my WiFi adapter. Thanks!
Answer: $ip = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile).InterfaceIndex).IPAddress

OR
function Get-LocalIP {
    (
        Get-NetIPAddress `
            -AddressFamily IPv4 `
            -InterfaceIndex $(
                Get-NetConnectionProfile
            ).InterfaceIndex
    ).IPAddress
}

$ip = Get-LocalIP

Comment: not sure about PS 3.0 (as per the question), but this does work nicely for 7.2.8... :)
Answer: To grab the device's IPv4 addresses, and filter to only grab ones that match your scheme (i.e. Ignore and APIPA addresses or the LocalHost address). You could say to grab the address matching 192.168.200.* for example.
$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress

Answer: # Patrick Burwell's Ping Script - firstname.lastname@example.com #
$Output= @() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against
  if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
  ){# If true then run...
   $Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
   Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
  }
  else{#If false then run...
    $Output+= "$name," #Fills the array with the #false response
    Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors
  }
}

#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)

#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments

Comment: Does ANYONE know how to get line 7 to write a SINGLE LINE into the array? :)
Comment: $Output+= $Name,',',($IPV4.IPV4Address).IPAddressToString # each entry goes into a separate line
Answer: As I was working in Powershell 3, none of the answers here worked for me. It's based on Rob's approach, but this one works when you have multiple network adapters, it also picks out the IP correctly using capture groups
function GetIPConfig {
    return ipconfig | select-string  ('(\s)+IPv4.+\s(?<IP>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(\s)*') -AllMatches | %{ $_.Matches } | % { $_.Groups["IP"]} | %{ $_.Value }
}

Answer: Non of the top comments are actually fully correct since a computer can have multiple interfaces and an interface can have multiple IP addresses. There are a few answers here which technically correct but utilizes "funky" ways to filter out wellknown addresses (like APIPA, localhost, etc) whereas even Powershell 3.0 have a native way to do so with PrefixOrigin.
$IPv4Addresses = $(Get-NetIPAddress | Where-Object { $_.PrefixOrigin -ne "WellKnown" -and $_.AddressFamily -eq "IPv4" }).IPAddress

Answer: I do this :
$interFaceAliasName="LAN" # You have to change the name according to your interface's name
$myInterface=(Get-NetIPAddress -InterfaceAlias $interFaceAliasName)
$myIP=$myInterface.IPv4Address

Answer: Below command worked for me

(Invoke-RestMethod -Uri 'https://api.ipify.org?format=json').ip
Answer: Here's a pretty simple method, split line with 'ipv4 address' on white space, and pick the last word.  It assumes 'ipv4 address' only appears once.
$ip = (-split (ipconfig | where { $_ -match 'ipv4 address' } ))[-1]

Trying this somewhat convoluted one made from two different scripts for network speed and renaming computers.  It excludes hyper-v and wi-fi.  Get-netadapter puts 'wi-fi' under 'name' and 'hyper-v' under 'interfaceDescription'.
Get-CimInstance Win32_NetworkAdapter |
  where { $_.speed -and $_.macaddress -and
  $_.name -notmatch 'wireless|wi-fi|bluetooth|802\.11|hyper-v' } |
  get-netipaddress | ? AddressFamily -eq IPv4 | % ipaddress

192.168.1.23

For troubleshooting, showing both the names and the ipaddresses.  You can check the netenabled property to see if an interface is connected too.
Get-CimInstance Win32_NetworkAdapter |
  where { $_.speed -and $_.macaddress -and $_.netenabled } |
  select name, @{n='ipaddress';e={$_ | get-netipaddress -addressfamily ipv4}},
  netenabled

name                                        ipaddress      netenabled
----                                        ---------      ----------
Intel(R) 82579LM Gigabit Network Connection 172.18.136.171       True
Hyper-V Virtual Ethernet Adapter            172.25.96.1          True

Answer: I recently had the same issue. So I wrote a script to parse it from the ipconfig /all output. This script is easily modifiable to obtain any of the parameters of the interfaces and it works on Windows 7 also.

Get output of IP config in LineNumber | Line format

$ip_config = $(ipconfig /all | % {$_ -split "rn"} | Select-String -Pattern ".*" | select LineNumber, Line)

Get list of interfaces (+ last line of ipconfig output) in LineNumber | Line format

$interfaces = $($ip_config | where {$_.Line -notmatch '^\s*$'} | where {$_.Line -notmatch '^\s'}) + $($ip_config | Select -last 1)

Filter through the interfaces list for the specific interface you want

$LAN = $($interfaces | where {$_.Line -match 'Wireless Network Connection:$'})

Get the start and end line numbers of chosen interface from output

$i = $interfaces.IndexOf($LAN)
$start = $LAN.LineNumber
$end = $interfaces[$i+1].LineNumber

Pick the lines from start..end

$LAN = $ip_config | where {$_.LineNumber -in ($start..$end)}

Get IP(v4) address field (returns null if no IPv4 address present)

$LAN_IP = @($LAN | where {$_ -match 'IPv4.+:\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'})
$LAN_IP = &{If ($LAN_IP.Count -gt 0) {$Matches[1]} Else {$null}}
Answer: $a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""

Also check which index of ipconfig has the IPv4 Address

get IPv4 address into a variable


A barrel of any (AND, OR, NOT) gate for logical completeness

Question: The book is called "Introduction to Computing Systems: From Bits and Gates to C and Beyond". Section 3.3.5 Logical Completeness.
It says "We say that the set of gates {AND, OR, NOT} is logically complete because we can build a circuit to carry out the specification of any truth table we wish without using any other kind of gate. That is, the set of gates {AND, OR, and NOT} is logically complete because a barrel of AND gates, a barrel of OR gates, and a barrel of NOT gates are sufficient to build a logic circuit that carries out the specification of any desired truth table".
I just want to know the meaning of the word "barrel" in this context.
Comment: It seems you forgot to actually include the context. Or is this *all* the context that you have. Then the question is plain unanswerable.
Comment: It simply means "a large quantity".
Comment: Knowing that a "barrel" of such gates is *not* a term from boolean algebra, I read the text referenced in the OP. The reader *is* lead to look for some mathematical term "barrel", where as all the author means is an arbitrary "box" of AND-gates, say. In other words, a English Usage issue and not a Mathematics issue.
Comment: It literally means a barrel. You can't build a truth table if you have [a barrel / any number of] AND gates, i.e., just AND gates will get you where you need to go, no matter how many you have, even if you have enough to fill a whole big barrel. You can build the truth table if you have a NAND gate, btw, which probably comes up next in the book.
Answer: It's difficult to be sure because the example is not a complete sentence.  It probably means something like "a large supply in no particular order or arrangement" in the manner of what you might get if you tossed a bunch of stuff into a large container like a barrel.
When I was a kid I had a game called "Barrel of Monkeys." The idea is that the plastic monkeys would be in there in any old arrangement, jumbled and tangled, and you had to lift them out by using a monkey to hook on to the next one. Then the next, and so on.

In this case, a barrel of logic gates seems to refer to an arbitrarily large supply of them, from which you are required to construct all possible logic circuits. It's a standard problem in logic circuits. What is the minimum set of gate types you need to be able to construct any possible logic circuit?
Comment: I can speculate, too. I can even speculate that I can speculate much better than you.
Comment: +1 I have read the original text referred to and this is precisely the context.


Getting the examples in libspotify to work under Windows 7

Question: I want to get started with libspotify on my Win 7 machine but I dont have a clue on how to get it all setup so that I can even run the examples included in the pack. I have a Spotify Premium account and I have tried installing libspotify by copying libspotify.dll to c:\windows, c:\windows\system32  and to c:\windows\SysWOW64 and also changed the path variable to include the path where libspotify.dll is located but I still dont understand how to get the examples to work.
I have Code::Blocks installed but as soon as I try to import and run any of the .c files included in the /examples/ folder I get all kinds of error messages. The truth is that I am not even sure how to install libspotify and the documentation is absolutely non existent so for a beginner it is impossible to even have a chance at getting started.
Is there somebody out there who can do a simple walkthrough on how to install libspotify and get the examples up and running on a Win 7 (64-bit) machine?
The only thing I really want to do with libspotify is to be able to via a command prompt or something like that be able to queue a song in Spotify so I dont really care about the other parts. But I can probably solve that by myself as long as I can get an example up and running.
Answer: Sadly libspotify is not well-supported on Windows, in fact the example code won't even build because there is no Windows audio driver for them. Your best bet to just get up and running would be to use mingw, or linux in a VirtualBox environment.


Integrate Whatsapp URL Scheme into an app

Question: Hello Folks at Stack Overflow from all over the world! Hope you're all doing pretty well! I have a quick question to ask. Has any of you found out or knows about a workaround to get a Whatsapp URL scheme to open a screen to draft a custom message and specifying a custom contact as well. I have already read the documentation on the Whatsapp website using the abid (Address Book ID) or text parameter but this does not lead me anywhere. if we want to send a custom email for instance we simply use:
E-mail

Is there such a workaround with Whatsapp Messeger?
Any feedback on this will be greatly appreciated folks. Thank you.
Answer: I cant provide a solution for this problem, but I think, https://www.whatsapp.com/faq/iphone/23559013 as it describe the Whatsapp API.


Rashi's biography sources

Question: I know that Rashi had daughters — either two or three — and no sons. I also know he was a vintner — meaning he made wine. I know he was a student of or student of a student of Rabenu Gershom. I guess I know this all from my schooling. My question is: Where is the source of all this information in classical Judaic sources? Meaning not a recent professor's, or any professor's, thesis, but a source in the rabbinic literature.
Comment: Related: http://judaism.stackexchange.com/q/27823
Comment: Actualy, R. Dr. Hayyim Soloveitchik casts doubt on the assertion that he was a vintner.
Answer: Seder HaDoros has a lot of the popular information that we know about Rashi, see the sources that he brings.

Rashi's biography sources


Do relatives (except my parents) have any right to complain about my dress up , according to Islam?

Question: Im an 18 years old girl,my dress up is not fully Islamic but I don't wear haram or revealing clothes.My parents sometimes suggest me to wear scarf but they don't force me.There are some relatives of mine who often complains about my dress up to me and my mom.I know they tell me because of my own good but sometimes this behavior of them makes me irritated.I just want to know if they have these kinds of rights over me.
Answer: Wearing hijab in front of non-mahrams is obligatory. Anyone, not just your relatives, have the right to advise you if you are committing a sin or leaving something obligatory.
That is because the believers are told to enjoin good and forbid wrong (الأمر بالمعروف والنهي عن المنكر).  See in the Quran in 3:104, 3:110
3:114, 5:63,5:78-79, 9:71, 9:112, 22:41, 31:17 etc. And also in hadith.


How to add classifier to dependencies and publish with git branch name?

Question: For an sbt/Scala/Play project:
I would like to use the current branch name and add that as a classifier for the dependency resolutions. If it's not a particular branch then I'd like to default with no classifiers.
Also the repo should publish its branch name as classifier.
I.e. If I am on develop branch, all internal dependencies should resolve with classifier develop and if on any other branch it should resolve with no classifiers.
Also for publish, based on the branch I'd like to add branch name if needed.
Any help would be appreciated.
Answer: I encountered the same problem.
I ended up using the above approach, i.e. using:
def branch() = "git rev-parse --abbrev-ref HEAD" !!
And in the version:
version := branch + "-0.0.3-SNAPSHOT",
Pay attention though that you need two exclamation mark and not one (the one return the command returns code).
Now I can use it as resolver in artifactory (and to distinct between different branches).
Answer: What about having a def to generate ModuleIDs for your dependencies in libraryDependencies that uses git rev-parse --abbrev-ref HEAD under the covers?
Use the following in a build.sbt build definition as a gentle start. Use show libraryDependencies to print out the dependencies with branch added.
def branch() = "git rev-parse --abbrev-ref HEAD" !

def dependency(g: String, m: String, v: String): ModuleID = {
    g %% m % s"$v-${branch()}"
}

libraryDependencies += dependency("com.typesafe.akka", "akka-actor", "2.3.4")

You may also be quite successful with A GIT plugin for SBT.
Comment: In Play/Build.scala , how can i get latest SNAPSHOT or latest release version, in gradle world, i just use latest.integration or latest.release. Thanks for helping!
Comment: `latest.integration` as described in [Dependencies](http://www.scala-sbt.org/0.13.5/docs/Detailed-Topics/Library-Management.html#dependencies) in the official docs of sbt.


Where to use Womens and Women'S

Question: What is the difference between womens and Women's? where to use Womens and Women's?
Comment: "Women's" is the plural possessive of "woman."  "Womens" isn't a word.
Comment: [Related question about *mens*](http://english.stackexchange.com/questions/112420/is-mens-a-valid-word) | [Related question about the "opposite of the greengrocer's apostrophe"](http://english.stackexchange.com/questions/59425/is-there-a-term-for-the-opposite-of-the-greengrocers-apostrophe)
Comment: Could you please say where you saw *womens*? The nouns *woman* and *women* should not be capitalized, unless it is the title of a book, or a proper noun such as [*Woman's Hour*](http://www.bbc.co.uk/programmes/b007qlvb)
Comment: I saw at least 5 `womens` labels in Manchester shops and changing rooms in few days I spent there. But it could possibly be related to numerous emigrants living there.
Answer: NEVER use "womens".
Women is the plural of woman , so there cannot be a plural of  women.
However, you will see this simple truth ignored everywhere you look:

Womens Clothing Department
Womens Restroom, Mens Restroom (signs on doors that say WOMENS and MENS) — wrong!!!
Womens Issues, Womens Lib, etc.

Do not let these mistakes that other people make confuse or distract you. They are WRONG.  Usually these errors occur because people never learned the difference between plurals and possessives.

Woman is singular.
Man is singular.
Women is plural.
Men is plural.
Woman's is a singular possessive.
Man's is a singular possessive.
Women's is a plural possessive.
Men's is a plural possessive.
Womens is not a word. Mens is not a word.

Learn the difference well, and don't believe what you see online or on signs!  A million people might get this wrong; that does not make them right.
Comment: But according to many on this site if people 'get it wrong a million times' it becomes *de facto* English - see postings *passim* on the use of *diagnose*. They will talk to you about *the etymological fallacy*. If there is an argument for it, why not apply it to grocers' apostrophes too! Personally I won't have any of it and support a corollary to the *etymological fallacy*.
Comment: Whatever. I get paid well to fix such garbage.

Where to use Womens and Women'S


Magento 2 Connection to External Database

Question: Can anyone provide a tutorial, or link to a tutorial for adding a connection to an external database in Magento 2?
Slowly getting my head around the new structure and procedures in M2, but this one is eluding me.
Comment: I found the fishpig tutorial too. To be honest, no idea how far M2 differs from M1. I suspect that the code itself is largely the same, but that's not guaranteed, plus, with the differences in the file structure for new modules, I wouldn't like to guess.
Comment: How far it is from http://fishpig.co.uk/magento/tutorials/create-external-database-connection/ ? I cannot find anything useful in https://wiki.magento.com/display/MAGE2DOC/Developer%27s+Guide :(
Comment: What do you mean by "external database"? Magento connects to MySQL by default. There are modules that hook up to Redis etc. For other data sources you can write your own PHP code in a module to talk to them. Not sure what more you are after so cannot respond.
Comment: By external database, I mean a non-magento database, located on a different MySQL server from the M2 db. In order to provide real-time data from systems outside of M2.
In M1 this was easily achieved with standard mysqli connectors, but M2 is crashing whenever we attempt a new connection. I believe there are connection building tools within M2, but unable to find any docs or tutorials.
Answer: FishPig here. The tutorial on http://fishpig.co.uk/ is for M1 and is quite old (there are better ways connection to a DB on M1 than the tutorial says). Anyway, I've been trying to connect to an external DB while porting over Magento WordPress Integration to M2 so figured I'd post here what I have.
I'm not sure if this is the best way to do it but here's what I have that's working. Any feedback and improvements would be welcome!
<?php

namespace FishPig\SomeModule;

class App
{
    protected $connectionFactory = null;

    public function __construct(
      \Magento\Framework\App\ResourceConnection\ConnectionFactory $connectionFactory
    ) {
        $this->connectionFactory = $connectionFactory;

        $this->_initDb();
    }

    protected function _initDb()
    {
        $db = $this->connectionFactory->create(array(
            'host' => 'localhost',
            'dbname' => 'enter_your_db_name',
            'username' => 'enter_your_db_username',
            'password' => 'enter_your_db_password',
            'active' => '1',
        ));

        // Let's test the DB with a query

        $tableToTest = 'enter_your_table_name';

        $select = $db->select()
            ->from($tableToTest, '*');

        if ($results = $db->fetchAll($select)) {
            echo sprintf('
%s
', print_r($results, true));
        }
        else {
            echo 'The query was empty.';
        }
    }
}

This code uses DI to inject the \Magento\Framework\App\ResourceConnection\ConnectionFactory class. This works well because the class is a factory so doesn't instantiate the DB connection straight away. This allows you to gather the DB details and connect.
I should also point out that there are some values (DB details and DB table name for testing) that you will need to change for this code to work.
Comment: Could you add your di.xml too.
Comment: About custom connections https://magento.marcelhauri.ch/blog/magento2-custom-database-connection
Answer: Database connection settings and backend name are declared in app/etc/config.php which was earlier declared in local.xml
Comment: `app/etc/env.php`
Answer: 1) In app/etc/env.php add this code:
'custom' => array (
      'host' => 'localhost',
      'dbname' => 'second_db_name',
      'username' => 'db_username',
      'password' => 'db_password',
      'engine' => 'innodb',
      'initStatements' => 'SET NAMES utf8;',
      'active' => '1',
),

And
'custom' =>
     array(
        'connection' => 'custom'
     ),

Final env.php file look like this:
  'db' =>
  array (
    'table_prefix' => '',
    'connection' =>
    array (
      'default' =>
      array (
        'host' => 'localhost',
        'dbname' => 'first_db_name',
        'username' => 'db_username',
        'password' => 'db_password',
        'active' => '1',
      ),
       'custom' => array (
          'host' => 'localhost',
          'dbname' => 'second_db_name',
          'username' => 'db_username',
          'password' => 'db_password',
          'engine' => 'innodb',
          'initStatements' => 'SET NAMES utf8;',
          'active' => '1',
      ),
    ),
  ),
  'resource' =>
  array (
    'default_setup' =>
    array (
      'connection' => 'default',
    ),
     'custom' =>
    array(
      'connection' => 'custom'
    ),
  ),

2) Next step is to configure resource model to use new connection. The di.xml configuration file of module will help to set new resource name to resource model. In Vendor/Module/etc/di.xml add this code:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Vendor\Module\Model\ResourceModel\Module">
        <arguments>
           <argument name="connectionName" xsi:type="string">custom_setup</argument>
        </arguments>
    </type>
</config>

Comment: I certainly hope you are not using root for your database as well as having it as the password.
Comment: This is sample coding my friend. I have used root in only local server.
Comment: In custom array you can not use `'host' => 'localhost',` for remote connection.


time complexity analysis of recurrence relation

Question: I am not able to solve time complexity analysis of this recurrence relation: T(n)=3T(n/2)+n^2.I want to find time complexity analysis of this recurrence relation without using masters theorem could you please help me to do so.
Comment: Do you want to solve the recurrence or analyse the runtime of evaluating it? What have you tried and where did you get stuck?
Answer: Imagine your recurrence as a tree. It has a height of $log_2(n)$ since your input size $n$ is divided by $2$ every time.
The cost for a node on the $ith$-level is $(\frac{n}{2^i})^2$.
On the $ith$-level there are $3^i$ nodes.
The cost for that level (whithout considering the childnodes) ist therefore $3^i*(\frac{n}{2^i})^2$
The overall cost is the sum of the cost for each level that is $\sum_{i=0}^{log_2(n)} (3^i*(\frac{n}{2^i})^2) = \sum_{i=0}^{log_2(n)} (3^i*\frac{n^2}{2^{2i}}) = n^2*\sum_{i=0}^{log_2(n)} (\frac{3^i}{2^{2i}}) = n^2*\sum_{i=0}^{log_2(n)} (\frac{3^i}{4^{i}}) = n^2*\sum_{i=0}^{log_2(n)} (\frac{3}{4})^i$.
Which you can now solve with a formula for a geometric series that gives you $4n^2-3^{log_2(n)+1}$


Cannot Add Machine to ArcGIS Server Cluster

Question: After almost year of success, SQL database failed to register in ArcGIS Server.  Traced problem to secondary/failover server in cluster.  Deleted secondary server from cluster and database now registers fine.  Cannot add secondary machine back in.  set up that secondary machine as own server and can add database fine.  But cannot add to original setup.  Can run ArcGIS Server manager of original on secondary machine, but cannot log onto secondary ArcGIS Server manager from anywhere else (i.e. http://ip.address.machine2:6080/arcgis/manager/site.html) fails.  Can ping on network, log onto, etc.  ipconfig /all returns virtually identical results for each machine.  Ports look fine on each, no firewall.  Can telnet to primary, but not secondary - possible troubleshoot aid?
Comment: Very specific issues like this are best asked of Tech Support.  GIS SE is not intended to be a replacement for GIS vendors' normal tech support mechanisms.
Comment: What is the security setting on the server in order to add them they have to be `HTTP only` is there an error?  I'm with @Vince on this though.  There are a ton of great open source GIS server options that are as good if not better than ESRI.  What you are paying for is the support, take advantage of it to the fullest.  Answer your own question with the solution it is an interesting problem.
Answer: My suspicion is that the folder permissions for the configuration store have changed somehow, which is a notorious occurrence with AGIS SVR. Are you using domain service accounts? Is the config store on SVR1 or a shared network location? Make sure the service account that is running SVR1 and 2 (should be same) has the correct permissions to the config store.


Where is mesh debug to be found?

Question: I am working in blender 2.69 and have been following the Blender Tutorials DVD12 on Youtube --> https://www.youtube.com/watch?v=OaKYhO-XMFo
The video above refers to the "Mesh Debug" options in the properties pane. I know its only visible in edit mode but for some reason I can't see it on my version. i have also downloaded the latest version of Blender 2.76b and the mesh debug option is not visible there either. Any ideas how I can make this option show on my version?
Answer: It's in the (by default included but disabled) 3d print toolbox addon, but it changed the name, now is called "mesh analysis" in the 3d view properties panel (open with N)
Comment: Uh-oh. Mesh Analysis has disappeared from the Properties Panel. How do I get it back? Meanwhile I'll continue looking through the Q and A's.
Comment: Doh. Never mind. I was in a hurry to leave for the day. Sorry for the newbie mistake.

Where is mesh debug to be found?


MVC Controller - keeping methods small

Question: I'm reading uncle Bob's Clean Code and it completely revolutionizes my programming style. In this book author claims that best methods are small methods. What about controller's action methods in modern frameworks? Do you try to follow the "20 lines per method" rule, or you delegate some tasks to private methods?  I don't ask about things that you can move to services and external classes, sometimes there are situations that you cannot avoid bigger code in action. Another question and another look at this problem - do you tract controller class as (some sort of)  special class with only action methods,  or just another regular class with private methods and own fields along with action methods?
Comment: Rules are meant to be followed until you understand them well enough to break them, when it makes sense to do so.
Comment: I'd disagree with some of that. If an action has more than 20 lines it is almost certainly doing too much, and it is most likely implementing business logic. Consider moving the code mapping your business entities into your view models into separate methods, or even classes - that's the only thing that should be taking up any significant amount of line count.
Answer:
or just another regular class with private methods and own fields along with action methods?

Yes. It's just a class, i.e. keep methods small and refactor as needed into private sub-methods (or delegate to other classes, if appropriate).
Personally, 20 lines is a good upper limit, but I try for less. Occasionally, e.g. for complex algorithms with lots of state, you might go way over 20.

MVC Controller - keeping methods small


Old cord no red wire, new cord has a red wire

Question: We have 14/3 cord in our house. We bought a new 14/3 cord to connect it together from a outlet to a switched. The 14/3 that's already in our house does not have a red wire. The new one we bought has a red wire. How do we connect when the old one does not have  red wire?
Comment: Cord, or _cable_? Might help if you'd revise to explain what you're doing.
Comment: And what colors _does_ the existing 14/3 have?
Comment: It may be time to take a deep breath and start over. Please [edit] your question to explain your initial goal (adding a switched light by bringing power from an existing outlet?). Include a picture of the power source (the outlet?), then a diagram of the wiring scheme you're planning. Then ask your question for clarification, approval of the process, how to connect what to where, did you buy the right products, etc.
Comment: What does the old one have?  Usually can go with black to black, white to white, red to  colour.  An plain outlet usually does not need a xx/3 cable, nor does a plain switch.  More info on what you have is good to put in your question.
Comment: Sorry I meant cable the old cable has colors black, white and ground. The new cable has red, black, white and ground.
Comment: What I was trying to do was use the outlet wire that does not have a red wire connect it to a switch that I'm adding a light under the staircase. So I would need a red wire for the switch right?
Answer: This is a terminology issue. The industry standard nomenclature in the US for NM cable (e.g., Romex) excludes the ground wire (bare or green). In other words:

14/2 = Black + White + bare ground, 14 AWG
14/3 = Black + White + Red + bare ground, 14 AWG

You thought "black + white + ground = 3 wires" and based on printing on the jacket confirmed that it is 14 AWG, so you ordered 14/3. But what you actually have is 14/2.
The good news is you wasted a few $ but no harm done. It is perfectly fine to just ignore (or preferably, cap both ends of the red wire with wire nuts, so no loose bits of metal can touch anything). Or return it and buy 14/2. Or buy 14/2 and save this for the next time you wire up a switched circuit that needs the red wire.
There are a number of situations involving switches where you need 3 wires (besides ground). There are also some where you absolutely don't need that red wire (e.g., black & white from existing circuit to switch box, black connected to switch, white connected to white going to light, black going to light connected to the other side of the switch).
Comment: You can use black or red wire for the hot(not both in your case).  The one you don't use, use wire nuts on both ends.  It is common to use the black and nut the red, but either one can be use as the hot.  To prevent future confusion, should use the black only.  Red is use for types of circuits(three way switches) that you do not have right now
Comment: Thanks everyone it was very helpful!!
Comment: What I was trying to do was use the outlet cable that does not have a red wire to connect it to a switch. I'm trying to add a light fixture under the staircase and is the red wire needed for a switch?
Comment: Black and white connect to black and white at the existing outlet (pigtails or second set of screws), in switch box you have this cable and another black/white going to the light. In the box, whites together, blacks to the two screws on the switch. At the light, black to hot/line, white to neutral.


What is a difference between 'Operating System' and 'Command Shell'?

Question: What is a difference between 'Operating System' and 'Command Shell'?
Answer: A shell and an OS are different. Let me explain.
An operating system is a program initiated by either the BIOS or EFI. The OS controls the very low-level aspects of the hardware and provides APIs to software to use them. OSes are usually a collection of a kernel and a bunch of applications. Examples of OSes are Window$, Mac OS X, UNIX, Ubuntu, Solaris. Note that Linux is not an OS, but rather a kernel, which is the most important part of an OS.
A shell is an application that runs on the OS and provides the user interface to the OS. Examples of shells are bash, sh, cmd.exe and windowserver.app.
Usually an OS comes packed with one or more shells.
Comment: @magicyoung it doesn't have to be, but most user-oriented OSes have one. Examples that don't have a shell are microcontrollers, Wii Remote, computer diplays, cars and other embedded systems.
Answer: Actually shell is just like any program, which takes uses input (commands) and execute them.

ps aux | grep bash

will give you all the shell processes running on your computer (assuming you are using bash).
Check the code here for a simple implementation of a shell. You can compile it and run it. That will a new shell for you.


Bandwidth Monitoring for Linksys E4200

Question: I have a Linksys E4200 router with about 10 computers connecting to it. I'm looking for a way to monitor bandwidth usage in real time. I am willing to install custom firmware if it can get the job done. It seems bandwidth is leaking from the network but I suspect there are one or more users using more than their fair share and I'd like to find out exactly where it is going.
Comment: Try DD-WRT, OpenWRT, or Tomato; they all have better bandwidth logging, monitoring, and control than the stock firmware and all seem to support the E4200.
Comment: I've been looking into Tomato but I'm not sure if it offers bandwidth monitoring for individual clients or just general bandwidth usage over the whole network. I'm also having trouble finding up to date info on which version of the firmware is best with the E4200.
Comment: You might have to trawl through the forums. I spent quite a while figuring out how best to install DD-WRT on an E1000, and it ended up dying after a month just like lots of people said theirs did. Now I'm looking for a CA-42 cable to un-brick it. `:-(`
Answer: I have recently install Tomato on my E4200, version 1.28 by Shibby, you should definitely look at that, seems to run well.
http://tomato.groov.pl/?page_id=164
What you want are  K26RT-N, which supports 5Ghz as well.
Here's an even more direct link to latest (Build '101')
http://tomato.groov.pl/download/K26RT-N/build5x-101-EN/Linksys%20E4200/
You can get the AIO build, which gives you everything. I can pretty much guarantee it will meet your needs.
EDIT: I think these are for the V1 version of the router, not sure about the newer V2's.
Answer: You can download AdvancedTomato for E4200v1 from:
https://advancedtomato.com/downloads/router/e4200v1
Its essentially Shibby's mod with a more modern UI.
Couple of things:

You'll need to assign static IPs to all your clients.
IP traffic and Bandwidth monitoring are kept separate. You can enable one and not the other.
Its best to store your bandwidth logs and syslog on an external USB. You can define this under Custom Log File Path.
Keep in mind that enabling QoS will disable hardware acceleration.

Bandwidth Monitoring for Linksys E4200


Can't get Janino compiler to compile files in same directory as jar

Question: I'm using Janino to compile java files at runtime to use in a program. I'm using netbeans and I can only get it to compile at runtime when I put the directory in the src folder. If I try to compile it using relative paths It won't work.
I'm following the example at http://docs.codehaus.org/display/JANINO/Advanced#Advanced-compiler
Here's what works when i put the files to be compiled at runtime in a folder called scripts in the src directory:
        String engineClass = "DefaultEngine"; //name of engine class
        String guiClass = "DefaultGUI"; // name of gui class
        ClassLoader cl = new JavaSourceClassLoader(
                this.getClass().getClassLoader(),
                new File[]{new File("scripts")},
                (String) null,
                DebuggingInformation.NONE);
        AbstractEngine engine = (AbstractEngine) cl.loadClass(engineClass).newInstance();
        AbstractGUI gui = (AbstractGUI) cl.loadClass(guiClass).newInstance();

It doesn't work if I put the scripts folder in the same directory as the jar.
I can only get it to work when I run the project from inside the IDE with the scripts folder in the src directory.
When I try running the project using the scripts folder in the same folder as the jar file it gives a ClassNotFoundException on the
AbstractEngine engine = (AbstractEngine) cl.loadClass(engineClass).newInstance(); line
Answer: I figured it out. I had to put new File(System.getProperty("user.dir")+"/scripts") for the path


Data view for A/B Tests?

Question: I'm trying to export our Job data to a data warehouse and it'd be helpful to know which of the jobs we're exporting are associated with AB tests. I can definitely see that Marketing Cloud has some other view to associate Jobs with AB tests, but I haven't seen that data exposed in the documentation. Is this something that I can pull via Query, or do I have to rely on manual exports? Do I need to just put all AB Tests in their own tracking folder and filter by Category?
Answer: Not an exact solution but you can try this:
1- Please go to Tracking - Sends and tick A/B Test in the grid.

2- Then you can click on that column to see all A/B tests and please move them in a folder.

3- Now you can use this SQL to get all the jobIDs in this folder/category:
<code>SELECT j.JobID
FROM _Sent s
JOIN _Job j on s.JobID = j.JobID
WHERE j.Category = 'Folder Name'
</code>
Comment: I was afraid of that - thanks for sharing your workaround. I've requested that the Marketing Cloud product team expose this data view for us. Please vote for it here: https://success.salesforce.com/ideaView?id=0873A000000cRh3QAE

Data view for A/B Tests?


Android's Media Scanner: How do I remove files?

Question: I'm writing an app that removes files that may or may not be listed in any one of the types of media libraries such as music or pictures. While I can use the MediaScannerConnection.scanFile method to add files to the media library there doesn't seem to be any call to notify the service that the file has been removed. Sending it the path of the file that no longer exists doesn't result in the desired behavior either. How should I go about removing items from the library that no longer exist on the Android storage?
Answer: I was able to put a method together using bits and pieces from these two questions

What is the String 'volumeName' argument of MediaStore.Audio.Playlists.Members.getContentUri referring to?
How can I refresh MediaStore on Android?

Basically I just run a query on each one of the MediaStore types (Audio, Video and Images) selecting by path and deleting any records I find.
public static void RemoveAllForPaths(String[] paths, Context context)
{
    private static final String[] FIELDS = { MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.TITLE };
    if(paths == null || paths.length == 0) return;
    String select = "";
    for(String path : paths)
    {
        if(!select.equals("")) select += " OR ";
        select += MediaStore.MediaColumns.DATA + "=?";
    }

    Uri uri;
    Cursor ca;

    uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    ca = context.getContentResolver().query(uri, FIELDS, select, paths, null);
    for(ca.moveToFirst(); !ca.isAfterLast(); ca.moveToNext()){
        int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
        uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
        context.getContentResolver().delete(uri, null, null);
    }
    ca.close();

    // More of the same just setting the URI to Video and Images
}

I'm not entirely sure how safe this is to do but it's the only solution I've found so far and some initial testing seems to be working. I invite others to submit other answers if anyone has any further information on this approach or a better method for performing this functionality.
Comment: For path wildcards I added  `select += MediaStore.MediaColumns.DATA + "like ?";`  and appended `%` to my path string list.  This returned all the files in a specific folder
Answer: Easy as pie: whenever you add a file, let MediaStore ContentProvider knows about it using
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(fileToAddInMediaStore)));

For deletion: just use
getContentResolver().delete(Uri.fromFile(fileToDeleteFromMediaStore), null, null)

Comment: Have you tried your solution? I tried and this doesn't seem to work.
Comment: @Pascal Just tried your solution, and it works. Had to wait for my Nexus 7 to get the KitKat update.
Comment: yes, it works for me. The only flaw I saw was that when I removed a file, the mediaStore is notified and recreated an empty (0 byte) file on some device. don't know exactly why, but I deleted it afterwards.
Comment: As noted in http://stackoverflow.com/questions/15147536/how-to-trigger-mediascan-on-nexus-7 this will crash the app starting with Android 4.4.
Comment: @BerndS , I am using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE. The link you gave is talking about Intent.ACTION_MEDIA_MOUNTED. Did you actually tried my solution on 4.4?
Comment: @Pascal Sorry I thought you were talking about ACTION_MEDIA_MOUNTED. My bad.
Comment: So do you delete the file and then send the file path of the deleted file to the scan file? I have tried the command and am only able to add to the media library, not delete.
Comment: Check my earlier comment about file deletion
Answer: Answer of Spencer Ruport is right, but you don't need to query and open a cursor in order to delete.
So for one file that is music file the code is simple like that:
public void DeleteMP3FromMediaStore( Context context, String path )
{
    Uri rootUri = MediaStore.Audio.Media.getContentUriForPath( path );

    context.getContentResolver().delete( rootUri,
        MediaStore.MediaColumns.DATA + "=?", new String[]{ path } );
}

P.S. I wanted to comment answer of Spencer Ruport but don't have enough reputation yet.
Comment: A lot simpler and cleaner way. Thanks. I was able to use this for bulk delete too, by mentioning a relevant where clause.
Comment: Seems like the most proper, direct and safest way. I hope it works on all configurations.
Answer: The following works well for me. You can delete or add files using this.
MediaScannerConnection.scanFile(
                context,
                new String[]{fileToDelete, fileToAdd},
                null, null);

Comment: This will create zero byte files on some devices
Comment: media picker still shows the files as being there after deleting the file and then rescanning it
Answer: The available method is to remove the item from library.
This post is detailed expressed how to add into or remove from the Media Library.
http://androidyue.github.io/blog/2014/01/19/scan-media-files-in-android/  Hopes this could help you.
Comment: Hi, I like your post on github, but I can't seem to get the "Remove From Media Library" to work. I move files from the sdcard/Tumblr folder programatically (as I like them stored on the memory card instead of internal storage). When I do this, I need to update mediastore to let it know the image is "deleted" from the internal storage Tumblr folder. But, no matter what I do with your code, I can't get it to work. 2 question: (1) How do I specify the path for Tumblr in internal storage, (2) do i use EXTERNAL_CONTENT_URI or INTERNAL_CONTENT_URI. Thank you in advance.


Do campaign contributions create a conflict of interest for politicians?

Question: My understanding of politics in the US is that a large portion of campaign funds come from different lobbying groups and special interests. Does this create a conflict of interest for politicians beholden to their campaign contributors in addition to their constituents? What are the pros and cons of this system as compared to an alternative system where candidates are limited to using public resources adequate to run their campaign?
Comment: How is it not self-evident?
Answer: Among other pros of raising private donations:

Overall, political advertising costs money (a LOT) since it not only has to compete with other political advertising but with all the NON-political ads out there. This inflates the prices of advertising to the point that no publicaly funded candidate can afford to advertise. Which in turn gives an incumbent a 100% guarantee of re-election, which is obviously bad for democracy. With no incumbent, the edge goes to a celebrity, or someone beloved by the media.
In other words, "adequate to run their campaign" is not something we have enough public money to spend on, for any definition of "adequate".
A candidate that is opposed by the 4th branch of government (media) has ZERO chance of getting their voice out without raising a substantial amount of money. Leaving aside the sure-to-generate-debate issue of whether MSM in America is liberal (but if you care, look who major newspapers editorial opinions endorsed recently), the proof is in the pudding: Media-organized debates have uniformly excluded less "major" candidates of all political persuasions.

As far as the cons,  "beholden to their campaign contributors" is a nice phrase to use around the coctail table, but there needs to be some research to show that it is actually true.
FiveThirtyEight ran a post last year that raising spending on ads in a non-edge case (e.g. when both candidates are already somewhat known) by 100% merely adds 1% margin to the vote. And for any campaign other than national Prez election, advertising is the biggest expenditure (for Prez, get out the vote operations and organizing take money too).
Comment: you should source the FiveThirtyEight 1% margin with doubling advertising. I know that I linked to a Freakanomics source in one of my other answers.
Comment: @user1873 - I read it on RSS feed and it's behind a paywall, so I'm not sure how to find it again.
Comment: I'm not sure that answers the question. It doesn't say whether or not politicians' policy decisions are actually influenced by who their donors are.
Comment: @Avi - it's a LOT more complicated than that. Policy decisions are influenced by wanting to win. Whether donors determine who wins is complicated. Do coal state politicians support pro coal policies because coal companies donate? Or rather because coal jobs lost belong to their voters?
Comment: @DVK I know you posed those questions rhetorically, but I think those are the questions you have to answer before you've answered OP's question. He can clarify if I'm misinterpreting, of course.
Comment: I am indeed asking whether a politician who accepts money from a private individual or lobbying group will generally be influenced to advance their agenda vs that of the voters or platform on which the politician campaigned.


Can dreams predict the future?

Question: On Quora there is a discussion that dreams can predict the future. I have experienced the feeling that things happening to me in real-life had occurred in my dreams, before these events actually happened. Can dreams predict the future?
Comment: Related https://psychology.stackexchange.com/q/20639
Answer: Short answer
Dreams cannot predict the future.
Background
Likely you are referring to Deja reve ('already dreamed'), which has been hypothesized to be (Schredi et al., 2017):

...the distinct impression that the uncanny familiarity one is
  sensing has come from a preceding dream, but one not usually
  remembered until the experience is taking place.

Deja reve are reported by Schredi et al. to occur in nearly 80% of the population.
Dreams are representations of past experiences (re-)generated is our minds creates while we sleep. It has been proposed that dreams reflect biological processes of long-term memory consolidation. Consolidation strengthens the neural representations of recent events (i.e., their memories) and embeds these new memory fragments into older, existing memories. This also maintains the stability of existing memory representations in the face of subsequent experiences (Payne & Nadel, 2004). In sleeping rodents, for example, neurons in the hippocampus fire in patterns remarkably similar to those recorded during a previous maze-running session—almost as if the animals replay the experience in their sleep (source: Science Magazine).
In all, dreams are related to memories and memory formation. However, they have nothing to do with future events. The brain cannot recall what never has perceived in the past. Hence, déjà vu experiences and dreams have nothing to do with what the future may bring, other than cases of pure coincidence.
References
- Payne & Nadel, Learn Mem (2004); 11(6): 671–8
- Shredi et al., J Consciousness Studies (2017); 24:(7-8): 155-62
Comment: @FrankHubeny That type of Bayesian 'predicting the future' is certainly not the type that the linked discussion on quora is referencing.
Comment: We are able to predict the future when we are awake. I don't see why dreams cannot act as predictions. When we are awake it is also all memory projected as a trend into the future. I would think this answer implies we cannot predict the future when we are awake either. And yet we do within reasonable accuracy.

Can dreams predict the future?


How can I use browser userscripts on my Android phone?

Question: I am a passionate Stack Exchange user and I have a lot of userscripts in my desktop Chrome browser, installed with Tampermonkey. I want to use them on my Android phone, is it possible?
Comment: Related: https://android.stackexchange.com/questions/242847/how-can-i-install-greasemonkey-tampermonkey-or-similar-in-firefox-android
Comment: Also related: https://android.stackexchange.com/questions/229969/how-can-i-use-userscripts-on-firefox-for-android
Answer: Google Chrome on Android so far doesn't support plugins, of which Tampermonkey is necessary to run userscripts, so here I recommend Firefox for Android. You can install Tampermonkey addon in Firefox and then start with your favorite scripts. Note that all userscripts are not compatible with Tampermonkey such as  SE-AutoReviewComments for which you need
USI- Unified Script Injector addon.
Where can I find scripts to play with?
Stack Apps is a Q&A site for apps, scripts, and development with the Stack Exchange API. People discuss about developing around SE, and publish their projects there. You can find a lot of userscripts in the scripts section.
One of my scripts isn't working
beeshyams asked me this question before, but I wasn't a Firefox user then, so I installed Firefox fresh and installed that userscript, and found nothing wrong.
When you encounter some issues with userscripts, try removing and reinstalling them, as well as clearing/resetting your Firefox addon, and see if the issue resolves by itself. Usually this solves 99% of them.
Comment: There's also [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/) which is the original such add-on for Firefox.
Comment: Firefox doesn't let any other add-on be installed other than those recommended ones.
Comment: FF 81 (mobile) has disabled the TamperMonkey addon (it's listed as "Not Yet Available"). Apparently it's [in the pipeline](https://github.com/Tampermonkey/tampermonkey/issues/940)
Answer: Tampermonkey or any other userscript manager can no longer be added to Firefox as of writing this answer. It was never even possible with Chrome. However, You can instead install actively maintained android firefox fork iceraven that supports extensions like tampermonkey, greasemonkey etc.
Answer: The situation changes all the time, I was using Firefox 68 for that but later versions drop add-on support. And using old version 68 is not very safe.
But hopefully Kiwi Browser took the relay of Firefox for browsing with userscripts on Android:
Since 2021 or so, I've been using for months without problems tons of userscripts with Violentmonkey (open source) and many userstyles with Stylus with Kiwi Browser!
It can install and run also other extensions from the Chrome Store.
Answer: It is possible with the help of Xposed framework.
I am the author of ChromeXt which adds support of UserScripts to Android Chrome:
https://github.com/JingMatrix/ChromeXt.


Summarizing several percentages of uneven size samples

Question: We are comparing the prevalence of a trait across 40 depth bins in the ocean. The notable part is that the percentage of organisms with this trait is nearly the same (80%) across all depth bins, despite different total counts and diversity of entities.
My question is how to summarize these percentages and show the low variability of this value across the depths. We are not as interested in a multiple comparison / null hypothesis test, as I have found those.
 It feels wrong to average and derive standard deviation for percentages. The total count of data points is around 480k, but N can be a couple orders of magnitude different between bins, so the ratio we are comparing could be 8/10 or 8000/10000.
Answer: You could view this as a meta-analysis problem. Each bin gives you an estimate of the prevalence (which you might want to transform) and its standard error. Using the standard inverse variance procedure for meta-analysis you would then get an overall estimate and also an estimate of its heterogeneity. You might be interested in the CRAN Task View on MetaAnalysis for some hints. I use metafor but your mileage may vary.
I have added the meta-analysis tag, feel free to edit it out if you disagree.


Use of the term illegal to describe a person

Question: A respected newspaper reporter advised me today that journalists use the term undocumented immigrant instead of illegal alien to refer to someone living in the country illegally simply because a person can not be illegal. However, most deem the term undocumented immigrant to be merely an euphemism. According to his rationale "[a] person can't, under [by] the definition, be illegal. Only an object or action can be described as such." This surprised me especially because the term "illegal alien" so widely used in the press and even by the Internal Revenue Service. What is the appropriate English term for a someone living in the country illegally?
Comment: It feels like this is a question about politics, not language.
Comment: There has recently been a political effort in the United States to make the term "illegal immigrant" unacceptable in polite civil discourse. Though it is still an active area of controversy, with a fair number of "die-hards" that have sworn on principle to never stop using the term, it should be noted that on the whole the campaign has been largely effective in its aims, with many mainstream journalists now preferring the "undocumented" modifier.
Answer: Illegal immigrant is a correct expression, the issue apprears  to be one of legal definition especially in the United States:

noun [ C ] UK  /ɪˌliː.ɡəl ˈɪm.ɪ.ɡrənt/ US  /ɪˌliː.ɡəl ˈɪm.ɪ.ɡrənt/ us also illegal alien:

someone who lives or works in another country when they do not have the legal right to do this

Ngram: illegal immigrant, illegal alien, undocumented immigrant.
I agree that "undocumented immigrant" sounds like an euphemism for "illegal immigrant" which still is the more common expression.
Undocumented (AmE):

not having any documents to prove that someone or something is legal:
  undocumented immigrants/aliens/workers'

(Cambridge Dictionary)
There is a debate in the US about the usage of the term illegal referring to immigrants:
Immigration Debate: The Problem with the Word Illegal:

describing an immigrant as illegal is legally inaccurate. Being in the U.S. without proper documents is a civil offense, not a criminal one.  (Underscoring this reality, Justice Anthony Kennedy wrote for the majority opinion on SB 1070, Arizona's controversial immigration law: "As a general rule, it is not a crime for a movable alien to remain in the United States.")
In a country that believes in due process of the law, calling an immigrant illegal is akin to calling a defendant awaiting trial a criminal.  The term illegal is also imprecise. For many undocumented people — there are 11 million in the U.S. and most have immediate family members who are American citizens, either by birth or naturalization — their immigration status is fluid and, depending on individual circumstances, can be adjusted.

(TIME)
Comment: These are helpful points to bring up, but as "Illegal" can refer to violations of civil law, I'm not sure the "legally inaccurate" is quite correct. I've asked at https://law.stackexchange.com/questions/37567/equivalent-of-illegal-for-violating-civil-law for any adjectives which *do* apply to crossing borders contrary to administrative/civil law.
Comment: And as a correction--crossing borders without approval is contrary to criminal law; it is apparently just that but some "illegal immigrants" might not have crossed illegally (by overstaying a legitimate visa) or by a statute of limitations on their initial crime having passed. It seems the court ruling was in reference to *remaining* in the United States--not those who crossed illegally (within the last 5 years).
Answer: The difference between undocumented immigrant and illegal immigrant extends to other circumstances.
For example, when people overstay a tourist visa, they did not immigrate illegally and are not illegal immigrants. When they earn money by working while on a student visa, they did not immigrate illegally and are not illegal immigrants.
Center for Migration Studies :

"the total undocumented population in the United States has declined gradually over the past few years ... 482,781 "Suspected In-Country Overstays" ... individuals who remained in the United States beyond their period of admission ..."
Comment: "For example, when people overstay a tourist visa, they did not immigrate illegally and are not illegal immigrants." I think many would argue they immigrated by overstaying, and the manner by which they immigrated (by overstaying) is illegal; thus they immigrated illegally.
Comment: @user102008 indeed, as I suspect you know, one whose nonimmigrant status in the US has lapsed is an immigrant under the statutory definition of immigrant found at [8 USC 1101(a)(15)](https://www.law.cornell.edu/uscode/text/8/1101#a_15).
Comment: If you're gonna bring up a couple rare cases of the phrase, you can't leave out the cases that make up 98% of the usage. Very very rarely will someone use "illegal immigrant" to describe someone overstaying their visa, despite it technically being accurate. They are an immigrant, and they are illegally staying in the country. Can you site an example of someone using it in this manner?


Parsing unsupported date formats in via Cocoa's NSDate

Question: With the Cocoa framework how can I parse @"2008-12-29T00:27:42-08:00" into an NSDate object? The standard -dateWithString: doesn't like it.
Answer: You can use NSDateFormatter to parse dates:
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    date = [dateFormatter dateFromString:dateStr];

The unicode date format patterns defines the format string you can use with the setDateFormat: method.
Note that if you're targeting 10.4 then you need to call: [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];. Not needed for iphone, or leopard as this mode is the default there.
Comment: I can't get this to work for strings formatted like the example in the question, which loosely seems to be RFC 3339 format, but with a colon in the timezone offset (ending in -08:00). The Unicode technical standard you linked at draft #4 is now up to draft #10, and the treatment of Z has changed a little -- it's now accepted up to 4 times and there's a new Appendix J -- but in no case does it accept the "-08:00" format. "GMT-08:00", yes, and "-0800", yes, but not with the colon and without GMT. I needed to parse a date like that and in desperation ended up ripping out the colon before parsing.
Comment: This will produce wrong result if the user has AM/PM set on his iPhone - AM/PM marker will get added. Also, if the user is using Japanese Imperial calendar this will get you the year in that calendar, not in Gregorian calendar. To get this right you need to explicitly set the locale and calendar on the date formatter.
Comment: I couldn't get this to work unless I quoted the Z as well like so

[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
Comment: +1 for adding unicode date format patterns link. Been looking for something like that for a while.
Comment: @metamatt I am stuck on the same issue. wish i had seen this post before, would have saved close to an hour :( Did u manage to find a better solution in the end than ripping off the colon?
Comment: @shyam No, I moved on, and left that hacky solution in place.
Answer: If you only need to handle the ISO 8601 format (of which that string is an example), you might try my ISO 8601 parser and unparser.
Comment: Maybe if the code were licensed with MIT or Apache 2.0.  BSD sucks for use with iPhone apps because of the attribution clause, since most apps don't actually distribute documentation with the binary.
Answer: Actually, you need to set timezone, calendar and locale. If you don't set locale, an user has AM/PM time enabled the formatter will add AM/PM marker! If you don't set the timezone, it will use the current timezone, but will mark it as "Z" ("Zulu" or GMT). If you do not set calendar, users with Japanese Imperial calendar will have number of years since current Emperor's ascension instead of the number of years since Jesus Christ was born. Be sure to test in all of the scenarios I mentioned!
    NSDateFormatter * f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    f.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    f.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    f.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
    NSString * str = [f stringFromDate:someDate];
    NSDate * date = [f dateFromString:dateStr];

Answer: How the time zone is set changed from ios 5 to ios 6. iOS 6 supports the format +01:00 using ZZZZZ but ios 5 doesn't. I solved this issue with this solution which worked for me to parse a date with the following format in ios 5 and 6.
2013-05-07T00:00:00+01:00
NSMutableString *newDate = [date mutableCopy];
NSRange range;
range.location = 22;
range.length = 1;
[newDate replaceCharactersInRange:range withString:@""];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:newDate];


Can we get a rental car from near Edinburgh's Waverly station?

Question: We are traveling by train from London to Edinburgh's Waverly station. We need to get a rental car once we arrive. Can we arrange for a rental car company to pick us up at the station? Or is there a shuttle or something similar that we can take?
Comment: Oops. We just found the rental car company on the map and it's very close to the station. We can easily walk. Sorry.
Comment: If you've found an answer, post it as an answer below; it may help future travellers with the same question (the more detailed you can make your answer, the better).
Answer: The car hire company Enterprize offer a service called "we'll pick you up" - if you call the local office after you book they will pick you up in a car off their and drive you to their office. Other companies may have offices close to the station.
Answer: Europcar has an office in the station. I think they use the New Street car park a couple of minute's walk away.


Justification for acoustic wave equation boundary conditions

Question: In analyzing the standing acoustic waves produced by a wind instrument, one usually assumes that the openings of the instrument are antinodes of the acoustic wave (as depicted below).  What is the justification for this boundary condition?
Answer: Before I answer the question, first some explanation about what the graph shows. There are generally two ways to graphically depict a one dimensional pressure wave.
One is by showing how the pressure is distributed over space. When a standing wave is depicted in this way, the antinodes indicate large pressure variations while the nodes indicate a constant pressure.
The second method is by showing the local displacement of the air from it's rest position. When a standing wave is depicted in this way, the antinodes indicate large displacement variations while the nodes indicate a spot where the air almost stands still.
At positions where the pressure has an antinode, the displacement has an node and the other way around.
The graph you give uses the second method and shows the displacement of the air. You can see that there is a node at the end of the tube, because the air there does not move.
Now about the hole. The (very rough) assumption that is made in this model is that the hole creates a connection to the environment, thereby reducing the pressure to zero at that point. This will thus lead to a node in a pressure graph and a antinode in a displacement graph.
This assumption is perfectly fine to get a feeling of how a flute works, but, as Alephzero's explains, is far from the complete story.
Answer: This is a very over-simplified approximation which doesn't explain the finger-hole positions on a simple instrument like a recorder or penny whistle.
The justification, so far as it goes, is that making a hole in the side of the tube is equivalent to cutting off the part of the tube below the hole. That is not really true, unless the "hole" was a slot that extended around the full circumference of the tube.
A relatively small hole, as in most real wind instruments, acts more like the opening of a Helmholtz resonator. The actual wave pattern is three-dimensional, not a simplified one-dimensional approximation to the waves in a pipe. For example, the resonant frequency of the instrument depends on the diameter of the hole, as well as on its position along the length of the pipe. One way to make fine adjustments to the intonation of an instrument is to change the diameter of the holes - for example by applying a thin coat of varnish to reduce the hole diameter slightly.
To get an accurate prediction of the acoustics of the instrument, you also need to take account for the finite impedance of the air outside the hole. That has an effect which is similar to the "end correction" to the resonant frequencies of a simple open or closed pipe.
A useful and fairly accurate acoustic model would therefore consist of a branching network of pipes, where each "hole" is modeled as a short pipe, including its diameter, length (i.e. the thickness of the instrument where the hole is drilled through it), and its own end correction factor - including the "shading" effects of a mechanical key mechanism that partial covers the hole when it is "open", or the same thing done by the player's fingers.
Note that even when the finger hole is "closed", there is still a closed-off cavity in the wall of the instrument, which modifies the pitch compared with a simple "one-dimensional wave in a pipe" model.