Best option to practice piano whilst away from home?

Question: In a few weeks, I will be on a holiday that will last just over a month. Most of my hobbies can be bought with me, however I fear that this will not be the case with piano.
This answer outlines some useful ways to keep practicing however relies heavily on the face that there are pianos in the area. For me this will certainly not be the case.
I have considered some options that I might be able to do however I am not sure about the long (month)-term benefits or consequences.
The main option I am considering is getting a roll up piano. I personally am not to fond of keyboards (as I am an organist/pianist) however even after the warnings about wrist strain and loss of touch I still feel that this is a better option than not having a piano/keyboard at all.
So the questions I would like answered are:

Is it worth getting a roll up piano or a similar small portable keyboard for practice during around a month of no piano?
Is a month even enough to seriously impair or damage skill?
Are there any other alternatives?

Edit:
When I mean portable, I mean it has to be able to fit in an average sized suitcase.
Comment: _Nothing_ is enough to seriously impair or damage skill (except actual physical damage). Of course you'll always need to refamiliarise with a proper keyboard after a change, but that's not necessarily a bad thing. — Other alternatives: if this is not so much to keep you in training with piano as with being able to play music, then why not bring a completely different instrument? Might be a good opportunity to learn one.
Comment: How long have you been playing for?
Answer: One  option is mental practice, in which you basically are imagining, in as much detail as you can, what you would be practicing. You do this in terms of feel, movement, and the sound your movement would produce. I play violin, and find that when I'm spending half an hour in the evening or morning doing this, my playing improves more than when I only play. Sometimes I'm playing air fiddle, sometimes it really is all in my head. Solid mental practice should at least help you not lose any skills while you cannot play. It does take practice to be able to use the technique well, of course.
The classic read on this is The Inner Game of Tennis, by Timothy Gallwey.
I've taken several breaks in my playing, where I'm playing either very little, or not at all, for a few months at a time. It's never taken me more than two weeks at most to catch up to where I was before when I get back to playing regularly. If I've been doing any practice at all, it only takes a few days to get back where I was. You won't lose much if you take a complete break, and you may find yourself reinvigoriated when you come back to your instrument. Whatever you choose, enjoy your holiday!
Answer: I had no idea roll-up pianos existed!  Checking out their reviews, even for the expensive ones that come with foot pedals, I would suggest they're fun unless you're used to the real thing, in which case you'll find they're unplayable, that's how it seems.
As they're not played in the same way, I would say they're not sufficient to practice with.  There are reviewer comments about poor latency, insufficient polyphony, requiring a perfectly flat surface, etc.  These are toys, by the looks of it, they are certainly not pianos.  Unless your skills are single-fingered melodies, then I don't think this is worth it.  I just saw a guy on YouTube really struggling with his.

A month without practice is nothing to worry about, although I can understand the apprehension, I worked abroad for a year and thought my English would suffer!
I have also been on holidays which have meant I was away from keyboards for a month, and don't read sheet music when I play, everything is memorised, a month without playing is not long enough for me to forget how to play something that I could play off-by-heart before.  In fact, sometimes I think a break does some good, any loss of skill would be effortlessly recovered, and certainly nothing serious.

When on holiday I just don't think about it.  I don't do anything to practice away from a keyboard, so I cannot suggest any alternatives.  If you're a writer/composer, you can still write lyrics, record local sounds for inspiration, experiment with melody on a smartphone/tablet keyboard app, listen to new music to find new things to learn to play, anything like that.
Answer: Mental practice and/or playing a table edge is what is realistic.  I think that there may be software for turning tablets into keyboards that might work better than the rollups.  But in either case, the touch will be nothing at all like that of an organ or piano and you'll probably be fighting most of the time to get the sound properly to register.
If you need a visual aid, it would likely be much less distracting to take a piece of cloth with piano print on it: I think they are available as keyboard covers.  Of course, you need to pin it to the table, but tablecloth clamps left and right should do the trick.
If you want something useful as an instrument, take a small accordion, possibly a reedless one.  Reedless accordions (like from Roland) are probably the smallest portable keyboards that are musically useful.  However, if you indeed use a piano keyboard, the range is very limited.  The same size factor with a chromatic button accordion is much more useful, but that gives you an instrument that has not even the right hand controls in common with piano/organ.  To be fair, the instrument itself is rather different anyway, more comparable to a harmonium.
A full-size acoustic concert instrument useful for most keyboard music will easily weigh in at 15kg.  You don't want that for travel.  If you don't have a "converter accordion", the left hand side will be limited to particular keyboard music using a bass/chord accompaniment scheme with reasonably simple chords.  Stuff like Scott Joplin and most popular music works quite well, Grieg doesn't.  There are small acoustic converter accordions, but used instruments are rare and not at "tryout" financial levels.
At any rate: accordions make for a few portable acoustic and electronic keyboard options but are a separate instrument class.  And when you are aiming for "portable", a piano keyboard rather than a chromatic button keyboard for the right hand is a liability regarding the size/range tradeoff.
If you are game for learning what amounts to an instrument of its own even though related, you get more options to carry music with you.  Certainly beats a roll-up piano.


Dúvida Código Python e Opencv2

Question: Nesse código eu consigo fazer a detecção facial a partir de uma webcan. Eu uso a camera do meu notebook. Eu quero que esse código emita uma mensagem de texto, por exemplo "Pessoa Detectada" toda vez q ele detectar um rosto. Eu tentei colocar um "if" mas me atrapalhei.
(if len(facesDetectadas)>=1:
        print ("PESSOA DETECTADA")

Outra dúvida que eu tenho é que nesse código eu estou acessando a câmera do meu notebook (video = cv2.VideoCapture(0)). Se eu quiser acessar uma câmera q esteja conectada a um servidor, como ficaria essa linha de código?
Abaixo segue o meu código. Obrigado pela atenção.
import cv2

video = cv2.VideoCapture(0)
classificadorFace = cv2.CascadeClassifier('cascades\\haarcascade_frontalface_default.xml')

while True:
    conectado, frame = video.read()

    frameCinza = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    facesDetectadas = classificadorFace.detectMultiScale(frameCinza, minSize=(70,70))
    for (x, y, l, a) in facesDetectadas:
        cv2.rectangle(frame, (x, y), (x + l, y + a), (0, 0, 255), 2)

    cv2.imshow('Vídeo', frame)

    if cv2.waitKey(1) == ord('a'):
        break

    if len(facesDetectadas)>=1:
        print ("PESSOA DETECTADA")

video.release()
cv2.destroyAllWindows()

Comment: Obrigado pela dica. Olhei o tour do site e achei ótimo. Não havia me atentado para esse detalhe e ja corrigi isso. Grato pela atenção.
Comment: Olá @Rodrigo, vejo que você já e membro do site a algum tempo, porém me parece que você ainda não esta muito ambientado de como o site funciona então vale apena você dar uma olhada no nosso [Tour], digo isso porque estou vendo que você fez um total de 9 perguntas até o momento e apesar das repostas dadas a você terem ajudado você nunca aceitou uma resposta, apesar de parecer que a mesma resolveu seu problema. Isso não é bom para a saúde do site, porque sua pergunta fica como **não resolvida**, ao aceitar uma resposta recompensara quem te ajudou e ajudara quem tiver p msm problema. =D
Answer:
Eu quero que esse código emita uma mensagem de texto, por exemplo "Pessoa Detectada" toda vez q ele detectar um rosto.

Você está fazendo certo. Ao fazer a verificação if len(facesDetectadas)>=1, você está verificando se houve ao menos uma face detectada. Eu testei seu código e tudo funcionou conforme esperado.
Verifique se não está tendo nenhum erro com seu código. Por exemplo, se o arquivo haarcascade_frontalface_default.xml está dentro de uma pasta chamada cascades no mesmo diretório do seu arquivo .py.
Verifique também se você está acessando a webcam corretamente. Com esse seu código, é esperado que abra uma janela com o streaming da sua webcam e, ao reconhecer um rosto, este deve ficar com um quadrado vermelho em volta dele.
A sua cláusula if está correta. Se você ainda estiver com erros, é com outra parte da execução do seu código.

Se eu quiser acessar uma câmera q esteja conectada a um servidor, como ficaria essa linha de código?

Você vai ter que acessar a câmera pelo endereço de rede e porta dela.
video = cv2.VideoCapture('endereço_ip:porta')
Veja o endereço exato do streaming da câmera que você deseja trabalhar. Pode ser que esteja ainda dentro de uma função javascript em diretório no endereço especificado, por exemplo:
video = cv2.VideoCapture('endereço_ip:porta/?action=stream')
Ou em um MJPEG:
video = cv2.VideoCapture('endereço_ip:porta/nome_do_arquivo.mjpeg')
Há diversas outras formas, mas tudo vai depender da configuração de instalação da sua câmera.
Comment: Obrigado pela dica.
Comment: Se ainda estiver com erro depois de verificar o que eu disse, mostra aqui pra gente ajudar.

Dúvida Código Python e Opencv2


PHP get redirected link

Question: Im trying to get URL of final website im getting redirected.
Link i go is- http://www.primewire.ag/external.php?url=aHR0cDovL3d3dy5wcm9tcHRmaWxlLmNvbS9sL0RBMTU1RjYwRUYtRkMyNzREQ0Q4RA
after you go that link you get redirected into- http://www.promptfile.com/l/DA155F60EF-FC274DCD8D
I want to get second URL.
I found similar question in here
But using code that i got from there
        $url= 'http://www.primewire.ag/external.php?url=aHR0cDovL3d3dy5wcm9tcHRmaWxlLmNvbS9sL0RBMTU1RjYwRUYtRkMyNzREQ0Q4RA';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $a = curl_exec($ch); // $a will contain all headers

        $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL

        // Uncomment to see all headers
        /*
        echo "
";
        print_r($a);echo"
";
        echo "
";
        */

        echo $url; // Voila

echos out first URL not redirected URL.
Thank you
Comment: Enable verbose mode to output the full set of requests and responses to be sure the redirect is actually happening
Answer: The server is not redirecting (response is 200 not 304).
The returned HTML contains
<frameset rows="24,100%" frameborder="0">
   <frame src="frame_header.php?hello=&title=" scrolling="no" />
       <frame src="http://www.promptfile.com/l/DA155F60EF-FC274DCD8D" />

</frameset><noframes>http://www.promptfile.com/l/DA155F60EF-FC274DCD8D</noframes>

which would trigger an HTML browser to load that page. curl doesn't parse the returned HTML, just the HTTP headers because it's an HTTP client, not an actual HTML browser. So the second URL is not actually ever being requested (which you could verify by looking at what curl actually returned in your example code), and the effective URL is actually the one you are getting back.
Comment: Then is it possible to parse that HTML?
Answer: Your code is working right, but the target server is not redirecting you anywhere. Here's the html response to your first curl request:
<frameset rows="24,100%" frameborder="0">
   <frame src="frame_header.php?hello=&title=" scrolling="no" />
       <frame src="http://www.promptfile.com/l/DA155F60EF-FC274DCD8D" />

</frameset><noframes>http://www.promptfile.com/l/DA155F60EF-FC274DCD8D</noframes>

As you can see, that is not a redirect, it's a frame which loads the final page. Follow redirects won't help you here.

PHP get redirected link


Spring boot MVC - Block users from seeing endpoints by changing id in url

Question: I'm writing a pretty simple ecommerce app with spring boot and thymeleaf and I found out that users can see any order by changing the id in URL.
For example:
User placed an order with ID 5, so he can see his order on url: /order/details/5
But if the user changed url to f.e /order/details/4 he can see details of order that he shouldn't be able to see.
Is there a simple way to block it with Spring security?
Comment: Yes Authorization is way to go.
Answer: First off, let's get some lingo out of the way:
Authentication - The act of proving someone's identity. E.g., you login with a username, but you need a password to prove that it's you.
Authorization - Is the act of granting a user permission to perform an action.
Those terms are important when reading the Spring Security Documentation.
I assume that you already authenticate user and now you want to authorize them to view, e.g., their own orders, but not those of other users.
But I guess the orders are stored in a database. So you'll probably have to authenticate in your service layer. Meaning Spring Security takes care of authentication and you have the user available. When you fetch some order, you also need to make sure that the authenticated user is the owner.
Another thing to consider is using UUIDs as primary key. That makes it much harder to guess an ID but this is absolutely no replacement for authorization! Seriously. It is not. Security by obscurity is broken.
Comment: Yes, that's right.
Comment: Thank you for your comment.
Yes, I already Authenticate users, by email and password, so now I need to authorize users to view.

So I guess first I need to check IF the authenticated userID matches the userID in Order table - then authorize the view, am I correct?


How to store (and analyse) multi-answer multi-choice questionnaire data

Question: I have just carried out a questionnaire which has a number of questions which are multi-answer and multi-choice. That is, the respondent can tick as many of the options as apply to them - so they may choose no items, one, two, or seven! There is also an 'Other' field for those who find the options don't apply to them.
My question is: how should I store this data (within the R language) so that I can analyse it most easily? The sort of analyses I'd like to do are generally fairly simple - looking at the percentages of different responses within the questions, and won't involve much that is hugely deep statistics (I don't really have a large enough sample size to do this).
I can think of a number of ways to store the data, as listed below, but I'm not sure which will work best and be easiest to deal with. Other people must have dealt with these issues before and found out how best to do it - so what do you think?
Possible ideas I've had include:

Use a single column of a dataframe for each question, which contains some sort of comma-separated list - easy to input the data, but I suspect it'll be hard to analyse
Multiple columns for each question - up to the maximum number of answers that I think anyone will tick (5-6 I suspect - but what if I get more?) and put the name of the answer in each of these columns
A column for each possible answer and use boolean values in the columns to signify what has been ticked. This probably sounds better, but I'm not sure how I'd then go about analysing it.

What do people think?
Answer: Your last option sounds the best to me. Analyzing, is just filtering on that column of the data frame.
Answer: The last answer is the best one for your situation. The basic approach is that each check-box should be stored as a 0 (unchecked) or 1 (checked). If you have logic in the questionnaire so some people do not get asked the question, you can have 0 (exposed to question, but unchecked), 1 (checked) and missing/null (not exposed to question).
The analysis can be very easy - sum up the values in the column (ie count all the 1s) and divide by the number of responses (count all the 1s and 0s). That's the percentage that checked the box and where you can start.
In some situations, when you have a very wide range of possible answers and each respondent has responses on a small set of that range, it may be more efficient to store each record as a combination of the respondent id, the response type, and the value of the response. This helps you avoid having a table with hundreds or thousands of columns which can be unwieldy for storage purposes.


How do I use the RISC-V Vector (RVV) instructions in LLVM IR?

Question: In this presentation Kruppe and Espasa give an overview of the RISC-V Vector extension (RVV) and on slide 16 they show LLVM IR samples which use the vector instructions through intrinsic functions, such as:
%vl = call i32 @llvm.riscv.vsetvl(i32 8)

At the time of the talk (April 2019) LLVM support for the V extension was developed out-of-tree at https://github.com/hanna-kruppe/rvv-llvm. However, that repository is archived now and the README file indicates that it is outdated since support for the RISC-V V extension is now developed upstream. I assume that this means that the features are now available from LLVM master at https://github.com/llvm/llvm-project.
However, when I pull the current master and build it and try to compile the sample code with llc (specifying the target with --mtriple=riscv32-unkown-none-rv32imv), I get following error:
error: ../llvm-project/build/bin/llc: test.ll:4:18: error: use of undefined value '@llvm.riscv.vsetvl'

It seems that the V extension is available, since llc -march=riscv32 -mattr=help lists it:
Available features for this target:
...
  experimental-v           - 'V' (Vector Instructions).

Do I have to explicitly enable target features that are marked as experimental? Are these vector intrinsics shown in the slides even present in the upstream version? If yes, how do I use them? If no, how do I then use vector instructions in LLVM IR?

Follow-up: in this post Eli Friedman explains that target-specific intrinsics should be defined in include/llvm/IR/IntrinsicsRISCV.td, and indeed in the archived out-of-tree repository that file contains some vector-specific intrinsics which are not present in the upstream version. If these intrinsics have not been ported upstream, what is then the correct way to use the RISC-V vector instructions?
Comment: Is there any update on this topic since last year?
Comment: @fabian Yes, support for vector intrinsics has been merged in the mean time and can be used by enabling the V extension: `llc -mtriple riscv32 -mattr=+experimental-v -o test.S test.ll`
Comment: thank you for the quick reply. I am coming from the riscv-gnu-toolchain wanting to use LLVM instead now. So I am somewhat new to LLVM. Can you point me to some resources on how to set up a RISC-V toolchain with vector support for rvv1.0 (intrinsics or inline assembly)? I am looking to go from C/C++ all the way to RISC-V binary/elf.
Answer: There are only two riscv triple defined in llvm/include/llvm/ADT/Triple.h: riscv32 and riscv64.
By default HasStdExtV which is the flag corresponding to experimental-v in initialized to false in llvm/lib/Target/RISCV/RISCVSubtarget.h, if you want to use this extension you need to enable this feature.
Clangs seems also supporting this feature. In clang/lib/Driver/ToolChains/Arch/RISCV.cpp you can see that march support v feature and generate experimental-v for llc.
There is nothing in include/llvm/IR/IntrinsicsRISCV.td about Vector extension , however you can find the description of the  instructions from the standard 'V' Vector
extension in llvm/lib/Target/RISCV/RISCVInstrInfoV.td. It still experimental. In clang also you can find that even if the v extension is supported, in the default you can see // Currently LLVM supports only "mafdc". in clang/lib/Driver/ToolChains/Arch/RISCV.cpp
Comment: @kassiopeia what about inline assembler or writing your vector function in assembly language (i.e. compiler the `.s` file with clang then as separate translation unit)? Perhaps this is already supported by LLVM/clang.
Comment: @maxschlepzig I asked on the LLVM dev mailing list and was told that currently there is only MC layer (i.e. assembly level) support for RISC-V V instructions, so yes, I can use vector instructions in assembly code. However, I was hoping to use LLVM's register allocation and instruction scheduling functionality, which is currently not possible.
Comment: Thanks a lot for pointing that out, I do now explicitly enable the V extension with `-mtriple=riscv32 -mattr=+experimental-v` in `llc` and with `-menable-experimental-extensions -march=rv32imv0p9` in `clang`. Yet it seems that the extension cannot actually be used, since the lack of intrinsics means the vector instructions cannot be used in LLVM IR. Unless there is another way that does not involve intrinsics?
Answer: I asked on the LLVM developper's mailing list: currently (Nov 2020) there is only MC layer (i.e. assembly level) support for the RISC-V V extension in LLVM (so no intrinsics right now).
However, there is an RFC and patch that adds initial support for vector load, store and integer add intrinsics, as well as the required infrastructure to generate vsetvl[i] instructions.


launch screen xib not displaying imageview correctly

Question: I'm using a launch screen xib and I can't get the image within the UIImageView to appear.  Currently, I have a UILabel with the imageView placed right below the label and also centered horizontally.  I set all the constraints for the imageView but for some reason the label appears but the image doesn't.  This is my first time using the whole wAny hAny size classes.  Is there something I'm missing?
Comment: Do you have all images for each resolution ? Are you using Images.xcassets ?
Comment: No I'm using a xib, instead of launch images
Comment: Set center vertically and also set the fixed width and height of uiimage.
Comment: No, i am asking about Hand-White-Out.png, do you this image in all resolution ?
Comment: @Balaji I added the center vertically constraint and aspect ratio.  It got better but still off.  6+ image is still tiny.
Comment: @Brosef this is what you want ? https://www.dropbox.com/s/80zm4px6mh8c1s7/demoCanDelete%203.zip?dl=0
Comment: @Brosef: Can u show the image that you want
Comment: @saadnib yes i do.  I'm using the highest resolution version for the 6+ and setting the `UIImageView` setting to "aspect fit".
Comment: @Brosef can you write constraint in words that you want ? like image must have in center , label must be above the image view etc
Comment: @Jageen not sure what you mean.  I don't know where I would write the constraints since its a launch file xib.
Comment: @Brosef i mean write it in question, :)
Comment: @Jageen The image is suppose to be the same image that appears on the first view controller after the launch screen with the same (x,y) position and size.  The image on the first view controller has a vertical space constraint to the top layout guide with a constant of 164.  It also has a horizontal centered constraint and aspect ratio.  It also has a equal widths constraint with a multiplier of 88:320 to the superview.
Comment: @Brosef You first set proper constrain wAny | hAny? (because your print-screen have only wCompact and hRegular.
Comment: @Jageen I set the xib to be wCompact and hRegular because it is only in iphone portrait style.  Not sure if this answers your question.
Answer: Based on my recent experience, it appears that as of iOS 8.3, any images in the launch screen XIB have to be in the image assets. I do not know if this is the OP's problem or not, but definitely worth mentioning for other folks coming here with the same issue.
Comment: I'd like to think this is problem I'm having. But I put the image into Images.xcassets, and it is still not showing up - just as the OP describes it.
Comment: I had this problem in iOS 9 and this solved my problem.
Comment: @Sandy, is your image in the image assets? Can you view the image in your storyboard?
Comment: from assets it's showing but from launchimage it's not.
Comment: from assets it does, but from launchimage no.
Comment: I Use iOS 9.. images are there in assets... Still not seeing :(
Answer: This is happening because of the horizontal space constraints of the imageView, both the leading and trailing space to the superview. Here the launch screen is laid out in the wAny|hAny size class. It could not satisfy the Horizontal space -(196) on a smaller device. So what you can do

Remove the horizontal space constrains(both leading&trailing) of imageView
Add widthconstraint to the imageView or Aspect Ratio could be more appropriate
Other constraints looks fine, top & bottom spacing and centre horizontally in container keep as it is
Comment: Someone in the comments advised me to set the width and height, but I just set the aspect ratio thinking it would achieve the same result.  When I went back and set the width and height constraints it all worked.  However, the image isn't getting bigger when going from the 5 to 6 to 6+.  It just stays the same size.  How can I get it to grow with the size of the screen?
Comment: if you add the with&height constraints imageView remains same, it wont resize accordingly. Use the Aspect Ratio instead. So that when the height increases(it would happen automatically by the top & bottom space constraints) the with also get increased.
Comment: I removed the width and height constraints and replaced with the aspect ratio.  However, with width and height constraints gone, I'll have to implement leading and trailing again to satisfy the requirements.
Comment: I hope now u have.. top⊥ space, aspect ratio and horizontal centre in container constraints right?
Comment: I do, but the image is very large.  Even on the iphone 5 its very big.
Comment: Use image with proper resolution or you could fix the width. Dont know a proper solution


Matrix representation of PCA

Question: In both Wikipedia and this medium post, I see the succinct principle components decomposition of X represented as
$$T=XW$$
However, it seems to me that it should be $T = WX$ instead, if according to the Wikipedia page that columns of $W$ are the eigenvectors of $X^TX$ and $X$ is arranged as row vectors for each observation. In short, $X \in \mathbb{R}^{nxk}$, where $n$ is the number of observations and $k$ is the dimension of each data point, and $W \in \mathbb{R}^{nxn}$, so $XW$ does not even exist.
Am I getting the derivation somewhere wrong?
Comment: It depends on the orientation of you data matrix
Answer: Since the data samples have dimension $k$, the scatter matrix, $X^TX$ will be of dimension $k\times k$ leading to $k$ dimensional eigenvectors. So, $W$ is of dimension $k\times k$. With this correction, $T=XW$ indeed exists. You can also think of it as $$T=\underbrace{\begin{bmatrix}x_1^T\\x_2^T\\\vdots\\x_n^T\end{bmatrix}}_{X^T}\underbrace{\begin{bmatrix}w_1&\cdots&w_k\end{bmatrix}}_{W}=\begin{bmatrix}x_1^Tw_1&\cdots &x_1^Tw_k\\\vdots&\ddots&\vdots\\x_n^Tw_1&\cdots&x_n^Tw_k\end{bmatrix}$$
where $i$-th row of $T$ represents the projection of $i$-th data sample to the first $k$ (whatever it is) PCs.
Comment: Thanks! But could it be that the $x_1$ and $x_k$ in your answer are actually $w_1$ and $w_k$?
Comment: Yes, they are. I've edited.

Matrix representation of PCA


How to get the destination nid from an URL object

Question: In a preprocess function I want to access the destination node id via the URL object
I cannot find any method that will return the node id for me but I can clearly see that it holds the node id. (see attached)

Any idea how I can get the node id without going the long way of generating it from the URL path?
Comment: $your_url_object->getRouteParameters() should do it I think from memory
Answer: Looks like you're using the latest Devel, 4.0.1, which sadly currently doesn't show the available methods tab unless you patch it.
If you had the available methods tab, you would've seen that you can retrieve using the public method getRouteParameters
<code>$nid = $url_object->getRouteParameters()['node'];
</code>
Comment: hey thanks, that worked although just `['node']` at the end did the job just fine,
Comment: Also thanks for the patch, do you know why this has been removed in the newest version? It is pretty handy.


What is the rule on licensing and third party code?

Question: When you create a module that uses third party code, is there any instance in which it is "okay" to include it in the module as opposed to have the user download it themselves?
For instance, if you make a module that integrates a CKEditor plugin - I would think that you can't or rather, shouldn't put it into your module on drupal.org.
I see this here: https://www.drupal.org/node/422996
My gut tells me it is likely not good practice to bundle it up into your module.
Comment: You could ask for an explicit permission from the 3rd party code owner.
Comment: Are you asking about a module that you want to put on drupal.org or one that you are delivering in a different way?
Comment: Someone raised an issue saying I could 'put the ckeditor plugin' into the module because the plugin is GPL. Not that I want to do it, but wanted clarification.
Comment: @Kevin the main issue with doing that, and why it's not permitted is that if they release an update, you have to release an update. This makes for your code to become outdated quickly.  In change, if it's something outside of your project, and it doesn't change any interfaces, you don't have to modify your project and they can just update when they want the library.
Answer:
My gut tells me it is likely not good practice to bundle it up into your module.

You shouldn't. That page starts out with:

This is the policy for 3rd party code libraries in Drupal's contribution repositories.

In general 3rd party libraries and content are forbidden, so do not commit any. Instead, document for your users how to find and install the library/content themselves.

The other way is exceptions and they're clearly defined and you need to request approval.
Comment: Anyone may use GPL-compatible licensed code within GPL code, but this is against drupal.org's policy (except the whitelisted libraries) for contributed modules, themes and install profiles (distributions). If the person distributing the code does so outside of drupal.org, there is no licensing issue. However I think that it is a good idea to distribute dependencies separately in case another module does want to depend on the same library, and dependencies aren't duplicated on a site.
Comment: Yes, I agree. That's why I said it is "against drupal.org's policy (except the whitelisted libraries)". Not sure why the response to my comment? It is perfectly acceptable however to distribute code outside of drupal.org with GPL-compatible code in GPL licensed module.
Comment: If it's a library, even if GPLv2+ or GPLv2+ compatible, in order to get added, it needs an explicit exception. Here's the quote, from the same link that @Kevin posted, _Getting an exception needs explicit approval by Drupal Licensing Working Group (LWG). Exception requests should be posted in the LWG's issue queue with the component "Exception Request". (Upfront: 90% of all exception requests are moot. Only ask for an exception if it is really required.) _
Comment: Umm.. I have no idea what I read or what went through my head. You're totally right.
Comment: And further, you can have your git privileges on d.o revoked if you violate this policy: http://drupal.org/node/1001544


On a stringed instrument, should a note ring during a rest?

Question: In this example of Banjo tablature, what should happen with the B's and G's during the rests? Should they be allowed to ring during the rest, or should they be dampened in some way?

If they should just ring, why not have a note that extends across the whole thing? If it shouldn't ring, what's the correct way to dampen it?
EDIT
I should have also noted that Track 25 references a downloadable (with the code from Hal Leonard Banjo Method - Book 1: For 5-String Banjo) audio clip. In that clip, the player does allow it to ring.
Comment: Related: [Guitar notes: rest vs tie](https://music.stackexchange.com/questions/11910/guitar-notes-rest-vs-tie)
Answer: It should not ring. Sometimes silence is just as important or more important as the notes you play.
Listen to a song of any style and see if the instruments play the entire time. (Hint: they don't).
As far as how to silence the strings that depends on the instrument as well as the context of when the rest happens.
As a beginner I'd say use you picking or strumming hand to stop the string from ringing by placing it on the string.
Comment: This is incorrect.  ring or not ring depends entirely on the piece in question and the  mood or style the performer wishes to project.
Comment: @carlwitthoft based on the complexity of the piece and what I assume to be the OP's playing ability I would teach this player that rests are for silence. As the player improves and grows, yes, I agree there is room for interpretation.
Comment: @DonBranson  oops -- comcast long ago killed their personal web services.  One of these days I'll update to my box.com location.  In the meantime,  what job would you like to offer me?  :-)
Comment: As an analogy - consider use of the Sus pedal on a piano to extend notes into a rest. Again, performer's option -- tho' obviously not thru the entire rest.
Comment: @CarlWitthoft - Note the edit I just made to the original question. Care to add your own answer? Also, btw, the link to your resume (http://witthoft.com/resume) 404s for me.
Comment: @CarlWitthoft - given that a composer writes what he would like played, and rests are as valid as notes, if a musician is trying to faithfully follow what's written, shouldn't he adhere to the music? Unless it's an interpretation, which allows laisse faire anyway?
Comment: @CarlWitthoft - Heh. I was hoping a physicist such as yourself could offer some interesting coding challenges for me. :)
Answer: Just as the note tells you how long it should last, a rest tells you how long the silence is for. But that's the problem with a lot of tab. It doesn't actually tell you how long each note is. Ironically here it does say the rest is for one beat.
That's where real music scores (sic), and is added to good quality tab.
So, rests need to be 'played' in silence. To make that silence, mute the string after playing the previous note, by touching it gently with a finger, or palm, from either hand. Whichever is more convenient.
You're right - if the writer wanted that G or B to ring, he'd have written it as a minim (2 beat note). He didn't. Think of it like a trumpeter. Playing all those notes, but somewhere he has to breathe in for the next lot. That rest helps, and there's no sound while that happens!
Having said all that, there is plenty of guitar music - some very old, which has chordal playing but the chords are arpeggiated. Here, the notes are written out individually, and look like they need to each play for a specific short time. Do that, and the piece sounds stilted. What needs to happen is for each chord note to continue ringing. To write this on the stave gets to be, and look, complicated. So it's simplified. One has to listen to what's being played, and make a judgement. But for accuracy's sake, play any music exactly as writ.: that's (presumably) the way the composer wanted it. Rests and all.
Comment: Again, I disagree -- not only with guitars, but with any string instruments. the amount of hold or fade into a following rest depends on the piece of music in question .
Comment: @CarlWitthoft - quite happy for you to express your disagreement! However, the composer should have in mind how long each note - and each rest - will be. It's his baby! Interpretation is another thing. But with a tight band, it's important that each player keeps to an agreed timing on notes and rests, especially in intricate phrases.
Answer: A good guitar tablature would show a Let ring marker above the note (e.g. see  here). By the way, the tab you posted puzzles me a little, since it seems to keep  tablature and standard notation together, while they usually stands one over the other, as you can see here.
Comment: I've seen the tablatures where one stands over the other. Those are further on in the book, so I take it that they're starting with simple things and adding on as the student progresses.
Comment: Ok, so I guess they want you to silence at the pause (not ring).
Answer: Tablature is not as rigid as normal note notation; in particular whether a (typically bass) note should be left to ring is often left open.  One way of disambiguation is putting standard notation in parallel for reference.
For standalone tablature, a half note without other simultaneous notes would typically be notated by doubling the stem.  For an explicitly written rest, however, there is not much other interpretation than silence.  That silence will typically be achieved by inconspicuous dampening, letting the note end in an organic rather than sudden manner.


9-patch stretching when it shouldn't stretch, Android

Question: I am trying to set a 9-patch image as the background for one of my activities but it is stretching unescessarily making everything get all wierd.  I used draw9patch to create it and added one pixel to the bottom left and one pixel to the top right.  I then save it into my drawables directory as intro_bg.9.png.  I want to stretch the very bottom and stretch the far right side but only if it has too.  If it doesn't then I would like it to stay in tact.
When I set it as the background of the parent layout however it stretches it both horizontally and vertically and it doesn't even show my buttons when I run it on my droid.
I've done the Google searches but there is no good info on how to get something like this working.  What am I missing?
I have also tried some other configurations including using the padding sides(right and bottom) but that gave the same results.
Thanks
Code to set as background:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/intro_bg"
>

Looks like:

Should look like:
Comment: you should post 9patch image and maybe a screenshot, makes it easier to understand. and your relevant part of xml layout code.
Comment: What are dimensions of the image? I looks like it is just too big.
Comment: Origionaly .png that I made into the 9-patch is 475x845.  Is there a recommended size for this type of thing?
Comment: I went ahead and tried making the all of the image show up but its too small in the top left corner now and the buttons are still not showing up.
Answer: Your image is just too big to fit the layout. If you want it to be contracted you need to paint a line on the top and left borders -- the line marks region which will be contracted or stretched. I guess right now you have just dots on the borders.
Second option is to set the image as activity background, then it will be fitted in the screen. To do this add styles.xml to res/values folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

Then apply the theme to your activity at the manifest. The intro_bg drawable even doesn't need to be a 9-patch.
Comment: making it smaller didn't work.  How would I go about setting it as the background to my activity?
Comment: I didn't mention to make it smaller. Just draw longer lines on the top and left borders of nine-patch.
Comment: You were right about drawing the lines bigger.  Thanks for the help.


Investigate the behaviour of a function without computing its second derivative

Question: Let a function $f(x)$ be continuous over the interval $[0,\infty]$. For this function we have $f(0)=0$ and $f(a)=0$. Also we have $f(b)>0$, with $b<a$.
Suppose that the only zeros of $f'(x)$ are $x_1$ and $x_2$, where $0<x_1<b<a$ and $x_2>a$. If I am interested on studying the behaviour of $f(x)$ over $[0,a]$, can I claim that this function increases from $0$ to $x_1$ then decreases from  $x_1$ to $a$ ? or I need to compute the second derivative ?
Edit:
Note that $f'(b)<0$.
Comment: Do you (maybe) mean that the **only** zeros of $f'$ are at $x_1$ and $x_2$?
Comment: I think we have too little information about f(x) to make such claims.
Comment: It might be sufficient to compute the first derivative and study its' sign.
Comment: @PhoemueX  yes, exactly!
Comment: Please, consider this additional information: $f'(b)<0$
Comment: If you know that $x_1, x_2$ are the only zeroes of $f^\prime$ and also know that $f^\prime $ is, say, continous, then you can conclude what you proposed.
Comment: You only say that $f$ is continuous. Where does $f'$ exist?
Comment: $f'(x)$ is also continuous over $[0 , \infty]$.. Excuse me but I forgot to mention it..
Comment: @HagenvonEitzen  Thank you for helping me!! One last question (if possible):  An additional information is that $f(x)$ changes concavity at a point between $x_1$ and $a$. Now suppose I have a sum of 3 functions that have the same behaviour as $f(x)$ but with $x_{11}$, $x_{12}$ and $x_{13}$ as the points at which these functions reaches their maximum (all these points are $< a$). Can I claim that the resulting function has the same behaviour as these functions but with a maximum at $x^*$ ($<a$)?
Answer: Yes you can claim that the function is increasing from $0$ to $x_1$ and decreasing from $x_1$ to $a$ . For arriving at this conclusion, you must be sure that function has zeros only at $0$ and $a$ . And also, $f'(x)=0$ only at $x_1$ if $0\lt{x}\lt{a}$ . Here the condition $x\gt{a}$ is not needed.
Then using the fact that $f(b)\gt{0}$ you can find that the function is positive in $\left[0,a\right]$ and here, the extrema is at $x_1$ . And also $x_1\lt{b}$ and $f'(b)\lt{0}$ means it is decreasing.Therefore, it is evident that function is increasing from $0$ to $x_1$ and decreasing from $x_1$ to $a$


NodeJs With Mysql createPool and nodejs mysql wrapper module

Question: i am using nodejs with mysql createPool and node-mysql-wrapper.
Link:
https://www.npmjs.com/package/node-mysql-wrapper
There is no option in the documentation to implement with module with myslq create pool. I tried it, but its not working. Here is my code:
var connection = mysql.createPool({
            connectionLimit: 100,
            host: 'localhost',
            user: 'root',
            password: '',
            database: 'test'
        });

var db = wrapper.wrap(connection);

db.ready(function(){
    db.table("users").findById(8,function(user){
        console.log(user);
    });
});

Comment: `wrapper.wrap()` accepts a `connection` object not a `connectionPool`. You need to call `connection.getConnection(function(err, conn) { wrapper.wrap(conn); })`. See the example here https://github.com/mysqljs/mysql#pooling-connections
Answer: As @Tajen Shrestha said. You need bind the wrapper with connection object. For e.g.:
var conObj = connection.getConnection.bind(connection);

var db = wrapper.wrap(conObj);

db.ready(function(){
    db.table("users").findById(8,function(user){
        console.log(user);
    });
});

Comment: Unhandled rejection TypeError: Cannot read property 'database' of undefined


Extracting weights from a classifier's posterior distribution

Question: Given a classifier $C$ that gets text as an input and outputs a posterior distribution $p_1\dots p_n$ on $n$ possible topics.
In other words, for each user post, I have a list of probabilities $\{p_i\}$ that represent the chance that the user was writing about topic $i$.
I would like to calculate weights $w_i=f(p_i)$ such that the weight would be negative if the user is very not likely to write about a topic, and positive if the user is very likely to write about a topic.
What would be the standard way to do this transformation ?
Answer: You could use the Logit function as a start, i.e
$$ w_i = \log \left( \frac{p_i}{1-p_i}\right)$$
The weights will have a range of about $[-8, 8]$
Comment: I was thinking about using the `logit` but I quite alot of time $p_i$ is very close to zero, which causes the weights to explode to negative infinity


Limiting behavior of a martingale

Question: This is a homework question:
Suppose that $X_0=1$ and that for $n\geq 1$ $$X_n\sim  \left\{
  \begin{array}{l l}
    U(0,X_{n-1}) & \quad \text{with probability $1-X_{n-1}/2$}\\
    U(X_{n-1},1) & \quad \text{with probability $X_{n-1}/2$}
  \end{array} \right.$$ Determine the limiting behavior of $X_n$.
My attempt:
1) Check if this is a (sub/super)martingale
2) By the martingale convergence theorems, since it is bounded (below by 0, above by 1) this random variable must converge to something.
3) It can't possible converge to some value $x\in (0,1)$ since if $X_n=x$, then theres a high probability that $X_{n+1}$ is more than $\epsilon$ units away from $x$ for any $\epsilon>0$. So it should converge to either 0 or 1 (or both).
4) My guess is $X_n \overset{a.s.}{\longrightarrow} X\sim \text{bernoulli}(p=1/2)$.
A quick simulation however suggests that it converges almost surely to just 0!
<code>quiz5_number2 <- function(reps=1000, path=NULL){
  x0<-1
  path<-c(path,x0)
  for(i in 1:reps){
    y<-rbinom(1, size=1, prob= 1-x0/2)
    x1<- runif(1, min=0,max=x0)*y + runif(1, min=x0,max=1)*(1-y)
    x0<-x1
    path<-c(path,x0)
  }
  path
}
path<-quiz5_number2(100)
plot(path)
</code>

How would you answer this problem?
I realize the problem seems poorly worded. Blame my teacher :)
EDIT: On further analysis it is quite simple to see that while 0 is an 'absorbing' state (if you get to zero you will stay there), 1 is not an absorbing state (if you are at 1 you have 0.5 chance to be drawn from uniform(0,1) and 0.5 chance to stay). So I guess it makes a lot of sense that it converges to 0. Thank you for reading.
Comment: Where is $q$ in your code? Is that a typo?
Comment: What are you referring to? q? what is q? EDIT: AHH! yes that is a typo!
Comment: Apart from a full formal proof, I think I have figured it out that it does indeed converge almost surely to 0.
Comment: If $X_N=0$ for some $N\geq 1$, then by definition, $X_{N+1}=U(0,0)=0$ with probability 1 and $X_{N+1}=U(0,1)$ with probability 0. So zero is like an absorbing point. When the process hits that, it is gonna stay there forever!
Comment: Yes I came to that same conclusion awhile ago :) Thanks for the input!
Answer: You are correct in suggesting to use the martingale convergence theorem.
Let us compute $\mathbf{E}[X_n|X_{n-1}]$. A trite calculation shows that this equals
$$(1-X_{n-1}/2)\mathbf{E}[U(0,X_{n-1})|X_{n-1}]+(X_{n-1}/2)\mathbf{E}[U(X_{n-1},1)|X_{n-1}].$$
Computing the uniform expectations and then reducing, we find
$$\frac{X_{n-1}}{2}\cdot(3/2-X_{n-1}).$$
Since $X_{n-1}$ clearly lies between $0$ and $1$ for all $n$, the last quantity is positive, and in fact it is bounded by $(3/4)\cdot X_{n-1}$. Thus the sequence is a positive supermartingale. It converges almost surely, and it is clear that the limiting random variable must be positive almost surely and have zero expectation (just take the expectation in the above calculation to show that the expectation must decrease to zero exponentially):
$$\mathbf{E}X_n \le \left(\frac{3}{4}\right)^n.$$
So the limit is zero.
Comment: @ phils: This is self-study question (see the tags), you are not supposed to solve them, give some hints next time.
Comment: Ok. I will remember.

Limiting behavior of a martingale


Are there areas of mathematics (current or future) that cannot be formalized in set theory?

Question: I often read that ZFC can formalize "most" of everyday mathematics, but I could never find an example which it cannot. The closest I got is differential geometry (DF), where some article mentions that the translation from concepts of DF into set theory would render it almost "meaningless", in the sense that any intuitions one could have would be lost in the translation. So, if I didn't misunderstand, at least in theory, the translation could be done, so that a future AI machine could prove theorems of differential geometry using set theory. On the other hand, the Stanford Encyclopedia of  Philosophy states that "all of mathematics can be reduced to a formal system of set theory"(http://plato.stanford.edu/entries/set-theory/).
So, the questions are:

Is there any current area of mathematics that could be not formalized within set theory? If so, which ones? and
Is there any reason to think that every math of the future will be always formalizable in set theory? any references to read on the subject are welcomed!

Clarification: by set theory I am not restricting to ZFC, but to any flavor of it, including all additional axioms you want (about large cardinals or any kind)
Comment: Grothendieck topologies, which are used in algebraic geometry, require the existence of "large cardinals," an extension to ZFC.
Comment: IMHO, the translation of every (possible) area of mathematics into "formal set theory" (in which one is only allowed to talk about the $\in$ relationship and equality) renders it meaningless. This includes contemporary set theory itself!
Comment: @ThomasAndrews Both claims are false. It is perfectly possible to develop topos-theoretic cohomology within NBG, and with some work and care you can even do it directly in ZFC. Now, if you want to apply it to sites that algebraic geometers care about, however...
Comment: thanks, I will edit the question, I meant set theory of any flavor
Comment: Sorry, that should be cohomologies, not topologies. But the dependency is still there.
Comment: I don't really think that we need a tag for [foundations], but I am open for discussion. If someone disagrees, please start a meta thread on the topic.
Comment: sure I just wast sure what to chose as the third tag (although I am not sure if I still need to put at least 3, as when I was new)
Comment: According to what I read [at physics.SE](http://physics.stackexchange.com/questions/1894/path-integral-vs-measure-on-infinite-dimensional-space/1897#1897): "Currently, there is no satisfying mathematical formalization of the [path integral](https://en.wikipedia.org/wiki/Path_integral_formulation)." Personally, I do ont know about this area. But maybe someone else can tell you more about this.
Answer: First let me point out that set theory is a foundation to mathematics as much as electric current is the actual way a computer "thinks". You don't even have to go that far, you can go to the machine code itself.
Have you ever looked at a disassembled code? It takes a piece of code that was compiled from, perhaps, a high level language (such as C++, Visual Basic, C#, and so on), and it shows you what are the operations sent to the computer. It is very un-enlightening about the purpose of the original code, unless the original code itself was in assembly. But it still works.
In a similar way translating everything into the language of $\{\in\}$ and sets ends up in a very strange result, often allowing for insane type errors (e.g. $\{\langle 0,1\rangle\}\subseteq 4$). But the point of foundational set theory is not to have a sensible translation, but to have some sort of a consistent CPU where mathematics can be executed. In this aspect set theory allows us to turn everything into first-order logic theories, where we can apply completeness, incompleteness and deduction theorems on them.
Classic mathematics such as calculus, basic linear algebra, measure theory, classic functional analysis, those things can be easily modeled in $\sf{ZFC}$. Truth to be told, $\sf{ZFC}$ is a lot stronger than needed, and there are people nowadays working on using arithmetics (usually second-order arithmetics, or weakening of it) as the use of foundational theory.
However the more mathematics progressed into abstractions and infinite there were points that were not within the reach of "vanilla $\sf{ZFC}$". For example classes, classes of classes, a lot of category theory, etc.
While it is possible to switch from $\sf{ZFC}$ to $\sf{NBG}$, which is a conservative extension which allows classes, one turns into a two-sorted theory which is often slightly less convenient, but it to can only take you so far and not always enough. So Grothendieck suggested universes, which was a concept later used for the Tarski-Grothendieck set theory which itself is an extension of $\sf{ZFC}$. But large cardinals allow us to correct this situation as well. Large cardinals allow us to have frameworks much stronger than universes. In fact the TG set theory is equivalent to some large cardinal additions to $\sf{ZFC}$.
Speaking of large cardinals, we can go further, it has been suggested that there is a deep connection between some concepts in model categories and homotopy theory and large cardinals. I am not familiar with the details, but I had a couple of short chats with a few people who do, and it seems that in order to formalize some general notion of model category apparently you end up using a lot more than inaccessible cardinals (the words Vopenka principle come to mind). But that too is within the reach of $\sf{ZFC}$+suitable large cardinal axioms.
What cannot be formalized in set theory? Well. Nobody knows the future, I can only assert with certainty that at some point we die. Currently I believe that the way we think about mathematics is such that essentially everything can be turn into set theory. In particular $\sf{ZFC}$+axioms which have not yet been proven inconsistent with $\sf{ZFC}$.
But let us turn our heads, for a moment, to the other side of set theory. Algebraic set theory. The idea is not to put emphasis on elements and membership structure, but rather on functions between our sets. Such set theories like ETCS have been proposed as foundation for a lot of the mathematics in place of the classical $\sf{ZFC}$ foundations. There has been a lot of discussions over the topic a month ago after a paper called "Rethinking Set Theory" by Tom Leister was posted online. Taking part in those discussions I have learned two things that I have known before:

Whenever you take "concrete mathematics" (e.g. analysis, measure theory, etc) and turn it into set theory you will invariably lose some of the intuition.
Structural set theory while able to serve basis for $\sf{ZFC}$, make a crappy language to discuss a lot of the topics which do interest $\sf{ZFC}$ oriented set theorists. This is in a similar fashion of how $\sf{ZFC}$ make category theory cumbersome.

The discussions sort of faded out and died, but it seemed that they have went out with sort of a hint that type theory's day of the tentacle is nigh. In the form of Martin-Lof and SEAR/SEARC. But I don't know about that. I should stop. Thanks for reading.
Comment: @PyRulez: Is it the best? For one is disproves choice, as for the category of all categories, it might allow that, but it will probably behave very differently from what you'd expect. Just sit and write a formula for the category of all categories, and if you can stratify it, kudos. In any case, New Foundations is probably equiconsistent with Peano arithmetic. So just work with that, why don't you.
Comment: There seems to be some misunderstanding going on here. No large cardinals are needed to develop the theory of model categories; in fact the very purpose of model category theory is to get rid of the need for universes in the study of abstract homotopy theory. It is true that Vopěnka's principle has some applications in model category theory (as well as category-theoretic model theory, which is a completely different subject), but that's kind of like saying that large cardinals have applications in point-set topology.
Comment: @Zhen: Well to formalize in the syntactical sense you really just need something like PA. I read this as in the sense of "construct a model". And large cardinals *do* have applications in point-set topology.
Comment: There are plenty of interesting model categories that can be constructed in ordinary ZFC without the assistance of large cardinals. (Strange ones like StNaamen or whatever you're thinking of are probably not of interest to homotopy theorists.)
Comment: @ZhenLin: StNaamen is not a model category, it's Qtficiation, QtNaamen is. But it only requires to start with a set model of ZFC, not the inaccessible that Misha and Assaf suggests in their paper. They also have some problems there which they ignore (regarding what are the actual objects of StNaamen). I pointed these to Misha during my work with him the last fall. I should really get to write that blog post about this.
Comment: @Zhen: I tried to mitigate the offensive part of the text, anyway.
Comment: @AsafKaragila Thanks Asaf, I guess I should name you honorary mentor!
Comment: @julian: Oh, you won't get very far with this... :-) I'm just glad to help!
Comment: I have another question which I am not sure if it is really related to this one, so I'll post it as a separate question.
Comment: @julian: I was thinking about sleep, but I'm not really tired. So I'll stick around and see what you have to say. (Then possibly I will type a short monograph...)
Comment: please go sleep, no hurry, plus the next ones are more boring
Comment: @julian: I'm not a fan of sleeping anyway. But I can't say too many intelligible things on your new question anyway... :-)
Comment: Quine's New Foundations are the best. I have always wondered if it would allow a category of all categories containing an internal version of itself.
Comment: @AsafKaragila I guess I should say NFU. I will then (I'm not writing papers yet, but that probably will be one.)
Comment: @user170039: Other than progressing towards an Archaeologist badge, was there any actual point in this edit?


Images not showing in jQuery slideshow

Question: I am  creating a slide show image using HTML, php and jQuery, but the images do not appear. Ii do not know what the error is. I am new with the jQuery, and I know there must be some little mistake, but I do not know where to search and find it.
index.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery Slider</title>

Answer: Why don't you use the slider already created by the jQuery team?
http://jqueryui.com/slider/
Comment: first i want the image to slide by itself second i do not know how to make the images related to the slider that you talk me about it.
Comment: if you read into the documentation, you'll see that you can make the image slide by itself, however it doesn't sound like you're open to this solution, so I won't waste anymore of my time.
Answer: You should add a space character  between the selectors, you are selecting an element with class of slider and ID of 1.
$(".slider #1").show("fade",500);
       ---^

As IDs are unique, you can select the element using ID selector:
$('#1')...

Also note that numeric IDs are valid only in HTML5 documents. I recommend you to use a slideshow plugin like nivoSlider or Flexslider.
Comment: what you mean by adding space between selectors ??

Images not showing in jQuery slideshow


error function integration $\int_{0}^{\infty} \frac{x \operatorname{erf}(a x ) }{x^2+y^2} dx $

Question: I'm interested in the following integral,
$$
\int_{0}^{\infty} \frac{x \operatorname{erf}(a x ) }{x^2+y^2} dx
$$
where, $\operatorname{erf}$ is error function. Does the analytical solution exist to this integral?
Comment: As Per Mathematica the integral does not converge.!
Comment: Care to add some context?
Comment: Note that $\mathrm{erf}$ is bounded on the real line, whence the integrand behaves like $1/x$ for large positive $x$, i.e., the integral diverges.
Answer: Others have said the integral does not converge, so do not treat this as a converged solution. If we treat this formally only, take the Mellin transform of the integrand with respect to $a$ to a new parameter $s$ to get
$$
  -\frac{x^{1-s} \Gamma \left(\frac{s}{2}+\frac{1}{2}\right)}{\sqrt{\pi } s
    \left(x^2+y^2\right)}$$
if we integrate this with your range we get
$$
\text{ConditionalExpression}\left[-\frac{\sqrt{\pi }
    \left(\frac{1}{y^2}\right)^{s/2} \csc \left(\frac{\pi  s}{2}\right) \Gamma
    \left(\frac{s+1}{2}\right)}{2 s},(s-2) \arg \left(\frac{1}{y^2}\right)\geq
    -2 \pi \land \Re(s)<2\land \left(\Re\left(y^2\right)\geq 0\lor y^2\notin
    \mathbb{R}\right)\right]
$$
dropping the conditions (warning this might make everything invalid) gives
$$
-\frac{\sqrt{\pi } \left(\frac{1}{y^2}\right)^{s/2} \csc \left(\frac{\pi
    s}{2}\right) \Gamma \left(\frac{s+1}{2}\right)}{2 s}
$$
The inverse Mellin transform of this (from $s$ to $a$) gives an expression with hypergeometric function and digamma function, as well as erfi:
$$
 \frac{1}{2} \left(2 a^2 y^2 \, _2F_2\left(1,1;\frac{3}{2},2;a^2
    y^2\right)-\pi  \sqrt{\frac{1}{y^2}} y \;\text{erfi}(a y)+2 \log (a)-\log
    \left(\frac{1}{y^2}\right)-\psi ^{(0)}\left(\frac{1}{2}\right)\right)
$$
which might be a place to look for analytic continuation or formal solutions in terms of series etc.


Modelling small data set problem

Question: I have a small dataset (20 instances per 13 classes). The 13 classes are human users from their behavior features, I have to classify if an unseen behavior feature is of a user or not.
Data: These features are basically mouse events (x, y, timestamp) in a sequence upto 200 elements-long. And there is also an associated bi-gram key press time which has been binned into a range of 200 bins with 1 ms width. A user would have 20 events as <code>[[[x, y, time]...], [0,0,0,..,1,2,0,3,..]]</code>
Problem: I have tried several statistical techniques, and of all, SVMs with linear kernel are giving the best result, but the result is far from decent. I have trained an SVM per user, and the average false acceptance rate is only 25%, with false rejection rate around 7%.
I am not a seasoned data scientist and just breaking into the field, what are the ways I can go around improving the solution? (In terms of algorithms, technqiues to try) I have already tried K-means, Distance-based, random forests. Is my data too small to even capture the hypothesis? Can methods like one-shot learning be applied.
Background: I tried to create a heatmap of the mouse-movements, and there does seem to be patterns tied to users. Here are two plots for different users.

Here's a sample of the dataset
Answer: As you mention, your dataset is quite small. Personally I think that it is too small for exploring the implementation of a model, but trying a few things wouldn't hurt.
There is a python package called smote which helps in oversampling/undersampling. This method is mainly used when dealing with imbalanced datasets , but you could try implementing it and creating new artificial entries. You can check out the docs here: SMOTE and the paper, on which it is based here: SMOTE paper . Please bare in mind that by following this method and creating artificial instances you might alter the dataset so much that the initial information is lost thus resulting to a model which will not address your task properly. Also, a synthetic dataset means that you will probably have to deal with overfitting.
Moreover, since you have tried multiple models, you could combine them (model ensembling) and create a multiple model voting system. Sklearn has a method for this from the ensemble class Voting Classifier

Modelling small data set problem


Choosing the correct AUC value with RocR package

Question: I have somewhat of an odd question.
I'm currently working on a dataset and after training my model, I'm trying to get the correct AUC and I'm using the RocR package to get that value.
Im using these commands
  pred <- predict(model, testData,type='prob')
  pr=prediction(pred[,2],testData$var)
  prf <- performance(pr, measure = "tpr", x.measure = "fpr")

  auc <- performance(pr, measure = "auc")
  auc <- email@example.com[[1]]

I've noticed that whether I add the type='prob' changes the value of my auc, meaning that if i predict just the binary output instead of the probabilities, the AUC changes. So my question is which value should I use? I'm a bit lost.
Answer: What's your model? Note that predict is not a ROCR function, ROCR starts from prediction. It's your job to specify the model correctly. Of course, what the model generates have a significant impact on you AUC statistics, because you're comparing your prediction against testData$var. You'll need to think what exactly you want to predict. ROC is just a statistical tool, it's garbage in and garbage out, so make sure don't give garbage inputs.
What's testData$var? It's supposed to be the classified labels. Are they related to your binary or probability prediction (I don't know what model you're using)?
Note that you don't choose your AUC statistics, you choose your model that maximize AUC statistics as much as possible.


Ajax div update to insert JS for subsequent asynchronous request to external site

Question: I wanted to use the postscribe library (https://github.com/krux/postscribe) to make an asynchronous request to google trends, which would update a div with a graph without requiring a page reload.
Using the library on its own through a few methods (drupal_add_js or a custom block) works just fine, but I wish for the js code to be reloaded everytime the appropriate ajax callback is initiated.
$form['trends-visual'] = array(
  '#prefix' => '
',
  '#suffix' => '

',
  '#ajax' => array(
    'effect' => 'fade',
  ),
);

$form['trends-graph'] = array(
  '#prefix' => '
 '
',
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'trends_ajax_submit_callback',
  )
);

The callback
function trends_ajax_submit_callback($ajax, &$form, &$form_state)  {

 $form_state['rebuild'] = TRUE;
 $commands = array();
 $commands[] = ajax_command_html('#trends-visualization-container',
   '\');
         }
       }
      })(jQuery);</script>');

return array('#type' => 'ajax', '#commands' => $commands);

Triggering the Ajax with $form['submit'] results in the following JS error:
Uncaught SyntaxError: Unexpected token ILLEGAL

This is referencing my JS code, specifically this line:
postscribe('#trends-graph', '');

Hopefully this can be of use to someone!


How do I remove the legend, labels and all the numbers from the graphs from apex charts

Question:
I've tried everything I can. If anyone can help me out, it'll be great. I want the numbers on the graphs and the legend gone
Comment: how did you add border radius to the bar chart on top and bottom
Answer: Legend and data-labels can be disabled by
const options = {
  dataLabels: {
    enabled: false
  },
  legend: {
    show: false
  }
}

EDIT
If you want to remove all the additional graphics, try using sparkline which will only keep the chart and hide everything.
sparkline: {
  enabled: true
}

Comment: What about the numbers on the axes? How do I eliminate them?
Comment: Also, can I eliminate the weird +,-,search bar at the top
Comment: chart: {...
      sparkline: {
        enabled: true
      },
      toolbar: {
        show: false,
       },
    },
dataLabels: {
      enabled: false
    },
    legend: {
        show: false,
    },

 yaxis: {
        show: false,
    },
    xaxis: {
      show: false,
      labels: {
          show: false,
      },
      axisBorder: {
        show: false,
      },
      tooltip: {
          enabled: false,
      }
    },

https://github.com/moesaid/cleopatra/blob/406db65cf154df433fe4199e7fc36cd9a8f1a03d/src/js/charts/analytics_1.js
Answer: const options = {
  dataLabels: {
    enabled: false
  },
  legend: {
    show: false
  }
}


Sistema fica só em load - Tomcat 9 - Eclipse

Question:
O sistema carrega só a primeira tela, nenhuma outra pagina carrega, fica só no loading.
Obs:
Quando tento debugar o código, ele não chega no breakpoint.
Ao parar o servidor Tomcat, é retornado os seguintes erros:
<code>    WARNING: The web application [cq] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(Unknown Source)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
set 21, 2018 10:16:19 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
WARNING: The web application [cq] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation. Stack trace of request processing thread:[
 java.lang.Object.wait(Native Method)
 java.lang.Object.wait(Unknown Source)
 org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1118)
 org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
 org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
 org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
 org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
 org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87)
 org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112)
 org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:230)
 org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:237)
 org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
 org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
 org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)
 org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:45)
 org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:170)
 org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
 org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
 org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
 org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
 org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
 org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
 br.portoseguro.cq.controller.ControleQualidadeController$$EnhancerBySpringCGLIB$$2830b65f.inicio(<generated>)
 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 java.lang.reflect.Method.invoke(Unknown Source)
 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
 org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
 org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
 org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
 org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
 org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
 org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
 org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
 org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
 org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
 org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
 org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
 org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:412)
 org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
 org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
 org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1385)
 org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
 java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 java.lang.Thread.run(Unknown Source)]
set 21, 2018 10:16:19 AM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks
SEVERE: The web application [cq] created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Locale context]) and a value of type [org.springframework.web.servlet.DispatcherServlet$1] (value [org.springframework.web.servlet.DispatcherServlet$1@6265a548]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
set 21, 2018 10:16:19 AM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks
SEVERE: The web application [cq] created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Request attributes]) and a value of type [org.springframework.web.context.request.ServletRequestAttributes] (value [org.apache.catalina.connector.RequestFacade@2e51ede1]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
set 21, 2018 10:16:19 AM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-nio-8080"]
set 21, 2018 10:16:19 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: null
set 21, 2018 10:16:19 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot get a connection, general error
set 21, 2018 10:16:19 AM org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
INFO: Illegal access: this web application instance has been stopped already. Could not load [org.hibernate.internal.util.JdbcExceptionHelper]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [org.hibernate.internal.util.JdbcExceptionHelper]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1312)
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1300)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1159)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1121)
    at org.hibernate.dialect.MySQLDialect$3.convert(MySQLDialect.java:515)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:90)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:230)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:237)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
    at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
    at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)
    at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:45)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:170)
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at br.portoseguro.cq.controller.ControleQualidadeController$$EnhancerBySpringCGLIB$$2830b65f.inicio(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:412)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1385)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

set 21, 2018 10:16:19 AM org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
INFO: Illegal access: this web application instance has been stopped already. Could not load [org.hibernate.NonUniqueResultException]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [org.hibernate.NonUniqueResultException]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1312)
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1300)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1159)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1121)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1668)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1700)
    at org.hibernate.jpa.internal.TransactionImpl.begin(TransactionImpl.java:48)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:170)
    at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at br.portoseguro.cq.controller.ControleQualidadeController$$EnhancerBySpringCGLIB$$2830b65f.inicio(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:494)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
</code>
Comment: @KennedyAnderson apenas remova a biblioteca de drive da pasta WEB-INF/lib e também do classpath(como citou acima) e faça um teste e diga se o erro persiste ou muda.
Comment: Olá Kennedy. Somente com um print da tela há muito pouco que possa ser feito para te ajudar. Recomendo que você crie um [Exemplo Mínimo Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Comment: @AnthonyAccioly Obrigado pela orientação.

Fiz alguns testes e removi alguns cenários. Criei uma pagina fora do diretório "views" e o consegui chama-la.

dentro do diretório não esta conseguindo.
Comment: E não teve alterações no meu "spring-context".
Comment: @KennedyAnderson os dados de configuração do banco estão corretos? Parece alguma treta de conexão com o banco.
Comment: @adyjr, sim esta tudo certo =\
Comment: Você está migrando uma aplicação que rodava no tomcat 7 ou 8 para o tomcat 9? Isso pode ocorrer por conta da versão do Tomcat, ou versão do Java também.
Comment: @adyjr eu fiz a troca do 8 para 9 se não me engano, pois eram duas maquinas diferentes, e uma utilizava o 9 e outra o 8.
Comment: Mas esse mesmo sistema funcionava no tomcat 8, ou não?
Comment: @adyjr Sim, funcionava. Por algum motivo agora não funciona.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/83487/discussion-between-adyjr-and-kennedy-anderson).
Comment: @KennedyAnderson onde está sua biblioteca(drive) de conexão com o banco?
Na pasta lib do tomcat, ou dentro da aplicação?
Comment: @adyjr, desculpe não consigo acessar o chat aqui da empresa.

O drive antes estava dentro da pasta WEB-INF/lib, retirei e adicionei ao Tomcat (Run > Run Configurations > Classpath > "User Entries" + Add External JARs).

Mas o problema permanece.
Comment: @KennedyAnderson poderia verificar se existe outro driver do mesmo tipo que você está usando na pasta lib do tomcat?
Comment: @adyjr

Retorna um erro diferente, logo ao tentar subir o Tomcat..

SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring-context.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: cq_portoseguro] Unable to build Hibernate SessionFactory
Comment: @adyjr,  fiz alguns testes em classes, e este problema estava ocorrendo por conta de duas classes no projeto, removi elas e irei refazer.

Obrigado pela a ajuda!
Answer: Problema estava ocorrendo devido a problemas em classes DAO, Controller e Service.
Foram removidas e serão refeitas.
Comment: Especificamente na classe DAO, no construtor.


Strict warning: Only variables should be passed by reference

Question: I get the following error:

Strict warning: Only variables should be passed by reference in include() (line 18 of /home/sites/dev/theparce/sites/all/themes/parce/block--block--3.tpl.php).

This is the block code which is causing that error.
if ($user_gallery) {
  print render(node_show($user_gallery));  // Line 18
  print drupal_render ($user_gallery_edit);

}
else {
  print drupal_render($user_gallery_new);
}

Why do I get that error, even if I get all printed as expected?
Answer: That error happens when a function is expecting a reference as parameter, but it is not getting a reference.
In your case, render() is defined as render(&$element), but node_show() is defined as node_show($node, $message = FALSE), not &node_show($node, $message = FALSE).
The same would be true for drupal_render(), since the function is defined as drupal_render(&$elements).
As explained on Passing by Reference, when a function requires a reference parameter, you can pass to the function:

Variables (for example, a temporary variable containing the result of a function which is not returning a reference)

References returned from functions

Using other expressions, the result is undefined, and it depends from the PHP version.

render(node_show()) produces a fatal error in PHP 5.0.5, a strict standards notice in PHP 5.1.1, and a notice in PHP 7.0.0

render(5) produces a fatal error

render(new DateTime()) produces a notice in PHP 7.0.7 (Notice: Only variables should be passed by reference)


Integrability of two independent random variables

Question: Suppose that $X$ and $Y$ are two independent random variables.
How does one show that if $X+Y\in L^1$, then both $X$ and $Y$ are in $L^1$?
I know that one can approach this problem using the fact that the joint law of $X+Y$ is the convolution of the laws of $X$ and $Y$, but I would like to know   more "elementary" ways of proving the claim.
That is, how does one establish that
$$E[|X|: |X|>M] \to 0 $$ as $M \to \infty$?
Answer: Use the following law
$$\mathbb{E}(|Z|) \leq \sum_{n=0}^{\infty} \mathbb{P}(|Z| > n) \leq \mathbb{E}(|Z|) + 1$$
which is known as layered representation of expectation. From assumption $X+Y$ is in $L^1$, we have
$$\sum_{n=0}^{\infty} \mathbb{P}(|X+Y| > n) \leq \mathbb{E}(|X+Y|) + 1 < \infty$$
Then note that
\begin{align*}
\mathbb{P}(|X+Y| > n) &\geq \mathbb{P}(|X| - |Y| > n)\\
&\geq \mathbb{P}(|X| > n + m \text{ and } |Y| < m)\\
&\geq \mathbb{P}(|X| > n + m) \cdot \mathbb{P}(|Y| < m) &\text{by independence}
\end{align*}
for any $m$. Choose $m$ sufficiently large so that $\mathbb{P}(|Y| < m) > 0$ (such $m$ must exists for $\lim_{m \rightarrow \infty} \mathbb{P}(|Y| < m) = 1$) so that we can bound the tail sum
$$\sum_{k \geq m} \mathbb{P}(|X| > k) = \sum_{n \geq 0} \mathbb{P}(|X| > n + m) \leq \frac{\sum_{n=0}^{\infty} \mathbb{P}(|X+Y| > n)}{\mathbb{P}(|Y| < m)} < \infty$$
This shows that
$$\sum_{k \geq 0} \mathbb{P}(|X| > k) < \infty$$
and so by the layered representation inequality,
$$\mathbb{E}(|X|) \leq \sum_{n=0}^{\infty} \mathbb{P}(|X| > n) < \infty$$
hence $X$ is in $L^1$. Likewise for $Y$.
Answer: Suppose that the positive part $X_+$ of $X$ is not integrable. So
$$
\sum 2^n P(2^n\le X_+<2^{n+1})=\infty  \quad\quad\quad\quad (1)
$$
Let's take $M>0$ so large that $P(|Y|\le M)\ge 1/2$. Let me write $A_n$ for the events from (1). Since $X,Y$ are independent, the probability that $A_n$ happens and at the same time $|Y|\le M$ is $\ge (1/2)P(A_n)$. This implies that $E(X+Y)_+=\infty$, by focusing on the contribution coming from those sets.
This contradicts our assumption that $X+Y\in L^1$.
Comment: Monotone convergence.
Comment: A random variable is a measurable function $Y:\Omega\to\mathbb R$.
Comment: How do you know that there is a large enough $M$ such that $P(|Y| \leq M) \geq 1/2$?
Comment: In order to obtain such M by monotone convergence, I guess that I would need to have  $P(|Y| < \infty) = 1$. Wouldn't I? But, it is not clear to me how the fact that $Y$ is finite almost surely follows from that of $X+Y$