Promise returning undefined when try to get link of image in functions firebase

Question: I'm trying to get the value of a response from a firebase function, however it is only returning me as undefined, I saw in some article that the body parser doesn't work anymore, I suspect the problem is in my function, but I'm not getting it find the problem, this is my function code, the image image is salve but don't return the 'imageUrl' to save in database
    exports.uploadImage = functions.https.onRequest((request, response) => {
    cors(request, response, () =>{
        try{
            fs.writeFileSync('tmp/imageToSave.jpg',
             request.body.image, 'base64')
            const bucket = storage.bucket('cloneinstagram-b46a9.appspot.com')
            const id = uuid()
            bucket.upload('tmp/imageToSave.jpg',{
                uploadType: 'media',
                destination: `posts/${id}.jpg`,
                metadata:{
                    metadata:{
                        contentType: 'image/jpeg',
                        firebaseStorageDownloadTokens:id
                    }
                }
            },( err, file) => {
                if(err){
                  console.log(err);
                    return response.status(500).json({error: err});
                }else{
                    const fileName = encodeURIComponent(file.name);
                    const imageUrl = 'https://firabasestorage.googleapis.com/v0/b/'+ bucket.name + '/o/' + fileName + '?alt=media&token=' + id;
                    return response.status(201).json({imageUrl: imageUrl})
                }
            }
        )
        }catch(err){
            console.log(err)
            return response.status(500).json({error:err})
        }
    })
 });

and this my mobile code
      axios({
            url: 'uploadImage',
            baseURL: 'https://us-central1-cloneinstagram-b46a9.cloudfunctions.net/',
            method: 'post',
            data:{
                image: posts.image.base64
            }
        })
            .catch(err => console.log('erro', err))
            .then(resp => {
                posts.image = resp.data.image;
                console.log(' teste image',posts.image)
                axios.post('posts.json', {...posts})
                .catch(err => console.log('teste image', err))
                .then(res => console.log('teste imagem', (res.data.image)))
            })
        }

@EDIT This code solved my problem
exports.uploadImage = functions.https.onRequest((request, response) => {
cors(request, response, () => {

    fs.writeFileSync('tmp/imageToSave.jpg', request.body.image, 'base64')
    const bucket = storage.bucket('cloneinstagram-b46a9.appspot.com')
    const id = uuid()

    bucket.upload('tmp/imageToSave.jpg', {
        uploadType: 'media',
        destination: `posts/${id}.jpg`,
        metadata: {
            metadata: {
                contentType: 'image/jpeg',
                firebaseStorageDownloadTokens: id
            }
        }
    })
        .then(uploadTaskSnapshot => {
            const fileName = encodeURIComponent(file.name);
            const imageUrl = 'https://firabasestorage.googleapis.com/v0/b/' + bucket.name + '/o/' + fileName + '?alt=media&token=' + id;
            return response.status(201).json({ imageUrl: imageUrl })
        })
        .catch(err => {
            console.log(err)
            return response.status(500).json({ error: err })
        })
});

});
Answer: As explained in the Cloud Functions doc, you need to deal with asynchronous processing by returning JavaScript promises.
So, in your case, you need to use the "Promised version" of the upload() asynchronous method, and not the "callback version".
As explained in the doc for this method (see the examples):

If the callback is omitted, (the method will) return a Promise.

So the following should do the trick:
exports.uploadImage = functions.https.onRequest((request, response) => {
    cors(request, response, () => {

        fs.writeFileSync('tmp/imageToSave.jpg', request.body.image, 'base64')
        const bucket = storage.bucket('cloneinstagram-b46a9.appspot.com')
        const id = uuid()

        bucket.upload('tmp/imageToSave.jpg', {
            uploadType: 'media',
            destination: `posts/${id}.jpg`,
            metadata: {
                metadata: {
                    contentType: 'image/jpeg',
                    firebaseStorageDownloadTokens: id
                }
            }
        })
            .then(uploadTaskSnapshot => {
                const fileName = encodeURIComponent(file.name);
                const imageUrl = 'https://firabasestorage.googleapis.com/v0/b/' + bucket.name + '/o/' + fileName + '?alt=media&token=' + id;
                return response.status(201).json({ imageUrl: imageUrl })
            })
            .catch(err => {
                console.log(err)
                return response.status(500).json({ error: err })
            })
    });

});

For more details on why you need, in Cloud Functions, to deal with asynchronous processing by returning Promises, I would suggest you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/
Comment: Keeps returning undefined, but i'll read the docs, thanks for the help.


$I=\int_{-1}^{2}\frac{xf(x^2)}{2+f(x+1)}dx$

Question: Let $f:R\to R$ be a function defined by $f(x)=\begin{cases}
      [x] & x\leq 2 \\
      0 & x>2 \\
      \end{cases}$
where $[x]$ is the greatest integer less than or equal to $x$.Then find $I=\int_{-1}^{2}\frac{xf(x^2)}{2+f(x+1)}dx$

This question was asked in JEE Advanced.I have problem in breaking the limits of integration into parts.
I broke the integration limits like this.
$I=\int_{-1}^{2}\frac{xf(x^2)}{2+f(x+1)}dx=\int_{-1}^{0}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx+\int_{0}^{1}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx+\int_{1}^{\sqrt{2}}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx+\int_{\sqrt{2}}^{\sqrt{3}}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx+\int_{\sqrt{3}}^{2}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx$
But the book says
$I=\int_{-1}^{2}\frac{xf(x^2)}{2+f(x+1)}dx=\int_{-1}^{0}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx+\int_{0}^{1}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx+\int_{1}^{\sqrt{2}}\frac{x\bigl[x^2\bigr]}{2+\bigl[x+1\bigr]}dx$
I am confused why have they not included limits from $\sqrt{2}$ to $\sqrt{3}$ and limits from $\sqrt{3}$ to $2.$After splitting of limits,i could solve.Please help me.
Comment: Please, add $dx$'s.
Answer: Above $x=\sqrt2$, $f(x^2)$ doesn't bring any contribution as it is zero.
Comment: Yes i got it,thank you.@Yves Daoust


How to write dihedral group in cycle notation?

Question: Since each symmetry can be thought of as a permutation of the vertices, the elements of $D_n$ can be thought of as elements of $S_n$. So I'm wondering if there's a systematic way that we can always write elements of $D_n$ in disjoint cycle notation?
Answer: The dihedral group $D_n$ is a subgroup of $S_n$ for all $n\ge 3$, see also here, so we can write the elements in cycle notation. More precisely, $D_n$ is generated by an $n$-cycle $\sigma$ and a $2$-cycle $\tau$ satisfying the conditions $\sigma^n=\tau^2=1$, $\sigma\tau=\tau\sigma^{n-1}$. This gives a systematic way how to write the elements of $D_n$ in cycle notation. For example, for $n=3$, take $\sigma=(123)$ and $\tau=(23)$. Then $D_3=\{id,(12),(13),(23),(123),(132) \}$.
Comment: @OmarShehab "generated" does not mean that the group consists only of the generators. $S_n$ is generated by $(1,2,\ldots .n)$ and $(12)$, but contains all cycles of length $\le n$, so "everything".
Comment: Would this be affected by how we define the reflection in $D_n$ (the axis of reflection being the line connecting the edges or vertices)
Comment: No, it would not be affected, because we only speak of a group of permutations which is *isomorphic* to $D_n$. There are several ways to realize these permutations.
Comment: @DietrichBurde, you said '$D_n$ is generated by an $n$-cycle $\sigma$ and a $2$-cycle $\tau$'. But, in your example, $D_3$ contains more than one $3$-cycle and more than one $2$-cycle. Am I missing something?


Where should hooks go? Only in modules?

Question: I need to use 1 hook from webforms.  Where does this belong? Do I have to make a custom module just to implement 1 hook or is there a more appropriate place?
Answer: A custom module is the most appropriate, probably only, place for your hook(s).
Most hooks only get run for modules; there are exceptions such as hook_form_alter(), hook_theme() etc. which are also called for themes, but generally speaking you'll need to write a custom module for any hooks you want to implement.
In case you're not familiar with building modules take a look at the Module Developer's Guide.

Where should hooks go? Only in modules?


Swap being used when not necessary

Question: I have: vm.swappiness = 1 as suggested here to prevent using Swap when there is plenty of available memory.
(0 would completely disable swap, as far as I understand)
In frequent cases, I end up with, say, 5GB swap used (total 16GB),
while I have 9GB free available memory (total 32GB)
(only 1GB free if we count cached RAM).
As my application starts to get slow (since most of the Swap is from MariaDB), I run:
swapoff -a
swapon -a

And all the swap memory is moved to the main RAM.
I end up with 5.6GB available RAM, 4GB if we count cached.
There is no apparent reason to have so much Swap.
I've been researching about this, and I cannot find a way to prevent using Swap when it's not needed.
vm.swappiness = 1 is definitely "permanently saved", since it is on the sysctl.conf file, and there have been reboots, etc.
I don't want to disable swap, but the only workaround I can think of is:

disable swap
have a cron running every 1 minute to check how much free RAM there is
enable swap if available RAM is low

But, this is VERY risky to do, and I wish the OS was smart enough to manage this better!
Is there absolutely no way to only use swap when absolutely needed?
Comment: Check `cat /proc/sys/vm/swappiness` to be sure.  Some distros have a habit of resetting it (but CentOS typically isn't one of them).  Would it be possible that the RAM was briefly consumed then released, leaving some data moved to swap - did you run `mysqltuner` to show the maximum theoretical usage of mysql?
Comment: @tater Thanks. The result of the command is "1", as expected. Yeah, I suppose one possibility is that something may take a lot of RAM and then release, but I haven't caught that happening yet. However, the scenario above does happen often, slowly over time. The database itself is 'fine' (well tuned/configured, and regularly checked). The server runs other things beside MariaDB, however.
Comment: Why do you think this is a problem? Swapping out parts of processes that aren't used so that memory can be used for other things (like caching!) is normal and generally welcome behavior. You are probably losing performance by forcing everything out of swap.
Comment: @MichaelHampton - in my question above, I mention about the system performing poorly. Once the swap is moved into actual RAM, performance seems to improve.
Answer: Do you have lot of stuff running on the server?  If so, maybe consider a dedicated machine or VM for the DB.
Is this physical or VM/cloud server?  Some cloud providers do NOT want you to use swap at all (so just putting that out there in case it is relevant): https://docs.rackspace.com/support/how-to/swap-space-on-cloud-servers/
There is some good discussion on this page for troubleshooting swap for MySQL or MariaDB -- maybe check the NUMA section toward the end: https://fromdual.com/do-not-underestimate-performance-impacts-of-swapping-on-numa-database-systems
This Q&A at MariaDB site leads to NUMA interleaving settings as a possible solution:
https://mariadb.com/kb/en/swap-usage-wont-decrease/
A lot of discussion about memory and MariaDB:
https://mariadb.com/kb/en/mariadb-memory-allocation/
And this is the authoritative youtube video for NUMA  :-D
https://youtu.be/KmtzQCSh6xk
Please upvote/accept this answer if it is helpful.  Thanks.
Comment: Thank you for your suggestions. The server is physical & dedicated. Interesting stuff about NUMA -- I'll have a look!

Swap being used when not necessary


Submitting form in a chrome extension doesn't work

Question: I'm building a chrome extension that consists on a form that when submitted executes onsubmit="submit(); return false;".
I know the method submit works because I created a button outside the form with onclick="submit()" and that works perfectly.
Here is the form:
<form method="post" name="gaffeForm" onsubmit="submit(this); return false;">

Title :

            <input type="text" name="title" size="50" id="pageTitle" placeholder="Title" required />

URL :

            <input type="url" name="url" size="50" id="pageURL" placeholder="URL" required />

Error :

            <textarea name="gaffe" rows="5" cols="50" id="pageGaffe" placeholder="Gaffe" required ></textarea>

Comment :

            <textarea name="comment" rows="5" cols="50" id="gaffeComment" placeholder="Your comment on the gaffe" required ></textarea>

Tags :

            <input type="text" name="tags" size="50" id="gaffeTags" placeholder="Separate the tags with a comma" required />

            <input type="submit" value="Submit" />

</form>

And here is the submit() function:
function submit(f) {
    var xhr = new XMLHttpRequest();

    var title = $('#pageTitle').val().replace(/\//g, "%2F");
    var url = $('#pageURL').val().replace(/http:\/\//, "").replace(/https:\/\//, "").replace(/\//g, "%2F");
    var gaffe = $('#pageGaffe').val().replace(/\//g, "%2F");
    var comment = $('#gaffeComment').val().replace(/\//g, "%2F");
    var tags = $('#gaffeTags').val().replace(/\//g, "%2F");

    xhr.open("POST", "http://localhost:3000/F0ETF87dar8F7deO92K/" + title + "/" + url + "/" + gaffe + "/" + comment + "/" + tags, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (req.status == 200) window.close();
        }
    };
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Connection", "close");
    xhr.send();
    return false;
}

So, when I click submit with all my fields filled in what happens is that the fields comment and tags go blank, and that's it... I've tried a lot of different ways of executing submit() but none have worked... Thank you.
Answer: Is the page loaded from the extension or is it loaded from a website and you are trying to have the submit() function in an extension content script called?
If the submit function is in a content script it can't be called from a website as the chrome extension security system doesn't allow javascript calls between page content and javascript in content scripts.
Comment: The form is in popup.html and submit is a function inside popup.html too.
Comment: Ah. Do you load the content script explicitly inside popup.html? I'm not sure if the content scripts are all automatically available to your html file, or if you have to explicitly load them, and your source file fragment doesn't appear to load any explicit script files. If you copy your `submit` function into popup.html does it work then?
Comment: My content script doesn't have anything to do with this. My submit function IS inside popup.html
Answer: Sending request to a different port is prohibited by the cross-origin policy. If you open error console you will probably see a security error.
You can set domain permissions in the manifest, but you cannot set port.
Comment: I don't understand what you mean by ports... The XMLHttpRequest works fine because the function submit works flawlessly when executed by a button outside the form, but it doesn't execute when I press submit. And I've tried deleting everything that's in the function and just putting an alert and it still doesn't execute
Comment: @Alberto Elias: I mean you are trying to submit to port 3000. Unless you are currently viewing this page at port 3000 it wouldn't allow you to make XMLHttpRequest to 3000 from 80.
Comment: well, it does work! And it's in port 3000 because my server right now is in localhost so the web is in that port. But I know the method works because I've executed it by pressing a different button outside the from different from submit.


Is there a way to solve for $x$ in $\cos(ax)/\cos(bx)=c$?

Question: Is there a way to solve for x in $\dfrac{\cos(ax)}{\cos(bx)} = c$?
This is similar to the question on $\dfrac{\cos^{-1}(ax)}{\cos^{-1}(bx)} = c$.
Comment: To the best of my knowledge, there is no way to find a closed form solution for $x$ in general.
Comment: Do you know anything about the ratio `a/b`?
Comment: @yatima2975: No.  They represent more complicated expressions, but they're independent and arbitrary.
Answer: The answer is similar to the other one.
If $a/b = m/n$ is rational then the equation can be written as $\cos (m\theta) = c \cos (n \theta)$ where $ax = m \theta$.  For $c = \pm 1$, $\theta$ will be an easily described angle, and if $|c| \neq 1$, then $\cos(\theta)$ is an algebraic function of $c$ since the equation is equivalent to $P_m(\cos \theta) = P_n( \cos \theta)$ where the $P$ are Chebyshev polynomials.  If $c$ is an algebraic number then so is $\cos(\theta)$.
For $a/b$ irrational and $c \neq \pm 1$ there is no algebraic solution.
Comment: Your last statement is a bit confusing: it must be interpreted as "there is no algebraic method of solution", not "there is no algebraic number that is a solution".
Comment: @Robert: yes, though actually I meant something stronger like "it is expected that the solution is not in a finite extension field of $Q(a,b,c)$, assuming as many standard conjectures as needed from transcendental number theory".


Django: ModuleNotFoundError: No module named 'requests'

Question: when i run server i have below error:
ModuleNotFoundError: No module named 'requests'

but requests have been installed on my system, when i run sudo pip3 install requests command, output is :
Requirement already satisfied: requests in /home/sadegh-khan/.local/lib/python3.6/site-packages

the terminal pic of my error and command to install requests is:
Comment: try running `python3 manage.py runserver 8002`
Comment: which command you are running to run server?
Comment: python manage.py runserver 8002
Comment: According to the following post: [Python module not found even though "Requirement Already satisfied in Pip"
](https://stackoverflow.com/a/45345642/5433307) easy-install solved my problem! `easy_install requests`
but why!?
Comment: python3 manage.py runserver 8002 would solved your problem because python manage.py runserver will run in python2 but you installed requests for python3 that is the problem
Comment: after easy-install i tried python3 manage.py, but problem solved. Of course now also i am using python manage.py and i have not any problem.
Answer: You're installing requests by running pip as sudo, which means it is installed globally. Yet your screenshot (and please don't post screenshots anyway) shows you are inside a virtualenv, .venv.
Don't use sudo; just install requests inside the venv.
Comment: Are you running Django under Python 2 or 3? And are you sure you're in the same venv?
Comment: i am sure that running Django under Python 3. yes im sure in the same Virtualenv.
Answer: If you are using Python3 instead of running the server using python manage.py runserver go ahead and run python3 manage.py runserver
Instead of
python manage.py runserver

or
py  manage.py runserver

Run
python3  manage.py runserver


connecting backend API address

Question: I have a frontend single page application written using Vuejs, I use axios to call a backend API. I am trying to use kubernetes to run the service:
My deployment and service yml file:
<code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: testapi
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: testapi
    spec:
      containers:
      - name: testapi
        image: testregistry.azurecr.io/testapi:latest
        ports:
        - containerPort: 3001
---
apiVersion: v1
kind: Service
metadata:
  name: testapi
spec:
  type: LoadBalancer
  ports:
  - port: 3001
  selector:
    app: testapi
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: testportal
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: testportal
    spec:
      containers:
      - name: testportal
        image: testregistry.azurecr.io/testportal
        ports:
        - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: testportal
spec:
  type: LoadBalancer
  ports:
  - port: 8080
  selector:
    app: testportal
</code>
The frontend is running at the client browser. My axios url is connect to http://testapi:3001, which obviously is not working. Any idea how to have it connected to the backed API?
Answer: you can only use that service name from any other deployment inside the same kubernetes cluster. if you want to call it from front-end, you will have to expose an external public accessible endpoint.

connecting backend API address


Golang vendor package with vendored sub-packages

Question: Situation:
Let's assume I've a package called mypackage. It exposes one method called Build(), that returns a concrete struct exposed by a third party library called thirdpartypackage, e.g. like shown as follows:
package mypackage

import tpp "github.com/thirdpartycompany/thirdpartypackage"

func Build() *tpp.SharedStruct{
   //...implementation
}

The package that exposes SharedStruct is vendored inside mypackage, because I want to distribute it and make that package independent.
Problem:
After importing mypackage into another project and using thirdpartypackage in my (integration) tests, I'm getting the following error:

cannot use XXXX (type
  "github.com/mycompany/mymainproject/vendor/github.com/mycompany/mypackage/vendor/github.com/thirdcompany/thirdpartypackage-go".Token)
  as type
  "github.com/empatica/mycompany/vendor/github.com/thirdcompany/thirdpartypackage"

Basically the compiler is distinguishing the vendored third-party package inside my library and the vendored package that I put in my main project.
Question:
Are there ways to solve this issue, that are not removing the vendored dependencies from my library, like suggested here? Am I missing something?
Comment: Vendoring works good for commands and less good for individual packages...
Comment: This is why most vendoring tool flatten the vendor directory.  Govendor does this by default, I'm not sure about other vendor tools.  The paradigm I've started using for our libraries intended for import (as opposed to apps themselves) is to add `/vendor/*/` to our `.gitignore`.  This ignores subfolders in `/vendor/`, but NOT files (like `vendor.json`, for govendor).  Govendor then gracefully handles flattening the dependency tree, and your error vanishes, because both packages are now using the same fully-qualified import path for the structure's package.
Comment: Can you give your exact directory structure your point is not clear
Answer: I think what you are missing is this point:

Code below a directory named "vendor" is importable only by code in the directory tree rooted at the parent of "vendor", and only using an import path that omits the prefix up to and including the vendor element. (go command)

What I understand from your problem is your mypackage has vendor as its child, so when it's imported by any other package at same level, then for obvious reason they cannot see that vendored list.
You can understand this as being similar to a protected feature.
So if you want to use that version in any other package, then this vendor should be present at same level. For example
ParentDirectory
 > mypackage
 > otherpackage (this will be importing mypackage)
 > vendor (vendor should be present in here so that all children under ParentDirectory can access this)

I hope I am clear with my point.


How to separate a string with a char?

Question: Say I have two string; "fruit;mango;apple;banana" and "animal;dog;cat;cow". What i want is a function to check the first word before 1st semi colon and then if its "fruit" get the other 3 elements(without semi colon) and store it in an array called fruit and if animal take the elements and store is animal array. I thought of using loop and chatAt() but that code will be kinda messy.
So I want to know is there any function to separate a string with char?
Comment: You can start from `split` method: `"fruit;a;b;c".split(";")` give you array ["fruit", "a", "b", "c"]
Comment: Can you post some code of what you have already tried ?
Comment: Hi, I think you should have a look at the [how to ask](http://stackoverflow.com/help/how-to-ask) page, as it'll give you some pointers on how to restructure this question so we can best help.  Including some code that you've written would be a good start
Comment: Your final paragraph seems to be your question - how to split a string. The answer is in the duplicate I've closed this for. I've edited your title accordingly.
Answer: Try this:
String s =  "fruit;mango;apple;banana" ;
String[] elements = s.split(";");
if(elements.length > 0){
    if(elements[0].equals("fruit")){
        String[] fruits = new String[elements.length-1];
        System.arraycopy(elements, 1,fruits , 0, elements.length-1);
        System.out.println(Arrays.toString(fruits));
    }
}

Comment: Thanks, already changed to (elements.length > 0)
Answer: Here's use following code:
String data="fruit;mango;apple;banana";
    List<String> fruitList=new ArrayList<String>();
    List<String> animalList=new ArrayList<String>();
    String tok[]=data.split(";");
    if(tok[0].equals("fruit"))
    {
        for(int i=1;i<tok.length;i++)
        {
            fruitList.add(tok[i]);
        }
    }
    else
    {
        for(int i=1;i<tok.length;i++)
        {
            animalList.add(tok[i]);
        }
    }
    if(!fruitList.isEmpty())
        System.out.println(fruitList);
    if(!animalList.isEmpty())
        System.out.println(animalList);

Output
[mango, apple, banana]

Now the data string can be any of animal or fruit type.
Answer: String str1 = "fruit;mango;apple;banana";
String str2 = "animal;dog;cat;cow";

String[] arrStr1 = str1.split(";");
String[] arrStr2 = str2.split(";");

ArrayList<String> fruit = null;
if(arrStr1[0].equals("fruit")) {
    fruit = new ArrayList<String>(Arrays.asList(arrStr1));
    fruit.remove("fruit");
}

ArrayList<String> animal = null;
if(arrStr2[0].equals("animal")) {
    animal = new ArrayList<String>(Arrays.asList(arrStr2));
    animal.remove("animal");
}

How to separate a string with a char?


Erro ao criar arquivo PDF no Android

Question: Estou com um problema para criar um PDF usando o iText no Android.
Tenho que salvar na memória interna do dispositivo,
mas esta dando erro pois não sei o caminho para salvar porque no tutorial ele salvava no C:/temp.
Este é o código
public class PdfActivity extends Activity {

    private static String file = "texto";
    private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLD);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);

        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream(file));
            document.open();
            addTitlePage(document);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addTitlePage(Document document)
        throws DocumentException{
            Paragraph preface = new Paragraph();

            //pula uma linha
            addEmptyFile(preface, 1);
            //titulo com font grande
            preface.add(new Paragraph("Documento de Teste", catFont));

            addEmptyFile(preface, 1);
            preface.add(new Paragraph("Conteudo teste do corpo, um texto simples para ser exibido como corpo do documento", smallBold));
            document.add(preface);
            document.newPage();

    }
    //metodo para pular uma linha
    private static void addEmptyFile(Paragraph paragraph, int number) {
        for(int i=0; i<number; i++){
            paragraph.add(new Paragraph(""));
        }
    }
}

A variável file é onde vai o caminho.
Uma imagem do LogCat:
Answer: Em qual caminho você está a salvar o arquivo PDF? em todo caso você pode estar olhando as Variáveis de Ambiente para obter informações sobre os diretórios do sistema. Veja um exemplo, um arquivo FooBar.pdf será criado no diretório padrão de documentos.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pdf);

    try
    {
       Document document=new Document();
       File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
       File pdffile = new File(path, "FooBar.pdf");
       PdfWriter.getInstance(document, new FileOutputStream(pdffile));
       document.open();
       document.add(new Paragraph("Foo Bar Bar Baz Baz Foo"));
       document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Comment: Consegui o que estava acontecendo era que ele não achava as classes da biblioteca mesmo exportando o jar, ai copiei o arquivo e colei na pasta libs e deu certo , seu código me ajudou muito criou o documento certinho, obrigado

Erro ao criar arquivo PDF no Android


Double self-referencing property with Entity Framework

Question: This code represents in small scale my problem:
public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Person Parent { get; set; }
    public virtual ICollection<Person> Friends { get; set; }
}

When I use this class in an Entity Framework (4.1) scenario, the system generates one only relation, thinking that Parent and Friends are the two faces of the same relation.
How can I tell to semantically separate the properties, and generate two different relations in SQL Server (since we can see that Friends are totally different from Parents :-)).
I tried with the fluent interfaces, but I think I don't know the right calls to do.
Thanks to all.
Andrea Bioli
Answer: You could use this in the Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>()
        .HasMany(p => p.Friends)
        .WithOptional()
        .Map(conf => conf.MapKey("FriendID"));

    modelBuilder.Entity<Person>()
        .HasOptional(p => p.Parent)
        .WithMany()
        .Map(conf => conf.MapKey("ParentID"));
}

I am assuming here that the relationships are optional. The People table gets two foreign keys FriendID and ParentID now. Something like this should work then:
using (var context = new MyContext())
{
    Person person = new Person() { Name = "Spock", Friends = new List<Person>()};
    Person parent = new Person() { Name = "Sarek" };
    Person friend1 = new Person() { Name = "Kirk" };
    Person friend2 = new Person() { Name = "McCoy" };

    person.Parent = parent;
    person.Friends.Add(friend1);
    person.Friends.Add(friend2);

    context.People.Add(person);

    context.SaveChanges();

    // Load with eager loading in this example
    var personReloaded = context.People
        .Where(p => p.Name == "Spock")
        .Include(p => p.Parent)
        .Include(p => p.Friends)
        .First();
}


Unable to determine cause of HTTP 500 in apache with mod_wsgi

Question: I have apache httpd 2.4.6 running with a working django application, but occassionally during our nightly test runs, the server returns a 500 error code and I can not figure out why.  There is nothing in the apache error logs indicating a reason.  I have set the LogLevel to 'info' in my apache config (and reloaded apache).  I modified the 'dispatch' method of my view so that it logs the request params to a file.  When a successful POST is done, it logs it just fine, but there is nothing in there for the time when a 500 is returned.  I don't think it's even getting to the django app before returning the 500.
So then I modified by wsgi entry point to be this:
<code>class MyWSGIHandler(WSGIHandler):
    def __call__(self, environ, start_response):
        print >>environ['wsgi.errors'], pprint.pformat(environ)
        retval = super(MyWSGIHandler, self).__call__(environ, start_response)
        print >>environ['wsgi.errors'], pprint.pformat(retval.__dict__)
        return retval
application = MyWSGIHandler()
</code>
Again, normally, this will log everything properly to my apache error log, but when the 500 is returned, there's nothing.  The only thing that makes me certain that the request is making it to the server is a line in the apache access log:
[05/Jun/2014:22:41:10 +0000] "POST / HTTP/1.1" 500 600
I don't know where to go from here.
Comment: Do the errors co-incide with maintenance work? e.g. log rotate is causing an apache reload to happen?
Answer: Django will intercept unhandled exceptions in your code itself and convert them to 500 responses and doesn't propagate the exception up to the WSGI server. Thus neither the WSGI server or your wrapper will see them if that is what is occurring.
You need to configure Django to log details of such errors. One way is to set ADMINS and mail configuration so it can email them to you. The other way is to set up the logging module properly with Django so it will redirect logged messages to stderr and into the Apache error log. Have a look through the Django documentation for more information.
Comment: That was actually the first bit of troubleshooting that I did.  I forgot to mention that in my problem description.  In fact, I intentionally introduced an error in the code for a short time to verify that the email notification and logging was working.
Comment: What is generating the 500 response content then. Is it Apache or Django? Do you happen to have ErrorDocument directives configured in Apache?
Comment: Everything points to it being generated by apache.  I do not have ErrorDocument directives configured.
Comment: If it is Apache, there would generally be some sort of error indicating a problem in the Apache error log. Are there no messages at all for that time period?
Comment: Correct.  There are no messages at all in the error_log for that time period.
Comment: I believe this is actually being caused by the authentication layer.  A timeout to an LDAP server actually.  Closing out this question.  Thanks for your time.
Answer: I finally determined the problem.  I'm using LDAP for authentication and sometimes the ldap server would time out for a user that was not in the LDAP directory.  For whatever reason, this was causing the 500 to be returned.  I have that user defined in a .htdigest file and had set my AuthBasicProvider to "ldap file".  After I switched that around to "file ldap", I haven't seen the problem since.


Nested Array Tree Node JS

Question: I am comparing 2 arrays with the ID's and adding nested children objects to generate the tree.
if you look in the code comparing issue_id with descendents_parent_issue_id
I am able to generate the tree but a children is adding only 1 object. Expecting tree level nested objects.
Following Code Output
[{
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "hierarchy_level": 1,
    "children": [{
        "issue_id": 7,
        "parent_issue_id": 2,
        "issue": "Breakdown",
        "issue_code": "bd7catA",
        "entity_id": null,
        "hierarchy_level": 2,
        "children": [{
            "issue_id": 881,
            "parent_issue_id": 7,
            "issue": "Hydraulic arm failure",
            "issue_code": null,
            "entity_id": 52,
            "hierarchy_level": 3
        }]
    }]
}, {
    "issue_id": 1,
    "parent_issue_id": null,
    "issue": "Loading",
    "issue_code": null,
    "hierarchy_level": 1
}, {
    "issue_id": 3,
    "parent_issue_id": null,
    "issue": "Performance",
    "issue_code": null,
    "hierarchy_level": 1
}, {
    "issue_id": 4,
    "parent_issue_id": null,
    "issue": "Quality",
    "issue_code": null,
    "hierarchy_level": 1
}]

My Code

const issuesList = [
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "hierarchy_level": 1
  },
  {
    "issue_id": 1,
    "parent_issue_id": null,
    "issue": "Loading",
    "issue_code": null,
    "hierarchy_level": 1
  },
  {
    "issue_id": 3,
    "parent_issue_id": null,
    "issue": "Performance",
    "issue_code": null,
    "hierarchy_level": 1
  },
  {
    "issue_id": 4,
    "parent_issue_id": null,
    "issue": "Quality",
    "issue_code": null,
    "hierarchy_level": 1
  }
];

const issues = [{
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 7,
    "descendents_parent_issue_id": 2,
    "descendents_issue": "Breakdown",
    "descendents_issue_code": "bd7catA",
    "descendents_entity_id": null,
    "descendents_hierarchy_level": 2,
    "descendents_issuesancestor_issues_issue_id": 7,
    "descendents_issuesancestor_ancestor_issue_id": 2
  },
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 881,
    "descendents_parent_issue_id": 7,
    "descendents_issue": "Hydraulic arm failure",
    "descendents_issue_code": null,
    "descendents_entity_id": 52,
    "descendents_hierarchy_level": 3,
    "descendents_issuesancestor_issues_issue_id": 881,
    "descendents_issuesancestor_ancestor_issue_id": 2
  },
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 8,
    "descendents_parent_issue_id": 2,
    "descendents_issue": "Setup/ Changeover",
    "descendents_issue_code": "st8catA",
    "descendents_entity_id": null,
    "descendents_hierarchy_level": 2,
    "descendents_issuesancestor_issues_issue_id": 8,
    "descendents_issuesancestor_ancestor_issue_id": 2
  },
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 942,
    "descendents_parent_issue_id": 7,
    "descendents_issue": "Pump Overload",
    "descendents_issue_code": null,
    "descendents_entity_id": 52,
    "descendents_hierarchy_level": 3,
    "descendents_issuesancestor_issues_issue_id": 942,
    "descendents_issuesancestor_ancestor_issue_id": 2
  }
  ];

function processIssues(arr, arrayB) {
  return arr.reduce((result, item) => {
    const itemInB = arrayB.find(itemB => itemB.descendents_parent_issue_id == item.issue_id)

    if (itemInB) {
      let child = [];
      child.push({
        issue_id: itemInB.descendents_issue_id,
        parent_issue_id: itemInB.descendents_parent_issue_id,
        issue: itemInB.descendents_issue,
        issue_code: itemInB.descendents_issue_code,
        entity_id: itemInB.descendents_entity_id,
        hierarchy_level: itemInB.descendents_hierarchy_level
      });
      item.children = child;
    }

    if (item.children) {
      processIssues(item.children, arrayB)
    }

    return [...result, item];
  }, []);
}

var sourceIssue = processIssues(issuesList, issues);
console.log(JSON.stringify(sourceIssue));

Expected output
[{
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "hierarchy_level": 1,
    "children": [{
        "issue_id": 7,
        "parent_issue_id": 2,
        "issue": "Breakdown",
        "issue_code": "bd7catA",
        "entity_id": null,
        "hierarchy_level": 2,
        "children": [{
            "issue_id": 881,
            "parent_issue_id": 7,
            "issue": "Hydraulic arm failure",
            "issue_code": null,
            "entity_id": 52,
            "hierarchy_level": 3
        },{
            "issue_id": 942,
            "parent_issue_id": 7,
            "issue": "Pump Overload",
            "issue_code": null,
            "entity_id": 52,
            "hierarchy_level": 3
          }]
    }]
}, {
    "issue_id": 1,
    "parent_issue_id": null,
    "issue": "Loading",
    "issue_code": null,
    "hierarchy_level": 1
}, {
    "issue_id": 3,
    "parent_issue_id": null,
    "issue": "Performance",
    "issue_code": null,
    "hierarchy_level": 1
}, {
    "issue_id": 4,
    "parent_issue_id": null,
    "issue": "Quality",
    "issue_code": null,
    "hierarchy_level": 1
}]

Please help
Answer:

const issuesList = [
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "hierarchy_level": 1
  },
  {
    "issue_id": 1,
    "parent_issue_id": null,
    "issue": "Loading",
    "issue_code": null,
    "hierarchy_level": 1
  },
  {
    "issue_id": 3,
    "parent_issue_id": null,
    "issue": "Performance",
    "issue_code": null,
    "hierarchy_level": 1
  },
  {
    "issue_id": 4,
    "parent_issue_id": null,
    "issue": "Quality",
    "issue_code": null,
    "hierarchy_level": 1
  }
];

const issues = [{
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 7,
    "descendents_parent_issue_id": 2,
    "descendents_issue": "Breakdown",
    "descendents_issue_code": "bd7catA",
    "descendents_entity_id": null,
    "descendents_hierarchy_level": 2,
    "descendents_issuesancestor_issues_issue_id": 7,
    "descendents_issuesancestor_ancestor_issue_id": 2
  },
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 881,
    "descendents_parent_issue_id": 7,
    "descendents_issue": "Hydraulic arm failure",
    "descendents_issue_code": null,
    "descendents_entity_id": 52,
    "descendents_hierarchy_level": 3,
    "descendents_issuesancestor_issues_issue_id": 881,
    "descendents_issuesancestor_ancestor_issue_id": 2
  },
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 8,
    "descendents_parent_issue_id": 2,
    "descendents_issue": "Setup/ Changeover",
    "descendents_issue_code": "st8catA",
    "descendents_entity_id": null,
    "descendents_hierarchy_level": 2,
    "descendents_issuesancestor_issues_issue_id": 8,
    "descendents_issuesancestor_ancestor_issue_id": 2
  },
  {
    "issue_id": 2,
    "parent_issue_id": null,
    "issue": "Availability",
    "issue_code": null,
    "entity_id": null,
    "hierarchy_level": 1,
    "descendents_issue_id": 942,
    "descendents_parent_issue_id": 7,
    "descendents_issue": "Pump Overload",
    "descendents_issue_code": null,
    "descendents_entity_id": 52,
    "descendents_hierarchy_level": 3,
    "descendents_issuesancestor_issues_issue_id": 942,
    "descendents_issuesancestor_ancestor_issue_id": 2
  }
  ];

function processIssues(arr, arrayB) {
  return arr.reduce((result, item) => {
    const itemInB = arrayB.find(itemB => itemB.descendents_parent_issue_id == item.issue_id)

    if (itemInB) {
      let child = [];
      child.push({
        issue_id: itemInB.descendents_issue_id,
        parent_issue_id: itemInB.descendents_parent_issue_id,
        issue: itemInB.descendents_issue,
        issue_code: itemInB.descendents_issue_code,
        entity_id: itemInB.descendents_entity_id,
        hierarchy_level: itemInB.descendents_hierarchy_level
      });
      item.children = processIssues(child, arrayB);
    }

    return [...result, item];
  }, []);
}

var sourceIssue = processIssues(issuesList, issues);
console.log(JSON.stringify(sourceIssue));
Comment: getting the same output with the above code

Nested Array Tree Node JS


How to create Span with initial size?

Question: How can I create Span<int> with the initial size?
I want to achieve below points.

Array should be allocated on the stack and not heap(because of this I want to use Span<T>)
I know the size of the array in advance. so don't want to waste CPU reallocating and copying array around.
Comment: A span is an anonymous reference to another array. You would want to allocate an array with stackalloc then call AsSpan
Comment: oh, got it thanks :)
Answer: Using stackalloc operator array can be created on stack and can be assigned to Span

Span<int> numbers = stackalloc int[length];
Span<int> numbers = stackalloc[] { 1, 2, 3, 4, 5, 6 };

attached link for reference https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/stackalloc
edit
This requires C# version 7.2 or greater

How to create Span with initial size?


Prove that $f(t)=\frac{\int_{1}^{b}{x^{1+t}\,dx}}{\int_{1}^{b}{x^{t}\,dx}}$ is an increasing function.

Question: Let $b>1$ and define $f:\mathbb{R}\to\mathbb{R}$ by $$f(t)=\frac{\int_{1}^{b}{x^{1+t}\,dx}}{\int_{1}^{b}{x^{t}\,dx}}.$$
I would like to prove that $f$ is an increasing function for all $t$.
Ideas so far: Certainly, it should be true, as $f$ represents the centre of mass of the region beneath the graph of $y=x^t$ over the interval $[1,b]$. So physically, it's obvious. Aside from a vague physical proof, I can show by differentiation that the derivative of $f$ satisfies  $$f'(t)=(t+1)-t\frac{f(t)}{f(t+1)},$$
But I'm not sure where to go with this.
Comment: Your physical argument can be restated in terms of statistics, since $f(t)=\Bbb EX_t$ with $X_t$ having PDF $\propto x^t$ on support $[1,\,b]$. By unitarity, increasing $t$ subtracts area under the curve from low $x$ and adds them to high $x$, and therefore increases $\Bbb EX_t$.
Comment: Thanks Gae. S. I have fixed my error.
Comment: Thanks, J.G. That's the sort of physical argument that I had in mind (except in terms of shifting mass, rather than considering a pdf) but is there an argument that makes this more than simply intuitive?
Comment: Are you sure that $f'(t)$ exists for all $t$? It is not even obvious to me that $f$ is continuous in $t= -1,-2$
Comment: Paul Frost, it is continuous. You can get this by way of L'Hopital applied at the problem points.
Answer: This answer is an alternative proof of the log-convexity result given above by Jack D'Aurizio. Defining $g(t)=\int_{1}^{b}{x^t}\,dx$, by the Cauchy Schwarz inequality we see that
\begin{align*}
g''(t)\cdot g(t)&=\int_{1}^{b}{ x^t(\log{x})^2}\,dx\cdot\int_{1}^{b}{x^t}\,dx\\
&=\int_{1}^{b}{( x^\frac{t}{2}\log{x})^2}\,dx\cdot\int_{1}^{b}{(x^\frac{t}{2})^2}\,dx\\
&\geq \left(\int_{1}^{b}{x^t\log{x}}\,dt\right)^2\\
&=(g'(t))^2.
\end{align*}
This proves the log-convexity of $g$ and, as D'Aurizio points out, this implies that $f(t)=\frac{g(t+1)}{g(t)}$ is an increasing function.
Comment: This is perfectly fine (+1)
Comment: Thanks, Jack. I voted up yours too - not sure why anyone would do the opposite. It's a very elegant proof!
Answer: Key point: your $f$ is a ratio of moments.
$$g(t) = \int_{1}^{b} x^t\,dx $$
is quite trivially a continuous and positive function. $g(t)$ is midpoint-log-convex by the Cauchy-Schwarz inequality:
$$ g(t_1) g(t_2) \geq g\left(\frac{t_1+t_2}{2}\right)^2. $$
By putting together the continuity and the midpoint-log-convexity we get the log-convexity of $g$, which implies that $f(t)=\frac{g(t+1)}{g(t)}$ is an increasing function, as wanted.
Comment: Jack, D'Aurizio, had to do a bit of background reading but that all chains together. That the continuity implies the log-convexity is neat.
Comment: Jack D'Aurizio, below I have posted what I think is an alternative argument showing the log-convexity. I knew nothing about this until a week ago, so feel free to down vote my argument if you see an error in my reasoning!


React: How to set up Edit Function in CRUD app to switch out whole components while keeping id

Question: Hey Guys I'm pretty new to React and I'm running into a bit of a pickle here.
I'm making a simple CRUD website creator and I've got the add and delete function created and they work great! but I'm having trouble with the edit function.
I've based this on the this tutorial which works with String data-type
https://www.digitalocean.com/community/tutorials/react-crud-context-hooks
So in my mind this is how it should should work
I've got use state as passing an object with a couple of properties
const [selectedSection, setSelectedSection] = useState({
id: null,
section: {},

});
I've set the id to the current component I'm editing with
const currentSectionId = route.match.params.id;

in my useEffect I'm carrying over the current id with while setting the new compenent skipping the id in the current section
  useEffect(() => {
const sectionId = currentSectionId;
const selectedSection = sections.find(
  (currentSectionTraversal) => currentSectionTraversal.id === parseInt(sectionId)
);
    setSelectedSection(selectedSection);},[currentSectionId, sections]);

  const onSubmit = (e) => {
    e.preventDefault();
    editSection(selectedSection);
    history.push("/");
    console.log("selectedSection id",selectedSection.section, selectedSection.id)
  };

and the button function to spread the selectedSection and change the only the requested value in the button.
const handleOnChange = (userKey, newValue) => setSelectedSection({ ...selectedSection, [userKey]: newValue });

in my render code I've got my button set up like
<button href="/" className="bg-green-400 w-mt hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                  value={selectedSection.section}
                  onChange={() => handleOnChange("section", QuickLinks)}

                  type="submit"
                  >Add Section</button>

Now I've tried different things like changing the data-type in the useState Object, having the setSelectedSection in use effect to change the SelectedSection.section
but in the console what I'm noticing is the button is not carrying the data over.
I've imported my compenent as Quicklinks but I'm not sure why it's not passing the component into the selectedSection.section
here is the entire code of the editSection
import React, { useState, useContext, useEffect} from "react";
import { useHistory, Link } from "react-router-dom";

import { GlobalContext } from "./GlobalState";

import QuickLinks from '../components/sections/quick_links/quickLinks';
import QuickLinksPreview from './images/quick-link.jpg';

export const EditSection = (route) => {
  let history = useHistory();

  const { sections, editSection } = useContext(GlobalContext);

  const [selectedSection, setSelectedSection] = useState({
    id: null,
    section: {},
  });

  const currentSectionId = route.match.params.id;

  useEffect(() => {
    const sectionId = currentSectionId;
    const selectedSection = sections.find(
      (currentSectionTraversal) => currentSectionTraversal.id === parseInt(sectionId)
    );
    setSelectedSection(selectedSection);
  }, [currentSectionId, sections]);

  const onSubmit = (e) => {
    e.preventDefault();
    editSection(selectedSection);
    history.push("/");
    console.log("selectedSection id",selectedSection.section, selectedSection.id)
  };

  const handleOnChange = (userKey, newValue) => setSelectedSection({ ...selectedSection, [userKey]: newValue });

  if (!selectedSection || !selectedSection.id) {
    return
Invalid Employee ID.
;
  }

    return (
        <React.Fragment>

            <form onSubmit={onSubmit}>

                {/* ----------------------------Item List Start COPY------------------------ */}

Quick Links

Multi Card Quick Links

for Description and links

                         Beta
                        {/* Component Development Status
                           Constrution
                         Active
                         Testing
                        */}

                    S03-S5
                      {/* Pricing Levels as Structure
                            S = Labels that it is sections
                            02 = is the Template Id for Developers
                            S = Standard Price
                            3 = Price level
                      */}

                    <button href="/" className="bg-green-400 w-mt hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                      value={selectedSection.section}
                      onChange={() => handleOnChange("section", QuickLinks)}

                      type="submit"
                      >Add Section</button>

                  {console.log("Selected section", selectedSection.section)}
                  {/* ----------------------------Item List END COPY------------------------ */}

                  <Link to="/">Cancel</Link>

            </form>

        </React.Fragment>
      );
};

Answer: Try using onClick instead of onChange for the button. I think onChange is for <input> tags not buttons. Also href is for links, not buttons. Unless this button is in a form type=submit isn't necessary. Also an arrow function isn't required for onClick. onChange={() => handleOnChange("section", QuickLinks)} -> onClick={handleOnChange("section", QuickLinks)}.
Comment: maybe also rename `handleOnChange` to `handleOnClick` for readability.
Comment: Thats super helpful thank you! it's passing the function now in the console. though it does have a renderloop crashing it but I call that progress!


Proving a random walk with a drift is recurrent

Question: Given the following set of independent random variables $\mathbb{P}(X_n=1)=\frac{1+n^{-\beta}}{2}, \mathbb{P}(X_n=-1)=\frac{1-n^{-\beta}}{2}$ and the sum $S_n=\sum^n_{i=1}X_n$ I managed to prove that if $\beta<0.5$ then $S_n$ is transient by using Hoeffding's bound and that if $\beta > 1$ $S_n$ is recurrent by treating the random variables as a simple random walk with a drift - which I proved is finite almost surely.
I am now trying to prove the case of $0.5\leq\beta\leq1$. I am pretty sure intuitively that it is recurrent however I am not successful in proving the case.
Any help will be appreciated.
Answer: One way to prove this is to use the Lindeberg central limit theorem.  Let $m_1=2$, $m_2$, $m_3$, $\dots$ be a sequence of positive integers with $m_{i+1}\ge m_i^2$ for all $i$, and let $T_i:=X_{m_i+1}+\cdots+X_{m_{i+1}}$.  To apply the Lindeberg CLT to $T_i$, the first step is to compute the mean
\begin{eqnarray*}\mu_i&:=&{\Bbb E}X_{m_i+1}+\cdots+{\Bbb E}X_{m_{i+1}}\\
&=&(m_i+1)^{-\beta}+\cdots+m_{i+1}^{-\beta}\\
&\le&\int_{m_i}^{m_{i+1}} x^{-\beta} \, d\beta\\
&=&\frac{1}{1-\beta}(m_{i+1}^{1-\beta}-m_i^{1-\beta})&\qquad&\hbox{(if $\beta<1$; $\log(m_{i+1}/m_i)$ if $\beta=1$)}\\
&=&O(m_{i+1}^{1-\beta})&\qquad&\hbox{(if $\beta<1$; $O(\log m_{i+1})$ if $\beta=1$)}\\
&=&O(m_{i+1}^{1/2})
\end{eqnarray*}
and the variance
$$\sigma_i^2:={\Bbb E}[(X_{m_i+1}-(m_i+1)^{-\beta})^2]
+\cdots+{\Bbb E}[(X_{m_{i+1}}-m_{i+1}^{-\beta})^2].$$
Since $m_i\ge 2$ and $\beta\ge \frac 1 2 $, each term $(X_j-j^{-\beta})^2$ in this sum is always between $(1-3^{-1/2})^2$ and $(1+3^{-1/2})^2$.  Therefore, $\sigma_i^2=\Theta(m_{i+1}-m_i)$, and since $m_{i+1}\ge m_i^2\ge 2 m_i$, we also have $\sigma_i^2=\Theta(m_{i+1})$ and so  $\sigma_i=\Theta(m_{i+1}^{1/2})$.
Now, the Lindeberg condition is that, for all fixed $\epsilon>0$,
$$
\frac{1}{\sigma_i^2}\sum_{m_i+1\le j\le m_{i+1}} \mathbb{E} \left[(X_j - j^{-\beta})^2 \cdot \mathbf{1}(| X_j - j^{-\beta} | \ge \epsilon \sigma_i ) \right]\qquad\qquad(*)
$$
approaches zero as $i$ becomes large, but
since $|X_j-j^{-\beta}|$ is bounded and $\sigma_i\to\infty$, for $i$ large enough, (*) will be zero.  This means that we can apply the Lindeberg CLT to find that
$(T_i-\mu_i)/\sigma_i$ converges in distribution to a standard normal distribution.
Now, $$S_{m_{i+1}}=S_{m_i}+T_i \le T_i + m_i \le T_i + m_{i+1}^{1/2}$$ so
$${\Bbb P}(S_{m_{i+1}}\le 0\mid S_{m_i})\ge {\Bbb P}((T_i-\mu_i)/\sigma_i\le (-m_{i+1}^{1/2}-\mu_i)/\sigma_i)$$
and, by our estimates on $\mu_i$ and $\sigma_i$, there are constants $K>0$ and $L>0$ so that, for all sufficiently large $i$,
$$
m_{i+1}^{1/2}+\mu_i\le K m_{i+1}^{1/2}, \qquad \qquad
\sigma_i\ge L m_{i+1}^{1/2},
$$
so for sufficiently large $i$,
$${\Bbb P}(S_{m_{i+1}}\le 0\mid S_{m_i})\ge {\Bbb P}((T_i-\mu_i)/\sigma_i\le -K/L)\qquad(**)$$
and, by convergence in distribution, the right-hand side of (**) approaches $\Phi(-K/L)$ as $i\to\infty$, so for sufficiently large $i$,
$${\Bbb P}(S_{m_{i+1}}\le 0\mid S_{m_i})\ge\frac{\Phi(-K/L)}{2}.$$
This proves that $S_n$ is almost surely nonpositive infinitely often.  Similarly, $S_n$ is almost surely nonnegative infinitely often, so $S_n$ is recurrent.
Comment: Thanks. I see in the mean why it will be $O(m_{i+1}\cdot(m_i+1)^{-\beta})$ but not why it would be $O(m_{i+1}\cdot m_{i+1}^{-\beta})=O(m_{i+1}^{1-\beta})$
Same goes for the variance being $\Theta(m_{i+1})$, why does that happen?
Comment: Why does $|X_i|$ being vounded imply it meets the criteria for the lindeberg condition?
Comment: Also, I am having trouble with the end given that lindeberg holds and from that CLT, why does the convergence in distribution bound the right hand side? Also, it needs to bounf it by a positive real number not by 0
Comment: I expanded my answer to try to explain these points more clearly.
Comment: Where did you find the lindeberg equation formulation you used?
I saw online:
$\lim_{n\to\infty}\frac{1}{\sum_{i=1}^{n}\sigma_{i}^{2}}\sum_{k=1}^{n}\mathbb{E}\left[\left(T_{i}-\mu_{k}\right)^{2}\cdot1_{\left\{ \left|T_{k}-\mu_{k}\right|>\epsilon\sqrt{\sum_{j=1}^{n}\sigma_{j}^{2}}\right\} }\right]=0$

Also, the limit we receive is $\frac{\sum_{k=1}^{n}\left(T_{k}-\mu_{k}\right)}{\sqrt{\sum_{j=1}^{n}\sigma_{j}^{2}}}\overset{d}{\to}\mathcal{N}$ and not as written. What have I missed?
Comment: You need to use the form of the Lindeberg condition applicable to triangular arrays of random variables.  See for example section 10.2 in  [these lecture notes](https://www.stat.berkeley.edu/users/pitman/s205f02/lecture10.pdf) or Theorem 27.2 in Billingsley's _Probability and Measure_ (3rd ed.), and keep in mind that the $X$'s are being normalized in different ways in these two places and in my answer.


Service based database vs SQL Server Compact vs LocalDB?

Question: My goal is to create a stand-alone C# Windows form application with 2-3 tables that will be installed on client machine with a installer file. And I don't want to install SQL Server 2008 software on client machine, I'm using Visual Studio 2013 C# for development.
My options are SQL Server Compct 4.0 but I don't see Visual Studio 2013 has inbuilt support for that, when I add  new item to project I don't see Compact (.sdf) file option there.
I've installed third-party SQL Server Compact Toolbox so I can create .sdf file and connectivity but I believe Microsoft is not giving support for compact db now.
I can see service-based database (.mdf) file which is actually a LocalDb\\ something.
So what should I use if I don't want to install SQL Server 2008 on client but want to have db
at client software?
Comment: If you're using a `.mdf` file, or `LocalDB` - then you're using **SQL Server** (the full version) and thus you **MUST** install the SQL Server software on the client - possibly the Express edition or the further slimmed down LocalDB version - but still, you have to install something.
Comment: You want a SQL Database but you don't want to install any software? Perhaps you don't actually need a SQL database, perhaps you can use an XML file. As an aside, LocalDB is de facto at this point, and SQL CE is legacy software. Additionally, LocalDB offers a silent install mode, you can get the localdb.msi installers here http://www.microsoft.com/en-us/download/details.aspx?id=29062
Comment: maybe this can help http://stackoverflow.com/questions/2990750/how-to-choose-light-version-of-database-system
Comment: If you have only 2-3 tables why don't you just use **MS Access** database ? Simply you can add the access DB as a file to installer project and can be easily deployed in client machines.
Answer: You should mostly base your choice on your target platforms and the level of SQL Server functionality you expect.
Target Platforms:
LocalDB does not support older versions of Windows (e.g. Windows XP) or WoW.  Toad World's LocalDB overview has a good breakdown of its target-platform restrictions.
SQL Server Compact Edition has very few target-platform restrictions.  Check out its download page under "System Requirements" for specifics.
Functionality:
LocalDB better approximates SQL Server Express functionally.  SQL Server Compact Edition has many functional limitations (e.g. no support for stored procedures).
MSDN's introductory overview of LocalDB explains many of the important functional differences between LocalDB and SQL Server Compact Edition; and the aforementioned Toad World LocalDB overview explains some of what (not) to expect from LocalDB functionally too.
Redistribution:
Both SQL Server Compact Edition (per the "Additional Information" section of its download page) and LocalDB (per SQL Server forums) are freely redistributable: so you should be okay with either with respect to fine print.
Comment: Yes - but the fact remains - LocalDB is based on SQL Server Express and **requires** an installation - it cannot be used by just copying a few DLLs
Comment: @marc_s: LocalDB is a _version_ of SQL Server Express - with restrictions and simplifications that do not apply to SQL Server Express proper. For example, SQL Server Express supports remote connections and protocols other than named pipes; LocalDB does not. The differences between LocalDB and full SQL Server Express may not matter in many situations, but differences do exist between them.  See the references I cited for numerous other examples.
Comment: @marc_s: Fair enough. The installer is smaller, and installing LocalDB is simpler.  Technically SQL Server Compact Edition [requires an installation too](http://technet.microsoft.com/en-us/library/ms174619.aspx) - slipstreamed into app installation though it may be.  I see LocalDB as a shade of grey between full SQL Server Express and SQL Server Compact Edition in this respect.
Answer: maybe SQLite would be an option? check out: http://www.sqlite.org/
it's just a DLL/Assembly you need to reference and it's pretty straightforward..


Formula for calculating sample size for hypergeometric distribution

Question: Suppose you have an urn with "N" marbles.  All marbles are either black or white.  You take a sample of size "n" without replacing them to the urn.
With this one sample you would like to be able to make one of the following two statements:

Y% or greater of the marbles are white.
Less than Y% of the marbles are white.

Thoughts:

This approach uses the hypergeometric distribution.
In practice, my "N" will be large (1*10E5 to 1*10E6).

Questions:

What is the size of "n"?
What is the formula for calculating the required sample size "n"?
How to estimate the confidence interval for Y?

Thanks in advance.
Comment: Do you have a rough idea of the size of the proportion $Y$?
Comment: Roughly 1 in 1000 marbles is black.
Answer: First of all for background:
"The hypergeometric distribution applies to sampling without replacement from a finite population whose elements can be classified into two mutually exclusive categories like Pass/Fail" (Wikipedia)
That being said, if your sample size is extremely large it is possible that even without replacement your results may approximate the binomial distribution.
Equation for sample size calculation for small populations:
Hypergeometric distribution
 = (^2 ) / ((^2 (−1)+^2 ))
Where:

n  =  Minimum sample size
N  =  Population size
z  =  Confidence level  (zα/2)
p  =  Proportion of events in population
q  =  Proportion of non-events in population
E  =  Accuracy of sample proportions

Simple binomial distribution (included for comparison)
=(^2 )/^2
Useful links and resources:
My current reputation prevents me from posting more than 2 links so please vote this answer up if it is helpful to you:
Formula and examples: University of Regina
Online calculator
Google has the book: "Six sigma and beyond"
Useful examples on "stattrek.com"
Wolfram Alpha
digitheadslabnotebook.blogspot.com
Comment: The first link is indeed no longer valid.  I am leaving it in case someone wants to use it to track down another source.  The online calculator link still works for me (albeit slow).
Comment: First link ends up with "Forbidden", the second one does not open.
Answer: Using the formula provided by Stan in his answer to his own question and plugging in the values for $N$, $p$ and $q$ in the question, i.e.
Population: $N = 1,000,000$
proportion of white marbles: $p = 0.001$
proportion of black marbles: $q = 1 - p$
and assuming a precision
$E = 0.05$
we end up with
$$
n = \frac{1,000,000 \cdot z_{1-\alpha / 2}^2 \cdot 0.000999}{2499.998 + z_{1-\alpha / 2}^2 \cdot 0.000999}
$$
Here we need a clarification:
$z$ is not the confidence level but usually interpreted as the $(1-\alpha/2)$ quantile of the standard normal Distribution.
The confidence level is $1-\alpha$.
Typical values of $\alpha$ are 0.01, 0.05 and 0.1 and are set to control the probability of error type 1 in hypothesis testing. Wikipedia
Using the $(1-\alpha/2)$ quantile implies we want to conduct a two sided hypothesis test (otherwise we would have to use the $(1-\alpha)$ quantile).
Back to the example:
Let's use $\alpha = 0.01$, i.e. an 99% confidence level. Now we get a result for sample size $n$:
$$
\begin{align}
n &= \frac{1,000,000 \cdot 2.58^2 \cdot 0.000999}{2499.998 + 2.58^2 \cdot 0.000999}\\
&= 2.6513
\end{align}
$$
Discussion of result:
Clearly it is impractical to draw 2.6513 marbles from the urn. Thus drawing 2 or 3 marbles are the options to choose from.
Neither would be very satisfying...
Imagine we opt for drawing 3 marbles. What are the probabilities of drawing 0, 1, 2 or even 3 white marbles?
$P(0) = 0.997003$
$P(1) = 0.002994009$
$P(2) \approx 0$
$P(3) \approx 0$
Regarding a hypothesis test $H_0: p_0 = 0.001$ we are fine because the chances of rejecting the true hypothesis are at most 1% (as required by setting $\alpha = 0.01$).
Caution:
If it is not just about hypothesis testing but also about estimating the proportion of white marbles in the population you would not want to do this based on a sample size of just 3, because your estimate would be limited by design to the values 0%, 33.3%, 66.% or 100%. Not quite what you had in mind when specifying a precision of 0.05 (i.e. 5 percentage points).


Como posso saber se a variável é um número inteiro em Python?

Question: Como posso sabe se a variável é um número inteiro em Python?
Eu sei fazer isso em PHP:
is_int($variable); // bool(true)

Mas como posso fazer em Python?
Exemplo:
numero = 1 #é numero
nao_eh_numero = 'texto' # não é número

Answer: Válido pra Python 2 e 3
Usando isinstance
Passar como primeiro parâmetro a variável que deseja validar e como segundo parâmetro o "tipo".
Exemplo:
isinstance(numero, int) # True

Observação
Se você pretende validar se a variável é um número, usando Python 2. Precisará mudar o segundo parâmetro para (int, long), no Python 3 isso não é necessário porque não existe long.
isinstance(numero, (int, long))

Usando type
type(numero) == int # True

A diferença entre os dois é que isinstance também valida se o objeto é derivado da classe (uma classe filha). Ou seja, ele verifica toda a estrutura de herança do objeto. Já o type devolve apenas o tipo exato.
Exemplo para ilustrar
class MinhaClasseInt(int):
    pass

x = MinhaClasseInt(0)

type(x) == int # False
isinstance(x, int) # True

Answer: Eu usei essa formula aqui que fica mais fácil e dá o valor exato. Sem precisar se preocupar com o código considerar o (type)!
como:
x1 = float(input('Valor = '))
print(x1, type(x1))
def valor(v):
  n = int(v)
  m = v * 10
  s = n * 10
  if m == s:
    return ('O número {} é inteiro'.format(v))#retorn 1
  else:
    return ('O número {} é decimal'.format(v))#retorn 2
r = valor(x1)
print(r)

Esse ai tem como vc mudar o (return) ou diminuir e ele vai verificar se o valor é inteiro ou decimal (float "flutuante"])
Você também pode testar o código e o resultado com esse aqui:
import os
while True:
  x1 = float(input('Valor = '))
  print(x1, type(x1))
  def valor(v):
    n = int(v)
    m = v * 10
    s = n * 10
    if m == s:
      return ('O número {} é inteiro'.format(v))#retorn 1
    else:
      return ('O número {} é decimal'.format(v))#retorn 2
  r = valor(x1)
  print(r)
  p = input('RECOMEÇAR ! Aperte [ENTER]')
  os.system('cls' if os.name == 'nt' else 'clear')

Mas o básico é isto:
def valor(v):
    n = int(v)
    m = v * 10
    s = n * 10
    if m == s:
      return ('O número {} é inteiro'.format(v))#retorn 1
    else:
      return ('O número {} é decimal'.format(v))#retorn 2

Na parte de retornar tem (#reorn 1) or (#retorn 2). É para ficar mais facil de lidar com os resultados e fazer tipo assim:
def valor(v):
  n = int(v)
  m = v * 10
  s = n * 10
  if m == s:
    return 1
  else:
    return 2
while True:
  n = float(input('valor = '))
  r = valor(n)
  #Agora vc pode brincar
  if r == 1:
    print('Você digitou um numero INTEIRO se imbecil !')
  elif r == 2: # Ou vc pode usar [ELSE]
    print('Você digitou um numero DECIMAL seu aderbal !')

Ai fica mais ou menos assim:
Answer: Eu faria diferente e de forma mais fácil.
Faça assim:
numero = float(input('Digite um numero qualquer :'))

if(numero // 1 == numero):
    print('\nNúmero inteiro !')
else:
    print('\nNúmero Decimal !')

Perceba que número 1 retorna somente a parte inteira; logo, se essa divisão retornar o próprio número então se trata de um inteiro.
Comment: É a mesma coisa que o Guilherme BL respondeu: https://pt.stackoverflow.com/a/228700/3635
Answer: Na verdade esse // nem precisa ser feito, apenas perguntar:
if int(numero) == numero:

Comment: Mas a outra [resposta](https://pt.stackoverflow.com/a/176529/8063) já disse isso. :/
Answer: Mas usando tanto o type quanto o isinstance, se o conteúdo da variável for digitado com um ponto decimal (12.0, por exemplo), a variável será um float e o resultado da expressão será False, mesmo o número sendo inteiro.
Acho que esta resposta fica melhor:
if numero // 1 = numero: # se for True o número é inteiro

Isso funciona mesmo se for uma variável tipo float.
Comment: Se é um float, não é um inteiro. Matematicamente eles até podem ser equivalentes, mas computacionalmente não. O tipo float exige uma representação diferente, geralmente seguindo o padrão definido na IEEE 754.
Comment: Sim, a resposta computacional é com o código acima.
Mas eu quis aprimorar e pensar em uma resposta para a questão matemática.
Answer: def int_float(num):

  if num.isnumeric():
     num = int(num)
     return num

  elif num.replace(".", "").isnumeric():
     num = float(num)
     return num
  else:
     return num # é string

OBS:

.replace(".", "") - TROCA O PONTO do decimal POR NADA
.isnumeric() - Confirma se é número
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: @Samuel, não use as edições para descaracterizar as respostas. Mesmo que não concorde com o conteúdo respeite o que o autor quis dizer, a finalidade das edições é melhorar a leitura e apresentação visual da publicação. Para indicar a comunidade que uma publicação é de baixa qualidade você pode [a sinalizar](https://pt.stackoverflow.com/help/flagging) e também pode usar o nosso [sistema de votação em conteúdo](https://pt.stackoverflow.com/help/why-vote).


How can I use @WebMvcTest for a Controller that uses an autowired ConversionService?

Question: In a Spring Boot application, I have two POJOs, Foo and Bar, and a BarToFooConverter, which looks like:
@Component
public class BarToFooConverter implements Converter<Bar, Foo> {
    @Override
    public Foo convert(Bar bar) {
        return new Foo(bar.getBar());
    }
}

I also have a controller which makes use of the converter:
@RestController("test")
public class TestController {
    @Autowired
    private ConversionService conversionService;

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public Foo put(@RequestBody Bar bar) {
        return conversionService.convert(bar, Foo.class);
    }
}

I'd like to test this controller with @WebMvcTest, something like:
@WebMvcTest
@RunWith(SpringRunner.class)
public class TestControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(
                put("/test")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"bar\":\"test\"}"))
                .andExpect(status().isOk());
    }
}

but when I run this, I find that my BarToFooConverter was not registered with the ConversionService:
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [com.example.demo.web.Bar] to type [com.example.demo.web.Foo]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:206)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:187)
    at com.example.demo.web.TestController.put(TestController.java:15)

This seems to make sense, because, according to the Javadoc:

Using this annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests (i.e. @Controller, @ControllerAdvice, @JsonComponent Filter, WebMvcConfigurer and HandlerMethodArgumentResolver beans but not @Component, @Service or @Repository beans).

However, the reference guide differs slightly, saying that @WebMvcTest does include Converters:

@WebMvcTest auto-configures the Spring MVC infrastructure and limits scanned beans to @Controller, @ControllerAdvice, @JsonComponent, Converter, GenericConverter, Filter, WebMvcConfigurer, and HandlerMethodArgumentResolver. Regular @Component beans are not scanned when using this annotation.

It seems that the reference guide is incorrect here - or am I registering my Converter incorrectly?
I have also tried mocking the ConversionService in my test with:
@WebMvcTest
@RunWith(SpringRunner.class)
public class TestControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ConversionService conversionService;

    @Test
    public void test() throws Exception {
        when(conversionService.convert(any(Bar.class), eq(Foo.class))).thenReturn(new Foo("test"));

        mockMvc.perform(
                put("/test")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"bar\":\"test\"}"))
                .andExpect(status().isOk());
    }
}

but now Spring complains that my mock ConversionService is overriding the default one:
Caused by: java.lang.IllegalStateException: @Bean method WebMvcConfigurationSupport.mvcConversionService called as a bean reference for type [org.springframework.format.support.FormattingConversionService] but overridden by non-compatible bean instance of type [org.springframework.core.convert.ConversionService$$EnhancerByMockitoWithCGLIB$$da4e303a]. Overriding bean of same name declared in: null
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.obtainBeanInstanceFromFactory(ConfigurationClassEnhancer.java:402)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
    ...

Ideally I'd like to use my original approach, with the real Converter in my test rather than mocking the ConversionService, but with @WebMvcTest to limit the scope of the components that are started, so I also tried using an includeFilter in the @WebMvcTest annotation:
@WebMvcTest(includeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.example.demo.web.Bar*"))

but it still fails with the original 'No converter found capable of converting...' error message.
This feels like something that must be quite a common requirement - what am I missing?
Comment: I don't have time to investigate this any more thoroughly now, but just as a mention for people finding this - there seems to be a difference in the Spring version - I upgraded the version of Spring Boot a few weeks ago and found that tests started failing. I can't remember why now, but think it was that the real `ConversionService` was now being injected, when it hadn't been previously.
Answer: You can register your converter manually in @Before annotated method. All you have to do is to inject GenericConversionService and call addConverter(new BarToFooConverter()) to make the converter resolvable. In this case you can get rid of mocking part. Your test could look like this:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest
@RunWith(SpringRunner.class)
public class TestControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private GenericConversionService conversionService;

    @Before
    public void setup() {
        conversionService.addConverter(new BarToFooConverter());
    }

    @Test
    public void test() throws Exception {
        mockMvc.perform(
                put("/test")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"bar\":\"test\"}"))
                .andExpect(status().isOk());
    }
}

Alternative solution: Spring Boot since version 1.4.0 provides a collection of test-related auto-configurations and one of these auto-configurations is @AutoConfigureMockMvc that configures MockMvc component that works fine with injected converter components.


Uncertainty in Binary Classification of New Data (via Random Forest)

Question: We trained a binary classification RF and validated it with a test set of about N=300 entries. Here are the performance statistics:

We now would like to classify a production set of a couple of million items. If we just do that, the output of that will be p TRUE and 1-p FALSE where p lies within [0,1].
However, because we have a certain FP- and FN-Rate, this result/ratio comes with some uncertainty, right?
For that reason, we would like to quantify this uncertainty, e.g. with a 95% confidence interval, based on our performance measures. E.g. something like: With 95% probability, 20-25% of items in the production set are TRUE, 75-80% are FALSE. These numbers probably don't even add up, the range for TRUE would be sufficient.
Also, all these performance measures displayed above come with their own confidence intervals, maybe these could be considered too in that uncertainty calculation?
Bonus-Question: We used the caret package in R. Is there some sort of a function (in caret or in another R package) to do this automatically?
Answer: I get to your main question in the second paragraph, first a more general remark: You probably already know that you should not be optimizing accuracy with a data-set that has this level of class imbalance because there is probably also classification cost imbalance. (You imply that there is when you say you are mainly interested in the true class. If there isn't, then the problem is trivial and you can in your case have almost 90% accuracy without even constructing a classifier.) Most likely, a true record predicted as false is a bigger problem than the other way around. It is more important to identify the few true records and it can be tolerated to identify some more false records as true to get there. As you said, tree based algorithms provide per predicted record a probability that it belongs to the class true which you call $p$. You are not forced to put the cutoff at $p=0.5$, you can put it lower to make sure you don't miss the few true records. The relative misclassification costs between false positives and false negatives, as determined by your application scenario, can tell you where to put the cutoff.
To understand what this number $p$ means and what can be done with it, we need to look at the tree classifier. All your training set records have started at the tree's root, branched multiple times according to rules that the algorithm finds in the data and end up in a leaf. The goal is to have relatively pure leaves, each leaf being dominated by records of one class. (You could have perfectly pure leaves if you just keep branching, but you would be overfitting on your training set.) $p$ is the proportion of records in that leaf that are of the class you are trying to identify. This number loosely follows a frequentist interpretation of probabilities: If the record is part of this leaf, it has x out of y chances of being that class.
A forest is just a collection of trees that have been randomized (the variables to branch on are chosen randomly rather than to optimize gains in purity) and left unpruned (you branch till all leaves are pure). Each record is rooted through all the trees in the forest. $p$ is computed slightly differently here: It denotes the proportion of trees in the forest where this record ends up in a leaf dominated by this class. The probability within each tree would be binary since the leaves are pure in the absence of pruning. It only makes sense to compute $p$ on forest level.
Knowing how those values of $p$ are derived, I don't see how it would be possible to construct confidence intervals around every single one of them. Even if it was possible, it wouldn't be very practical, you would have one CI per record in your production set.
I also don't think you can or should make the kind of pronouncements you want to make on a data-set level ("With 95% probability, 20-25% of items in the production set are TRUE, 75-80% are FALSE"). Because of your class imbalance, you don't want to find out how many records exactly are true (according to a 0.5 cutoff), you want to bias that number upwards (by lowering the cutoff) so that you don't miss the true records. What you should do is determine your misclassification costs, put them in a loss function and then optimize that.
Also, once that you have chosen your model based on test set performance, you can retrain that same model (same number of trees in the forest same type of randomization etc.) with all the labeled data you have available. It was good to set a test set aside in order to choose a model. Once that is done, you want to use all the information you have to train a model which you will use for your unlabeled production set.
Comment: You can do that. If you want to have a better idea what the cutoff does to your production set, you are going to have to classify some records manually, perhaps those just above and just below the cutoff, to see if the classifier treats them right.
Comment: Thanks for this exhaustive answer, also regarding the workings of a random forest. Yes, we are aware of classification cost imbalance and specificity is more important to us (=higher cost of false positives than false negatives). We're not going to make the kind of pronouncements on the data-set level as you suggest, but we will probably try out different cutoff values and see how they affect the overall TRUE rate in the production data set, e.g. varying the cutoff value (which is now 0.3) in the range [0.2,0.4] and see how strongly the TRUE rate varies. Or do you think this is nonsense?
Answer: If I understand your question correctly, I think it has been answered before:
Confidence Interval - Binary classification
Also be careful when interpreting confidence intervals:
From OpenIntro
A careful eye might have observed the somewhat awkward language used to describe confidence intervals.  Correct interpretation:
We are [XX]% confident that the population parameter is between...
Incorrect language might try to describe the confidence interval as capturing the population parameter with a certain probability.
This is one of the most common errors:  while it might  be  useful  to  think  of  it  as  a  probability,  the  confidence  level  only  quantifies  how plausible it is that the parameter is in the interval.
As we saw in Figure 5.2, the 95% confidence interval method has a 95% probability of producing an interval that will contain the population parameter.  A correct interpretation of  the  confidence level is  that  such  intervals  will  contain  the  population  parameter  that percent of the time.  However, each individual interval either does or does not contain the population parameter.  A correct interpretation of an individual confidence interval cannot involve the vocabulary of probability.
Another especially important consideration of confidence intervals is that they only try  to  capture  the  population  parameter.  Our intervals say nothing about the confidence of capturing individual observations, a proportion of the observations, or about capturing point estimates.  Confidence intervals only attempt to capture population parameters.
Comment: Thanks for your hint at the language/interpretation problem - I had that in mind, actually, but didn't want to make things all too complicated. Still, I don't think our question is answered in the other question. The answer there talks about confidence intervals for performance metrics, not for overall classification results, if I'm right.


How do I find the Logistic Distribution for a Logit Regression in R

Question: As far as I am aware, R gives the output of a logit model, of the form:
glm.logit=glm(model,binomial(),Data.df)

as the log-odds ratio.
I would like to obtain the distributional function $\frac{exp(\beta'x_i)}{1+exp(\beta'x_i)}$ from my model
Comment: you can take out the coefficients and do an exponential of them to get you what you need? if that's what you are referring to
Comment: is it the same question as your previous? https://stats.stackexchange.com/questions/495657/confusion-over-predict-command-in-r
Answer: Not sure what you are after, but if you wonder whether we could display prediction as probabilities instead of on the log-odds scale, you can simply use a dedicated function or call the predict method with argument type = "response", as shown below:
data(birthwt, package = "MASS")
birthwt$lwt <- birthwt$lwt * 0.45
birthwt$race <- factor(birthwt$race, levels = 1:3, labels = c("white", "black", "other"))
fm <- low ~ lwt + race
m <- glm(fm, data = birthwt, family = binomial)
d <- expand.grid(lwt = seq(40, 100), race = factor(levels(birthwt$race)))
d$yhat <- predict(m, d, type = "response")

The predictions can easily be plotted using any R graphical backend. Here is an example using ggplot:
library(ggplot2)
library(directlabels)
p <- ggplot(data = d, aes(x = lwt, y = yhat, color = race)) +
       geom_line(aes(group = race), size = 1) +
       guides(color = FALSE) +
       labs(x = "Mother weight (kg)", y = "Pr(low = 1)", caption = "Predicted response curves")
direct.label(p + aes(label = race), method = "smart.grid")

Note also that there are builtin tools for the logit function, $\text{logit}(x) = \frac{x}{1-x}$, or her loyal companion $\frac{1}{1 + \exp(-x)}$, namely qlogis() and plogis, which stand for the quantile and cumulative distribution functions for the logistic distribution.


Concerns regarding documentation of libraries in java

Question: I was asked in class to look for libraries along with their operation and documentation type. This is the first time I'm hearing or having anything to do with library documentation. I tried looking for some form of clear and concise explanation of what it is but I don't think I've actually understood what it is and its importance.
Can someone explain to me what is meant by documentation type and where can I find more details of a particular library's documentation?
Comment: What about Java documentation: https://docs.oracle.com/javase/8/docs/api/
Comment: Yes,while looking for details about various libraries I've across this page. While this gives a lot of description about the libraries I didn't really get what portion of all that info actually covered anything about documentation. There is also so much information about each library that I don't know what I should focus on specifically.
Comment: @Hades the JavaDoc link above gives specific, lowlevel api detail for every Class and every method on each class. This is one type of documentation, another example would be the Java platform documentation which is broader and higher level https://docs.oracle.com/javase/8/docs/
Comment: For a general definition of documentation, see https://en.wikipedia.org/wiki/Software_documentation
Answer: Documentation has all the information you need to make use of the library. There are code samples, tutorials, developer guides, API documentation, and more to quickly understand the library and use it.
Actually API documentation is mostly developers look while using particular library.
It has technical content deliverable, containing instructions about how to effectively use and integrate with an API. It's a concise reference manual contains all the information required to work with the API, with details about the functions, classes, return types, arguments and more, supported by tutorials and examples.
If you talk about JAVA 7 https://docs.oracle.com/javase/7/docs/api/ is the documentation.
Answer: Java APIs are most often documented with JavaDoc. Whether it is generated and shared online or with the library varies from library to library. Other types could be wiki pages, web pages, or other text docs, manuals, reference materials. Pick a couple of popular libraries and then look for their docs. What did you find?


Php function missing one record

Question: I have a php function
function getMembersByFamilyNumber($familyNumber){
        $html = "";
        $query = db_execute("SELECT * FROM `family_members` WHERE `family_number` = '".$familyNumber."' and `isActive`= '1' and `isDelete`= '0' ORDER BY id DESC");
        $check = mysql_fetch_assoc($query);
        if ($check) {
            while($result = mysql_fetch_assoc($query)){
                extract($result);
                $html.='

                        <time class="cbp_tmtime" datetime="2013-04-10 18:30">'.$familyNumber.' '.$relation_head.'</time>

'.$name.'

                            <button type="button" class="btn btn-success pull-right" onclick="editPageContent(\'editpagecontent\',\'editMember\',\''.$id.'\');">Edit</button>
                            <button type="button" class="btn btn-danger pull-right" onclick="deletePageContent(\'deletepagecontent\',\'deleteHead\',\''.$id.'\');">Delete</button>

Age: '.$age.' years old

Education: '.$education.'

Occupation: '.$occupation.'

Alive: '.$alive.'

Phone: '.$phone.'

CNIC: '.$cnic.'

                ';
            }
            return $html;
            exit;
        }else{
            return "

No members found.

";
        }

    }

Is is returning only one record, but in database there is two records against this query, whenever i i execute this query in MySQL it returning two rows, but whenever i run this code it return only second record, missing first record, every time it missing first record. means if my table have 5 records this function returns 4 records and miss 1st record. Why this happens? help me.
Comment: In your loop you are setting the value of the `$html` each time through the loop, rather than appending it.  That means your last record will be the only one displayed.
Comment: Perhaps because you call #check=mysql_fetch_assoc($query), which removes first entry, then later call $result = mysql_fectch...... You should be able to get rid of the $check=mysql.. part and the "if" statement, and use everything in the while.
Comment: No, I  m not seeting value of $html, i m appending it by $html.=""
Comment: Instead of the CHECK try this:
  if (mysql_num_rows($query) >0)
  then go to the WHILE loop with undisturbed data
Answer: Use mysql_num_rows($query) not use
$check = mysql_fetch_assoc($query);
        if ($check) {
This is correct solution:
if (mysql_num_rows($query) > 0) {
while($result = mysql_fetch_assoc($query)){
Comment: ok i removed my $check statement, but still same issue, why it is missing my 1st record?
Comment: Because, `$check = mysql_fetch_assoc($query);` get row from query data and set pointer to next value.

Php function missing one record


Stipe Checkout Barcelona vs now

Question: So I happily stumbled upon the video 'Shut up and take my money' from DrupalCon Barcelona (2015) to learn about the module 'stripe_checkout'. Notwithstanding my undying admiration for Drupal Commerce, I fully concur with the speaker that not all sites that want people to give them money need an entire Commerce Interface.
I was able to (navigating beyond the update-esoterica) mirror the behavior from the video on my sandbox, then the client site.
I very foolishly promised the solution to my client before remembering to test as an anonymous user.
It is quite clear that the Barelona Video version prompted for Email, then CC data. However, the current stripe_checkout gathers the email from the Logged in User, and FAILS COMPLETELY for anonymous users. Unless I am missing something (always a possibility) there is no 'config setting' for allowing/disallowing for anonymous users.
So my questions:
1) Has anyone out there already cleared this hurdle with some glueCode or some-such that could be shared here?
2) Or is there some other mechanism for clearing this hurdle short of implementing full-on Drupal Commerce?
Comment: Welcome to Drupal Answers! Wasn't the downvoter, but I'm guessing it's because you're asking for free code or tutorials (strongly discouraged here). You might find a more receptive audience on its project page or more DC-centric channels (the .org forum, IRC, Slack, etc.).
Answer: I fully accept responsibility for my 'inappropriate' question, and thanks for those that posted helpful information about how to avoid the slings and arrows of StackExchange participation in the future. I do find myself flummoxed by all this, but I so completely find StackExchange answers of such a high quality I accept my confusion as a 'price of admission'. I do apologize in advance for additional faux pas in the future... indeed, perhaps this post.
So I solved it, with a direct code edit, not the proper glueCode that I will continue to work on. Notwithstanding, I am going to post my 'Psuedo-Diff' of the code changes I made to accomplish what I was looking for. With the caveat that I am 'breaking rules', perhaps others can find this a helpful jumping-off point for better expression of a similar solution.
I really need this for a project, so this is 'good enough' for me for this site for right now, but I fully intend to circle-back and attempt to solve this problem with proper glueCode or maybe even participation in the overall project. With that, I will say, 'So Long!' and post my Pseudo-Diff code below:
<code>
/**
 * @file: modules/contrib/stripe_checkout/src/Controller/StripeChargeController.php
 * @line: approx 64
 */
                        $amount = $node->$field_name->value;
                        $field_settings = $node->$field_name->getSettings();
                        $currency = $field_settings['currency'];
-                       $user = \Drupal::currentUser()->getAccount();
+                       if (!\Drupal::currentUser()->isAuthenticated()) {
+                               $user = \Drupal\user\Entity\User::load(10);
+                       /**
+                        * use whatever UID correlates to the dedicated 'anonymous payer'
+                        * you set up for this purpose, for me for this site is is User Number 10
+                        */
+                       } else {
+                               $user = \Drupal::currentUser()->getAccount();
+                       }

/**
 * @file: modules/contrib/stripe_checkout/src/Plugin/Field/FieldFormatter/StripeCheckoutFormatter.php
 * @line: approx 92
 */
                $default_settings = $this::defaultSettings();
+               if (!\Drupal::currentUser()->isAuthenticated()) {
+                        $user = \Drupal\user\Entity\User::load(10);
+                       /**
+                        * use whatever UID correlates to the dedicated 'anonymous payer'
+                        * you set up for this purpose, for me for this site is is User Number 10
+                        */
+               } else {
+                       $user = \Drupal::currentUser();
+               }

/**
 * @file: modules/contrib/stripe_checkout/src/Plugin/Field/FieldFormatter/StripeCheckoutFormatter.php
 * @line: approx 127
 */
                                        'locale' => 'auto',
                                        // @todo Make configurable.
                                        'image' => 'https://stripe.com/img/documentation/checkout/marketplace.png',
-                                       'email' => \Drupal::currentUser()->getEmail(),
                                        'label' => $link_text,
                                ],
                                '#is_free' => $is_free,
                                '#price' => $price,
                                '#entity_id' => $item->getEntity()->id(),
                                '#field_name' => $item->getFieldDefinition()->getName(),
-                               '#logged_in' => \Drupal::currentUser()->isAuthenticated(),
+                               '#logged_in' => TRUE,

/**
 * @file: modules/contrib/stripe_checkout/src/Plugin/Field/FieldFormatter/StripeCheckoutFormatter.php
 * @line: approx 151
 */

+                       if (\Drupal::currentUser()->isAuthenticated()) {
+                               $elements[$delta]['#data']['email'] = $user->getEmail();
+                       }

</code>

Stipe Checkout Barcelona vs now