R: partial sort of matrices by largest elements to index matrix and value matrix?

Question: Suppose a large sparse adjacency matrix. I want two matrices:

1st value matrix where first column for the largest element, second column for the second largest element and third for the third largest element
2nd index matrix where first column for the index of the largest element, second column for the index of the second largest element and third for the index of the third largest element

where the partial sort per vector is probably most efficiently done with sort's partial directive, like here https://stackoverflow.com/a/2453619/164148.
Does there exist some ready solutions for the partial sort of matrices by its largest elements to corresponding value/index matrices?
Answer: max.col works for the maximum position while the order method below works for any number of maximal positions: we order the index matrix to descreasing order and pick the wanted count of largest positions. Similar to max.col, we could use which.max function
<code>> which.max(c(100,1:10))
[1] 1
> max.col(c(100,1:10))
 [1] 1 1 1 1 1 1 1 1 1 1 1
</code>
and repeatedly finding the maximal position until not needed. We will next concentrate on the order method. Alternative A shows a case where the value matrix and the index matrix are equal. Alternative B shows a case where the value matrix and the index matrix are not equal.
Alternative A showing a case with index matrix equal to the value matrix.
<code>> set.seed(123); r<-10; c<-10; m2 <- matrix(rbinom(r*c,70,0.5),r,c)
> m2
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]   35   37   41   40   37   34   36   31   35    33
 [2,]   31   36   38   31   33   30   42   38   38    35
 [3,]   39   34   31   43   28   32   37   28   35    32
 [4,]   34   33   37   29   38   37   44   33   42    39
 [5,]   39   41   40   45   34   39   34   33   38    30
 [6,]   32   34   35   30   38   29   33   33   32    31
 [7,]   40   32   34   39   34   28   39   37   35    41
 [8,]   39   37   33   36   27   38   37   33   32    38
 [9,]   35   40   36   39   40   25   31   32   40    38
[10,]   29   41   39   35   34   38   34   34   29    38

> t(apply(m2, 1, function(x) order(x,decreasing=T)[1:3]))
      [,1] [,2] [,3]
 [1,]    3    4    2
 [2,]    7    3    8
 [3,]    4    1    7
 [4,]    7    9   10
 [5,]    4    2    3
 [6,]    5    3    2
 [7,]   10    1    4
 [8,]    1    6   10
 [9,]    2    5    9
[10,]    2    3    6
</code>
that is the index matrix and its value matrix, in this case, is the same.
Alternative B showing where the index matrix not equal to the value matrix.
max.col returns the maximum position of each row of a matrix, breaking ties at random, but it does not have the partial directive
<code>require(quanteda)
mytext <- c("Let the big dogs hunt honor", "No holds barred, it is a honor child child child.", "My child is an honor student")
myMatrix <-dfm(mytext, ignoredFeatures = stopwords("english"), stem = TRUE)
> myMatrix %*% t(myMatrix)     #Tells how sentences are related to each other
# 3 x 3 sparse Matrix of class "dgCMatrix"
# text1 text2 text3
# text1     5     1     1
# text2     1    12     4
# text3     1     4     3
> t(myMatrix) %*% myMatrix     #Tells how words are related to each other
# 9 x 9 sparse Matrix of class "dgCMatrix"
# let big dog hunt honor hold bar child student
# let       1   1   1    1     1    .   .     .       .
# big       1   1   1    1     1    .   .     .       .
# dog       1   1   1    1     1    .   .     .       .
# hunt      1   1   1    1     1    .   .     .       .
# honor     1   1   1    1     3    1   1     4       1
# hold      .   .   .    .     1    1   1     3       .
# bar       .   .   .    .     1    1   1     3       .
# child     .   .   .    .     4    3   3    10       1
# student   .   .   .    .     1    .   .     1       1
#
> max.col(t(myMatrix) %*% myMatrix)
[1] 5 2 2 3 8 8 8 8 9
>
> max.col(myMatrix %*% t(myMatrix))
[1] 1 2 2
</code>
and
<code>> n<-length(myMatrix);max.col(t(myMatrix) %*% myMatrix,partial=n-1)
Error in max.col(t(myMatrix) %*% myMatrix, partial = n - 1) :
   unused argument (partial = n - 1)
</code>
where unfortunately partial directive is not defined in the max.col command. So we test the method A:
<code>> mytext <- c("Let the big dogs hunt honor", "No holds barred, it is a honor child child child.", "My child is an honor student")
> myMatrix <-dfm(mytext, ignoredFeatures = stopwords("english"), stem = TRUE)
> aa<- myMatrix %*% t(myMatrix)
> aa
3 x 3 sparse Matrix of class "dgCMatrix"
      text1 text2 text3
text1     6     1     1
text2     1    18     5
text3     1     5     6
> t(apply(aa, 1, function(x) order(x,decreasing=T)[1:3]))
      [,1] [,2] [,3]
text1    1    2    3
text2    2    3    1
text3    3    2    1
</code>
that is correct and other way around we get
<code>> aaa<- t(myMatrix) %*% myMatrix
> aaa
18 x 18 sparse Matrix of class "dgCMatrix"
   [[ suppressing 18 column names 'let', 'the', 'big' ... ]]

let     1 1 1 1 1 1 . . . . . . .  . . . . .
the     1 1 1 1 1 1 . . . . . . .  . . . . .
big     1 1 1 1 1 1 . . . . . . .  . . . . .
dog     1 1 1 1 1 1 . . . . . . .  . . . . .
hunt    1 1 1 1 1 1 . . . . . . .  . . . . .
honor   1 1 1 1 1 3 1 1 1 1 1 2 1  4 1 1 1 1
no      . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
hold    . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
bar     . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
,       . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
it      . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
is      . . . . . 2 1 1 1 1 1 2 1  4 1 1 1 1
a       . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
child   . . . . . 4 3 3 3 3 3 4 3 10 3 1 1 1
.       . . . . . 1 1 1 1 1 1 1 1  3 1 . . .
my      . . . . . 1 . . . . . 1 .  1 . 1 1 1
an      . . . . . 1 . . . . . 1 .  1 . 1 1 1
student . . . . . 1 . . . . . 1 .  1 . 1 1 1
> mmm <- t(apply(aaa, 1, function(x) order(x,decreasing=T)[1:3]))
        [,1] [,2] [,3]
let        1    2    3
the        1    2    3
big        1    2    3
dog        1    2    3
hunt       1    2    3
honor     14    6   12
no        14    6    7
hold      14    6    7
bar       14    6    7
,         14    6    7
it        14    6    7
is        14    6   12
a         14    6    7
child     14    6   12
.         14    6    7
my         6   12   14
an         6   12   14
student    6   12   14
</code>
and the corresponding value matrix
<code>> t(apply(mmm, 1, function(x) colnames(aaa)[x]))
        [,1]    [,2]    [,3]
let     "let"   "the"   "big"
the     "let"   "the"   "big"
big     "let"   "the"   "big"
dog     "let"   "the"   "big"
hunt    "let"   "the"   "big"
honor   "child" "honor" "is"
no      "child" "honor" "no"
hold    "child" "honor" "no"
bar     "child" "honor" "no"
,       "child" "honor" "no"
it      "child" "honor" "no"
is      "child" "honor" "is"
a       "child" "honor" "no"
child   "child" "honor" "is"
.       "child" "honor" "no"
my      "honor" "is"    "child"
an      "honor" "is"    "child"
student "honor" "is"    "child"
</code>
where the value matrix is not equal to the earlier index matrix.


Live Ubuntu USB doesnt works on newer systems

Question: What is the problem?

The USB when used with a Dell laptop (Windows 7) or a Sony Vaio (Windows 7) works perfectly. I just plug it in and start the system, and instead of windows, it boots in Ubuntu as expected. However, when I use it with my new Hp laptop (Windows 10) it just boots to Windows 10. Well, I tried another way, used "Advanced Recovery Options" and selected "Boot from USB". But that said that there was no such device found.

How I created the USB?

I flashed the installer to a spare 8Gb USB using Balena Etcher and then booted into Ubuntu Trial using the Sony Vaio laptop. There I started the installer and installed Ubuntu to a 32Gb USB.
Comment: You haven't mentioned what release of Ubuntu
Comment: Please tell us more about 1. the problematic computer: Brand name and model; 2. the iso file (complete name of the file (version (20.04.1 LTS?), flavour (Kubuntu, Lubuntu ... or standard Ubuntu?), architecture (64-bit is necessary in UEFI mode)); 3. You may need to turn off secure boot to make the computer accept booting from USB.
Comment: Also, have you tried other methods like Rufus or [Universal USB Installer](http://www.pendrivelinux.com/universal-usb-installer-easy-as-1-2-3/)?
Answer: Simplified Full Install of Ubuntu 20.04 to USB that Boots BIOS and UEFI Mode
It sounds like you may have created the USB in BIOS boot mode and it won't boot on your UEFI mode computer. To boot your USB in both modes tales a little more work.

Download BIOS/UEFI Template: https://phillw.net/isos/linux-tools/uefi-n-bios/dd_grub-boot-template-for-uefi-n-bios.img.xz

Flash image to target USB using Win32DiskImager, Rufus, mkusb, balenaEtcher, etc.

It is recommended to unplug any internal drives especially when installing in UEFI mode. Creating while booted in BIOS mode saves a few steps.

Boot Live Installer USB, and insert Target USB.

Start install process, select: Language, Keyboard, Wireless, Updates and Something Else.

Select Target USB for Bootloader installation.

(Optional Data Partition), Select the empty space on the Target drive and click the plus sign to create a FAT32 partition with mount point "/Windows". Leave at least 6GB empty space for root partition.

Select the empty space on the Target drive and click the plus sign to create an ext4 partition with mount point "/".

Select Install now, confirm partition to be formatted, enter location, name and password.

When install is complete copy /boot/grub/grub.cfg from root partition to overwrite /boot/grub/grub.cfg on boot,esp partition.

If created using Rufus/Etcher or in UEFI mode reinstall GRUB for BIOS boot:
sudo mount /dev/sdx3 /mnt
sudo grub-install --boot-directory=/mnt/boot /dev/sdx

Thanks to Sudodus for the mkusb based BIOS/UEFI Template
Comment: Thanks a lot pal, it worked out like a charm!!!
Well, only thing left is that it wont boot directly... First Windows > Advanced Recovery > Boot from external > EFI drive.

But then that it works, it's awesome.


"Unable to mount Android, Error initialising camera: -60: Could not lock the device" when connecting a Samsung Galaxy S2 via MTP

Question: Whenever I connect my Samsung Galaxy S2 phone (running Android 4.0) via USB using an MTP connection one of two messages always pops up, either:
Unable to mount Android: Error initialising camera: -60: Could not lock the device

or: Unable to mount Android: Error initialising camera: -53: Could not claim the USB device

The phone however does mount successfully and I can add and delete files etc. I would just like to understand what the error message means, googling only seems to bring up descriptions of people mounting digital cameras and this doesn't seem relevant for a mobile phone.
Comment: I thought MTp didn't work on CM9, works fine in MIUI and Samsung Stock ROMs.
Comment: @UriHerrera I found it the other way round, MTP works fine with CM9 but not with stock
Comment: Before going too far with this. I suggest you create a new user (I'll call it newuser here) Logon as newuser and try connecting your MTP device. As "myself" I get that same error, as newuser , it works. I think something happened in the past copying $HOME around from one install to another. The 'file' .gvfs gets messes up, but it seems to be more than that.
Comment: Might there be a virtual machine running, by any chance? I got this error too when running Windows 7 as guest. The Win7 guest was somehow grabbing the camera before Ubuntu did and thus foiling up the permissions. After I disconnected the camera from Windows things proceeded normally in Linux.
Comment: @MarisanoJames I started to get the second error message after I upgraded to Ubuntu 14.04. I did not get any error messages in Ubuntu 12.04. I always had Win 7 in virtual machine.
Answer: I found that when I was plugged into a usb 3.0 port I got the following messages:
<code>usbfs: USBDEVFS_CONTROL failed cmd gvfs-gphoto2-vo rqt 33 rq 102 len 0 ret -71
</code>
But when I plugged into a usb 2.0 port it worked.
Comment: this made it for me
Answer: Try this : http://www.tuxtrix.com/2011/07/how-to-access-samsung-galaxy-s-ii-usb.html . It worked for me
Note : In Android 4.0 with TW launcher, you need to click on "more" to get the option.
Comment: Thanks for putting the effort in to answer. I know how to connect the phone with mass storage, my question was related to why does the error message appear and what does it when connecting via MTP
Answer: I get this as well, but to be honest it's a bug and there's not much to question about it - but instead report it. Should not happen.


Kitchen faucet occasionally doesn't allow water to flow

Question: My faucet in the kitchen works 99% of the time but occasionally when you turn it on 0 water comes out. When this occurs the water still works in the bathroom, and in other apartments. (I'm the middle unit in a triplex)
This just started happening four days ago and I've lived here for six years. It's happened maybe five times in the past four days. The plumber says it's because the pipes are too narrow but I don't think the pipes would've gotten drastically narrower suddenly four days ago.
I've experimented with turning on all the other faucets and it does not cause this cut off to happen. I really can't figure out when it will cutoff, it doesn't seem tied to anything going on.
The plumber says it's unfixable unless we rip up and replace the whole system. I just don't get how this problem could have not been happening at all and now it's a notable disruption all of a sudden. Could there be something else causing it? He didn't check on anything, and I've seen things about switches getting triggered by accident or converters… could it be one of those things, or something else?
Answer: Most faucets have an aerator screwed on the end that helps smooth out the water flow and prevents/reduces splashing when the water hits the bowl. If there's any "crud" in the water pipes (usually rust from iron piping or mineral buildup from hard water), it can, on occasion break free and flow through the pipes. It will get stuck in the aerator, reducing water flow. It sounds like this is what's happened to you.
Simply unscrew the aerator (righty-tighty, lefty-loosey) from the faucet. Look for a collection of small particles in there. Turn it upside down and bang it on the bottom of the sink to knock the majority out, then run water through it while still upside down to rinse it out. If there's still anything left stuck in there, you may need to use a toothpick or a metal pick to get it out.
Screw the aerator back on and all should be good.
Your flow is likely to be intermittent because the crud hasn't built up and settled in place - it's still loose. Each time you turn the faucet on, water pressure hits the crud and moves it around. If it's arranged with "holes" in the crud, you'll get water, if it manages to make a solid cover over the aerator, no water...
It's possible that the aerator may be damaged. If that's the case, you should be able to find a replacement.

In a comment, the original question seems to have left out the critical detail that there is a pull-out sprayer integrated into the faucet.
I just looked at the one in my kitchen, and it appears that the head can be unscrewed from the hose. There may be a filter somewhere close to that junction that could be cleaned out.
It could be that forcing water (use the tub spout) backwards from the "normal" output end to the hose attachment end could force whatever bits of crud have collected in the spray head out and return full functionality.
It could be that this faucet does not have a removable head in which case replacing the head and attached hose, or the full faucet are the only options.
Comment: I'm trying to get the landlord to send a new plumber and I mentioned this possibility to her. My faucet has a kind of hose thing on it with a head that adjusts between types of spray, and I'm not sure where in there I could unscrew to see this aerator? I can picture it on a normal faucet but I don't see anything easy to access on this one. My friend said I should be careful because if I try to fix it I might make it worse and the landlord can then make me pay. Also, fwiw, now sometimes when we try the faucet there's a loud knocking sound and a trickle of water comes out. Still quite rare.
Comment: @LindaBoden having a pull-out sprayer integrated into the faucet is a _key_ bit of information that you left out of your original question. I've updated my answer to address that.


Facebook SSL certificates for social Plugins?

Question: FB Documentation says that SSL certificates shall me mandatory for Canvas Apps.
Is it also mandatory for FB Social Plugins e.g. Like, Share
Answer: No, it is not necessary.
It's required only for Facebook Apps.
Comment: Thanks, my application uses FB for intial login creation and then uses the access_token for performing future actions. I guess it should not be mandatory for me to buy a SSL certificate, Right
Comment: Right now the SSL certificate is only required for apps running inside a Facebook iframe. I assume you have a web application run on your site so in this case you are safe for now
Comment: Yeah i was thinking on same lines. Thanks for clarification
Answer: Social Plugins will screws up if you share media content on your page like video, flash or Audio. It will not play anymore on the wall where it shard.
Media can only shared if your Blog Webpage works with SSL .


Yahoo Callback Domain Issue

Question: While creating a new app on Yahoo Developers Network the field (i.e. Callback Domain) is not accepting any URL having slash ('/') in it, but previously it is taking the URLs with slashes.
Error thrown:

Application Create failed. Scopes creation failed when creating App:
  507 - {"domain_name":{"errors":[{"code":2402,"message":"Invalid domain
  name: mobile.local.com/"}]}}

My redirect URL contains path for a sub-page and it is not possible for me to remove all the slashes from my callback domain URL.
What can I do in such case?
Please help.
Comment: I get ```Invalid Developer Credentials received``` - Did you get that error by an chance? Can't believe it's so hard to just register an app lol
Comment: Ok I just created a new Yahoo account and I can now create/register apps. I think the key is to create a Yahoo account from scratch, don't use one the alternative login methods (ie: signing in via Google).
Answer: Finally after a lot of research i found out that you just need to provide your domain only in the call back domain field and yahoo will work fine.
When a request is received the domain of redirect uri in the request is matched with the value saved in callback domain field and if it matches then user data is sent on that url.

Yahoo Callback Domain Issue


How can I auto-skip a certain disk on boot up?

Question: I'm running dual boot Windows 10 and Ubuntu. I have several disks including a WD SSD which I only for Windows (NTFS) and don't need to mount it in Ubuntu.
However, since installing this new disk, every time I boot Ubuntu it spends several minutes checking the disk before finally giving me the Gnome/Ubuntu log in screen. I'd like to continue check the other disks, but skip this one, as it's Windows' responsibility.
I have tried removing/commenting it from fstab, but that doesn't make any difference. Is there a way to automatically skip, rather than having to press Ctrl+C every time?
This is what my fstab currently looks like:
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda6 during installation
UUID=d4ae91d8-28db-476f-95f6-27d6cabbb816 /               ext4    errors=remount-ro 0       1
# /boot was on /dev/sda5 during installation
#UUID=edb1d7c4-7f64-494b-970a-30e19e551a99 /boot           ext4    defaults        0       2
# /raptor was on /dev/sdb2 during installation
UUID=7583d83a-c588-474b-8523-3d501d2e8413 /raptor         ext4    defaults        0       2
# /win_C was on /dev/sda1 during installation
UUID=6E4EABC64EAB8605 /win_C          ntfs    defaults,umask=007,gid=46 0       0
# /win_d was on /dev/sdb1 during installation
UUID=EA9CDD939CDD5AA1 /win_d          ntfs    defaults,umask=007,gid=46 0       0
# /win_e was on /dev/sdc1 during installation
UUID=7A4E15745CE2076E /win_e          ntfs    defaults,umask=007,gid=46 0       0
# /win_f was on /dev/sdd1 during installation
UUID=A8DC8E26DC8DEF3E /win_f          ntfs    defaults,umask=007,gid=46 0       0
# swap was on /dev/sdb3 during installation
UUID=674fa812-da28-43c1-b9de-d805551f88a6 none            swap    sw              0       0
# Manually added WD SSD 500GB (mostly used for windows)
UUID=7C5E67055E66B792 none   ntfs defaults,noauto 0  0

# Keep /tmp in RAM (faster and less SSD wear)
# http://www.howtogeek.com/62761/how-to-tweak-your-ssd-in-ubuntu-for-better-performance/
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0
# NAS on zotac
192.168.50.186:/nas/shared /zotac-shared nfs rsize=8192,wsize=8192,timeo=14,intr,nfsvers=3

UUID=edb1d7c4-7f64-494b-970a-30e19e551a99  /boot       ext4    defaults      0       2

Comment: To clarify I've edited the question. The disk checks occur after the GRUB menu and before the Gnome desktop login screen. I think this is normal, but in my case they take a very long time.
Comment: I suggest you post the contents of your /etc/fstab
Answer: The simplest solution would be to use the noauto flag in your /etc/fstab file. This will prevent the OS from mounting a given partition completely.
For example:
/dev/sda3    none    ntfs-3g    defaults,noauto    0    0

or:
UUID=b72e8406-34e8-4e38-a422-e4ab6e35e6b8 none    ntfs-3g    defaults,noauto    0    0

If you choose to do this by UUID, you can list the values for each mount point in your system with sudo blkid, which will return something like:
/dev/nvme0n1p3: UUID="b72e8406-34e8-4e38-a422-e4ab6e35e6b8" TYPE="swap" PARTUUID="4b9f203e-de2c-4cc0-a9a6-2ac423b1b0e9"
/dev/nvme0n1p2: UUID="b33696cc-f2db-4dd4-9a63-15028cf5afc4" TYPE="ext4" PARTUUID="cd2a90a1-5a6b-4468-a4da-0a2f7c2a8f54"
/dev/nvme0n1p1: UUID="D3F2-9195" TYPE="vfat" PARTUUID="4e505bb1-c12b-4c71-afdf-42ac9a2f721b"
/dev/mmcblk0p1: UUID="dd5dffcf-9e3b-43eb-82a2-36137fc249be" TYPE="crypto_LUKS" PARTUUID="7688e21d-c1d3-4f02-95ac-5e816e2c1e05"

Note: I've removed all the squashfs records from the list just to keep it clean.
This should give you a faster boot time while also ensuring the Windows-only partitions are not visible in the Ubuntu UI.
Comment: Thanks, this looks like it should work but, for me at least, it doesn't. Is there a log or something I can look at to see what is going on?
Comment: The information in `/var/log/syslog` should let you know if something's not quite right.
Answer: Comment the line with the disk that you wanted to skip in /etc/fstab using
sudo nano /etc/fstab

Then find the line that you want to comment and put an asterisk(*) at the beginning.
Comment: Ha, sorry, my bad. I thought the comment said command lines.
Comment: According to this, comment lines start with a hash character (#). https://www.man7.org/linux/man-pages/man5/fstab.5.html
Comment: The hash (#) character signifies root access. When you access root with sudo su, there is a hash at the beginning of every line. However, when copying and pasting, it would not work with the hash pasted, as it would fail as an error (because the hash already exists)
Comment: Jeff we're talking about inside an fstab file, which the link above explains. I think the hash (#) you're talking about signifies root access at the command line.


Registration form [FOSUserBundle]

Question: I built my own registration form and when I try to register users it doesn't react. Everything with FOSUserBundle works good. Also when I use the default FOSUserBundle registration form it works and it saves all the data in my table. Should I use only the default form from FOSUserBundle or what?
Here is my form that I made:
<form action="{{ path('fos_user_registration_register') }}" method="post">

        <input type="text" name="name"/>

        <input type="text" name="surname" />

        <input type="text" name="email"  />

        <input type="password" name="password"/>

        <input type="submit" name="submit" value="Sign up"/>

</form>

Comment: please be more precise when asking a question ... it doesn't react can hardly be anything ... you can't submit the form, it times out, it does not do what you want?
Answer: You need to pass the registration form from the controller ( if you are overriding the controller ) to the view in order to have the csrf token available. Otherwise the form will not validate.
In order to overwrite FOSUserBundle's standard registration form use bundle inheritance.
Please read FOSUserBundle's documentation chapter Overriding Default FOSUserBundle Forms.
If you just want to add "name" and "surname" to your user entity, add the properties and the mapping information and afterwards add the fields to the overriden form class. then override the registration form template provided by FOSUserBundle if you need further  changes in there.
Comment: so what i think is wrong, so i must use only the form from the controller?
Comment: you can override the default form or override the whole registration controller that's your choice. but if you just want to add "name" and "surname" to your user entity you only have to override the form and the template and add the properties+mapping information to your user entity.
Answer: Read documentation how you can override registration controller if you need extend functionality. Or you can just override standard form to add additional fields.

Registration form [FOSUserBundle]


Matlab, legends in a barplot

Question: I'm having a for loop which creates a barchart with 4 bars on the basis on 2 vectors.
two bars are red and two are green. Red and green means two different things. I would like to show that in a legend, but how am I going to do it. I've tried several things but nothings seems to do what i want. My latest output gave a legend like this:`
'red color' Wrong answer
'red color' Wrong answer
'green color' right answer'
'green color' right answer

as you can see the output gave me 4 legends but I just want 2.
How can fix this:
R = [-1 -1 1 1];
T = [2.0741 2.1521 2.9529 2];
figure;
% Barchart
for i=1:length(T)
   h = bar(i, T(i));
     if i == 1 hold on, end
     if R(i) == -1
       col = 'r';
       legendInfo{i} = ['Wrong answer '];
     else
       col = 'g';
       legendInfo{i} = ['Right answer '];
     end

     set(h, 'FaceColor', col)

end

set(gca,'xTick',1:length(R),'xTickLabel',1:length(R))
xlabel('question number.');
ylabel('time per question')
legend(legendInfo)

Answer: You can pass handles to legend to specify which entries you want to have:
R = [-1 -1 1 1];
T = [2.0741 2.1521 2.9529 2];
figure;
% Barchart
for i=1:length(T)
   h(i) = bar(i, T(i));
     if i == 1 hold on, end
     if R(i) == -1
       col = 'r';
       legendInfo{i} = ['Wrong answer '];
     else
       col = 'g';
       legendInfo{i} = ['Right answer '];
     end

     set(h(i), 'FaceColor', col)

end
set(gca,'xTick',1:length(R),'xTickLabel',1:length(R))
xlabel('question number.');
ylabel('time per question')

[~,legendsIWant]=unique(R)
legend(h(legendsIWant),legendInfo(legendsIWant));

Comment: Thanks a lot, It works just great. I did not know it could be solved in that way..
Comment: I was wondering if you had a link to a place where I can read more about this legendIWant ?
Comment: legendsIWant is a simple variable, it contains `[1,3]`, which means that the first and third box should show up in the legend. Instead of hard-coding this numbers, I used the already existing variable R to determine it. `h(legendsIWant)` simply selects the first and third handle to the graphics object, and `legendInfo(legendsIWant)` selects the first and third text.

Matlab, legends in a barplot


python command on terminal not working

Question: Same question found here but without a valid solution. The problem is that typing python in the terminal produces:
The program 'python' can be found in the following packages:
 * python-minimal
 * python3
Try: sudo apt install <selected package>

In fact, $ which python returns nothing. Additional information:
~$ echo $PATH
/usr/local/cuda-8.0/bin:/home/fontana/bin:/home/fontana/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

By default python should point to python2.7 in /user/bin. If I type python2.7, python runs normally. How to restore the default behavior when typing python in the terminal?
EDIT: Potential source of the problem: I've recently installed python 3.4.6 (in /user/local/bin) using the following commands. Than I tried to reinstall python 3.4.6 since there was a problem with pip now fixed.
./configure
make
make test
sudo make install

Comment: The answer is in the question: Reinstall python-minimal.
Comment: DO NOT change the system version of Python. You will break your system horribly. Change it back. If you must add a new version of python, then install it manually instead of using packages.
Comment: The next question is then always: what did you do that might have caused this?
Comment: I've edited the post.
Comment: I'm not capable to restore the previous situation. My impression is that pointing python (when typed in the terminal) to /usr/bin/python2.7 should do the trick, but I don't know how (maybe using export PATH?).
Comment: You point python using an ordinary symlink - see `man ln`. However, that's merely one tusk of the elephant of damage perhaps lurking, waiting to be discovered at unfortunate times. If you lack the skill to undo the damage, then backup your data and reinstall...having learned a valuable lesson.
Comment: I have solved the problem using `sudo apt install python-minimal`
Comment: So exactly what Ubuntu mentioned as solution and user535733 said 15 hours earlier :-)
Comment: @user535733, Could u rewrite the solution as an answer?
Answer: I fixed the problem with
sudo apt install python-minimal

as suggested in the warning message. I have decided to install python-minimal rather than python3 since the latter was already working smoothly in the terminal.
Comment: it seems python-minimal is python 2.7. However, I would like to install python 3.X

python command on terminal not working


How do I op a user who has spaces in their username on a Minecraft server?

Question: I have a Minecraft server which allows Bedrock clients, I would like to make one of our players who has a space in their Gamertag an operator.
We tried op "user name", however this throws exceptions harder than my lawyer ;P
Any ideas? :)
Answer: The quotation mark method seems like it would work, but it doesn't in /op. However there are still other methods that work. As the other answer mentions, you will be able to get a player UUID from that person in the chat.
But what if the player hasn't chatted recently?
If your player hasn't chatted recently, you won't see their username in chat and won't be able to get a UUID. Sure, you could just ask them to send a chat message, but that will get tricky when you're trying to deop a person, because they can resist you by simply not sending any chat messages.
But, there is yet another method that is the most elegant:

Specified the player to be grant op to.
In Java Edition, must be a collection of game profiles (player profiles), which can be a player name (must be a real one if the server is in online mode), or a player-type target selector.

A target selector (@p, @r, @a, @e) can also be used to select a player. And target selectors have a name argument to select targets by name, and unlike /op directly? It allows " syntax.
This is the command to use:
op @a[name="a name with spaces and \"quotation marks\""]

Comment: Nice one, I like the bit about the double-quoted string too; cheers!
Comment: I imagine this still suffers from the UUID spoofing trick? Seeing as it will lookup the UUID from the name? I assume... *shrug*
Comment: @SeanAirey I'd doubt the second method would be
Answer: If you hover over the user's name in chat, you'll see their UUID, e.g. 584fb77d-5c02-468b-a5ba-4d62ce8eabe2. You can use this in the /op command instead of a username: /op 584fb77d-5c02-468b-a5ba-4d62ce8eabe2
Comment: **SECURITY ALERT**: Assuming this is a server running GeyserMC/Floodgate, you open yourself to potentially OP-ing (you can't OP one without OP-ing the other) the owner of the UUID (if one exists); [do a lookup of the UUID](https://namemc.com/) first, though the chances of it happening might be miniscule, it is still a security risk.
Comment: @aytimothy as long as the UUID generation code is actually random, you're more likely to have cosmic rays give someone OP than for a UUID collision to happen.
Comment: @aytimothy I don't understand that response. To clarify, I am asking whether the security risk you just pointed out is present in my answer also.
Comment: @Polygnome Bedrock players will be assigned a random UUID as they don't have a Java one, which may be the same as an actual Java player's UUID. It's so unlikely that I'd say it would never happen (the person would have to join your server, even if they manage to match the UUID), but I guess the chance is still there.
Comment: @aytimothy I'm confused. Isn't OP-ing the owner of the UUID the exact goal?
Comment: @ExpertCoder14 You answered second.
Comment: ...can't really hover using a console or automation. But then you could scroll back the log?
Answer: You could try adding to your ops.json:
{
    "uuid": "61c1bca3-2d8a-4756-a4fb-26fe22f3b000",
    "name": "Damemon",
    "level": 4,
    "bypassesPlayerLimit": false
}

Replace 61c1bca3-2d8a-4756-a4fb-26fe22f3b000 (UUID) and Damemon (username) with your friend's Floodgate UUID and name. The level and bypassesPlayerLimit can be left as-is.
Answer: Put the first letter in their name in and press Tab, or alternatively use their player ID.
Comment: What first letter? Your second option is already given by someone else, it seems.
Comment: first solution still won't work


use php inside JavaScript

Question: I have an ajax function that post to an PHP file.
Now since I'm using WordPress I can use the get_url function so I don't need to hard code the entire URL.
The WordPress function is an PHP so I'm trying to use PHP inside the ajax post. But it wont do the trick.
Any ideas ? and is it possible ?
This is what I have.
$(document).ready(function(){

$('#submit').click(function(){

$.post('<?php echo get_template_directory_uri(); ?>/send.php', $("#mycontactform").serialize(),  function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;

});

});

I have also tried the php echo inside quotes like this.
   $.post(' "<?php echo get_template_directory_uri(); ?>" /send.php' ....

ether  way I get this path
http://mysite.com/%27%3C?php%20echo%20get_template_directory_uri();%20?%3E%27/send.php&email=&message=&name=&sent=1

Comment: Where are you using that code? In a JS file?
Comment: Unless this is placed in header.php (for example), it won't work. The WordPress template functions are only loaded in the template files. Apart from that, there's nothing wrong with the code (the first part above).
Comment: Yes, forgot too mention that.
was thinking of creating a variable but since in a js file it didnt to the trick
Comment: what you should do is rename the extension to php and include it as javascript it would work totaly fine like that
Answer: Javascript to PHP = nope you cant embed javascript to php, only php can embed html and javascripts.
the better way to do it is to create a .php file and insert the javascript there...
Example: js.php
<?php
    function doSubmit() {
        ?>

        <?php
    }
?>

call the js.php using "include(js.php);" and call the functions inside another php
Inside your index.php
<?php
include('js.php');
?>

Comment: Alternatively, just put doSubmit() inside your functions.php file and you don't need to include the file. +1 anyway.
Comment: by the way yeah @Kieran is right, you could also do it...but my concept is to wide QStarter's imagination about php coding :)
Comment: Thanks. going to try this in a moment :) thanks alot @ChowKiko and the rest for all help
Comment: you may CHECK my post if my ANSWER is correct so that guest could identify the correct answer...thanks

use php inside JavaScript


Windows Phone development in Visual Studio 2012 RC

Question: Today Microsoft released Windows 8 Release Preview and visual studio 2012 rc. I'm a Windows phone developer. What dev tool I have to use for create my apps in Windows 8 rp?
Answer: In Microsoft Visual Studio 2012 express download page, it is mentioned like
"A Visual Studio 2012 Express product for Windows Phone will be available in conjunction with the next Windows Phone release. Until then, you can continue to use Visual Studio 2010 Express for Windows Phone to create Windows Phone apps."
http://www.microsoft.com/visualstudio/11/en-us/products/express
Answer: The Windows Phone 8 SDK is out now, for those that are still reading this. It includes the 7.1 and 7.1.1 as well, and all runs within Visual Studio 2012. You can get it here:
https://dev.windowsphone.com/en-us/downloadsdk
Comment: Just a sidenote: Windows 8 is required for installation of the Windows Phone 8 SDK, so if you're still on windows 7: Sorry, no cake for you...
Comment: Yeah utter garbage, no chance anyone will be developing for Windows Phone 8 if they are forcing developers to use Windows 8 OS, madness!
Answer: For Windows 8, install VS2010, the Windows Phone SDK, and don't forget the 7.1.1 SDK update that fixes problems with Windows 8.
Comment: its that I get VS2010 free from my school otherwise I killed someone


How to delete lines starting with certain strings

Question: Is there a way to delete lines starting with certain strings.
I have this youtube-dl code
youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E

and its result is like this
[youtube:playlist] PL1C815DB73EC2678E: Downloading webpage
[download] Downloading playlist: Less than 1 minute
[youtube:playlist] playlist Less than 1 minute: Collected 4 video ids (downloading 4 of them)
[download] Downloading video 1 of 4
[youtube] KNLwsqzFfNg: Downloading webpage
[youtube] KNLwsqzFfNg: Extracting video information
[youtube] KNLwsqzFfNg: Downloading DASH manifest
[download] Destination: _1 min. - Amendes pour les particules du LHC-KNLwsqzFfNg.m4a

[download]   0.4% of 231.51KiB at  6.10KiB/s ETA 00:30
[download]   1.1% of 231.51KiB at 27.07KiB/s ETA 00:10
[download]   4.0% of 231.51KiB at 19.24KiB/s ETA 00:04
[download]   6.5% of 231.51KiB at 75.06KiB/s ETA 00:03
[download]  13.4% of 231.51KiB at 98.22KiB/s ETA 00:03
[download]  28.7% of 231.51KiB at 81.40KiB/s ETA 00:02
[download]  61.7% of 231.51KiB at 91.56KiB/s ETA 00:01
[download]  86.2% of 231.51KiB at 82.96KiB/s ETA 00:00
[download] 100.0% of 231.51KiB at 73.21KiB/s ETA 00:00
[download] 100% of 231.51KiB in 00:02
[ffmpeg] Correcting container in "_1 min. - Amendes pour les particules du LHC-KNLwsqzFfNg.m4a"
WARNING: Your copy of avconv is outdated, update avconv to version 10-0 or newer if you encounter any errors.
[avconv] Destination: _1 min. - Amendes pour les particules du LHC-KNLwsqzFfNg.mp3
WARNING: Your copy of avconv is outdated, update avconv to version 10-0 or newer if you encounter any errors.
Deleting original file _1 min. - Amendes pour les particules du LHC-KNLwsqzFfNg.m4a (pass -k to keep)
[download] Downloading video 2 of 4
[youtube] wTvXkMpJflk: Downloading webpage
[youtube] wTvXkMpJflk: Extracting video information
[youtube] wTvXkMpJflk: Downloading DASH manifest

I want to delete all lines starting with [youtube], [ffmpeg]  and  [avconv] and get like this
[youtube:playlist] PL1C815DB73EC2678E: Downloading webpage
[download] Downloading playlist: Less than 1 minute
[youtube:playlist] playlist Less than 1 minute: Collected 4 video ids (downloading 4 of them)
[download] Downloading video 1 of 4
[download] Destination: _1 min. - Amendes pour les particules du LHC-KNLwsqzFfNg.m4a

[download]   0.4% of 231.51KiB at  6.10KiB/s ETA 00:30
[download]   1.1% of 231.51KiB at 27.07KiB/s ETA 00:10
[download]   4.0% of 231.51KiB at 19.24KiB/s ETA 00:04
[download]   6.5% of 231.51KiB at 75.06KiB/s ETA 00:03
[download]  13.4% of 231.51KiB at 98.22KiB/s ETA 00:03
[download]  28.7% of 231.51KiB at 81.40KiB/s ETA 00:02
[download]  61.7% of 231.51KiB at 91.56KiB/s ETA 00:01
[download]  86.2% of 231.51KiB at 82.96KiB/s ETA 00:00
[download] 100.0% of 231.51KiB at 73.21KiB/s ETA 00:00
[download] 100% of 231.51KiB in 00:02
WARNING: Your copy of avconv is outdated, update avconv to version 10-0 or newer if you encounter any errors.
WARNING: Your copy of avconv is outdated, update avconv to version 10-0 or newer if you encounter any errors.
Deleting original file _1 min. - Amendes pour les particules du LHC-KNLwsqzFfNg.m4a (pass -k to keep)
[download] Downloading video 2 of 4
etc..
etc..
.
.

i tried this method but its showing error and it only suppose to delete [youtube]
youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | sed '^/[youtube]/ d'

Comment: Your pattern is wrong. It should be `sed '/^\[youtube\]/d'`.
Answer: sed -i '/\[youtube\]/d' /path/to/file

will delete lines, containing "[youtube]".
As one command you can combine patterns like
sed -i '/\[youtube\]\|\[ffmpeg\]\|\[avconv\]/d' /path/to/file

Or right from your command
youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 \
 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E |
    sed '/\[youtube\]\|\[ffmpeg\]\|\[avconv\]/d' > output.txt

This will write the result to a file output.txt.
If you want to delete lines not just containing [youtube], but starting with [youtube], then add ^ to the pattern, like sed '/^\[youtube\]/d'.
But in your case it does not matter.
Comment: I tried this `sed -i '/\[youtube\]\|\[ffmpeg\]\|\[avconv\]/d'   youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E` and not working.  may be because its not a file and its a download link
Comment: Try with a file. It will work. Or you can do it right from the link using | pipe.
Comment: @potholiday I updated the answer
Comment: worked...  the edited one worked
Comment: and for me `> output.txt` is not necessary
Comment: how to delete `WARNING` line also  i tried like this \WARNING/d' but its not deleting.
Comment: @potholiday  You do not need to escape there, just `'/^WARNING/d'`
Comment: `sed '/\[youtube\]\|\[ffmpeg\]\|\[avconv\]|/^WARNING/d'` is showing error any idea whats happening
Comment: Do you see that `|` is also escaped with `\`?
Comment: showing this error `sed: -e expression #1, char 40: unknown command: `^'
`
Comment: There was a typo. `sed '/\[youtube\]\|\[ffmpeg\]\|\[avconv\]\|^WARNING/d'
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/24863/discussion-between-potholiday-and-pilot6).
Comment: it's really simple.  `sed -i '/youtube\|ffmpeg\|avconv\|WARNING/d'  file_name` you don't need multiple escapes
Answer: I suggest using grep -vE like so:
youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | grep -vE '^\[(youtube|ffmpeg|avconv)\]'
From man grep:
-v, --invert-match
              Invert the sense of matching, to select non-matching lines.  (-v
              is specified by POSIX.)

-E, --extended-regexp
              Interpret  PATTERN  as  an extended regular expression (ERE, see
              below).  (-E is specified by POSIX.)

The -E flag is used to avoid escaping square brackets with slashes. Without -E flag you have to escape the square brackets with a backslash, like so grep -vE '\[youtube\]\|\[ffmpeg\]\|\[avconv\]'
Edit:
Since you've requested awk,here's one with awk:
youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | awk '{if ($0~/^\[youtube\]/||/^\[ffmpeg\]/||/^\[avconv\]/||/^WARNING/) next;print}'
Comment: The `[` and `]` should be escaped. With the `-E` option (extended regex option) you can avoid escaping `(`, `)` and `|` in the command: `grep -vE '\[(youtube|ffmpeg|avconv)\]'`. As for the "starting requirement", `^` needs to be prepended.
Comment: @Lekensteyn good point. I'll add that
Comment: @Serg not working. when executed it shows `>` and a blinking cursor. may be some syntax problem
Comment: @potholiday it was missing the single quote at the end. Fixed everything and added awk version. please review
Comment: `grep` script doesn't show any difference from the original code, no change at all.  `awk` i tried like this `youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | awk '{if(/[youtube]/||/[ffmpeg]/) $0="";print}'` it deletes all except `warning` lines
Comment: @potholiday you can add ||/WARNING/, too. like  `if(/[youtube]/||/ffmpeg/||/avconv/||/WARNING/)`
Comment: [ffmpeg] and WARNING are on separate lines, so you have to add that to if statement to delete that line
Comment: @Serg `awk` command prints only the warning lines it deletes all other the lines . eg it deletes [download]  line also
Comment: @potholiday What about `if ($0~/[youtube]/||/WARNING/||/[ffmpeg]/||/[avconv]/)` ? does that make difference ?
Comment: @potholiday OK, fixed both grep and awk versions, now should be working as it should. My attention to details isn't at its best. Let me know how this works
Comment: Now it seems to be working, however it leaves empty lines in place of the removed lines; change `$0=""` to `next` to fix this
Comment: @Serg `gerp` is working fine but `awk` has problem
Comment: @potholiday what exactly ?
Comment: @Serg  same problem `awk` only prints `WARNING` line.. any way your `grep` is working fine. But how to  delete `WARNING`  also.  I tried this `youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | grep -vE '^\[(youtube|ffmpeg|avconv|WARNING)\]'` but still it prints WARNING line also
Comment: @potholiday in that code you posted, WARNING is inside brackets [ ].  Try `grep -vE '^\[(youtube|ffmpeg|avconv\]\|^WARNING` .
Comment: tried this `youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | grep -vE '^\[(youtube|ffmpeg|avconv\]\|^WARNING'` but getting error
Answer: Use grep -v as following:
youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | grep -v '^[youtube]' | grep -v '^[ffmpeg]' | grep -v '^[avconv]'

Answer: Using Perl:
< inputfile perl -pe 's/^\[(youtube|ffmpeg|avconv)\].*$//' > outputfile

To parse the output of youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E directly, pipe its output to the command without redirecting the content of inputfile:
`youtube-dl --extract-audio --audio-quality 0 --newline --audio-format mp3 https://www.youtube.com/playlist?list=PL1C815DB73EC2678E | perl -pe 's/^\[(youtube|ffmpeg|avconv)\].*$//' > outputfile`

< inputfile: redirects the content of inputfile to perl's stdin
> outputfile: redirects the content of perl's stdout to outputfile
-p: places a while (<>) { [...] } loop around the script and prints each processed line
-e: reads the script from the arguments

Perl script breakdown:

s: asserts to perform a substitution
/: starts the pattern
^: matches the start of the line
\[: matches a [ character
(: starts grouping the allowed strings
youtube: matches a youtube string
|: separates the second allowed string
ffmpeg: matches a ffmpeg string
|: separates the third allowed string
avconv: matches a avconv string
): stops grouping the allowed strings
\]: matches a ] character
.*: matches any number of any character
$: matches the end of the line
/: stops the pattern / starts the replacement string
/: stops the replacement string
Comment: you might want to edit the command to include pipe from the OP's `youtube-dl` command. Others might not understand. Otherwise, I've tested it with an input file with text from OP's post,seems to work, hence +1
Comment: Thanks @Serg, I saw you updated yours as well so +1 on yours either
Answer: Here is a similar question with easy answer
https://askubuntu.com/questions/1493280/remove-lines-from-a-txt-file-that-start-with-a-special-string?noredirect=1#comment2616486_1493280


pysintaller exe file does not run, throws could not find Hyper API binary directory error

Question: I've created a python script that creates a Tableau (.hyper) extract file using the Tableau Hyper Api.  Largely based on the sample scripts provided by Tableau.
I'm trying to package this using pyinstaller.  Pyinstaller creates the exe "successfully" but when I try run the exe I get this error:
Traceback (most recent call last):
  File "create_datasource.py", line 3, in <module>
    import tableauhyperapi
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\__init__.py", line 126, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\catalog.py", line 15, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\connection.py", line 20, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\result.py", line 18, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\date.py", line 14, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\impl\hapi.py", line 14, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "C:\Users\user\AppData\Roaming\Python\Python38\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "tableauhyperapi\impl\dll.py", line 28, in <module>
  File "tableauhyperapi\impl\util.py", line 65, in find_hyper_api_library
RuntimeError: tableauhyperapi.dll library not found. Could not find the Hyper API binary directory, tried C:\Users\user\AppData\Local\Temp\_MEI450082\tableauhyperapi\bin.
[43160] Failed to execute script create_datasource

I've tried adding the tableauhyperapi.dll as a binary file to the pyinstaller command, but it still throws the above error.
Could anyone assist with where I'm going wrong?
Comment: You need to add the dll specifically so it is extracted to the relative folder named in the second-last line of the error message - the relative folder after _MEI450082. If you can't figure out how to do this read the documentation https://pyinstaller.readthedocs.io/en/stable/spec-files.html#adding-binary-files or if you can't get that to work come back here and show the full pyinstaller command you tried. There might be other files to add once you've got that one working.
Comment: Thanks for your reply @barny.  I have tried adding the binary using the --add-binary command.  I'm using Windows 10.

This is the command I used:
C:\Users\username\AppData\Roaming\Python\Python38\Scripts\pyinstaller --onefile  --add-binary "C:\Program Files\Python38\Lib\site-packages\tableauhyperapi\bin\tableauhyperapi.dll;lib" create_datasource.py
Comment: Why are you putting the dll in `lib` folder? I said "the relative folder after _MEI450082" because that's where the code is looking and says it can't find it - isn't that clear? i.e. tableauhyperapi\bin
Comment: Ah right. Okay I get it now. Thanks
Comment: @barny, if you copy your first comment above to the answer section, I can flag it as the correct answer.
Answer: You need to add the dll specifically so it is extracted to the relative folder named in the second-last line of the error message - the relative folder after _MEI450082.
If you can't figure out how to do this read the documentation pyinstaller.readthedocs.io/en/stable/
Basically you need to add something like this to your pyinstaller command:
—add-binary "c:\full\path\to\tableauhyperapi.dll;tableauhyperapi/bin"

There might be other files to add once you've got that one working.
Answer: Adding to barny's answer and specific to tableau hyper API, you will run into Could not auto-detect Hyper binary: Hyper binary is not in the expected directory AppData\Local\Temp\_MEI176802\tableauhyperapi\bin\hyper
Use --add-data to resolve that. Command:
pyinstaller --onefile --name ExecName.exe --paths 'c:\full\path\to\site-packages' --add-binary 'c:\full\path\to\site-packages\tableauhyperapi\bin\tableauhyperapi.dll;tableauhyperapi/bin' --add-data 'c:\full\path\to\site-packages\tableauhyperapi\bin\hyper;tableauhyperapi/bin/hyper' Script.py


The period of $\sin(nx)$

Question: How can I prove with induction that period of $\sin(nx)$ is $\frac{2\pi}{n}$? I know how to prove this using a different method, but I need to prove it with induction.
Comment: What have you tried so far?
Comment: Try comparing it with the period of $e^{inx},\;x\in\mathbb{R}$.
Answer: Note that $$f(x)$$ hase nthe period $T$ if $$f(x+T)=f(x)$$ for all $$x$$ in the domain of $$f(x)$$

The period of $\sin(nx)$


.htaccess complex rewrite rule

Question: I have a little complex rewrite rule and I can't get the hang of it.
What I want to do is use .htaccess to make my website see this link:
https://some-domain.com/human/jeff

As this link (because the system knows how to handle this link):
https://some-domain.com/?type=human&which=jeff

Notes:

I want to apply this rule only if type=human.
which param can contain only letter characters.
If the type is human, there wont be any more url params except for those.

After a lot of trying this is my final and failed .htaccess content:
RewriteEngine On
RewriteRule     ^(https://[^/]+)/?\?type=(human)&which=([a-zA-z]+)$ $1/$2/$3 [NC, L]

Here is the logic behind it:

Group 1: (https://[^/]+) $1 will contain any string matching https://{any non empty string that does not containing "/"} - https://some-domain.com
Static: /?\? matches "/?" or "?"
Group 2: type=(human) $2 will contain "human"
Group 3: which=([a-zA-z]+) $3 will contain a non empty string with only letter characters (jeff).

Expected result:
This will match the regex
https://{any non empty string that does not containing "/"}/human/{any non empty string}

And I'm pretty much stuck here
Thank you!
EDIT:
I Should also mention that the rewrite should be for POST requests only, and the post params are needed.
Comment: You are using invalid characters in your Rewrite pattern. `http` , `domain` and `querystring` are there different things that can not be matched in `RewriteRule` . You need to use `RewriteCond` directive.. Not sure how the answer bellow worked for you.
Comment: @starkeen Actually I was wrong, it didn't work. can you help me with the rule?
Answer: Try this pattern: ^(https?:\/\/[^\/]+\/)\?type=(human)&which=([a-z]+)$
^ - beginning of a string
https?:\/\/[^\/]+\/ - match http literally, then match s optionally (zero or one), \/\/ matches // literally, [^\/]+ matches on or more characters otehr than / and then matches / literally
\?type=(human)&which=([a-z]+) - match ? literally, then match type=human literally (human will be stored in captruing group), then match &which= literally, then match one or more letters with [a-z]
It will match your string when it is in desird form (type=human and only letters in which).
Substitution pattern: \1\2\/\3
\1 - replace with first capturing group, similairly for \2 and \3
Demo
Comment: is this what you mean? `RewriteRule        ^(https?:\/\/[^\/]+\/)\?type=(human)&which=([a-z]+)$           \1\2\/\3`
Comment: @HikeNalbandyan Yes, but I think you'd need to use `$1` instead of `\1`. Try it out :)
Answer: In this line :
RewriteRule     ^(https://[^/]+)/?\?type=(human)&which=([a-zA-z]+)$ $1/$2/$3 [NC, L]

This part ^(https://[^/]+)/?\?type=(human)&which=([a-zA-z]+)$ is pattren and should match against a URI but not full URL.
Try this :
RewriteEngine On
RewriteCond %{QUERY_STRING} ^type=(human)&which=([A-Za-z]+)$  [NC]
RewriteRule ^ /%1/%2? [R=301,L]
RewriteRule ^(human)/(.*)$ /?type=$1&which=$2 [L]

Note: clear browser cache then test.
Comment: TY Mohammed, could you explain this line? `RewriteRule ^ /%1/%2? [R=301,L]`
Comment: @HikeNalbandyan this is RewriteRule so , the pattern (Regex) ^ to match any thing and then in substitution (target) %1 represent fist captured group in previous condition (human) and %2 represent the second captured  group ([A-Za-z])
Answer: Thank you, Michał Turczyn and Mohammed Elhag for helping.
Here is the final and working content of .htaccess.
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_URI} ^/(human)/([a-zA-Z]+)/?$ [NC]
 RewriteRule ^(human)/(.*)$ /?type=$1&which=$2 [L]
</IfModule>

This rule applies only when the REQUEST_URI is /human/{any non empty string}

.htaccess complex rewrite rule


Error while installing MegaSync on Ubuntu 20.04

Question: I am trying to install MegaSync on my new ubuntu 20.04 installation =). They already have a version out for ubuntu 20.04. (See https://mega.nz/sync). However, when I try to install it with sudo dpkg -i megasync-xUbuntu_20.04_amd64.deb I get a big list of dependency errors. It seems to me Megasync is missing some packages. However when I open the software updater it says there are no new updates that need to be done. I am not so experienced with Ubuntu yet so any help would be greatly appreciated.
Selecting previously unselected package megasync.
(Reading database ... 195014 files and directories currently installed.)
Preparing to unpack megasync-xUbuntu_20.04_amd64.deb ...
Unpacking megasync (4.3.1-15.1) ...
dpkg: dependency problems prevent configuration of megasync:
 megasync depends on libc-ares2 (>= 1.7.4); however:
  Package libc-ares2 is not installed.
 megasync depends on libcrypto++6; however:
  Package libcrypto++6 is not installed.
 megasync depends on libmediainfo0v5 (>= 0.7.56); however:
  Package libmediainfo0v5 is not installed.
 megasync depends on libqt5core5a (>= 5.12.2); however:
  Package libqt5core5a is not installed.
 megasync depends on libqt5dbus5 (>= 5.0.2); however:
  Package libqt5dbus5 is not installed.
 megasync depends on libqt5gui5 (>= 5.8.0) | libqt5gui5-gles (>= 5.8.0); however:
  Package libqt5gui5 is not installed.
  Package libqt5gui5-gles is not installed.
 megasync depends on libqt5network5 (>= 5.1.0); however:
  Package libqt5network5 is not installed.
 megasync depends on libqt5svg5 (>= 5.6.0~beta); however:
  Package libqt5svg5 is not installed.
 megasync depends on libqt5widgets5 (>= 5.11.0~rc1); however:
  Package libqt5widgets5 is not installed.
 megasync depends on libzen0v5 (>= 0.4.31-2~); however:
  Package libzen0v5 is not installed.

dpkg: error processing package megasync (--install):
 dependency problems - leaving unconfigured
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu2) ...
Processing triggers for mime-support (3.64ubuntu1) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Errors were encountered while processing:
 megasync

Answer: You have to use apt / apt-get instead of dpkg. They will install dependencies for package:
sudo apt install ./megasync-xUbuntu_20.04_amd64.deb

Comment: Thanks! The `./` is very important, otherwise it doesn't work!
Answer: None of the solutions I found in the web worked so I tried the following:
I downloaded libcrypto++9 from here, and installed it as a .deb.
http://archive.ubuntu.com/ubuntu/pool/universe/libc/libcrypto++/libcrypto++9_5.6.1-6_amd64.deb
The same for libc6 from:
http://ftp.br.debian.org/debian/pool/main/g/glibc/libc6_2.31-4_amd64.deb
Then I downloaded libqt5gui5-gles_5.15.1+dfsg-2_amd64.deb from
http://ftp.br.debian.org/debian/pool/main/q/qtbase-opensource-src-gles/libqt5gui5-gles_5.15.1+dfsg-2_amd64.deb
You should do it with any package that is missing in your own configuration. I recomend this website to find them: https://pkgs.org/
Comment: This answer can break a system since it not only advises installing software from `.deb` files, but the answer also suggests installing packages from other distributions.  Additionally, pkgs.org is not an official mirror or source for Ubuntu software.  When there are official sources like https://packages.ubuntu.com, referring users to unofficial software sources poses an unnecessary risk.  This answer also lacks [formatting](https://askubuntu.com/help/formatting), which is needed so the names of packages can be distinguished from the surrounding text.


Injection proof $f(m/n)$

Question: Prove $f(m/n)=2^m3^n$, $m/n$ is in lowest term, is an injection.
I have learnt injection for $x_1=x_2, f(x_1)=f(x_2)$. I would like to ask how to deal with $m/n$. Thanks.
Comment: What is $f(2./2)$?  What is $f(1/1)$?
Comment: sorry $m/n$ is in lowest term, I forget to add the condition. I'll edit it
Comment: Apply uniquensess part of prime factorization theorem.
Answer: Lets prove that your function is one to one function.
That is:
$f(a/b) = f(c/d) \implies a/b = c/d$
$$f(a/b) = 2^a\cdot 3^b = 2^c\cdot 3^d = f(c/d)$$
Then $2^{a-c} = 3^{d-b}$
Since the left and the right side have no common divisor, the only solution is that both must be 1.
$a-c = 0$ and $d-b=0$ or $a=c$ and $b=d$
Which means $\frac{a}{b} = \frac{c}{d}$

Injection proof $f(m/n)$


What does it mean 'there is no cow level'?

Question: In a loading screen it said that there is no cow level. What is this referring to?
Comment: Found a screen cap of the message linked [elsewhere](http://gaming.stackexchange.com/questions/66096/how-can-i-reach-whimsyshire-the-secret-level-in-diablo-iii): http://i.stack.imgur.com/HwilC.jpg
Answer: Way back with Diablo 1, there were rumors that clicking repeatedly on the corpse of a specific cow would open up a secret level.
Blizzard denied this (rightfully so), and made a humorous nod to the rumor by including a cheat code in their game Starcraft.  Typing "there is no cow level" into the console would allow you to skip a level.
In Diablo 2, they added an actual secret cow level.
In Diablo 3, they did not add in a cow level, but instead added a different secret level.
Comment: +1 for mentioning the Starcraft reference.  I actually initially thought this question was in reference to the old Broodwar.  Kudos to you sir either way :)
Comment: I'm so glad you mentioned the Starcraft reference.  Pretty much Fredley, it's an ongoing Blizzard joke through their games.
Comment: the joke was repeated in WoW's loading screens early on, responded by community that Thunderbluff is one
Answer: If you know nothing else about video games, know these three things:

The cake is a lie.
There is no cow level.
All your base are belong to us.

With this knowledge, no video game meme will ever confuse you.
Comment: -1 This does not answer the question. It should be a comment.
Comment: You definitely forgot the arrow to the knee meme, though everyone hates that now :D
Comment: I probably blocked it out because of that time when i was younger that I wanted to be an adventurer, but then I took an arrow to the knee =P
Comment: -1 I agree with @TheJug
Comment: @The Jug - I acknowledge that. There was already a great answer to the question, I figure the humor could be appreciated.
Answer: Its referring to Diablo 2. There was a Secret Level the "Cow Level". Blizzard said in Diablo 3 will be no Cow Level.
But... in D3 are Secret Levels.


Why is the Java API for XML Processing (JAXP) bundled with Java 7 not working?

Question: I have the following XML file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE starfleet SYSTEM "http://localhost:8080/xml-validate/dtd/starfleet.dtd">
<starfleet>
    <title>The two most famous starships in the fleet</title>
    <starship name="USS Enterprise" sn="NCC-1701">
        <class name="Constitution"/>
        <captain>James Tiberius Kirk</captain>
    </starship>

    <starship name="USS Enterprise" sn="NCC-1701-D">
        <class name="Galaxy"/>
        <captain>Jean-Luc Picard</captain>
    </starship>
</starfleet>

And the following DTD:
<!ELEMENT starfleet (title,starship*)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT starship (class,captain)>
<!ATTLIST
    starship name CDATA #REQUIRED
    sn CDATA #REQUIRED>
<!ELEMENT class EMPTY>
<!ATTLIST class name CDATA #REQUIRED>
<!ELEMENT captain (#PCDATA)>

I wanted to parse and validate the XML by using JAXP and a simple JSP file.
My SAX Exception Handler is:
package myPkg;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXParseException;

public class ParsingExceptionHandler extends DefaultHandler {
    public SAXParseException parsingException = null;
    public String errorLevel = null;

    public void warning(SAXParseException e) {
        errorLevel = "Warning";
        parsingException = e;
    }

    public void error(SAXParseException e) {
        errorLevel = "Error";
        parsingException = e;
    }

    public void fatalError(SAXParseException e) {
        errorLevel = "Fatal error";
        parsingException = e;
    }
}

And the JSP file that executes the actual validation is:
<%@page language="java" contentType="text/html"%>
<%@page import="javax.xml.parsers.SAXParserFactory"%>
<%@page import="javax.xml.parsers.SAXParser"%>
<%@page import="org.xml.sax.InputSource"%>
<%@page import="org.apache.commons.lang3.StringEscapeUtils"%>
<%@page import="myPkg.ParsingExceptionHandler"%>
<title>Starfleet validation (SAX - DTD)</title>
<%
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    InputSource inputSource = new InputSource("webapps/xml-validate/xml/enterprises.xml");
    ParsingExceptionHandler handler = new ParsingExceptionHandler();

    try {
        parser.parse(inputSource, handler);
    } catch (Exception e) {
        out.println("Something went wrong...");
    }

    if (handler.errorLevel == null) {
        out.println("The document is valid.");
    } else {
        out.println(
            "*** Validation " + handler.errorLevel + ": "
            + StringEscapeUtils.escapeHtml4(handler.parsingException.toString())
        );
    }
%>

The problem is that no matter what I do, the catch part of the code is entered, which means that my XML file is never deemed "valid" by the parser. Something must be wrong with my XML, right? However, the Exception Handler is never used and so its parsingException and errorLevel attributes always remain null, causing the message "The document is valid" to be displayed in the browser. Any insight into why is this happening?
P.S.: This is running inside a Tomcat instance.
Comment: The first thing you should do is to add `e.printStackTrace()` into the `catch` block, to see **what exactly** went wrong.
Comment: @JozefChocholacek I inspected catalina.out and found the root of the issue. I will place it as an answer.
Answer: Apparently, the path I used inside my JSP file to refer to the location of the XML file was not correct.
I had put:
InputSource inputSource = new InputSource("webapps/xml-validate/xml/enterprises.xml");

Erroneously assuming that this relative path would resolve to Tomcat's installation directory... but Tomcat actually resolved it (on my computer running OS X) to:
~/dev/apache-tomcat/bin/webapps/xml-validate/xml/enterprises.xml

Notice the introduction of the bin directory above.
So, all I had to do was to change the given path to:
InputSource inputSource = new InputSource("../webapps/xml-validate/xml/enterprises.xml");

And the XML was successfully found.


Optimizing quadratic form with respect to inner positive definite matrix with a trace constraint

Question: Let $\{z_i\}_{i=1}^n$ and $\{w_i\}_{i=1}^n$ be two collections of vectors in $\mathbb R^p$. Let $A$ be a real positive definite $p\times p$ matrix, with Cholesky factorization $LL^T$, where $L$ is also $p\times p$.
I want to solve the following optimization:
$$\min_L  F(L) \rightarrow \min_L \sum_{i=1}^p z^T_i LL^T z_i - w^T_i LL^T w_i$$
subject to the constraint
$$\text{tr}(LL^T) = 1.$$
My approach: Lagrange multipliers. I thought that $\frac{d}{dL} \left(zLL^Tz - wLL^Tw\right) = 2(zz^T-ww^T)L$, and $\frac{d}{dL}\text{Tr}(LL^T) = 2L$, but this doesn't seem to lead to a solution.
Edited: Rewrote problem to include a positive semi-definite constraint, via the Cholesky factorization.
Comment: Your constraint does not deal with the off-diagonal elements of $A$. Therefore I can make those elements as large as I wish and make their signs negative, which will drive the function value towards $-\infty$
Comment: Great point. I want to add a positive negative constraint. Will rephrase.
Answer: Rather than solve for the Cholesky factor directly, find a solution in terms of a less structured matrix, $M$. Let a colon denote the matrix inner product, i.e.
$$\eqalign{
A:B &= {\rm Tr}(AB^T) \cr
M:M &= {\rm Tr}(MM^T) &= \frac{1}{\mu^2} \cr
}$$
Also, for typing convenience let
$$\eqalign{
 A &= \frac{MM^T}{M:M},\quad\;
 Y &= Y^T = \sum_kz_kz_k^T - w_kw_k^T \cr
}$$
Calculate the gradient of $F$.
$$\eqalign{
 F &= Y:A \cr
dF &= Y:dA \cr
  &= Y:\Bigg(\frac{dM\,M^T+M\,dM^T}{M:M} - \frac{MM^T\big(dM:M+M:dM\big)}{(M:M)^2}\Bigg) \cr
 &= 2\mu^2\Big(YM-FM\Big):dM \cr
\frac{\partial F}{\partial M}
 &= 2\mu^2\big(YM-FM\big) \cr
}$$
Set the gradient to zero and solve for $M$.
$$\eqalign{
 &YM = F M \cr
}$$
Thus it appears that the columns of $M$ are equal to
the eigenvector $\{v_k\}$ of $Y$ associated with its minimum eigenvalue $\{\lambda_k\}$, i.e.
$$k = \arg\min_j \lambda_j,\quad F = \lambda_k,\quad
M = (\,v_k\;v_k\;v_k\;\ldots\,) \,=\, v_k{\large\tt 1}^T
$$
Given the solution in terms of $M$, recover a solution in terms of $L$.
$$\eqalign{
L &= {\rm cholesky}\bigg(\frac{MM^T}{M:M}\bigg) \cr
A &= LL^T = \frac{MM^T}{M:M},\quad\quad
{\rm Tr}(LL^T) = \frac{M:M}{M:M} = 1 \cr
}$$
Comment: I mostly followed this (have to brush up on some basics with matrix calculus), but I don't quite understand how you conclude $YM=FM$ implies that $M=v_k1^T$. Can you briefly explain this? Also, do you have a good reference for matrix calculus that you would recommend, evidently I'm not strong enough and some of the standard stuff out there, such as Matrix Cookbook, is pretty unreadable for the basics.
Comment: I understand that the columns of M should correspond to eigenvectors of $Y$, but I don't understand why it consists of copies of the eigenvector corresponding to the smallest eigenvalue.
Comment: Because $Y$ operates on $M$ column by column, and must produce the _same value_ of $F$ for every column. Now it is _possible_ that the minimum eigenvalue has multiplicity greater than one. In that case, you could use all of the associated eigenvectors (or linear combinations thereof) as the columns of $M$.
Answer: Define the $p\times n$ matrices $Z=[z_1,\dots,z_n]$ and $W=[w_1,\dots,w_n]$ (such that given vectors are respectively their columns). Convince yourself that you can rewrite your optimization problem as
\begin{align}
\min_{A} &<A,ZZ^T-WW^T> \\ &A\geq 0 ~,~<A,I> = 1
\end{align}
where $A\geq 0$ implies $A$ should be positive-semi-definite. Also, for any two symmetric matrices $A,B$, we define $<A,B> = \mathrm{trace}(AB)$. We can define the eigen-decomposition
\begin{align}
A = \sum_{i=1}^{p}\lambda_iu_iu_i^T
\end{align}
where $u_i$ are the eigen vectors and $\lambda_i$ are the eigen values (of unit-norm). Let $B=ZZ^T-WW^T$. Convince yourselves that your optimization problem of finding $A$ is same as finding pairs $(\lambda_i,u_i)$ in the optimization problem
\begin{align}
\min_{\lambda_i,u_i}&\sum_{i=1}^{p}\lambda_iu_i^TBu_i
\\& \lambda_i\geq 0~,~\forall i
\\& \sum_{i=1}^{p}\lambda_i = 1
\end{align}
From rayleigh-ritz ratio, it follows that for any unit-norm $u_i$, we have that
\begin{align}
u_i^TBu_i\geq \lambda_{min}(B)
\end{align}
and equality is achieved when $u_i$ is the eigen-vector corresponding to $\lambda_{min}(B)$. Thus, it follows that
\begin{align}A = uu^T
\end{align} where $u$ is the eigen-vector corresponding to smallest eigenvalue of $B$.


How to send MQ messages (JMS) using JMeter

Question: I have to put messages in a queue for which I have all the connection details (host, port, channel, manager, queuename and username). I never worked on implementing JMeter for sending MQ. Can anyone let me know where can I get (blog or reference) step by step procedure to perform this? I tried referring to official site, can't really understand those JNDI, connection Factory settings
Comment: Does this answer your question? [Jmeter to connect to IBM MQ](https://stackoverflow.com/questions/33278071/jmeter-to-connect-to-ibm-mq)
Comment: Sounds like you are using IBM MQ.  This answer may help: https://stackoverflow.com/questions/33278071/jmeter-to-connect-to-ibm-mq
Answer: Man, your MQ statement is too general as there are too many possible message queue system providers like Apache ActiveMQ, RabbitMQ, IBM MQ, TIBCO, etc. and the values for all these JNDI/JMS properties, connection factory names, queue names, etc. will be different.

To get an overview of Java communication with "MQ" get familiarized with Getting Started with Java Message Service (JMS)
Download .jar files for your MQ system and put them to JMeter Classpath
Perform configuration as per your MQ system connection settings, example setup for Apache ActiveMQ is here: Building a JMS Testing Plan - Apache JMeter


serialize objects after you terminate program

Question: I'm familiar with the process of serializing an object and writing it to a file, but is there a way tp dp so after the user terminates the console?
Comment: Huh?  Needs a lot more detail, please.
Comment: Sure there is. One way would be to simply keep a `Collection` of the objects that have been modified during runtime. Then, on program close, simply serialize all objects. Can't really help without more context though :/
Answer: Yes, you could add SIGTERM handler. In java you can do it by using Runtime.addShutdownHook()
Comment: i tested this method with intellij ide and noticed sgutDownHook doesn't work with it's stop button(ctrl+f2). is there a way to fix that?
Comment: Probably intellij sends other signal when you click stop button and I guess they are using the same methods as you could use in the terminal. How about checking their site fos some tips? If it is possible, then it should documented somewhere


How do I grant sudo privileges to an existing user?

Question: I want to grant a newly created user sudo privileges in Ubuntu.
I tried
sudo adduser hduser admin

but it says no admin group exists.
How can I do it?
Comment: This was changed recently, which is the reason for the confusion.
Comment: What is the output of `sudo visudo`?
Comment: sudo adduser  sudo - did the trick for me. Second sudo is the group name instead of sudo
Answer: You need to add the user hduser to the sudo group (which is the "administrators" group in Ubuntu).
If you have already created the user, you can add the user to the sudo group by running the following command in a Terminal:
sudo usermod -a -G sudo hduser

Comment: Note that the user must log off, then back on again for this change to take effect.
Comment: not working ubuntu 14
Comment: Usage: usermod [options] LOGIN

Options:
  -c, --comment COMMENT         new value of the GECOS field
  -d, --home HOME_DIR           new home directory for the user account
  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE
  -f, --inactive INACTIVE       set password inactive after expiration
                                to INACTIVE
  -g, --gid GROUP               force use GROUP as new primary group
  -G, --groups GROUPS           new list of supplementary GROUPS
  -a, --append                  append the user to the supplemental GROUPS
Comment: FYI, In RHEL/CentOS it is: sudo usermod -aG wheel hduser
Comment: No problem here using ubuntu 14.  Thx.
Comment: Yes , @JacobFoshee is right  - "user must log off, then back on again for this change to take effect."
Comment: still if i use visudo on the user i just added to sudo I will get permission denied, why is that ?
Comment: No problem here using ubuntu 16.
Comment: How do i remove sudo access from existing user ?
Answer: Instead you can try,
sudo adduser hduser sudo

In Ubuntu you need to add the user only to the group sudo.
Answer: 1) Become root. You can do this using sudo -i or becoming root the old fashioned way su -
2) Run visudo
3) I changed this portion of the sudoers file to have my chosen users become sudo users, and you can add users similarly (blank lines introduce to format cleanly):
## User Aliases
## These aren't often necessary, as you can use regular groups
## (ie, from files, LDAP, NIS, etc) in this file - just use %groupname
## rather than USERALIAS
# User_Alias ADMINS = jsmith, mikem dbadmin
ALL=(ALL) ALL
ics ALL=(ALL) ALL
csm ALL=(ALL) ALL
coa ALL=(ALL) ALL

4) Press : and x to write the changes to sudoers and exit vi.
Comment: This seems needlessly complicated. Why bother running visudo when the [`adduser` command](http://askubuntu.com/a/7484/116961) will do what you want?
Comment: @dan-dascalescu - $ sudo adduser username sudo won't work if the 'sudo' group does not exist. So adding the user manually is certainly an option. However, it's certainly more elegant to create a sudo group, add it to the sudoers file (e.g. via visudo), then add the appropriate user(s) to that user group.
Comment: @JarrettBarnett That was the case for me. Thank you for your answer.
Answer: Edit the sudoers file: sudo visudo
and add:
user    ALL=(ALL:ALL) ALL

Comment: Why bother editing `/etc/sudoers` when the [`adduser` command](http://askubuntu.com/a/7484/116961) will work?
Comment: @DanDascalescu maybe because for some people it doesnt work?
Comment: @Zanna You have edited `sudo visudo /etc/sudoers` Is it correct? AFAIK, it is either `sudo visudo` or `sudo nano /etc/sudoers`
Comment: ah @Lnux you're right, but you should always use `visudo` to edit `/etc/sudoers` because it stops you from making a fatal syntax error. I corrected


How to get rid of Atom's Welcome screen

Question:
I searched around the net and the solutions are too complicated. Is there any easy way to get rid of the "Welcome Guide" Screen?
Comment: Related issue for searchers who arrive here: To disable Telemetry Consent tab, do Settings->Packages->Metrics->Disable.
Answer: You have two solutions. I think the second achieves the best when you say "to get rid of":

By unchecking the option Show On Startup in the configuration of the Welcome plugin (Settings » Packages » welcome), Atom doesn't show the Welcome screen at startup (or when opening a new Atom window), but still loads the plugin:

By disabling the Welcome plugin (Settings » Packages » welcome), Atom doesn't load it (which saves memory) and so doesn't show the Welcome screen (under any circumstance):
Answer: On OS X, you go to menu Atom → Preferences → Packages and then you have to either find Welcome in the Core Packages or use the filter. You can't get there by going directly to packages in the top nav. Crazy.
Answer: I am running Linux Mint and I deselected to "show on startup" and turned off telemetry, but for some reason was never saved and always showed. Even going through preferences did nothing for me to fix the issue. This was the only thing that fixed it for me was creating a config file for it in my home directory under the .atom directory.
cat ~/.atom/config.cson
"*":
  core:
    telemetryConsent: "no"
  welcome:
    showOnStartup: false
There are other values for this file, but these should turn off the Welcome screen and Telemetry if it keeps showing up for you.
Comment: This proved to be the best option for me. Per another answer, the check-mark on the Welcome screen to disable it on did not appear in the v1.60.0 version I was running. And editing the `.cson` file was the most straightforward was to disable it.
Answer: It sounds pretty trivial, but after disabling the welcome guide from the welcome page,

and restarting Atom you may still see the welcome guide if you didn't close the page and have the "Restore Previous Windows On Start" (under Settings → Core) set to "yes" or "always":

Simply make sure to close the welcome guide before you restart Atom (or if you do not want to have windows restored you can also change that option to "no").
Answer: The easiest way that worked for me is when the welcome page appears, uncheck the Show welcome guide when open. For clarification Here is the image
Comment: Think that didn't exist when the question was asked. But if there's such a checkmark then it's the right answer.
Comment: I can confirm I did not see that checkbox in Atom version `1.60.0 x64` but I suspect that means I need to update Atom. When I try to check for updates in the 'Atom -> Check for Updates' menu option it returns an error. At the time of this comment, latest Atom version is 1.63.1

How to get rid of Atom's Welcome screen


ffmpeg decode JPEG 2000 in multithread

Question: So, I have a Video-decoder written in c++ whit help of ffmpeg library, non problem till when it comes to decode JPEG 2000 frame in multi threads, in this case the image is discontinuous, I set the context to have even number of threads and to process image slices:
<code>    m->context->thread_count = m_cfgHhiThreads->value();
    m->context->thread_type = FF_THREAD_SLICE;
</code>
here is a sample image captured after decoding process (dimension is fine), this only happen if multithred is set
Question is, why is this happening?
FFMPEG does not report any error, it actually think that the image has been correctly decoded. It is also correctly decoded the problem is in slicing.
Comment: Please ask a question.
Comment: does ffmpeg command line show the problem?
Answer: I find out that if I setup exact so many thread as the image slice number it actually work fine.

ffmpeg decode JPEG 2000 in multithread


News Notification in Android

Question: I am working on app in which i need to implement a functionality of News Notification.
For example, The NDTV news app: it gives notification whenever there is new news. How does it happen?
Could anyone provide me a solution example?
Any help will be appreciated.
Comment: You will have to read the rss feed and then show the notification accordingly
Comment: Thanks for reply Auto-Droid. In my case i need to push data from web service. The notification will occur in a fixed interval. Any Example will be appreciated.
Comment: Create pending intent in android, start services at certain intervals, check if there is new news and display in your notification
Answer: Use this code :
<code>    private void generateNotification(Context context, String message) {

    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    String appname = context.getResources().getString(R.string.app_name);
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    Notification notification;
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, myactivity.class), 0);

    // To support 2.3 os, we use "Notification" class and 3.0+ os will use
    // "NotificationCompat.Builder" class.
    if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
        notification = new Notification(icon, message, 0);
        notification.setLatestEventInfo(context, appname, message,
                contentIntent);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);

    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context);
        notification = builder.setContentIntent(contentIntent)
                .setSmallIcon(icon).setTicker(appname).setWhen(0)
                .setAutoCancel(true).setContentTitle(appname)
                .setContentText(message).build();

        notificationManager.notify((int) when , notification);

    }

}
</code>

News Notification in Android


How to display coordinates of moving object in iOS?

Question: I am trying to display location of object that is moving by gesture. Everythink works fine untill I want to display its position. Below is code:
<code>- (void)panDetected:(UIPanGestureRecognizer *)panRecognizer
{
    CGPoint translation = [panRecognizer translationInView:self.view];
    CGPoint imageViewPosition = _iconCamera.center;
    imageViewPosition.x += translation.x;

     // This line generates error
    _labelCameraPosition.text = [NSString stringWithFormat: @"%.1f", _iconCamera.center.x];

    self.iconCamera.center = imageViewPosition;
    [panRecognizer setTranslation:CGPointZero inView:self.view];
}
</code>
When I want to display this value image is shaking but not moving. What should I do?
Comment: try getting the presentation layer of the object, and checking its frame: (CALayer*)self.iconCamera.layer.presentationLayer - this is used for the current position of views that are animating, not sure if it works in that case.
Comment: Why do you use _iconCamera a few times and self.iconCamera once?
Comment: its messy code for now. I just want make it working. I will care about consistency later.
Answer: This answer is based on that you are using auto layout.
in viewDidAppear, set your label and imageView like this.
<code>self.label.translatesAutoresizingMaskIntoConstraints = YES;
self.imageView.translatesAutoresizingMaskIntoConstraints = YES;
</code>
since you are changing frame when using auto layout. set translatesAutoresizingMaskIntoConstraints to yes automatically translate its new frame to constraints.
Comment: I love this answer! Works perfectly! But I dont know why :-)
Comment: UIControl created by storyboard has its own constraints, and this property is NO by default,if you move the view around, changing its frame, the old constraints will try to break the change(the shaking). After setting to yes, the new frame automatically add new constraints to the view, which will make view moving smoothly.


Prove $\sum_{n=1}^{+\infty} \dfrac{1}{n^2} = \dfrac{\pi^2}{6}$ from $\lim_{a \to 0+} \dfrac{\pi}{a} \dfrac{1 + e^{-2 \pi a}}{1 - e^{-2 \pi a}}$?

Question: Yes, I need to prove the solution to the Basel problem from a limit. The context is that we can combine the Fourier transform of $1/(n^2 + a^2)$ and the Poisson summation formula to show that (if $a
> 0$) \begin{align} \sum_{n = -\infty}^{\infty} \dfrac{1}{n^2+a^2} &= \sum_{n = -\infty}^{-1} \dfrac{1}{n^2+a^2} + \sum_{n = 0}^{\infty} \dfrac{1}{n^2+a^2} \\&= \dfrac{\pi}{a} \sum_{n = -\infty}^{-1} e^{-2\pi a |n|} + \dfrac{\pi}{a} \sum_{n = 0}^{\infty} e^{-2\pi a n}
\\&= \dfrac{\pi}{a} \left[\dfrac{r}{1-r} + \dfrac{1}{1-r} \right] \\&= \dfrac{\pi}{a} \dfrac{1+r}{1-r}, \text{ where } r = e^{-2 \pi a} \end{align}
Then I have to consider the limit $a \to 0^+$ to show $\displaystyle \sum_{n=1}^{+\infty} \dfrac{1}{n^2} = \dfrac{\pi^2}{6}$.
My thoughts:
Since \begin{align} \dfrac{\pi}{a} \sum_{n = -\infty}^{-1} e^{-2\pi a |n|} &= \dfrac{\pi}{a} \sum_{n = 1}^{\infty} e^{-2\pi a n} \\&= \dfrac{\pi}{a} \dfrac{r}{1-r}\end{align} should I simply take $\displaystyle\lim _{a\to 0^+}\dfrac{\pi}{a} \dfrac{r}{1-r}$ ?
Thank you very much.
Comment: The limit in the title is infinite.
Comment: @Gary would you mind to show how?
Comment: $$
1 + e^{ - 2\pi a}  \to 2,\;1 - e^{ - 2\pi a}  \to 0,\; a \to 0 \Rightarrow \frac{\pi }{a}\frac{{1 + e^{ - 2\pi a} }}{{1 - e^{ - 2\pi a} }} \to \frac{\pi }{0}\frac{2}{0} = \infty
$$ (note that $e^0=1$)
Comment: @Gary I see. So we should simply focus on the $(\pi/a) \cdot r/(1-r)$ limit to prove the required sum?
Comment: Well in that case you have $$
\frac{\pi }{a}\frac{{e^{ - 2\pi a} }}{{1 - e^{ - 2\pi a} }} \to \frac{\pi }{0}\frac{1}{0} = \infty ,
$$ don't you? You may want to study basic analysis (such as limits) before working with things like Fourier transforms and Poisson summation.
Answer: It turns out the correct way to approach this question is first recognizing \begin{equation} \sum_{n=-\infty}^{+\infty} \dfrac{1}{n^2 + a^2} = \sum_{n=-\infty}^{-1} \dfrac{1}{n^2 + a^2} + \sum_{n=1}^{+\infty} \dfrac{1}{n^2 + a^2} + \dfrac{1}{a^2} = 2\sum_{n=1}^{\infty} \dfrac{1}{n^2 + a^2} + \dfrac{1}{a^2} \end{equation} because $(-n)^2 = n^2$, so that \begin{equation} 2\sum_{n=1}^{\infty} \dfrac{1}{n^2 + a^2} = \dfrac{\pi}{a}\dfrac{1+\exp(-2\pi a)}{1-\exp(-2\pi a)} - \dfrac{1}{a^2},\end{equation} and by applying L'Hopital's rule around 3 times you would get the limit of RHS as $a \to 0^+$ to be $\dfrac{\pi^2}{3}$. The result follows.


Primeng menubar ng-template start and end or not showing even after doing the same way in example

Question: I am trying to use the sample provide in here, but somehow I am not able to get it work with ng-templates. modified the stackblitz provided in example and tried but no luck. please help me to figure out what am I missing
Below is my header code

  <ng-template pTemplate="start">

  </ng-template>
 <ng-template pTemplate="end">
    <input type="text" pInputText placeholder="Search">
 </ng-template>

My local packages are
 {
"@angular/animations": "~9.1.3",
"@angular/common": "~9.1.3",
"@angular/compiler": "~9.1.3",
"@angular/core": "~9.1.3",
"@angular/forms": "~9.1.3",
"@angular/platform-browser": "~9.1.3",
"@angular/platform-browser-dynamic": "~9.1.3",
"@angular/router": "~9.1.3",
"ngx-electron": "^2.2.0",
"primeicons": "^4.1.0",
"primeng": "^11.4.0",
"rxjs": "~6.5.4",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
}

Comment: The stackblitz doesn't look like what you're showing here.
Comment: @eko image is from local stackblitz is for reference code
Answer: Updating the answer based on comment:
One module import was missing in app.module.ts's imports array which is required for the desired output. So, please import TabViewModule and add it into the import array.
Adding the imports array:
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MenubarModule,
    InputTextModule,
    TabViewModule,
  ]

and HTML template:

  <ng-template pTemplate="start">

  </ng-template>
  <ng-template pTemplate="end">
    <input type="text" pInputText placeholder="Search">
  </ng-template>

Please refer to updated demo link in here.
Demo image for reference:
Comment: This started happening with angular 12  as well, TabViewModule  import fixed the issue for me , thanks.
Comment: updated snippet give in primeng docs please check
Comment: Okay but I still don't understand what output are you expecting from the given snippet?
Comment: Okay, I have updated my answer. Please go through the demo link as well and let me know if you face any issue regarding it. Also do upvote and accept the answer if it resolves your query.
Answer: While importing TabViewModule (in Ali's answer) makes the problem go away, I think it's enough to import SharedModule from primeng/api (TabViewModule imports SharedModule which has the necessary PrimeTemplate class defined).
Comment: yes, i confirm and this should be the accepted answer !