User password valid only for one day

Question: When users forget their password they click on the reset password link. There, they enter their username, or password, and a mail goes to their inbox, instructing them on what to do.
The instructions say to follow a link that resets the password, and then redirects them to their user profile to enter a new password. Although they enter a new password, the next day (and everyday) the system doesn't recognize the password, and they have to reset it again.
Why does this happen?
How does the "reset password" work? Does it check the access date to see if the day has changed, or does it use some kind of flag to let the system know the password is valid only for one day?
Comment: Yes, similar issue here. What Drupal version you using? Modules related to authentication?
Comment: @Caleb The problem for me had to do with the registration text sent with mail to users been registered. The text included three links. The first link was the login page. The second link was the reset link (when you forget your password and ask for a new one this is the page with this functionality). The problem was that the default text was asking the user to click the second link to login automatically thus making the user reset their password before even using it. Anyway if you have access to your database you can make tests by changing manually the registration time (unix timestamp).
Comment: Would you mind reformatting that comment as an answer to this question? This could help future visitors with the same problem (mine is a little different, but I couldn't tell that except by seeing your solution).
Comment: @Caleb i tried to explain more but i don't know if i made it clearer.
Answer: Finally the problem in my case had to do with the text that was sent with mail after user registration. When user was registered a mail was sent in his inbox with his username and a (system created) password. Then the text was providing a link to the login page, a second one linking to the auto log in page (where the user supposedly would not have to enter his password) and a third one that it is irrelevant.
So i realized that the second link was actually a link to reset your password if you forget the old one. So the user when first reading the mail he click on the second link to log in automatically but he doesn't know that the password given to him was reseted and now his log in was valid only for one day or for one use. Each time he has to reset his password.
Anyway if you have access to your database you can experiment to see if it is another issue for you. You can create a fake account in drupal. In the mail that is sent to you click the second link (something like http://mysite.com/foo/user/reset/1085/1349294892/7bc9baf9d42aa774be00a0f36090323f). Then go to table 'user' of the drupal database, find the fake user you created and modify the record of the column 'created'  and put a unix-timestamp older than a day (there are online unix-timestamp creator). This way you can experiment if the password is temporary or not.

User password valid only for one day


Returning a value from a finally block

Question: I found this piece of code in a java certification website
   public class Test1{
        public static void main(String args[]){
            System.out.println(method());
        }
        public static int method(){
           try{
              return 1;
           }
           catch(Exception e){
              return 2;
           }
           finally{
              return 3;
           }
        }
    }

So the output of this piece of code is shown as 3.
How is this possible..since it is returning 1 in the try block itself?
The code will never reach finally right??
Comment: A `finally` block will _always_ be executed; but `return`ing in `finally` is... Uh. Basically, that's a "don't do that" thing
Comment: You haven't tried to read something about the behaviour of a `finally` block, right? For example this: https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Comment: Also, related, and a good read if you're actually considering structuring your code this way for some reason: https://stackoverflow.com/questions/48088/returning-from-a-finally-block-in-java?rq=1
Comment: @fge explained pretty well
Answer: The code will never reach finally right?
No, If there is a finally block control will go to finally after try or/and catch
Because in any case finally will always execute. Except as Mike Kobit said  System.exit
Thanks  Jason C,  From JLS 14.17. The return Statement

It can be seen, then, that a return statement always completes abruptly.
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the method or constructor whose try blocks or catch clauses contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

From JLS 14.20.2. Execution of try-finally and try-catch-finally

If execution of the try block completes normally, then the finally block is executed, and then there is a choice:

If the finally block completes normally, then the try statement completes normally.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.

So In you code try returns 1, then control goes to finally which returns 3. so return value of function will be 3.
Comment: Well, nearly always. [*Certain* cases](http://stackoverflow.com/questions/12430642/what-are-the-circumstances-under-which-a-finally-block-will-not-execute) (like `System.exit`) it will not.
Comment: @TimBiegeleisen no, if you are returning something from finally too.
Comment: But then is it possible to `return` a value from the `try` block?  It seems like the answer is no.
Comment: To which place in the call stack does the `try` block `return` the value 1?
Comment: @TimBiegeleisen See the JLS for more details.
Comment: @SumitSingh This is a good answer although the piece of the JLS you quoted is incomplete. For completeness, add the foot note of 14.17, in particular, *"It can be seen, then, that a return statement always completes abruptly."* ties the behavior together by relating "completes abruptly" to "return". Also the part, *"... Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement."*
Answer: As Sumit Singh mentioned in his answer, this happens because return causes the method to end abruptly.
You can observe the same behaviour, when you throw new Exceptions inside your try-catch-finally block, since throw is also abrupt.
See the following code:
public class FinallyTest {
    public static void main(String[] args) {
        abrupt();
    }

    @SuppressWarnings("finally")
    public static void abrupt() {
        try {
            throw new IllegalArgumentException("In Try");
        }
        catch(Exception x) {
            throw new IllegalArgumentException("In Catch");
        }
        finally {
            throw new NullPointerException("In Finally");
        }
    }
}

When running the code, the console shows
Exception in thread "main" java.lang.NullPointerException: In Finally
at FinallyTest.abrupt(FinallyTest.java:15)
at FinallyTest.main(FinallyTest.java:3)

Even though you throw a new IllegalArgumentException inside the try block, only the NullPointerException from the finally block is thrown, since this block ended abruptly.
Answer: Finally block will always get executed just before return statement get executed. (There are some exceptions like JVM itself crash or system.exit() is called)
Here is the reason:
We normally use finally to free up our resources or to cleanup. Now if developer will write return statement accidentally in try block then logically finally would never get executed. To overcome this problem, JVM by itself handle this scenario and execute finally block just before returning from try block.
Remember the finally block always executes when the try block exits. And above explained scenario is also applied to return, continue, or break.
Answer: Because if we think about priority finally has more than try or catch, to make it clear what if the exception haven't caught even then the finally executes and here it is working inside a method so logically when a method is suppose to return a single output int value then obviously it will always return values from finally.
Is it makes sense?
Comment: But since in the try block, it is returning a value, why would it still go and execute finally?
Comment: @AqeelSmith Because that's the very point of `finally`: to be finally executed whatever happens. It normally is used for cleanung up, such as `.close()`ing stuff.
Comment: I am still not very clear about this!
Comment: As just not be very technical just for your understanding purpose, remember
priorities  `finally` has more than `try` or `catch`
so finally wins the race in any case whether try works or catch

Returning a value from a finally block


C: use fwrite to write char to different line

Question: I have to write to a file as follows:
 A
 B
 C
 D
 ...

Each character of the alphabet needs to be written to different line in the file. I have the following program which writes characters one after another:
 FILE* fp;
 fp = fopen("file1","a+");
 int i;
 char ch= 'A';
 for(i=0; i<26; i++){
     fwrite(&ch, sizeof(char), 1, fp);
     ch++;
 }
 fclose(fp);

How should I change the above program to write each character to a new line. (I tried writing "\n" after each character, but when I view the file using VI editor or ghex tool, I see extra characters; I am looking for a way so that vi editor will show file exactly as shown above).
I tried using the following after first fwrite:
 fwrite("\n", sizeof("\n"), 1, fp);

Thanks.
Comment: Could you show the modified code that writes `\n`s? Was it something like `fwrite("\n", sizeof(char), 1, fp);`?..
Comment: By writing "\n" after each character, did you do another fwrite or something else?
Comment: Is there some reason that you need to use fwrite? fwrite is intended for binary data, and to write text you usually use fprintf and putc.
Answer: fwrite("\n", sizeof("\n"), 1, fp);

should be
fwrite("\n", sizeof(char), 1, fp);

Otherwise, you are writing an extra \0 that is part of zero-termination of your "\n" string constant (sizeof("\n") is two, not one).
Answer: What "extra characters" do you see? You do realize that the "a+" parameter to fopen opens the file for appending, so that you're writing to the end of the file. Did you perhaps mean "w+", which will overwrite the file?
You could use:
fputc((int)ch, fp);
fputc((int)'\n', fp);

Or even fprintf(fp, "%c\n", ch);


Question about definition of inner product space

Question: While practising I came across the following easy question:
"Is the space $B(0,1):=\{f:[0,1]\rightarrow\mathbb{R}$ bounded$\}$ an inner product space?"
But I'm not quite sure what the correct answer is here. As far as I can tell this is not even a space but just a set. No operations or inner products are defined on it, so it does not have any structure. To me this seems like asking
"Is the space $\{a,b,c\}$ an inner product space?"
Which without any further information seems like it's a strange question.
So my question is:

Why do they even call this a space while the specification is just a set?
What is the correct answer here?
Answer: You can easily see that the set $B(0,1)$ is closed under scalar multiplication, and $+ , \times $. So it's a Banach space (with the sup norm) and also an algebra.
Put inner product $\langle f,g\rangle = \int f(x)\bar g(x) dx$, $B(0,1)$ is an inner product but not But  a Hilbert space, because it's not complete.
Comment: I should mention that there is at least *some* subtlety here. For instance, the space $B(0,1)$ is often given the sup norm $||f||_{\infty} = \max_{x\in[0,1]} |f(x)|$, and in this context, the question "is $B(0,1)$ an inner product space" might mean "does $B(0,1)$ admit an inner product giving rise to the norm $||\cdot ||_{\infty}$". The problem is that there are many natural norms on $B(0,1)$, so it usually is good to specify which one is meant, and you're right to complain that this question doesn't.
Comment: The vector space structure on $B(0,1)$ is implied by the use of the word "space". It's like saying "the group $\mathbb{Z}$". I didn't tell you what the group operation is, but of course you know what I mean; it's too cumbersome to say things like "the group $(\mathbb{Z}, +)$" all the time. The meaning of "Is $X$ an inner product space" is exactly "Does $X$ admit an inner product".
Comment: I know all this, but this doesn't answer my question.
Comment: @mollyerin Oke thanks, that's more along the line of what I was looking for
Comment: @mollyerin  Thanks again, that was even more along the lines of what I was looking for.
Comment: It's a good answer, but a further subtlety should be noted.  In order to have an inner product we need "coercivity", i.e. the inner product of a vector with itself is zero only when the vector is zero.  This is not true here since *bounded* functions need not be continuous.


Webform submissions to 3rd party API with Refresher Authentication token

Question: How can you send the submitted information in a webform to a 3rd party API?
I have read this: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-programmatically-create-and-update-a-submission
But it looks this recipe is more about updating a submission rather that doing requests.
Any help?
Note:
I realized I can use handlers for submission, but need to use a refresh authentication token for submission. Are there any hooks for that?
I'm looking for hooks grab the data submitted from a specific form, then creates a POST request to create an access code and finally makes a POST request for a 3rd party API.
Using Zoho CRM API
Comment: You are going to want to write your own webform handler in a custom module.
Comment: @RyanHartman I thought this will be the case.
Answer: I have found this article creating a extension of a post handler to target specific webforms on submission.
https://www.chapterthree.com/blog/drupal-8-how-to-extending-a-webform-remote-post-handler
Code: https://github.com/chapter-three/drupal-hook-webform-handler-invoke-alter-example/blob/master/snippet.php
This is a very hard-coded solution, so I might think this might be a good idea to create a contrib module to extend the post request handler with multiple submissions.


Constructing a bijection between $(0,1)$ and $[0,1]$.

Question: I am trying to prove the proposition indicated in the title. Will it work if i define $h:(0,1)\to[0,1]$ as follows
$$h(x) = \begin{cases}x\text{ if }x\in(0,\frac{1}{4})\cup(\frac{1}{2},\frac{1}{4})\cup(\frac{1}{2},1)\\0\text{ if }x = \frac{1}{4}\\1\text{ if }x = \frac{1}{2}\end{cases}$$
Comment: No. You have no $x\in(0,1)$ with $h(x)=\frac12$
Comment: Man, I gave you a function that gives you a very similar bijection. Use a technique similar.
Answer: Hint: The following trick goes half the way, namely gives a bijection $(0,1)\to (0,1]$:
$$h(x)=\begin{cases}\frac1{\frac1x-1}&\text{if }\frac1x\in\Bbb N\\x&\text{otherwise}\end{cases} $$


Document management system: what to use as storage backend (docs content repository)?

Question: I want to make a document management system (interface in Ruby).
What do profesional sollutions (Alfresco, Liferay social office, others) use for storing and versioning documents?
What else can I use?
Key points:

storage space optimization (deltas, compression ...)
versioning
ability to index docs (can be external)
ability to make backups at runtime (live hot-backup)
locking?
scalability on large data volume
ensure data integrity (hashing?)
permissions
transactional
Workflow support (optional)

Bonus points:

how does KnowledgeTree do it?
how does Liferay Social Office do it (jcr?) ?
how does Alfresco do it ?

Any books on this issue ?
Answer: Most of the enterprise document management solutions I've seen (Cimage, Documentum, LiveLink) definitely don't care about #1.  Storage is relatively cheap, especially if it's storage vs processing (store and retreieve).  They mostly rely on filesystem based storage - perhaps with name abstraction such that ShoppingList.doc perhaps becomes 20100909100101a.doc.rev1, with a database tracking the given-name, the stored name, revisions, and various other data {MIME type, headers & properties etc}.  By not generating deltas + compression you get indexing very easily from any number of existing products/agorithms.  Versioning is also extremely simple with this approach.
Depending on the size and scale you're building, you could also store versioned files within a database.
An (S)FTP or CIFS storage process would also allow your software to run on an app server with modest space, but store the files+history on a file or cloud server of some sort - although this isn't much different from filesystem based storage.
Answer: Y'know, my first instinct would be to just use Subversion. You'll need external indexing, and if you want to store hashes you'll need to write some code to do it yourself, but everything else fits.
It ships with ruby bindings, though I'm not personally familiar with their quality.
Comment: When I'll have TBytes of docs I'll need some sort of distributed storage and SVN won't work.
Comment: @clyfe: Distributed storage is a whole different ballgame from what you're asking for. None of the systems you mentioned use distributed storage, and I can't imagine why you'd need it unless your traffic is ridiculously high. A good server with a bunch of 2TB disks in RAID 10 should do you just fine.
Answer: alfresco is commonly used as the backend, it has a nice REST API. You can also define your own integration API if you don't like the included one.
Comment: Any usable docs or books? All tough I like the features, their wiki really kills my tiny ruby brain. I'm mostly interesting in how to define users, ACL's and read/write content, maybe define workflows ...


Swiper js append and prepend not working with multiple instances

Question: I have created multiple swiper carousels on the page with the code below. Everything works except the append and prepend slide if i remove the code the everything works fine
 $('.swiper-container').each(function() {
    var cggoSwiper = new Swiper( $(this) , {
      //swiper paramenters here
    });
      cggoSwiper.appendSlide(cggowlContentAfterSlider);
      cggoSwiper.prependSlide(cggowlContentBeforeSlider);
    });

Please help
Comment: What is the value of `cggowlContentAfterSlider`? As per official documentation you need to add HTML content in `appendSlide` method. Please go through https://idangero.us/swiper/api/#methods
Comment: @DhananjayKyada it's HTML only
Comment: You should specify a unique reference for `cggoSwiper` variable. Because in `each` loop it will be overwritten every time.
Comment: @DhananjayKyada i am new to javascript. Will be really helpful if you could show me some reference
Answer: You should get the reference from the following code:

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

Slide 6

Slide 7

Slide 8

Slide 9

Slide 10


React-admin ImageInput / FileInput multiple upload

Question: I have a problem while using  or FileInput in react-admin.
I used multiple= false OR didn't use multiple
<ImageInput
    source="picture"
    multiple={false}
</ImageInput>

And i checked picture and got
picture: {
   rawFile: "....",
   url: "...",
   title: "..."
}

But I used multiple=true and upload many images
<ImageInput
   source="picture"
   multiple={true}
</ImageInput>

after thet, checked picture and got
picture: [
   0: {url: "...", title: "..."},
   1: {url: "...", title: "..."},
   0: {url: "...", title: "..."}
]

I need rawFile in every Json object of picture but I don't see them
Please help me
Answer: Hi did you try with the <ImageField/> compoenent as provided in the doc ?
https://marmelab.com/react-admin/Inputs.html#imageinput
If it doesn't work maybe try to change the save button compoenent and write you own:
https://marmelab.com/react-admin/CreateEdit.html#using-onsave-to-alter-the-form-submission-behavior
I usualy write my imge component like that and it work like a charm:
<ImageInput {...props} accept="image/*" source="image" multiple={true} >
   <ImageField source="src" title="title"/>
</ImageInput>


Maximum of two (or more) gaussian distributions with known and possibly different means/variances

Question: I am a software engineer by trade doing stats in my free time.  I am playing around with an implementation of Microsoft's TrueSkill rating system for ranking players and openings in from a data set of ~700,000 Dominion games.  I want to measure the log loss of predictions that the system gives for multiplayer games so that I can optimize hyperparameters of the system as well as explicitly model the inherent turn order advantage in the game.
In general, the TrueSkill builds a Bayesian Graphical Model, assuming a normal distribution on player skills as well as a normal distribution for player luck per game, and produces a mean/variance for the independent performance of players.  For a two player game, the probability of one beating the other is encoded in the difference of the performance distributions.
However, predicting the probability of a player winning a 3 player game seems to requires estimating the probability that given player will exceed the maximum performance of the other two players.  Is the maximum of two Gaussian also Gaussian?
I've read these notes which seem to solve a more general version of problem that I want on page 27 with equation (8-47).
Basically it says that for random variables X and Y, then if
$Z = \max(X, Y)$
With X and Y independent,
(1) $F_z(z) = F_x(x) F_y(y)$
and hence
(2) $f_z(z) = F_x(z)f_y(z) + f_x(z)F_y(z)$
Should I then plug in the formulas for the cdf/pdfs and pray that I get something useful?
Answer: The answer to this is basically "Yes". The formulae for the cdf/pdfs won't simplify very far (which seems to be what you're "praying" for). Further discussion is given in the following paper, in which they also consider the case when the gaussians are correlated:
Exact Distribution of the Max/Min of Two Gaussian Random Variables by Nadarajah, S. and Kotz, S. (2008).


Importar classes java para um projeto de forma automática?

Question: Gostaria de saber se existe alguma forma de importar, de forma automática, classes java vindas de um dado diretório local para o meu projeto atual. Por exemplo: Digamos que quando eu aperte um botão "Importar" na minha aplicação, todas as classes java que se encontrarem em "c:/minha pasta/minhas_classes" serão importadas para o meu projeto. Existe alguma forma de fazer isso?
Especificando: Eu estou tentando construir um sistema onde iniciantes de programação enviam sua classe java e o sistema avalia esse código. A princípio essa avaliação seria apenas através de simples casos de teste nas classes que são submetidas no sistema. Mas mesmo assim, para execução de um caso de teste, é preciso ter a classe importada para um projeto. Este é o porque de eu estar procurando uma forma de importar automaticamente Tendo uma pasta específica no servidor onde ficariam as classes que os alunos submetem, se existir uma forma de importar todas para um projeto de forma automática, eu conseguiria realizar o caso de teste em todas elas assim que fossem submetidas.
Comment: São perguntas diferentes. Pode parecer sem sentido, mas é exatamente isso que estou precisando para construir meu sistema. Isso dará resultados a um sistema de avaliação de classes que estou construindo para ajudar alunos iniciantes em programação. É um projeto da minha faculdade
Comment: Eu pensei que já tinha ficado bem claro. Bom, fiz uma correção detalhando mais. Obrigado pela sugestão
Comment: Importar em tempo de execução?? Não faz sentido algum isso pra mim.
Comment: Não está muito claro o que você quer importar e nem como, seria interessante detalhar melhor isso que você falou nos comenta rios no corpo da pergunta, até para que fique mais objetivo o que você precisa.
Answer: Amigo você pode usar o pacote
com.sun.tools.javac do JDK para compilar um bloco de código em tempo de execução, ou seja seu código em java compilando outro código em java durante a execução.
Um exemplo:
int errorCode = com.sun.tools.javac.Main.compile(new String[] {
        "-classpath", "bin",
        "-d", "/temp/dynacode_classes",
        "dynacode/sample/PostmanImpl.java" });

Mas detalhes de como isso funciona, você pode seguir esse link:
http://www.javaworld.com/article/2071777/design-patterns/add-dynamic-java-code-to-your-application.html
Espero que tenha ajudado.


Custom 404 page in a theme doesn't work as expected,

Question: I want to use a custom 404 page, I also have a theme installed.
This is what I did:

Go to Content, create a Node, I got path: node/28
Go to System->Site Information->Error Pages-> 404 page, I enter node/28

Then I type some pages that are not exists, it doesn't link me to the node/28, instead, it still use the themes' 404 page.
Some hint here?
BTW, I am using Drupal 7 and the theme called MD magnum.
Comment: Did you try clearning cache? If not use drush to do so: drush cc all
Comment: does your theme already have an error page template?
Comment: @CR47  Hi,thanks, I clear the cache, and it works, but not correctly, the themes' 404 page overlap with my node/28. I only want to show my own 404 page, so what should I do to disable the themes' 404 page?
Comment: @jdu Hi,thanks, I clear the cache, and it works, but not correctly, the themes' 404 page overlap with my node/28. I only want to show my own 404 page, so what should I do to disable the themes' 404 page?
Answer: Do what @jdu said and check the theme's template files for an error page template.  It will probably have the name page--error.tpl.php and probably be in /sites/all/themes/md_magnum/templates/
After that set your new error page URL in admin/config/site-information to the node you created.
To verify it is set you can check in your database under the variables table for site_404 to be set to that URL.
Make sure after you make these changes you clear cache completely and refresh your page.  If you are in Chrome, you may have to clear browser cache as well if you are using the same URL.


Which function is larger as $n$ gets very large?

Question: Which function is larger as $n$ gets larger, $f(n)=2^{2^{2^n}}$ or $g(n)=256^{256^n}$?
I understand that logarithms would be useful for answering this question, and that indeed one could write $g(n)$ in a similar form to $f(x)$ and then compare. However, I am struggling to actually complete any of these approaches. Namely, I am struggling firstly in computing logs and logs and logs, etc, and also in writing $g(x)$ in a similar way to $f(x)$.
In your answers could you please help me by showing the stages :)
Answer: We work with logarithms to base $2$. So $\log f(n) = 2^{2^{n}}\log 2 = 2^{2^{n}}$.
Repeat: $\log \log f(n) = 2^n \log 2=2^n$.
But $\log g(n) = 256^n \log 256 = 8 \cdot 256^n$ so $\log \log g(n) = \log 8 + n \log  256 = 8n + 3$.
Since eventually it's obvious we have $2^n > 8n + 3$ (if not, use induction) then $\log \log f(n) > \log \log g(n)$ and since $\log$ is strictly increasing we have $f(n) > g(n)$ for sufficiently large $n$.

Alternatively (well, really the same thing written differently), note that $256 = 2^8$ so $$g(n) = \left(2^{8}\right)^{2^{8n}}=2^{2^{8n+3}} < 2^{2^{2^n}}$$ when $2^n > 8n+3.$
Comment: Thank you. This was helpful. Could one then say, if you compare these exponents' rate of change, that d/dx (2^n) > d/dx 8n+3?
Comment: Well, first off I think you mean $\frac{d}{dn}(2^n) > \frac{d}{dn}(8n+3)$ and secondly, no - not really. $n$ is a discrete variable, taking derivatives makes no sense. Even if it were a continuous case, normally taking derivatives isn't enough to determine comparison of growth. Instead, there's an easy induction to show that $2^n > 8n+3$. Can you do it?
Answer: Logarithms are not necessary here. Rewrite the second expression as
$$256^{256^n}=\bigl(2^8\bigr)^{2^{8n}}=2^{2^3\cdot2^{8n}}=2^{2^{8n+3}},$$
and you can check $2^{2^n}>2^{8n+3}$, which amounts to $2^n>8n+3$ for all $n\ge 6$ by induction.


Set values at the end of the bar

Question: import os
import numpy as np
import matplotlib.pyplot as plt

x = ['Buildings', 'Forest', 'Glaciar', 'Moutain', 'Sea', 'Street']
y = [33.41, 90.72, 37.79, 60.95, 51.76, 59.88]

x_pos = [i for i, _ in enumerate(x)]

for i, v in enumerate(y):
    y.text(v + 3, va='center', str(y), color='blue', fontweight='bold')

plt.barh(x_pos, y)

plt.ylabel("Cenários")
plt.xlabel("Percentagem de acerto %")
plt.title("Taxa de Reconhecimento")

plt.yticks(x_pos, x)

plt.show()

So im new to python, but i want to place does y values at the end of each bar
I found come solutions but any of them working, can someone help me pls? thnx
Comment: have a look on here https://matplotlib.org/3.1.0/gallery/pyplots/fig_axes_labels_simple.html
Comment: Does this answer your question? [How to display the value of the bar on each bar with pyplot.barh()?](https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh)
Answer: You need to use the x and y position and plt.text
plt.barh(x_pos, y)

for i, v in enumerate(y):
    plt.text(v + 3,  i, v, va='center', color='blue', fontweight='bold')

Comment: Yes it does, I was able to make it functional with you tip
Comment: Thank you very much Sheldore

Set values at the end of the bar


Duvida com o fatiamento com número negativo

Question: Galera, como funciona o fatiamento de string com número negativo no python? Ele vem fatiando subtraindo dos índices?
nome = 'Fernando'
print(nome[::-2])
'onne'
eu vi que ele veio tirando a partir do índice 7 2 em 2 números. é assim que funciona mesmo ou eu estou equivocado?
Answer: Não esta "subtraindo", ele esta "pulando", no "slice" funciona assim:
[start:stop:steps]

No seu exemplo você passou o valor de steps e omitiu os valores de start e stop, esses dois que são usados para "aparar" a str, nesse caso então você irá apenas "pular" certos caracteres.
Se fizer algo como:
nome = 'ABCDEFGHIJK'

print(nome[::-2])

Irá retornar:
KIGECA

Se tivesse usado numero positivo print(nome[::2]) iria retornar:
ACEGIK

Quando você usa números negativos no steps ele irá começar o índice a partir do final
Como você omitiu o start e o stop ele vai do inicio ao fim pulando ("steps") conforme você configurou (-2).
Se fizer print(nome[::3]) irá retornar:
ADGJ

Se fizer print(nome[::5]) irá retornar:
AFK

O indice com valores positivos e negativos fica mais ou menos assim na string ABCDEFGHIJK:

A
B
C
D
E
F
G
H
I
J
K

0
1
2
3
4
5
6
7
8
9
10

-11
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1

Usando o step com valor [::2] (positivo) irá obter, se usar [::-2] Se vai retornar a string na ordem inversa, pois o índice começa do final:

A
C
E
G
I
K

0
2
4
6
8
10

-11
-9
-7
-5
-3
-1

Usando [::-5]

A
F
K

-11
-6
-1

Com a name='Fernando' usando [::-2] você tem o seguinte (veja quais ficaram em negrito):

F
E
R
N
A
N
D
O

0
1
2
3
4
5
6
7

-8
-7
-6
-5
-4
-3
-2
-1

Sendo


How to draw a jitter plot using 100x11 array in Matlab?

Question: I'm able to draw a plot for out with size 100x11 using below code
x=0:0.1:1;
plot(x, out(:,(x*10)+1),'ko');
But I'm unable to figure out how to draw jitter plot for that data.
Below is my complete Matlab code that I'm using to save data into the output variable and trying to plot the data of output using jitter plot.
clc;
close all;
clear all;

heads = 0;
flip_chance = 0.0;
weight = 0.0;
c = 2;
output = zeros(100,11);
for p = 0.1:0.1:1.0

    for i = 1:1:100

        heads = 0;
        flip_chance = 0.0;

        for j = 1:1:10
           weight = rand();
           flip_chance = (p*10)+weight;
           if flip_chance >= 0.5 && weight <= p
              heads = heads + 1;
           end

        end
        %fprintf ("p : %f , heads : %d\n ", c, heads);
        output(i, c) = heads;

    end
     c = c+1;
end
x=0:0.1:1;
plot(x, output(:,(x*10)+1),'ko');

When I run with the plot I'm getting below output

I trying to get the plot in the below format
Comment: This question is now substantially different from the one that I answered. Please avoid changing the question. Adding clarifications like the second graph you posted is OK, but You should post a new question about changing intervals.
Comment: The extent of the data plotted is adjusted with the `XLim` property: `set(gca,'XLim',[-0.1,1.1])`.
Comment: sorry for changing the question, changed it back. Thanks for your help.
Answer: A jitter plot is imply a scatter plot like you make but with some noise added to the location of each dot. You can for example use the following code:
sz = size(output);
x = repmat(linspace(0,1,sz(2)),sz(1),1);
plot(x+0.06*rand(sz),output+0.6*rand(sz),'k.')

I'm using x+0.06*rand(sz) because x has increments of 0.1, so this gives a dot spread of 60% of the dot spacing along the x axis. You can change the 0.06 to suit your tastes. The same with output+0.6*rand(sz): 0.6 is 60% of the spacing.
EDIT
The "goal" graph you posted uses jitter only in the y axis. You'd leave out the random value added to x to accomplish this. It also seems to use a lot of jitter, merging visually the points for different y-groups. You'd set the random multiplier to at least 1 for such a graph, but I don't recommend it.
Comment: How can I change the tick intervals of x and y labels?
Comment: @Venkat `xticks` and `yticks`


tabela de abreviações de 3 letras para cidades por estado

Question: No Estado de SP por exemplo ADA seria Adamantina, ADO Adolfo, AGU Aguai, AGD Agudos, ..., ADC,  Alvaro de Carvalho, ABR Americo Brasiliense, ... SJC Sao Jose dos Campos, ... Mas "poderia ser" é chute.
As três letras constarão em meio físico (placas) e digital, não podem ser arbitrárias.  Precisamos de preferência de um padrão, como fez a IATA (aeroportos) ou Anatel, mas não um padrão federal (namespace de ~5500 itens para as 3 letrinhas), um padrão estadual, onde por exemplo em SP temos ~650 itens para associar os códigos das mesmas 3 letras.
NOTA TÉCNICA
O código de 3 letras faz o papel de um código de hash, e neste sentido vale a relação clássica de chance de colisão... Se temos 26^3 combinações com 3 letras, para manter em níveis aceitáveis as chances de colisão, não podemos mapear mais do que uma fração disso, digamos 1% a 5% das 17576 combinações. O namespace de 5500 (31%!) justamente extrapolou e a Anatel pagou o preço, foi forçada a usar Y no lugar de I,  ou "abreviações nada-haver" por conta do excesso de colisões nas escolhas mais mnemônicas — mais parecem placas de carro do que siglas mnemônicas. Da minha avaliação os 3% de SP ou max. 4% de MG são razoáveis e gerariam bons resultados.

Se houver um algoritmo pronto e padronizado seria também uma solução. Por exemplo Metaphone é um padrão mas não preserva o mesmo alfabeto nem gera códigos mnemônicos para iniciais no caso de nomes compostos (ex. São José dos Campos resultaria em SJC) de duas ou mais palavras. Acredito que não precisemos "reinventar a roda" e o algoritmo ideal para o português já exista... Grosseiramente o algoritmo ideal é simples, faz isso:

Se nome simples, tenta as 3 primeiras letras. Itu e Jaú ficam resolvidos automaticamente, Campinas e Marília ficariam  CAM e MAR.
1.1. Se houver colisão (ex. Marinópolis não pode usar MAR), adotar a primeira letra seguida de apenas consoantes (ex. MRN).
Nomes compostos de várias palavras: tentar primeiro as iniciais sem preposiçao, depois gerar combinações com o item anterior das palavras inicial ou final do nome. Exemplo: Santa Rita do Passa Quatro pode ser SRP, SPQ, ... ou ainda STQ, SQT, etc.

Ideal que o algoritmo seja bem fundamentado e já adotado como padrão em outro lugar.
Outro problema a ser resolvido pelo algoritmo, para que seja justo com os futuros usuários das siglas criadas. Quem merece mais a sigla "mais bonita"?  Por exemplo, BOR vai para Borborema (15790 habitantes e fundada em ) ou para Borá (890 habitantes e fundada em 1965 )?  A mais antiga ou a mais populosa?

Referências

Cidades brasileiras com aeroportos: aparentemente todas elas deveriam ter abreviações IATA, mas não encontrei uma listagem sistemática do Brasil (não confundir com aeroportos)... Alguns exemplos mas não sei se são oficiais: ANS Anápolis-GO, PTM Patos de Minas-MG, PTS Patos-PB,  URA Uberaba-MG, UDI Uberlândia-MG... e os mais exóticos,  BSB Brasília-DF, GYN  Goiânia-GO, ...
Abreviações Anatel: só em PDF e parece ser (Date  HTTP header) de 2013.
Abreviações do CDHU/SP: não possuem 3 letras, mas são todas palavras simples e reduzidas, simplificando bastante o trabalho do algoritmo. Ajudaria como "referência oficial" se não houver outra de ponto de partida... Só está disponível em PDF e parece ser  de 2005.
Dados das cidades, por estado, etc. Wikidata. Como fazer queries SparQL pode ser chato, algumas tabelas como a de São Paulo  já se encontram prontas, e um dataset homologado também pode ser utilizado.
Comment: Oi @RovannLinhalis, estou aguardando sinal verde de um projeto para retomar o assunto aqui, com subsídios no Github... Na verdade um algoritmo quebra-galho, como o da resposta atual (que foi ótima!), eu já havia publicado em PHP antes de vir fazer a pergunta... O projeto não visa o CEP mas pode ser melhor entendido/imaginado como substituto do CEP numérico por um código com letras e números, iniciado pelas 2 letras do estado, depois 3 letras do município. Ver https://github.com/OSMBrasil/CRP  e  http://datasets.ok.org.br/city-codes
Comment: Que tal pegar o da Anatel e separar por estado?
Comment: @JeffersonQuesado editei a questão explicando melhor, confira a "NOTA TECNICA", se precisar reviso.
Comment: @Bacco, agradeço por estar explicando seu voto-contra, mas repare que estou apenas contextualizando o problema, não me importo se responderem com C# ou Perl ou etc... E justamente um problema que fiz questão de trazer aqui e não no Stackoverflow principal, porque quero primeiro enfatizar o contexto da lingua portuguesa (!).  São questões numéricas, posso remover tudo que coloquei sobre Brasil e SP, mas perderia o contexto... Que tal esperar a comunidade se manifestar? Já haviam 2 votos creio que em 1 semana alguém responde... Ou acha mais importante dar mais cara de "problema de programação"?
Comment: Meu voto não é vinculante, teria que ter mais 4 de fechamento. Pode ser que o pessoal não feche. Eu até acho que foi bem elaborada, mas não consigo ver problema real de programação que não deixasse no mínimo ampla. A necessidade em si eu acho realmente fora de escopo (mas é como eu vejo, não necessariamente como outros vêem).
Comment: De qualquer forma, retirei o comentário e o voto pra não influenciar, e logo mais deleto estes aqui.
Comment: @PeterKrauss se eu entendi bem você quer um algorítimo que que defina um código de 3 letras para cada município do Brasil?
Temos 5564 municípios( segundo fonte: https://ww2.ibge.gov.br/home/estatistica/populacao/contagem2007/popmunic2007layoutTCU14112007.xls ) e 17576 combinações possíveis!
Acho que consigo fazer em Python + SQLite!
Comment: Eu inicialmente achei que o @Bacco estava sendo ortodoxo demais em relação ao escopo. Porque a pergunta é interessante, e mesmo que rigorosamente fora do escopo pensei que talvez desse pra encaixar forçando a barra um pouco. Vendo como a pergunta evoluiu, pensei até em fechar como não clara ou mesmo "baseada em opiniões" também. Resolvi ficar com a sugestão do Bacco porque no fundo é pergunta pra um geógrafo responder.
Comment: Oi @DiogoLindoso, o que tentei expressar é que as abreviações para os ~5600 municípios já existem, foram feitas pela Anatel, e que não queremos isso ("... mas não um padrão federal"), estamos buscando abreviações por conjuntos menores, por estado: SP, MG, etc. que nunca passam dos ~800. Quanto ao algoritmo que esbocei é um chute, é bacana fazer mas o difícil mesmo é descobrir se existe algum "algoritmo padrão", que já venha sendo usado ou tenha uma boa fundamentação.
Comment: Caso não exista um padrão (e a sua pesquisa prévia parece indicar isso), qualquer caminho será arbitrário. Você está em busca do menos arbitrário possível, certo? "Possível" dentro de condições que você mesmo está determinando. Precisaria definir mais claramente as condições. Por exemplo, a população deve ser levada em conta? A resposta que apareceu desconsiderou isso. As regras sobre colisões não estão claras também. Pode repetir siglas em estados diferentes? Definidas as condições, o algoritmo estaria praticamente dado. Nesse caso, o que sobraria pra perguntar?
Comment: Bom, já respondeu uma das minhas pergunta no comentário postado quase ao mesmo tempo do meu. :) Reitero que acho o assunto interessante, mas não sei como deixar a pergunta menos problemática.
Comment: @bfavaretto, sim, nos faltam parâmetros e fundamentos, não sei se edito mais uma vez a pergunta ou se começo um Github ;-) Como já começaram a responder vou fazer uns testes e manter também uma certa compatibilidade entre pergunta e resposta.. A resposta parece boa, talvez fiquemos por aqui.
Comment: teve progresso @PeterKrauss ?
Answer: De forma oficial, também procurei e não encontrei nada a respeito, acredito que se houvesse, estaria no IBGE.
A solução poderia ser um algoritmo próprio, e claro, manter armazenados esses registros para caso haja uma nova cidade no estado, o resultado seja igual.

Com um pouco de tempo e vários fors, fiz esse algoritmo para gerar as siglas, não levei em consideração a UF, e a ordenação das cidades é alfabética.
Basicamente a prioridade é que a primeira letra seja a inicial da primeira palavra. A segunda letra, a inicial da segunda palavra. A terceira Letra, a inicial da última palavra.
Não sendo possível, tenta pegar as letras seguintes, das palavras seguintes ou anteriores (no caso da última letra).
Não sendo possível, tenta pegar a 2 letras seguintes da primeira palavra, e se também não for possível, percorre a primeira palavra de forma reversa tentando montar a sigla.
Se depois de todas as tentativas, não for possível, a flag de sucesso continua como false e o sistema avisa que não gerou sigla para aquela palavra.
Segue o código comentado:
static void Main(string[] args)
{
    List<string> cidades = new List<string>(645);
    #region addCidades
    cidades.Add("BIRITIBA-MIRIM");
    cidades.Add("BOA ESPERANCA DO SUL");
    cidades.Add("CONCHAL");
    cidades.Add("DOBRADA");
    cidades.Add("DOIS CORREGOS");
    cidades.Add("MERIDIANO");
    cidades.Add("MESOPOLIS");
    cidades.Add("MIGUELOPOLIS");
    cidades.Add("MINEIROS DO TIETE");
    cidades.Add("MIRA ESTRELA");
    cidades.Add("MIRACATU");
    cidades.Add("MIRANDOPOLIS");
    cidades.Add("NOVA CAMPINA");
    cidades.Add("PANORAMA");
    cidades.Add("VIRADOURO");
    cidades.Add("VISTA ALEGRE DO ALTO");
    cidades.Add("VITORIA BRASIL");
    cidades.Add("VOTORANTIM");
    cidades.Add("VOTUPORANGA");
    cidades.Add("ZACARIAS");
    #endregion

    //Primeiro a lista é ordenada por ordem alfabética, fazendo com que a sigla SAL seja gerada para a cidade SALES e não para a cidade SALTO.

    Dictionary<string, string> siglas = new Dictionary<string, string>();

    foreach (string c in cidades)
    {
        string[] cs = c.Replace("'", " ").Replace("-"," ").Split(' '); //Depois, vamos separar cada nome em palavras com o `Split(' ')`, observando que as cidades com hifén ou apóstrofo também são separadas em palavras.
        bool sucesso = false;
        string sigla = null;
        for (int i = 0; i < cs.Length && !sucesso; i++) //Percorrer cada palavra
        {
            for (int j = 0; j < cs[i].Length && !sucesso; j++) //Percorrer cada letra da palavra atual (i)
            {
                sigla = cs[i][j].ToString(); //Primeira letra da sigla

                for (int k = i+1; k < cs.Length && !sucesso; k++) //Se há mais palavras depois da palavra atual (i), entra no for
                {
                    for (int l = 0; l < cs[k].Length && !sucesso; l++) //Percorre cada letra da palavra (k)
                    {
                        sigla = cs[i][j].ToString() + cs[k][l].ToString(); //Segunda letra da sigla

                        for (int m = cs.Length-1; m > k  && !sucesso; m--) //Se há mais palavras além da palavra (k), entra no for
                        {
                            for (int n = 0; n < cs[m].Length && !sucesso; n++) //Percorre cada letra da palavra (m)
                            {
                                sigla = cs[i][j].ToString() + cs[k][l].ToString() + cs[m][n].ToString(); //Terceira letra da sigla

                                if (!siglas.ContainsKey(sigla)) //Se a sigla ainda não foi utilizada
                                {
                                    siglas.Add(sigla, c); //Adiciona no dicionário
                                    sucesso = true; //Marca a flag como sucesso pra sair de todos os outros for
                                }
                            }
                        }

                        for (int m = l+1; m < cs[k].Length && !sucesso; m++) //Se não gerou a terceira letra com a palavra m, percorre as letras seguintes à (l) da palavra (k)
                        {
                            sigla = cs[i][j].ToString() + cs[k][l].ToString() + cs[k][m].ToString(); //Terceira letra da sigla

                            if (!siglas.ContainsKey(sigla)) //Se a sigla ainda não foi utilizada
                            {
                                siglas.Add(sigla, c); //Adiciona no dicionário
                                sucesso = true; //Marca a flag como sucesso pra sair de todos os outros for
                            }
                        }

                    }
                }

                for (int m = j + 1; m < cs[i].Length && !sucesso; m++) //Se não gerou a segunda letra com a palavra (k) percorre a palavra [i]
                {
                    if (m + 1 < cs[i].Length) //Dá preferência a letra seguinte se existir
                    {
                        sigla = cs[i][j].ToString() + cs[i][m].ToString() + cs[i][m + 1].ToString(); //Compoe a sigla com a segunda (m) e terceira letra (m+1)

                        if (!siglas.ContainsKey(sigla)) //Se a sigla ainda não foi utilizada
                        {
                            siglas.Add(sigla, c); //Adiciona no dicionário
                            sucesso = true; //Marca a flag como sucesso pra sair de todos os outros for
                        }
                    }

                    for (int n = cs[i].Length - 1; n >= 0 && !sucesso; n--) //Percorre a palavra (i) no sentido inverso para gerar a terceira letra
                    {
                        sigla = cs[i][j].ToString() + cs[i][m].ToString() + cs[i][n].ToString(); //Compoe a sigla com a segunda (m) e terceira letra (n)

                        if (!siglas.ContainsKey(sigla)) //Se a sigla ainda não foi utilizada
                        {
                            siglas.Add(sigla, c); //Adiciona no dicionário
                            sucesso = true; //Marca a flag como sucesso pra sair de todos os outros for
                        }
                    }
                }

            }
        }

        if (sucesso) //Se foi possível gerar a sigla
        {
            Console.WriteLine("Sigla " + sigla + " gerada para a cidade " + c);
        }
        else //Se nenhuma combinação foi possível
        {
            Console.WriteLine("Não foi gerada sigla para a cidade " + c);
        }

    }

    Console.WriteLine("Siglas geradas: " + siglas.Count + " de um total de " + cidades.Count+" cidades");

    Console.ReadKey();

}

Resultado:

Sigla BMI gerada para a cidade BIRITIBA-MIRIM
Sigla BES gerada para a cidade BOA ESPERANCA DO SUL
Sigla CON gerada para a cidade CONCHAL
Sigla DOB gerada para a cidade DOBRADA
Sigla DCO gerada para a cidade DOIS CORREGOS
Sigla MER gerada para a cidade MERIDIANO
Sigla MES gerada para a cidade MESOPOLIS
Sigla MIG gerada para a cidade MIGUELOPOLIS
Sigla MDT gerada para a cidade MINEIROS DO TIETE
Sigla MET gerada para a cidade MIRA ESTRELA
Sigla MIR gerada para a cidade MIRACATU
Sigla MIS gerada para a cidade MIRANDOPOLIS
Sigla NCA gerada para a cidade NOVA CAMPINA
Sigla PAN gerada para a cidade PANORAMA
Sigla VIR gerada para a cidade VIRADOURO
Sigla VAA gerada para a cidade VISTA ALEGRE DO ALTO
Sigla VBR gerada para a cidade VITORIA BRASIL
Sigla VOT gerada para a cidade VOTORANTIM
Sigla VOA gerada para a cidade VOTUPORANGA
Sigla ZAC gerada para a cidade ZACARIAS
Siglas geradas: 20 de um total de 20 cidades

Coloquei no .NETFiddle

Obs. Pelo comprimento do código, coloquei apenas 20 cidades. No Fiddle tem todas as 645 de SP que eu tinha aqui na base.

Extra:

Gerei as siglas para 2977 cidades que tenho aqui na base e não houve nenhum problema:
Comment: Rapaz, impressionante. Tem como compartilhar a ideia por traz de tantos laços?
Comment: @JeffersonQuesado tentei passar a ideia na descrição... o que acha ?


Measurements Numbers in Compressed Sensing

Question: here is a question about Compressed sensing. Let us denote the $k$-sparse signal $x\in \mathbb{R}^n$, measurement/sensing matrix $A\in \mathbb{R}^{m\times n}$ and the measurement $y = Ax \in \mathbb{R}^m$.
In the noiseless situation, we know that the signal $x$ could be perfectly reconstructed if $A$ satisfies the restricted isometry property. Denote the reconstructed signal as $x'$. Now I am more interested in the reconstructed performance (i.e. mean square error between $x$ and $x'$), instead of uniqueness or perfect reconstruction. It is intuitive that with more number of measurements $m$ the reconstruction performance would become better. But I could not find references for this idea. Is there any mathematical proof for this relationship?
Could anyone help me? Thanks in advance!
Answer: There is a wonderful book called " A Mathematical Introduction to Compressive Sensing" by Dr.Simon Foucart and Dr.Holger Rauhut. You can find the answer in Chapter 6 from this book.
I can not give you the exact answer since there are lots of mathematical concepts that should be introduced first. But you can find the answer yourself from this book.
By the way, the error really depends on which method you use to construct $x'$, for example l1 minimization, Iterative hard thresholding or Orthogonal Matching Pursuit...... There are lots of method and the errors are different.
Also, we have some constraints on number of measurements m, but sparsity k is more important than m in the error analysis (if I memorize correctly).
In this book, they consider the noisy case, which means $y=Ax+e$. But it doesn't matter, you can simply remove error term and the results still hold.
Comment: Thanks for your answer!


Evaluating $\lim_{x \to 0} \frac{1}{x} \int_{x}^{2x} e^{-t^{2}}\,dt$

Question:
How to evaluate this limit ?
  $$\lim_{x \to 0} \frac{1}{x} \int_{x}^{2x} e^{-t^{2}}\,dt$$

Can we use L'hospital rule here?
Comment: Hint: Expand the integrand for small $t$ and convince yourself that only the first term contributes.
Answer: Using $\frac{d}{dx}(\int_{f(x)}^{g(x)} h(t)dt)=h(f(x)).f'(x)-h(g(x)).g'(x)$ And the L hospital rule we have $L=\lim{x\to 0}\frac{e^{-4x^2}.2-e^{-x^2}.1}{1}=1$
Answer: $e^{-t^2}$ is a "bell curve"
$\frac{1}{x}\int_x^{2x} e^{-t^2} \ dt$
asks what is the average height of the grey stripe

The limit as $x$ approaches $0$ moves the grey stripe over to the $y$ axis.
$\lim_\limits{x\to 0} \frac{1}{x}\int_x^{2x} e^{-t^2} \ dt = \lim_\limits{t\to 0} e^{-t^2}$
Comment: It is better to use theorems like FTC to justify the intuition presented here.
Comment: We are really using the MVT here even if I did not call it out.
Answer: $F(x)=\displaystyle {\int_{x}^{2x}}e^{-t^2}dt$;
MVT, FTC:
$\dfrac{F(x)-F(0)}{x}=F'(s)$, $0<s<x$, where
$F'(s)= 2e^{-(2s)^2}-e^{-s^2}$;
Note: $\lim x \rightarrow 0 $ implies $ \lim s \rightarrow 0$.
$\lim_{x \rightarrow 0}\dfrac{F(x)-F(0)}{x}=$
$\lim_{s \rightarrow 0}(2e^{-(2s)^2}-e^{-(s)^2})=1$;
OR, a bit shorter:
MVT for integrals:
$I(x):= \displaystyle{ \int_{x}^{2x}}e^{-t^2}dt =$
$ e^{-s^2}\displaystyle {\int_{x}^{2x}}1dx = xe^{-s^2}$, $s \in [x,2x].$
$\lim_{x \rightarrow 0} \dfrac{I(x)}{x}= \lim_{s \rightarrow 0}e^{-s^2}=1$;
Answer: If we let:
$$f(x)=e^{-x^2},\,F(x)=\int f(x)dx$$
Then we can say that:
$$L=\lim_{x\to 0}\frac{F(2x)-F(x)}{x}$$
and since we can see that:
$$\lim_{x\to 0}F(x)=\lim_{x\to 0}F(2x)$$
we know that our limit is of the form $\frac 00$ and so we can say:
$$L=\lim_{x\to 0}\frac{F'(2x)-F'(x)}{1}=\lim_{x\to 0}\left[2f(2x)-f(x)\right]=\lim_{x\to 0}\left[2e^{-4x^2}-e^{-x^2}\right]=2-1=1$$
Answer: The substitution $t=ux$ also works:
$$\lim_{x\to0}{1\over x}\int_x^{2x}e^{t^2}\,dt=\lim_{x\to0}\int_1^2e^{x^2u^2}\,du=\int_1^2\left(\lim_{x\to0}e^{x^2u^2} \right)\,du=\int_1^21\,du=1$$
The step in which the limit is brought inside the integral can be justified from the fact that
$$\left|\int_1^2(e^{x^2u^2}-1)\,du \right|\le\left|\int_1^2(e^{4x^2}-1)\,du \right|=e^{4x^2}-1$$
Answer: L'Hospital's Rule is unnecessary here.
By Fundamental Theorem of Calculus we have $$\lim_{x\to 0}\frac{1}{x}\int_{0}^{x}e^{-t^2}\,dt=e^{-0^2}=1$$ and hence $$\lim_{x\to 0}\frac{1}{x}\int_{x}^{2x}e^{-t^2}\,dt=\lim_{x\to 0}2\cdot\frac{1}{2x}\int_{0}^{2x}e^{-t^2}\,dt-\frac{1}{x}\int_{0}^{x}e^{-t^2}\,dt=2\cdot 1-1=1$$


Which wind instruments are often doubled in symphonic orchestra just for the sake of loudness?

Question: Which wind instruments are often doubled in symphonic orchestra just for the sake of loudness?
What I mean is two instruments of the same kind and type (for example, two bass clarinets, or two a3 trombones) that play in unison exactly the same part throughout the whole peice, which means that both musicians look at the same stave on the score. And the reason for doubling is simply because only one would sound too soft, bearily audible.
Comment: There are an awful lot of implicit assumptions here. Some information about how the question came about might be very helpful.
Comment: Nor is it just about volume. You could have, say, eight violins and one double bass and like the balance. But you could want six double basses and 50 fiddles, not just because you want "more sound," but because the sound *of* larger sections is different. Meanwhile, nobody wants to pay more musicians than they have to, so few organizers are doubling just for kicks.
Comment: @Aaron - (1) I recall reading, possibly somewhere here on the Music Stack, that conductors sometimes invite additional musicians to the orchestra to play the same parts as other musicians in order to amplify the volume of those parts. It seems likely that this is done because those particular instruments are not sufficiently loud on their own. I'm curious to know which instruments are typically involved in this practice.
Comment: @Aaron (2) I assume it wouldn't include instruments like trumpets, as they already produce a considerable volume, or percussion instruments like drums, cymbals, and timpani, as they are already naturally rather loud on their own. Additionally, it goes without saying that the string section wouldn't be included, as it already has a substantial number of players.
Comment: It's not necessarily because the instrument is inherently in need of doubling, but more about *balance*. You could perform Handel's *Messiah* with one singer per choral part (or maybe two or three? I'm not sure whether they split) and one instrument per orchestral part. A more common small force would be a handful of singers per choral part, two first violins, two seconds, one or two violas, one cello, etc. And then sometimes (including in Handel's time) you have a choir of hundreds, and that needs a lot more instruments to balance it.
Answer: In the classic era orchestra it was common practice to have each woodwind played by two players (in German we call this "doppeltes Holz"). So you'd get 2 flutes, 2 oboes, 2 clarinets and 2 bassoons. In romantic era you even occasionally get three players, often also incorporating non-standard range instruments like piccolo flute, piccolo clarinet, bass clarinet, contrabassoon, ....
Now, the thing here is that these may play a part unisono (a 2 or a 3) for increased volume, multiple voices or solo by the composers decision. Each of these configurations will have distinct sound characteristics, and a skilled composer will make use of these.
There is a different performance practice of doubling the woodwinds: Usually this happens when you've got a very large string apparatus. In this case each woodwind position is played by two players to increase volume. So e.g. instread of 2 flutes you'd get 4 flutes with 2 player playing each flute part.
Answer: What you describe is rare, but not nonexistent. For example, Berlioz famously doubles the bassoon part to Symphonie Fantastique (Bsn. 1 and 3 read the same part, and Bsn. 2 and 4 read the same part). Bsns. 3 and 4 don't always play, but they are sometimes indicated to play for the explicit purpose of exactly doubling Bsns. 1 and 2. I feel that the reason for this is more about the exceptional timbre of the bassoon quartet, rather than pure volume, though.
Comment: This happens frequently with horn parts, too.  A composer might write for 2 or 4 horns to pay in unison, but not because they are too quiet to be heard - it's because they sound epic playing four on a part in unison!
Answer: For woodwinds and brass, this only happens when the composer wants the timbre of a massed unison.  It happens most in french horns, but even this is uncommon.  It does happen in the string section - a dozen players will play the exact same violin music, for example.
Answer: I never observed this to happen. Flute 1 and flute 2 have different voices (update: this does not exclude, that they sometimes play the same notes, but more often they have an appropriate interval in between) and the piccolo is entirely different. Same for oboe 1, oboe 2 and cor anglais, bassoon 1, bassoon 2 and contrabassoon or clarinet 1, clarinet 2 and bass clarinet.
I can't imagine a brass instrument requiring doubling for whatever reason.
If the composition is not perfectly balanced, the conductor should be able to improve the balance. While bass clarinet would surely be easily drowned against a full orchestra, this does not happen in real world scores.
Comment: When you say "flute 1" and "flute 2", how many actual musicians are you talking about? Literally two people, or is "flute 2" not an individual but a section of half a dozen different musicians (each with their own instrument)?
Comment: Strange! It looks like I was misinformed! Thanks for this input.
Comment: In my personal orchestral experience FWIW  wind parts often double for short periods within pieces.  Yes, "oddity" items like bass clarinet or Cor Anglais are never doubled, but that's a bit of an exception.
Comment: @R.M. No, most often this is just one person (as opposed to *Violin 1*). WIkipedia - see [here](https://en.wikipedia.org/wiki/Orchestra) - sketches this.
Comment: The first horn player is often doubled (known as [bumping](https://orchestrationonline.com/orchestration-tip-horn-bumping)), although the two players will only play together at certain points (e.g. unison lines for all the horns).


Making Nginx and PHP-FPM code version agnostic

Question: This is not a question about a current problem but more of a "preventive medicine" question:
I have the following code which is part of a much larger scrip I use to rise up Nginx environments on Debian-oriented systems:
sed -i 's/post_max_size \= .M/post_max_size \= 200M/g' /etc/php/7.0/fpm/php.ini
sed -i 's/upload_max_filesize \= .M/upload_max_filesize \= 200M/g' /etc/php/7.0/fpm/php.ini
sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g" /etc/php/7.0/fpm/php.ini
/etc/init.d/php7.0-fpm restart && systemctl restart nginx.service

This piece of code is the only one from the whole scrip which isn't version agnostic. I find this fact a tiny bit "disturbing" because I might run the script a year or 5 years from now with version 7.0 intact and that's likely to cause errors.
Do you think regex is good enough to make the above code version agnostic? Maybe there's a better way?
Comment: Ansible is easy to learn, quick to get started, and can save you a lot of time managing even a small number of servers.
Comment: It's time for a proper configuration management system.
Comment: Related: https://unix.stackexchange.com/questions/413933/nginx-version-agnostic-php-fpm-configuration
Comment: @MichaelHampton do you have something to recommend for me?
Comment: The idea of using an asterisk (`*`) seems promising: https://askubuntu.com/questions/992464/version-agnostic-php-fpm-restart
Answer: Use a symlink.
ln -s /etc/php/7.0 /etc/php/current
ln -s /etc/init.d/php7.0-fpm /etc/init.d/phpcurrent-fpm
sed -i 's/post_max_size \= .M/post_max_size \= 200M/g' /etc/php/current/fpm/php.ini
sed -i 's/upload_max_filesize \= .M/upload_max_filesize \= 200M/g' /etc/php/current/fpm/php.ini
sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g" /etc/php/current/fpm/php.ini
/etc/init.d/phpcurrent-fpm restart && systemctl restart nginx.service


Literature about the equation $x^m+y^m+z^m=(x+y)^m$

Question: I am studying the equation

$$
x^m+y^m+z^m=(x+y)^m,
$$

(and the related inequalities) where $x,y,z,m\in\mathbb{N}$ and $x,y,z,m>0$.
Is there anybody familiar with such equation, and/or knows where I can find some material about it? Thanks for your help!
This post is related to the conjecture exposed here A conjecture involving the equation $x^n+y^n+z^n= (x+y)^n$.
Answer: For $m=3$ there is a solution in small integers:
$$1^3 + 8^3 + 6^3 = 9^3 = (1+8)^3\quad\quad(1)$$
To find further solutions, we can transform the equation to an elliptic curve as below. Put $x=1$ (this is without loss of generality as any solution in integers is equivalent to a solution in rationals with $x=1$, and any such solution in rationals can be converted to one in integers by multiplying through by the cube of the least common multiple of the denominators):
$$1 + y^3 + z^3 = (1+y)^3$$
$$z^3 = 3y(1+y)$$
Put $t = y + \frac{1}{2}$:
$$z^3 = 3(t-\tfrac{1}{2})(t+\tfrac{1}{2}) = 3t^2 - \tfrac{3}{4}$$
$$t^2 = \frac{z^3}{3} + \frac{1}{4}\quad\quad(2)$$
From $(1)$, we have the solution to (2): $(t,z)=(\tfrac{17}{2},6)$. To use the elliptic curve $(2)$ to find new solutions we need one more initial solution. Surprisingly, perhaps, we can obtain a suitable second solution by rearranging $(1)$ as below (although it contains negatives it serves perfectly well as a starting point for finding further solutions in positives):
$$9^3 + (-1)^3 + (-6)^3 = 8^3$$
$$1 + (-\tfrac{1}{9})^3 + (-\tfrac{6}{9})^3 = (\tfrac{8}{9})^3\quad\quad(3)$$
Since $-\tfrac{1}{9}+\tfrac{1}{2}= \tfrac{7}{18}$ and $-\tfrac{6}{9}=-\tfrac{2}{3}$, this implies the solution to $(2)$: $(t,z)=(\tfrac{7}{18},-\tfrac{2}{3})$.
Letting $z=at+b$ be the straight line through the above two solutions to $(2)$ we have:
$$6 = \tfrac{17}{2}a + b$$
$$-\tfrac{2}{3} = \tfrac{7}{18}a + b$$
Subtracting:
$$6+\tfrac{2}{3} = (\tfrac{17}{2}-\tfrac{7}{18})a$$
$$\tfrac{20}{3} = \tfrac{146}{18}a$$
$$a = \tfrac{360}{438} = \tfrac{60}{73}$$
Hence:
$$b = 6 - (\tfrac{17}{2})(\tfrac{60}{73}) = 6 - \tfrac{510}{73} = -\tfrac{72}{73}$$
So we expect a third solution where $(2)$ meets the line $z = \frac{60}{73}t - \tfrac{72}{73}$.  The calculation is tedious to write out in full but it can be shown that the solution is $(z,t) = (-\tfrac{7140}{8000},\tfrac{913}{8000})$.  To check this, note that:
$$\frac{z^3}{3}+\tfrac{1}{4} = -\tfrac{7140^3}{3(8000^3)}+\tfrac{1}{4} = -\tfrac{357^3}{3(400^3)}+\tfrac{1}{4}= \tfrac{-15166431+16000000}{64000000}=-\tfrac{833569}{64000000}=\tfrac{913^2}{8000^2}=t^2$$
and:
$$\tfrac{60t}{73}-\tfrac{72}{73} = \tfrac{(60(913/8000))-72}{73} =\tfrac{54780-576000}{584000}=\tfrac{-521220}{584000}=-\tfrac{7140}{8000}=z$$
To obtain a solution in rationals of the original equation we have
$$y=t-\tfrac{1}{2}= \tfrac{913}{8000}-\tfrac{1}{2} = -\tfrac{3087}{8000}$$
Hence:
$$1^3 + (-\tfrac{3087}{8000})^3 + (-\tfrac{7140}{8000})^3 = (\tfrac{4913}{8000})^3$$
Multiplying through by $8000^3$ and rearranging:
$$4913^3 + 3087^3 + 7140^3 = 8000^3 = (4913+3087)^3$$
Further solutions may be obtained by finding further rational points on the elliptic curve $(2)$.  For a general explanation of how to find rational points on elliptic curves see Silverman J H, An Introduction to the Theory of Elliptic Curves, especially section on The Geometry of Elliptic Curves pp 8ff.
Answer: I'm posting this as a separate answer, again for case $m=3$, as its reasoning is quite different to that of my earlier answer.
Suppose we have a solution in integers to the equation:
$$a^3 + b^3 = 9c^3\quad\quad(1)$$
Then we can infer a solution to:
$$x^3 + y^3 + z^3 = (x+y)^3\quad\quad(2)$$
since:
$$(a^3)^3 + (b^3)^3 + (3abc)^3 = (a^3)^3 + (b^3)^3 + 3a^3b^3(a^3+b^3) = (a^3 + b^3)^3\quad\quad(3)$$
We can also infer a further solution to (1) and therefore to (2) since, given (1):
$$(a(a^3 + 2b^3))^3 + (-b(2a^3 + b^3))^3 = 9(c(a^3 - b^3))^3\quad\quad(4)$$
Proof:
LHS of $(4) = a^{12} + 6a^9b^3 + 12a^6b^6 + 8a^3b^9 - 8a^9b^3 - 12a^6b^6 - 6a^3b^9 - b^{12}$
$\quad\quad\quad\quad= (a^{12} - 2a^9b^3 + a^6b^6) - (a^6b^6 - 2a^3b^9 + b^{12})$
$\quad\quad\quad\quad= (a^6 - b^6)(a^6 - 2a^3b^3 + b^6)$
$\quad\quad\quad\quad= (a^3 + b^3)(a^3 - b^3)(a^3 - b^3)^2$
$\quad\quad\quad\quad= 9(c(a^3 - b^3))^3 = \text{RHS of } (4)$.
The above is a special case of a proof of a more general proposition (replacing $9$ with any cube-free integer $N$) that may be found in (A).
Since we have a solution to $(1)$, namely:
$$1^3 + 2^3 = 9(1^3)$$
we can use the above to obtain a series of solutions to (2) which, with suitable changes of sign and rearrangement as necessary, yield solutions in positive integers.  Successive solutions increase rapidly in size, the first three being:
First:
$$1^3 + 2^3 = 9(1^3)$$
$$\Rightarrow(1^3)^3 + (2^3)^3 + (3(1)(2)(1))^3 = ((1^3)+(2^3))^3$$
$$\Rightarrow 1^3 + 8^3 + 6^3 = (1+8)^3 = 9^3$$
Second:
$$17^3 + (-20)^3 = 9(7^3)$$
$$\Rightarrow(9(7^3))^3 + (17^3)^3 + (3(7)(17)(20))^3  = (20^3)^3$$
$$\Rightarrow3087^3 + 4913^3 + 7140^3 = 8000^3$$
Third:
$$(-36520)^3 + 188479^3 = 9(90391^3)$$
$$\Rightarrow(9(90391^3))^3 + (36520^3)^3 + (3(36520)(188479)(90391))^3 = (188479^3)^3$$
$$\Rightarrow6646883738818240^3 + 48707103808000^3 + 1866552387462840^3 = (6646883738818240 + 48707103808000)^3 = 6695590842626240^3$$
(A) Reference: Gordon R A (2018), Rational Arc Length The Mathematical Gazette Vol 102 No. 554 pp 210-225 (see especially pp 213-4).


Problema com Z-index

Question: Estou tendo problemas na utilização do z-index. Os elementos #questionSingUp e #actionSingUp do CSS não estão sobrepondo a div .loginActionWrap.
Já tentei alterar via JavaScript mas também não consegui.

var changeToLogin = document.getElementById("loginBtn");
var animation = document.getElementById("divAnimation");
var changeToSingUp = document.getElementById("singUpBtn");
var formSingIn = document.getElementById("actionSingIn");
var formSingUp = document.getElementById("actionSingUp");
var questionSingIn = document.getElementById("questionLogin");
var questionSingUp = document.getElementById("questionSingUp");

changeToLogin.addEventListener('click', function() {
 animation.classList.add("animationToRight");
 animation.classList.remove("animationToLeft");

 //questionSingIn.style.display = "none";
 //formSingIn.style.display = "block";

 //questionSingUp.style.display = "block";
 //formSingUp.style.display = "none";

   console.log("clicado");
});

changeToSingUp.addEventListener('click', function() {
 animation.classList.add("animationToLeft");
 animation.classList.remove("animationToRight");

 //questionSingIn.style.zIndex = "1";
 //formSingIn.style.display = "none";

 //questionSingUp.style.display = "none";
 //formSingUp.style.display = "block";

   console.log("clicado");
});
h2 {

  font-size: 28px;
  color: #C1C4D6;
}
p{
  font-size: 14px;
  color: #C1C4D6;
  padding: 15px 0px 20px;
 /* display: block;*/

}

.retangle {

  padding-top: 50px;
  padding-left: 100px;
  padding-right: 100px;
  height: 300px;
  width: 600px;
  line-height: 50px;
  text-align: center;
  position: relative;
  top: 50%;
  left: 50%;
  margin-top: -150px;
  margin-left: -400px;
  background-color: rgb(0, 0, 0, 0.55);
  border-radius: 3px;
  opacity: 0.90;
}

#questionSingUp {
  z-index: 1;
  position: absolute;
  width: 270px;
  height: 200px;
  background-color: pink;

}

#questionLogin {

  position: relative;
  width: 270px;
  height: 200px;
  float: right;
  background-color: red;
}

#actionSingUp {
/*display: none; PRETOOOOOOOO*/
z-index: 2;
position: absolute;
width: 270px;
height: 200px;
background-color: rgb(58,58,58);
}

#actionSingIn {
/*display: none; PRETOOOOOOO*/

position: relative;
margin-left: 329px;
width: 270px;
height: 200px;
background-color: rgb(58,58,58);
}

.loginActionWrap {
  z-index:-1;
  height: 450px;
  width: 370px;
  line-height: 50px;
  text-align: center;
  position: relative;
  top: 50%;
  left: 50%;
  margin-top: -400px;
  margin-left: -365px;
  background-color: rgb(255,255,255);
  border-radius: 3px;
  box-shadow: 0 0 10px 3px rgba(39, 37, 37, 0.45);

}
#singUpBtn{
  display: inline-block;
  border: solid 1px #C3C3C3;
  color: #C3C3C3;
  min-width: 140px;
  border-radius: 5px;
  line-height: 31px;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;

}

#loginBtn {
  display: inline-block;
  border: solid 1px #C3C3C3;
  color: #C3C3C3;
  min-width: 140px;
  border-radius: 5px;
  line-height: 31px;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 14px;
}

.animationToRight {
  -webkit-animation: mymoveRight 5s ; /* Safari 4.0 - 8.0 */
  animation: mymoveRight 0.5s ;
  -webkit-animation-fill-mode: forwards;
}

.animationToLeft {
  top: 50%;
  left: 50%;
  -webkit-animation: mymoveLeft 5s ; /* Safari 4.0 - 8.0 */
  animation: mymoveLeft 0.5s ;
  -webkit-animation-fill-mode: forwards;
}

/* Safari 4.0 - 8.0 */

@keyframes mymoveRight {
    from {right: 50%;}
    to {margin-left: 0%;}
}

@keyframes mymoveLeft {
    from {margin-left: 0%;}
    to {left: 50%;}
}

#c1{
  height: 450px;
  width: 370px;
  line-height: 50px;
  text-align: center;
  position: relative;
  top: 50%;
  left: 50%;
  margin-top: -400px;
  margin-left: -365px;
  background-color: rgb(255,255,255);
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>particles.js</title>
  <meta name="description" content="particles.js is a lightweight JavaScript library for creating particles.">
  <meta name="author" content="Vincent Garreau" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

Dont have an accont ?

Lorem ipsum dolor sit ames
               lorem ipsum dolor sit ames
               lorem ipsum dolor sit ames
               lorem ipsum dolor sit ames

       Sing up

Have an accont ?

Lorem ipsum dolor sit ames
               lorem ipsum dolor sit ames
               lorem ipsum dolor sit ames
               lorem ipsum dolor sit ames

      Log in

Comment: Coloque `z-index: -1` no `.loginActionWrap` que ele sempre ficará por trás.
Comment: @Sam Obrigado pela atenção, porém quando coloco z-index:-1 a div que era branca fica transparente assim podendo ver tudo que está por trás dela.
O ideal seria se somente #actionSingUp  sobreponha  .loginActionWrap
Answer: O que acontece é que o #questionSingUp está com z-index menor que o #actionSingUp. Tente deixar assim:
#questionSingUp {
  z-index: 10;
  position: absolute;
  width: 270px;
  height: 200px;
  background-color: pink;
}

E a outra ficaria assim:
#actionSingUp {
  /*display: none; PRETOOOOOOOO*/
  z-index: 5;
  position: absolute;
  width: 270px;
  height: 200px;
  background-color: rgb(58,58,58);
}

Problema com Z-index


Generator of a category

Question: I have a question on the definition of a generator of a category $C$. I have made a stupid mistake in the original formulation of the question. I beg your pardon for this.
Let $G$ be a generator of $C$. Let $f:X\to Y$ be a $C$-morphism. Does $f_*:Hom(G,X)\cong Hom(G,Y)$ imply that $f$ is an isomorphism? If yes, is this property for all $C$-morphisms $f$ equivalent to $G$ being a generator of $C$?
Original question: Let $G$ be a generator of $C$. Does $Hom(G,X)\cong Hom(G,Y)$ imply $X\cong Y$? If yes, is this property for all objects $X$ and $Y$ equivalent to $G$ being a generator of $C$?
Comment: What structure are you attaching to the hom-sets? Just the set structure? If you only have the set structure, then any two hom-sets with the same cardinality will be isomorphic, and this property will fail. (Take for example, $C$ = category of abelian groups, $G = Z$, $X = Z, Y=Z \times Z.$) Or do you want a natural transformation of functors?
Comment: A _strong_ generator has the property you want.
Comment: Thanks. A strong generator is a generator but the opposite is not always true, I suppose. Is this opposite true if I require some conditions on the category $C$? I think, that it is true in Sets for example.
Answer: The answer is no.  Consider a poset with one least element $0$ and two incomparable elements, $A$ and $B$ both greater than $0$.  Then $0$ is a generator (vacuously, because there is never more than one morphism between two objects), and $\hom(0,A)\cong \hom(0,B)$, as they are both sets with one element.  However, since $A$ and $B$ are incomparable, they are not isomorphic.
The problem is that there is no structure to the isomorphism $\hom(G,X)\cong \hom(G,Y)$.  The isomorphism isn't natural, it isn't induced by a particular map, it's just there.  There may be a way to add structure to the problem to get something Yoneda-esque, but as currently formulated, just being a generator is not enough to give what you want.

Generator of a category


One class SVM with caret in R using cross validation

Question: I am using one class SVM to train and predict anomalies. I would like to train the model using cross validation in an easy way as I have done with a multiclass SVM with caret in R.
Now, I train the model doing:
svm.model<-svm(training,y=NULL,
               type='one-classification',
               nu=0.01,
               gamma=0.002,
               scale=TRUE,
               kernel="radial")

However, I would like to use caret, apply cross validation and do something like:
train_control <- trainControl(method="repeatedcv", number=10, repeats=3)

svm.model <- train(classe~., data=training, method="svmRadial", trControl=train_control)

But instead of training a multiclass SVM I would like to use one class SVM.
Is there a way to do that in R with caret?
Answer: Simple option is not to use caret and just use the tune function from E1071.
svm_model <- tune(svm(training,y=NULL, type='one-classification', nu=0.01, gamma=0.002, scale=TRUE, kernel="radial", tunecontrol = tune.control(nrepeat = 3))

The default setting from tune is 10 fold CV. Using tune.control you can adjust this to repeat this as many times as you want. see ?tune.control for more options
If you want to use caret you will have to build your own model, because at the moment there is no one-classification model. But if you follow the steps on the caret page for using your own model you could adjust the first example.
Also look at these examples(example1, example2)
Comment: Thanks for the answer @phiver. However, the tune command that you have written doesn't work. Looking at the documentation of the function I do not see a way to specify a type='one-classification' in the tune function nor in the tune.svm function. How would you do that?
Comment: This link https://datalearner.wordpress.com/2013/10/24/r-tip-support-vector-machines/ might help. Tuning should work with type specification. Just make sure you have enough samples
Comment: I have 632 observations of 53 variables for training. With all the information that you have given me I execute:  `tune.svm(x = training,y=rep(TRUE,length(training[,1])), tunecontrol = tune.control(nrepeat = 3),scale=TRUE,kernel="radial",type="one-classification",nu=0.01)`. It seems to work and I get the value of gamma. However, I am not sure of having to do y=rep(TRUE,length(training[,1])), since this is a one-classification method, so it shouldn't be necessary.


Solve IVP using Laplace Transforms: $y'' + 4y' + 5y = \delta(t-1), y(0) = 0, y'(0) = 3$

Question: I have the following problem
$$y'' + 4y' + 5y = \delta(t-1),\quad y(0) = 0,\quad y'(0) = 3$$
When transforming I get
$$s^2Y - sy(0) - y'(0) + 4(sY - y(0)) + 5Y = e^{-s} \\
Y(s^2 + 4s +5) = e^{-s} + 3 \\
Y(s) = \frac{e^{-s} + 3}{s^2 + 4s + 5}$$
Now, I rewrote $s^2 + 4s +5 = (s + 2)^2 + 1$
$$Y(s) = e^{-s}\left( \frac{1}{(s+2)^2 + 1} \right) +
3\left( \frac{1}{(s+2)^2 + 1}\right)$$
And transforming back I use the fact that
$e^{at}\sin{bt} = \mathcal{L}^{-1}\left(\frac{b}{(s-a)^2 + b^2}\right)$ thus I get
$$y(t) = \delta(t-1) e^{-2t}\sin{t} + 3e^{-2t}\sin{t}$$
But this I get something else when wolfram solves the equation. And when plotting my solution it seems wierd. Can anyone check if there's anything wrong here?
Sorry about the formatting, couldn't get it to line up..
Comment: Actually $\mathcal{L}^{-1}\left(e^{-s}Y(s)\right)$ gives $\theta(t-1)f(t)$ where $\theta(t)$ is Heaviside theta function equal to $0$ for $t<0 $ and $1$ for $t>0$. Therefore your result should be $$y(t)=e^{-2 t} \theta (t-1) \sin (t-1)+3 e^{-2 t} \sin (t)$$
Comment: Is the equation $y'' + 4y' + 5 = \delta(t-1)$ or $y'' + 4y' + 5y = \delta(t-1)$?
Comment: $5y$, sorry about that
Comment: when you wrote $s^2Y - sy(0) - y'(0) + 4(Y - y(0)) + 5Y = e^{-s} $ the following step is $Y=\dfrac{e^{-s}+3}{s^2+9}$
Comment: Oh, well, I forgot to put an $s$ there.
Comment: Thanks, that gives the correct answer. But i thought $u(t-1) = \frac{e^{-s}}{s}$
Comment: Yes, it is. But $u(t-1)\cdot f(t)$ gives $e^{-s}F(s)$
Comment: @Raffaele In regard to your previous comment, note that $u(t-1)\cdot \color{red}{f(t-1)}$ gives $e^{-s}F(s)$, as stated on result **27** on the following [table](http://tutorial.math.lamar.edu/pdf/Laplace_Table.pdf). Consequently, it follows that you are missing an $e^2$ in your result, which I also show in my answer below:
$$y(t)=\color{red}{e^2}\cdot e^{-2t}\theta(t-1)\sin(t-1)+3e^{-2t}\sin(t)$$
Answer: Let's start off from the last point where you were on the right track:
$$Y(s) = \color{red}{e^{-s}\left( \frac{1}{(s+2)^2 + 1} \right)} +
\color{green}{3\left( \frac{1}{(s+2)^2 + 1}\right)}$$
The only mistake you made is when evaluating the Inverse Laplace transform of the red part, as shown below:

In this answer, we prove the following result (Result 27 on the Table of Laplace Transforms):
  $$\mathcal{L}\{u_c(t)\cdot f(t-c)\}=e^{-cs}F(s) \tag{1}$$
  Where $F(s)=\mathcal{L}\{f(t)\}$ and $u_c(t)=u(t-c)$. This is often referred to as the Second Shifting Theorem.

By definition, we must consider the following improper integral:
$$\begin{align} \mathcal{L}\{u_c(t)f(t-c)\}&=\int_0^{\infty} e^{-st}u_c(t)f(t-c)~dt\\&=\int_c^{\infty} e^{-st}f(t-c)~dt \end{align}$$
Using the change of variable $y=t-c$, we obtain:
$$\int_c^{\infty} e^{-st}f(t-c)~dt=\int_0^{\infty} e^{-s(y+c)}f(y)~dy=e^{-cs} \int_0^{\infty} e^{-sy}f(y)~dy=e^{-cs}F(s) \tag*{$\blacksquare$}$$

Using $(1)$, and selecting $c=1$, we clearly see that the Inverse Laplace transform of the red part is:
$$\mathcal{L}^{-1}\left\{\frac{e^{-s}}{(s+2)^2+1}\right\}=u_1(t)\cdot e^{-2(t-1)}\sin(t-1)=e^{2-2t} u(t-1)\sin(t-1)$$
The answer you obtain will indeed be the same as Wolfram Alpha's answer, namely:
$$y(t)=e^{2-2t}u(t-1)\sin(t-1)+3e^{-2t}\sin(t)$$


How to pause and resume andengine game?

Question: I am developing a game for Android using game engine. I want to have a pause and resume button on game screen.
I have implemented this by using MenuScene and for pausing the game I am using
engine.stop();

But once it stop the engine, it does not fire any touch or click events.
How to start the engine again?
or what can be the best way to implement the same ?
Comment: Please check my answer.It may help you
Answer: Okay,although i am not pro at andengine, i can give some advice. First of all, stopping the engine is not a pause solution that you are looking for. So instead of that,you must do it manuelly,which i mean;

Stop moving things:
To do this,you can use yourPhysicsWorld.unregisterPhysicsConnector() function if you are using some physics.
Or you can just set velocity to zero of all moving things(setVelocity(0,0))
Stop Update System:
Simply you can do this with yourScene.unregisterUpdateHandler()
Save Important Data:
If you have some important data, you must save them first.I won't give detailed information about it but if you don't know how to store data,you can look for SQLite and SharePreferences on Google.

Remind that if you want to return to game,you have to register the Update Handlers and Physics Connectors back to the scene.
Answer: I find that the easiest way to pause your game is doing the following:
mScene.setIgnoreUpdate(true);
mScene.setChildScene(mPauseScene, false, true, true);

when mScene is your main game scene and mPauseScene is the pause scene.
Then, to resume the game, you do:
mScene.clearChildScene();
mScene.setIgnoreUpdate(false);

Since the question mentioned a pause/resume button, I highly recommend this tutorial. It shows, in a very straight-forward way, how to implement such a button. I have used it in my game, and it works great.
Comment: Your answer works. But i have ques, if I have others childScene attached to my current GameScene. mScene.clearChildScene(); would clear those childScenes too. What can be solution for that.
Answer: To Pause the game:
GameScene.gameScene.setChildScene(pauseScreen, false, true, true);

add these lines to your game Screen.So that your game will go into pause
To Resume the Game:
 GameScene.gameScene.clearChildScene();

How to pause and resume andengine game?


Avoid IndexOutOfRangeException by looping back to start of array

Question: I have a array [4,4] that I am looping through and printing values.
 trainingpatterns.array = new int[4, 4];
   for (int i = 0; i < 4; i++)
        {
               var element1 = x + array.coordinates[0];

                var element2 = x + array.coordinates[2];

                var element3 = x + array.coordinates[4];

                var element4 = x + array.coordinates[6];

            for (int j = 0; j < 4; j++)

            {
               var element1 = y + array.coordinates[1];

                var element2 = y + array.coordinates[3];

                var element3 = y + array.coordinates[5];

                var element4 = y + array.coordinates[7];

   Console.WriteLine(trainingpatterns.array[element2, element6]);

However my loop requires me to go over the index. So when it gets to [5,4] for example the exception will be thrown.
What I want to do is if the x value goes out of bounds, for it to loop back to the start. So for example [5,4] will print [0,4] or [6,4] will print [2,4].
I have tried using a try catch but I cannot make the function universal for all values.
Thank you.
Comment: Why do you need to 'go over the index'?
Comment: What do you mean by "However my loop requires me to go over the index"? The code you've given doesn't...
Comment: You can use the mod operator `%` if you have an index that's going to grow larger than the bounds and you want it to wrap around.
Comment: @DStanley: Actually it'll stop at [3, 3] :)
Comment: @DStanley Actually it'll stop at `[3,3]`. But I think the OP is simply asking how to wrap array indices around. (And one answer is to index the array as `arr[i % 4]`.)
Comment: Aplogies, I am actually adding to the coordinates, which I have now added into my code. Which means I am producing coordinates that are larger than the array.
Comment: @user3365114: Right - in that case, use the code in my answer.
Comment: @DStanley Hello there, apologies, when you mean index the array as arr[i % 4], do you mean to add the mod operator when the array is being created?
Comment: @dvnrrs actually made that comment in response to my comment that was deleted (by me).
Comment: Oh yes sorry. @dvnrrs. Hello there, apologies, when you mean index the array as arr[i % 4], do you mean to add the mod operator when the array is being created?
Comment: @user3365114 No, when it's being accessed. `i % 4` will always be in the range [0, 3]; when `i` gets bigger it "wraps" around back to zero.
Answer: I suspect you just want to use the % operator:
int length0 = inputArray.GetUpperBound(0);
int length1 = inputArray.GetUpperBound(1);
...

var value = inputArray[x % length0, y % length1];

Note that this will not wrap negative numbers, however - the range of a % b is (-b, +b), whereas you want [0, +b). Taking account of this is a bit more longwinded, but let me know if you need it. If your index values will always be non-negative, you don't need to worry about it.


Playing mp3 file within a specific webpage using javascript/mozilla

Question:
Possible Duplicate:
Why doesn't Firefox support mp3 file format in <audio>

I am trying to embed a single mp3 file and not a playlist into a site using a Mozilla Add-on. My goal is for this file to play when ever a user visits a specific page, and not the entire site in general. I have chosen that websites Sitemap for an example. My main file is overlay.js, and I don't have any html based files, so I was wondering how would I make this possible, because I have searched the Q/A here, but majority of them explains how to use Audio for Html 5, rather then having a file play in javascript, or when ever a user clicks the Sitemap button. I have tried:
<code>var audio = new Audio();
audio.src = "chrome://path/to/file.mp3";
audio.play();
</code>
It doesn't work.
Comment: https://developer.mozilla.org/en-US/docs/Using_HTML5_audio_and_video
Answer: Firefox does not support mp3 files. For more information try this: http://html5doctor.com/html5-audio-the-state-of-play/
Comment: Wish I could accept all answers, thanks everyone solution solved.


Global Inverse Function Theorem

Question: Suppose that $f:\mathbb R^n\to\mathbb R^n$ is $\mathcal C^1$. For each of the following assertions, give a brief proof or a counterexample.
(a) If $f$ is one-to-one, then $Df(x)$ is invertible for all $x$.
(b) If $Df(x)$ is invertible for all $x$, then $f$ is an open mapping, i.e. the image of every open set is open.
(c) If $Df(x)$ is invertible for all $x$, then $f$ is onto.
(d) If $Df(x)$ is invertible for all $x$, the $f$ is one-to-one.
(e) If $f$ is one-to-one and onto, and $Df(x)$ is invertible for all $x$, then $f^{-1}$ is $\mathcal C^1.$
This question really made me doubt my understanding of IFT. If someone could correct/verify my answers that would be greatly appreciated. I may have gotten them all wrong:
a) True (I think?). If $f^{-1}$ is also differentiable then its derivative is $[Df]^{-1}$. I don't know if the inverse is necessarily $C^1$.
b) False. IFT gaurantees a $\textit{local}$ inverse. I don't think we can connect these local inverses to produce $f^{-1}$ defined on all of $\mathbb{R}^n$.
c) True. Again, I'm not sure about this extension to a global statement, but this seems to be true. If I have a local inverse at all points, then I must be hitting anything in the target.
I'm guessing F, T for the last two but I'm really not sure. Thank you!
Comment: You are guessing. I luv it.
Comment: $x \mapsto x^3$ is bijective.
Comment: Please use an image-to-LaTeX converter to convert your question into LaTeX so that people with screen readers can read them. Also LaTeX is more searchable than images.
Comment: https://math.stackexchange.com/q/4577592/27978
Comment: https://math.stackexchange.com/a/3112603/27978
Comment: Try to prove each statement. If you get stuck, try to identify carefully the exact step where you get stuck. Try to use that to find a counterexample. If you stuck, try to figure out where you get stuck. Try to use that to try again to prove the statement. Repeat. If after an hour or so of trying this, go do something else and try again the next day.
Answer: a) This is false. The counterexample is $f\colon\mathbb{R}\to\mathbb{R}$ given by $f(x) = x^3$. This is a one-to-one function but at $x = 0$ it's derivative is equal $0$, i.e. $Df(0)$ is not invertible.
b) This is true. In IFT, the derivative is invertible at just one point, but here we're assuming that it's invertible at all $x\in\mathbb{R}^n$. Suppose $O\subset\mathbb{R}^n$ is an open set and $a\in O$. Because of the IFT, there exists open sets $a\in U\subset O$ and $f(a)\in V\subset f(O)$ such that $f$ is an diffeomorphism betwen $U$ and $V$. Hence, $f(O)$ is an neighborhood of $f(a)$ and, because $a$ is an arbitrary point of $O$, $f(O)$ is an neighborhood of all of it's point and, therefore, an open set.
c) It's false. The counterexample is the function $\tan^{-1}\colon\mathbb{R}\to\Big(-\frac{\pi}{2},\frac{\pi}{2}\Big)$, whose image is limited.
e) To prove that $f^{-1}$ is $C^1$, one just need to prove that $Df^{-1}$ is an continuous function. Because $f$ is onto, to every $y$ there exists $x$ such that $y = f(x)$. By the ITF, there exists neighborhoods $x\in U$ and $y\in V$ such that $f$ is and $C^1$-diffeomorphism betwen them. This implies that $f^{-1}$ is also an $C^1$-diffeomorphism and then $Df^{-1}$ is continuous at $y$. Hence, of every $y\in\mathbb{R}^n$, the derivate $Df^{-1}$ is continuous at $y$ and, therefore, $f^{-1}$ is $C^1$.
Unfortunately I couldn't solve d).

Global Inverse Function Theorem


Approximation of arbitrary convex function

Question: I am currently studying Jürgen Moser's "A New Proof of de Giorgi's Theorem Concerning the Regularity Problem for Elliptic Differential Equations". During the proof of the first lemma, he claims that an arbitrary convex function $f$ can be approximated by a sequence of twice continously differentiable convex functions $f_m$, such that $f_m''(u)=0$ for large $|u|$, $f_m \rightarrow f$ and $f_m'(u) \rightarrow f'(u)$, where $f'(u)$ exists.
Having looked in several books about convex analysis (Rockafellar), I found out that a convex function should be twice differentiable almost everywhere. I further found in one of Rockafellar's books (convex analysis, thm. 25.7) a Theorem that shows the claim, except for the restriction on $f''$.
Now the question is how can we come up with that restriction on $f''$ and maybe someone has a reference for a book as well, since I would be interested in seeing the proof.
Comment: Is this about pointwise convergence? Then you could just cut off at say $|u|>m$ and replace that bit by a linear function.
Comment: I then need to apply Fatou's Lemma so I think pointwise convergence almost everywhere should be enough. Then interpolation would actually do the job..
Comment: I thought about it again and I am not certain that Interpolation would do the job. The function's derivate could only be defined on $\mathbb{R}$ \ $ \mathbb{Q}$. Then interpolation on the rational numbers wouldn't necessarily do the job, I guess. Any thoughts on that?
Answer: So I figured it out a few days ago and wanted to share it with you.
Most importantly it is a well known result that an arbitrary convex function can be uniformly approximated by a convex $C^{\infty}$-function on any closed bounded subinterval of the domain. I personally am not interested in the construction, but if you are, you might find some answers in the later mentioned references. Since this Approximation is applied on the Lemma of Fatou and the Lemma of Lebesgue, pointwise convergence of the Approximation is actually enough.
Assume $g$ is the function which approximates our convex function $f$ uniformly on the set $[-n,n]$. Then define
$\tilde{g}_n:= \mathbb{1}_{(-\infty,-n)} (g_n(-n)+g_n'(-n)(x+n)) + \mathbb{1}_{[-n,n]} g_n +\mathbb{1}_{(n,\infty)}(g_n(n)+g_n'(n)(x-n))$.
This function then approximates the convex function $f$ pointwise, and the second derivative vanishes outside the bounded set $[-n,n]$.
Some good references on approximation of convex functions might be:
D. Azagra, "Global and fine approximation of convex functions," Proc. London Math. Soc., vol. 107, p. 799–824, 2013
A. D. Alexandroff, Almost everywhere existence of the second differential of a convex function and some properties of convex surfaces connected with it, Leningrad State University Annals
J. J. Koliha, "APPROXIMATION OF CONVEX FUNCTIONS", Real Analysis Exchange, Vol. 29(1), 2003/2004, pp. 465–471
R. Tyrrell Rockafellar, "SECOND-ORDER CONVEX ANALYSIS", Journal of Nonlinear and Convex Analysis 1 (1999), 1-16


overriding defconfig in bbappend file

Question: In my chip vendors recipe they define
SRC_URI += "file://defconfig"

In my own layer, I want to override their defconfig and use my own.
I have a bbappend file in my recipe-kernel layer that adds my own defconfig file. My bbappend file:
SECTION = "kernel"
SUMMARY = "Kernel config and device tree customization"

FILESEXTRAPATHS_prepend := "${THISDIR}/files:"
SRC_URI += "file://defconfig"
SRC_URI += "file://tree_changes.diff"

The tree_changes.diff file is being applied so my bbappend file is being used at least for that.
The problem is that the vendor defconfig is always used. I dont really want to touch the vendors recipes, is there any better way of overriding the defconfig?
The chip vendor (Atmel/Microchip) bbfile is here:
https://github.com/linux4sam/meta-atmel/blob/dunfell/recipes-kernel/linux/linux-at91_5.4.bb
Comment: To override a recipe, the `.bbappend` is the best way. If it does not work, there is something else. Can you provide us the chip vendor recipe (the original .bb)?
Comment: ok good to know at least im in the right direction. My bbappend file also applies a device tree diff which definately is being applied. I added the chip vendor and lnik to their bb file. I still want to use their bb file as they do other things...I just want to use my own defconfig
Answer: Could it be that your defconfig file is not located under ${THISDIR}/files/<machine> in your layer but rather under ${THISDIR}/files ?
${THISDIR}/files/<distro> or ${THISDIR}/files/<machine> have a higher priority than just ${THISDIR}/files.
The different defconfig files are located in

${THISDIR}/files/at91sam9
${THISDIR}/files/sam9x60
${THISDIR}/files/sama5
${THISDIR}/files/sama5d4

in vendor meta-layer, so they would still be used.
So you would need to move your defconfig file to ${THISDIR}/files/<your_machine> in your custom layer. Note that FILESEXTRAPATHS_prepend = "${THISDIR}/files:" remains the same in the recipe. Yocto takes care of extending the path.
Comment: To complete Markus answer, one would thus need to put the defconfig of the bbappend into `${THISDIR}/files/`. Note that `FILESEXTRAPATHS` remains the same in the recipe, it'll take care of finding it in the subdirectory corresponding to the family or machine being built.
Comment: Thank you @qschulz - I updated the answer to make it more precise.
Comment: This is exactly the case. I am putting it in ${THISDIR}/files. Thank you.. I cant test this out yet but when I do i'll mark this as the answer. Any idea where it says abut putting it in ${THISDIR}/files/ having a higher priority?
Comment: It's described here https://www.yoctoproject.org/docs/current/mega-manual/mega-manual.html#var-FILESPATH

overriding defconfig in bbappend file


What kind of geometry is useful to study for mathematical competitions?

Question: I'm bad in geometry but I would like to be better. What kind of geometry is useful to learn olympiad level geometry? I mean, can projective geometry solve more problems than geometry with complex numbers or analytical geometry? And which of those geometries allows me to write shortest proofs on average as there is a time limit in competitions?
Comment: The Art of Problem Solving book [Introduction to Geometry](http://www.artofproblemsolving.com/store/item/intro-geometry) is probably a good place to start.  The book The Art and Craft of Problem Solving also has a chapter on geometry.
Comment: It may be also a good idea to consider exercises from past olympiades. So you can get a feeling, what is useful to learn.
Comment: Plane geometry of the sort covered in math competitions is pretty much a dead field. The fact that it's intuitive and doesn't require any complicated machinery or advanced math makes it well-suited to competitions, but you're quite unlikely to see anything along those lines at the high-school level. As such, using complex analysis, for example, is a great idea where applicable.
Answer: The answer depends on what you mean by "bad in geometry." For many people the problem is very simple. Geometry isn't taught in schools the way it once was, so you can be very good at algebra and other things, but geometry can still seem foreign and strange.
It might be good to learn geometry - at first - in normal school books from earlier times in order to have a good base, before moving on to more difficult contest-level problems. What the best book is may depend partly on what languages you can read. For English, have a look here:
http://www.knowledge-dojo.com/ ,
particularly Durell's A New School Geometry.
Answer: I'd recommend learning some non-Euclidean geometry as well. Pretty much master geometry with complex numbers and analytic geometry. The main idea at these mathematical competitions is to totally master your emotions and any nervousness you may have. Remember that you've trained well!


A problem regarding the definition of Uniform-continuity.

Question: We know the definition of Uniform-continuity is
If $A \subset \mathbb{R}$ and  $f:A \rightarrow \mathbb{R}$ with
$$\forall \epsilon>0\ (\exists \delta>0\ (|x-y|<\delta \implies |f(x)-f(y)|<\epsilon) )$$
then f is uniformly continuous on A.
If we consider the statement: Given $f:A \rightarrow \mathbb{R}$ such that
$$\forall \delta>0\ (\exists \epsilon>0\ (|x-y|<\delta \implies |f(x)-f(y)|<\epsilon) )$$
Does this statement also hold for uniformly continuous functions defined on $A$?
Comment: Every bounded function (even those with no point of continuity) satisfy this condition.
Comment: Thank you. If I take $f(x)=x$, this function also has this property, right? I am searching for a counter-example.
Answer: The latter implication follows purely logically from the first.
That implies, yes, the property is valid for all uniform continuous functions.
So for non uniform-continuous functions:
A counter example is $\mathbb R - \{0\}\ni x \mapsto 1/x$ .
Assume there is such a $\delta$, then set $x=-\delta/2$, $y=\delta/2$
Then $d(x,y)=\delta$, but $d(f(x),f(y))$ is not bounded for $\delta$ arbitrarily small
Comment: How can we conclude the second statement using the first? Can you please explain? I could not understand how it happens.
Comment: Since for  $\epsilon=1$ there exists $\delta>0$ s.th the function varies at most $1$ within $x,y$ varying $\delta$. Then for points $x,y$ with distance $|x-y|=D$ , the function varies at most $\lceil D/\delta \rceil=:\epsilon\prime$
,
Use $D,\epsilon\prime$ in the second statement