August LP205R on Ubuntu GNOME 15.04

Question: Similar question have been asked before, but there were no answers. I cannot comment there, nor I have an answer, therefore I don't see other option but to ask again.
I have a USB laser presenter August LP205R that does not work on GNOME Ubuntu 15.04, but works OK on Windows with both PowerPoint & PDF presentations. Here are the outputs asked for in the previous link:
xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=11   [slave  pointer  (2)]
⎜   ↳ RF 2.4G  RF 2.4G                          id=14   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ Laptop_Integrated_Webcam_HD               id=9    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=10   [slave  keyboard (3)]
    ↳ Dell WMI hotkeys                          id=12   [slave  keyboard (3)]
    ↳ RF 2.4G  RF 2.4G                          id=13   [slave  keyboard (3)]

lsusb
Bus 001 Device 004: ID 0bda:0129 Realtek Semiconductor Corp. RTS5129 Card Reader Controller
Bus 001 Device 003: ID 0c45:64ad Microdia
Bus 001 Device 005: ID 1d57:83ed Xenta
Bus 001 Device 002: ID 8087:07e6 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

xev gives output only on Start/End slideshow button:
KeyPress event, serial 33, synthetic NO, window 0x3000001,
    root 0xac, subw 0x0, time 14518987, (642,556), root:(643,609),
    state 0x10, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyRelease event, serial 36, synthetic NO, window 0x3000001,
    root 0xac, subw 0x0, time 14519138, (642,556), root:(643,609),
    state 0x11, keycode 50 (keysym 0xffe1, Shift_L), same_screen YES,
    XLookupString gives 0 bytes:
    XFilterEvent returns: False

I even tried the getscancodes and dmesg | tail recommended previously:
~/Downloads$ tar -xvzf getscancodes-1.0.tar.gz
getscancodes/
getscancodes/getscancodes.c
getscancodes/getscancodes
getscancodes/Makefile
getscancodes/getscancodes.o

~/Downloads$ cd getscancodes/

~/Downloads/getscancodes$ make
gcc -O2 -Wall   -c -o getscancodes.o getscancodes.c
gcc -o  getscancodes getscancodes.o

~/Downloads/getscancodes$ sudo ./getscancodes /dev/input/event16
[sudo] password for :
getscancodes: No such file or directory

~/Downloads/getscancodes$ cd ..

~/Downloads$ sudo ./getscancodes /dev/input/event16
sudo: ./getscancodes: command not found

~/Downloads$ cd getscancodes/

~/Downloads/getscancodes$ dmesg | tail
[ 8630.569019] usb 1-1.2: New USB device found, idVendor=1d57, idProduct=83ed
[ 8630.569043] usb 1-1.2: New USB device strings: Mfr=1, Product=1, SerialNumber=0
[ 8630.569059] usb 1-1.2: Product: RF 2.4G
[ 8630.569073] usb 1-1.2: Manufacturer: RF 2.4G
[ 8631.425965] usbcore: registered new interface driver usbhid
[ 8631.425982] usbhid: USB HID core driver
[ 8631.720489] input: RF 2.4G  RF 2.4G  as /devices/pci0000:00/0000:00:1d.0/usb1/1-1/1-1.2/1-1.2:1.0/0003:1D57:83ED.0001/input/input11
[ 8631.776680] hid-generic 0003:1D57:83ED.0001: input,hidraw0: USB HID v1.10 Keyboard [RF 2.4G  RF 2.4G ] on usb-0000:00:1d.0-1.2/input0
[ 8631.778126] input: RF 2.4G  RF 2.4G  as /devices/pci0000:00/0000:00:1d.0/usb1/1-1/1-1.2/1-1.2:1.1/0003:1D57:83ED.0002/input/input12
[ 8631.833351] hid-generic 0003:1D57:83ED.0002: input,hidraw1: USB HID v1.10 Mouse [RF 2.4G  RF 2.4G ] on usb-0000:00:1d.0-1.2/input1

~/Downloads/getscancodes$

I was wondering if somebody could help me figure out if & how should I update or make a new *-keyboard.hwdb file from the data above, as mentioned here:

Xubuntu - Logitech presenter works only partialy
How do I change the keymap of a single device (Logitech presenter)?

Thanks in advance! :)
Answer:
Looking in web for similar device point me that your device is 1d57:83ed Xenta and it create two input devices (a mouse and a keyboard) labeled as RF 2.4G  RF 2.4G with id=14 & id=13 from your commands output.
getscancodes was already created in ~/Downloads/getscancodes folder but /dev/input/event16 is not the corresponding event device file. You can find related event file using:
xinput --list-props 14
xinput --list-props 13

Than run ./getscancodes /dev/input/eventXX for both event files and try all keys.
If getscancodes didn't work, there a standard tool from Ubuntu  repository. Give it a try:
sudo apt-get install evtest
sudo evtest

The method explained in How do I change the keymap of a single device (Logitech presenter)? is outdated.
So follow Xubuntu - Logitech presenter works only partialy which have same instructions mentioned as comment/header in /lib/udev/hwdb.d/60-keyboard.hwdb

August LP205R on Ubuntu GNOME 15.04


Fragment's onDestroyView not called on back button press

Question: I have three Fragments in my application: Fragment A, B and C.
Steps:

I am replacing A by B and keeping A in backstack.
I am replacing B by C and not keeping B in backstack.
I am pressing back button, on pressing back button  A's onCreateView and then onStart is called (as it is
on back stack)

The problem is Fragment C's onStop, onDestroyView etc are not called and thus Fragment A is not visible on the screen and Fragment C is visible (as it;s view is not destroyed).
Comment: why are you not adding **B->C Transaction** to backstack? any special requirement?
Answer: I believe there is some misunderstanding of the back stack.
When you replace A with B, you put the transaction A->B in the back stack, not the A fragment. The back stack knows that when the user presses the back button, it will have to rollback the transaction: destroy B and recreate A. In your case, you are replacing C with B and you're pressing back button: A will be recreated and B cannot be destroyed since it doesn't exist.
Maybe you can find a solution listening for back stack events using FragmentManager.addOnBackStackChangedListener(), but I don't know if it fits your requirement.
Comment: I wanna give you what I consider the best solution for what I understand of your project. You could create the FragmentC 'inside' the 'FragmentB' that means that you can create the FragmentC using the `getChildFragmentManager()` of FragmentB. When you press back, FragmentB can be destroyed, and since C is child of B, it will be destroyed too. Please, if you find this solution good, accept the answer too.
Comment: Thank you @Mimmo Grottoli. You cleared my understanding up to a very good extent. Please tell me how can destroy view of C.
Answer: Please go through dev blog
http://developer.android.com/guide/components/fragments.html
Fragments lifecycle is affected by Activity lifecycle.
Comment: This is Fragments doc, and the question was about back stack, not Fragment or Activity lifecycle.


SonataAdmin memory on random files

Question: I have configured SonataAdmin bundle but and i've got a random memory problem when i intend to load admin/dashboard ,
Here is my 2 entities which contains Sonata CRUD :
namespace Jade\ReveBundle\Admin;

use Doctrine\Common\Collections\Collection;

use Jade\ReveBundle\Entity\Thematique;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;

class ProduitAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('titre')
            ->add('description')
        ;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('titre')
            ->add('description')
        ;
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->add('titre')
            ->add('description')
        ;
    }

    public function validate(ErrorElement $errorElement, $object)
    {
        $errorElement
            ->with('titre')
                ->assertMaxLength(array('limit' => 32))
            ->end()
        ;
    }
}

namespace Jade\ReveBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;

class ThematiqueAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('titre')
            ->add('description')
        ;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('titre')
            ->add('description')
        ;
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('id')
            ->add('titre')
            ->add('description')
        ;
    }

    public function validate(ErrorElement $errorElement, $object)
    {
        $errorElement
            ->with('titre')
                ->assertMaxLength(array('limit' => 32))
            ->end()
        ;
    }
}

Anyone i've got an idea of the problem ?
Thx for your answer
Comment: "random memory problem", please elaborate and provide error messages if applicable
Answer: If the error is "PHP Fatal Error: Allowed memory size of xxxx bytes exhausted...", then try to increase PHP memory limit. Sonata is using Doctrine ORM and entities may consume a lot of memory.
A lot of informations are stored in memory in profiler in dev mode, too.
File web/app_dev.php and web/app.php:

<?php
ini_set('memory_limit','128M'); //or some other reasonable value
...

or in php.ini:
memory_limit = 128M

Comment: A list or datagrid cannot consume so much memory. Increasing the limit is not a real solution.
Comment: Author of this question did not write his value of the memory_limit. So it's solution if his value is too low.

SonataAdmin memory on random files


Data is appended to end of file instead of the specified offsets

Question: I am working with 4 files and want to inject a string at a specified offset to each one of them.I am using fseek() but the data is being written to the end of files instead of intended offsets.Why, and how can i fix it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SZ 14
#define TARGET_NUM 4

long GetFileSize(FILE *fp);

int main(void)
{
    long offset[TARGET_NUM] = { 10,15,20,25 };

    const char *file_names[TARGET_NUM] = {
                                             "file1.txt", "file2.txt",
                                             "file3.txt", "file4.txt",
                                         };

    char dat[TARGET_NUM][SZ + 1] = {
                                       { '1','0','0','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','1','0','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','0','1','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','0','0','1','0','0','0','0', '0','0','0','0','0','0', 0 },
                                   };

    FILE *fp[TARGET_NUM];

    long f_size;
    for (size_t n = 0; n < TARGET_NUM; n++) {
        fp[n] = fopen(file_names[n], "a");
        if (!fp[n]) {
            fprintf(stderr, "Error, file %s failed to open.\n", file_names[n]);
            goto cleanup;
        }
        f_size = GetFileSize(fp[n]);
        if (offset[n] < f_size) {
            fseek(fp[n], offset[n], SEEK_SET);
            fprintf(fp[n], "%s", dat[n]);
        }
    }

cleanup:
    for (size_t n = 0; n < TARGET_NUM; n++) {
        if (fp[n]) {
            fclose(fp[n]);
        }
    }
    return 0;
}

long GetFileSize(FILE *fp)
{
    fseek(fp, 0L, SEEK_END);
    long sz = ftell(fp);
    fseek(fp, 0L, SEEK_SET);
    return sz;
}

Comment: Mode "*`"a"`*" stands for ***a***ppend.
Answer: The "a" mode means that the data will be written to end-of-file.
Try using "r+" mode (read + write) instead.
Quote from N1570 126.96.36.199 The fopen function:

6 Opening a file with append mode ('a' as the first character in the mode argument)
  causes all subsequent writes to the file to be forced to the then current end-of-file,
  regardless of intervening calls to the fseek function.

This means that file pointer opened with "a" mode will ignore operations performed with fseek.


Thread.sleep(#milliseconds) is working locally. When deployed to heroku, the program doesn't pause

Question: I'm doing calls to twitter from my twitter bot. Twitter has a limit of 180 calls per hour I believe, so I have a sleep function between calls so that I can keep it below that amount every hour. It works flawlessly on my machine, but does not pause when I'm watching the logs on Heroku.
The program has some functions and then here is the sleep function.
<code>Thread.sleep(90000);
</code>
I'd like to wait 90 seconds between calls: 1) to limit calls, 2) to make it tweet less often. The program actually does seem to pause 5000ms, which is what I used to have it set on. I made a new local folder and cloned the repo to it to make sure that the repo didn't still have the old parameter of 5000 for the sleep function, but it said 90000 as it should. Is there any particular reason this wouldn't work on Heroku?
Answer: Figured it out. The .jar file was not updating with the new code. Once I deleted and remade the jar file, everything worked as intended.


Anki doesn't start in Ubuntu 19.04

Question: I've installed Anki from "Ubuntu software" and as an addition installed this: sudo apt-get install python3-distutils (because of known issue) and it still doesn't work. Could someone please explain to me what should I do to fix the problem?
Upd1:
After launching from terminal (as @Emmet asked) the output is here:
su@uranus:~$ anki
Traceback (most recent call last):
  File "/usr/bin/anki", line 6, in <module>
    import aqt
  File "/usr/share/anki/aqt/__init__.py", line 32, in <module>
    import aqt.forms
  File "/usr/share/anki/aqt/forms/__init__.py", line 44, in <module>
    from . import about
  File "/usr/share/anki/aqt/forms/about.py", line 42, in <module>
    from aqt.webview import AnkiWebView
  File "/usr/share/anki/aqt/webview.py", line 90, in <module>
    class AnkiWebView(QWebEngineView):
NameError: name 'QWebEngineView' is not defined

Comment: Launch it from terminal, paste the output here.
Comment: @Emmet added an output to the body
Comment: See https://askubuntu.com/a/1123878/66509 for links. You can request package build for Disco or grab package from cosmic manually [from link](https://launchpad.net/~torkvemada/+archive/ubuntu/torkvemada/+files/anki_2.1.7+dfsg-1cosmic1_all.deb).
Comment: This is a bug and should be reported at https://bugs.launchpad.net/ubuntu
Answer: The only problem here is a forgotten import in the Python script mentioned at the bottom of the traceback :
    File "/usr/share/anki/aqt/webview.py", line 90, in <module>
      class AnkiWebView(QWebEngineView):
NameError: name 'QWebEngineView' is not defined

Just open webview.py and add the import needed:
from PyQt5.QtWebEngineWidgets import *

(There are a bunch of other imports missing from QtWebEngineWidgets aside from QWebEngineView, so it's easier to just import them all)
Comment: This is already in the works for being fixed - see my answer and the attached bug.  A fix was already released in Eoan (devel release), its pending SRU team intervention to release in disco-updates
Answer: I've the same problem today :D
this the steps  how i fixed it
First remove anki:
sudo apt-get remove anki
sudo apt-get autoremove
sudo apt-get update

Second install anki from this steps https://apps.ankiweb.net/
1) Downloads Anki from website
https://apps.ankiweb.net/downloads/current/anki-2.1.11-linux-amd64.tar.bz2
2) Installation
tar xjf anki-2.1.11-amd64.tar.bz2
cd anki-2.1.11-linux-amd64
sudo make install

3) to run anki
use this /usr/local/share/anki/bin/anki write it on terminal
Or
sudo nano /usr/bin/anki

and write in /usr/bin/anki file this code
#!/usr/bin/bash
/usr/local/share/anki/bin/anki

save file
and write on terminal
sudo chmod -R 755 /usr/bin/anki

now you can run anki just when you write anki on terminal
congratulation :D
Answer: You're not importing QWebPage.
Try adding this import to the top of your script:
from PyQt5.QtWebKitWidgets import QWebPage

Source: https://stackoverflow.com/questions/41754786/nameerror-name-qwebpage-is-not-defined
Comment: There is no user script involved, only a package installed with apt from the Ubuntu repository.
Answer: This is a KNOWN BUG and is already in the process of being fixed.
I have already uploaded a fix to the repos for this.  It awaits SRU team release into the disco-updates pocket of the repositories.
More details at: https://bugs.launchpad.net/ubuntu/+source/anki/+bug/1825722
Answer: FYI, a fix was released as of 19.04. So the workaround shouldn't be necessary from now on. Still, the upstream Debian package seems to be barely maintained and affected by the same bug.

Anki doesn't start in Ubuntu 19.04


How to use a color instead of drawable for toggle button selector

Question: <ToggleButton
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />

    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

How can use a color instead of a drawable?
I tried this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:color="@color/bg_blue"/>
    <item android:state_checked="false" android:color="@color/bg_light_grey"/>

</selector>

defined the above selector in color folder with name bg_toggle.xml
and
android:background="@color/bg_toggle"

which gives an Exception:
android.view.InflateException: Binary XML file line #50: Error inflating class android.widget.ToggleButton
org.xmlpull.v1.XmlPullParserException: Binary XML file line #4:  tag requires a 'drawable' attribute or child tag defining a drawable
Thank You
Answer: try this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@color/bg_blue"/>
    <item android:state_checked="false" android:drawable="@color/bg_light_grey"/>

 </selector>

EDIT
From android Doc

Note: A color resource can also be used as a drawable in XML. For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute (android:drawable="@color/green").
Comment: Can i use a **color** in **drawable attribute**? like **android:drawable="@color/bg_blue"**
Answer: Instead of that try like this:
  ToggleButton btnToggle=(ToggleButton) findViewById(R.id.<Your ToggleButtonId>);
    btnToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked)
                buttonView.setBackgroundColor(Color.RED);
            else buttonView.setBackgroundColor(Color.GREEN);
        }
    });

Comment: It is generally considered better practice to handle ui states with xml selectors.


Grep on source code excluding build folders

Question: I use grep to look for a variable usage or a function call in the following way
 grep -Rni <function_name>

However, the search also includes my build and build_debug folders.
Considering the case in which my code is structured as following
root/
  |
  ->build
  |
  ->build_debug
  |
  ->pkg_1
     |
     ->src
     |
     ->include
  ->pkg_2
     |
     ->src
     |
     ->include

How can I modify the query so that it does not look into build and build_debug?
Thanks!
Comment: There's this fancy new thing called "manual".
Comment: You're right. Apologies.
Answer: grep --exclude-dir build --exclude-dir build_debug -Rni


How to find all minimal winning coalitions in a weighted-majority voting game in a fast way?

Question: EDIT: I found a solution thanks to the paper A survey of algorithms for calculating power indices of weighted majority games
I'd like to solve the following problem:
Given a set N={1,..,n} with a vector of weights W={w_1,..,w_n}, sorted in descending order and with total sum 1,
find all subsets C (also called "coalitions") of N such that

C is "winning", that means that the sum of the weights of elements inside the subset C exceeds a certain threshold (e.g. 0.5)
C is "minimal", that means that removing any element from C will make the subset not "winning" anymore.

To clarify, an example could be: N={1,2,3} W={0.45,0.35,0.2}

The "winning" subsets here are {1,2},{2,3},{1,3} and {1,2,3} since they all exceed 0.5 total weight
only {1,2}, {2,3} and {1,3} are minimal, since in {1,2,3} you could remove one element and get the ones above.

From the paper cited above, I now implemented this code which recursively generates the list of all minimal winning coalitions
MWC = function(w,threshold=0.5){
  n = length(w)
  l = list()
  enumerate = function(S1,n1,b1){
    if(n1==n){
      return(list(c(S1,n1)))
    }else{
      if(sum(w[(n1+1):n]) >= b1){
        l = c(l,enumerate(S1,n1+1,b1))
      }
      if(w[n1] >= b1){
        l=c(l,list(c(S1,n1)))
      }else{
        l = c(l,enumerate(c(S1,n1),n1+1,b1-w[n1]))
        return(l)
      }
    }
  }
  return(enumerate(c(),1,threshold))
}

w = c(0.46,0.3,0.19,0.05)
MWC(w)

The code runs up to around n = 20, after the exponential complexity makes everything unfeasible.
Comment: why is {2,3} not also a winning subset in your first sample?
Comment: You're totally right, I edited the question. sorry for the mistake
Answer: One solution to your problem will be using while loop and applying the above constraints within the loop.
Below is the working code:
N = 1:10

W <- c(0.60, 0.40, 0.33, 0.30, 0.25, 0.20, 0.15, 0.10, 0.05, 0.03);

Winning_Sets <- c()

i <- 1

while (i != (length(N) - 1)) {
  if (i == 1) {
    Subsets <- combn(N, i)
  } else {
    Keep_Combs <- Subsets[,which(Intermediate_Sets == 'No_Match')]
    Subsets <- combn(N, i)
    if (i == 2) {
      Subsets <- apply(Subsets, 2, function(x) {
        x <- x[x[i - 1] %in% Keep_Combs]
      })
    } else {
      Subsets <- apply(Subsets, 2, function(x) {
        unlist(apply(Keep_Combs, 2, function(y) {
          if (identical(y, x[1:(i - 1)]) == TRUE) {
            x
            }
          }))
        })
    }
    Subsets <- do.call('cbind', Subsets)
  }
  Intermediate_Sets <- apply(Subsets, 2, function(x) {
    if (sum(W[x]) > 0.5) {
      paste('{', paste(x, collapse = ','), '}', sep = '')
    } else {
      'No_Match'
    }
    })
  Winning_Sets <- append(Winning_Sets, unlist(Intermediate_Sets[Intermediate_Sets != 'No_Match']))
  if (length(which(Intermediate_Sets == 'No_Match')) > 0) {
    i <- i + 1
  } else {
    i <- length(N) - 1
  }
}

Output:
Winning_Sets
 [1] "{1}"          "{2,3}"        "{2,4}"        "{2,5}"        "{2,6}"        "{2,7}"
 [7] "{3,4}"        "{3,5}"        "{3,6}"        "{4,5}"        "{2,8,9}"      "{2,8,10}"
[13] "{3,7,8}"      "{3,7,9}"      "{3,7,10}"     "{4,6,7}"      "{4,6,8}"      "{4,6,9}"
[19] "{4,6,10}"     "{4,7,8}"      "{5,6,7}"      "{5,6,8}"      "{3,8,9,10}"   "{4,7,9,10}"
[25] "{5,6,9,10}"   "{5,7,8,9}"    "{5,7,8,10}"   "{6,7,8,9,10}"

Comment: Hi, this code doesn't seem to always work (for example it doesn't work with N = 1:3
W <- c(0.45,0.35,0.2); )

I noticed that the problem in this specific case it stops after the first iteration since i=2. Some other times it returns the error "Error in do.call("cbind", Subsets): second argument must be a list"

I also noticed that it uses the function combn(N,i), so when you proceed in the iterations you will still generate all the subsets of N and then you remove the ones that where generated in excess. This gives problem when N is big if i is sufficiently high.
Comment: But I think that it can be fixed by passing to combn a different N that excludes the elements removed...I'll try it !
Comment: My bad missed to check those conditions but by adding some constraints it can be solved. Can you also tell how big N will be?
Comment: Ideally around 50, but I don't know if that will be feasible since the possible number of subsets is ( 2^57 - 1)  ...however the bigger the better, with my code I have serious slow downs around 20, I'm hoping to get at least to 30...


c# receive data from GPS over TCP connection

Question: I put a GPS Tracing device in my car, which sends me position information every ten seconds.
Now I want to develop an application that will show information about position of my car.
The problem is that I don't know how to receive data from GPS over GPRS/TCP connection.
Any suggestions?
Comment: Did you implement this? I am looking for something similar.
Answer: Yo can develop a C# application which acts as a server and your GPS device equipped with GSM/GPRS modem will connect to your server. Once the connection is established, you can receive and transmit data from/to GPS device.
Your server PC should be on public/static IP.


What To Cover Hole With

Question: I had a room remodeled and added a sink, the pipe that connects to the sewage line for drainage runs straight up into the wall and my drywall guy said to call a plumber to get them to add the appropriate covering for the hole.  Drywall guy said it had to be something specific to allow proper ventilation and be up to code.  Plumber quoted me $150 just to come out and look at it...I'm thinking it can't be to difficult (and probably pretty standard) vent/cover to add to it.
This is an image of what I've got - what do I need to purchase to cover that hole?
Answer: The only real question is whether this has to be covered in an accessible way or if it actually has to provide ventilation. I really hope it is not to provide ventilation, because if so you are venting plumbing system into your living area. Assuming it is only for access (i.e., for future maintenance/repairs) then there are inexpensive access panels such as this one:

There are many different brands. I first learned about this type of product from a Home RenoVision YouTube video, but unfortunately I can't find the right video at the moment. But basically you expand your hole to the right size for the cover and it just snaps into place.
Comment: While working the venting should be only inwards, and the normal tolerances of an access door/panel should allow adequate air to move inwards. When the mechanical vent fails, there will be a stink going the other direction, and you'll replace it. If not obvious, I hate mechanical vents, and will go to considerable effort to install a vent pipe instead...
Comment: since it's the drain line for a sink, would venting into the laundry room be a big issue?
Answer: Since what you are showing a picture of is a mechanical vent, you need an access door or access panel, because mechanical vents need to be able to replaced when they fail (as they do.)
They come in many sizes and are widely available.
Comment: Recommendations are specifically off topic here. The access doors are not anything special, unless it's a firewall - go ask at your hardware store if you still have one, or buy one online, or even at the orange or blue boxes.
Comment: any one you recommend?  Just so I know I'm getting the right thing, haha

What To Cover Hole With


throw() with clang++ shows possible memory leak

Question: I have a piece of code, which when compiled with g++ does not show any memory leaks.
Whereas, the same when compiled with clang++ shows, possible memory leak.
Here's the trace,
==7115==
==7115== HEAP SUMMARY:
==7115==     in use at exit: 16 bytes in 1 blocks
==7115==   total heap usage: 2,324 allocs, 2,323 frees, 2,166,060 bytes allocated
==7115==
==7115== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==7115==    at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==7115==    by 0x4129830: __cxxabiv1::__calloc_with_fallback(unsigned long, unsigned long) (in /opt/xxx/lib64/libc++abi.so.1)
==7115==    by 0x4128946: __cxa_get_globals (in /opt/xxx/lib64/libc++abi.so.1)
==7115==    by 0x412B287: __cxa_throw (in /opt/xxx/lib64/libc++abi.so.1)
==7115==    by 0x4E712AE: Lib::GenCmd::RaiseException(Status, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) (LibBase.cpp:291)
==7115==
==7115== LEAK SUMMARY:
==7115==    definitely lost: 0 bytes in 0 blocks
==7115==    indirectly lost: 0 bytes in 0 blocks
==7115==      possibly lost: 0 bytes in 0 blocks
==7115==    still reachable: 16 bytes in 1 blocks
==7115==         suppressed: 0 bytes in 0 blocks
==7115==
==7115== For counts of detected and suppressed errors, rerun with: -v

Well, its not possible to share the code snippet, but I can tell you RaiseException() is the function where I have a call made to throw() (at line 291) an exception. Here's the function snippet:
void GenCmd::RaiseException(Status status, std::string AdditionalMsg) throw(Status) {
    s_last_error = GetStatusString(status);

    if (false == AdditionalMsg.empty()) {
        s_last_error = s_last_error + AdditionalMsg;
    }
    throw(status);
}

Status is a structure, defined as below (along with default, parameterized & copy constructors)
typedef struct _Status {
    const u64_t m_status          : 8;
    const u64_t ReservedByte1     : 8;
    const u64_t m_action          : 8;
    const u64_t ReservedByte3     : 5;
    const u64_t m_testbit1        : 1;
    const u64_t m_testbit2        : 1;
    const u64_t m_cmd_failure     : 1;
    const u64_t m_module_code     : 4;
    const u64_t m_file_code       : 8;
    const u64_t ReservedByte7     : 4;
    const u64_t m_line_no         : 16;
}Status

The fact, that no leaks are seen with GCC, but only with Clang makes me think this to be some issue with Clang. (With Clang, I mean it could be libcxxabi as well)
I was navigating through the source for clang, & __cxa_get_globals() is the function where a calloc() call is made. I am not yet sure of the execution flow for clang.
Any idea or any inputs which could confirm this to be a Clang issue & not my code issue?
Here's the clang version I am using. The code is compiled with C++11, additionally with '-stdlib=libc++, '-lc++', '-lc++abi'.
[user~]$ clang --version
clang version 7.1.0
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/bin

Update: This exception is raised from the constructor.

Update
I wrote another dummy code to see the behaviour with Clang, & it seems the issue is actually with the Clang (libc++abi).
Have a look at the below naive code
#include <iostream>
#include <stdexcept>

class Positive {
    int m_number1;
 public:
    Positive() : m_number1(10) {
    }

    Positive(int no) {
        if (no < 0) {
//            throw 100;
              throw std::invalid_argument("Send positive nu");
        } else {
            m_number1 = no;
        }
    }

    ~Positive() {
    }

    void print() {
        std::cout<< "Value of member is: " <<m_number1 <<std::endl;
    }
};

int main() {
    try {
        Positive p1;
        p1.print();

        Positive p2(100);
        p2.print();

        Positive p3(-10);
        p3.print();

    } catch(...) {
        std::cout << "Some Exception occured" <<std::endl;
    }
   return 0;
}

Even on executing the above code, I saw the same result on Valgrind. Here's the output:
[user]$ valgrind --leak-check=full --leak-resolution=high --show-leak-kinds=all ./a.out
==119789== Memcheck, a memory error detector
==119789== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==119789== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==119789== Command: ./a.out
==119789==
Value of member is: 10
Value of member is: 100
Some Exception occured
==119789==
==119789== HEAP SUMMARY:
==119789==     in use at exit: 16 bytes in 1 blocks
==119789==   total heap usage: 3 allocs, 2 frees, 201 bytes allocated
==119789==
==119789== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==119789==    at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==119789==    by 0x40FF830: __cxxabiv1::__calloc_with_fallback(unsigned long, unsigned long) (in /usr/local/lib/libc++abi.so.1.0)
==119789==    by 0x40FE946: __cxa_get_globals (in /usr/local/lib/libc++abi.so.1.0)
==119789==    by 0x4101287: __cxa_throw (in /usr/local/lib/libc++abi.so.1.0)
==119789==    by 0x4014B0: Positive::Positive(int) (in /home/user/test/a.out)
==119789==    by 0x4010F9: main (in /home/user/test/a.out)
==119789==
==119789== LEAK SUMMARY:
==119789==    definitely lost: 0 bytes in 0 blocks
==119789==    indirectly lost: 0 bytes in 0 blocks
==119789==      possibly lost: 0 bytes in 0 blocks
==119789==    still reachable: 16 bytes in 1 blocks
==119789==         suppressed: 0 bytes in 0 blocks
==119789==
==119789== For counts of detected and suppressed errors, rerun with: -v
==119789== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[user]$

Interestingly, it shows 3 allocations made. Which I am assuming to be something related to the 3rd object, but how can I ensure that is cleared (or not allocated itself)?
Probably, the same thing can help me fix my original code.
Comment: Without seeing the code snippet its impossible to tell if the warnings was correct or not. But if you have manual memory allocations that are not in smart pointers (for example) then yes, it is possible for a `throw` to cause a memory leak.
Comment: @CoryKramer added the snippet for the function under test
Comment: what's `Status`?
Comment: @Swift-FridayPie, Status is a structure
Comment: `s_last_error`  is a global variable judging by `__cxa_get_globals` call?  It's likely it was allocating memory ahead of time  and string is still allocated after `throw `. does diagnostic change if you use  `s_last_error += AdditionalMsg;` It's kind of false positive then.
Answer: I also found this problem. It actually occurs if your code throws anything at least once, so the simplest reproduction scenario is just running this code:
int
main()
{
    try {
        throw 42;
    } catch (int) {}
}

However, if you throw several times there is still just one 16-bytes "leaked" block (which is not really leaked, since it is still reachable from some global variable). Digging into libc++abi library sources shows that such blocks are actually allocated once per thread to hold some exception processing context, and each one is freed when a thread is destroyed since it uses TLS and have proper destructor registered. So after all, it looks totally safe and is not an issue.


On the complexification of the commutator ideal

Question: Let $\mathfrak{g}$ be a real Lie algebra and $\mathfrak{g}_{\mathbb{C}}$ its complexification. Then, since $\mathfrak{g}$ is a Lie subalgebra of $\mathfrak{g}_{\mathbb{C}}$, the commutator ideal $[\mathfrak{g},\mathfrak{g}]$ is contained in $[\mathfrak{g}_{\mathbb{C}},\mathfrak{g}_{\mathbb{C}}]$. Now the complexification of $[\mathfrak{g},\mathfrak{g}]$ is $[\mathfrak{g},\mathfrak{g}]_{\mathbb{C}}$ and is obviously contained in $\mathfrak{g}_{\mathbb{C}}$ (since the complexification of a subspace must be contained in the complexification of the space itself).
My question is: Why does then follow that $[\mathfrak{g},\mathfrak{g}]_{\mathbb{C}} \subset [\mathfrak{g}_{\mathbb{C}},\mathfrak{g}_{\mathbb{C}}]$? We only know that $[\mathfrak{g}_{\mathbb{C}},\mathfrak{g}_{\mathbb{C}}] \subset \mathfrak{g}_{\mathbb{C}}$ and from that we can't conclude the claim, or can we? It is probably utterly trivial but I just don't see it.
Answer: The complexification is given by
$$
_ℂ=⊗_ℝℂ.
$$
Then we have
$$
[\mathfrak{g}_{\mathbb{C}},\mathfrak{g}_{\mathbb{C}}]=[\mathfrak{g}\otimes_{\mathbb{R}}\mathbb{C},\mathfrak{g}\otimes_{\mathbb{R}}\mathbb{C}]=[\mathfrak{g},\mathfrak{g}]\otimes_{\mathbb{R}}\mathbb{C}=[\mathfrak{g},\mathfrak{g}]_{\mathbb{C}},
$$
and the commutator is given by
$$
[x_1+iy_1,x_2+iy_2]=[x_1,x_2]-[y_1,y_2]+i([x_1,y_2]+[y_1,x_2].
$$
Comment: This is even more elegant


How to check that the data is 'null' in django view?

Question: I have a small validation to do in my view,i have to check whether the data received from the data field (for which'null'=true) of the form is null or not.
Presently i did this by
if data_received == None :
                    "some task"

and i got what i wanted.
My question is
Is this code optimum or there is some better way to do the same.
Comment: `if data_received is None:` is preferable..
Comment: @avasal That's not equivalent. It won't give the same result if `data_received` is false in a boolean context.
Comment: condition should be `if data_received`:
Comment: @avasal It also won't give the same result of data_received is equal to 0.
Answer: That's pretty much as good as it's going to get. You typically want to use is None instead of == None just in case the left hand side is an instance of a class which has defined == to mean something special when used with None, but it's not a big deal here.
Answer: is None used for == null   and  is not None used for !=null
Answer: That's the best way I can think of doing it.  If your pulling data that might be Null in Django from an SQL server then you might have a bottleneck in actually pulling that data.


Pólya's Urn, but No Induction

Question: Recall Pólya's Urn: Initially there is 1 red and 1 blue ball in an urn. In
each step, we select a ball from the urn uniformly at random, and then put it back
together with a new ball of the same color. Therefore after n steps, there are n + 2
balls in the urn. Suppose that after n steps there are r + 1 red and b + 1 blue balls,
where r + b = n. Show that $\frac{r}{(r + b)}$ is the conditional probability that a red ball was
selected in the first step. Fully justify your answer.
Hint: Let $C_1$ be the color of the first ball selected. Let $R_n$ the number of red balls
after n steps. Explain why $$P(R_n = r+1|C_1 = R) = 2\binom{n-1}{r-1}\frac{r!b!}{(n+1)!}$$ and $$ P(R_n = r+1|C_1 = B) = \frac{b}{r}P(R_n = r+1|C_1 = R)$$
I'm familiar with normal urn and red/blue ball problems, but this one has me confused in a few ways...Where did the equations in the "hint" come from? How do the hint equations for the $C_1$ case help lead us to finding $\frac{r}{(r + b)}$ is the conditional probability? The problem is also asking me to "argue directly" rather than use induction. And then "apply Bayes Rule." Any help or direction with this problem would be very much appreciated!
Answer: @BallBoy already fully answered your question, but here is a (IMHO) more interesting proof.
Consider a specific sequence of draws to get to $(r+1, b+1)$ final state, e.g. $(C_1, C_2, C_3, \dots) = (R, B, R, \dots)$ etc.  Can you prove that (somewhat surprisingly) each such sequence is equally likely?
Once you prove that, the problem becomes: you have $r$ red balls and $b$ blue balls and randomly line them up.  What is the probability the first ball is red?  Clearly the answer is just ${r \over r+b}$.
Answer: Some direction:
For the first equation in the hint, you are given that at step $1$ you pick and add a red ball. You need the probability that, in the remaining $n-1$ steps, you will pick and add exactly $r-1$ red balls. First you need to choose which $r-1$ steps will be red; then you need to find the probability of picking that exact situation.
For the second equation in the hint, calculate using the same method, then relate it to $P(R_n=r+1|C_1=R)$.
Once you have the relation in the second equation, forget about the first equation, and now apply Bayes' Rule to calculate $P(C_1=R|R_n=r+1)$. You'll see that the $P(R_n=r+1|C_1=R)$ terms cancel.
Good luck!

Pólya’s Urn, but No Induction


SWIG reference input, custom class output

Question: I am trying to work with C++ lib in C# with SWIG.
I have a method which gets float and/or uint8_t reference inputs and returns with a custom class object.
Cannot apply SWIG commands to overcome on this right.
C++:
virtual eoReturn GetValue(CHANNEL_TYPE type, float &value) {...}
virtual eoReturn GetValue(CHANNEL_TYPE type, uint8_t &value) {...}

.i:
%module eoTest
%{
    #include "eoTest.h"
%}

%include typemaps.i
%include cpointer.i
extern eoReturn eoProfile::GetValue(CHANNEL_TYPE INPUT, float &INPUT);
extern eoReturn eoProfile::GetValue(CHANNEL_TYPE INPUT, uint8_t &INPUT);
%include "eoTest.h"

Is still SWIGTYPE_p_float and unsigned_char.
Any idea how to solve this? Or how to initalize a SWIGTYPE_p_float in C#? That also would help I guess.
Answer: One solution what found:
added the following to the interface file:
%include cpointer.i
%pointer_functions(float, floatp);

This has created methods with names like 'new_floatp', 'delete_floatp', 'floatp_assign'...
Could use in C# like this:
SWIGTYPE_p_float f = WrapperCPP.new_floatp();
WrapperCPP.floatp_assign(f, 12);
Console.WriteLine("Value: " + WrapperCPP.floatp_value(f).ToString("0.0")); // Value: 12
WrapperCPP.delete_floatp(f);

This would work same for uint8_t too as
%pointer_functions(unsigned char, uintp);

Hope could help someone too. Cheers


Output observable when slider track is clicked

Question: How do I go about about outputting the sliders value (selectedV) when the track is clicked. Currently i can only achieve this by dragging the sliders handle.
I click the track to move the handle the observable does not register.
<code>self.selectedV = ko.observable(2);
</code>
Here is my example:
http://jsfiddle.net/ERz7u/21/
Comment: Use the `slideStop` event.
Answer: As @Origineil suggested, changing the following piece of code from
<code>$(element).on('slide', function (ev) {
    valueObservable(ev.value);
});
</code>
to
<code>$(element).on('slideStop', function (ev) {
    valueObservable(ev.value);
});
</code>
does give the results you expect. (at least in chrome )
http://jsfiddle.net/gonefishern/ERz7u/30/


HQL java.lang.NumberFormatException: For input string

Question: Hello can you please help me. I have been trying to fix this for past few days without any success. I am trying to query "Biljeska" objects and return them as Biljeska list. Classes setup:
Biljeznica.java:
@Entity
@Table(name = "biljeznica")
public class Biljeznica implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -5589212916227508153L;

    @Id
    @Column(name= "naziv")
    private String naziv;

    @Column(name= "opis")
    private String opis;

    public Biljeznica(){}
// getters and setters

Korisnik.java:
@Entity
@Table(name = "user")
public class Korisnik extends NovaBiljeskaForm implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 3476436475286629836L;

    @Id
    @Column(name= "id")
    @GeneratedValue
    private int id;

    @Column(name= "ime")
    private String ime;

    @Column(name= "prezime")
    private String prezime;

    @Column(name= "username")
    private String nick;

    public Korisnik(){}
//getters and setters

Biljeska.java:
@Entity
@Table(name = "biljeska")
public class Biljeska implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 3706596321179671012L;

    @Id
    @Column(name= "id")
    @GeneratedValue
    int id;

    @Column(name = "naslov")
    private String naslov;

    @Column(name = "tekst")
    private String tekst;

    @ManyToOne (cascade = CascadeType.ALL)
    @JoinColumn(name ="korisnik")
    private Korisnik korisnik;

    @ManyToOne (cascade = CascadeType.ALL)
    @JoinColumn(name = "biljeznica")
    private Biljeznica biljeznica;

    public Biljeska(){}

h2 schema:
CREATE TABLE user (
id INT(11) IDENTITY PRIMARY KEY,
ime VARCHAR(50) NOT NULL,
prezime VARCHAR(50) NOT NULL,
username VARCHAR(45),
password VARCHAR(100) NOT NULL ,
enabled TINYINT NOT NULL DEFAULT 1
);
CREATE TABLE biljeznica (
naziv VARCHAR(50) PRIMARY KEY,
opis VARCHAR(100) NOT NULL
);
CREATE TABLE biljeska (
id INT(11) IDENTITY PRIMARY KEY,
naslov VARCHAR(100),
tekst VARCHAR(1000),
korisnik VARCHAR(45) NOT NULL,
biljeznica VARCHAR(50) NOT NULL,
FOREIGN KEY (korisnik) REFERENCES user (username),
FOREIGN KEY (biljeznica) REFERENCES biljeznica (naziv)
);

Data i am inserting into schema via test-data.sql :
INSERT INTO user(ime, prezime,username,password,enabled)
VALUES ('Ivo','Ivić','iivic','$2a$10$VQoRdaQK0KzAl4QoBzfZleRBcHitGS5jRA771ilGdL2DvkVTLDqSe', true);
INSERT INTO user(ime, prezime,username,password,enabled)
VALUES ('Marko','Markić','mmarkic','$2a$10$VQoRdaQK0KzAl4QoBzfZleRBcHitGS5jRA771ilGdL2DvkVTLDqSe', true);
INSERT INTO user(ime, prezime,username,password,enabled)
VALUES ('Pero','Perić','pperic','$2a$10$VQoRdaQK0KzAl4QoBzfZleRBcHitGS5jRA771ilGdL2DvkVTLDqSe', true);
INSERT INTO user(ime, prezime,username,password,enabled)
VALUES ('Adminko','Adminić','admin','$2a$10$VQoRdaQK0KzAl4QoBzfZleRBcHitGS5jRA771ilGdL2DvkVTLDqSe', true);
INSERT INTO user_role (username, role)
VALUES ('iivic', 'ROLE_USER');
INSERT INTO user_role (username, role)
VALUES ('mmarkic', 'ROLE_USER');
INSERT INTO user_role (username, role)
VALUES ('pperic', 'ROLE_USER');
INSERT INTO user_role (username, role)
VALUES ('admin', 'ROLE_USER');
INSERT INTO user_role (username, role)
VALUES ('admin', 'ROLE_ADMIN');
INSERT INTO biljeznica(naziv, opis)
VALUES('Web aplikacije u Javi', 'Bilješke s predavanja iz kolegija web aplikacije u
Javi');
INSERT INTO biljeznica(naziv, opis)
VALUES('Razvoj aplikacija na Android platformi', 'Bilješke s predavanja kolegija razvoj
aplikacija na Android platformi');
INSERT INTO biljeznica(naziv, opis)
VALUES('Napredne teme računalnih mreža', 'Bilješke s predavanja napredne teme
računalnih mreža');
INSERT INTO biljeska(naslov, tekst, korisnik, biljeznica)
VALUES('Testni naslov', 'Testni tekst', 'iivic', 'Web aplikacije u Javi');
INSERT INTO biljeska(naslov, tekst, korisnik, biljeznica)
VALUES('Moj naslov', 'Moj tekst', 'pperic', 'Web aplikacije u Javi');

Method in repository class where i want to return list of Biljeska objects:
@Autowired
    public HibernateBiljeskaRepository(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session currentSession() {
        return sessionFactory.getCurrentSession();
    }
    public List<Biljeska> findAll() {
        return currentSession().createQuery("select b from Biljeska b, Biljeznica bi, Korisnik k where b.korisnik = k and b.biljeznica = bi",Biljeska.class).getResultList();
    }

Exception occurs at return statment of findAll() method
Error messagge i am getting:
Apr 28, 2017 1:19:01 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 22018, SQLState: 22018
Apr 28, 2017 1:19:01 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Data conversion error converting "iivic"; SQL statement:
select biljeska0_.id as id1_0_, biljeska0_.biljeznica as biljezni4_0_, biljeska0_.korisnik as korisnik5_0_, biljeska0_.naslov as naslov2_0_, biljeska0_.tekst as tekst3_0_ from biljeska biljeska0_ cross join biljeznica biljeznica1_ cross join user korisnik2_ where biljeska0_.korisnik=korisnik2_.id and biljeska0_.biljeznica=biljeznica1_.naziv [22018-193]
Apr 28, 2017 1:19:01 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/labos1] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not extract ResultSet] with root cause
java.lang.NumberFormatException: For input string: "iivic"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at org.h2.value.Value.convertTo(Value.java:922)
    at org.h2.mvstore.db.MVPrimaryIndex.getKey(MVPrimaryIndex.java:338)
    at org.h2.mvstore.db.MVDelegateIndex.find(MVDelegateIndex.java:69)
    at org.h2.index.BaseIndex.find(BaseIndex.java:128)
    at org.h2.index.IndexCursor.find(IndexCursor.java:169)
    at org.h2.table.TableFilter.next(TableFilter.java:467)
    at org.h2.table.TableFilter.next(TableFilter.java:537)
    at org.h2.command.dml.Select.queryFlat(Select.java:542)
    at org.h2.command.dml.Select.queryWithoutCache(Select.java:655)
    at org.h2.command.dml.Query.query(Query.java:341)
    at org.h2.command.dml.Query.query(Query.java:309)
    at org.h2.command.dml.Query.query(Query.java:36)
    at org.h2.command.CommandContainer.query(CommandContainer.java:110)
    at org.h2.command.Command.executeQuery(Command.java:201)
    at org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcPreparedStatement.java:110)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:71)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2123)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1911)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    at org.hibernate.loader.Loader.doQuery(Loader.java:932)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    at org.hibernate.loader.Loader.doList(Loader.java:2615)
    at org.hibernate.loader.Loader.doList(Loader.java:2598)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2430)
    at org.hibernate.loader.Loader.list(Loader.java:2425)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:375)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1481)
    at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1441)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1410)
    at org.hibernate.query.Query.getResultList(Query.java:146)
    at hr.tvz.hibernate.HibernateBiljeskaRepository.findAll(HibernateBiljeskaRepository.java:58)
    at hr.tvz.hibernate.HibernateBiljeskaRepository$$FastClassBySpringCGLIB$$d420114f.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
    at hr.tvz.hibernate.HibernateBiljeskaRepository$$EnhancerBySpringCGLIB$$d7521f20.findAll(<generated>)
    at hr.tvz.controleri.NovaBiljeskaController.showSpremljeneBiljeske(NovaBiljeskaController.java:215)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

I am really confused and i do not understand why am i getting this error...
Thank you in advance!
Edit :
Solved thanks to Alex
Solution: change Biljeska attributes into
@ManyToOne (fetch = FetchType.EAGER)
@JoinColumn(name ="korisnik", referencedColumnName="username")
private Korisnik korisnik;

@ManyToOne (fetch = FetchType.EAGER)
@JoinColumn(name = "biljeznica", referencedColumnName="naziv")
private Biljeznica biljeznica;

and hql to :
"select b from Biljeska b"

Comment: suppose you can share the User.java where the exception happens.
Comment: Exception happens at line  return currentSession().createQuery("select b from Biljeska b, Biljeznica bi, Korisnik k where b.korisnik = k and b.biljeznica = bi",Biljeska.class).getResultList(); and user.java does not exist
Comment: suppose you follow this [post](https://www.javacodegeeks.com/2013/03/bidirectional-onetomany-manytoone-association.html) on `@ManyToOne` and `@OneToMany` relationships. your pojo  class is missing relationship.
`
Answer: In SQL code you made biljeska.korisnik a foreign key to user.username. But in the Java code, you didn't specify what column of the Korisnik class the foreign key refers to, so it's trying to refer to the primary key, which is an integer and that's why you got NumberFormatException.
You must use JoinColumn.referencedColumnName in Biljeska.korisnik to reference the username column.
Comment: Thank you for your answer it helped me :) . + I just had to change hql query to "select b from Biljeska b". You got beer on me !!


Throttling Email Requests

Question: I have some questions regarding user experience when it comes to throttling email requests from public pages in my app such as Signup Email Verification and Password Recovery.
First of all, I want to throttle requests because I do not want to spam email recipients with my app's transactional emails. I am concerned about User A trying to signup an account using User B's email address for the sake of annoying User B at my app's expense (like getting flagged as spam)
I haven't read a fool proof approach to protect apps from these types of attacks (if you know of one, I would really appreciate it if you can tell me).
Currently I have implemented a captcha, but I would also like to implement throttling. So my questions would be:

How many times would I let a user send a request before I throttle sending emails for the same request? I did a single quick test with facebook, and I learned they throttle password recovery emails after the 3rd try.
How long should I throttle the request? 10 minutes? 30 minutes?
Should I A) let the user know I throttled the request, like placing a notice? or B) Act like I didn't do anything? Facebook did (B). I think it is more of a security thing? But, my problem is that, if I choose (B), a legitimate user not receiving any emails would keep on requesting for the whole throttling period. Which would be very bad UX?
Comment: Are you sure this potential misuse situation is actually a likely one though? You could design safety features for all sorts of potential situations, but if they're never really that big a risk in the first place perhaps your energy could be best used elsewhere?
Comment: No, that's a fair point - that is a valid situation. But it's more of a business driver than one of user experience. Not that it matters here though - the solutions to the problem still impact the user experience.
Comment: @JonW I agree with you on that 100%, but for this one the main problem is our domain's sending reputation (or sender score?). Being a startup with low sending rate, the percentage of a spam attack like this can really hurt our sending reputation with email systems and it would be very difficult to recover from it. Correct me if I am just being over paranoid.
Comment: @JonW Yeah, we really wanted to make it more open, but we had to really consider some worst case scenarios and how great the impact will be. So we decided to do it in the end. Right now we wanted to learn some best practices from others for the throttling so that we do not over discourage potential users.
Answer: Something to remember about transactional emails is that they should be intentionally triggered by the user. What this means is a site shouldn't send a confirmation or password reset email unless the user directly requests it.
Why does that matter? Because if the user intentionally did something, you don't need to ask them to do it again. They already went through the trouble. Though you may be concerned about people exploiting the system, design for your typical user first. Once a particular form is submitted, like for a password reset, there's no reason to even have that form be available anymore until the password has been reset. This means, simply don't send the same email twice. Of course, minor exceptions exist, but for the most part there isn't a good reason for a user to receive the same email over and over again.
When it comes to throttling rates, the answer to what you should do specifically is this: For those on dedicated IPs, your throttle rate should be fine tuned to match your IP reputation. (It never hurts to know this.) If you're on a shared IP, your host might be handling that for you. This means, quite commonly, err on the safe side and throttle as much as possible. The last thing you want is to be flagged by an ISP as spam.
You don't need to let the user know about your batch process. Only inform the user about their experience and how that experience is being affected. This means saying something to the effect of:
We sent you an email [to do a thing]. You should see it in your inbox within [a timeframe]. If you don't see it, *let us know* and we'll sort things out.
If you detect that something shady is likely going on, then lock the account, but don't blame the user. Just inform them through a secure method of the steps that should be taken to fix things.

Throttling Email Requests


What is this type of navigation is called?

Question: I came across the term for this style of navigation on a site but I failed to save the url. Anyone know what this type of navigation is called?
Comment: Are you looking for the name of the navigation style (which is a user mode)? Or for the specific piece of UI (which is a bunch of pixels)?
Comment: I'm going to go with Antid's answer below. It looks like a regular ol' navbar. Does it appear on the top of the screen? The layout of it looks like a Button Group: http://getbootstrap.com/components/#btn-groups
Comment: There was a specific term used in the article "something something picker" which is being used in the UX community.
Answer: If the purpose is to serve as navigation header for your site, this is called Navigation Bar. http://getbootstrap.com/components/#navbar
Answer: I believe it's called a "scope bar" according to Apples HIG. I suppose it depends on the context in which it's used.
Comment: A scope bar implies that the options are different scopes on a single data set. I expect that Work and Play could be two scopes on one set of data, but Profile, Notebook, and especially the Twitter icon seem to be unrelated.


How to write the new RCT AppDelegate interface with User Notifications in ios on react-native

Question: I've recently upgraded my react-native SDK version to 0.73,
But according to the Upgrade Helper here the AppDelegate interface definition changed from
@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate>

to
@interface AppDelegate : RCTAppDelegate

But as my project uses "UserNotifications" which should be used to extend/implement the AppDelegate interface, I couldn't figure out how to extend this new interface.
Answer: Alrighty, found it here: https://github.com/zo0r/react-native-push-notification/issues/2344
To extend the AppDelegate interface with the latest react-native, I should use the obvious
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UNUserNotificationCenter.h>

@interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>

@end


Wiping my Hard Drive and dualbooting Ubuntu 13

Question: I've searched far and wide, but still haven't found a way to do what I want;
I want to set up a GNU GRUB dualboot with windows 7 and ubuntu 13. As of now, I am running a;

Alienware M15X Purchased September 14 2010
Intel Core i7 CPU Q740 @ 1.73GHz 1.73GHz
6GB of RAM
64-bit Windows 7 Ultimate Service Pack 1
ATI Mobility Radeon HD 5800 Series

I want to wipe everything on my desktop other than files necessary for windows to still perform. I want no information left, other than windows 7 in a running state. After that, I'll add Ubuntu as a dual-boot using GNU GRUB. Any recommendations?
Answer: This is probably your best course of action: you make a recovery disk in Windows, boot off of it, and re-install, which will wipe your hard drive and give you a fresh install. Afterwards, make an Ubuntu boot disk and select "Boot alongside Windows 7" at installation. Then just follow the instructions on screen from there on out.
Answer: The files in Windows you can uninstall via Windows control panel and delete any folders that you don't need. Then for Ubuntu this link has all the answers for a windows user not familar with Ubuntu.


A curious observation regarding eigenvectors of $3 \times 3$ matrices - Hoffman and Kunze's *Linear Algebra*

Question: I am reading Hoffman and Kunze's Linear Algebra, 2nd ed., and I made a curious observation in a couple of the examples relating to computing eigenvalues and eigenvectors in Chapter 6.
In Example 2 on pages 184-185, we have the (real) $3 \times 3$ matrix
$$
A = \begin{bmatrix}
3 & 1 & -1\\
2 & 2 & -1\\
2 & 2 & \phantom{-}0
\end{bmatrix}.
$$
The characteristic polynomial for $A$ is $(x-1)(x-2)^2$. Thus, the characteristic values of $A$ are $1$ and $2$. We have
$$
\begin{align}
A - I &=
\begin{bmatrix}
2 & 1 & -1\\
2 & 1 & -1\\
2 & 2 & -1
\end{bmatrix}\\\\
A - 2I &=
\begin{bmatrix}
1 & 1 & -1\\
2 & 0 & -1\\
2 & 2 & -2
\end{bmatrix}.
\end{align}
$$
The characteristic spaces associated to each characteristic value is one-dimensional in this case. The vector $\alpha_1 = (1,0,2)$ spans the null space of $T - I$ and the vector $\alpha_2 = (1,1,2)$ spans the null space of $T - 2I$.
Here, my observation is that $\alpha_1$ is the middle column vector of $A - 2I$, and $\alpha_2$ is the middle column vector of $A - I$.
A similar thing happens in Example 3 (pages 187-188):
$T$ is the linear operator on $\Bbb{R}^3$ which is represented in the standard ordered basis by the matrix
$$
A =
\begin{bmatrix}
\phantom{-}5 & -6 & -6 \\
-1 & \phantom{-}4 & \phantom{-}2 \\
\phantom{-}3 & -6 & -4
\end{bmatrix}.
$$
The characteristic polynomial is computed to be $(x-2)^2(x-1)$. Then, we have
$$
\begin{align}
A - I &=
\begin{bmatrix}
\phantom{-}4 & -6 & -6 \\
-1 & \phantom{-}3 & \phantom{-}2 \\
\phantom{-}3 & -6 & -5
\end{bmatrix}\\\\
A - 2I &=
\begin{bmatrix}
\phantom{-}3 & -6 & -6 \\
-1 & \phantom{-}2 & \phantom{-}2 \\
\phantom{-}3 & -6 & -6
\end{bmatrix}.
\end{align}
$$
The null space of $T-I$ is one-dimensional and the null space of $T-2I$ is two-dimensional. The vector $\alpha_1 = (3,-1,3)$ spans the null space of $T-I$. The null space of $T-2I$ consists of the vectors $(x_1,x_2,x_3)$ with $x_1 = 2x_2 + 2x_3$, so the authors give an example of a basis of the null space of $T-2I$ as $$\begin{align}\alpha_2 &= (2,1,0)\\ \alpha_3 &= (2,0,1).\end{align}$$ However, we can also take $$\begin{align}\alpha_2 &= (-6,3,-6)\\ \alpha_3 &= (-6,2,-5)\end{align}$$ and we see again that $\alpha_1$ is the first column of $A - 2I$ and $\alpha_2,\alpha_3$ are the second and third columns of $A - I$.
I find this quite curious, more so since the authors don't mention this observation at all. Is there a simple explanation for why this is happening, and can this observation be used to quickly find eigenvectors of linear transformations?
Answer: Let the minimal polynomial of $A$ be
$$
f(x) = \prod_{i=1}^n (x-\lambda_i),
$$
where $\lambda_1,\dots,\lambda_n$ are eigenvalues of $A$ (not necessarily distinct).
Then,
$$\prod_{i=1}^n(A-\lambda_i)=0.$$
So, we have
$$(A-\lambda_1)(\prod_{i=2}^n(A-\lambda_i))=0,$$
that is, the columns of $\prod_{i=2}^n(A-\lambda_i)$ are eigenvectors of $
\lambda_1$.
Comment: If you take $\lambda_1=1$ and $\lambda_2=\lambda_3=2$, then the result is $(A-1)((A-2)^2)=0$. The columns of matrix of $(A-2)^2$ do.
Comment: I think one should use the minimal polynomial of $A$ in this argument, not the characteristic polynomial. For Example 3, by the given argument we will say that the columns of the matrix $(A-I)(A-2I)$ are eigenvectors of $A$ with eigenvalue $2$ because the characteristic polynomial of $A$ is $(x-1)(x-2)^2$. However, $(A-I)(A-2I) = 0$, so this does not really say anything. If we instead argue with the minimal polynomial in place of the characteristic polynomial then the argument is correct.
Comment: But in the first example, it is only the middle column of $A - 2I$ that is an eigenvector of $A$ for the eigenvalue $1$, not the other columns.
Comment: Oh! I see what you mean now. This is lovely :)
Comment: @Brahadeesh  You are right.
Comment: Very interesting connection HCT with eigenvectors (+1)


How to focus first invalid ngx-formly field

Question: I am using ngx-formly for creating dynamic form from field configuration. On submitting form, validation is showed correctly. I want to focus first invalid formly field.
Answer: A little late to the party here but I was able to implement a solution that returned the user to the first instance of an invalid input using getElementById:
<code>  var errorField = null;
  fields.forEach(field => {
    for (var key in field.formControl["controls"]) {
      let control = field.formControl["controls"][key];
      if (control instanceof FormControl && control.status === "INVALID") {
        errorField = control["_fields"][0]["_elementRefs"][0].nativeElement.id;
        break;
      }
      else if (control instanceof FormGroup) {
        for (var subKey in control.controls) {
          let subControl = control.controls[subKey];
          if (subControl.status === "INVALID") {
            errorField = subControl["_fields"][0]["_elementRefs"][0].nativeElement.id;
            break;
          }
        }
      }
      if (errorField) break;
    }
  });

  let el = document.getElementById(errorField);
  el.scrollIntoView({
    behavior: 'smooth',
    block: "center"
  });
</code>


How I can use Twig on Codeigniter?

Question: How I can use Twig on Codeigniter?
I want to install twig with composer then use twig in my project but i can't do it.
please tell me step by step, thanks.
Comment: Why can't you do it? Why not just look at the documentation? This is a Q&A site, not a code writing service.
Answer: Of course you can, it can be tricky to configure but just load twig as a library.
Here is the repository I use for my CI project with Twig: https://github.com/kenjis/codeigniter-ss-twig
Comment: i installed this configuration:
### Installation With Composer and then in controllers/welcome.php used this codes:
  `$this->load->library('twig');
  $data = 'welcome to codeigniter !';
  $this->twig->display('welcome_message', $data);`

  then in welcome_message.php writed
  `{{ data }}`
  but has an error:
**Fatal error: Class 'Twig_Loader_Filesystem' not found in C:\xampp\htdocs\CITwigWithComposer\application\libraries\Twig.php on line 94**
  hot to fix it?

How I can use Twig on Codeigniter?


SnowFlake-Kafka connector -> Landing Table -> Destination table. How to cleanup Landing Table

Question: I'm investigating taking data from Kafka -> SnowFlake/Kafka connector -> SnowFlake. Unfortunately, the connector seems to use just two columns (and put the entire JSON payload into a single column). So I created a stream/task to periodically copy data from the landing table to the destination table (using insert). Everything works beautifully except for deleting data in the landing table once it has landed in the destination table. Using streams, I know what has landed. How do I delete the rest of the data? Truncate seems so much faster. Do I just periodically run a delete task that deletes these entries? I am also concerned about warehouse time to perform these deletes. Thanks
Comment: Did you ever find a solution that worked for you? If so, can you share?
Answer: For a use case where multiple statements(like insert, delete, etc) to access the same change records, surround them in explicit transaction statement(Begin..Commit) which will lock stream.
You can have an additional column like a Flag, lock stream using Begin, use the stream to insert to target table from staging, use stream to perform a second merge to staging table to mark the column Flag.
https://docs.snowflake.com/en/user-guide/streams.html#examples

begin;

select * from <stream>;

insert into target_table select columns from <stream> where metadata$action='INSERT' and flag=0;

merge into staging_table st
using (
select column
  from stream
  where flag = 0) sc
  on st.column=sc.column
  when matched then update set st.flag=1;
commit;
delete from staging_table where flag=1;
Comment: What do I set for the conditional? I already use  "when SYSTEM$STREAM_HAS_DATA('kafka_check')" for my insertion task. How do I then say delete record=0 to record = current in the underlying table where current is the record that I just consumed in the stream that tracks that table? I think my problem is how do I translate the stream state back to thee underlying table to do a efficient delete? Thanks
Comment: Another workaround would be to stop the kafka connector, consume the stream, truncate the staging table, recreate the stream, and turn on the connector again.
Comment: Would it work to just pause the snowpipe rather than stopping the Kafka Connector? Or does that cause errors within the Connector? If pausing works, I would see the path similar as: pause pipe -> consume data -> truncate -> recreate stream -> resume snowpipe. We are trying to solve the exact same issue.


Back button on mobile web app

Question: I have 2 main questions about the back button and its functionality on a web site when running on a mobile. This isn't an app, but a responsive website working like an app.
The first question is whether or not should I use the back button or not and use the native button from the mobile device? I've been looking and found this question. It has a great answer but it's from 2011. The scenario is very different today.
I know we shouldn't rely on the browser functionality and provide the ones we need by ourselves. But today almost all the mobiles have a back button that most users are used to use. So is it ok to remove the back button?

Second, and most important question. If I stay with the back button, is it ok to use it until the users reach the home page? Or it should always go back 1 step in the history?
For example, let's say I have an e-commerce, the users search, find a list of products, return to the homepage and search again, this time he finds an item, explore it and decide to go back.
Should I provide a back button until he reaches the homepage or go all the way back? What is the best use case?
The page I'm building is like an e-commerce, but users can't buy, just search and then contact the company.
Answer: Question 1: Back button is totally needed! There is a few reasons for this.

With a back button, you ensure consistancy accross devices and browsers. Each browser could have the button in different places, different shapes or even hidden in a submenu. Essentially, you maintain control of the experience.
Not all user uses the back button in browser, myself for example, I almost never do on mobile.
Maintain Expectations. A good web app will feel as native as possible and the user will expect it's standard natigation to be found in all apps.
Control the behavior. With a back button you have full control over the behavior versus the browser button. (More about that in Q2).

Android apps is a perfect example of this. Back navigation is core to the system input but all apps still maintain the back button within their UI.
Question 2:
A back button should always go back the previous location in the hierarchy, ideally in the same state. Meaning if the page was scrolls to item Y, then going back should bring you back to list, scolled to item Y.
It is important to note that a back button does not go back in "history" but rather in "hierarchy".
History:
A -> B -> C -> D -> C
Hierarchy:
A -> B -> C -> D
Using this history, if the button was pressed at any step, the back button should result in:
NA | A | B | C | B
There could be a few justified exception to this. If a step makes the previous one not relevant anymore, then you could "double" jump back in hierarchy. For instance, if you ask a user to confirm his phone number and that it is "final" then going back should not bring you back to the confirm phone number screen.
If your application goes really deep, such as browse "categories-> category 1 -> category 1.1 -> category 1.1.1" then consider using a "home" or "categories" button to go back to the root!
Hope this helps! :)

Back button on mobile web app


Action of symmetric group

Question: First of all, this is again one of my questions ! Sorry, at the moment I've got plenty of questions ! There is something I just struggle with since hours. In an exam I got, I had to show that if we have $p$ a prime number and $A$ a set of $p$ elements, then :
$S_p \times A^p \rightarrow A^p$ defined by $(\sigma, (a_1, \dots, a_p)) \rightarrow (a_{\sigma^{-1}(1)}, \dots, a_{\sigma^{-1}(p)}) = \sigma .(a_1, \dots, a_p)$
is a group action. But I don't find out why ! Thus, if I take for example $A = \{a_1, a_2, a_3\}$ a set of three elements and I consider $s=(1 \; 2)$, $t=(1 \; 2 \; 3)$, we have : $t.(a_1,a_2,a_3) = (a_{t^{-1}(1)}, a_{t^{-1}(2)}, a_{t^{-1}(3)}) = (a_3, a_1, a_2)$, and $s.(t.(a_1,a_2,a_3)) = (a_3, a_2, a_1)$. Now if the application is an action of group, we must have : $(st).(a_1,a_2,a_3) = s.(t.(a_1,a_2,a_3))$ ; but we have $st = (2 \; 3)$, so $st.(a_1, a_2, a_3) = (a_1, a_3, a_2) \neq (a_3, a_2, a_1)$. So, I find that finally, this is not a group action !
Is there somewhere I made a mistake ? In the same way :
$s.(t.(a_1, \dots, a_n)) = s.(a_{t^{-1}(1)}, \dots, a_{t^{-1}(p)}) = (a_{s^{-1}(t^{-1}(1))}, \dots, a_{s^{-1}(t^{-1}(p))}) = (a_{s^{-1}\circ t^{-1}(1)},\dots, a_{s^{-1}\circ t^{-1}(p)})$,
and as : $s^{-1} \circ t^{-1} = (ts)^{-1}$, we have : $s.(t.(a_1, \dots, a_n)) = (ts).(a_1, \dots, a_p)$.
But I must have made a mistake, cause I have to show that this is an action... But I don't find where !
Someone could help me ?
Answer: Observe that when you make act $\;(12)\;$ on something, it is in the order they are given, thus:
$$s(t(a_1,a_2,a_3)=s(a_3,a_1,a_2)=(a_1,a_3,a_2)$$
and now $\;st=(23)\;$ , and thus
$$st(a_1,a_2,a_3)=(a_1,a_3,a_2)=s(t(a_1,a_2,a_3)) ...!$$
If it is not with the above agreement, what you're given is, certainly, not a group action...
Comment: Okay, thank you ! I get it !

Action of symmetric group


Surjectivity and Orthogonal Complements with Quadratic Forms

Question: My question is asking to clarify the final part of a proof proposed in the following link:
Guarantees of a Quadratic Form for Two Related Matrices
The question being:

Suppose I have a matrix: $\mathbf{Q} =\mathbf{Z}^T\mathbf{B}\mathbf{Z}$, where $\mathbf{Z} \in \mathbb{R}^{n\times m},\mathbf{B}\in\mathbb{R}^{n\times n}, m \leq n.$
Can I say that if $\mathbf{Q}$ is positive definite, then $\mathbf{B}$
  is also positive definite?

Now the responder has helped met a lot, but I cannot fathom why "$B$ is not definite positive" in the final part of the proof. Namely in the paragraph:

Now, if $Z$ is not surjective, it's false. Choose B which is definite
  positive in the range of $Z$ and definite negative in the orthogonal
  complement. Then for all $X\neq0$, $X^T Q X > 0$ but B is not definite
  positive.

Simply expanding $X^T Q X$ I arrive at $X^T Z^T B ZX$ but I cannot see how we use orthogonal complement properties from here, or the fact that $Z$ is now non-surjective.
Answer: Something clicked and I think I understand it now. I am posting my interpretation here for others to comment on:
Suppose $Z$ is not surjective. This means dim(Im($Z$)) < n.
Everything that Im($Z$) cannot map to is by definition the orthogonal compliment by the following statement for finite dimensional inner product spaces:
$V=Im(Z)  \bigoplus Im(Z)^{\perp}$
So let's assume we construct a B such that there exists $x \in Im(Z) : x^TBx > 0$ and there exists $y \in Im(Z)^{\perp} : y^TBy \leq 0$. That is the $B$ is positive definite in the image, and negative definite in the orthogonal compliment.
Then $u^TQu > 0,$ $ \forall u \in \mathbb{R}^m$ but $ u^T B u$ not necessarily always $> 0 $ due to its construction. That is $u \in \mathbb{R}^m $ but sometimes $u \in Im(Z) $ and other times $u \in Im(Z)^{\perp}$.
(I think in fact if $B$ is symmetric then $Im(Z)^{\perp} = ker(Z^T) = ker(Z) \Rightarrow u^T B u = 0$).
Let me know how others feel about the precision of this argument.


Minimum of $f(x,y)=|ax-by|$ subject to box constraints

Question: $$ \begin{array}{ll} \underset {x, y} {\text{minimize}} & f(x,y) := | a x - b y | \\ \text{subject to} & 0 \le x \le C_1 \\ & 0 \le y \le C_2 \end{array} $$
What is the minimum? I found a similar question, Minimum of $|az_x-bz_y|$, but their $x$ and $y$ are integers. Thus, I guess the question is very different.
I started by computing partials:
\begin{align}
\frac{df}{dx}=\frac{a(ax-by)}{|ax-by|}=a\, {\mathrm{sign}(ax-by)}\\
\frac{df}{dy}=\frac{b(by-ax)}{|ax-by|}= b\, {\mathrm{sign}(by-ax)}\\
\end{align}
Having difficulty proceeding further with the Lagrange method. Is there a simpler way?
Comment: You calculated $\frac{df}{dx}$ wrong. It is $\pm a$ , depending on the sign of $ax-by$.
Comment: Please see the corrections
Answer: There is a simpler way:
$f(x,y) \ge 0$ and $f(0,0)=0$ so the minimum is $0$.
You also have $f\left(x,\dfrac{a}{b}x\right)=0$, which may provide other ways of achieving the minimum. At these points, there may not be a well-defined derivative.
Comment: Are there other minimums. For example, if we  exclude point $(x,y)=(0,0)$.
Comment: Also, do you think there is an analytical solution. Like Lagrange method???
Comment: There are other minima when $\left(x,\dfrac{a}{b}x\right)$. Your derivatives are telling you that when $ax \gt by$ then reduce $x$ or increase $y$, and when $ax \lt by$ then reduce $y$ or increase $x$.


Ratchet Server vs Long Polling

Question: I am developing a website which has a chat feature and requires instant notifications when a user receives a new message.  I am trying to decide whether to use a Ratchet server or implement a long polling system with AJAX.  I have currently implemented a basic Pub/Sub Ratchet server which works fine when delivering notifications while a user remains on the "Chat" page on my site.  My problem here is that the connection is closed whenever the user moves to any other page, and I need to re-create a connection to the server.  I am aware that there are possible solutions such as having the websocket connection exist within an IFrame which is always displayed, however I do not want to go down this path if I do not have to.  Would a better approach be to implement long polling with AJAX?  I am concerned that if I continually re-create a users connection to the Ratchet server whenever they change pages within the site, it will add too much overhead when the site is under heavy usage (thousands of users at a time).  Does anyone have experience in this area with Ratchet servers?
Thanks.
Answer: As a disclaimer I'm not very knowledgeable in this area, but you should not use long polling. You say you need "instant notifications," which means with AJAX you would have to be making very frequent requests, whereas with websockets you simply establish the connection and wait for data.
I haven't done any sort of testing, but it seems like establishing and maintaining one websocket connection per browser tab would be less overhead than constantly making AJAX requests, not to mention that you can't truly have "instant notifications" with AJAX because you'd have to make requests at an unsustainable rate to achieve that.
So open a websocket connection for each browser tab the user has. If they open a new tab, or browse to a different page, simply open the connection again.

Ratchet Server vs Long Polling


How to embed and escape R Markdown code in a R Markdown document

Question: I'm trying to write a memo on R Markdown syntax and as such I'd like to include in the document's output the R Markdown code and the output.
To be clear, I'd like the output to look something like:
~~~~~~~~~~~~~~~~~~
Including the following code chunk in the document:
<code>```{r, eval=FALSE}
summary(cars)
```
</code>
will produce the following output:
<code>summary(cars)
</code>
~~~~~~~~~~~~~~~~~~
I'm failing to escape the <code>```</code> and the <code>{r, eval=FALSE}</code>.
Answer: Maybe if you evaluate this:
<code>```{r comment=NA}
cat("```{r, eval=FALSE}\nsummary(cars)\n```")
```
</code>
Comment: Actually the answer to this question finishes it : http://stackoverflow.com/questions/15081212/remove-hashes-in-r-output-from-rmarkdown-and-knitr
Comment: Actually it prints `##` in front of every line as an R eval result. It's okay but ideally I'd like to show it as just a code chunk


How to render both an xml view and a java view in android

Question: In my app I have a very basic looking compass which is rendered within my activity through a class. I am trying to display the compass with a layout. So rather than having just a circle with a line pointing north, I can include text box and buttons. How do I render this within a layout? Currently my activity sets the content view like so:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        compassView = new CompassView(this);
        setContentView(compassView);

I have tried setContentView(R.layout.activity_display_compass) which is my xml file however it only display "hello world" (the TextView), not the compass. See my xml file below.
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>

    <View
        class = "com.example.gpsfinder.CompassView"
        android:id="@+id/compassView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Any guidance would be greatly appreciated.
Answer: To use a custom View subclass in your xml layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>

    <com.example.gpsfinder.CompassView
        android:id="@+id/compassView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

And then you probably need to add some of these constructors in your Java code:
// you used this ctor when creating the view programmatically
public CompassView(Context context) {
    this(context, null);
    // add additional initialization here
}

// this constructor is needed for the class to be used in XML layout files!
public CompassView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    // add additional initialization here
}

// this constructor is needed for the class to be used in XML layout files,
//  with a class-specific base style
public CompassView(Context context, AttributeSet attributeSet, int defStyle) {
    super(context, attributeSet, defStyle);
    // add additional initialization here
}

Comment: I spoke too soon, my compassView remained static. ie does not move depending on orientation?
Comment: That would be a **separate** problem.  The code I posted is what's needed to integrate a custom View subclass into an Android XML layout.  I'd recommend posting a new question, where you explain that the compass isn't rotating.  You'll need to show the full source code for your compass class (or at least most of it, including the part that handles rotation).
Comment: @Calgar99, I just want to make sure I understand you, though.  You're saying that the compass **needle** doesn't rotate as you hold the device flat, and point it North, South, East, West?  Or are you saying that the entire `CompassView` does not rotate, for example, when the user turns the phone from portrait to landscape orientation?  Those are different problems, so I want to make sure I'm clear what you're describing.  Thanks.
Comment: The needle does not move, which it did before.
Comment: Ok, that's what I thought you meant at first.  As I said, that's unrelated to the problem of just using a custom View in a layout xml file.  The only thing I can think of, without seeing the CompassView code, is that I suggested that you add a couple more constructors (which are needed by Android in this situation).  Did you remember to initialize your view the same way in all of your constructors?  Or chain them together, so that the same initialization code gets run no matter which constructor is used?


How do estus charges work?

Question: Can anyone advise how Estus Charges work?
I have an Estus Flask 10+7, but I'm not sure what the "+7" means.
Does it mean I get 17 uses of it? Because after 10 uses I'm no longer able to drink the Flask. Is there some way to recharge the flask to get 7 more uses without going back to a bonfire?
Answer: The +7 next to your Estus Flask doesn't have anything to do with how many times you can use the flask, it indicates how strong it is (aka how much HP or FP it restores per use). The 10 is your number of uses (aka you can use the flask 10 times before returning to a bonfire). There are a few ways to regain Estus Flasks without returning to a bonfire, but they're not reliable.
Your number of uses can be increased by giving the blacksmith Estus Shards, and the strength of the flask can be increased by  burning an Undead Bone Shard at the Firelink Shrine Bonfire.

How do estus charges work?


What is the difference between green and purple Endermen?

Question: I've already seen the green-eyed endermen:

and I know the basic story behind them. But what about these purple guys:

with bright purple eyes and sparkly nether-portal-like particles around them? What's the difference between the two?
Comment: An `XOR` operation on the colour value?
Comment: The difference is one of them looked nice and original and the other is purple and shiny which only enhances how horrible the Endermen really are, and by horrible I mean there the worst mob, or character ever seen in a video game...
Answer: Here's a quote from the Minecraft wiki:

In the final release of 1.8, the Enderman's eyes are now purple, and instead of emitting smoke they emit nether portal particles.

So there's no difference between them, they have only changed up the skin a bit from the pre-release to the actual release.
Source
Comment: Also my guess is that Notch wanted it to seem that they came from the Nether instead of the far lands, like they were supposed to be orginally.
Comment: I still insist that "Farlanders" would have been a better name...
Comment: @RCIX: I presumed it was a play on 'Ander' (Other) in German with reference to 'Slender Man'. The combination of which sounds suitably spooky to me.