recursive method that checks if a string is palindrome in java

Question: the input: "mnkknm" where n=0
the output: flag is always equal 1 while it should be equal 3
and it returns -1
what is the problem ?
note : palindrome means for example if the Reverse of malayalam is also
malayalam then its palindrome
another note : i should write the code recursive as it's a homework
public static int PalindromeCheck(String x , int n)
{

int flag =0;
if (n+1 !=x.length()/2)
{
char s = x.charAt(n);
char y = x.charAt(x.length()-1-n);
if (s==y)
{    flag++;
System.out.println(flag); // i write it to check the value of the flag
}

return  flag+PalindromeCheck(x,n+1) ;
}

if (flag==x.length()/2)
{
return 1;}
else{
return -1;
}

Comment: Why you need a recursive method for this? It's as simple as to split the string by half, then take the second half, reverse it and compare.
Comment: @Victor Or just iterate the first half, and test that each character matches the corresponding index (offset from the length) on the right hand side.
Comment: @ElliottFrisch or just iterate the first half of chars,  XOR-them, iterate the second half, XOR-them and compare! as fast as binary comparison!
Comment: @Victor AFAIK `XOR` would not work - does is consider order? (`"abab"` is not a palindrome) | lot of values will create same XOR value (e.g.  `'a' ^ 'g' == 'b' ^ d' == 'c' ^ 'e'`)
Comment: Or just reverse the string and check if it's equal to the original. Though best to compare without case.
Answer: try this method please
public static boolean isPal(String s)
{
    if(s.length() == 0 || s.length() == 1) {
        return true;
    }
    if(s.charAt(0) == s.charAt(s.length()-1)) {

        return isPal(s.substring(1, s.length() - 1));
    }
    return false;
}

Comment: Please use *brackets* for `if` statements even if it's just one line.
Answer: First, I would create a helped method with that recursive signature (the public function should just take a String). And we can test for null and the empty string as special cases there. Like,
public static boolean isPalindrome(String x) {
    if (x == null) {
        return false;
    } else if (x.isEmpty()) {
        return true;
    }
    return isPalindrome(x, 0);
}

Then your current method seems close, but you want to compare n with a less than operator to the half of the length of x. Then test that the character matches on the right hand side (offset by n from x.length() but we need a -1 because of zero based indexing). Also, the method should return a boolean (and I fixed the name). Like
private static boolean isPalindrome(String x, int n) {
    if (n < x.length() / 2) {
        if (x.charAt(n) != x.charAt(x.length() - n - 1)) {
            return false;
        }
        return isPalindrome(x, n + 1);
    }
    return true;
}

Answer: i'd first do 2 or 3 quick checks :

if first character fail to match the last. that's a huge time saver without having to reverse anything, esp when input is really long

then ask it to locate any character that isn't the same as the first. if not, the string already is a nonstop-chain of that same character, then it must be a palindrome.

(optional one) if input is REALLY REALLY long, quick check on distribution of components of just that same first character - by definition of a palindrome,

if length is even then # of occurrences of that char must also be even.
if length is odd, then it should be even unless the exactly-center character is also that same one, otherwise you'll know the distribution is already not-balanced between left and right, then what's the point of reversing it when u can return false at this point and save time.
if both passes, then do what others have suggested : reverse the right-side half and check if it lines up with left-most index position (0 or 1 depending on which langauge). The reversal part doesn't have to do any of these small checks. just reverse it at high speed.


Yahoo Finance data query counting and efficiency

Question: I am developing a web application which will use financial data from yahoo finance. As I know there is a limit of queries (500k). So, I am implementing an auto fill search field which will send request for every press of the key starting from first symbol. As I understand this kind of tool will generate a lot of queries without significant job done.
Is there any solution, which can efficiently allocation queries? Database?
What is the best practice using such financial data sources?
Right now I am programming with PHP, also I am developing similar application in iOS, so what are the best solutions you can suggest?
Thank you.
Comment: pay for a better data feed? just like yahoo does
Answer: My 3D stock charting application stores (caches, to be precise) the data in flat files in a tmp sub-folder with file names similar to the symbol successfully retrieved. The application checks the date on the file and if it's not recent enough, well, it fetches new data. I could have used a database, but after going through 3 server moves and several databases I haven't had to update it. It just works.


Tomcat experts, /proxy/http/188.8.131.52/index.html to proxy http://184.108.40.206/index.html - possible?

Question: How to setup tomcat proxy so that, e.g., /proxy/http/184.108.40.206/index.html causes Tomcat to proxy http://22.214.171.124/index.html?
Comment: Are you trying to make an open proxy where any IP address substituted for 188.8.131.52 works; or just one specific destination server?
Answer: This looks possible via urlrewritefilter. (A filter which can be used in Tomcat or any servlet engine) The rule would look like this (untested) but should work according to the docs:

 <rule>
   <from>^/proxy/http/[^/]+/(.*)</from>
   <to type='proxy'>http://$1/$2</to>
 </rule>

http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/3.2/index.html

Tomcat experts, /proxy/http/1.2.3.4/index.html to proxy http://1.2.3.4/index.html - possible?


Evaluate imbalanced classification model on balanced sample

Question: Why would be too optimistic to compute presicion, recall and f1-score to evaluate a model trained for imbalanced classification on a balanced testing sample ?
Comment: I don't think it's optimistic at all to build a model on an _imbalanced_ data set and then evaluate it on a _balanced_ data set. Or the other way around. It depends on the data.
Comment: Do you have a source for this claim?
Comment: I am not sure if my claim is true in general. I just have few examples where metrics that are higher on a balanced testing sample than a imbalanced testing sample
Answer: I do not quite understand what you mean by "optimistic". Training on a balanced set and testing on an imbalanced set is fine to me, as long as the test set model the real distribution of the data well and the classifier performs well.
However, if you want to estimate the precision on the imbalanced set based on the performance on the training set, that will not work. Precision and recall will look very different between balanced and imbalanced set.
Comment: In my opinion, when your training set and test set have very different class distribution, you cannot compare performance metrics that are sensitive to class distribution to detect over fitting. However, performance on test set still can be a estimate of how well the model will perform on unseen data.
Comment: opimistic in the sense of having high metrics like f1-score, presicion and recall. But in reality, the model maybe will not generalize well.


Configure pytest using testpaths to search for tests inside tests folder

Question: I'm trying to improve the test collection speed by including the testpaths option in the pytest.ini file.
Inside each App folder I have a tests file where I put my tests, so I'm including it as follows:
[pytest]
testpaths = tests

However, no tests are collected. It returns the error: ERROR: file or directory not found: tests
What I'm I missing?
Comment: `testpaths` should be relative to the project root, so if you have a subdirectory `app1/tests`, then `testpaths = tests` won't work. Do a configuration per-app and place one `pytest.ini` with `testpaths = tests` in each of your app directories.
Comment: In my project pytest successfully find tests when a path of the `app1/tests` is not specified. If I set `testpaths = tests`, pytest catch all tests in `./*/tests/test_*.py` subdirectories.
Comment: According to the [documentation](https://docs.pytest.org/en/6.2.x/reference.html#confval-testpaths), testpaths is a list of directories that should be searched for tests. I don't think this is what you are providing here.
Answer: For example, you should put pytest.ini in the root directly of django-project as shown below:
django-project
 |-core
 |  └-settings.py
 |-my_app1
 |-my_app2
 |-pytest.ini # Here
 └-tests
    |-__init__.py
    └-test_1.py

In addition, if the specified testpaths below doesn't exist, the tests in tests folder are run:
# "pytest.ini"

[pytest]
DJANGO_SETTINGS_MODULE = core.settings
testpaths = my_tests # Doesn't exist


How to navigate the URL after booking page

Question: I have node content type for booking and created booking page in drupal 7 and same page is displaying error, confirmation and booking page. I am trying to split into three different pages(nodes) using same node--booking.tpl.php content type. I have custom booking.class.php that manages the booking process using two steps function prebooking and postbooking
After booking, I would like to redirect to xyz.com/booking-confirm if it's successfully booking and if it's error xyz.com/booking-error and currently, using xyz.com/booking for all actions.
What should I do? I am not sure, which option works. I have found this using some articles and stuck at this point.

Should I use header to redirect it?
header('Location: /booking-confirm');
header('Location: /booking-error');

Should I hook them in template.php?
function MYMODULE_user_register_form($form, &$form_state) {
    $form_state['redirect'] = 'path/to/somewhere';
}
Should I use drupal_goto to redirect it? it's in booking.class.php class?
Should I use hook_init? It's in template.php or booking.class.php ?

I am not sure, which is correct option to figure it out. I would like to split the URL using same content type. Any approach to solve the issue.
Comment: "I am not sure, which option works" Well have you tried any of them? If not, why not?
Comment: I have few but does not helps me. I thought would have been ask to make sure..I am on right path. Do you have option?  Thanks!
Answer: You should use form state to do redirects since users are interacting with forms. header is not really want you want and neither is drupal_goto.
The class(es) should return either a success/fail style response to the caller (in form submit) and based on that, you should handle the response and redirect with form_state redirect. The only job of your booking class should be to create a booking, it does not need to handle redirects or worry about any of that logic.
Also, no, absolutely don't do redirects from hook_init.
Vanilla example:
function myform_submit($form, &$form_state) {
  $book = new MyBookingClass();
  $form_data = $form_state['values'];

  // createBooking() returns either TRUE or FALSE

  if ($book->createBooking($form_state['values'])) {
    $form_state['redirect'] = '/booking-confirm';
  } else {
    // There was some sort of error.
    $form_state['redirect'] = '/booking-error';
  }
}

Comment: Great! let me review this your answer on my end. Thank you Kevin.
Comment: Is this function goes in booking class or custom display module?
Comment: Wherever your form code is for the booking form? It does not go in the class.
Comment: The thing with this answer is though, @Kevin you're assuming he's used Form API and proper FAPI processes to do this, which OP doesn't mention anywhere in his question.
Comment: Oh, well, that will certainly make it a lot more harder than it needs to be.


Alternating Euler sums

Question: $ \displaystyle \sum_{n=1}^{\infty} (-1)^{(n-1)} \frac{{\rm H}_n}{n^p} $
Does this have a nice closed form? I am trying to evaluate the case of p=4 also
Comment: Recall that $H_n$ are harmonic numbers.
Comment: Have a look at (http://math.stackexchange.com/q/457371)
Comment: I have the p=3 case. Lookibg forward to the 4 th power case. The integrations are quite complex.
Comment: I advise you, for another time, to make a prior web search and indicate through the relevant site(s) what is the degree of knowledge you have about the issue at hand.
Answer:
In Euler Sums and Contour Integral Representations by P. Flajolet and B. Salvy they state in Theorem 7.1 (Sitaramachandra Rao) for odd weight $q+1$:
\begin{align*}
\sum_{n=1}^\infty(-1)^{n-1}\frac{H_n}{n^q}
&=\frac{q+1}{2}\left(1-2^{-q}\right)\zeta(q+1)-\frac{1}{2}\zeta(q+1)\\
&\qquad-\sum_{k=1}^{q/2-1}\left(1-2^{1-2k}\right)\zeta(2k)\zeta(q+1-2k)
\end{align*}

We  obtain for odd  $q+1=5$:

\begin{align*}
\sum_{n=1}^\infty(-1)^{n-1}\frac{H_n}{n^4}
&=\frac{5}{2}\left(1-2^{-4}\right)\zeta(5)-\frac{1}{2}\zeta(5)\
-\left(1-2^{-1}\right)\zeta(2)\zeta(3)\\
&=\frac{59}{32}\zeta(5)-\frac{\pi^2}{12}\zeta(3)
\end{align*}
Answer: A very simple solution to the case $p=4$ that can be extended to all values, $p=2m, \ m\ge1$, may be found in https://math.stackexchange.com/q/3269815.

Alternating Euler sums


Lock access to error_log from url

Question: I have a website on WordPress.
Versions:

WordPress 3.3.1
PHP 7.2.13
Apache 2.4.37

My problem is that, error_log file is exposed to be viewed from url.
For example:
www.example.com/wp-content/themes/MyThemeName/error_log

Can you please help me with dealing this and restricting access to error_log ?!
Answer: Best is to reconfigure your website to NOT store log files in a public directory in the first place.
Adding the following to your httpd.conf (or if you must, to a .htaccess file)  is one way to block access to specific files:
<Files "error_log">
  Require all denied
</Files>

Comment: I tried this code into .htaccess and restarted server. url is still accessible and logs in it are visible.

Lock access to error_log from url


Carregar imagem alternativa em caso de não ter a imagem correta

Question: Eu tenho esse código que carrega a imagem do jogador de acordo com o seu nome, é possível complementar esse código carregando uma foto default, quando o código não encontrar a foto do jogador?
$player_img = "players/" . $row['LastName'] . "_" . $row['FirstName'] . ".png";

Answer: Resposta:
$player_img = "players/" . $row['LastName'] . "_" . $row['FirstName'] . ".png";
if (file_exists($player_img)){
    echo '';
} else {
    echo '';
}

Comment: Muito obrigado por ajudar, o código funcionou mas a foto está carregando no topo da pagina e não no lugar aonde deveria carregar.
Comment: Recomendo criar uma outra pergunta no SO para isso.
Answer: Para correr o código normalmente basta redefinir "$player_img" caso a referencia não aponte para uma imagem no servidor.
// receber a referencia noralmente
$player_img = "players/" . $row['LastName'] . "_" . $row['FirstName'] . ".png";
// verificar se não existe
if( !file_exists($player_img) ){
   // definir uma imagem padrão
   $player_img = "players/default.png";
}

Comment: Funcionou perfeitamente, obrigado!


Is $\mathbb{R}[X]/(P)$ isomorphic to $\mathbb C$ for every irreducible polynomial $P$ of degree $2?$

Question: Trying to solve a problem, I got stuck on the following question.

If $P\in\mathbb R[X]$ is an irreducible polynomial and $\operatorname {deg} P=2$, then is it true that $$\mathbb{R}[X]/(P)\cong\mathbb C?$$

I believe it must be true from the bits I've been hearing throughout my studies, but of which I haven't seen proofs. I've been unable to find anything on the internet other than this single page. It tells me that there is something called Weierstrass' theorem which should be relevant, but can't find even the precise statement of the theorem, let alone the proof.
Here's what I have tried.
First of all, I can assume that $P$ is monic, because for any polynomial of degree $2$ there's a monic polynomial generating the same ideal in $\mathbb R[X].$ So I have
$$P(x)=x^2+bx+c$$
for some real numbers $b,c$ such that $b^2<4c$.
I want to assume there is an isomorphism $\phi:\mathbb R[X]/(P)\to\mathbb C$ and work out what it should look like. I will denote by $[S]$ the coset of $S\in \mathbb R[X]$ in $\mathbb R[X]/(P).$ I'd like to find $S$ such that $\phi([S])=i.$
I have
$$
[x^2+bx+c-1]\mapsto -1,
$$
So the coset that is mapped to $-1$ has to be a square root of $[x^2+bx+c-1]$ in $\mathbb R[X]/(P).$ Such a coset must be represented by a linear polynomial $kx+l$. Thus
$$(kx+l)^2-(x^2+bx+c-1)\in (P),$$
that is
$$
(kx+l)^2-(x^2+bx+c-1)\equiv a(x^2+bx+c)
$$
for some real number $a$, and further
$$
(k^2-1-a)x^2+(2kl-b-ab)x+l^2-c-ac+1\equiv 0.
$$
This gives
$$
\begin{cases}
k^2=1+a\\
l^2=(1+a)c+1\\
2kl=(1+a)b
\end{cases}
$$
The problem is that solving this gives formulas that are very difficult to handle. And I need to handle them if I want to prove that what I'm constructing is indeed an isomorphism. Is there a better way of doing it?
Comment: Dear ymar: Are you supposed to know the fact that $\mathbb C$ is algebraically closed?
Comment: @Pierre-YvesGaillard I do know this fact from my course in analytic complex functions. It was proven there.
Comment: The non-constructive proof is simple then: $\mathbb{C}$ is an extension of $\mathbb{R}[x]/(P)$, and $\mathbb{R}[x]/(P)$ is an extension of $\mathbb{R}$. Now, look at the degrees of the extensions (i.e. their dimension as $\mathbb{R}$-vector spaces).
Comment: Dear ymar: Then you know that any proper algebraic extension of $\mathbb R$ is isomorphic to $\mathbb C$.
Comment: @Hurkyl I think I understand. If $\xi\in \mathbb C$ is a root of $P$, then $\mathbb R[X]/(P)\cong \mathbb R[\xi].$ I have $\mathbb R\subseteq\mathbb R[\xi]\subseteq\mathbb C,$ and since $\operatorname{deg}(P)=2$, it must be that $(\mathbb R[\xi]:\mathbb R)=2$. But also $(\mathbb C:\mathbb R)=2$, so $(\mathbb C:\mathbb R[\xi])=1.$ So I get $\mathbb C=\mathbb R[\xi]\cong \mathbb R[X]/(P).$ But I don't see where I used the fact that $\mathbb C$ is algebraically closed.
Comment: @Hurkyl OH, I see! :) $\xi$ is in $\mathbb C$ _because_ of the closedness.
Comment: Right. Well, technically, the $\xi$ I mentioned in my answer is not in $\mathbb{C}$. But because $\mathbb{R}[\xi]$ is an algebraic extension of $\mathbb{R}$, it must be (isomorphic to) a subfield of $\mathbb{C}$, the algebraic closure. (more precisely, isomorphic to a sub-extension of the extension $\mathbb{C}$ over $\mathbb{R}$). (and, of course, this isomorphism sends $\xi$ to something that really is in $\mathbb{C}$)
Comment: @Hurkyl I should have used a different symbol. I didn't mean $\xi$ to be the same as in your answer, but simply a root of this polynomial in $\mathbb C$. I know that when $F\subseteq K$ are fields and $k\in K,$ then if $T\in F[X]$ is the minimal polynomial of $k$, we have $F[k]\cong F[X]/(T)$. I'm using this fact. Is it more than right-ish now?
Comment: Yah, that sounds good.
Answer: You're making working with the quotient ring harder than it needs to be. You're familiar with working with the usual presentation of the complex numbers $\mathbb{R}[i] / (i^2 + 1)$, right? Working in $\mathbb{R}[x] / (P)$ isn't much different; it's just $x^2$ reduces to something else.
It might help you to define a new variable $\xi$ to be the image of $x$ in $\mathbb{R}[x] / (P)$, and do arithmetic in terms of $\xi$.
Anyways, it's much, much easier to figure out the image $x$ in $\mathbb{C}$ than it is to find a preimage of $i$ in $\mathbb{R}[x] / (P)$. (the latter shouldn't be all that hard once you get used to arithmetic, though)
Hint: for it to be a homomorphism, you need to find a complex number α such that $\alpha^2 + b \alpha + c = 0$.
Answer: If $\mathbb R[X]/(P)$ injects into $\mathbb C$ (and the injection preserves $\mathbb R$), then $X$ must map to one of the complex roots of $P$ which you can find using the quadratic formula.
So if $p+qi$ is a root of $P$, then the residue class $[\frac{1}{q}X-\frac{p}{q}]$ ought to behave like $i$. Proving that is probably just a matter of inserting the quadratic formula (which splits nicely into real and imaginary terms here) and reducing.
Comment: Thank you. I will try to complete this constructive proof and if I have trouble, I'll ask here again.
Answer: Hint $\ $ For an explicit isomorphism proceed as in the quadratic formula. Suppose R is an ordered field which is closed under taking sqrts of positive elements, and suppose that some polynomial $\rm\ a\:X^2 + b\:X + c \in R[X]\: $ of negative discriminant $\rm\:d = b^2 - 4ac < 0\:$  has a root $\rm\:x\:$ in some extension field $\rm\:F\supset R\:.$ Then $\rm\:-1\:$ is a square in $\rm\:F\:$ since
$$\rm  (b+2ax)^2 =\: b^2+4a(bx+ax^2) =\: b^2+4a(-c) =\: d < 0\ \ \Rightarrow\ \ \left(\frac{b+2ax}{\sqrt{-d}}\right)^2 =\: -1 $$


Extract E-mail Addresses from Text File (SED? AWK?)

Question: I have a file of e-mail addresses harvested from Outlook so that the addresses in the harvested form show up like this:
-firstname.lastname@example.com
-firstname.lastname@example.com
-firstname.lastname@example.com,JOHN DOE, RICHARD ROE,"\O=USERS:SAM"

etc.
What I would like to end up with is a text file that has one validly formed address on each line. So email@example.com would be OK, but "RICHARD ROE" and the "\O=USERS,etc." would not be. Perhaps this could be done with SED or AWK?
Comment: What is the question?
Comment: How can I manipulate the text file to extract properly formed email addresses without the cruft?
Comment: Is the email address alway the first part of the line? And it ends with a `,` (comma)?
Comment: Unfortunately, no. Sometimes the lines end with a comma, sometimes a semi-colon, sometimes double-quotes, ex.:
Comment: Usually a line will contain at least one valid email address, but not always. The problem is the additional material that is not in valid email address format.
Comment: The format of a valid email address is given here: http://tools.ietf.org/html/rfc3696#page-5 . It seems somewhat complex to check all the special cases..
Comment: Also I believe `-email@example.com` is a syntactically valid email address.
Answer: Here's one way with GNU awk given your posted input file:
$ gawk -v RS='[[:alnum:]_.]+@[[:alnum:]_]+[.][[:alnum:]]+' 'RT{print RT}' file
email@example.com
firstname.lastname@example.com
firstname.lastname@example.com

It just finds simple email addresses, e.g. "bob@the_moon.net" or "firstname.lastname@example.com", feel free to change the setting of RS if you can figure out an appropriate RE to capture the more esoteric email addresses that are allowed or post a more representative input file if you have examples. here's another RE that works by specifying what character cannot be in the parts of an email address rather than those that can:
$ gawk -v RS='[^[:space:][:punct:]]+@[^[:space:][:punct:]]+[.][^[:space:][:punct:]]+' 'RT{print RT}' file
email@example.com
firstname.lastname@example.com
email@example.com

Again it works with your posted sample, but may not with others. Massage to suit...
With other awks you can do the same by setting FS or using match() and looping.
Comment: +1 Interesting answer. Now I think `awk` is working like `grep -oE '[[:alnum:]_.]+@[[:alnum:]_]+[.][[:alnum:]]+' file`. However, it might be slower than `grep` since it still does field splitting.. Is there a way to avoid having `awk` do the field splitting?
Comment: No. You can set FS to some value that doesn't exist so there'll only be 1 field per record, but that's not the same as not attempting to do it at all. grep would probably be faster but it's not as extensible but then you'd need to become familiar with GNU grep functionality too. For me, it's easier to just remember the GNU-specific stuff for 1 tool, gawk.
Comment: I got in contact with one of the maintainers at Gnu, and he suggested to look at the source code. In the file `field.c` (for gawk version 4.1) line 238, a function called `set_record` is defined. It seems like they are not doing any field splitting unless you explicitly reference `$i`, where `i>=1` or `$NF`. So this is good news :)
Comment: What about setting `FIELDWIDTHS="5000"` or some other large number. That should presumably prevent field splitting?
Comment: Just like setting `FS=RS`, for example, it won't stop awk from doing field splitting, it'll just result in awk splitting each record into 1 field.
Comment: But at least it should be more efficient than the usual splitting at white spaces? Now we only need consider a single field and there should be no regex pattern matching involved..
Comment: I really don't know. I'd assume the awk code is optimized to handle the case where there's multiple fields separated by white space since that's the normal case so setting FS to something other than a blank char may be less efficient overall even if it results in fewer fields.
Comment: Interesting. They must also be looking for `$var` too, then - basically `$anything-except-zero`. Thanks for the info.
Answer: You can try:
awk -F, '{
  for (i=1; i<=NF; i++)
    if ($i ~ /@/)
       print $i
}' file

or like this:
awk -F, -f e.awk file

where e.awk is:
{
    for (i=1; i<=NF; i++)
        if ($i ~ /@/)
            print $i
}

Comment: awk -F, '
> for (i=1; i<=NF; i++)
>     if ($i ~ /@/)
>        print $i
> }' backup02.txt
awk: syntax error at source line 2
 context is
  >>> for <<<  (i=1; i<=NF; i++)
 extra }
awk: bailing out at source line 5
Comment: @user26732 You have some spurious brackets `>` before `for` and after the `if` and `print`
Comment: I cut and pasted the code; this time I typed it in:  awk -F,'for (i=1; i<=NF; i++) if ($i ~ /@/) print $1}' backup02.txt
awk: syntax error at source line 1
 context is
  >>> backup02. <<< txt
awk: bailing out at source line 1
Comment: @user26732 Yes you are completely right.. It seems I forgot the opening brace `{`, see my update..
Comment: I'm not sure what's going on: $ awk -F,'{for (i=1; i<=NF; i++) if ($i ~ /@/) print $1}' backup02.txt
awk: syntax error at source line 1
 context is
  >>> backup02. <<< txt
awk: bailing out at source line 1
Comment: @user26732 There should be a space between `,` and `'` after the `-F` option, and there should be `print $i` not `print $1`
Comment: Creating the e.awk file helped, but there is still cruft including lines like the following:/O=FIRST ORGANIZATION/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=ABC  Such a line obviously doesn't contain an email address.
Comment: The syntax I used was: $awk -F, -f e.awk backup02.txt
Comment: @user26732 Maybe you could provide a sample of the problematic line in your question, or better: If you provide the whole file at http://pastebin.com/ Then it would be easier for us to check for ourselves..
Comment: The line `/O=FIRST ORGANIZATION/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=ABC` works fine with me. That is: it is not printed..
Comment: I did provide an example, it's the line that begins with /O, etc. This is generated by Microsoft Exchange in lieu of a properly formed email address. The problem is that this "address" can show up anywhere in a line, beginning, middle, or end. It looks like, after running your code, that there are no more names in lieu of properly formed email addresses. Because of confidentiality, I can't post the entire file!
Comment: @user26732 Yes I understand that you cannot post the file. Is this: `/O=FIRST ORGANIZATION/OU=FIRST ADMINISTRATIVE GROUP/CN=RECIPIENTS/CN=ABC` the *entire* line? Or is there more entries on that line?
Comment: OK, I submitted "eggsample" to pastebin
Comment: @user26732 Can you provide a link to that?
Comment: Like I said, that "O/=First etc" can appear **anywhere**, beginning, middle, end, and there are often variations, so you can't do a simple find/replace.
Comment: http://pastebin.com/WaD4qzt8
Comment: @user26732 thanks, I will have a look at it..
Comment: The following `awk -F'[,;]' -f e.awk file` seems to work on the "eggsample".
Comment: Thanks very much! There's still a few, but not many.
Comment: @user26732 You are welcome.. If you can describe the last cases I can have a look at them if you like..
Comment: Is there a way to pipe the output to a new file? The example I was going to pull is exactly the same as in eggsample.txt, so maybe awk hasn't modified the original file and I was just seeing the terminal content.
Comment: @user26732 I am not sure what you mean. But `awk -F'[,;]' -f e.awk file > temp.txt` will save the output in `temp.txt`
Comment: That was the issue, I added ">newfile.txt" at the end of the script and the cruft is all gone in newfile.txt


How to change DNS server IP address

Question: How can I change the DNS server IP address in Windows XP from command line?
I don't want to do it from UI every time I need since it requires a lot clicks.
Answer: FYI, You can update both the primary and secondary dns servers by using the following commands
netsh interface ip set dns name="Local Area Connection" source=static addr=10.0.0.1 register=PRIMARY
netsh interface ip add dns name="Local Area Connection" addr=10.0.0.2 index=2

Comment: Actually it works, take note that the 2nd one is `add dns` not `set dns`. I had the same problem earlier using `set dns` and it complaint that `index` is not a valid argument
Comment: @Aaron I think second command has syntax error, index is not recognized in XP
Comment: @erdogany Really?  That might be an XP thing because i just ran it on windows 2003 and it worked.
Comment: thank you for highlighting this! I was also getting " 'index' is not a valid argument for this command."
Answer: In a command prompt:
netsh interface ip set dns "local area connection" static 10.0.0.1
You can list the interfaces on your PC using:
netsh interface ip show interfaces

How to change DNS server IP address


Learning to play with one-finger chord function on a keyboard

Question: Just started teaching myself to play the keyboard. I'm trying to use one-finger chords now, but not sure how long I am supposed to play the chord for. Is it over the whole bar or bars of music or just the first note the chord letter (say C or G) is mentioned at the beginning of the bar?
I'm assuming it is over the whole bar but not sure.
Comment: @WillRoss1 - entirely possible on a lot of keyboards. Just press the 'one finger chord' button.
Comment: @StephenKelly May I ask why you are learning to play this way? It is only applicable to specific keyboards, is significantly limited in what it can do (no dim chords, sus chords, inversions, extensions, etc.) and won't help you advance to the next level at all (may even make it far more difficult). Don't get me wrong, I'm not saying there is not a valid reason, but as a classically trained pianist this just doesn't make any sense to me. Hence why I'm asking :) I'd really love to know the benefits of this. Thanks!
Comment: Could you clarify what you mean by "one finger chord"? A chord, by definition, contains multiple notes, which is impossible with only one finger.
Comment: @Tim Oh, you mean that setting that I accidentally turned on when I was 12 and thought me keyboard was broken? XD
Comment: WillRoss1 you can play a lot of chords with the function. It's similar to the buttons on accordions.
Answer: There seems to be some confusion based on the comments under the question. The term keyboard in this case is a synthesizer, that means an instrument with lots of sounds, often several hundreds of sounds and lots of different styles for the rhythm box.
On such a keyboard the "one finger chords" is a standard option. You start the drum machine and then you press a key with one finger  on the left side of the instrument and the chord is played. Like press C and you get a C major chord played in the style you have chosen.
Now the question is about whether the chord should be continued the whole bar. Yes, the normal thing is that the chord is continued until a new chord is indicated. You don't need to keep pressing the key, the chord will continue until a new key (for the next chord) is pressed.
It is called "one finger chords", but as soon as you want other types of chords you need to press more than one key, like C7 is C and B pressed at the same time. But as long as you stick to plain major chords you only need to use one finger.
Answer: When reading from music like this...

...piano staff with chord symbols.
Or, like this...

...a lead sheet with only melody and chord symbols, the convention is to play the chord until a new chord symbol is given. Often the chord changes are one or two per bar. Sometimes you may see the note N.C. meaning no chord.
Sustain the chord while moving through the notes of the melody. Some of the melody notes will be chord tones and others will be non-chord tones. That melodic flow in and out of chord tones is very common.
Answer: I started that way too, for me it depends on the style you are playing. I would try learning chords and try to fit them with your preferred style. The beat helps you decide how long of a measure it should be played.


d3 version 4, I'm trying to make a mouseover conditional based on class

Question: I am trying to make this mouseover conditional. if the "selected" class exists then return the mouseover function
This is the code:
.on("mouseover", function() { if(d3.select(this).classed("selected")) {
return ""}
else{
return mouseover}
})

Thanks in advance
Answer: It seems to me that you want to call the mouseover function depending on the class. If that is correct, you just need to do:
.on("mouseover", function() {
    if (d3.select(this).classed("selected")) {
        mouseover()
    }
 })

Or, alternatively:
selection.selectAll(".selected").on("mouseover", mouseover)

Here is a demo. The first circle doesn't have the class, the second one does:

var svg = d3.select("svg");
svg.selectAll(null)
  .data([1, 1])
  .enter()
  .append("circle")
  .attr("cy", 50)
  .attr("r", 20)
  .attr("cx", function(d, i) {
    return 100 + 100 * i
  })
  .classed("selected", function(d, i) {
    return i
  })
  .on("mouseover", function() {
    if (d3.select(this).classed("selected")) {
      mouseover()
    }
  })

function mouseover() {
  console.log("mouse over")
}

<svg></svg>
Comment: I want the mouse over to work on lines that do not have the class "selected"  so from what you posted it works for me except on the first occurrence, I get an error. this is what i'm using:   .on("mouseover", function(d) {
                                if (d3.select(this).classed("line selected")) {
                                                return " "} else {mouseover(d)
                                }
                    })
Comment: In that case, just invert the boolean: `if (!d3.select(this).classed("selected")){mouseover()}`. Also, my code cannot throw any error, so I don't know what error are you talking about.


Does GLES20 draw out of bound vertices?

Question: I am trying to make a grid with OpenGL ES 2.0 for Android. What I am trying to understand is whether extra vertices use more memory even if they're not drawn on the screen. For example, I am drawing a line which is three times longer than visible area. I am using this Line class - https://stackoverflow.com/a/16223456/1621987.
<code>mLine = new Line();
mLine.setVertices(0f, -10f, 0f, 0f, 10f, 0f);
...
GLES20.glDrawArrays(GLES20.GL_LINES, 0, vertexCount);
</code>
Is it efficient to do it performance and memory wise?
Comment: Not exactly the same question, but this is similar to http://stackoverflow.com/questions/23186192/texture-partially-off-screen-performance-difference.
Answer: Lines that are too long for their vertices to be seen, but are still partially visible, will be clipped to the window, that is, their ends will be clipped away if they're out of sight. Lines totally outside the window will be culled and not sent to the rasterizer to be drawn at all. For OpenGL to determine this, though, each line must be sent to the graphics pipeline.
(Of course, it's also possible to omit such lines to keep them from being drawn, if your code determines beforehand that they won't be seen.)
Thus, this is not so much a matter of using less memory as it is of eliminating unnecessary work.

Does GLES20 draw out of bound vertices?


How do I know what in my code is triggering this 'System.ObjectDisposedException ?

Question: I'm debugging and enhancing a C#/XAML program that repeatedly generates an exception while running which I can see looking at the Output window.
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
(for some reason they seem to happen in pairs) The program itself keeps running after the exceptions occur.
The program consists of some XAML/C# code-behind which forms a front-end and test harness for a library of calls in a .Net DLL, which is also part of our C# code.
The total code-base (front end and DLL) is about 100K lines of C# source code code spread among about 25 files.    It mostly runs in one thread except for code which runs in socket-data handlers which get called by the system when data arrives from outside hardware devices (this program runs a factory manufacturing process).
How do I narrow-down/track-down where or what in my code is triggering these exceptions?
Comment: It means you are trying to access an object that has been disposed, either by an explicit `Dispose()` call, a `using` block, or by a containing object being disposed.  Without a stack trace and source code that's about all that can be inferred.
Comment: So how do I break on this exception so I can get a stack trace?
Answer: In Visual Studio you can break execution when an exception is thrown. Go to debug menu -> exceptions -> Common Language Runtime Exceptions -> System -> System.ObjectDisposedException and check the checkbox for "Thrown".
Answer: This exception indicates an attempt to access an object after it has been .Dispose()-ed. The reason the program continues to run is that the exception is handled. a First-Chance exception is always generated when an exception is thrown, even if it is handled with a catch statement.
In general, many first chance exceptions like this are not something to worry about. If you want to track them down, you will need to attach a first chance exception handler, and then use the StackTrace Property to find them. Assuming your Main function is in Program, the following code should work
static Program()
{
    AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
    { // Breakpoint here
    };
}

This will give you access to the exception via the e.Exception


What functionality is available from Drupal.theme()

Question: I have some complex data in javascript I need to render, mostly as tables.
This page explains how to add new theme functions, but I just want to create basic vanilla html. This apparently is the "official documentation."
I can't for the life of me find a list of the functions/functionality available in Drupal.theme()
I note this list of functions available from php - but I'm assuming the javascript version is a subset?
Answer: These are the JS theme functions defined by core:
Tabledrag

Drupal.theme.prototype.tableDragChangedMarker
Drupal.theme.prototype.tableDragIndentation
Drupal.theme.prototype.tableDragChangedWarning

Vertical Tabs

Drupal.theme.prototype.verticalTab

Overlay Module

Drupal.theme.prototype.overlayContainer
Drupal.theme.prototype.overlayElement

Many contrib modules also define their own theme functions, it's not possible to list all of those here so your best best is to run a grep -nr "Drupal.theme.prototype" /path/to/drupal and see what's available in your own installation.
It's also worth bearing in mind that individual theme functions will only be available in the page if the file that contains them has been included. So if the Overlay module is disabled, for example, the related theme functions won't be available. If the vertical tabs JS hasn't been added that won't be available, and so on.
Comment: thanks Clive - that is a small subset isnt it? I was hoping for a longer list of useful list/table contructs. oh well. Grep tip is very nice too.


How to find the index of a class instance in a list from the attribute

Question: I have a list of all instances of a class. I am tring to find out the index of the instance in that list given an attribute value.
for eg. I have the following code:
class Test():
    all_objects=[]
    def __init__(self,name,age):
        self.name = name
        self.age = age
        Test.all_objects.append(self)

Test("joe",23)
Test("kate",16)
Test("adam",56)

#this is ugly ..
for ind,item in enumerate(Test.all_objects):
    if item.name == 'joe':
        print(ind)

I can find the index of the instance by iterating over each element in the list. Is there a better way to do this? (perhaps using the index() method somehow)
CLARIFICATION:
I was looking for a way to do this without having to iterate over the all_objects list. Looking at the comments and answers below, it seems like there might not be a way around this.
I thank you all for confirming this for me.
Comment: No way to do it without iterating.
Comment: If instance names are supposed to be unique, maybe you want to use a dictionary instead of a list for `all_objects`?
Comment: `[obj.name for obj in Test.all_objects].index('joe')`?
Comment: it is not ugly - it is very readable - and I use only this method as preferred.
Answer: Using functional programming ⬇
my_filter = filter(lambda x: x[1].name == 'joe', enumerate(Test.all_objects))
print(next(my_filter)[0])

One liner ⬇
print(next(filter(lambda x: x[1].name == 'joe', enumerate(Test.all_objects)))[0])

One liner and prints Not Found when the specified instance is not found ⬇
print(next(filter(lambda x: x[1].name == 'joe', enumerate(Test.all_objects)))[0], 'Not Found')

Answer: If you want to search many times maybe create a dict with the name and its associated object:
objects = {i.name: i for i in Test.all_objects}

Now you can access the objects by its name:
a = objects['joe']

Obviously that doesn't work if there are multiple objects with the same name you can overcome that by using a defaultdict:
from collections import defaultdict

objects = defaultdict(list)
for i in Test.all_objects:
    objects[i.name].append(i)

Now every key has a list of objects.


Do young singers need to rotate their roles but not older ones?

Question: This question is based on the following line in the Wikipedia article on Éponine (a character from Les Miserables):

Éponine is also featured in the stage musical adaptation. She is played by two actors, a young girl for Young Éponine in the Montfermeil scenes, and by a young woman for the adolescent Éponine in the later Parisian scenes. Actresses playing Young Éponine and Young Cosette sometimes interchange roles in different performances to equalize performance opportunities and vocal strain.

(emphasis mine)
Is this something only young actresses do, and not older ones? If so, why - is there a biological explanation, or something else? The sentence is not cited, so it could also be wrong, in which case that would also be an answer.
Answer: This sounds unlikely. The young Cosette is a relatively demanding singing role for a child. The young Eponine is a silent role, so presumably far easier to cast. Since there are usually strict limits on how often children are allowed to perform, it would be illogical to 'waste' a valuable Cosette and have her play Eponine. But maybe they do it anyway to give their Cosettes a break from singing.
For a different show with two similar child roles (e.g. 'The Sound of Music'), companies will often train children for both parts so they are more flexible in their planning.
Comment: @Allure This is about professional theater. Normally it's forbidden to employ children, but there are certain exceptions like for theatres. There's always an upper limit on how many days a year a child is allowed to work.
Comment: Might be nice to address the broader topics of voice care. I'm not sure that "cast management practices" is on-topic here, but "taking care of your voice" is.
Comment: @AndyBonner Voice care is already covered in numerous other questions here. I don't think the question is quite off-topic, but I agree it's borderline.
Comment: Any idea why there are usually strict limits on how often children are allowed to perform? I'm again wondering about a biological explanation, if there is one.


Let $\sum_{n=0}^\infty \frac{(-1)^{n+1}}{3 n+6 (-1)^n}$, does it converge or does it diverge?

Question:
Let $\displaystyle \sum_{n=0}^\infty  \frac{(-1)^{n+1}}{3 n+6 (-1)^n}$, does it converge or does it diverge?

I'm not completely sure that my calculation is correct, check it please.
$$\begin{align}\sum_{n\ge 0} \frac{(-1)^{n+1}}{3 n+6 (-1)^n}&=-\frac13\sum_{n\ge 0} \frac{(-1)^{n}}{n+2 (-1)^n}\cdot\frac{(-1)^n}{(-1)^n}\\&=-\frac13\sum_{n\ge 0} \frac1{n(-1)^n+2}\\&=-\frac13\lim_{m\to\infty}\left(\sum_{n=0\\ 2\mid n}^m\frac1{n+2}+\sum_{n=0\\ 2\nmid n}^m\frac1{-n+2}\right)\\&=-\frac13\lim_{m\to\infty}\left(\sum_{n=2\\ 2\mid n}^{m+2}\frac1{n}-\sum_{n=-2\\ 2\nmid n}^{m-2}\frac1{n}\right)\end{align}$$
If $m$ is even then
$$\begin{align}\lim_{m\to\infty}\left(\sum_{n=2\\ 2\mid n}^{m+2}\frac1{n}-\sum_{n=-2\\ 2\nmid n}^{m-2}\frac1{n}\right)&=\lim_{m\to\infty}\left(\left(\sum_{n=1}^{m-2}\frac{(-1)^{n}}n\right)+\frac1m+\frac1{m+2}+1\right)\\&=-\log (2)+1\end{align}$$
If $m$ is odd then
$$\lim_{m\to\infty}\left(\sum_{n=2\\ 2\mid n}^{m+2}\frac1{n}-\sum_{n=-2\\ 2\nmid n}^{m-2}\frac1{n}\right)=\lim_{m\to\infty}\left(\left(\sum_{n=1}^{m-1}\frac{(-1)^{n}}n\right)+\frac1{m+1}+1\right)=-\log (2)+1$$
Then finally
$$\bbox[2pt,border:yellow solid 2px]{\sum_{n=0}^\infty\frac{(-1)^{n+1}}{3 n+6 (-1)^n}=\frac{\log(2)-1}{3}}$$
Are my calculations correct?
Answer: One may set
$$
S_N=\sum_{n=0}^N \frac{(-1)^{n+1}}{3 n+6 (-1)^n},\quad N\ge0, \tag1
$$ giving
$$
\begin{align}
S_{2N}&=\sum_{p=0}^N \frac{-1}{6p+6}+\sum_{p=1}^{N} \frac{1}{6p-9}
\\\\S_{2N}&=-\frac16+\frac13\log 2+\psi\Big(N-\frac12 \Big)-\psi\left(N+2 \right) \tag2
\end{align}
$$ and, as $N \to \infty$, giving
$$
\lim_{N \to \infty}S_{2N}=-\frac13+\frac13\log 2, \tag3
$$
where $\psi$ denotes the standard digamma function.
Similarly,$$
\begin{align}
S_{2N+1}&=\sum_{p=0}^N \frac{-1}{6p+6}+\sum_{p=0}^{N} \frac{1}{6p-3}
\\\\&S_{2N+1}=-\frac13+\frac13\log 2+\psi\Big(N+\frac12 \Big)-\psi\left(N+2 \right)
\end{align}
$$ and, as $N \to \infty$, it gives
$$
\lim_{N \to \infty}S_{2N+1}=-\frac13+\frac13\log 2.
$$
We thus have

$$
\sum_{n=0}^\infty \frac{(-1)^{n+1}}{3 n+6 (-1)^n}=-\frac13+\frac13\log 2
$$

in agreement with your calculations.
Answer: Lemma: Suppose $a_n\to 0$ and $\sum_{n=1}^{\infty}(a_{2n-1}+a_{2n})$ converges. Then $\sum_{n=1}^{\infty} a_n$ converges.
Proof: Let $S_n$ denote the $n$th partial sum of $\sum a_n.$ The hypotheses imply that $S_{2n}$ converges. Since $S_{2n+1} = S_{2n} + a_{2n+1}$ and $a_{2n+1}\to 0,$ $S_{2n+1}$ also converges. This implies $S_n$ converges.
In our problem, we have $a_n\to 0.$ We also have
$$a_{2n-1}+a_{2n} =\frac{1}{3(2n-1) -6}-\frac{1}{3(2n)+1) -6} = \frac{15}{(6n-9)(6n+6)}.$$
Thus for large $n,$ $a_{2n-1}+a_{2n}$ is positive and on the order of $1/n^2.$ It follows that $\sum (a_{2n-1}+a_{2n})$ converges. By the lemma, $\sum a_n$ converges.


Opencart PayPal Express Error 18112

Question: When we have a lot of product options in opencart, it causes the description passed through to paypal express to be longer than 127 characters.  Because of this, when we return to the cart to confirm the order, we get error 18112 - "The value of Description parameter has been truncated."
Paypal says "This warning error message is returned if the your cart is passing through a description value that is more than the allowed limit. For PAYMENTREQUEST_0_DESC the character length limitation is 127 characters; hence if your cart passes a value that is greater than this limit, this error will be returned."
I need help figuring out how to truncate the description that paypal express receives so that it is no more than 126 characters.
Here is the section of code that handles the options descriptions.  Could anyone help me figure out how to truncate the description sent to paypal down to 126 characters?
    foreach ($this->cart->getProducts() as $item) {
        $data['L_PAYMENTREQUEST_0_DESC' . $i] = '';

        $option_count = 0;
        foreach ($item['option'] as $option) {
            if ($option['type'] != 'file') {
                $value = $option['option_value'];
            } else {
                $filename = $this->encryption->decrypt($option['option_value']);
                $value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
            }

            $data['L_PAYMENTREQUEST_0_DESC' . $i] .= ($option_count > 0 ? ', ' : '') . $option['name'] . ':' . (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value);

            $option_count++;
        }

Answer: The easiest way to do this is with substr. I'm surprised you didn't think of it since you're using utf8_substr, which appears to do the same thing.
$descr = ($option_count > 0 ? ', ' : '') . $option['name'] . ':' . (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value);
$descr = substr($descr, 0, 126);
$data['L_PAYMENTREQUEST_0_DESC' . $i] = $descr;

Comment: I know I had to use substr, but I had no idea where/how to use it.  This code is from the default paypal express module that comes with opencart.  And I already feel like an idiot, but where does the code you gave me go?  In place of another section?
Comment: Replace the line in your `foreach` starting `$data['L_PAYMENTREQUEST_0_DESC' . $i]` with the block above and that should work
Comment: Thank you so much for your help!  This is for a nonprofit site I'm creating as a volunteer.  I really appreciate your help and quick response!

Opencart PayPal Express Error 18112


MLB near perfect game

Question: To throw a perfect game a pitcher would have to get 27 batters out in a row.
How many times in MLB history has a pitcher had 26 strait outs only to allow the would be final batter to reach base?
Comment: @ThomasShields Thanks for your comment. It is good to hear from you once again. I believe this may be true in regards to a pitcher throwing a no-hitter. However, it is my understanding that in order to throw an official perfect game the pitcher would have to pitch from inning 1 through at least inning 9 (facing a minimum of 27 batters) without allowing a batter to reach base. Baseball has always provided many unique situations, without doubt I may be missing or misunderstanding something. :–)
Comment: The final batter wouldn't reach the base. If he reached the base, he would be followed by someone else, so he wouldn't be the final batter.
Comment: @corsiKa As long as the runner reaches first base safely, it would no longer constitute a perfect game (would still be a no-hitter in an error occured) regardless of whether he gets tagged out in between first and second.
Comment: technically you wouldn't have to get 27 batters out in a row; a batter could reach base on an error (other than the pitcher's) and the pitcher could still get a perfect game
Comment: Ah, you may be right :) I'll have to check the official rules after I get out of calc class
Comment: @corsiKa Not necessarily.  I can think of two ways this could happen. First, the batter could get a hit but then get thrown out trying to reach the next base, ending the game with a win for the defense.  Second, the batter could hit a walk-off homerun, ending the game with a win for the offense.  It would be great if the OP could clarify their question with a proper definition of a near perfect game.
Comment: This is far to easily found. Not a good trivia question.
Comment: @waxeagle Ironically when reviewing questions previously posted on this site, I read a number of your questions including your highest rated question (How is offside determined in Soccer?) Based on this reading I felt this question was appropriate.
Comment: @Tyson Good point on the second option (home-run). I believe it would still be considered a perfect game if the runner was tagged out between first and second, though. Getting to first, rounding toward second, and getting out I do not believe counts as reaching base. I may be mistaken in this.
Answer: According to Wikipedia, this has happened 13 times. The earliest on July 4, 1908 and the most recent on June 20, 2015.

MLB near perfect game


Fourier Transform of $xf(x)$

Question: I am not able to get the Fourier Transform of $xf(x)$ if $&ltf(x)>$  is the Fourier transform of $f(x)$ .
BTW i tried using convolution theorem but didn't work out .
Comment: Are you asking how to find FT of xf(x) given FT of f(x) is known? Its been while I read Fourier transform but I think the derivation can be found in any book.
Comment: Vedananda, could you perhaps expand on that a bit? It's not completely clear what you question is, at least not to me.
Comment: Oh... I get it now.  But it is already answered...  And you should post **such stuff** to mathematical forums...
Comment: Yes exactly Anuragsn , if i know what FT of $f(x)$ is , how do i find FT of $xf(x)$. :)
Answer: If the Fourier-transform of $f(x)$ is
$$FT[f(x)] \equiv f(k) = \int_{-\infty}^{\infty} f(x) e^{- i k x} dx$$
then
$$FT[xf(x)] = \int_{-\infty}^{\infty} x f(x) e^{- i k x} dx $$
$$ = \int_{-\infty}^{\infty} i \frac{\partial}{\partial k} \Big[ f(x) e^{-i k x} \Big] dx
= i \frac{\partial}{\partial k}  \int_{-\infty}^{\infty} f(x) e^{-i k x} dx$$
which means
$$FT[xf(x)] = i \frac{\partial f(k)}{\partial k} $$
Comment: I would add that this is in keeping with the general principle that polynomials transform to differential operators and vice-versa.
Comment: is there a typo on the second line? on the first line it states that the transform of f(k) is the integration of f(x) and "k" appears in the exponent, but on the second line "k" still appears in the denominator but the transform was applied to "xf(x)".
Comment: I know it is possible to proceed like the previous answer if $f \in \mathbb{L}^1$ or $f \in \mathcal{S}$ (Schwartz space). Is it possible to apply the same result to other kind of functions, for example $f(x)=\frac{x}{1+x^2}$?

Fourier Transform of $xf(x)$


How to disable new user registered email to admin

Question: When a new user registers, there's an email sent to the admin in the form:
Subject: Account details for [name] at [site name] (pending admin approval)
Message: [Name] has applied for an account.
[profile URL]
How can I remove this email alert? The reason being, that I've created a customised message triggered by the Apply for role module.
Thanks.
Comment: Which version of Drupal are you running?
Comment: Possibly dup of http://drupal.stackexchange.com/questions/3070/disable-register-email-notification?rq=1
Comment: That one seems to refer to the e-mails sent to the registrants, not the site admins.
Answer: This email is not configurable via the UI.
You can use hook_mail_alter(), which will allow you to stop the sending of a message.
So you would create a custom module that does this:
<code>/**
 * Implements hook_mail_alter().
 */
function MODULE_NAME_mail_alter(&$message) {
  // Stop the default drupal email that goes out to admins when a user
  // registers on the site. An alternative email is sent out via other means.
  if ($message['key'] == 'register_pending_approval_admin') {
    $message['send'] = FALSE;
  }
}
</code>


Derive a procedure to select one of the 2 options with equal probability when we are not using a fair coin.

Question: Derive a procedure to select one of the 2 options with equal probability when we are not using a fair coin.

$P(\text{H}) = p$.
$P(\text{T}) = 1 - p = q$.

I came up with the following two-roll outcomes:

$P(\text{HH}) = p^2$.
$P(\text{HT}) = pq$. Let the event $\text{HT}$ be $A$.
$P(\text{TH}) = qp$. Let the event $\text{TH}$ be $B$.
$P(\text{TT}) = q^2$.

If $\text{HH}$ or $\text{TT}$ is hit we repeat the toss until $A$ or $B$. So
\begin{align}
P(A) & = pq + (p^2 + q^2)pq + (p^2 + q^2)^2pq + \ldots \\
& = pq(1 + (p^2 + q^2) + (p^2 + q^2)^2 + \ldots) \\
& = pq\left(\frac{1}{1 - (p^2 + q^2)}\right) \\
& = \frac{p(1 - p)}{2pq} = \frac{p(1 - p)}{2p(1 - p)} = \frac 12.
\end{align}
Now we want to solve for a different number other than 1/2, i.e., 1/3 or 3/4
where some solution is done in a fixed amount of N flips. How do we find a formula for this?
Answer: Your solution does not have a guaranteed fixed bound $N$ on the number of biased coin flips required. The expected number of flips is finite, and the procedure runs forever with probability $0$ (so it can't happen), but for any arbitrarily large $N$ there is a small probability that your procedure will require more than $N$ flips. So if that is ok with you, then here is how you get any target probability $p_1$. You use your procedure as a subroutine so that you can get a stream of fair coin tosses. Then, for a given target probability $p_1$ that you can iteratively compute the binary expansion for, you flip your fair coin until you get heads. If it takes $N$ fair coin flips until you get heads, then you declare event $A$ if the $N$th binary digit in the expansion of $p_1$ is $1$, and you declare event $B$ if the $N$th binary digit in the expansion is $0$. This procedure has a finite expected number of flips, and the probability that you get infinitely many flips is $0$, although again, for any arbitrarily large $N$ there is a small probability that the procedure will require more than $N$ flips of your original biased coin.


Updating 7 to 8, how to remove .less / scss files

Question: I am updating a website from Drupal 7 to Drupal 8 and suddenly I see all these .less files influencing the style of the page. I found them in the theme's /srss directory (mytheme/srss/bootstrap/)
When I look at the current Drupal 7 version of the site, the navbar.less and navs.less files are not referenced.
On the Drupal 8 version of the site, I see navbar.less and navs.less styling the menu links. Turning off their attributes (in the browser only), specifically padding and margins, puts things back closer to where they are supposed to be.
Deleting or moving the _navbar.less and _navs.less files does nothing. Even after clearing the cache.
How do I remove or neutralize these *.less files from my site?
Comment: Browsers don't normally interpret .less files, they interpret CSS files which are compiled from those .less files. If you have sourcemaps, some browsers will use those to show you the .less files that originally created the CSS, maybe that's what you're seeing. It's probably the CSS files you need to change (or the .less files, and then re-compile them)
Comment: For less you would recompile the less files, not the sass files. Maybe you have the less browser plugin enabled and that's doing something. Difficult to say without more info about the site and how it's all configured to be honest
Comment: It's commented out in the /scss/bootstrap.scss on both the prod (D7) and this dev (D8) version. Plus the CSS is the same so I am still not sure how it suddenly got started being used.  I think I have to look at re-running the SCSS to rewire things(?).
Comment: Doesn't sass configure compiling to less files?  The theme is a sub of bootstrap, the theme files were copied from the Drupal 7 site and I have modified the .tpl.php to .html.twig and the preprocessing in the .theme file (for things Drupal 8 doesn't do anymore). In the Developer window of the browser I see the Styles of the Elements and it shows the source (navbar.less) and the entry (.navbar-nav > li > a). But only on the D8. Same item on the D7 site and no reference to navbar.less on any element in the page.  What else would help?
Comment: Deleting the Less files should be considered harmful. These are CSS preprocess files. To build your CSS from maybe with Gulp or Grunt. No one writes pure CSS these days anymore. Everybody uses some CSS preprocessor like Less. Or Sass.
Comment: Seems the issue is completely different. The theme is based on bootstrap and In Drupal 7 the theme did not have a CDN provider option but in Drupal 8 it is defaulted to `jsDelivr`. The _navbar.less_ and _navs.less_ references came from the CDN stylesheet [link](https://firstname.lastname@example.com/dist/css/bootstrap.css). Changing the theme's CDN Provider to "None" removed the reference and these LESS file references are gone (as well as their styling). So it was a change in Bootstrap from Drupal 7 to Drupal 8 issue introducing the CDN (and about 20+ /core stylesheets).
Answer: Seems the issue is completely different. The theme is based on bootstrap and In Drupal 7 the theme did not have a CDN provider option but in Drupal 8 it is defaulted to jsDelivr. The navbar.less and navs.less references came from the CDN stylesheet link. Changing the theme's CDN Provider to "None" removed the reference and these LESS file references are gone (as well as their styling). So it was a change in Bootstrap from Drupal 7 to Drupal 8 issue introducing the CDN (and about 20+ /core stylesheets).


Why does airflow's `last run` date not actually show the last run date?

Question: In the dags listing \admin I see my dag and the last run column shows 2021-04-30 19:31 which is a run I triggered manually. But going to /admin/taskinstance/ it shows it actually ran on schedule at 2021-05-01 03:50 (according to the docs I expected it to show about 1 hour later, at 2021-05-01 04:50 which is what the database shows).
So what gives? Why does airflow not actually show the last run date in \admin?
For reference, here's my dag definition:
ranking_generator = models.DAG(
    dag_id="activity_ranking_generator",
    schedule_interval="50 3 * * *",
    start_date=datetime.datetime(2021, 4, 28),
    catchup=False,
    max_active_runs=1,
)

Comment: Can you please add screenshots. I'm not sure I follow on what exactly is the issue.
Answer: I got it, the date shown in the dag listing seems a day late. You can see it when you go to the task instances (browse - task instances) listing, the execution date is always 1 day before the start date, it's the start date that shows when it actually ran.. I'm guessing the execution date (what is shown as Last run in the dag listing) shows when it was scheduled and it executes 1 day after that date (it's a daily task) so that's why it seems wrong.. Had read about this but still got confused. Anyway, looks good now.


Css links inside text

Question: This might be simple to answer ..I have a div inside which I have some text and in that text there can be some links also eg hello http://google.com hello http://bing.com.
The question is how can I make those links appear as hyperlinks using css.
Thanks
edit:
I just saw that after posting this question the links were automatically displayed as hyperlinks.I need the same thing.
Answer: That's not a requirement that CSS can solve AFAIK.  You need to use something like Javascript to process the text inside the DIV to find things that are URL-like and put anchor tags around them.  In the case of what happened when you submitted your answer, my guess would be that the server-side code on Stackoverflow did the same thing, just on the server not rendered live in your browser.
Answer: There isn't a pure CSS solution to turning URLs into links.
Here is an example of a PHP code snippet that does exactly that: http://css-tricks.com/snippets/php/find-urls-in-text-make-links/
And this SO answer has a solution using Javascript, which is arguably more elegant:
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"$1");
}

https://stackoverflow.com/a/37687/1512956
Answer: try this one

   Google
   yahoo

DEMO http://jsfiddle.net/rSpMV/1/
Answer: You need to use something like javascript to solve this issue.
just like this:
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"$1");
}

Please check this: stackoverflow question

Css links inside text


Filtragem por período em inputs do tipo data

Question: Tenho um sistema onde possuo um <input type="date"> e preciso filtrá-lo, para trazer no calendário apenas as datas de 3 meses atrás e do mês atual
Eu estava utilizando os atributos min e max para teste, pois eles são valores fixos, e funcionava:
<input type="date" name="dateIni" min="2013-12-01" max="local">

Porém, preciso alterar manualmente toda vez que vira o mês. Como automatizar isso?
Comment: A pergunta está pouco clara para mim. Você quer dizer um input type date com calendário (HTML5) e que quer limitar a escolha possivel de datas para max 3 meses antes do dia actual?
Comment: Qual é o plugin de calendário que você está utilizando? Poste um exemplo de código para podermos ajudar! xD
Comment: Isso. Segue o exemplo. Date:
Comment: Só para deixar claro, você quer que ao carregar a página o `min` seja setado para `data_atual - 3 meses`?
Comment: Sim e a max a data de hoje.
Comment: Fiz um update ao código. Era essa a função que queria? Funciona para mim no Chrome.
Answer: Tente assim:
function decimas(n){
    return n > 9 ? "" + n: "0" + n;
}
function getDate(m) {
    var data = new Date();
    var diffAno = 0;
    var mesAnterior = data.getMonth() - (m === undefined ? 1 : m - 1);
    if (mesAnterior < 1) {
        mesAnterior = mesAnterior + 12;
        diffAno = -1;
    }
    mesAnterior = decimas(mesAnterior);
    var diaAnterior = decimas(data.getDate());
    return (data.getFullYear() + diffAno) + '-' + mesAnterior + '-' + diaAnterior;
}

document.querySelector('input[name=dateIni]').setAttribute("min", getDate(3));
document.querySelector('input[name=dateIni]').valueAsDate  = new Date();

Exemplo
Tenha em conta que input type date é +/- recente (HTML5) e que muitos browsers não reconhecem essa tag. Talvez melhor usar uma bibleoteca que tenha um date picker separado.
Acrescentei a função decimas() porque a recomendação da W3C é usar dois digitos na data.
Comment: @HaoneNakano, este script lê a data do dia actual e retira 3 meses. Depois aplica a data ao input


Algorithms for encryptor in RSA

Question: In RSA we denote encryptor as $E$ such that:
$$\gcd(E,\phi(p,q))=1\tag{where $p,q$ are primes}$$
I know if for all prime factors $c$ of $\phi(p,q)$, $c \not\mid E$, that we can choose this $E$ as a encryptor, since in this case gcd is $1$.

What I did is for example:
$$p=331,q=233,\phi(p,q)=(331-1)\cdot(233-1)=76560$$
Since $76560=2^4\cdot3\cdot5\cdot11\cdot29$, the smallest $E$ that would work is next prime after $5$ which is $7$.
Basicly, this is like looping though all the primes $P=\{2,3,5,7\cdots\}$, if it's not in the prime factor of $\phi(p,q):F=\{2,3,5,11,29\}$, then it's a valid choice of $E$.
So we can denote the smallest $E$ as the following:
$$\min(P\cap F^c)$$

This is the algorithm i'm using right now, is there better approaches
to find such $E$ ?
And there are many choice of $E$, but I don't know smaller $E$
is better or larger $E$ is better, would there be any difference if I
pick different $E$ in RSA ?

Any help or suggestion would be appreciated.
Answer: Normally we use $\gcd(e,\lambda(n))=1$ as the criterion, where $\lambda(n)$ is the Carmichael function of the modulus $n$, for $n=pq$ this equals the least common multiple of $p-1$ and $q-1$, almost always smaller than $\phi(pq)=(p-1)(q-1)$.
Also, $p$ and $q$ are normally chosen beforehand with the property that $p-1$ and $p+1$ have no small prime factors except (the unavoidable) $2$. This to avoid some attacks.
This means that choosing $e=3$ is then always possible, and this is OK when using proper OAEP padding etc and almost always $e=2^{16}+1$, which are both very efficient for encrypting. If not, try the next prime, e.g.
See the key generation section of the Wikipedia page for more info and references.
Comment: Maybe you should also add that, when using 3 in textbook RSA, cuberoot attack is also possible and many other attacks therefore we use RSA encryption with proper paddings like PKCS#1.5 and OAEP...

Algorithms for encryptor in RSA


Creating new Virtual Machine in Microsoft Hyper-V server 2012 r2

Question: I am new to Windows Hyper-V server 2012 r2, trying to create new virtual machine in ther Hyper-V server.
Try to follow http://www.danielclasson.com/guide-how-to-create-and-configure-virtual-machines-in-hyper-v-server-2012-using-powershell/
But got stuck in *.iso file for the Windows installation:
Not able to copy iso file within the hyper-v server.
Any proper step should i follow, suggestions, help.......
thanks in advance
Comment: What command are you executing? What is the error message you see?
Comment: I am not able to locate the iso file, meant i was not able to bring it to the hyper-v server itself.
Comment: The iso needs to be on a disk that the host can access.
Comment: meant i should use a bootable disk to start the VM? ok thanks
Comment: Now things all went fine, but when i start the VM "
Start-VM –Name DC" getting error " The Virtual Machine Management Service failed to start the virtual machine, because one of the Hyper-V components is not running
Answer: 1) Make sure that Intel VT and all virtualisation capabilities like VT / V and Trusted Execution Prevention / Data Execution Prevention are enabled in BIOS (it may have other names in your BIOS).
2) Make sure your BIOS is up to date
3) Please refer following URL for Wordkaround suggested at MSDN:
https://msdn.microsoft.com/en-us/library/windows/hardware/ff545448(v=vs.85).aspx#when_to_use_dv
This workaround suggests that disabling the I/O verification option in Driver Verifier for all drivers on the hostcomputer resolves this issue.
https://support.microsoft.com/en-us/kb/2761004
Answer: Above information is useful but I also find the step by step way to install windows os in hyper v manager in windows server 2012 at following links
http://www.ittechpoint.com/2016/04/how-to-install-windows-os-in-hyper-v-manager-in-windows-server-2012-R2.html
Comment: This looks like a link only answer ...


SCCM OSD "no task sequences available for this computer"

Question: I keep running into the scenario were SCCM OSD has failed to find any task sequences advertised for the current computer and I need to delete a computer accocation and re-add it. When I re-add the computer thru computer association the computer never shown in the collection I have created for the OSD advertisement. It seems like the mac address is still referenced some where in SCCM so I can't re-add it.
How do I track down where the MAC address is listed and clean out the references so I can re-add it to SCCM.
Thanks,
Dean Miller
Answer: Through the built-in default SCCM reports you should be able to find a report called "MAC - Computers for a specific MAC address" (under the Network category). Just put your MAC address in there (colon separate the character pairs in the MAC) and search, it should back with any SCCM known machines with that MAC that you can then look for in the main console and delete.
Alternatively (and slightly more work), create a new collection, create a query membership rule with a criteria something like "Network Adapter" - "MAC Address" and put your MAC in as the value. It should now list any known machines with that MAC.


Fundamental Theorem of Calculus

Question:
Suppose that $f: \mathbb{R} \rightarrow \mathbb{R}$ is differentiable at every point, and that $f'(x)$ is continuous.
1) Prove that $\displaystyle\int_0^1 \left( \int_0^1 \left(f'(x)f(y)-f(x)f'(y)\right)^2 \ dx \right) \ dy \geq 0$
2) Hence prove that $2\displaystyle\int_0^1 f'(t)^2 dt \int_0^1 f(t)^2 \ dt \geq \dfrac{1}{2} \left(f(1)^2 - f(0)^2 \right)^2$

Ok, so I've done 1) quite easily using the fact that since the inside integral is a square, this implies that the integral is $\geq 0$ then using the same theorem this implies that the outside integral also gives something $\geq 0$.
Now, in regards to 2) I've tried doing this a number of ways but it doesn't seem to fall out properly. Clearly the Fundamental Theorem of Calculus needs to be used at some point but every way I've tried doing it doesn't actually help. Thanks for any help!
Answer: Using the Cauchy-Schwarz inequality, $2\int_0^1 f'(t)^2\,dt\int_0^1 f(t)^2\,dt\ge 2(\int_0^1 f(t)f'(t)\,dt)^2=\frac{1}{2}(\int_0^1 (f(t)^2)'\,dt)^2=\frac{1}{2}(f(1)^2-f(0)^2)^2$ where I have used that $(f(t)^2)'=2f(t)f'(t)$.
Note that if you don't want to use the Cauchy-Schwarz inequality, you can use 1) and write $0\le \int_0^1(\int_0^1(f'(x)f(y)-f(x)f'(y))^2\,dx)\,dy=\int_0^1(\int_0^1 f'(x)^2f(y)^2+f(x)^2f'(y)^2-2f'(x)f(x)f'(y)f(y)\,dx)\,dy\implies 2\int_0^1 f'(x)f(x)\,dx\int_0^1 f'(y)f(y)\,dy\le2\int_0^1\int_0^1 f'(x)^2f(y)^2\,dx\,dy=2\int_0^1 f'(x)^2\,dx\int_0^1 f(y)^2\,dy$
this gives $\frac{1}{2}(\int_0^1 (f(x)^2)'\,dx)^2\le \int_0^1 f'(t)^2\,dt\int_0^1 f(t)^2\,dt$, or using the fundamental theorem of calculus, $\frac{1}{2}(f(1)^2-f(0)^2)^2\le \int_0^1 f'(t)^2\,dt\int_0^1 f(t)^2\,dt$.

Fundamental Theorem of Calculus


Virtual Box and Multiple IPs

Question: I've got several VMs set up here, all running linux (mostly centos but 1 ubuntu).  I connect to them over SSH, but it's annoying having to go back to the VM server to check on IP addresses.  Also, on reboot they usually get a different IP due to the network setup here, which I have no control over.
What's the easiest way for me to track all the IPs that my VMs are using?
Answer: A lot of your options depend on your exact network configuration.  Most of the easy options involve some network modification, which you indicate is not the case.  Here are some options given that constraint:

If you use a Microsoft DHCP server integrated with Active Directory, then you may be able to register the hostname with the Active Directory, and inherit a DNS name.  Check out http://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-dhcp-configuring-client.html  I believe that DHCP_HOSTNAME needs to be set.  I've never actually done this, so there may be additional steps to make this work within a Microsoft context (perhaps having all the machines joining the domain, etc).
If your looking for a pure Linux solution, you may want to look at the avahi daemons.  It uses multicast DNS to push hostnames and services on a local network.  Assuming avahi is running on all your boxes, you should be able to edit /etc/nsswitch.conf, verify that mdns4 or mdns4_minimal is included on the hosts line, and should be able to resolve the hostname for all your servers directly.  Again, I've not set this up in a production environment, so there might be other configuration that is required.

Both of these are pretty messy, so your much better off working with whomever manages your network to get static IPs and DNS names, as Chopper3 mentions.  You might even be able to get away with static DHCP assignments, and then modify the hosts files, but again requires cooperation of your network team.
Comment: +1 to everything said here.  Absent any possibility of cooperation from your netops team, I'd say that mDNS is probably going to be your least-worst option.
Comment: I wish I could mark more than 1 item as accepted answer - this is a great solution... both this and the NAT solution work.
Answer: Setup a cronjob that makes a wget to a .php file that tells the hostname of the machine and the ip and you done.
Comment: I would only get it at boot time, but yeah, good idea.
Answer: Is it a requirement that you use bridge mode, versus NAT mode?  Cause of course if you have NAT enabled, then you could forward various different ports for your ssh access, and the IP (and of course port) would remain constant through reboots.
You can find details on this in the VirtualBox 3.1.2 user manual, section #6.3.1 "Configuring port forwarding with NAT".
Another thought:  I cannot help but notice that my IP address shows up in my virtual machine's XML file:
    <GuestProperty
        name="/VirtualBox/GuestInfo/Net/0/V4/IP"
        value="10.0.2.15" timestamp="1261587087753023000"
        flags=""/>

(On linux, you can find this in ~/.VirtualBox/Machines/MyVMName/MyVMName.xml)
So especially if you are using vboxmanage to start/stop your VMs, you could grep the machine's xml and update "something" -- like a web page, or a text file? -- so you'd always know the IP address of each VM.  I'm guessing this will work regardless of whether you're using NAT or bridged networking, though I haven't personally tried it...I have a static IP in my VM.  I don't know who/when/where this value gets updated in the XML file.  Presumably VBox updates it when it detects a DHCP reply it needs to redirect to the VM.
Answer: When the machines get an IP address via DHCP on the network, do they not get DNS as well?
eg. you should be able to connect to them via their hostname, which would stay static.
You could run all the virtual machines within their own "Virtual Network" and run your own DHCP/DNS/router which connects to the real network, but you'd still need your network admin to add route/dns forwarding which he might not like.
The other way of doing it, and which would leave you in some control, would be to cheat and use one of those external dns services. eg:
dyndns.org is a free service that lets you have a static hostname that gets mapped to a dynamic IP address. They also have a tonne of clients for various OS's to keep this upto date. Usually, you'd have this set to an external address (eg your home router) so you can just remember myhouse.dyndns.org rather than 184.108.40.206 or whatever its changed to recently.
In your situation, I would do similar for each of your virtual machines. Set yourself up an account and get a hostname for each machine. Install the client tell them to keep updates. So you end up with myvirt1.dyndns.org and it points to 192.168.x.x or whatever IP you've just been given.
-saying that, could you not just ask your network admin for a block of static address's?
Answer: Static IP's and a text editor
Comment: I don't have the option to use static IPs, as I mentioned above.
Comment: Ah, sorry, kind of misread/musunderstood that.

Virtual Box and Multiple IPs


Is this true about Fermat Primes?

Question: Let every prime of the form $2^n+1$ be called "Fermat Prime" (I know that the real definition is by using $2^{2^{n}}+1$, but I will use the other one to get things easier). By definition, we have that $p$ will be a Fermat Prime if and only if it is prime and it is not of the form $qn+1$ for any prime $q$ such that $2<q<p$.
Then, by Dirichlet Theorem on arithmetic progressions, we have that, as $N \to \infty$, the number of primes of the form $qn+1$ lower than $N$ will tend to be the same than the one of primes of the form $qn+2$ and of the one of the primes of the form $qn+3$; and like this up to $qn+(q-1)$.
So, to know the number of Fermat Primes as $N \to \infty$, we have that:

Only the primes of the form $3n+2$ can be a Fermat Prime. Then, as $N \to \infty$, The number of FM will be lower than $\pi(N)\frac{1}{2}$.
Only the primes of the form $5n+2, 5n+3$ and $5n+4$ can be a Fermat Prime. Then, as $N \to \infty$, The number of FM will be lower than $\pi(N)\frac{1}{2}\frac{3}{4}$.
...

If we continue like this, we would get that:
$$\lim_{N \to \infty}\pi_{\text{FermatPrimes}}(N)=\lim_{N \to \infty} \pi(N)\prod_{p>2}\frac{p-2}{p-1}=K \lim_{N \to \infty} \frac{\pi(N)}{\log{(N)}}$$
Which clearly diverges.
Is this true?
Comment: @Eric But let $p$ be a Fernat Prime. As $p-1=2^n$, the only factor than $p-1$ can have is 2. From here, you get to the conclusion that if a composite number has a divisor ($q$) greater than 2, that number plus 1 cannot be a Fermat Prime
Comment: In your notation, Euler proved that factors are of the form $2q n+1$ and Lucas that they are of the form $4 q n+1$.  These are incompatible with your "$qn+1$ for any prime $q$ such that $2<q<p$."
Comment: @user3141592 : And how does this make either $2q$ or $4q$ prime, as you have stated?
Comment: You actually have made the vacuous statement that the only numbers that can be Fermat primes are Fermat numbers.  That is, yes, all Fermat primes are a power of $2$ plus $1$.  Of course, all Fermat numbers are a power of $2$ plus one, so you have not said very much.
Comment: Additionally, you are doing neither your argument nor your reader any favors by using nonstandard notation.
Comment: @Eric What I have stated is that if $qn$ is not a power of two, $qn+1$ cannot be a FP
Comment: Since I can't make head or tails of how that claim fits with what you've already written, let's start very simply:  Where do you declare $p$, what is it, and what constraints does it have?
Comment: Yes, if $qn$ is not a power of two, $qn+1$ isn't even a Fermat *number*.
Comment: If I understood your process correctly, it would also "show" that there are infinitely many Mersenne primes. After all, a prime $p$ is a Mersenne prime if and only $2$ is the only prime factor of $p+1$.
Answer: Your derivation (or rather, your heuristic, since there are issues of convergence of the limiting process to deal with) only gives necessary conditions for primes to be Fermat primes, not sufficient conditions. Therefore the expression you derive is simply an upper bound, not an asymptotic formula.
Comment: I understand what you mean, but could you give any example of another condition that Fermat Primes should deal with?
Comment: Greg, there is nothing wrong with the sieve. A prime is $p$ is a Fermat prime if and only if $2$ is the only prime divisor of $p-1$ if and only if $p\not\equiv1\pmod q$ for any odd prime $q<p$. The explanation, as you implied, probably has something to do with the convergence of the various limiting processes here. For example, it takes time for the Dirichlet densities to average out, and early on there may larger deviations from the average and/or larger deviations from independence. Because those appear as factors here, a handful of factors smaller than the expected $(p-2)/(p-1)$...
Comment: (cont'd) may bring the density of Fermat primes to zero. I am too fluish to think straight. I will ask a colleague.
Comment: @Greg Thank you very much! I see your point, but I do not understand why are you saying that "it takes time for the Dirichlet densities to average out", as I am working with a limit tending to Infinity. Could you please tell me exactly where is the error in my question? Also, could you explain to me what do you mean with "Problem of convergence"?
Comment: @Jyrki Sorry, I did not want to mention Greg but you
Comment: @user3141592: The point was that the estimate of the factor $(p-2)/(p-1)$ is not exact, when you are only counting primes up to $N$. That factor is of the form $1-\big(1/(p-1)+ E(p,N)\big)$, where $E(p,N)$ is an error term that for a **fixed** prime $p$ tends to $0$ when $N\to\infty$. But the estimates of that error term (I'm too ignorant to say how large they can be for relevant size $p$ and $N$) may make that product a lot smaller.
Comment: Also, similar error terms appear when we look at the distributions of the primes w.r.t. several moduli $p_1,p_2,\ldots$. Your product formula assumes these are independent. Asymptotically they are, but at any finite point the non-independence introduces yet other error terms.
Comment: The convergence issue might be described as saying that at any finite point $N$ you have many primes (notably those relatively large in comparison to $N$) with respect to whom $N$ is not large enough for the asymptotics to have kicked in.
Comment: To drive the point home: If $p$ is comparable to $N$, the primes $<N$ cannot be equidistributed among the residue classes modulo $p$. This is because there are $p-1$ such residue classes, but only $\pi(N)\ll p$ primes.
Comment: @Jyrki Thank you, that's nice. But, for what you have salid, I understand that both the error term $E$ and the "Convergence issue" occurs when we set a finite value to $N$, but they both tend to dissappear when $N \to \infty$
Comment: I don't see why they would disappear. As $N$ grows you get more and more of those error terms. The "convergence issue" is, perhaps, just an umbrella phrase for all the difficulties you get from having to deal with an increasing number of error terms each going to zero individually, but new ones popping up constantly.
Comment: @Jyrki Sorry if I seem to insist a lot, but this time I do not really see your point. By Dirichlet's theorem, the error term regarding the primes of the form $pn+1$ will decrease as $N \to \infty$. For example, the number of primes of the form $3n+1$ will tend to be a half of the total. I see that if you apply that to $\pi(N)$ for a finite $N$, there will obviosly be an error term. But it will also tend to disappear as $N$ gets bigger. And this, applied here to 3, could be extended to any prime $p$
Comment: I told you. The error term coming from the prime $p=3$ does tend to $0$. When you double $N$, the error term coming from $p=3$ drops in size in some predictable fashion. But, when you double $N$ you get new error terms from all the primes $p\in[N,2N]$. That's a lot of primes with still large error terms. Your formula for $\pi_{FermatPrime}(2N)$ has a product over all those primes $<2N$, and therefore may have a large error term.
Comment: @Jyrki Setting a finite 2N, that is true. But, for $N \to \infty$, would't $N$ be big enought to solve the error term problem for every prime? I think that the main problem between my idea and yours is how big of an infinity are we talking about
Comment: For the error term $E(p,N)$ to be small, $N$ needs to be large in comparison to $p$. For the total error to be small $N$ needs to be large in comparison to all the primes $p$. That is impossible.
Comment: @Jyrki By "in comparison to all the primes $p$", do you mean $\pi(N)$? If so, $N-\pi(N)$ will be greater the greater $N$ is

Is this true about Fermat Primes?


Outliers and chi-squared goodness of fit

Question: Do outliers lead chi-squared tests of goodness of fit to fail?
Answer: The answer has to depend on what you are testing and how you implement a test as well as the data you have.

If one bin containing an outlier has observed frequency 1 and expected frequency almost zero, its contribution to a chi-squared test statistic may be enormous. (The usual advice is naturally: Don't do that! But it's among the possibilities.)
If you have bins with equal expected frequency, then sometimes a chi-squared test will not even notice an outlier; it may be one of several values in an open-ended bin for the highest values (or the lowest values, as the case may be).

This arbitrariness is one reason why chi-squared tests of goodness of fit are not often seen outside elementary texts and courses.
I exaggerate a bit, but in most problems better methods are available. For example, chi-square testing of normality is rarely useful compared with customised plots or even customised tests that do not entail arbitrary binning.


Pegar último login do usuário

Question: Em meu projeto me surgiu essa regra de negócio.
Preciso pegar a ultima vez que o usuário se logou no sistema. Então seria algo para que eu conseguisse pegar o dia e a hora do último login.
Já tenho a coluna criada no banco de dados chamada UltimoLogin que é um DateTime.
Alguém pode me ajudar?
Código do Controller
AutenticacaoController
 [HttpPost]
    public ActionResult Index(String Login, String Senha)
    {
        //verificando login pelo usuario do banco de dados ...
        Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();

        if (login != null)
        {
            FormsAuthentication.SetAuthCookie(login.Nome.ToString(), false);
            Session.Add(".PermissionCookie", login.Perfil);
            Session.Add("UsuarioID", login.UsuarioID);
            return RedirectToAction("Index", "Home"); // página padrão para todos os usuários
        }

        return RedirectToAction("Index");
    }

Answer: Você pode fazer assim, quando você for fazer o login do usuário sete a propriedade UltimoLogin para DateTime.Now e salve as modificações. Se esse db é uma instancia de um DbContext do Entity Framework ficaria assim
[HttpPost]
public ActionResult Index(String Login, String Senha)
{
    //verificando login pelo usuario do banco de dados ...
    Usuario login = db.Usuarios.Where(x => x.Login == Login && x.Senha == Senha).FirstOrDefault();
    if (login != null)
    {
        FormsAuthentication.SetAuthCookie(login.Nome.ToString(), false);
        Session.Add(".PermissionCookie", login.Perfil);
        Session.Add("UsuarioID", login.UsuarioID);
        login.UltimoLogin = DateTime.Now;
        db.Entry<Usuario>(login).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index", "Home"); //pagina padrao para todos os usuarios...
    }
    return RedirectToAction("Index");

}

E basicamente quando você precisar desse dado é so você pegar o valor daquela coluna. Se, como eu imaginei, você estiver usando o Entity Framework, ele já vai botar o valor pra você na propriedade UltimoLogin do objeto Usuario. A enumeração EntityState fica no namespace System.Data.Entity

Pegar último login do usuário


Can't push commits to master branch: pre-receive hook declined error

Question: Hi I'm new to using Git and I'm working on one of my Company's repositories on gitlab.  We're a small team, I have changes ready to be pushed to the master branch and I'm getting this error below when I try to do so.
remote: GitLab: You are not allowed to push code to protected branches on this project.
! [remote rejected] HEAD -> master (pre-receive hook declined)

When I try to push I'm not asked for any authentication details.  I have a personal access token with these scopes below and an SSH key that I believe was correctly set up about a month ago.  I'm not sure if that's the issue and I'm having a hard time figuring out what credentials Git is actually using.

However, I was able to create my own local branch (called jacobs_branch), added & committed my changes onto there so it's fully up to date with what I've been working on, and then pushed it to the repository as a remote branch.   But when I try to merge this branch onto master I just get the same error.  Below is a picture of our repo on gitlab.com with my new up to date branch and the older master one.

So is me not being able to push changes to the master branch an issue with me, or is it some kind of permissions thing?  I was also reading that I might need maintainer access to push to the master branch (which I probably don't have), but I'm not familiar enough to know for sure.  If there's any other info I can provide or if anyone has an idea of what's going on I'd appreciate the help!
Comment: When Git says *pre-receive hook declined*, this means Git ran some external, non-Git program that made a decision to reject your request. Git has no idea *why* this external non-Git program *made* that decision and cannot tell you; but the program that did make this decision could tell you. If it did, whatever it said, Git will copy through in the previous line(s) that say `remote:` in front of them. In this case, you got: `remote: GitLab: You are not allowed to push code to protected branches on this project.` Read that line.
Answer: someone set a permission preventing you from pushing to the master branch
there are many ways to do this based upon different vendors, but you'll need to talk with whomever owns the repository
this technique is normally used to force users to make pull requests to branches


Compute the integral $ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds\quad\text{for real}\ x>0. $

Question:
Use the residue theorem to compute the integral
  $$ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds\quad\text{for real}\ x>0, $$
  where the contour is oriented upwards. (Hint: treat the cases of $ x<1 $ and $ x\ge 1 $ separately.)

My Attempt:
Draw the semicircle $ \Gamma: 2+R\exp(i\theta), \theta\in[\frac \pi 2, \frac {3\pi}2], R>2 $.
Then $$\begin{align} \int_{\Gamma}\frac{x^{-s}}{s^3}ds &=\int\limits_{\substack{Re(s)=2\\Im(s)=-R}}^{\substack{Re(s)=2\\Im(s)=R}}\frac{x^{-s}}{s^3}ds+\int_{\frac \pi2}^{\frac {3\pi}2}\frac{x^{-2-R\exp(i\theta)}}{(2+R\exp(i\theta))^3}R\exp(i\theta)id\theta.
 \end{align}
 $$
Now let $ R\to\infty $ and by the standard trick we know that the second term on the right tends to zero and the first term on the right is $ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds\quad\text{for real}\ x>0. $ By the residue theorem,
$$ \begin{align} \int_{\Gamma}\frac{x^{-s}}{s^3}ds &=2\pi i Res(\frac{x^{-s}}{s^3}, 0)\\
&=2\pi i\frac{\ln^2 x}{2}\\
&=\pi i\ln^2 x .\end{align}$$
Therefore, $$ \int_{Re(s)=2}\frac{x^{-s}}{s^3}ds=\pi i\ln^2 x\quad\text{for real}\ x>0. $$

Am I right? I am confused that the hint says that we should treat the cases of $ x<1 $ and $ x\ge 1 $ separately, but I didn't use this fact, why?
Comment: @Reveillark By the assumption, $ x>0 $.
Comment: Reading is hard
Answer: The half-plane where $x^{-s}$ decays depends on the sign of $\log x$.

For $x \in (0,1)$ then $$\int_{\Re(s)=2} s^{-3}x^{-s}ds = \lim_{R \to \infty} \int_{\partial ([-R,2] +i[-R,R])} s^{-3}x^{-s}ds =2i\pi Res(s^{-3}x^{-s},s=0) = i\pi \log^2 x$$
For $x \ge 1$ then $$\int_{\Re(s)=2} s^{-3}x^{-s}ds = -\lim_{R \to \infty} \int_{\partial ([2,R] +i[-R,R])} s^{-3}x^{-s}ds =0$$
Comment: $[0,1]+i[0,1]$ is a filled square and $\partial([0,1]+i[0,1])$ is its boundary
Comment: boundary traversed counter clockwise (thus the minus sign in the $x\ge 1$ case)
Comment: ? It is a rectangle whose one side is $2-i[-R,R]$
Answer: Let $I(x)$ be given by the integral
$$\begin{align}
I(x)&=\int_{\text{Re}(s)=2}\frac{x^{-s}}{s^3}\,ds\tag1
\end{align}$$
For $0<x<1$, $\log(x)<1$ and we evaluate the integral of $\frac{x^{-s}}{s^3}$ over the closed contour, $C_R$,  comprised of $(i)$ the straight line segment from $2-iR$ to $2+iR$ and $(ii)$ the circular arc of radius $\sqrt{R^2+4}$ starting from $2+iR$ traversed counterclockwise and ending at $2-iR$.  Proceeding, we have
$$\begin{align}
\oint_{C_R}\frac{x^{-s}}{s^3}\,ds&=\int_{2-iR}^{2+iR}\frac{x^{-s}}{s^3}\,ds +\int_{\arctan(R/2)}^{3\pi/2+\arctan(2/R)}\frac{x^{-\sqrt{R^2+4}e^{i\theta}}}{(\sqrt{R^2+4}e^{i\theta})^3}\,i\sqrt{R^2+4}e^{i\theta}\,d\theta\tag2\\\\
&=2\pi i \text{Res}\left(\frac{x^{-s}}{s^3},s=0\right)\\\\
&=(2\pi i )\frac1{2}\left.\frac{d^2}{ds^2}\left(s^3\,\frac{x^{-s}}{s^3}\right)\right|_{s=0}\\\\
&=i\pi\log^2(x)
\end{align}$$
Letting $R\to\infty$, the second integral on the right-hand side of $(2)$ approaches $0$ and we find for $0<x<1$
$$I(x)=i\pi\log^2(x)$$
Similarly, for $x>1$, we close the contour in the right-half plane.  Inasmuch as no poles are enclosed, we find $I(x)=0$ for $x>1$.
Putting it together reveals
$$I(x)=\begin{cases}i\pi\log^2(x)&,0<x\le 1\\\\0&, x>1\end{cases}$$
Answer: Deleted comment as was unclear, so I will make it an answer; the main issue is that for $x>1$, the exponential term on the circular integral is high since $\cos(\theta) \leq 0$ on your domain, so the integral doesn't go to zero and the result is valid only for $x \leq 1$. For $x>1$ we can use the circular domain to the right so $-\frac{\pi}{2} \leq \theta \leq \frac{\pi}{2}$ and same argument works but no residue, so answer zero, or just move the vertical $s$ line to the right towards $\infty$ and use rectangles and no residue again to get zero this way
Comment: Crystal clear! Thx~~
Comment: You are welcome


Figuring out function composition

Question: If I know $f(x)$ and $f(g(x))$,
how do I figure out what is $g(x)$?
I can solve already some simple cases, but I'm looking for a general strategy.
Particularly in harder cases when just trying to figure it out is hard.
Comment: Can you provide an example that might illustrate where you're getting stuck?
Comment: I was just wondering is there any way to find solution to $g(x)$. I mean any other than just trying to figure it out.
Answer: Set $h$ so that $f(g(x))=h(x)$.
To get $g(x)$, $f$ is disturbing. $g$ is composited with $f$ from the left. You need the inverse operation. The inverse operation of composition from the left is the left inverse.
Let $f^{-1}$ denote the left inverse of $f$:
$$g(x)=f^{-1}(h(x))$$
$\ $
Let's presuppose that $f$ and $g$ are functions.
If $f$ is bijective, you can set the inverse function (compositional inverse / inverse) of $f$ for $f^{-1}$.
If $f$ is not bijective, you have to choose suitable partial inverses of $f$ for $f^{-1}$. The equation above can give you $g$ as a piecewise given function then.

Figuring out function composition