Circle crop image with transparent background - Android

Question: I'm trying to do what is described here "I want to crop a circular region from this bitmap. All pixels outside the circle should be transparent."
I already trying what's in that post but all of them don't offer the transparent background, only a circle image, I tried the below and it didn't work, any ideas?
<code>public Bitmap getCroppedCircleImage(Bitmap bmp, View view) {
    Bitmap bitmap = getCroppedImage(bmp, view);

    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff227722;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);

    //canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    Paint paint1 = new Paint();
    paint1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    Rect rectTransparent=new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    canvas.drawRect(rectTransparent,paint1);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    //Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
    //return _bmp;
     OutputStream stream = null;
    try {
        stream = new FileOutputStream("/sdcard/test.png");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    try {
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return output;
}
</code>
Comment: Use Picasso and a circle transformation https://gist.github.com/julianshen/5829333
Answer: You can use this library to achieve your goal
https://github.com/hdodenhof/CircleImageView


Why is infinite loop needed when using threading and a queue in Python

Question: I'm trying to understand how to use threading and I came across this nice example at http://www.ibm.com/developerworks/aix/library/au-threadingpython/
      #!/usr/bin/env python
      import Queue
      import threading
      import urllib2
      import time

      hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
      "http://ibm.com", "http://apple.com"]

      queue = Queue.Queue()

      class ThreadUrl(threading.Thread):
      """Threaded Url Grab"""
        def __init__(self, queue):
          threading.Thread.__init__(self)
          self.queue = queue

        def run(self):
          while True:
            #grabs host from queue
            host = self.queue.get()

            #grabs urls of hosts and prints first 1024 bytes of page
            url = urllib2.urlopen(host)
            print url.read(1024)

            #signals to queue job is done
            self.queue.task_done()

      start = time.time()
      def main():

        #spawn a pool of threads, and pass them queue instance
        for i in range(5):
          t = ThreadUrl(queue)
          t.setDaemon(True)
          t.start()

       #populate queue with data
          for host in hosts:
            queue.put(host)

       #wait on the queue until everything has been processed
       queue.join()

      main()
      print "Elapsed Time: %s" % (time.time() - start)

The part I don't understand is why the run method has an infinite loop:
        def run(self):
          while True:
            ... etc ...

Just for laughs I ran the program without the loop and it looks like it runs fine!
So can someone explain why this loop is needed?
Also how is the loop exited as there is no break statement?
Comment: The loop isn't exited until the thread stops.
Comment: Who says it's *needed*? It's not. It's just what this program wants, though. I suspect your question is: Why doesn't this program *get stuck* in an infinite loop?
Comment: I don't think the program "ran fine" without some kind of loop because it would only process at most one of the host urls.
Answer: Do you want the thread to perform more than one job?  If not, you don't need the loop.  If so, you need something that's going to make it do that.  A loop is a common solution.  Your sample data contains five job, and the program starts five threads.  So you don't need any thread to do more than one job here.  Try adding one more URL to your workload, though, and see what changes.
Answer: The loop is required as without it each worker thread terminates as soon as it completes its first task. What you want is to have the worker take another task when it finishes.
In the code above, you create 5 worker threads, which just happens to be sufficient to cover the 5 URL's you are working with. If you had >5 URL's you would find only the first 5 were processed.


Subfloor repair for LVP installation

Question: I'm preparing to install luxury vinyl plank in the living area of the second floor condo I just bought (carpet was installed previously). It's a woodframe condo with a wooden subfloor built in 1985, and there are several places where there are drops and dips in the subfloor. I'm trying to figure out what level of "level" I need to bring the subfloor to and what's the best way to do it. I'm hoping to DIY but understand I may need to hire a professional if it's bad enough.
I'm attaching a photo with a map of the problem areas. The worst is near the entrance to the room where there's a drop of roughly 1" over 4 feet, which from my understanding is quite substantial. The second biggest issue is a local low spot in the middle of the room.
I have had both Henry 549 "feather finish" recommended for filling in the low spots, or self leveling underlayment. Also gotten some recommendations for 1/4 plywood all around to even things out. The low spot in the middle of the room seems like a very straightforward fix with the Henry's 549, but I'm wondering if that 1" drop is over my head.
So far I've had 3 contractors take a look, and every one said that this is the nature of the beast with wood-frame construction and that they wouldn't recommend doing too much since the building will continue to shift over time.  They all said everything seemed to be structurally sound (I even took one to the unit below and confirmed that the ceiling looks normal there), so I should only repair to the extent necessary for the LVP install.
I'm wondering if it would it make sense to fill in the local low spot (and other more minor low spots) with Henry's 549 patch, and then add some 1/4" plywood everywhere except for the area marked high, up until say a couple feet out from the drop, then ramp up to the high area using the 549, so that the incline is less extreme? Or if anyone has other suggestions for how to approach this they would be quite welcome!  One of the contractors also mentioned using the underlayment that you roll out, but the installation instructions for my LVP mentioned only "APA rated" underlayment which I think is just the plywood.
Thank you!!
Comment: Do not settle for anything other than the APA plywood underlayment as required by the flooring company. APA Underlayment has 1) inner plys are plugged, 2) exposed surface (the surface facing up) is touched sanded so there are no rough edges where plys lap, 3) top exposed surface has all spaces between plys are patched solid, 4) follow installation instructions, including having edges over joists, etc. Also, each sheet of plywood should have a grade stamp so you can see it is "Underlayment" grade... not Grade A, or anything else.
Answer: Professional flooring installers would flood from the high point to the low point with self level.  They typically charge per bag and I've seen this kind of job cost 15k when done for more than one level of a house.  You can do as you suggest a hybrid approach.  Installers won't typically go that route because it is a lot more labor and requires a lot more expertise and judgement calls.  They want a fool proof and easy way to get the floor flat and there is more room to go wrong when making judgement calls.
Note you are going for flat not level.  Typically your finished floor material will say 1/8" over 10' or something like that.  To see how bad your floor is you take a 10' straight edge and move it around the room, then I sometimes use horseshoe shims (these come in 1/16 - 1" thick) and see which size will fit under any gaps that are visible under the straight edge.
Some things to keep in mind.  You can go outside the 1/8" over 10' if you can tolerate being able to detect bounce in your floor - I am assuming you are going for floating install.  It is worth also thinking about what section of the floors are being used for.  You'll notice out of flat more if this is a walking area than if this is under furniture.
I've done the hybrid method before.  If you put plywood down first to build up the 1" and then try to use SLC to feather out to the plywood you end up having a join between the edge of the plywood and the SLC and this edge is likely to crack.  If you just pour the SLC then there is no sharp edge transition.  You can mitigate the transition with different techniques.  This is why SLC is typically the one stop solution.
I hadn't heard of Henry 549 - it is interesting that it is a cement based SLC but doesn't require a primer over plywood.  Mapei and Sika both require a primer.
If you are doing the work yourself at $20-30 a bag you probably aren't much ahead using the plywood - labor is probably worse for the plywood with the cutting screwing and gluing but if you aren't investing in the SLC tools (spiked roller, squeegee, trowels, spike shoes, etc) then might be easier if you already have the carpentry tools.
If you are going the plywood layer method then filling in the large dip with SLC first makes a lot of sense.  The issue you run into is how do you adhere the plywood over the SLC.  I've screwed through it before and it can crack.  If it cracks and the pieces are able to move around then you can end up with noise when you walk on it.  Probably the best approach is to use construction adhesive on that section but you'll need to put a substantial weight on the plywood to ensure it pushed out any air.  Construction adhesive also can tend to be thick so it can end up pushing the plywood out of level especially if you aren't screwing it down (this is harder the thicker the plywood is.  You could trowel the adhesive onto the plywood much the way tiles are trowels do the ridges collapse and the air is able to escape.   Probably better to go with a glue used for glue down installs and use that to bond the plywood to the SLC over the area.  Hopefully the dip isn't huge - hard to tell how large the area of the dip is.
I'd expect any settlement to be finished.  If your joists are undersized and you have crazy amounts of movement in the floor it is possible the SLC would delaminate from the plywood overtime.  If you are installing with an underlay then I wouldn't expect a problem if it cracks but the floor is flat then any cracked piece won't have anywhere to move.  The underlay would further suppress noise of it between the finished floor and either the intact SLC or the subfloor.  Professional floor installers use SLC on super high end homes, if there were a tendency for it to breakdown overtime they wouldn't use it or there would be crazy amounts of lawsuits.  The henry 549 has a max lift of 1/2" so you'll need two lifts.  The other thing to watch is that this product doesn't require a primer and the plywood is going to suck the moisture out of it.  Sika and Mapei require primers (on plywood it is a latex primer) which prevent moisture from being sucked out of the mix.  I'd go for cold water for extra work time and you probably want to prewet your plywood.   Both mapei and sika have SLCs that can be feathered.
Comment: Thanks so much @FreshCodemonger!  The transition between plywood/SLC was something I wondered about.  I can def see the advantage of SLC being a one stop solution.  Another thing I wondered about with the plywood is whether I would need to fill in the large dip first (with SLC or something) before laying the plywood - ie it seems I wouldn't want say a large .5" space between the plywood and the subfloor below in that spot.  Is it typical to fill these in first to avoid that?  Thanks again!!
Comment: thanks for the additional info!!!  I'm leaning towards the pure SLC solution now, probably with Henry 549 since Henry is recommended in the installation instructions, and the 549 is designed for feathered edges like I'll have where I ramp up to the high spot (where other SLCs I've seen say they need a min thickness ~1/8").  One last question - one contractor seemed to suggest that over time the SLC might "break down" due to the building settling and weight from foot traffic (if I understood him correctly) - is that something you've seen?

Subfloor repair for LVP installation


HP EliteDesk 800 cannot see USB3 drives

Question: I have an HP EliteDesk 800 GM D1 mini box where I have (repeatedly) installed Ubuntu 22.04.1 and 22.04.3 (both fresh and fully updated) on its internal SSD.  In all cases the USB3 ports fail to recognize USB3 drives.  I have swapped this internal SSD with an SSD (Ubu 22.04.3) from a Lenovo W500 lappy and the USB issue stays with the HP box (all drives automount in the Lenovo box).
To eliminate the ports as culprits, which were working fine with the previous Ubuntu (16.04), I tried several different drives attached to each of the ports (the same ports supporting this USB3 keyboard and mouse and the USB3 hub connecting them).  The results were a bit confusing.
Only two drives were able to automount; both Kingston USB2 drives each formatted as an installer (Ubuntu 22.04.1 and ProxMox).  The other drives (USB3 WD with EXT4 and UDF, USB3 thumbs with FAT32 and UDF, a memory card with FAT32 (USB3 card reader)) all failed to mount.  Further, tools like lsusb, lsblk, blkid, Disks, and GParted show no attached anything for these failures.  Finally, dmesg shows no entries surrounding the attaching and detaching of any of these failures, and journalctl shows no activity for them either.
I took one of the USB3 thumbs with UDF and created an Ubu 22.04.3 installer.  It remained unrecognized.  I then took the USB2 Ubu 22.04.1 installer (these installers are all ISO9660) and created that as 22.04.3.  This automounted.
Edit 2:  Looks like the drives which function are USB2 while those that fail are trying to run over USB3.  However, USB3 hubs work as expected; I can even attached the USB2 installer and it automounts via the USB3 hub.
The below output is with a Kingston USB2 installer (22.04.3) and a WD USB3 EXT4 attached.
<code>$ sudo lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
loop0    7:0    0     4K  1 loop /snap/bare/5
loop1    7:1    0    62M  1 loop /snap/core20/1587
loop2    7:2    0  63.5M  1 loop /snap/core20/2015
loop3    7:3    0  73.9M  1 loop /snap/core22/864
loop4    7:4    0 163.3M  1 loop /snap/firefox/1635
loop5    7:5    0 236.9M  1 loop /snap/firefox/3131
loop6    7:6    0 400.8M  1 loop /snap/gnome-3-38-2004/112
loop7    7:7    0 349.7M  1 loop /snap/gnome-3-38-2004/143
loop8    7:8    0 485.5M  1 loop /snap/gnome-42-2204/126
loop9    7:9    0 496.9M  1 loop /snap/gnome-42-2204/132
loop10   7:10   0  91.7M  1 loop /snap/gtk-common-themes/1535
loop11   7:11   0  45.9M  1 loop /snap/snap-store/582
loop12   7:12   0  12.3M  1 loop /snap/snap-store/959
loop13   7:13   0  40.8M  1 loop /snap/snapd/20092
loop14   7:14   0   284K  1 loop /snap/snapd-desktop-integration/14
loop15   7:15   0   452K  1 loop /snap/snapd-desktop-integration/83
sda      8:0    0 119.2G  0 disk
├─sda1   8:1    0   512M  0 part /boot/efi
└─sda2   8:2    0 118.7G  0 part /var/snap/firefox/common/host-hunspell
                                 /
sdb      8:16   1  14.5G  0 disk
├─sdb1   8:17   1   4.7G  0 part /media/X/Ubuntu 22.04.3 LTS amd64
├─sdb2   8:18   1   4.9M  0 part
└─sdb3   8:19   1   300K  0 part

$ sudo blkid
/dev/sda2: UUID="87549ab1-a5e5-4de2-ba03-d7379bd2107d" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="80e7635e-d96e-4b12-af65-6eb1cbddcbdb"
/dev/loop1: TYPE="squashfs"
/dev/loop8: TYPE="squashfs"
/dev/sdb2: SEC_TYPE="msdos" LABEL_FATBOOT="ESP" LABEL="ESP" UUID="F7DB-4D56" BLOCK_SIZE="512" TYPE="vfat" PARTLABEL="Appended2" PARTUUID="f45e2fa1-c5a6-4d79-876d-c8245af921e0"
/dev/sdb3: PARTLABEL="Gap1" PARTUUID="f45e2fa1-c5a6-4d79-876c-c8245af921e0"
/dev/sdb1: BLOCK_SIZE="2048" UUID="2023-08-08-01-19-05-00" LABEL="Ubuntu 22.04.3 LTS amd64" TYPE="iso9660" PARTLABEL="ISO9660" PARTUUID="f45e2fa1-c5a6-4d79-876e-c8245af921e0"
/dev/loop15: TYPE="squashfs"
/dev/loop6: TYPE="squashfs"
/dev/loop13: TYPE="squashfs"
/dev/loop4: TYPE="squashfs"
/dev/loop11: TYPE="squashfs"
/dev/loop2: TYPE="squashfs"
/dev/loop0: TYPE="squashfs"
/dev/loop9: TYPE="squashfs"
/dev/loop7: TYPE="squashfs"
/dev/sda1: UUID="665D-3D08" BLOCK_SIZE="512" TYPE="vfat" PARTLABEL="EFI System Partition" PARTUUID="26c459fa-c12f-4bd2-b634-742e3371f6a4"
/dev/loop14: TYPE="squashfs"
/dev/loop5: TYPE="squashfs"
/dev/loop12: TYPE="squashfs"
/dev/loop3: TYPE="squashfs"
/dev/loop10: TYPE="squashfs"

$ sudo lsusb
Bus 001 Device 009: ID 0930:6544 Toshiba Corp. TransMemory-Mini / Kingston DataTraveler 2.0 Stick
Bus 001 Device 002: ID 8087:8000 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 002: ID 8087:8008 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
</code>
This output does not change with or without the WD USB3 EXT4 drive attached:
<code>$ ls -l /dev/* | wc -l
514
</code>
(With the Kingston USB2 attached it raises to 528.)
What is the next step to unpack or solve this mystery?
Edit:  Requested in comments (@waltinator).
<code>$ sudo journalctl  --follow
Sep 23 23:34:48 MYMACHINE kernel: usb 1-1.5.4: USB disconnect, device number 27
Sep 23 23:34:48 MYMACHINE kernel: usb 1-126.96.36.199: USB disconnect, device number 28
Sep 23 23:34:48 MYMACHINE acpid[565]: input device has been disconnected, fd 15
Sep 23 23:34:48 MYMACHINE acpid[565]: input device has been disconnected, fd 16
Sep 23 23:34:49 MYMACHINE kernel: usb 1-18.104.22.168: USB disconnect, device number 29
Sep 23 23:34:49 MYMACHINE kernel: usb 1-188.8.131.52: USB disconnect, device number 30
Sep 23 23:34:49 MYMACHINE acpid[565]: input device has been disconnected, fd 17
Sep 23 23:34:49 MYMACHINE acpid[565]: input device has been disconnected, fd 18
Sep 23 23:34:53 MYMACHINE sudo[5048]: pam_unix(sudo:session): session closed for user root
Sep 23 23:35:02 MYMACHINE sudo[5192]: ME : TTY=pts/1 ; PWD=/home/ME ; USER=root ; COMMAND=/usr/bin/journalctl --follow
Sep 23 23:35:02 MYMACHINE sudo[5192]: pam_unix(sudo:session): session opened for user root(uid=0) by ME(uid=1000)

__detached and re-attached EXT4__

__detached and re-attached installer__

Sep 23 23:35:49 MYMACHINE kernel: usb 1-1.2: USB disconnect, device number 25
Sep 23 23:35:49 MYMACHINE udisksd[604]: Cleaning up mount point /media/ME/Ubuntu 22.04.3 LTS amd64 (device 8:17 no longer exists)
Sep 23 23:35:49 MYMACHINE systemd[1]: media-ME-Ubuntu\x2022.04.3\x20LTS\x20amd64.mount: Deactivated successfully.
Sep 23 23:35:55 MYMACHINE kernel: usb 1-1.2: new high-speed USB device number 31 using ehci-pci
Sep 23 23:35:55 MYMACHINE kernel: usb 1-1.2: New USB device found, idVendor=0930, idProduct=6544, bcdDevice= 1.00
Sep 23 23:35:55 MYMACHINE kernel: usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Sep 23 23:35:55 MYMACHINE kernel: usb 1-1.2: Product: DataTraveler 2.0
Sep 23 23:35:55 MYMACHINE kernel: usb 1-1.2: Manufacturer: Kingston
Sep 23 23:35:55 MYMACHINE kernel: usb 1-1.2: SerialNumber: 50E549C6942EC1B1E9025DA5
Sep 23 23:35:55 MYMACHINE kernel: usb-storage 1-1.2:1.0: USB Mass Storage device detected
Sep 23 23:35:55 MYMACHINE kernel: scsi host6: usb-storage 1-1.2:1.0
Sep 23 23:35:55 MYMACHINE mtp-probe[5218]: checking bus 1, device 31: "/sys/devices/pci0000:00/0000:00:1d.0/usb1/1-1/1-1.2"
Sep 23 23:35:55 MYMACHINE mtp-probe[5218]: bus: 1, device: 31 was not an MTP device
Sep 23 23:35:55 MYMACHINE mtp-probe[5222]: checking bus 1, device 31: "/sys/devices/pci0000:00/0000:00:1d.0/usb1/1-1/1-1.2"
Sep 23 23:35:55 MYMACHINE mtp-probe[5222]: bus: 1, device: 31 was not an MTP device
Sep 23 23:35:56 MYMACHINE kernel: scsi 6:0:0:0: Direct-Access     Kingston DataTraveler 2.0 1.00 PQ: 0 ANSI: 4
Sep 23 23:35:56 MYMACHINE kernel: sd 6:0:0:0: Attached scsi generic sg1 type 0
Sep 23 23:35:56 MYMACHINE kernel: sd 6:0:0:0: [sdb] 30310400 512-byte logical blocks: (15.5 GB/14.5 GiB)
Sep 23 23:35:56 MYMACHINE kernel: sd 6:0:0:0: [sdb] Write Protect is off
Sep 23 23:35:56 MYMACHINE kernel: sd 6:0:0:0: [sdb] Mode Sense: 45 00 00 00
Sep 23 23:35:56 MYMACHINE kernel: sd 6:0:0:0: [sdb] Write cache: disabled, read cache: enabled, doesn't support DPO or FUA
Sep 23 23:35:56 MYMACHINE kernel: GPT:Primary header thinks Alt. header is not at the end of the disk.
Sep 23 23:35:56 MYMACHINE kernel: GPT:9839183 != 30310399
Sep 23 23:35:56 MYMACHINE kernel: GPT:Alternate GPT header not at the end of the disk.
Sep 23 23:35:56 MYMACHINE kernel: GPT:9839183 != 30310399
Sep 23 23:35:56 MYMACHINE kernel: GPT: Use GNU Parted to correct GPT errors.
Sep 23 23:35:56 MYMACHINE kernel:  sdb: sdb1 sdb2 sdb3
Sep 23 23:35:56 MYMACHINE kernel: sd 6:0:0:0: [sdb] Attached SCSI removable disk
Sep 23 23:35:56 MYMACHINE systemd-udevd[5216]: sdb: Process '/usr/bin/unshare -m /usr/bin/snap auto-import --mount=/dev/sdb' failed with exit code 1.
Sep 23 23:35:56 MYMACHINE systemd-udevd[5229]: sdb3: Process '/usr/bin/unshare -m /usr/bin/snap auto-import --mount=/dev/sdb3' failed with exit code 1.
Sep 23 23:35:56 MYMACHINE systemd-udevd[5228]: sdb2: Process '/usr/bin/unshare -m /usr/bin/snap auto-import --mount=/dev/sdb2' failed with exit code 1.
Sep 23 23:35:56 MYMACHINE systemd-udevd[5216]: sdb1: Process '/usr/bin/unshare -m /usr/bin/snap auto-import --mount=/dev/sdb1' failed with exit code 1.
Sep 23 23:35:56 MYMACHINE kernel: ISO 9660 Extensions: Microsoft Joliet Level 3
Sep 23 23:35:56 MYMACHINE kernel: ISO 9660 Extensions: Microsoft Joliet Level 3
Sep 23 23:35:56 MYMACHINE kernel: ISO 9660 Extensions: RRIP_1991A
Sep 23 23:35:57 MYMACHINE udisksd[604]: Mounted /dev/sdb1 at /media/ME/Ubuntu 22.04.3 LTS amd64 on behalf of uid 1000

__detached and re-attached EXT4__

^C
</code>
You can see detaching and attaching the USB2 installer shows output but not the USB3 EXT4 drive.
Comment: Collect more information with the terminal command `sudo journalctl  --follow` as you connect the disks. Please [edit] your question to add whatever information you get. Do not use Add Comment.
Comment: I have added a second edit.  Looks like the dividing line is USB2 v USB3.
Answer: After testing Ubu 20.04, 18.04, and 16.04 as well as LinuxMint 21, I starting wondering if I have done something to the hardware (this machine was working with 16.04 and USB3 auto-mounts before the rebuild).
I detached everything, opened the box, and removed the SSD and the RAM to take a look around.  This is very basic hardware and I saw nothing that could have been nudged or disconnected.  Then I put the RAM and SSD back in place, closed the box, and re-attached everything.
Upon booting USB3 drives again auto-mounted and were recognized by all the aforementioned tools.  I am not able to explain why there was this peculiar relationship but there you have it.  With any luck this will prevent someone else from pulling their hair out.

HP EliteDesk 800 cannot see USB3 drives


Is there a way of describing why multiplying complex numbers adds their angles intuitively?

Question: Everywhere I'd looked for an explanation of this angle-adding phenomenon, it seemed to have been in one of two forms:
Either something roughly like this:
$$\left(\cos\left(a\right)+i\sin\left(a\right)\right)\left(\cos\left(b\right)+i\sin\left(b\right)\right)=$$
$$\cos\left(a\right)\cos\left(b\right)+i\cos\left(a\right)\sin\left(b\right)+i\sin\left(a\right)\cos\left(b\right)-\sin\left(a\right)\sin\left(b\right)=$$
$$\cos\left(a+b\right)+i\sin\left(a+b\right)$$
or something to do with: $$e^{i\theta}=\cos\left(\theta\right)+i\sin\left(\theta\right)$$
These are fine, but they seem like shots in the dark that happened to hit.
What I mean (for the first one at least) is that it appears that multiplying sines and cosines where one of the coefficients squares to -1 just happens to fall into the proper form for the angle addition formulas, it's not intuitive that such would be the case.
I was simply wondering if there was an explanation that would make it seem 'obvious' that complex numbers should add their angles through multiplication, not just an explanation that shows that they do.
Comment: Well it's simply because $e^{i\theta_1}e^{i\theta_2}=e^{i(\theta_1+\theta_2)}$
Comment: Well yes, that's a compact version of the first case I showed.

For the math to be consistent you would indeed expect that the exponential form is equivalent to the sine and cosine form, but if I was trying to teach someone the basics of imaginary numbers I wouldn't want to go through all of the confusion that goes along with trying to understand Euler's formula.
Comment: There's indeed a very simple geometric reason for this. Do you have access to Needham's book *Visual Complex Analysis*? It's explained in Section 5 of Chapter 1 (pp. 8–10).
Comment: @HansLundmark I'll check it out, thanks.
Answer: To my mind the most conceptual way is to go in the other direction, and define the complex numbers in terms of rotations.
This can be done as follows: consider the set of all linear transformations $T : \mathbb{R}^2 \to \mathbb{R}^2$ which scale and rotate the plane. This is equivalent to asking that $T$ is a similarity that fixes the origin, where a similarity is a map that multiplies all distances between vectors by the same number. This set of transformations is clearly closed under composition; more specifically, if two transformations $T_1, T_2$ scale by $r_1, r_2$ and rotate by $\theta_1, \theta_2$, then their composite $T_1 \circ T_2$ scales by $r_1 r_2$ and rotates by $\theta_1 + \theta_2$.
The elements of $T$ can be described more explicitly as follows. Suppose $T \left[ \begin{array}{c} 1 \\ 0 \end{array} \right] = \left[ \begin{array}{c} a \\ b \end{array} \right]$. This already uniquely determines $T$, since it means that $T$ must be a scaling by $r$ and a rotation by $\theta$ where $(a, b) = (r \cos \theta, r \sin \theta)$. It's not hard to see geometrically that this implies that $T \left[ \begin{array}{c} 0 \\ 1 \end{array} \right] = \left[ \begin{array}{c} -b \\ a \end{array} \right]$ (draw a diagram), so it follows that
$$T = \left[ \begin{array}{cc} a & -b \\ b & a \end{array} \right].$$
Somewhat surprisingly, this implies that the collection of similarities is closed under addition; this is specific to the case of $\mathbb{R}^2$ and is false in higher dimensions. This means it is in fact a real subalgebra of $M_2(\mathbb{R})$, and it is isomorphic to the complex numbers via the map
$$\left[ \begin{array}{cc} a & -b \\ b & a \end{array} \right] \mapsto a + bi \in \mathbb{C}.$$
From this point of view $i$ corresponds to the $90^{\circ}$ rotation $\left[ \begin{array}{cc} 0 & -1 \\ 1 & 0 \end{array} \right]$, so $i^2 = -1$ just says that two $90^{\circ}$ rotations make a $180^{\circ}$ rotation. And Euler's formula is a special case of the matrix exponential, describing the infinitesimal generator of a rotation. Multiplication corresponding to addition of angles is built into the definition here and the surprise is that the complex numbers are closed under addition.


How can I fix railings that lack newel posts?

Question: In my new house these two rails:

are wobbly and feel unsafe. It seems to me that whatever I do to the existing pieces, they're always going to be rather unsafe—they're low (less than 3 feet high) and will always have a tendency to get wobbly rapidly, due to the one-ended way they're attached and the small area that's contacting the walls. .
I'd like to replace them with something sturdier—ideally something to which I'll then be able to attach a top-of-stairs baby gate.
My first problem is that I've been unable to even search for replacement items, because I'm at a loss for how to describe these top-of-stairs-sawn-off-stairwell-side-rail-ettes.  Can anyone tell me what they're called, point me in the right direction to shop for replacements, and/or supply any further advice on how to construct something better in the limited space available?
Comment: Yeah, those rail sections should terminate with "newel posts", which need to be securely anchored to framing below. They withstand a lot of torque.
Comment: The posts you're referring to are called "balusters"; the rail on top of them is just a handrail. Googling "anatomy of stairs" will turn up diagrams like http://site.stairwarehouse.com/over-the-post.jpg which also helps explain the other, uniquely-named stair parts. I don't have any advice on how to replace them; I'll leave that up to an answerer.
Comment: And the handrail that I see peeking out should extend to said newel post.
Answer: With the limited space on the right side. Here's a couple ideas that may help you.
Buy or build yourself a pair of stair posts. If you choose to purchase, they come in all sorts of different sizes and designs.
Example

Build a half wall or full wall on both sides.
Lots of ideas bouncing around the Internet.
Be creative.
Answer: If your house will always be occupied by sedate adults and slow seniors, then you should install newel posts or stub half-walls (per Doc306).
But if you have teenagers, or children who will become teenagers, then such half-measures will not survive. Teenage humans move quickly and will use any available handholds to change direction quickly. Posts and half-walls cantilevered from the floor and attached only at the bottom will inevitably be ripped out by these monsters as their strength and mass grows beyond their undeveloped wit.
In this case you should install sturdy poles attached at the top and bottom and designed to resist a quarter-ton of lateral stress in any direction. This will require cutting the flooring and most likely patching the ceiling.

The extra work and trouble of such an installation will save years of emotional stress, broken bones, and splintered railings.
Comment: nice... and these beautiful half-formed humans will indeed blame you (inadequate future strength needs assumptions) when they destroy your work. Best make it bulletproof.


Diagonal update of the inverse of $XDX^T$

Question: I have a matrix $F=XDX^T$, where $D$ is $m\times m$ and diagonal and $X$ is $n\times m$.
Now, I compute $F^{-1}$.
Is there an efficient method to update $F^{-1}$ if $D$ is updated by $D'=D+G$, where $G$ is a sparse diagonal matrix?
Comment: Note: "sparse diagonal matrix" is a very redundant expression. ;)
Comment: How else would I imply a diagonal matrix with only very few of the diagonal nonzero though?
Comment: I would probably have used "low-rank diagonal matrix". :)
Comment: Ah thanks, that makes more sense.
Answer: Yes, there is a very efficient way to compute the updated $F^{-1}$. Begin by writing $X$ in terms of its columns: $X = [x_1 x_2 \dots x_m]$. It follows that:
$$
XGX^T = \sum_{i=1}^{m} G_{ii} x_ix_i^T = \sum_{i\in S} G_{ii} x_ix_i^T
$$
where $S \subset \{1,\dots,m\}$ is the set of indices for which $G_{ii}$ is nonzero. Suppose that $S$ contains $r$ indices. Since $G$ is sparse by assumption, $r$ is much smaller than $m$. If we assemble the columns of $X$ corresponding to indices in $S$, we obtain a new matrix $Y$, such that:
$$
XGX^T = YHY^T
$$
where $Y$ is $m \times r$, and $H$ is a diagonal matrix whose diagonal consists of all the nonzero entries along the diagonal of $G$. Now apply the Woodbury matrix identity:
$$
(F+YHY^T)^{-1} = F^{-1} - F^{-1}Y(H^{-1}+Y^TF^{-1}Y)^{-1}Y^TF^{-1}
$$
Computing the left-hand side directly is costly, as it requires inverting an $m\times m$ matrix. However, since $F^{-1}$ has already been computed, we can compute the right-hand side efficiently; the only inverse required is that of an $r\times r$ matrix, and $r$ is much smaller than $m$.
Comment: Note, however, that though $D$, $XDX^T$, and their inverses have the same inertia (via Sylvester), the "corrected" inverse may or may not have the same inertia (this depends on the nature of G). Though, it should hopefully be cheap to permute the entries of G (and the corresponding columns of X) such that all zero entries of G are in the trailing portion of the matrix, making SMW applicable.


iterating through java collection using jQuery

Question: I am starting with this object,
public class myTO {

    private String id;
    private String name;
    }

Which is used in this object
public myCombiTO {
    private myTO myTO;

    private List<String> valueList;
    private List<String> displayList;
}

I create a list of these objects
List<myCombiTO> myCombiTOList = getMyCombiTOList();

I use this list to set a jsp page attribute
request.setAttribute("myAttrList", myCombiTOList);

And forward to the jsp page. I then use jquery and jstl to populate a drop down from this list
<select name="mYSelect" id="mySelect">
     <c:forEach var="myVar" items="${myAttrList}">
          <option value="${myVar.myTO.id}" >
               <c:out value="${myVar.myTO.name}" />
          </option>
    </c:forEach>
</select>

My problem is I want to populate a second drop down using jquery with the values from mycombiTO.getValueList(). so far I have this
$("#mySelect").change(function(){
        var myJSList = ${myAttrList};
        var chosenGroup = $("#mySelect").val();
        var valueArray = myJSList.get(chosenGroup).valueList;
        var displayArray = myJSList.get(chosenGroup).displayList;
        var items = {'display':[displayArray], 'value':[valueArray]};

        //now populate drop downs

        $.populateSelect($('#myselect').get(0), items);

    });

jQuery.populateSelect = function(element,items) {
    $.each(items, function() {
            element.options[element.options.length]  = new Option(this.display,this.value);
          });
};

However its not working please help.  I am having trouble creating the javascript object based on two arrays.  Hwoever ideally I would want to reference a java map from jquery using key/value pairs. Is this possible ?
Thanks in advance.
Comment: Related: http://stackoverflow.com/questions/2263996/populating-child-dropdownlists-in-jsp-servlet
Answer: Right now you're passing in items which is an object with only two key/value pairs, so the $.each() is running for only two iterations. And for those iterations, this.display and this.value refer to the entire arrays.
One option would be to simply pass the displayArray and valueArray in to the populateSelect(), and iterate over those:
jQuery.populateSelect = function(element,displayArray,valueArray) {
    $.each(displayArray, function(i,val) {
        element.options[element.options.length]  = new Option( displayArray[i] ,valueArray[i] );
    });
};

Going back to your original code, you could also do this:
jQuery.populateSelect = function(element,items) {
    $.each(items.display, function(i,val) {
        element.options[element.options.length]  = new Option( items.display[i] ,items.value[i] );
    });
};

Comment: Yeah OK thanks; I was hoping for a mechanism to just use the one datastructure for displayArray and valueArray ... ?
Comment: @batthink - Sure. You could go back to your original code, and iterate over `items.display` instead of `items`. I'll update my answer with that. Another solution would be to create an array of objects, and iterate over that array instead of creating an object with the arrays inside.
Answer: I think your java code should provide a json version of your objects. You could then either insert the whole myCombiTOList in your jsp, or get a single myCombiTO object with an ajax request in the change function.


Pendrive is not working after installing ubuntu 13.04 64 BIT on it. Help?

Question: I've installed ubuntu 13.04 64 bit on my hp v115w 8 gb pendrive. I mean the full installation, not the liveDisk one. Now the pendrive is completely dead. It booted from the pendrive couple of times last night. But after that today the computer is not even detecting the hardware.I've tried other computers but no computer shows any response when the drive is plugged in. I saw device manager, disk manager.. nowhere the drive is being detected! I know there is not any hardware failure! I need some urgent help!! please. Thank you!
Comment: in a terminal, type `tail -f /var/log/kern.log` then plug your drive. Do you see any messages ?
Answer: try installing https://apps.ubuntu.com/cat/applications/precise/gnome-disk-utility/
A Disk utility tool. And see if it helps!


Using Method Group gives me The call is ambiguous between the following methods or properties:

Question: I want to call a simple method group in Linq but I receive this error.
The call is ambiguous between the following methods or properties: 'System.Linq.Enumerable.Select<string,int>(System.Collections.Generic.IEnumerable<string>, System.Func<string,int>)' and 'System.Linq.Enumerable.Select<string,int>(System.Collections.Generic.IEnumerable<string>, System.Func<string,int,int>)'
var num = new [] { "12345", "5432" };

num.Select(Convert.ToInt32);

I understand that there is ambiguity between which method to call. My question is however, is there a way of specifying the signature without calling the method normally. I want to save typing by not having to use lambda expressions.
Thanks.
Answer: You could cast explicitly:

num.Select((Func<String, Int32>)Convert.ToInt32);

Comment: Then if the answer satisfies your question you could mark my answer.


Ubuntu 21.04 freezes on zoom Screen share option

Question: Today I upgraded from Ubuntu 20.04 to 21.04. It uses Wayland by default, also I have disabled my nvidia card (just selected Integrated Graphics from nvidia-settings). When I installed and tried zoom client from the Ubuntu Software I was not able to share screen on Wayland. Then I logged off and switched to Xorg session and tried the same thing. This time the zoom client freezed when I started to share my screen. There was not such a problem on 20.04, and I guess this is not solely related to Wayland.
Is there any fix for it?
Thanks!
Comment: FYI:  Ubuntu has two upgrade paths that are fully QA-tested, from one release to the next, **or** from one LTS to the next LTS, so 20.04 was fully QA-tested to move to 20.10 (and 20.10 to 21.04), and 20.04 will be fully QA-tested when 22.04 is near ready. You've gone outside of the intended & thus fully tested upgrade paths.
Answer: After upgrading from Ubuntu 20.04 to 21.04, I also faced same problem. You just need to do following steps.

Restart your system
There is gear icon (bottom right side) on login screen
Which have two options. First one is Ubuntu which is Wayland by default and another one is Ubuntu on Xorg.
You have to go for Ubuntu on Xorg

It works for me.
Comment: You saved my day, thx. One addition: Initially the gear icon wasn't there until I pressed Enter which made the password input box appear. Seems somewhat related: https://gitlab.gnome.org/GNOME/mutter/-/issues/878
Comment: my system froze after using zoom for like 5 minutes, I hope it's temporary :(
Comment: Wayland is very slow in my laptop. We need to find a solution with wayland :)


Is my Non-Contact Voltage Tester from Klein Tools safe?

Question: There are many questions regarding Non-Contact Voltage Testers. They are a great safety tool when used as recommended and when they are functioning as designed.
Has mine been recalled?
Model: Klein Tools NCVT-1
Date code: 1119C-G8
Answer: US Consumer Product Safety Commission announced a recall of select Klein Tools NCVT-1 voltage testers.
These were sold individually and as part of kits. I have one, but the recall is only for date code ending in H7. So I'm OK (code ends in G8).

Hazard: The on/off button can remain depressed during the power on or power off cycle, causing the tester to work improperly. Consumers testing electrical sources could fail to be warned of the presence of live voltage if the tester is not properly operating, posing a shock hazard to the users.

Full details at the link above. Safety first!
Comment: @JohnCanon, proper procedure is "known live, unknown, known live".  This protects against things like the battery dying just after you test the known-live wire.
Comment: For the time if/when the link dies, would you mind indicating what part of the tester is _un_ safe? i.e. is it failing to detect electricity in live wires, or does it provide a shock risk to the user, or is the tip small enough that people are using it as a nose pick and injuring themselves, or...?
Comment: My tester has date code G6, so I guess it is OK. Regardless, after turning it on, I always do a test against a known live conductor before wandering into the jungle of unknown wires.


Unable to buy Pages of Blacksmithing from the Auction House

Question: Note: The auction house no longer exists. This question is irrelevant to the current release of the game

When I go to the auction house, select pages and recipes -> artisan crafting -> pages of blacksmithing (or any of the pages), and i try to click buyout it wont let me.  it says you must purchase at least (coins worth)100 of this item.
Why can't i buy any recipes?  I haven't really used the auction house much but is it that there isn't enough stock of this item so i can't buy it out?
Comment: Question should be close as there is no longer an auction house for diablo 3.
Comment: @z- Question should not be closed. See [this answer](http://meta.gaming.stackexchange.com/a/8451/50582) to your own meta question about D3.
Comment: @BillyMailman the difference between the example and this one in D3 is the fact that you can't go back to a previous version of D3 where an AH exists, but in Minecraft you can play previous versions.
Comment: This discussion should be continued in the comment thread on the meta answer. But in the meantime, I will add the suggested disclaimer to my question
Answer: The answer (because I am an idiot and didn't notice) is that you have to change the quantity before you press search.  This way you can have enough of the item to make it above the minimum price
Comment: gotta wait two more days? odd


Encrypted home folder still accessible after logout

Question: I you have an account with an encrypted home folder, you can't access the user's plain text data in their home folder if that user hasn't logged in, yet, since the system last booted up. This is what I expected because it should in fact not be practically feasible to access a user's home folder without their password being entered.
However, I found that when a user with an encrypted home folder logs in and then logs out, the plain text data in their home folder still is accessible to other users. Sufficient access privileges are required, of course.
w doesn't list the user and the output of sudo pgrep -u <username> is empty, indicating that the user doesn't have any running processes.
What is the reason for this behavior? Why not just lock the user's home folder after they logged out?
Comment: Could you please include the output of `grep -Fe ecryptfs /var/log/auth.log` from around the time the user logged out?
Comment: The command yields this output: https://pastebin.com/jZXdahbJ According to Emacs, the only lines which contain the string "ecryptfs" are the lines which were produced when I ran that command.
Comment: The result is as expected just the lines which Emacs already showed me: https://pastebin.com/VtV7iCDg
Comment: Ok. It was worth a look.
Comment: I have noticed this bug in persistent live systems too (in an attempt to create a second user with encrypted home).
Answer: Known bug
If I understand correctly, this is a known bug.
See this link: wiki.archlinux.org/index.php/ECryptfs
Scroll down to the pink paragraph

Warning: Unfortunately the automatic unmounting is susceptible to break with systemd and bugs are filed against it ...

Work-around
As it is now, you had better shut down or reboot in order to remove the traces (It is not enough to log out).
Comment: Trying to explain better: 'It is not enough to log out'. (Logout does not remove the clear-text instances of the files, that have been used by the user with encrypted home. So information can leak from this user to another user, who logs in, at least if this other user has sudo privileges. But if you shut down or reboot, the clear-text instances of the files disappear.
Comment: What do you mean by "logout will leak the information between the users"? Do you mean that anything happens, other than that a different user with sufficient privileges can access the plain text data in the first user's home directory? (This is already possible before the logout, of course.)
Answer: I have been researching this issue for quite some time, i.e., unecrypted file system remains mounted after user logout.
I used "ecryptfs-migrate-home -u user" to create mount. followed directions and all works except no auto-unmount at logout.
I compared the config files in /etc/pam.d/ to pam_ecryptfs documentation and found the some differences. ecryptfs was in 4 of the pam.d config files whereas the pam_ecryptfs docs indicate just 2 files need/should/support ecryptfs, e.g.,

   /etc/pam.d/common-auth:
              auth    required        pam_ecryptfs.so unwrap
   /etc/pam.d/common-session:
              session optional        pam_ecryptfs.so unwrap

So, I commented out the other 2 instances, rebooted, and it all worked, auto-mounts at login and auto-unmounts on logout for both graphical and console logins.  (I used alternate tty's to verify from root account)
This is on 18.04 Lubuntu on laptop, desktop and virtualbox guest (windows host).
I am interested in others experience.
edit_1: improved wording. edit_2: added desktop and VB test results.
Comment: @Xen2050, I did the test of changing password. it worked.
Comment: Did disabling / commenting out any of those lines cause any problems? Does changing your password still re-wrap the eCryptfs keyfile?
Comment: This worked for me on Linux Mint 19. To add some more detail for others: the four config files in /etc/pam.d that refer to ecryptfs are: common-auth, common-password, common-session, common-session-noninteractive. Commenting out the lines in common-password and common-session-noninteractive led to the desired behavior of unmounting on log out. Also, the entry in common-auth was set to "optional" instead of "required" as it is supposed to be according to the documentation. However, I left this as is.
Comment: @Xen2050, sorry for late response. I did not detect any problems after changes commenting out lines and I have not tried changing password as yet.
Comment: The changing password might be important to test, it should re-wrap the encryption key with your new password automatically, so logging in the next time works. If it doesn't work, then just changing the password back to the previous one *should work*... [it's always good to have a backup though]
Comment: On Ubuntu 20.04 commenting the lines out in the files mentioned by @evencoil and rebooting does make it unmount on logout however changing the password breaks things and you can't login until you get it back to what it was.
Answer: I can't test or confirm this, but assuming that you are using ecryptfs (which is what Ubuntu offers during install, IIRC), the encrypted data is stored in a hidden folder /home/.encryptfs/$USER and mounted to your actual home folder's location using the ecryptfs driver when you log in.
Most likely, then, what is happening is that when you log out, it fails to automatically unmount that directory, so the files are still accessible. This could be caused by...

a bad config (perhaps it was supposed to be configured to unmount on logout but wasn't)
unexpected logout type (sometimes these solutions work for the DM login/out but don't work well otherwise)
if the unmounting is handled by a logout script (not necessarily the case), something preceding the unmount command could fail and cause the script to exit early.

One thing that can help you check this would be to run sudo mount | grep home before login, after login, and after logout to see if anything involving home is being mounted. You could also look in /etc/fstab for relevant entries. Finally, there is some config in /home/.ecryptfs/$USER/.ecryptfs/ with pertinent settings to automounting/unmounting.
Useful information about ecryptfs can be found in this answer and in the ever-helpful ArchWiki.
Comment: I tried what you told me: https://pastebin.com/DrmEXQPV I don't log out in any weird  way but in the standard GUI way. The FS is still mounted, as you can see. The config files you mentioned are empty. There is nothing in my `/etc/fstab` except 1 entry saying that my only data partition should be mounted to `/` and 1 entry which is about some university-related network resource. Should I try logging out in any different way? If so: How?
Comment: The logging out in a different way comment was a bit of a guess--desktop managers add a lot on top of logging in and logging out that complicates the notion and makes it hard to tell which events are triggered. I was wondering because there may have been some script or event that wasn't being run. Based on the other answers, it's not that kind of problem, but something to do with `ecryptfs` itself. On that note, though, do you use `ssh` or log in via the text terminals? It may be possible to write a script that will take care of unmounting on logout if we find where to put it.
Answer: Edit /etc/systemd/logind.conf and set KillUserProcesses=yes
Note that this breaks background programs, screen, tmux, and similar...
This question here goes into it in more detail.  I find defining a new systemd service unnecessary (or more accurately, not the desired behavior, as it's invoked as a shutdown hook, not when the user session terminates).
https://unix.stackexchange.com/questions/251902/ecryptfs-auto-umount-does-not-work
Comment: I will check if your method works for a persistent live system with a second user, which has encrypted home.
Comment: Sorry, but I could *not* make this method work in a persistent live system with a second user, which has encrypted home. (I have not tested your solution in an installed system, I will leave that to @UTF-8 who asked the original question.)
Comment: I'm not interested in fixing this on my own computer. I'm the only one who uses it anyways but want to use 2 accounts with encrypted home folders and no one else knows the password to either account. I'm interested in why it doesn't unmount the encrypted volumes automatically **by default**. Couldn't it just check for active background processes running in the user's context and unmount it if there aren't any?
Comment: @UTF-8, I agree with you, that it *should* work like you want it to work. If I understand correctly, this is a known bug. See this link , https://wiki.archlinux.org/index.php/ECryptfs . Scroll down to the pink paragraph 'Warning: Unfortunately the automatic unmounting is susceptible to break with systemd and bugs are filed'. -- As it is now, you had better shut down or reboot in order to remove the traces (logout will leak the information between the users.)
Comment: @UTF-8 it's a bug in systemd/session interaction since at least wheezy (I'm perfectly comfortable just hanging it on systemd) - the /etc/systemd/logind.conf change works for me on 16.04 (tested with three different users, different sessions, etc...)
Answer: I do it with a script in rclocal
#!/bin/sh
#

while true; do
    if [ ! -d /run/user/1000 ]; then
        if [ -f /home/momo/.mounted ]; then
            umount /home/harry
        fi
    fi

    if [ ! -d /run/user/1001 ]; then
        if [ -f /home/vm/.mounted ]; then
            umount /home/maud
        fi
    fi

    sleep 10
done
exit 0

Comment: How you get the userid?
Answer: If you do not need access from cron or at jobs (non-interactive tasks) to ANY home directories then you just need to comment out the line
session  optional        pam_ecryptfs.so unwrap

in /etc/pam.d/common-session-noninteractive.
This will cause all encrypted home directories to be unmounted when the user logs out.


How to use DefinitelyTyped in Angular5?

Question: If I am correct DefinitelyTyped has TypeScript definitions for multiple libraries. In my case I wanted to use Google Charts definitions available here.
I have installed them using
npm install --save-dev @types/node
npm install --save-dev @types/google-apps-script

But I don't know how to import them to my project. I have tried using
import { Google } from '@types/google-apps-script';

But Visual Studio Code throws an error, that it is not a module and my declare const google is still of :any, which I want to avoid.
Any help or hint would be appreciated.
Answer: To get Google Charts to work in my Angular 5 project I used these DefinitelyTyped types instead which is only for the Google Charts JavaScript library.
@types/google.visualization

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/google.visualization
Here is how I imported the types into an @Injectable Service class. This statement did not raise an error about it not being a module like when I tried to import using *.
import { } from 'google.visualization';

In the constructor is where you can load the charts library just once and then create your chart functions to pass with data and config options to the callback (setOnLoadCallback).
google.charts.load('current', {'packages':['corechart']});

I added a script element to index.html to load the 'https://www.gstatic.com/charts/loader.js' but perhaps there is a better way to include external libraries such as this.

How to use DefinitelyTyped in Angular5?


Error- Validate Multiple APi call response in one scenario in karate

Question: I am trying to use two api call (Post & put call) in one scenario in karate framework. But I am not able to validate 2nd Api call response. when i tried to do like response.id , it passing 1 st api call response.
Is there any solution for it?
Comment: Can you share some code ? it will be easy for us to identify exact problem. As per document `response` always get [overridden](https://github.com/karatelabs/karate#response) when new request is made to api.
Comment: @k33da_the_bug - i have added my feature file , could you please share your ideas
Answer: In your feature file, you wrote your print response in When instead of writing it after Then. Which means it is showing the previous response only. As per documentation response gets overridden after making a new http request.
Following,
...
When method put
And print 'jokerresult-->',response.joker_result
Then status 201

Should be like,
...
When method put
Then status 201
And print 'jokerresult-->',response.joker_result

let me know if it worked for you or not.


Push a Git branch to remote without checking the branch out

Question: Is there a way to push a branch to a Git remote without checking that branch out first?
Say I am on the master branch, and there is a release branch that I want to push to the remote, is there a way to push the release branch to the Git remote without having to check it out first?
Comment: https://stackoverflow.com/questions/18031946/what-does-set-upstream-do
Comment: @jmargolisvt did you read the question? The answer in that link says "sets the default remote branch for the current local branch." The point of this question is push a branch to a remote, if you haven't currently checked that branch out
Comment: @AlexanderMills looks like at least two other people agree that setting upstream might be the answer the OP is looking for.  If you think you have a better reading of the question, I encourage you to post your answer.
Answer: Try this:

git push -u origin new_branch_name
Answer: This question looks to me like a duplicate of push an 'unchecked out' branch. (Hooray for the "related" section.)
If the feature branch has the same name in both the local repository and in origin, you can use the following shorthand:
git push origin <feature_branch_name>

See this example in the manual. Otherwise specify both names with
git push origin <local_branch_name>:<remote_branch_name>


Custom tabs on android

Question: I want to create some tabs on android but I do not know if this kind of tabs is possible to create on android. If they are possible can someone give me some link to a similar tutorial or example so I can take a look how to create such tabs in android.
Here is what I'm looking for:
I need to have 2 tabs left and right, and a logo in the center that is not clickable.
Answer: You can use my library on Github it allows you to create a custom tab layout and use it. So you can create a layout which contains both image and text, and then you can modify tab according to position.
Comment: Aaahh sorry, you don't want your textview as a tab.
So maybe you can create this view by yourself with relativeLayout; two imageviews on left, two imageviews alignParentRight and logo centered.

Custom tabs on android


Nautilus preferences and menu missing

Question: My nautilus does not show a preferences button or file/edit etc when I hove over the left top. I recently did a clean install of Ubuntu natty narwhal 11.04. What happened and how can I fix this?
See screnshot here
Comment: Are you not missing the global menu on the top of the screen (hover your mouse over the bar at the top)? Or Is the top bar gone completely?
Comment: Vote to close, as there is no feedback to above question.
Answer: Open a terminal and type sudo apt-get install nautilus.
Then restart your session.
For some reason, Nautilus is not completely updated when you install the Elementary version. This will complete the upgrading process and Preferences and Menu will be there again the next time you start Nautilus.
Answer:
Install compiz fusion icon from synaptic
In compiz fusion icon choose for "select windows manager' and then for Metacity.
If you have your preferences and menu back then compiz is the reason why.
Comment: Too bad, that didn't solve it. I changed into classic ubuntu interface and now nautilus looks okay again; too bad for unity!

Nautilus preferences and menu missing


Description of subset of infinite product space leads to contradiction

Question: Let $\mathbb{R}^\omega$ be the infinite product space $\mathbb{R} \times \mathbb{R} \times ...$, and let $A$ be the subset of $\mathbb{R}^\omega$ containing points with coordinates $0$ except for a finite amount of coordinates. The following proof contains an error:
The set $A$ can be broken up into subsets of the form $\prod X_\alpha$ where $X_\alpha$ is $\mathbb{R}$ for a finite amount of $\alpha$ and $\{0\}$ otherwise. Of course, $A$ is then the union of all such sets.
Take an arbitrary coordinate $\beta$. We can find a subset $\prod X_\alpha \subset A$ as described before such that $X_\beta = \mathbb{R}$. Since the choice of $\beta$ was arbitrary, we can conclude that in the union of all such subsets, each coordinate maps to $\mathbb{R}$ and therefore $A$ can be expressed as $\prod X_\alpha$ where $X_\alpha = \mathbb{R}$ for all $\alpha$.
Let $x = (1, 1, ...)$. Since each $x_\alpha$ is in $\mathbb{R}$ we can conclude $x \in A$ for the derived definition of $A$. However, $x \notin A$ for the given definition of $A$, a contradiction.
I don't see a reason why the definition of $A$ cannot exist, so there must be something wrong with the proof, but I can't find the problem.
Answer: The issue is with your claim

$(*)\quad$ and therefore $A$ can be expressed as $\prod X_\alpha$ where $X_\alpha = \mathbb{R}$ for all $\alpha$.

Essentially, all you've shown up until this point is that $A$ isn't equal to any of its "finite-length approximations." But this doesn't imply that $A=\prod_{\alpha\in\omega} \mathbb{R}$ (and so your final paragraph is a non-starter, since $x\not\in A$).
If you try to prove $(*)$, I suspect you'll quickly see the issue.
Answer: Noah pointed out the mistake. But let me make an even stronger point:

The union of products need not be a product.

To see this, note for example that $\{\langle x,y\rangle\in\Bbb R^2\mid |x|,|y|<1\}$ is the union of countably many sets of the form $(a,b)\times(c,d)$. But the unit disc itself is not a product of any two subsets of $\Bbb R$.
Even worse, $\Bigr((0,2)\times(0,2)\Bigl)\cup\Bigr((3,5)\times(3,5)\Bigl)$ is a union of two products and it is not a product, since $\langle 1,4\rangle$ is not in the set, and if it were a product of two sets $A$ and $B$, then $1\in A$ since $\langle 1,1\rangle$ is in the set, and $4\in B$ for a similar reason.


Rename column R

Question: I am trying to rename columns but I do not know if that column will be present in the dataset. I have a large data set and if a certain column name is present I want to rename it. For example:
A   B   C   D   E
1   4   5   9   2
3   5   6   9   1
4   4   4   9   1

newNames <- data %>% rename(1=A,2=B,3=C,4=D,5=E)

This works to rename what is in the dataset but I am looking for the flexibility to add more potential name changes, without an error occurring.
newNames2 <- data %>% rename(1=A,2=B,3=C,4=D,5=E,6=F,7=G)

This ^ will not work it give me an error because F and G are not in the data set.
Is there any way to write a code to ignore the column change if the name does not exist?
Thanks!
Comment: Sorry I tried to post an example of a dataset but it did not go through right but basically the letters are the column names I am trying to change
Comment: You can't rename something that doesn't exist. You could always just use the `names()` function, something like `names(data) <- 1:length(data)`. That way, you just rename all of the columns in the dataframe, wihout knowing how many there are.
Comment: I get different datasets that I am trying to format and some would hypothetically have "A","C","D" and another could have "B","C","E". I am trying to have one code that will rename whatever variables are present for that dataset.
Answer: There can be plenty of ways to do this. One would be to create a named vector with the names and their corresponding 'new name' (as the vector's names) and use that, i.e.
#The below vector v1, uses LETTERS as old names and 1:7 as the new ones
v1 <- setNames(LETTERS[1:7], 1:7)
names(df) <- names(v1)[v1 %in% names(df)]

Rename column R


Navigation Bar not showing title

Question: I am unable to get the navigation bar to show the title that I specify. I have tried to change the title in the AppDelegate.m, as well as in the viewDidLoad of my first tab view. I suspect the title is being hidden, but I am unable fix it. Please provide any insight you may have.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    navigationController = [[UINavigationController alloc] initWithNavigationBarClass:[CRGradientNavigationBar class] toolbarClass:nil];

    UIColor *firstColor = [UIColor colorWithRed:155.0f/255.0f green:41.0f/255.0f blue:104.0f/255.0f alpha:1.0f];
    UIColor *secondColor = [UIColor colorWithRed:215.0f/255.0f green:90.0f/255.0f blue:18.0f/255.0f alpha:1.0f];

    NSArray *colors = [NSArray arrayWithObjects:firstColor, secondColor, nil];

    [[CRGradientNavigationBar appearance] setBarTintGradientColors:colors];

    self.navigationController.title = @"This title is not showing";

    [[navigationController navigationBar] setTranslucent:NO];

    //create the view controller for the first tab
    self.firstViewController = [[FirstViewController alloc] initWithNibName:nil
                                                                     bundle:NULL];

    //create the view controller for the second tab
    self.secondViewController = [[SecondViewController alloc] initWithNibName:nil
                                                                       bundle:NULL];

    //create the view controller for the third tab
    self.thirdViewController = [[ThirdViewController alloc] initWithNibName:nil
                                                                       bundle:NULL];

    //create the view controller for the fourth tab
    self.fourthViewController = [[FourthViewController alloc] initWithNibName:nil
                                                                     bundle:NULL];

    //create an array of all view controllers that will represent the tab at the bottom
    NSArray *myViewControllers = [[NSArray alloc] initWithObjects:
                                  self.firstViewController,
                                  self.secondViewController, self.thirdViewController, self.fourthViewController, nil];

    //initialize the tab bar controller
    self.tabBarController = [[MainUITabBarController alloc] init];

    //set the view controllers for the tab bar controller
    [self.tabBarController setViewControllers:myViewControllers];

    [navigationController setViewControllers:@[self.tabBarController]];

    [self.window setRootViewController:navigationController];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;

}

Answer: The relationship of your view controllers isn't right.

The root view controller of your app should be the TabBarController.
Each of the items should have it's own Navigation Controller.
The title of each ViewController can be set in viewDidLoad() with self.title = "....
Comment: Ok, so would I set each of the items to have its own Navigation Controller in the AppDelegate?
Answer: I've been able to set titles in the delegate as follows:
1.) Create view controllers
2.) Set those titles
3.) Then create UINavigationControllers and assign view controllers there
self.firstViewController = [[FirstViewController alloc] initWithNibName:nil bundle:nil];
self.secondViewController = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
self.thirdViewController = [[ThirdViewController alloc] initWithNibName:nil bundle:nil];
self.fourthViewController = [[FourthViewController alloc] initWithNibName:nil bundle:nil];

[self.firstViewController setTitle:@"First"];
[self.secondViewController setTitle:@"Second"];
[self.thirdViewController setTitle:@"Third"];
[self.fourthViewController setTitle:@"Fourth"];

UINavigationController *controller1 = [[UINavigationController alloc] initWithRootViewController:self.firstViewController];
UINavigationController *controller2 = [[UINavigationController alloc] initWithRootViewController:self.secondViewController];
UINavigationController *controller3 = [[UINavigationController alloc] initWithRootViewController:self.thirdViewController];
UINavigationController *controller4 = [[UINavigationController alloc] initWithRootViewController:self.fourthViewController];

NSArray *viewControllers = [NSArray arrayWithObjects:controller1, controller2, controller3, controller4, nil];

Navigation Bar not showing title


Applying the chain rule to a line integral over gradients to get the Integrated Gradients method

Question: I'm trying to understand how the authors of the paper 'Axiomatic Attribution for Deep Networks'
determined the formula for Integrated Gradients.
The path function $\gamma = (\gamma_1, ..., \gamma_n): [0, 1] \rightarrow \mathbb{R}^n$ specifies a smooth path from the baseline $x' \in \mathbb{R}^n$ to the input $x \in \mathbb{R}^n$, where $\gamma(0)=x'$ and $\gamma(1)=x$. The function $F : \mathbb{R}^n \rightarrow [0, 1]$ is represented by a deep neural network in this case. The authors integrate the gradients over the path $\gamma$ with $\alpha \in [0,1]$ using the following line integral:
$$\text{PathIntegratedGrads}_i^\gamma(x)::=\int_{\alpha=0}^1 \frac{\partial F(\gamma(\alpha))}{\partial \gamma_i(\alpha)} \frac{\partial \gamma_i(\alpha)}{\partial \alpha} d\alpha. \tag{1}$$
Now, the authors consider the straight line path:
$$\gamma(\alpha) = x' + \alpha \cdot (x - x') \text{ for } \alpha \in [0, 1]. \tag{2}$$
Plugging the straight line path into the above formula for $\text{PathIntegratedGrads}_i^\gamma(x)$ they get:
$$\text{IntegratedGrads}_i(x)::= (x - x')\int_{\alpha=0}^1 \frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial x_i} d\alpha. \tag{3}$$
Since
$$\frac{\partial \gamma_i(\alpha)}{\partial \alpha} = (x - x'), \tag{4}$$
it follows, that:
$$\frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial (x_i' + \alpha \cdot (x_i - x_i'))} \overset{!}{=} \frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial x_i}. \tag{5}$$
However, applying the chain rule, I got:
$$\frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial (x_i' + \alpha \cdot (x_i - x_i'))} = \frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial x_i} \frac{1}{\alpha}. \tag{6}$$
Then shouldn't integrated gradients instead be:
$$\text{IntegratedGrads}_i(x)::= (x - x')\int_{\alpha=0}^1 \frac{\partial F(x' + \alpha \cdot (x - x'))}{ \partial (x_i' + \alpha \cdot (x_i - x_i'))} d\alpha. \tag{7}$$
This is also the way it is implemented in the author's github:
<code># Scale input and compute gradients.
scaled_inputs = [baseline + (float(i)/steps)*(inp-baseline) for i in range(0, steps+1)]
predictions, grads = predictions_and_gradients(scaled_inputs, target_label_index)  # shapes: <steps+1>, <steps+1, inp.shape>

avg_grads = np.average(grads[:-1], axis=0)
integrated_gradients = (inp-baseline)*avg_grads # shape: <inp.shape>
</code>
Did I go wrong somewhere or am I missing something?
EDIT:
I'm still having some trouble to follow. Let's say we have the path integral and plug in the straight line path, then we get Integrated Gradients:
$$
\text{IntegratedGrads}_i(x)::=\int_{\alpha=0}^1 \frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial (x'_i + \alpha \cdot (x_i - x'_i))} \underbrace{\frac{\partial (x' + \alpha \cdot (x - x'))}{\partial \alpha}}_{(x - x')} d\alpha.\tag{8}
$$
Then I have a $\partial (x'_i + \alpha \cdot (x_i - x'_i))$ in the denominator of the integrand, whereas the paper only has a $\partial x_i$. Therefore, equation (8) is different from equation (3), which is the Integrated Gradients formula from the paper. When I rewrite the integrand of Integrated Gradients from the paper with the chain rule I get the following:
$$
\frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial x_i} = \frac{\partial F(x' + \alpha \cdot (x - x'))}{\partial (x'_i + \alpha \cdot (x_i - x'_i))} \underbrace{\frac{\partial (x'_i + \alpha \cdot (x_i - x'_i))}{\partial x_i}}_\alpha, \tag{9}
$$
which explains the additional $\alpha$ in (6) and that the LHS and RHS are not equal in equation (5). I also changed the equality sign in equation (5) to emphasize that the LHS and RHS are not the same.  What am I missing, such that I get the formula of Integrated Gradients as stated in the paper?
Answer: Regarding the interpretation of the math in the paper, I think you have a $∂(x′i+α⋅(xi−x′i))$ term instead of a $∂(xi)$ term in the denominator of the LHS of the equation "it follows, that:".
(I also wonder if there is some confusion about notation: The derivative is taken with respect to a variable[$xi$] at a particular point[$x′i+α⋅(xi−x′i$)].)
Regarding the implementation in github repository, I am not seeing the extra α term
in the implementation. [If it helps, the derivative returned by the ML library (e.g. tensorflow) corresponds to $∂F(x′+α⋅(x−x′))/∂xi$ and not $∂F(x′+α⋅(x−x′))/∂(x′i+α⋅(xi−x′i)$].
(If you want to do the complete derivation, first use the fundamental theorem of calculus, then the partial derivative chain rule as in case 1 here: http://tutorial.math.lamar.edu/Classes/CalcIII/ChainRule.aspx and the result should match up.)
Comment: Welcome to MSE. Please edit and use [MathJax](https://math.meta.stackexchange.com/questions/5020) to properly format math expressions.
Comment: I still have trouble understanding your derivation of Integrated Gradients. I have edited my question and hope that I have addressed my confusion more precisely.
Comment: I edited my answer.
Comment: All my confusion came from the notation! Thank you for clarifying.


Will an Egg move still be passed on if it is overwritten by the daycare's levelling?

Question: I'm trying to pass on the move Wish to a line of Eevees, as well as get the right nature and IVs. The Smeargle I used to pass on the move only has 1 IV, and I'd like to swap in another Eevee (one of the children which has Wish) that has 3 IVs.
However unlike Smeargle, Eevee learns a lot of moves, so I'll only get 5 or so Eggs before that Eevee forgets Wish, due to the daycare's feature of erasing old moves in favour of new.
So my question is, do I need to take out that Eevee periodically to re-teach Wish? (At the cost of a heart scale) Or will its moveset stay the same until its withdrawn, therefore continuing to pass on Wish anyway?
Comment: The Daycare Center forgets moves for you?
Comment: @Coronus - Yes, the top move is removed and a new move is added when the Pokemon reaches a level where it learns a move
Answer: AFAIK as long as you do not take out the Eevee from the day care, it will continue to pass on Wish to its children. So if you are just keeping it in there to make a lot of Eevees, it will serve its purpose.
If you really want to keep wish on it, then you can remove it periodically from the daycare and rearrange the moves it has learned, so that Wish ends up at the bottom. The moves will be learnt by deleting ones from the top and adding a move to the bottom of the move list. This will give you a chance to keep wish on the Eevee while it is leveling and learning moves in the daycare. (You have a window of 3 move learns before you rearrange or else you will lose Wish)
If by chance you end up losing Wish then you have to go to the move re-learner and pony up a Heart Scale.
PS: I bred Stealth Rock onto my Tyranitar(Larvitars) this way. So I know it works out better and takes very little effort on your part.
Comment: @Robotnik Yup, new moves learned during the daycare are applied as soon as you remove the Pokemon.
Comment: Isn't it also possible to put in a lvl 100 eevee? So it won't lvl up and the moves won't be forgotten?
Comment: According to the question, he has just hatched a eevee with Wish and wants to know how to keep it. Levelling a pokemon to high levels beyond which it does not learn a move is actually a pretty obvious but time-consuming solution to the problem.
Comment: Awesome, so I can just leave it in there and not worry about hatching eggs that won't have wish. Thanks
Comment: @Jerry - Thanks for mentioning that here. I missed that in my answer and it is the main mechanic upon which it works.
Comment: My female mawille had children and passed down Seismic Toss with Ditto. Except, Mahwile forgot seismic toss before it was put in the daycare. So, how do you know what egg move will be passed if forgotten egg moves can still be passed?
Comment: @Dedenneway Are you sure the Eggs were not created **before** removing Mawile from the daycare?
Answer: You will need to re-teach Wish as passing down Egg Moves only takes the current moveset into account.
Comment: I believe it only updates the move list when you retrieve the Pokémon from the daycare centre.
Comment: I realize it only takes the current move set into account, my question was more about when that current move set is set. If the eevee learns a move at level 8, does that wipe the old move straight away? Or is its current moveset only recalculated when you withdraw it?
Comment: It learns the new move straight away.
Comment: according to Jerry & Samyam the moves are only applied once you withdraw the Pokemon though - meaning I can leave it there and not worry about it.
Comment: Hmm... that hasn't been my experience. I'll do some more testing.


Need a progress indicator for a Perl system() command using T:R:G mod

Question: I want a progress indicator that takes the output of a Perl
   system('make')

and for each line output to STDOUT from the make command, I want to output a dot as a progress indicator.  Unfortunately, I'm using the Term::ReadLine::Gnu Perl mod.
How do I redirect STDOUT to capture and count the lines as the make command is running?
Comment: You may also find [Term::ProgressBar](http://search.cpan.org/perldoc/Term::ProgressBar) of use.
Answer: #!/usr/bin/perl

my $command = "make";

open (my $cmd, "$command |");
while(<$cmd>){
  print ".";
}
print "\n";

Comment: I recommend using a three-arg `open` for this: `open my $cmd, '-|', $command or die $!;`  This is safer and more efficient.
Comment: You'll want to autoflush STDOUT otherwise it'll wait for a whole line of dots before printing.  `use IO::Handle;  STDOUT->autoflush(1)`
Comment: good advice, I use the three-arg version exclusively for files, why not pipes as well?  Also, this might be a case where using print over die may have its advantages.
Comment: yeah, add $outStatus=$?; inside the while loop, then after the loop add a line like  print "$command was SUCCESSFUL\n" if ($outStatus ~~ 0);
Answer: make >& >(while read f; do echo -n .; done; echo)

Obviously this is a shell solution, but a dot as a progress indicator is a dot.
You could of course stick a tee in there to save a copy of the make to file in case of problems.
Since you didn't seem to like (neither upvoted or accepted) the shell solution for some unexplained reason, here is a pure perl one:
if (open(X,"make|")) { local($|)=1; while(<X>) { print "."; } close(X); print "\n";}

Comment: I hadn't thought of making the shell do the heavy lifting... interesting.
Comment: @bitbucket: Added a pure perl option to the previous shell answer.
Comment: I had to get some sleep...  I'm testing the solutions today.


What is the correct definition of the $clip(\cdot)$ function?

Question: I was wondering how to properly (or correctly if only one correct definition exists) define the $clip(x,min\_value, max\_value)$ function, which clips $x$ to the range $[min\_value, max\_value]$.
For convenience, take $f(\cdot) = clip(\cdot)$, $a = min\_value$, and $b = max\_value$. I am considering two candidate definitions:
1:
$f(\cdot) = \left\{\begin{matrix}
a\ \text{if}\ x \leq a\\
b\ \text{if}\ x \geq b\\
x\ \text{else}
\end{matrix}\right.$
or 2:
$f(\cdot) = \left\{\begin{matrix}
a\ \text{if}\ x < a\\
b\ \text{if}\ x > b\\
x\ \text{else}
\end{matrix}\right.$
Hence, as I see it, the important detail here is whether to use the $\leq$ and $\geq$ operators or the $<$ and $>$ operators alternatively.
I am wondering which of the two versions above is correct/preferred and if there is any paper I can cite for its definition.
The difference might seem trivial at first glance, but it of course has implications for defining the derivative of the function in the next step.
Comment: Those two definitions are perfectly equivalent. They define exactly the same function $f$.
Answer: Both are correct and exactly identical. In particular $f(a)=a$ and $f(b)=b$ for both your proposed definitions.
Comment: You will *not* get different derivatives. The functions are identical, so the derivatives will be identical. Perhaps your method for determining the derivative is wrong?
Comment: So do I see it correctly that I can choose either definition (since they are equivalent), but depending on my choice I will get distinct derivatives $f'$ (which will be justified by my choice of definition for $f$)?
Comment: Might be. I intended to make a "piecewise" derivative, one for each case (i.e. for x < a, x > b, and else, respectively). But I think I'll better make a separate question out of it then.


Proving estimate of tail of cumulative distribution function of standard normal distribution

Question: I tried to prove the following estimation, with no success:
$$\int_z^\infty e^{-t^2/2}dt= \frac{e^{-z^2/2}}{z}(1-z^{-1}+\mathcal{O}(z^{-2}))$$
Any advice on how to prove this?
Answer: Hint: Integrate by parts the LHS twice, using $\displaystyle\int uv'=uv-\int u'v$ with $v(t)=\mathrm e^{-t^2/2}$ each time. This will show you that the formula in your post should read
$$
\int_z^\infty\mathrm e^{-t^2/2}\,\mathrm dt=\frac{\mathrm e^{-z^2/2}}z\,\left(1-\frac1{z^2}+O\left(\frac1{z^4}\right)\right).
$$
Edit: Here are the two integrations by parts mentioned above.

First integration by parts: $u(t)=-1/t$, $v(t)=\mathrm e^{-t^2/2}$, results in
$$
\int_z^\infty\mathrm e^{-t^2/2}\,\mathrm dt=\frac{\mathrm e^{-z^2/2}}z-\int_z^\infty\frac1{t^2}\mathrm e^{-t^2/2}\,\mathrm dt.$$
Second integration by parts: $u(t)=-1/t^3$, $v(t)=\mathrm e^{-t^2/2}$, results in
$$
\int_z^\infty\frac1{t^2}\mathrm e^{-t^2/2}\,\mathrm dt=\frac{\mathrm e^{-z^2/2}}{z^3}-3\int_z^\infty\frac1{t^4}\mathrm e^{-t^2/2}\,\mathrm dt.$$
Estimate of the remainder term: $1/t^4\leqslant t/z^5$ on $(z,+\infty)$ hence
$$
0\leqslant\int_z^\infty\frac1{t^4}\mathrm e^{-t^2/2}\,\mathrm dt\leqslant\int_z^\infty\frac{t}{z^5}\mathrm e^{-t^2/2}\,\mathrm dt=\frac{\mathrm e^{-z^2/2}}{z^5}.$$
Comment: I dont get your hint. Two times integrating by parts gives: $\int_z^\infty e^{-t^2/2}dt= -ze^{-z^2/2}+\int_{z}^\infty t^2e^{-t^2/2} dt=-ze^{-z^2/2}-\frac{1}{3}z^3e^{-z^2/2}+\int_{z}^\infty\frac{ t^4}{3} e^{-t^2/2} dt$
Comment: Yes, that is because you did not read it: the hint is to consider $v(t)=\mathrm e^{-t^2/2}$, not $u(t)=\mathrm e^{-t^2/2}$.
Comment: Ye I just recognized. Thank you very much  I got it.
Comment: I completed calculations. I think you have to integrate by parts three times. But anyway get your estimation. Thanks again.
Comment: No, twice is enough. See Edit.
Comment: Ah ok I did not manage your estimation and integrated a third time. So this was indeed not necessary. Thank you very much for your effort!


Using jQuery ajax response data

Question: I am using ajax post and am receiving data in the form of html. I need to split up the data and place pieces of the data all over the page. I built my response data to be something like
 Hello there and Welcome

First timer visiting our site eh'
 It is a little more complicated and dynamic but I can figure it out if get this question answered. Thanks
$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    //Need to split data here
            }
        });

Answer: Update: Just realized you should probably do this:
success:function(data) {
    data = $('
').append(data);
    $('#greeting',data).appendTo('#one')
    $('#something',data).appendTo('#two')
}

As you cant use .find properly since it isnt a child but if you append it to an empty node you can. The other alternative would be using .filter
$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    $('#greeting',data).appendTo('#one')
                    $('#something',data).appendTo('#two')
            }
        });

You can extract from data and append where you want to. You can also do something like return JSON instead, and instead of extracting html from html just access the html from an object.
$(data.greeting).appendTo('#one')
$(data.something).appendTo('#two')

The response would have to be like:
({ 'greeting':'html', 'something' :'other html' })

Comment: Thanks for the reply, but for some reason I cannot just grab one tag via id. If it works I grab the entire string.
Comment: Could you elaborate on the JSON solution?
Comment: basically, return JSON from server-side which is a string parsed as Javascript. `json_encode` if you're using php will help. `dataType:'json'` will be needed as well on the client-side.
Answer: Why don't you string the answers together within confirm.php with the | character, then when the string gets returned as the variable data you can split it with datas = data.split("|") and access the individual answers with data[0], data[1], etc.
Answer: (Meder's response will work if you are comfortable with JSON, but regular expressions are probably a little easier and will work just as well for this.)
You will probably need to break up the response text using regular expressions. For example, if the response text is:

 Hello there and Welcome

First timer visiting our site eh'

Then you could use some JavaScript like this:
var greeting = response_text.match(/
.*
/);
var something = response_text.match(/
.*
);

(This site is great for learning about regular expressions: http://gskinner.com/RegExr/)
Comment: Take a look at Coding Horror's take on regex and HTML:

http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html

As they would say, regex and html is a bad idea, but not always. For example, if you were just inserting a welcome message into a couple places after the user logged in (for example, "Welcome, Theopile"), then it doesn't seem like a couple lines of regex is such a big crime.

To the OP - If you have something significantly more complicated than what you example is or if any part of the AJAX response is determined by the user, then Meder is completely right.
Comment: 1. My answer isn't specific to JSON, the JSON was an alternative tip 2. You should *never* use regular expressions to parse html. Only a matter of time before it's prone to failure - jQuery internally parses and grabs with DOM methods which is what you should be doing
Comment: Also, for some reason I can't add a comment to Meder's solution, but if you are using PHP, this site has a great example of using JSON:

http://www.extjs.com/learn/Tutorial:Creating_JSON_Data_in_PHP

Using jQuery ajax response data


Transfering the audio file name to html via javascript based on radio button selection

Question:

<input type="radio" name="qno" value="02" onClick="quesfl(this.value);">2
<input type="radio" name="qno" value="03" onClick="quesfl(this.value);">3
<input type="radio" name="qno" value="04" onClick="quesfl(this.value);">4

<audio controls>
<source id = 'bebo1' src= 'bebo1' type="audio/wav">
Your browser does not support this audio format.
</audio>

I wanted to play a particular audiofile by clicking the corresponding radio buttons. For that I wanted a variable 'bebo1' to get refered at the html audio part for play. This part is not working. The audio files are also available. Please help.
Comment: use something like jQuery to modify the `src` of the audio html tag. `getElementById` will return nothing, you do not have any HTML tag with an `id='bebo1'`.
Answer:
Update the src of source
Load & play audio with load() & play()

Try this:

    <input type="radio" name="qno" value="02" onClick="quesfl(this.value);">2
    <input type="radio" name="qno" value="03" onClick="quesfl(this.value);">3
    <input type="radio" name="qno" value="04" onClick="quesfl(this.value);">4

    <audio controls id="audio1">
    <source id="bebo1" type="audio/wav">
    Your browser does not support this audio format.
    </audio>


Call golang function from Tcl sript

Question: We use a third party Tcl parsing library to validation Tcl script for both syntax and semantic checking.  The driver was written in C and defined a set of utility functions.  Then it calls Tcl_CreateObjCommand so the script could call these C functions.  Now we are in the process of porting the main program to go and I could not find a way to do this.  Anyone know a way to call golang functions from Tcl script?
static int
create_utility_tcl_cmds(Tcl_Interp* interp)
{
    if (Tcl_CreateObjCommand(interp, "ip_v4_address",
                        ip_address, (ClientData)AF_INET, NULL) == NULL) {
        TCL_CHECKER_TCL_CMD_EVENT(0, "ip_v4_address");
        return -1;
    }

    .....
    return 0;
}

Comment: You can call Go functions from C code using [cgo](https://blog.golang.org/c-go-cgo), and a Google search for `go tcl` turned up this as the first result: https://github.com/nsf/gothic
Comment: The new main program will be in go so option 1 is out.  As for the second, I will look deeper but I daublt it will work with our third party tcl library, as it is pretty old
Comment: cgo is going to be the solution to interface with non-Go code no matter what (even the library I linked is a cgo wrapper). You could write your own bindings for your specific library if necessary.
Comment: The callback function registered by `Tcl_CreateCommand` (which might be easier for you to deal with to start with) takes an array of C strings that are the argument words to the function. The client data is just an arbitrary pointer (`void*`) that Tcl passes back without interpretation, and can be NULL if you don't need it; in C++ bindings, it's used to hold a thunk to the object that the command is a method dispatcher for.
Answer: Assuming you've set the relevant functions as exported and built the Go parts of your project as in

Using Go code in an existing C project

[…]

The important things to note are:

The package needs to be called main
You need to have a main function, although it can be empty.
You need to import the package C
You need special //export comments to mark the functions you want callable from C.

I can compile it as a C callable static library with the following command:
go build -buildmode=c-archive foo.go

Then the core of what remains to be done is to write the C glue function from Tcl's API to your Go code. That will involve a function something like:
static int ip_address_glue(
        ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) {
    // Need an explicit cast; ClientData is really void*
    GoInt address_family = (GoInt) clientData;

    // Check for the right number of arguments
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "address");
        return TCL_ERROR;
    }

    // Convert the argument to a Go string
    GoString address;
    int len;
    address.p = Tcl_GetStringFromObj(objv[1], &len);
    address.n = len; // This bit is hiding a type mismatch

    // Do the call; I assume your Go function is called ip_address
    ip_address(address_family, address);

    // Assume the Go code doesn't fail, so no need to map the failure back to Tcl

    return TCL_OK;
}

(Credit to https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf for providing enough information for me to work out some of the type bindings.)
That's then the function that you register with Tcl as the callback.
Tcl_CreateObjCommand(interp, "ip_v4_address", ip_address_glue, (ClientData)AF_INET, NULL);

Theoretically, a command registration can fail. Practically, that only happens when the Tcl interpreter (or a few critical namespaces within it) is being deleted.

Mapping a failure into Tcl is going to be easiest if it is encoded at the Go level as an enumeration. Probably easiest to represent success as zero. With that, you'd then do:
GoInt failure_code = ip_address(address_family, address);

switch (failure_code) {
case 0: // Success
    return TCL_OK;
case 1: // First type of failure
    Tcl_SetResult(interp, "failure of type #1", TCL_STATIC);
    return TCL_ERROR;
// ... etc for each expected case ...
default: // Should be unreachable, yes?
    Tcl_SetObjResult(interp, Tcl_ObjPrintf("unexpected failure: %d", failure_code));
    return TCL_ERROR;
}

Passing back more complex return types with tuples of values (especially a combination of a success indicator and a "real" result value) should also be possible, but I've not got a Go development environment in order to probe how they're mapped at the C level.
Comment: It's the mapping of errors that makes this all not as smooth as it should be; `GoInt` is actually the same type as `Tcl_WideInt`, and `GoFloat64` is known as plain old `double` in the Tcl API; those are trivial to handle. The code above indicates how to handle `GoString`. But errors… Tcl's a language that conceptually uses exceptions (though not in a C++ sense!) and Go very much isn't (and I don't know if the conventions for error handling are universally followed) so there's quite an impedance mismatch there.
Comment: Also, _be aware that Tcl cares about threads!_ A Tcl interpreter is strongly bound to a single POSIX thread (it's a many-to-one relationship; a thread can have multiple interpreters) in a very deep way inside its implementation. When calling into Tcl from Go, you **need** to respect that _or_ use `Tcl_ThreadQueueEvent()` to asynchronously post an event from elsewhere, which can get a bit complicated…

Call golang function from Tcl sript


How do I catch the special fish?

Question: Just recently, I tried to catch the Liege of the Lake for quite some time with no success. Hidden fish don't seem to show up on the fish radar, and I had a few times where I filled the encounter bar entirely only for the hidden fish to leave and hide itself in another part of the fishing spot. This made me wonder: are there some special techniques for finding these fish, let alone catching them?
Answer: Sooo...I just caught it finally last night...it is in the Vesperpoo, andl you will need to first get plenty of Dragon's Beard fishing line, the reel and rod from the shop next to that spot (which are like 18000 gil combined), and a green lure which I'll be honest I don't remember the name of and I'm nowhere near my game at the moment, sorry...but you may also want to be at level 7 skill level for fishing as well, since you get linger lasting line.
The key is you need to camp at the haven near that, and when you do there will be a cut scene where Gladio will ask you in the middle of the night like a weirdo if you wanna wake up at the ass crack of dawn to catch that legendary fish...it then becomes a tour, and i believe you will need to also clear the entire vesperpool before it will engage you...take note, it doesn't appear on the HUD, and you will simply have to keep casting til it takes interest in your lure, and then entice it to bite...
After that, once you've got him hooked, you really really REALLY need to be patient...it took me about 4 tries, and I had been fishing for almost 3 hrs to get my skill up, so I was kind of in a groove by that point...his stamina is off the charts and you can only reel when he stops struggling, so you'll need to pay special attention to line tension and also catch the jumps to, if you know what I mean...his "attack" will deplete your line very quickly if you don't just go with the flow and take your time...get ready for 20 minutes of battle fishing, and good luck!
Ps-I tried to upload the photo I took so you could see what your catch would be but it wasn't working...it's gratifying if you like a challenge though
Answer: The dreaded lake leige. My advice is get the best rod/reel that you can. Best line too. This one is extra hard because it's almost always vibrating. Never hold the reel button down. I slowly tap it because I know it's going to fight/turn as soon as I do. Patience is key. Wait for the fish to jump and use the direction. It doesn't look like much but every single time you hook it it comes in a little closer.

How do I catch the special fish?


Labeling edges of a cube with + and - so each face has an odd number of +s.

Question: I am looking for a specific proof, using tools from cellular homology, of the following theorem.

Let $I^n$ be the standard $n$-dimensional hypercube with its standard cellular structure. There exists a labeling of the edges in $I^n$ from the set $\{+,-\}$ such that there are an odd number of $+$-labelled edges incident to each face.

I recall seeing a proof a while ago now which used the fact that $H_\bullet(I^n,\mathbb{Z}_2)$ is trivial, where $H_\bullet(-,\mathbb{Z}_2)$ is mod $2$ cellular homology. Presumably by considering the image of the boundary map $\partial\colon C_2\rightarrow C_1$ on the $2$-cells, although it's not obvious to me how to restate the theorem in terms of this boundary map.
I wonder if anyone could reproduce this particular proof? (I'm aware of more basic methods for proving this theorem, such as induction on $n$.)
Answer: Recall that $I^n$ has trivial cohomology in all dimensions as it is a contractible space. In particular, $H^i(I^n,\mathbb{Z}_2)=0$ for all $i\geq 0$. We'll rename the $+$ and $-$ in the question to $1$ and $0$ respectively and consider these as labels from the coefficient group $\mathbb{Z}_2$ attached to the various face-types of the cell complex defined by $I^n$.
Consider the cochain $\alpha\in C^2$ which assigns to each face in $I^n$ the coefficient $1$. Because the second cohomology group of $I^n$ over $\mathbb{Z}_2$ coefficients is trivial, the coboundary map $\delta^1\colon C^1\to C^2$ has its image equal to the kernal of the coboundary map $\delta^2\colon C^2\to C^3$. We note that $\delta^2(\alpha)=0$ because there are an even number of $2$-cells (for $n\geq 3$) and so there must exist a $\gamma\in C^1$ such that $\delta^1(\gamma)=\alpha$. We see that $\gamma$ is an assignment of $0$s and $1$s to the edges of $I^n$, and because $\delta^1(\gamma)=\alpha$, there must be an odd number of $1$s on the boundary of each face. It follows that $\gamma$ is the required assignment.