Simplify this problem from Spivak's Calculis.

Question: I'm sorry I don't have the book with me (don't know the problem number) since I moved, but I still remember the problem.
It said something about finding $\int x^n\ dx$ by letting $p_n = \int_0^1 x^n\ dx$ and finding a general formula for $p_n$.
$$\begin{align}
\int_0^{2a} x^n\ dx
&= 2a\int_0^1 (2ax)^n\ dx\\
&= (2a)^{n+1} p_n
\end{align}$$
Additionally
$$\begin{align}
(2a)^{n+1} p_n
&= \int_0^{2a} x^n\ dx\\
&= \int_{-a}^a (x+a)^n\ dx\\
&= \int_{-a}^a \sum_{k=0}^n {n \choose k} x^k a^{n-k}\ dx\\
&= \sum_{k=0}^n {n \choose k} a^{n-k} \int_{-a}^a x^k\ dx\\
&= \sum_{k\text{ even}}^n {n \choose k} a^{n-k} 2\int_0^a x^k\ dx\\
&= \sum_{k\text{ even}}^n {n \choose k} 2a^{n-k} \cdot a^{k+1} p_k\\
&= 2a^{n+1} \sum_{k\text{ even}}^n {n \choose k} p_k\\
2^n p_n &= \sum_{k\text{ even}}^n {n \choose k} p_k
\end{align}$$
But this is where I'm stuck. I went through values of $n$ to confirm $p_n = p_0/(n+1)$ where $p_0 = 1$. But I haven't been able to prove this using induction (with step size of $1$ or $2$) or any other tricks I know. I thought I'd try rewriting the above to
$$\sum_{k\text{ even}}^n {n \choose k} (p_k-2p_n) = 0$$
But that doesn't help either. The problem always seems to boil down to not being able to simplify $\sum a\cdot b$.
Comment: Is the question to prove $p_n = p_0/(n+1)$ or the relationship between the integral for $0$ to $2a$ and the one from $0$ to $1$, or is it required to establish the derivative (and hence anti-derivative) of $x^n$ from first principles?
Comment: perhaps it would help if you could be more specific about where you are going with this. "proving $\int x^n dx$" is meaningless as $\int x^n dx$ is an expression, not a statement.
Comment: Sorry. Yes I'm trying to prove $p_n = p_0/(n+1)$
Comment: Do you need to establish a formula for $\frac{d}{dx}x^n$ from the definition of the derivative, or is it okay to use the power rule without derivation?
Comment: @Marconius I'm trying to find a general formula for $p_n$ directly from the last equation above.
Answer: Note that $2^n = (1+1)^n =\sum\limits_{k = 0}^n {n \choose k}$ and $0 = (1-1)^n =\sum\limits_{k = 0}^n {n \choose k}(-1)^k$, which combine to give you $\sum\limits_{k \text{ even}}^n {n \choose k} = 2^{n-1}$, and therefore $\sum\limits_{k \text{ odd}}^n {n \choose k} = 2^{n-1}$. This latter expression can be rewritten as $2^n = \sum\limits_{k \text{ even}}^{n+1} {n+1 \choose k+1} = \sum\limits_{k \text{ even}}^{n+1} {n \choose k}\frac{n+1}{k+1}$. Or: $$2^n\frac{1}{n+1} = \sum\limits_{k \text{ even}}^{n+1} {n \choose k}\frac{1}{k+1}$$
Comment: Sorry I don't see how to use this. :\
Comment: Never mind, got it. Thanks!
Comment: Good. It's always better to spot something yourself.


If $f$ is two times differentiable on $[a,b]$ and attains maximum at $x_0\in (a,b)$, prove $f''(x_0)\leq 0$.

Question:
Let $f:[a,b] \rightarrow \mathbb{R}$ be a two times differentiable function, that attains its maximum value at some $x_0\in (a,b).$ Prove that $f''(x_0)\leq 0.$

Attempt. By defintion, we have $\displaystyle f''(x_0)=\lim_{x \rightarrow x_0}\frac{f'(x)-f'(x_0)}{x-x_0}$, where $f'(x_0)=0$ by Fermat's theorem (since $x_0$ is an interior point of diferentiability of $f$), so:
$$\displaystyle f''(x_0)=\lim_{x \rightarrow x_0^+}\frac{f'(x)}{x-x_0}.$$
It is enough to prove that for some $\delta>0$ we have that $f'(x)\leq 0$ for $x\in (x_0,x_0+\delta).$ This is the point I am stuck.
Thank you in advance for the help!
Answer: You are stuck, because what you want to prove need not be true: Consider
$$f(x)=\begin{cases}x^2(\sin\frac1x-2)&x\ne 0\\0&x=0\end{cases} $$
This has a unique maximum at $x=0$, but oscillates between increasing and decreasing in every interval $(-\delta,\delta)$.
Instead, use that in order for $f''(x)$ to exist in $(a,b)$, the first derivative $f'(x)$ must be continuous. Then if e.g. $f''(x_0)>0$, we have $f'(x)>0$ in some interval $(x_0,x_0+\delta)$. Then conclude from the MWT that $f(x)>f(x_0)$ for all $x\in(x_0,x_0+\delta)$.
Answer: If $f$ is twice differentiable then
$$
f''(x_0)=\lim_{h\to 0^+}\frac{\big(f(x_0+h)-f(x_0)\big)+\big(f(x_0-h)-f(x_0)\big)}{h^2}
$$
If $x_0$ is a local maximum, then clearly, $f(x_0+h)-f(x_0)\le 0$ and $f(x_0-h)-f(x_0)\le 0$, and hence
$$
\frac{\big(f(x_0+h)-f(x_0)\big)+\big(f(x_0-h)-f(x_0)\big)}{h^2}\le 0
$$
and finally
$$
f''(x_0)=\lim_{h\to 0^+}\frac{\big(f(x_0+h)-f(x_0)\big)+\big(f(x_0-h)-f(x_0)\big)}{h^2}\le 0
$$
Answer: Suppose $f''(x_0)>0.$ Then for $x$ in a small enough interval $(x_0,x_1)$, we have
$$\frac{f'(x)-f'(x_0)}{x-x_0}= \frac{f'(x)}{x-x_0}> (1/2)f''(x_0) >0.$$
This implies $f'>0$ on this interval. Hence $f$ is strictly increasing on this interval, contradicting the fact that $f$ has a maximum at $x_0.$
Answer: Since $f(x_0)$ is a maximum, there exists an interval $[x_0, x_0 + \delta)$ such that $f$ is less than $f(x_0)$ on it.
Then for any $c \in [x_0, x_0 + \delta)$ there exists a $\xi \in [x_0, x_0 + \delta)$ such that
$$f'(\xi) = \dfrac{f(x_0 + \delta) - f(x_0)}{\delta} \leq 0.$$
Finally, by continuity of $\dfrac{f'(x)}{x-x_0}$, we have a sequence of $\xi_n$ such that $\dfrac{f'(\xi_n)}{\xi_n - x_0} \to a$, where $a \leq 0$, so the limit is $a$, which is $\leq 0$.
Comment: It is true that $\displaystyle f″(x_0)=\lim_{x\rightarrow x_0^+}\frac{f'(x)}{x-x_0}=\lim_{n \rightarrow+\infty}\frac{f′(\xi_n)}{\xi_n−x_0}≤0.$ Where do you use the continuity of f′ at the last part?
Comment: Sequential continuity implies if we can find one sequence converging to $x$ such that the image of the sequence converges to $f(x)$, then all such sequences converging to $x$ have their image converging to the same point $f(x)$.

In other words, it is not enough to say that $\lim_{n \to \infty} \leq 0$. But continuity assures us that $\lim_{x \to x_0^+} \leq 0$.
Comment: Fact. If $\displaystyle \lim_{x\rightarrow x_0}f(x)=\ell\in \mathbb{R}\cup\{\pm \infty\}$ and $x_n\rightarrow x_0$, then $f(x_n)\rightarrow \ell$ (and no continuity is needed).  (In our case, $\ell=f''(x_0)\in \mathbb{R}$). Please correct me if I am wrong, but I see no problem on the above statement I made.
Comment: True! But you can't apply the converse! Continuity is needed.


Random variables with some properties (conditional expectation)

Question: I am looking for two random variables which fulfills the following two things:
a) $\mathbb E(X|Y)<\infty$ and $\mathbb E(Y|X)<\infty$
b) $E(X|Y)> Y$ and $\mathbb E(Y|X)>X$ a.s
Here is the original task:
Comment: Sorry, I'm not a good English speaker too and my previous comments were not clear (I delete them). I just wanted to say that such random variables $X$ and $Y$ are necessarily non-integrable, otherwise we would get $E(X)>E(Y)$ and $E(Y)>E(X)$.
Comment: Maybe I misunderstood the question...my english isnt that good. I will add the original task above
Comment: Since this seems to be a textbook exercise, please read the `self-study` [tag wiki](http://stats.stackexchange.com/tags/self-study/info) and modify your question accordingly (e.g. explain what you've tried and where your specific difficulties lie)
Comment: @Stéphane By definition a random variable is integrable. Do you perhaps mean to say that the expectations of $X$ and $Y$ must *diverge*?
Comment: @whuber I have the impression that in many corners the term "integrable random variable" is used to mean "a random variable whose expected value exists and is finite". Also "square-integrable" = "...whose second raw moment exists and is finite".
Comment: @Alecos Thank you--some Googling confirms your characterization of the phrase.
Comment: @whuber integrable $= \in L^1$, as said by Alecos
Comment: Construction of $(X,Y)$ with these properties is related to the "Two Envelopes Parodox". Take a look at David Williams's book "Weighing the Odds", pages 400 and 404. As monsieur Laurent pointed out, $X$ and $Y$ will necessarily be nonintegrable.
Answer: By keeping things as simple as possible we can construct a rather pretty solution.
Step 0  We have to begin somewhere.  Since the variables are supposed to have strictly positive values, take the simplest positive number, $1$, and since $X$ appears first alphabetically, suppose $X=1$.  In order to obtain $\mathbb{E}(Y|X=1) \gt 1$, $Y$ will have to have nonzero probability of exceeding $1$.  The simplest possible way that could happen would be for all the probability to be assigned to a single value larger than $1$.  The simplest number larger than $1$ is $2$. So, let
$$\mathbb{P}((X,Y)=(1,2)) = p,$$
say, and let's stipulate that $\mathbb{P}((1,y)) = 0$ for all $y\ne 2$.
Step 1 Now that $Y=2$ has nonzero probability, we are forced to consider $\mathbb{E}(X|Y=2)$.  There is already probability $p$ that $X=1$ when $Y=2$.  In order to make $\mathbb{E}(X|Y=2)\gt 2$, we will need to assign some probability to values of $X$ greater than $2$.  Moreover, since we don't want to be assigning greater and greater probabilities to values--we want them to decrease so that they can sum to unity--we would prefer that some probability be assigned to $X\gt 3$ (for otherwise it would not be possible for the conditional expectation to be larger than $2$).  The simplest number in that range is $4$, so let's stipulate that
$$\mathbb{P}((X,Y)=(4,2)) = q,$$
say.  Then
$$\mathbb{E}(X|Y=2) = \frac{p(1) + q(4)}{p+q} \gt 2.$$
Writing
$$\zeta = q/p,$$
this implies $1 \gt \zeta \gt 1/2$.
So far we have obtained
$$\mathbb{P}((X,Y)=(1,2)) = p;\quad \mathbb{P}((X,Y)=(4,2)) = p\zeta.$$
Step 2 Now the tables are turned: we have assigned nonzero probability to $X=4$ and we need to determine what probabilities to assign to ordered pairs of the form $(4,Y)$.  By interchanging the roles of $X$ and $Y$ and quadrupling their values, we can proceed exactly as in the last step to assign probability $(p\zeta)\zeta = p\zeta^2$ to the ordered pair $(4,8)=4(1,2)$ and in so doing guarantee, by construction, that $\mathbb{E}(Y|X=4) \gt 4$.
Steps $2n$ and $2n+1$ Continue switching the roles of $X$ and $Y$, quadrupling the values and multiplying each successive probability by $\zeta$.
Step $\omega$ Continuing in this vein produces a pair of random variables $(X,Y)$ which can be thought of as functions of the set of steps $\{0,1,2,\ldots,n,\ldots\} = \mathbb{N}$, the natural numbers.  Such functions are sequences.  They are
$$X = (x_n) = 1,4,4,16,16,64,64, \ldots, 2^{\lfloor (n+1)/2 \rfloor}, \ldots$$
$$Y = (y_n) = 2,2,8,8,32,32, \ldots, 2^{\lfloor n/2\rfloor + 1}, \ldots $$
The probability associated with the natural number $n$ is $p\zeta^n$.  The total probability is $p + p\zeta + \cdots + p\zeta^n + \cdots = p/(1-\zeta)$.  Because this must be unity, finally we learn that
$$p = \frac{1}{1-\zeta}.$$
In order for $X$ and $Y$ to be random variables, the inverse images of any value must be measurable.  The inverse images under $X$ are the doubleton sets $\{1,2\}, \{3,4\}, \ldots, \{2n-1, 2n\}, \ldots$ while the inverse images under $Y$ are the doubletons $\{0,1\}, \{2,3\}, \ldots, \{2n, 2n+1\}, \ldots$.  Clearly these generate (via intersection) all singletons $\{n\}$, whence every subset of $\mathbb{N}$ must be measurable: this is the discrete measure on $\mathbb N$, given by its power set $\mathcal{P}(\mathbb{N})$.  Therefore $X$ and $Y$ are random variables with respect to the probability space
$$(\mathbb{N}, \mathcal{P}(\mathbb{N}), \mathbb{P})$$
where $\mathbb{P}$ is completely determined by its values on the atoms,
$$\mathbb{P}(\{n\}) = \frac{\zeta^n}{1-\zeta},\ n=0, 1, 2, \ldots.$$

The sense of "simplicity" adopted in this answer is objective, not subjective: it is the one John Conway describes in his book On Numbers and Games.  We could go even a little further and name $\zeta = 3/4$ as the simplest possible value of $\zeta$ for which $1/2 \lt \zeta \lt 1$--but any such $\zeta$ will do.
Comment: Ooohh I remember, this is in Williams' book "Weighing the Odds"


View date filter using years as an offset

Question: Is there a way to use years as a date filter offset?  What I want is to set it so that it it loads all content from the start of the previous year. So >= 01-01-2017 this year, >= 01-01-2018 next year, etc.  Is there a way to do that in the View configuration so that it's dynamic?  I'm sure I could do it with custom code by altering the query, but I'd rather avoid that.
Comment: Have you tried a <= filter?
Comment: I would need it to be dynamic.  So if I put a specific date I would have to update the configuration every year, which I don't want.  What I want is to set it so that it it loads all content from the start of the previous year.  So >= 01-01-2017 this year, >=01-01-2018 next year, etc.
Comment: `now -1 year` default value?
Comment: @Kevin  Nope that only covers 12/2017 to 12/2018
Answer: It turns out this was more of a PHP strtotime() question.  I just had to figure out the appropriate phrase to get the time frame I wanted, which is: "first day of january last year". I placed that phrase in the filter's offset value.


Registered custom block not showing up

Question: I tried to register two custom block in my custom_blocks module with the following code.
function custom_blocks_block_info(){
  $blocks = array();
  $blocks['featured_items'] = array(
    'info' => t('Featured Items'),
    'status' => TRUE
  );
  $blocks['workflow_illustration'] = array(
    'info' => t('How it works'),
    'status' => TRUE
  );
  return $blocks;
}

function custom_blocks_block_view($delta = ''){
  $block = array();
  switch ($delta) {
    case 'featured_items':
      $block['content'] = featured_items();
      break;
    case 'workflow_illustration':
      $block['content'] = workflow_chart();
      break;
  }
  return $block;
}

But the    problem is 'Featured Items' block is shown in the block administer page. But the 'How it Works' block is not shown (may be not registered :?) in the block administer page.
I tried deactivating the module >> clear drupal cache >> clear browser cache (?) >> activate the module again.
Still the 'Featured Block' is the only block showing up. Please help me to get my block accessible via block administer page.
Comment: May be the problem is in "workflow_chart()" function have you checked it?
Comment: No @Enxebre both featured_items() and workflow_chart() returning simple html output. something like return 'Something";
Comment: i suggest to try with a full inline content for testing
Comment: The blocks should still be listed in the block administer page regardless of what is in the block content. I copied your block_info() function into a custom module and tried it, and the two blocks show up in my blocks administer page. So the question is what is different on your drupal installation
Comment: Is what you've got in the question an identical copy-paste of your code? If it is, I'd suspect you've made some changes to core/contrib modules, or have dev/alpha/beta versions of modules that mess with blocks in some way. The code in your question, copied and pasted exactly, works fine for me too. Both blocks show up.
Comment: Could you check with another key for workflow_illustration?
Comment: ... I copied everything into a new module again. Got it working now. I don't know where I made the mistake. Finally I got my thing working now. Thousands of hearty thanks to you all genius.
Comment: Please let me know the answer for one more question.. When I add $block['subject']. The subject is always appear as the heading of the block. What I can do if I don't want any title to be appeared. But @Molot said it is not a good practise avoiding $block['subject'] ...
Comment: Add  in the title of the block in the block/region association
Comment: @pico34 Found it. Thank you anyway. Thank you all once again
Answer: First, try to provide $block['subject']. Second,  omit status in hook_block_info implementation, it may cause problems when there is no region assigned.
Comment: added $block['subject'] and removed the 'status' now hook_block_info just has 'info' => ''

but still it's not working @Mołot
Comment: Molot is on the right track - hook_block_info needs to have $block["info"] set. This is the administrative title of the block. In hook_block_view, you need to set $block["subject"] and $block["content"]
Answer: Double check if:

Module is enabled.
Module is not duplicated and system table points to the right file:
drush sqlq "SELECT * FROM system WHERE name = 'foo'"

You cleared all caches (in Development/Performance).

Troubleshooting

Check if hook_block_info() is called after clearing caches (add exit('foo'); to see if that break the site). If it's not called, then:

check for typos,
restart external caches (such as memcached or redis) if in use,
restart Apache server (it could be OPCache/XCache)

use drush to see if the hook is called:
drush cc all

install drush_extras (via drush dl drush_extras) and check if the block is on the list when running from CLI:
drush block-show | less +/my_block

if you've Devel enabled, try load the block at /devel/php and check if does exist:
print_r(block_load('foomodule', 'foodelta'), TRUE);

Answer: I remove status from info block.
disable the my module and click uninstall tab and did uninstall for same module.
after disabling the module it comes in uninstall list.
clear cache and it's working now.
changed  code:
function module_block_info() {
 $blocks = array();
 $blocks['hnavigation'] = array(
   'info' => t('Homepage Naviagation'),
 );
 $blocks['hslider'] = array(
   'info' => t('Homepage Banner Slider'),
 );

 return $blocks;
}

Previous code :
function module_block_info() {
 $blocks = array();
 $blocks['hnavigation'] = array(
   'info' => t('Homepage Naviagation'),
   'status'=>1,
 );
 $blocks['hslider'] = array(
   'info' => t('Homepage Banner Slider'),
   'status'=>1,

 );

 return $blocks;
}

Answer: If you're an eejit like me this can occur when you name a custom block something which matches a flagged #id tag in an adblocker.

Registered custom block not showing up


Obter nome do BD em uma conexão mysql

Question: Bom faço uma conexão com o BD mysql assim:
// Conecta-se ao banco do servidor
ini_set('default_charset', 'UTF-8');
$mysqli = mysqli_connect('127.0.0.1', 'root', '123', 'teste');
Query($mysqli, "SET NAMES utf8");

Como posso recuperar o nome do BD teste através da variável $mysqli que contem a conexão.
Comment: Bom isso Resolve sim.
Comment: O último parâmetro passado para a função "mysqli_connect" é o nome do banco, não seria melhor você armazenar isso é uma variável global? Assim você não precisaria fazer uma consulta para saber o nome do banco.
Answer: Use a função database() do MySQL ela retorna o nome do banco de dados da conexão.
SELECT database()

No php com MySQLi fica assim:
$db = new mysqli('localhost', 'usuario', 'senha', 'db003-producao');
$result = $db->query('select database() as db');
$registro = $result->fetch_array();
echo $registro[0];

Obter nome do BD em uma conexão mysql


Meaning of predict.fixed and predict.Subject values in 'predict' function of nlme

Question: As discussed in this SO thread, I am using the predict function in nlme to derive predictions for each participants' fourth day score in my own dataset, based on their previous scores and a mixed-effects model. So I am wondering which column of predicted values to use.
Here is an example of how the predict function works using the Orthodont dataset and code supplied by the nlme package manual
library(nlme)
fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject)
    newOrth <- data.frame(Sex = c("Female","Female","Female","Female","Male","Male"),
                          age = c(15, 20, 10, 12, 2, 4),
                          Subject = c("M01","M01","F30","F30","M04","M04"))
    ## The  Orthodont  data has *no*  F30 , so predict  NA  at level 1 :
    predict(fm1, newOrth, level = 0:1)

So if we specify levels as 0:1 the predict function gives two columns of predicted values for each participant. One is the marginal predictions, when we 'set the random effects to 0' or 'average across random effects'. The other column is the conditional or subject-specific random effects for each individual, where we 'hold the random effects constant'
If the population estimates are for the average subject, why are they all different? i.e. in what sense are they average?
I have been trying to get a sense of this for a while. Are the extrapolated population predictions for each subject derived from some combination of fixed group-level effects and from fitting a slope for each individual from the previous measurement occassions and then using that 'individual slope + fixed group effect' to come up with the estimated value?
Answer: I think it works as follows, the predict.fixed column only uses the fixed effects from your model. We can view these with summary(fm1):
Fixed effects: distance ~ age
                Value Std.Error DF   t-value p-value
(Intercept) 16.761111 0.7752460 80 21.620377       0
age          0.660185 0.0712533 80  9.265333       0

As you specified a different age for each subject in your dataframe age = c(15, 20, 10, 12, 2, 4) the resulting predictions are made 16.761111 + 0.660185 * newOrth$age. The differences are a result of differences in age.
As you noted the predict.Subject column includes the subject specific random effects. You can retrieve these with the command ranef(fm1). You will see that subject M01 has a random intercept of 1.0515830 and a random slope of 0.215684556. So the first value of predict.Subject is 16.761111 + 1.0515830 + 0.660185 * (15 + 0.215684556). Although the second line is the same subject with the same random effects, you've specified a different age for this subject (20 instead of 15) so the difference is the age coefficient 0.660185 multiplied by the 5 year difference in age. The second prediction in predict.Subject is 16.761111 + 1.0515830 + 20*(0.660185 + 0.215684556).
I hope that I understood your question and that this answer resolves your interpretation issues.
Comment: Thank you Niek. That `ranef()` command is very useful, and thankyou for the explanation of how these predicted values are derived.
Comment: Actually @Niek now I think about it I still don't understand, because if we held age constant (say at 15) and used your equation (i.e. an additive composite of the fixed effects) wouldn't the marginal prediction be the same for every participant? I know this cannot be the case because in my own data I have obtained marginal predictions for each individual at the same value of the predictor variable and their predicted scores are not all the same. Surely each individual's previous scores must inform the predicted value somehow *in combination with* the sample's fixed effects.
Comment: Actually sorry ignore that last comment. I had included Covariates which were different for each participant. If I run the model without these then the marginal predictions are the same for all participants who belong to the same group. Thank you again, this has been very enlightening.


How to workaround selecting multiple columns inside a single case expression

Question: I am wondering if there is any way to select two columns based on the outcome of an if statement.
Here is what I have so far ( I have cut off half of the unnecessary stuff ):
  ( SELECT IF(
               (SELECT g.id
                FROM users AS u
                INNER JOIN user_groups AS g ON (g.id = u.group_id)
                WHERE u.id = 2) >= 4,

               (SELECT p.action, p.id
                FROM permissions AS p
                WHERE p.required_points <=
                    (SELECT reputation
                     FROM users
                     WHERE id = 2)),

               (SELECT 0, 0)))

Basically, is there any multiple column operand that behave like if statements? and if so how would I implement them. Any links to resources will be greatly appreciate.
The error is:

#1241 - Operand should contain 1 column(s)

The entire sql query:
(SELECT p1.action,
          p1.id
   FROM user_permissions AS u1
   INNER JOIN permissions AS p1 ON (p1.id = u1.action_id)
   WHERE u1.user_id = 2)
UNION
  (SELECT p2.action,
          p2.id
   FROM users AS u2
   INNER JOIN user_groups AS g ON (g.id = u2.group_id)
   INNER JOIN group_permissions AS gp ON (gp.group_id = g.id)
   INNER JOIN permissions AS p2 ON (p2.id = gp.action_id)
   WHERE u2.id = 2)
UNION
  ( SELECT IF(
               (SELECT g2.id
                FROM users AS u3
                INNER JOIN user_groups AS g2 ON (g2.id = u3.group_id)
                WHERE u3.id = 2) >= 4,
               (SELECT p3.action, p3.id
                FROM permissions AS p3
                WHERE p3.required_points <=
                    (SELECT reputation
                     FROM users
                     WHERE id = 2)),
               (SELECT 0, 0)))

Comment: You have to repeat the `if` statement.  But, if you show your whole query (or a simplified version thereof), there might be an easier way of expressing this logic.
Comment: I did consider that however I didn't like the look of a pretty much completely copied if block and so assumed there must be a better way. I will post the whole sql now, hope it will help.
Answer: Oh, so that is basically the whole query.  This won't work:
SELECT IF( (SELECT g2.id
            FROM users u3 INNER JOIN
                 user_groups AS g2
                 ON g2.id = u3.group_id
            WHERE u3.id = 2) >= 4,
           (SELECT p3.action, p3.id
            FROM permissions AS p3
            WHERE p3.required_points <= (SELECT reputation FROM users WHERE id = 2)),
           (SELECT 0, 0)))

So, just move the queries to a from clause:
SELECT (case when g2.id >= 4, p3.action, 0),
       (case when g2.id >= 4, p3.id, 0)
FROM (SELECT g2.id
      FROM users u3 INNER JOIN
           user_groups AS g2
           ON g2.id = u3.group_id
      WHERE u3.id = 2
     ) g2 cross join
     (SELECT p3.action, p3.id
      FROM permissions AS p3
      WHERE p3.required_points <= (SELECT reputation FROM users WHERE id = 2))
    ) p3

If you don't really want the row with (0, 0), but it is there just so there is some other value, then let join or where filter it out:
SELECT p3.action, p3.id
FROM (SELECT p3.action, p3.id
      FROM permissions AS p3
      WHERE p3.required_points <= (SELECT reputation FROM users WHERE id = 2))
     ) p3
WHERE (SELECT g2.id
       FROM users u3 INNER JOIN
            user_groups AS g2
            ON g2.id = u3.group_id
       WHERE u3.id = 2
      ) >= 4

Comment: Oh thanks, sorry for the late response back. I hadn't really thought of using sub queries in that way.


What happens when assigning a string literal to a member const char* variable from within a constructor in C++?

Question: I saw something along these lines recently, and after quite a bit of searching I haven't found an answer that directly addresses this issue.
If I have the following code:
<code>class Foo {
    const char *some_string;

    Foo()
    {
        some_string = "StringLiteral";
    }
};
</code>
Is this valid?
The source was pretty reputable, so my best guess is that this is acceptable, and defined behavior.
My problem with this is that it looks like the memory the string literal is being used in should be stack-allocated, and this memory should no longer be valid outside the scope of the constructor.
Looking into this, the best answer I could get is that the compiler puts the string in static memory, which would mean it is still valid outside the scope of this function.
However, like I said, all the answers I saw didn't directly reference the string literal being assigned directly from within the function itself.
So, is this valid?  And why?
Comment: http://en.cppreference.com/w/cpp/language/string_literal *"String literals have static storage duration, and thus exist in memory for the life of the program."*
Answer:
So, is this valid? And why?

Yes, it's valid. Because string literals have static storage duration, wherever it appears (within the function body or not).

String literals have static storage duration, and thus exist in memory for the life of the program.
Comment: Perfect.  So the other answers were correct.  Thanks!  Soon as I can accept the answer I will :)


LinkedIn connection search by first name and last name

Question: Is there way to search first name and last name for linkedin connection filter using LinkedIn API?
Suppose I am authenticated by linkedIn and show connection in popup.LinkedIn connection response only 500 connection one time request. So I do paging 500 connection. But I want to send invitations to two persons, so I want to give search widget by first name and last name from my LinkedIn connections.
Answer: You could use the People Search API to search on first and last name, restricting the search to just your connections:
http://api.linkedin.com/v1/people-search?first-name=Clair&last-name=Smith&facet=network,F

Update:
In terms of 'filtering' the returned values to remove the current user making the call from the result set, you should check for the returned user's relationship to the viewer:
http://api.linkedin.com/v1/people-search:(people:(id,first-name,last-name,relation-to-viewer:(distance)))?first-name=Clair&last-name=Smith&facet=network,F

Then check the results, and remove the users that have a relation-to-user of 0.
Comment: Using people search API we can search by firstname and lastname .But when i add facet=network,F parameter restricting search in my connection then i get error "The remote server returned an error: (401) Unauthorized"
Comment: [link] http://api.linkedin.com/v1/people-search?Keywords="Clair%smith" . I am not exactly know user enter firstname or lastname or both in search textbox so i am using "keywords"? but my problem is that the "keywords" searches all profile selector fields in linkedin profile i want to restrict it searches only first name or last name or both in linkedin profile? how to do it
Comment: @sunil It's one or the other - `keywords` searches all fields, `first-name` and `last-name` search just what you'd expect.
Comment: In my application there is textbox so user can enter first-name or last-name or both how i find out it is first-name or last-name or full name. so i am using "Keywords" and restrict it searches only first_name and last_name in linked in profile and give me proper result through "People Search API " ? What parameter send to search People API parameter it searches only first name and lastname using Parameter "Keywords"
Comment: @sunil the parameter to tell the People Search API to only search first name is just that, `first-name`. In terms of your UI, why not just show the user a separate box for first name, one for last name so you can send those values right to the API? This is exactly what LinkedIn does on their own webpage.
Comment: Paul  :- when we search using people search API with parameter &facet=network,F then we got 1st connection.But issue is that in 1st connection owner Linkedin account name is display.How to exclude this owner account name from search result from first connection.For example i have 18 connection when using Connection API but when i using people search api and Facet=Network,F then it returns 19 connection including owner account name.
Comment: @sunil I'm not sure I understand what you mean when you say one of the connections returned has 'LinkedIn owner account name' displayed. Do you mean that one of the results, instead of name just says "LinkedIn Account" or something similar?
Comment: Paul:-suppose i login sunil patil using linkedin account the first connections include owner name "sunil patil" as connection in connection result set.
Comment: @sunil Added content to answer to determine which user's to filter.
Comment: @PaulMennega Is it possible to search by company and keyword in my connection search?


How to remove the header (Via:, 1.1 browsermobproxy) using a wrapper python for Browsermob-proxy + Selenium

Question: Some servers can respond to the Via header. For the purity of the experiment, I want to get rid of it. How it can be made using a wrapper on a python for Browsermob-proxy?
That it was better understood, I will result the code:
Sorry for my English!
<code>    from pyvirtualdisplay import Display
    from selenium import webdriver
    from browsermobproxy import Server

    display = Display(visible=0, size=(1920, 1080)).start()

    server = Server("/path...")
    server.start()
    proxy = server.create_proxy()

    profile  = webdriver.FirefoxProfile()
    profile.set_proxy(proxy.selenium_proxy())
    driver = webdriver.Firefox(firefox_profile=profile)

    proxy.new_har('test', options={'captureHeaders': True})
        ??? proxy.headers(headers = {'Via': ''})

    driver.get("http://headers.cloxy.net/request.php")
    time.sleep(10)

    print(driver.page_source)

    server.stop()
    driver.quit()
    display.stop()
</code>
Answer: Allowing users to remove 'via' header is a current issue.
However the full source is available on github. I managed to get rid of the via header by removing line 274 of LittleProxy/ProxyUtils.java, then having my project use my local copy of browsermob-core which uses my local copy of LittleProxy.


any universal non serif font in normal and bold variant

Question: .title{
font-family:'Arial Bold';
}

I thought there will not be a problem with Arial font but...
Arial Bold - doesn't exists on my Chrome, or Windows 7.
Arial Black is too heavy.
Is there any (non serif) font I can be sure it exists on any platform, any browser as normal and bold variant?)
Answer: Your browser is right: Arial Bold does not exist as a font family of its own. Arial is one of the most commonly available font families among operating systems. According to this source:

Helvetica is the granddaddy here, but Arial is more common on modern OS's.

What you're missing here is that you're trying to specify the font weight as part of the font family. What you need right here is font-weight.
Font family Arial Bold does not exist, as your browser says.
The font-family should only take Arial in your case. To control whether you want your font to be bold or regular, or italic, or underlined, you have to use different properties with their respective values in CSS.
font-weight takes the following values among others: regular, bold. So in order to use Arial, bold, your CSS would look like this:
font-family: 'Arial', sans-serif;
font-weight: regular; // I prefer to use numeric values myself

Comment: @qadenza there is no such font family as `Arial Bold`. `Arial` is the font family, `bold` is the weight. Combining the two as I wrote in the answer will get your bold Arial. It's not really fair to downvote my answer without even reading it to the end.
Comment: how to get `Arial Bold`, pls
Comment: oh, I see, thansk. seems that's special for `arial` other fonts have with `bold` after font name.
Comment: @qadenza it depends on your system. After all, every browser attempts to load font files from your system if you don't use any external services. But since you probably want your site to look the same on as many devices as possible, you need to rely on a font that's commonly available (again, unless you use an external service), so Arial is one of the safest to use for this purpose
Answer: Have you tried using @import to import a font from a server. If you are open to do that, this should be a good solution to what you are trying to do.
See this article for a good reference: https://css-tricks.com/snippets/css/using-font-face/#article-header-id-5


How to create a redirect for specific domain?

Question: I'm using Domain Access and Redirect modules. Both work well.
But Redirect module only allows me to create redirects from relative path which affects as follows all my domains.
So how to create domain-specific redirect?
Answer: You can do this by using Domain Redirect module.

This module allows the creation of an internal Drupal path that will
  direct the user to a unique path based on the domain that the user is
  in. The link is based at the path "/domain-redirect/12345" where
  "12345" is the redirect ID that is stored in the database.

OR
Try to use Domain Default Redirection module.

This small module provides a redirection feature instead of providing
  the default domain contents in the Domain Access suite.
Answer: You can perform multisite redirect by using Multisite Redirect module.

Multisite Redirect is a system designed to allow users to create and
  manage URL redirects across domains in a sort of multisite
  configuration. The primary use case for this module is one where a
  client might have multiple domains that are being consolidated into a
  single site.


Reactjs and Flexbox: Wrapping divs in render function making flex hard

Question: React is getting me in trouble with flexbox because of the wrapping div in a component's render function is throwing off my flex-directions.
From what I understand about React, all the component's jsx elements should be wrapped up in a single div. For example this works:
return (

)

whereas this doesn't:
return (

)

Yet this is making things hard with flexbox rows and columns. For example say we had this flex relationship.
<Parent Column Component /> //vertical flex
  <ChildRowComponent1 />    //horizontal flex
  <ChildRowComponent2 />    //horizontal flex
  <ChildRowComponent3 />    //horizontal flex

But ChildRowComponent2 & 3 can be swapped out dynamically - which causes me to refactor by putting ChildRowComponent2 & 3 in their own component but since all rendering must be wrapped up in a single div I get this extra div that messes up the flex directions.
<Parent Column Component />  //vertical flex
  <ChildRowComponent1 />     //horizontal flex

    <ChildRowComponent2 />   //horizontal flex now broken
    <ChildRowComponent3 />   //horizontal flex now broken

Question:
Is there a flexbox trick to handle these cases or am I just doing something  wrong with how I'm structuring my components?
Comment: Great editing @m01! Helped capture the problem very well!
Comment: This is a known problem, [see this report on github](https://github.com/facebook/react/issues/2127) - sadly no easy fix yet.
Answer: Fragments solve this problem. You don't need any extra
 elements when wrapping child elements. This won't add extra nodes to the DOM.
return (
 <React.Fragment>

 <React.Fragment>
)

React Fragment Documentation
Answer: Instead of creating a component that groups ChildRowComponent2 & 3, you can make it a function that returns a list. Then you can do this in your Parent component:
  render: function() {
    return (

        <ChildRowComponent1 />
        { this.renderOtherChildren() }

    )
  },
  renderOtherChildren: function () {
    var result = [];
    if (this.props.shouldHaveSecondChild) {
      result.push(<ChildRowComponent2 key={ 2 } />);
    }
    if (this.props.shouldHaveThirdChild) {
      result.push(<ChildRowComponent3 key={ 3 } />);
    }
    return result;
  },

If you're wondering why do you need the key prop, here is an explanation.
Comment: Well, I think that you could actually refactor your router so that instead of rendering the components, it would just *return the information* about which components should be visible. Then your `Parent` component would get this information in `props` and handle accordingly. (Disclaimer: I never used react-router.)

Btw: `this.props.children` is a list (e.g. `[, ]`), so you can use it as you would use the output from my `renderOtherChildren` function.
Comment: I'll experiment with this and let you know how it goes. Open to any other workarounds people have come up with.
Comment: Also @m01, could you elaborate on your answer just a little more? I've never seen another function that is potentially returning jsx, or other components, so seeing the syntax of that would be quite useful.
Comment: I added this to the answer.
Comment: I'm reading the link you posted now. I'll try it out and let everyone know how it turned out :)
Comment: One last clarifying question- this.props.children will change with routing so it's value, for example, could either be  or . How could we check for the routing cases in your renderOtherChildren method?


highlight the menu items related to the particular content type

Question: How to highlight the menu items related to the particular content type? Actually I want whenever the user visits the page related to the particular content type,it should highlight the particular menu item. Context module is the one solution for this. Is any other custom coding solution without installing any module?
Answer: You can use theme_menu_link function.
Add this code to template.php of your theme
function themename_menu_link(array $variables) {
  $path_parts = array();
  $element  = $variables['element'];
  $sub_menu = '';
  $menuName = $variables['element']["#original_link"]["menu_name"];
  //Check menu name
  if($menuName == 'main-menu')
  {
    $path_parts = explode('/',$element['#href']);
    if($path_parts[0]=='node' && is_numeric($path_parts[1]))
    {
      $menu_load_node = node_load($path_parts[1]);
      //Check node type (In our case 'article')
      if($menu_load_node->type == 'article')
      {
        $element['#attributes']['class'][] = 'highlight';
      }
    }
  }
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

All links to nodes with type 'article' will have class highlight
Comment: it is working only for main menu i am trying to highlight the custom menu. how to do highlight custom menu?
Comment: In string  if($menuName == 'main-menu') change main-menu to your menu name. Menu name You can see on menu edit page - this is Machine name of menu
Comment: When i printed the $variables variable I am not able to see the detail of custom menu.It is still referring to main menu only.
Comment: For the first output your custom menu as block on page. Maybe You have only main-menu on the page.
Comment: yes the custom menu is as block only and only 1 main menu on the page. Then, how can i implement it?


Tabs - Retornar para aba desejada

Question: Bom dia, pessoal! No meu cadastro de Fornecedores, na View Details, eu tenho uma Tab com as abas: Dados, Contatos e Compras, e quando eu clico na aba Contatos, há um botão para cadastrar novo contato e me direciona para a View Contatos dos Fornecedores.
Ao cadastrar o novo contato, preciso fazer retornar para a View Details dos Fornecedores, porém na aba Contatos.
Minha Tab da View Details dos Fornecedores esta assim:

        Dados

        Contatos

        Compras

Exibe os dados do Fornecedor

                Tipo do contato
                Descrição

                Telefone
                9999-8888

                Email
                oxoxoxoxo.com.br

        <button type="button"
                title="Novo registro"
                class="btn"
                style="background-color: lightsteelblue;"
                onclick="firstname.lastname@example.com("Create", "ContatoFornecedores", new { FornecedorId = @TempData["FornecedorId"] })'">
            Novo Contato
        </button>

Exibe todas as compras efetuadas junto ao Fornecedor

Qual a maneira que dá pra se fazer isso?
Answer: Pensei em colocar mais um parâmetro no onclick, ficando assim:
onclick="firstname.lastname@example.com("Details", "Fornecedores", new { id = @TempData["FornecedorId"], selectTab = 2})'">

Aí, quando retorna à View Details do Fornecedor, a url fica assim:
http://localhost:61801/Fornecedores/Details/9?selectTab=1
Agora precisava de uma maneira de pegar essa selectedTab no Controller e enviar para a View para abrir a aba que eu quero. Pensei em fazer assim:
public ActionResult Details(int? id, int? selectedTab)
{
    if (selectedTab == null)
    {
       TempData["SelectedTab"] = 0;
    }
    else
    {
       TempData["SelectedTab"] = selectedTab;
    }
    return View();
}

Será que estou indo pelo caminho certo?
Alguém poderia me dar uma luz?

Tabs - Retornar para aba desejada


Let $n\in \mathbb{N}, n > 1$ Show that some numbers are coprimes.

Question:
Let $n\in \mathbb{N}, n > 1$. Show that
$$\{a^2+a-1,a^3+a^2-1,...\}$$
contains an infinite subset $S$ s. t. every $2$ distinct elements are coprimes.

I don't know how to even approach this.. can you give me some places to start?
Attempt:
$a^3+a^2-1=a(a^2+a-1)+a-1$. Using Euclid algorithms we determine that:
$a^2+a-1=(a+2)(a-1)+1\implies (a^3+a^2-1,a^2+a-1)=1$ so they are relatively prime.
I was thinking of something like this:
Let $p,q \in\mathbb{N}, p > q > 1$ then some random elements of that set should be:
$a^p+a^{p-1}-1, a^q+a^{q-1}-1$. Then we need to show that:
$$(a^p+a^{p-1}-1,a^q+a^{q-1}-1)=1$$
Right?
Comment: @Peter it's an infinite subset
Comment: Does $a=n$? Also...aren't $a^3+a^2-1$ and $a^2+a-1$ always relatively prime?  So just take $S$ to be those two.
Comment: We must show that every pair (not only neighboured pairs) are coprime. Moreover, you did not clarify what $n$ is.
Comment: @Dr.Mathva And that is equivalent to proving that
$$(a^{n-p}-1,a^{p+1}+a^p-1)=1 \;\;\forall n,p\in \mathbb N : n>p$$
Comment: This is a tough problem, and is very similar to an old Romanian problem, I don't remember the year. Read my proof below.

By the way, I strongly suggest that for contest problems, you better try AoPS forums, as the people there are, much more comfortable with contest math type of problems, where in here and MathOverFlow, the value of these elegant problems are underestimated.
Comment: @Peter I found this problem in a book, by my guesses $n$ is the degree of the polynomial.

$n=2\implies a^2+a-1$, $n=3\implies a^3+a^2-1$ and so on
Comment: It seems that even the complete set has the property that any two polynomials are coprime. Upto degree $500$ , I did not find a counterexample with PARI/GP.
Comment: @Peter I see, so then the subset must be the set itself or any subset of it, however, Proof?
Comment: It is a contest, so a proof will not be trivial. But I think someone on this site will manage it.
Comment: I'm not sure if it might help, but the problem is equivalent to proving that $$((a+1)(a^n-a^p),a^{p+1}+a^p-1)=1 \;\;\forall n,p\in \mathbb N : n>p$$
Answer: Nice problem.
Here it is. Let $a_k=a^k+a^{k-1}-1$. We will construct such a set inductively. First, take any $k_1$, and add $a_{k_1}$ to the list. Now, let $k_2=\phi(a_{k_1})$, where $\phi(\cdot)$ is the Euler's totient function. Since $(a,a_k)=1$ for every $k$, it follows from Euler's theorem that, $a^{k_2+1}+a^{k_2}-1\equiv a\pmod{a_{k_1}}$, which is coprime with $a_{k_1}$, as $a$ is coprime with $a_{k_1}$.
Now, having constructed this set up to its $n^{th}$ element, that is, $S\supset \{a_{k_1},a_{k_2},\dots,a_{k_n}\}$, we now search for an $k_{n+1}$ so that, $(a_{k_{n+1}},a_{k_i})=1$ for each $1\leq i \leq n$. To do so, it suffices to select $k_{n+1}=\phi(a_{k_1})\cdots \phi(a_{k_n})$.
Answer: This is not an answer, as John Omielen commented below. It just responded Peter's comment in the question by proving that as polynomials in $a$, the elements in the set are pairwise coprime. I do not see a direct proof of the original question from this fact.
By the Euclid algorithm, for any pair of natural numbers $p > q$,
$$
\begin{aligned}
\gcd(a^{p+1} + a^p - 1, a^{q+1} + a^q - 1) &= \gcd(a^{p+1} + a^p - 1 - a^{p-q}(a^{q+1} + a^q - 1)), a^{q+1} + a^q - 1)\\
&= \gcd(a^{p-q}-1, a^{q+1} + a^q - 1).
\end{aligned}
$$
Taking them as polynomials in $a$, if the g.c.d. is not 1, then there is an element $\xi \in \mathbb C$ such that
$$
\begin{aligned}
\xi^{p-q} &= 1;\\
\xi^{q+1} + \xi ^q &= 1.
\end{aligned}
$$
The first equation tells that $\xi$ is a root of unity, and the second equation tells us that $\xi^{q+1}$ and $\xi$ lies on the unit circle on the complex plane, and the angle between them and the origin is $120^\circ$. The only chance for this to be true is $\xi$ be a primitive root of unity. But in this case $\xi^{q+1} + \xi^q = -\xi^{q-1} \neq 1$.
Therefore, $\gcd(a^{p+1} + a^p - 1, a^{q+1} + a^q - 1) = 1$ for all $p \neq q$.
Comment: Thank you for pointing out. The purpose of this was to reply Peter's comments on the relative primality of the sequence as polynomials in $a$. I thought it was sufficient but it was not. Maybe I will delete my post later.
Comment: You are welcome. As you have explicitly addressed my concerns stated in my comment at the top of your answer, I have deleted my original comment as I don't believe it's needed any more.


Entire function that maps real axis to unit circle

Question: Question: Determine the most general entire function $f$ having the property $|f(z)|=1$ when $\text{Im}(z)=0$.
One possible class of such functions is
$$
f(z)=e^{icz}
$$
with $c\in\mathbb{R}$ is a constant. But how to find other functions or how to prove all the entire function has such a form?
Comment: For any entire function $g$ which maps the real line into itself (like $\sin z, \cos z$) etc $e^{ig(z)}$ has this property.
Comment: @KaviRamaMurthy But how to show that functions having such form characterize all entire functions having such property?
Answer: Claim: $f$ is entire and maps $\mathbb R$ to $\{|z|=1\}$ iff $f=e^{ig}$ for some entire $g$ that is real on $\mathbb R.$
Proof: Let's concentrate on $\implies,$ since the other direction is clear.
Since $f$ is entire, so is $\overline {f (\overline z)}.$ Hence $f(z)\overline {f (\overline z)}$ is entire. The hypothesis implies the last function is $1$ on $\mathbb R,$ hence it is $1$ everywhere. Therefore $f$ is never $0$ on $\mathbb C.$
It follows that $f=e^h$ for some entire $h.$ Again using $|f|=1$ on $\mathbb R,$ we see $\text { Re }h=0$ on $\mathbb R.$ Letting $g=-ih,$ we see $f = e^{ig},$ with $g$ real valued on $\mathbb R.$
Comment: Thank you very much!


Como verifico se duas strings são anagramas uma da outra?

Question: Preciso comprar duas strings e verificar se a segunda é um anagrama da primeira. Pensei em usar laços de repetição FOR. Creio que deva primeiramente verificar se ambas têm o mesmo tamanho, depois percorrê-las e ir verificando se cada letra da primeira existe também na segunda. Caso todas existam, uma é anagrama da outra. Só não sei como fazer isso...
public static void main(String[] args) {
        Scanner ent = new Scanner(System.in);
        String s, r;
        int i, j;
        System.out.println("Digite a palavra/frase:");
        // crio as strings
        s = ent.nextLine();
        r = ent.nextLine();
        // verifico se têm o mesmo tamanho
        if (s.length()==r.length()) {
            // percorro ambas verificando se cada letra da 1ª existe na 2ª
            for (i=0; i<s.length(); i++) {
                for (j=0; j<r.length(); j++) {
                // não sei continuar...
                }
            }
        }
    }

Comment: Uma forma alternativa de fazer é ordenar as letras de cada palavra em sequência alfabética e verificar se são iguais.
Comment: Eu notei que durante a aceitação você primeiro aceitou a minha resposta e depois a do Victor. Não sei se você sabe que a aceitação, ao contrário do voto, só pode ser feita para uma resposta em cada pergunta. E a aceitação fica na última que você clicar. Não sei se sua intenção foi realmente escolher a resposta do Victor, que é uma boa resposta, não teria problema algum em aceitá-la, ou escolher a minha. Não importa qual você escolhe, a decisão é sua, mas é importante entender o funcionamento da ferramenta e fazer uma escolha de acordo com sua vontade real.
Comment: @bigown Isso aconteceu porque eu vi primeiro a sua resposta e já aceitei, depois vi a do Victor e achei que ela se adequava mais ao estilo de programação que eu uso. A sua solução é boa também (se eu pudesse, manteria o voto nas duas, até porque são bem parecidas), mas utiliza modularização, que eu ainda não entendo muito bem nem sei usar direito. De qualquer forma, agradeço pela ajuda e por se preocupar em explicar sobre o funcionamento da ferramenta :)
Answer: Penso em três formas de fazer isso.
A primeira forma é contar a frequência de cada caractere para cada String e então comparar as frequências.
A segunda forma é ordenar as letras de ambas as Strings e ver se o resultado coincide.
A terceira forma é usar funções do Java já prontas para isso:
    s = ent.nextLine();
    r = ent.nextLine();
    char[] a = s.toCharArray();
    char[] b = r.toCharArray();
    Arrays.sort(a);
    Arrays.sort(b);
    if (Arrays.equals(a, b)) {
        System.out.println("Anagrama");
    } else {
        System.out.println("Não é anagrama");
    }

Comment: Funcionou! Muito obrigada!
Answer: Achei essa resposta no SO que é o que você precisa:
public static boolean isAnagram(String s1, String s2) {
    //se as duas strings não tem o mesmo tamanho, não é anagrama
    if ( s1.length() != s2.length() ) {
        return false;
    }
    //tranfroma em arrays para poder ordenar
    char[] c1 = s1.toCharArray();
    char[] c2 = s2.toCharArray();
    //ordena para garantir a comparação simplificada
    Arrays.sort(c1);
    Arrays.sort(c2);
    //cria as novas strings baseadas nos arrays ordenados
    String sc1 = new String(c1);
    String sc2 = new String(c2);
    return sc1.equals(sc2);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Obrigada pela ajuda!


How to compare the significance of two models from two different datasets?

Question: I have two different regression models which I learned from two different data sets.
Is there any statistical method which shows the significance of models based on the number of parameters and cross validation errors?
The problem is that I used two different data sets and I worry that it might not make sense to compare two different models from two different data sets.
Answer: As I don't have enough reputation to comment, I'd put it here as an 'answer'.
But first of all, I am not very sure what you're looking for. I'd try my best to guess what you mean and please correct me if I'm wrong.
You have two difference statistical models, and the two models were based on two difference data-sets. You want to compare them for statistical significance.
Short answer: no, you can't.
Long answer: Basically when you compare two models, you want to know which one have a greater explanatory / predictive power with reference to the same data-set. Although you can compare the AICs (asymptotically equal to cross-validation errors) or even the R^2 (for linear regressions) but it is almost impossible to interpret the comparison. IN addition, to my knowledge, most common statistical tests for model fitness are designed for nested models only, i.e. your model A is a subset of model B.
Comment: You can't even compare AIC/BIC here.
Comment: @StudentT Agree. As I said, it is not interpretable for the comparison of AIC/BIC across data-sets.


Email Regular Expression Issue

Question: I have created the following regular expression for validating my email
^[_a-z0-9-]+(\.[_a-z0-9-])+@[a-z0-9-]+\.[a-z0-9-]+$

Now the issue that I am facing with the expression is an email of the following format is also being accepted
abc_xyz@gmail

I want the regular expression to enforce that the email address should contain the ".com/info/net" at the end , and that the above mentioned email format should be marked as invalid.
how can i achieve this
Comment: You're also disallowing upper-case letters. Also, that regex does not actually accept the string you say it does.
Comment: duplicate of http://stackoverflow.com/questions/201323/how-to-use-a-regular-expression-to-validate-an-email-addresses
Comment: In fact, Google can already apply for a "gmail" top level domain. It's pretty expensive but it can be done :)
Comment: You don't need to reinvent the wheel; there are plenty of examples and discussions on the web about email regexp's.
Comment: @ÁlvaroG.Vicario
Yea.. considering they got the money. :)

But in my case i would like to enforce the `.com` at the end, how can i achieve that
Comment: possible duplicate of [PHP email validation question?](http://stackoverflow.com/questions/2514810/php-email-validation-question). The question talks about PHP but the accepted answer is quite language agnostic.
Comment: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
Comment: possible duplicate of [JavaScript Regular Expression Email Validation](http://stackoverflow.com/questions/940577/javascript-regular-expression-email-validation)
Comment: this is not a duplicate as he wishes to constrain the domains and none of those questions answer that
Comment: @ori
well, i thought of posting a domain specific question as that might be helpful to others who want to implement it.
Comment: @Pointy
Yes, i overlooked that one. Thanks for the tip
Comment: Why are you trying to limit the tld's?  What about .me, .us, .gov, .name, etc?
Answer: ^[_a-z0-9-]+(\.[_a-z0-9-])+@[a-z0-9-]+\.(?:[A-Z]{2}|com|org|net|info)$

Try that. You can add as many other domain restraints as you wish. Just separate them with |
You may wish to take a look at this site: http://www.regular-expressions.info/ for more info   on regex, and http://www.regular-expressions.info/email.html for specific help on emails.
Comment: Thanks... I'll have a look at the sites that you have mentioned to understand the regular expression that you have built :)
Answer: You need to escape - inside your character classes, but still that email address should fail.
try:
^[a-zA-Z0-9][a-zA-Z0-9\._%\-\+]+@[a-zA-Z0-9\.\-]+\.[a-zA-Z]+$

even that prob does not cover all valid email addresses though...
Comment: Thanks... and yes you are right... it'll not cover all the valid email addresses... i can continue playing with it.. :)

Email Regular Expression Issue


Como converter array Bidimensional para um array Único?

Question: Eu tenho a seguinte definição do Array Bidimensional:
int[,] arrayBidimensional = new int[3, 3]
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

A variável acima, não tem um método .ToArray() para que o valor seja convertido para um array simples.
Como faço para converter esse array bidimensional para um int[ ] em vez de int[,] ? Existe uma forma simples de fazer isso?
Comment: A forma mais simples é percorrer as 2 dimensões do array (com um for), e atribuir os valores a um segundo array.
Comment: António Campos, podes exemplificar?
Answer: O algoritmo é simples: percorrer o array e criar um novo unidimensional.
using System;

class MainClass {
    public static void Main (string[] args) {
        int[,] arrayBidimensional = new int[3, 3]
        {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        var linhas = arrayBidimensional.GetLength(0);
        int colunas = arrayBidimensional.GetLength(1);
        var novoArray = new int[linhas * colunas];

        for(int i = 0; i < linhas; i++) {
            for(int j = 0; j < colunas; j++) {
                var indice = colunas * i + j;
                novoArray[indice] = arrayBidimensional[i, j];

                Console.WriteLine($"{indice} = {novoArray[indice]}");
            }
        }
    }
}

Veja funcionando no Repl.it
Pensando melhor, o código acima ainda pode ser simplificado para
using System;

class MainClass {
    public static void Main (string[] args) {
        int[,] arrayBidimensional = new int[3, 3]
        {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        var novoArray
            = new int[arrayBidimensional.GetLength(0) * arrayBidimensional.GetLength(1)];

        int indice = 0;
        foreach(var item in arrayBidimensional) {
            novoArray[indice] = item;
            Console.WriteLine($"{indice} = {novoArray[indice]}");
            indice++;
        }
    }
}

Veja funcionando no Repl.it
Comment: @AugustoVasques não altera, fica só pra quem editou.
Comment: se eu editar esse código do Repl.it essa alteração vai refletir no seu código ou a alteração é exclusiva para mim? Pergunto só por curiosidade, pois não ou vou fazer alteração nenhuma.
Answer: Podes fazer um cast.. não será o mais eficiente mas é simples:
int[] array1d = arrayBidimensional.Cast<int>().ToArray();

Comment: Na verdade, a eficiência é a maior possível, falando de complexidade. É a mesma eficiência do que o método da minha resposta. A única coisa que difere é ter alguma indireção a mais, são umas 2 chamadas a mais, uma tentativa de cast e, depois, um cast para cada item — que, sinceramente, não sei o que acontece, uma vez que o item já é do tipo que se tenta fazer o cast.


Fisher's Exact Test for many 2x2 data sets

Question: I'm trying to find an appropriate test or method to determine if the presence of a binary condition causes a separate binary result, given lots of situations (data points) of the 2x2 input/output space.  This would be Fisher's Exact test if I had just one sample set, but I have hundreds of 2x2 samples--I want to see if there is a causation relation over all the data.  Two entries in each 2x2 table are likely to have sparse nonzero entries across the whole dataset, so looking at any single 2x2 table wouldn't produce high confidence.  How can I expand the Fisher's Exact Test, or is there a more appropriate test for determining a causality relationship over the whole data set?
A clarifying example:
I want to determine if leaving crumbs on the kitchen counter attracts ants.  I've gathered data from 100s of neighborhoods all across the country, and each neighborhood has somewhere from 4-25 houses in it.  Each house reports if, on one day, they left food on the counter (condition), and whether or not they had ants (effect). Each neighborhood then reports how many houses were in the 4 possible Food/No Food, Ants/No Ants outcomes.  So my dataset looks like:

No Food/No Ants
No Food/Ants
Food/No Ants
Food/Ants

12
1
8
0

6
0
3
1

1
5
2
6

7
0
2
0

for 150 rows.  A lot of the rows look like the first & last row, where No Food is more than Food, and there are few numbers of Ants.  But there are a few occasional rows where this gets flipped, like Row #3.
I could add each column up and do a Exact test on the squished down 2x2.  However, not all neighborhoods have the same controlled conditions (there might be different species of Ants throughout the country), so I'm a little wary that this "squishing" eliminates some information that should be considered or would otherwise impact the analysis.  Is there an appropriate way to look at all the data and determine if Food causes Ants?
"multidimensional" Fisher's Exact?  2-proportion Z-test?
Thanks!
Answer: If you're comfortable making the large-sample assumption, you could use the Mantel-Haenszel test (though from your example data, this doesn't seem to be a good idea). Another option would be the stratified Fisher's exact test, where each of your neighborhoods could be considered a separate stratum. Finally, you could consider a mixed effects logistic regression.


Are more runs scored in the seventh inning due to the "changeover"?

Question: I have been told that more runs are scored in the seventh inning of baseball games than any other inning.
The reason would be the "changeover." If the starter is still pitching the seventh inning, it's probably his last, he's tired, and will probably give up more runs than in other innings. If a reliever is on the mound, he's probably not one of the two best (these pitch the eighth and ninth).
Is this in fact true?
Comment: @edmastermind29: I changed the question from a source question to a true-false question and wonder if it can be re-opened in its current form.
Comment: I'll reopen it...but note that the answers are now obsolete, unless elaborated upon to answer your question.
Comment: @edmastermind29: Thanks. The (original) answers were fine. I upvoted both and accepted one. Apparently there is a help center for questions. How do I go to it.
Comment: The answer regarding the Elias Sports Bureau does not address the in/validity of your stated theory (outside of saying "look here and you may find your answer" -- but that is an answer to your original question). [Here](http://sports.stackexchange.com/help/asking) are several help center items regarding asking questions.
Answer: Here are some links that disprove your hypothesis:
All Innings Are Not Created Equal
as well as many others:
2014 MLB Runs by Inning
including in depth analysis:
RPI Model
Another thing to consider is that the 7th inning is usually an inning that you see a reliever, or you continue to see a dominant starter.  In the reliever case, hitters production drops off (most people think it is because you only see that guy for one at bat every once in a while).  In the starter case, to begin the 7th inning the starter would be throwing a pretty solid game (probably a quality start) and it can be hard to say that even with the pitch count rising that he will be less effective.
Comment: I didn't "grow up" with Google and I didn't realize that the above searches could be done. (I'm old enough to personally remember Pirates like Roberto Clemente or Willie Stargell.) But thanks for the heads up.
Comment: Notice how the NL scores only .2 less runs than AL.  Certainly the run creation of the DH doesn't out weigh the strategy that it destroys.
Comment: @MarkMonforti Does it take away strategy, yes it does.  I can't stand watching pitchers hit. More runs, or less I'm a DH supporter.
Answer: Check out the Elias Sports Bureau. They keep statistics on all sorts of things across several sports.
Comment: Is this a free site? Or maybe a better question is what can I get free, and what do I have to pay for?
Comment: They don't seem to provide much information about how you can access the stats. My best recommendation would be to contact them.
Comment: FYI, the OP has changed his question.


Open preview in new window/page

Question: I'm using drupal 7.
Normally, during the creation of a contents, the preview is added above the form.
I would wish that the preview opens in a new window, and that it is separated from the form of creation of contents.
Do you know a solution?
Answer: This module looks like something that might fit your need: Simple preview

Open preview in new window/page


WebAPI Core routing issues

Question: So, I am playing around with Web API (ASP.NET Core 2) and having routing issues.
I have several controllers such as:
SchoolController
TeacherController.
Both have Gets: Get(int id)
Problem is that when I run it, I get a runtime error before even actually being able to invoke the methods.
Attribute routes with the same name 'Get' must have the same template:
Action: MyProject.WebAPI.Controllers.SchoolController.Get (MyProject.WebAPI)' - Template: 'api/school/{id}'
Action: MyProject.WebAPI.Controllers.TeacherController.Get (MyProject.WebAPI)' - Template: 'api/teacher/{id}'

Why would it do this when the controllers should have their own Gets etc... so you can do:
/api/{controller}/1

etc... ?

Now, I also have another Get method, both in their controllers but with a different method signature along with a different HttpGet name i.e:
// TeachersController:

[Produces("application/json")]
[Route("api/teacher")]
public class TeacherController : Controller
{

    // GET: api/Teacher/5
    [HttpGet("{id}", Name = "Get")]
    public IActionResult Get(int id)
    {

        // BLAH
    }
}

And for the school controller:
[Produces("application/json")]
[Route("api/school")]
public class SchoolController : Controller
{

    [HttpGet("{id}", Name = "Get")]
    public IActionResult Get(int id)
    {
        // BLAH
    }

    [HttpGet("SearchBasic")]
    public IActionResult SearchBasic(string schoolName, string zipCode)
    {
        // BLAH
    }
}

To be clear - the question is:

Why do I get the runtime errors as soon as the web app is started?
The get's are on different controllers, so why would there be any conflicts?
Comment: Right...you cant have actions with the same `Name` like you have in the controllers.
Answer: Controllers can't have actions with the same Route Name. They must be unique so that the route table can differentiate them.
Reference Routing to Controller Actions : Route Name

Route names can be used to generate a URL based on a specific route. Route names have no impact on the URL matching behavior of routing and are only used for URL generation. Route names must be unique application-wide.

emphasis mine
Update route names
[Route("api/teacher")]
public class TeacherController : Controller {

    // GET: api/Teacher/5
    [HttpGet("{id}", Name = "GetTeacher")]
    public IActionResult Get(int id) {
        //...
    }
}

[Route("api/school")]
public class SchoolController : Controller
{
    // GET: api/school/5
    [HttpGet("{id}", Name = "GetSchool")]
    public IActionResult Get(int id) {
        //...
    }
}

Comment: I wonder If there are 2 different Controller class, why .NET core doesn't allow same Action name - Get() ? Thanks
Comment: Great. Thank you. Fixed!
Comment: @Cheung because they end up in the same route table the names have to be unique. Even if in another controller.
Answer: Removing the name on get action from both controllers will solve the problem
Comment: I ran into this issue when using dotnet aspnet-codegenerator scaffolding.  The generated code adds a Name attribute to HttpGet.  Removing the Name attribute solved the problem.
Comment: Name is useful to use in CreatedAtRoute(nameof(GetTeacherAsync),new {}, res) response though
Comment: What is the exact reason ??

WebAPI Core routing issues


Custom Field into Custom Form

Question: I created a custom field to read qr codes from camera and it's working fine. Now I want to use this field or field widget in a custom form on the same custom module. Is it possible? Thank you,
Field Formatter
namespace Drupal\hospitator_qr_decode\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

/**
 * Plugin implementation of the 'hospitator_qr_decode_formatter_type' formatter.
 *
 * @FieldFormatter(
 *   id = "hospitator_qr_decode_formatter",
 *   label = @Translation("Hospitator QR Decode field formatter"),
 *   field_types = {
 *     "hospitator_qr_decode_field_type"
 *   }
 * )
 */
class HospitatorQrDecodeFormatterType extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {}

}

Field Type
namespace Drupal\hospitator_qr_decode\Plugin\Field\FieldType;

use Drupal\image\Plugin\Field\FieldType\ImageItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\SNcEH1C3UXSaTcNMHNLGNuLZqjGKbSrEMZce;
use Drupal\Core\TypedData\DataDefinition;

use Drupal\Core\Field\FieldStorageDefinitionInterface;

/**
 * Plugin implementation of the 'image' field type.
 *
 * @FieldType(
 *   id = "hospitator_qr_decode_field_type",
 *   label = @Translation("Hospitator QR decoder"),
 *   description = @Translation("This field stores the ID of an image file from webcam as an integer value."),
 *   category = @Translation("Reference"),
 *   default_widget = "hospitator_qr_decode_widget",
 *   default_formatter = "image",
 *   column_groups = {
 *     "file" = {
 *       "label" = @Translation("File"),
 *       "columns" = {
 *         "target_id", "width", "height"
 *       },
 *       "require_all_groups_for_translation" = TRUE
 *     },
 *     "code" = {
 *       "label" = @Translation("Hospitator QR code decoder"),
 *       "translatable" = TRUE
 *     },
 *   },
 *   list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
 *   constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
 * )
 */
class HospitatorQrDecodeItem extends ImageItem {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {}

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {}

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {}

  /**
   * {@inheritdoc}
   */
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {}

}

Field Widget
namespace Drupal\qr_decode\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Plugin\Field\FieldWidget\ImageWidget;
use Drupal\hospitator_qr_decode\Plugin\Field\FieldType\HospitatorQrDecodeItem;

use Zxing\QrReader;

/**
 * Plugin implementation of the 'hospitator_qr_decode_widget_type' widget.
 *
 * @FieldWidget(
 *   id = "hospitator_qr_decode_widget",
 *   label = @Translation("Hospitator Qr code widget"),
 *   field_types = {
 *     "hospitator_qr_decode_field_type"
 *   }
 * )
 */
class HospitatorQrDecodeWidget extends ImageWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {}

  /**
   * Form API callback: Processes a image_image field element from webcam.
   *
   * Expands the image_image type to include the alt and title fields.
   *
   * This method is assigned as a #process callback in formElement() method.
   */
  public static function process($element, FormStateInterface $form_state, $form) {}
}

And the custom Form
/**
 * @file
 * Contains \Drupal\hospitator_user_interface\Form\TimeTrackerForm.
 */
namespace Drupal\hospitator_user_interface\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class TimeTrackerForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'time_tracker_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['clock'] = array(
      '#type' => 'checkboxes',
      '#options' => array(
        'clock_in' => $this->t('Clock In'),
        'clock_out' => $this->t('Clock Out')),
      '#title' => $this->t('Select Clock Status'),
      '#required' => TRUE,
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Send'),
      '#button_type' => 'primary',
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if($form_state->getValue('clock')){
      drupal_set_message($this->t('Clock In submitted!'));
    }
    else{
      drupal_set_message($this->t('Clock Out submitted!'));
    }
  }
}

I just want to include my custom field and widget into my custom form.
Comment: There is a difference between a Field and a Form Element.
Comment: I edited the question in order to a better understanding. The question is ¿Can I include the Hospitator Qr Decode Field Ttype with its Widget to the Hospitator Time Tracker Form? Thank you,
Answer: Finally I solved the problematic creating an empty representative entity form time_tracker and got the widget with EntityFormDisplay.
$node = \Drupal::service('entity_type.manager')->getStorage('node')->create(array('type' => 'time_tracker'));

$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')->load('node.time_tracker.default');

if ($widget = $entity_form_display->getRenderer('field_clock')) {

  $items = $node->get('field_clock');
  $items->filterEmptyItems();

  $form['tracker'] = $widget->form($items, $form, $form_state);
}

Custom Field into Custom Form


IIS Rewrite rule to redirect and remove query string

Question: I'm trying to rewrite in IIS 7.5 from an old website to the new one. We have a list of URL's with and without query strings.
I can get the URL's without query strings to redirect but not with.
<rewrite>
    <rewriteMaps configSource="rewritemaps.config" />
    <rules>
    <rule name="Redirect Rule" stopProcessing="true">
      <match url=".*" ignoreCase="false" />
      <conditions>
        <add input="{StaticRedirects:{URL}}" pattern="(.+)" />
      </conditions>
      <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

this is the sample rewritemap:

add key="/boat-insurance/canoe.aspx" value="/boat/canoe-insurance" (this works)
add key="/boat-insurance/canoe/details.aspx?#details" value="/boat/canoe-insurance" (this does not)
Answer: It's possible to rewrite based on the query string (everything behind the ?) but the #details is NOT part of the query string. It's what is called the fragment identifier and it's a client-only part of the URL. The browser never sends that to the server so it's impossible for the server to use that for URL rewriting.
Comment: Thanks Marco, i could get the query string part to rewrite but the #details part was driving me up the wall !! Thanks for the pointer.


How to extract specific date format from a plain text (python)?

Question: I want to extract all dates (in the specific date format - January 1, 2020) into the dictionary in python. My text is for example:

"Psg January 1, 2020 hsjkfsdlkfhshdfh January 2, 1908 hdhahhajshjdjoi December 31, 2019 fafsfafagherhea"

I will then extract this into:
["January 1, 2020", "January 2, 1908", "December 31, 2019"]

I found the method str.split(). No success with this.
How can I do this?
Thank you for the help!
P.S.
Actually I want to extract that dates and then convert in the format:
"January 1, 2020" -> "1. January 2020"

and then turn it back in the text.
In the nutshell: I want to replace some format of date in text with some other format of a date.
Edit:
I have made the process. Thank you for your effort!
Comment: You should do this using regex
Comment: Possible duplicate of [Regex to match date like month name day comma and year](https://stackoverflow.com/questions/35413746/regex-to-match-date-like-month-name-day-comma-and-year/35413952)
Comment: @User123 Please, have a look at the [Why are some questions marked as duplicate?](https://stackoverflow.com/help/duplicates).
Answer: For this task is better to use regular expressions (re module in Python).
For example (Regex101 for explanation):
txt = '''Psg January 1, 2020 hsjkfsdlkfhshdfh January 2, 1908 hdhahhajshjdjoi December 31, 2019 fafsfafagherhea'''
import re

r = re.compile(r'(January|February|March|April|May|June|July|August|September|October|November|December)\s*(\d+),\s*(\d+)')

new_txt = r.sub(r'\2. \1 \3', txt)
print(new_txt)

Prints:
Psg 1. January 2020 hsjkfsdlkfhshdfh 2. January 1908 hdhahhajshjdjoi 31. December 2019 fafsfafagherhea

Answer: Using a regex like will help you easily '((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d+,\s+\d+)'
message = "Psg January 1, 2020 hsjkfsdlkfhshdfh January 2, 1908 hdhahhajshjdjoi December 31, 2019 fafsfafagherhea"
matches = re.findall(
    r'((?:January|February|March|April|May|June|July|August|September|October|November|December)\s+\d+,\s+\d+)',
    message)
for match in matches:
    print(match)

Then for the date format, use strptime and strftime
from datetime import datetime

input_format = "%B %d, %Y" # full month name, day and year
output_format = "%d.%B %Y"
for match in matches:
    new_date = datetime.strptime(match, input_format).strftime(output_format)
    print(match, ">>", new_date)

Answer: This has been asked a dozen times. Imo the best way is to use a library, e.g. datefinder:
import datefinder
text = "Psg January 1, 2020 hsjkfsdlkfhshdfh January 2, 1908 hdhahhajshjdjoi December 31, 2019 fafsfafagherhea"
matches = datefinder.find_dates(text)

for match in matches:
    print(match)

Which yields
2020-01-01 00:00:00
1908-01-02 00:00:00
2019-12-31 00:00:00

Answer: You can use the function find() to research the index of any month and you can count the character to extract
Seen : https://www.journaldev.com/23666/python-string-find
Answer: months = ['January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December']

date_info = "Psg January 1, 2020 hsjkfsdlkfhshdfh January 2, 1908 hdhahhajshjdjoi December 31, 2019 fafsfafagherhea"

for month in months:
    while month in date_info.split():
        m = month
        day = date_info.split()[date_info.split().index(month) + 1]
        year = date_info.split()[date_info.split().index(month) + 2]
        self_str = month + " " + day + " " + year
        rep_str = day.strip(',') + ". " + month +"~ " + year
        date_info = date_info.replace(self_str, rep_str)
while '~' in date_info:
    date_info = date_info.replace("~", "")
print(date_info)

Comment: is this the output you were looking for ?
Comment: Thank you, but I have made it in the different way.
Answer: Pure regex solution would be to use following regex to extract the specific date format strings from the given sentence :
\w+\s+\d{1,2},\s+\d{4}
Regex explanation and demo can be found here.
Then use this regex in re.findall function to match all occurrences of a pattern and return such occurrences.
import re
str = "Psg January 1, 2020 hsjkfsdlkfhshdfh January 2, 1908 hdhahhajshjdjoi December 31, 2019 fafsfafagherhea"
x = re.findall("\w+\s+\d{1,2},\s+\d{4}", str)
print(x)

Output :

['January 1, 2020', 'January 2, 1908', 'December 31, 2019']


Using a variable as a fixed effect and random effects grouping variable in linear mixed effects model

Question: I am trying to decide what is the right random effects structure for my given experimental design. I've read quite a few of the other posts regarding linear mixed effects models and have come across papers like the Barr et al., 2013 paper suggesting to use the maximal random effects structure for confirmatory hypothesis testing. However, for the random effects structures that I am deciding between, I have not come across a representative example and would love to get input from others more experienced with LMEs.
For context, I have a study with 15 subjects. Each subject (on a different day) conducts a task with a different pair of shoes on. I have 5 different pairs of shoes (treated as a categorical variable A,B,C,D,E). They conduct the task multiple times in the morning and multiple times in the afternoon. I want to understand how the pair of shoes and time of day ultimately impact their performance on the task.
Since my two factors of interest are the shoe and time of day I have been treating those as fixed effects. I know there is subject variability, so I have also been including a random intercept term for each subject. However, the shoes and time of day might have a different effect on each subject, so I have been thinking I should include a random slope for these terms as well. Then, my formula would be:
Y ~ Shoe + TimeOfDay + (Shoe + TimeOfDay | Subject)
I generally think this makes sense, but the only concern I have is that because the subject wears a different shoe on a different day, there might be some variability from day-to-day. So instead, I have been thinking of the following random effects structure to capture that:
Y ~ Shoe + TimeOfDay + (TimeOfDay | Shoe:Subject)
Now my grouping variable would be every combination of shoe/subject (essentially each day). And I am saying that each day, the time of day could have a different effect.
My core question is: Can I have a random effects structure like the latter? Where I have a fixed effect also used as part of a grouping variable in a random effect? It seems weird to me to look at variation across days as a random effect when part of the variation across days is what I am interested in capturing as part of the "Shoes" fixed effect. Given my design, are there any suggestions on how to decide between the two random effects structures that I am considering?
Answer: Discussion
It is unfortunate that many come across the Barr et al., 2013 paper before they see discussion about why the advice in that paper is poor (or at least doesn't acknowledge the major flaws with maximal models when specified by default). A good paper on the subject is Matuscheck et al., 2017, which talks about some of these issues, namely the sacrifices in power that arise from this design but more importantly the poor convergence rates of many maximal models. The type of data you have will largely shape what random effects you may actually be able to employ. You can check out the guides below in the references for how to optimally fit your models.
It would be good to summarize and plot your data with respect to the model you are trying to fit first. If it becomes clear that your data doesn't have meaningful variation with respect to random slopes, a random intercept-only model is often the better and easier choice for fitting. If your data indeed has large variation in slopes and intercepts, then perhaps you can consider a maximal model, but this still requires that you have enough data to even achieve that.
As for your model specification, there doesn't appear to be anything inherently wrong with the first model, but given that you include multiple random slopes in one cluster, you are more prone to some of the convergence/power issues I noted if your data doesn't match the model. The second model isn't specified as well, as it assumes that subjects are nested within shoes, where it should be shoes within subjects, noted (TimeofDay | Subject/Shoe). This is because each subject tries on every pair of shoe (note that vice versa isn't possible true).  Usually you want to specify the group "g" as (1 + x | g1/g2), as this includes both the overall random intercepts of g1 but also that of g2 within g1.
References

Barr, D. J., Levy, R., Scheepers, C., & Tily, H. J. (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68, 255–278. https://doi.org/10.1016/j.jml.2012.11.001
Bates, D., Mächler, M., Bolker, B., & Walker, S. (2015). Fitting linear mixed-effects models using lme4. Journal of Statistical Software, 67(1). https://doi.org/10.18637/jss.v067.i01
Brown, V. A. (2021). An introduction to linear mixed-effects modeling in R. Advances in Methods and Practices in Psychological Science, 4(1), 1–19. https://doi.org/10.1177/2515245920960351
Matuschek, H., Kliegl, R., Vasishth, S., Baayen, H., & Bates, D. (2017). Balancing Type I error and power in linear mixed models. Journal of Memory and Language, 94, 305–315. https://doi.org/10.1016/j.jml.2017.01.001
Meteyard, L., & Davies, R. A. I. (2020). Best practice guidance for linear mixed-effects models in psychological science. Journal of Memory and Language, 112, 104092. https://doi.org/10.1016/j.jml.2020.104092
Comment: You cant have shoe as both a random slope and random intercept, as shoe doesnt vary within shoe. Its acceptable to have as a fixed effect and random slope.
Comment: Thanks! This is very helpful. For the comment about the second model not being well specified - I think that might be a notation difference between MATLAB and r. Specifically I am using MATLAB's ```fitlme``` function which uses Wilkinson's notation for defining the model equation: https://www.mathworks.com/help/stats/fitlme.html. Specifically, using ```Shoe:Subject``` should consider the independent interaction between Shoe and Subject. However, I am still concerned whether including a random intercept for the combination of shoe/subject is misinformed if I also have a Shoe fixed effect
Comment: Sorry, it may not have been clear. I am not trying to make shoe both a random slope and random intercept. I am wondering if I can have a random effects structure as follows: ```(TimeOfDay | Subject:Shoe)```. In MATLAB, the notation ```Subject:Shoe``` means that I will have a random intercept for each combination of subject and shoe. I am not familiar with R notation, but my guess is that the full model structure in R would be something like: ```Y ~ Shoe + TimeOfDay + (TimeOfDay | Subject/Shoe)```. As you will see, Shoe is both a fixed effect and part of the random intercept grouping
Comment: Your intuition seems correct for how this is with R with a minor caveat. To clarify, the `:` operator here shows the combination of both random effect clusters here in the way you describe for Matlab (it will display all combinations of both). The `/` operator also adds the overall intercept of Subject, so if you are *only* interested in the Subject by Shoe combinations then you can just specify it with `:` instead of `/`.


PHP Menu Items Count then add under more button

Question: I use the bellow code to load the main menu elements from some CMS, the present code is perfect except that it loads ALL the main items on a single line of menu - which will make the width of it unusable in any centered design (under 1000px).. I want to change this script so after 15 main elements will add a "MORE" button under which the rest of the main menu items will show as sub-items of this "MORE" button (they will not have their own sub-items as the first 15 do).. How can I do it?
Thanks!
        <?php

require_once( '../../../inc/header.inc.php' );
require_once( DIRECTORY_PATH_INC . 'membership_levels.inc.php' );
require_once( DIRECTORY_PATH_ROOT . "templates/tmpl_{$tmpl}/scripts/TemplMenu.php" );

            class SimpleMenu extends TemplMenu
            {
            function getCode()
            {
            $this->iElementsCntInLine = 100;
            $this->getMenuInfo();
            $this->genTopItems();
            return $this->sCode;
            }

            function genTopItem($sText, $sLink, $sTarget, $sOnclick, $bActive, $iItemID, $isBold = false, $sPicture = '')
            {
            $sActiveStyle = ($bActive) ? ' id="tm_active"' : '';

            if (!$bActive) {
            $sAlt= $sOnclick ? ( ' alt="' . $sOnclick . '"' ) : '';
            $sTarget  = $sTarget  ? ( ' target="_parent"' ) : '';
            }

            $sLink = (strpos($sLink, 'http://') === false && !strlen($sOnclick)) ? $this->sSiteUrl . $sLink : $sLink;

            $sSubMenu = $this->getAllSubMenus($iItemID);

            $sImgTabStyle = $sPictureRep = '';
            if ($isBold && $sPicture != '') {
            $sPicturePath = getTemplateIcon($sPicture);
            $sPictureRep = "";
            $sText = ' ';
            $sImgTabStyle = 'style="width:38px;"';
            }

            $sMainSubs = ($sSubMenu=='') ? '' : " {$sSubMenu} ";
            $this->sCode .= "

{$sPictureRep}{$sText}

{$sMainSubs}

            ";
            }
            }

            $objMenu = new SimpleMenu();
            echo "
";
            echo $objMenu->getCode();
            echo "
";

    ?>

Answer: Personally I'd use CSS and Javascript (+jQuery) to do this.
Use Javascript to find any lis within ul#ddmenu that have an index of 15 or more, and give them a different class. Then, add your "More" button, and use onclick/hover etc to display the remaining lis.


How to change the title and html on slideToggle

Question: I have this HTML markup:
Hide comments
Hide comments

I'll like to change the title and HTML to "Show comments" on slideToggle but didn't know how. I write this code to show/hide a DIV:
$('.comment-show-link').click(function(e) {
        $('#comment-show-'+$(this).attr("hreflang")).slideToggle('slow');
        e.preventDefault();
});

But not know how to check if DIV is hidden or visible and in each case change title and HTML. Also I know that I can use text() or html() jQuery functions to achieve this but how? Any help?
Thanks in advance
Comment: See [How can I test if an element is already visible?](http://stackoverflow.com/questions/4410211/how-can-i-test-if-an-element-is-already-visible) and [How to change the value of multiple html attribute?](http://stackoverflow.com/questions/7795945/how-to-change-the-value-of-multiple-html-attribute). To learn how certain jQuery methods work, **read their documentation**: http://api.jquery.com/text/, http://api.jquery.com/html/.
Answer: Try this:
$('.comment-show-link').click(function(e) {
        var $this = $(this);
        var num = $this.attr('hreflang');
        $('#comment-show-'+num).slideToggle('slow', function(){
            if ($(this).is(':hidden')) {
               // do something here
               // $this.attr('...', '...')
            }
        });
        e.preventDefault();
});

Comment: Nice, this works! Thanks points and accept answer goes to you @undefined
Comment: one last question, I'm trying to change the HTML but it changes for every element in the page I want to change only the one I clicked this is the code I'm using: http://pastebin.com/f0Nrrpfn what's wrong?
Comment: @ReynierPM there is nothing wrong with your code, do you have multiple elements with same IDs?


Solving integrals using partial fractions

Question: I'm learning partial fractions. However, I am not sure about when to put $A, B, C..$ into the numerator and when to put $Ax+B, Bx+C..$ into the numerator.
For example, I have the following integral:
$$\int \frac{x^5}{(x-1)^2(x^2-1)}dx$$
and I want to calculate simplify using partial fractions.
I know that $(x-1)^2$ has just one real solution, so I will write it as $\frac{A}{x-1}+\frac{B}{(x-1)^2}$.
However, $x^2-1$ has two real solutions, $\{-1, 1\}$.
Do I write is as $\frac{Cx+D}{(x^2-1)}$ or just $\frac{C}{(x^2-1)}$?
I am really not sure about when to use the simple form $A,B$ and when to use $Cx+D, Dx+E$.
Thanks
Comment: $(x-1)(x^2-1)=(x-1)^3(x+1)$
Comment: @IsaacYIUMathStudio Thanks, but I rather need some theory about how to use partial fractions.
Answer: Actually, since the degree of the numerator is not smaller than the degree of the denominator, your first step should be to write $x^5$ as$$(x+2)\times\bigl((x-1)^2(x^2-1)\bigr)+4x^3-2x^2-3x+2.$$So$$\frac{x^5}{(x-1)^2(x^2-1)}=x+2+\frac{4x^3-2x^2-3 x+2}{(x-1)^2(x^2-1)}.$$On the other hand,$$x^2-1=(x-1)(x+1)\implies(x-1)^2(x^2-1)=(x-1)^3(x+1)$$and therefore you should try to get $A$, $B$, $C$ and $D$ such that$$\frac{4x^3-2x^2-3 x+2}{(x-1)^2(x^2-1)}=\frac A{x-1}+\frac B{(x-1)^2}+\frac C{(x-1)^3}+\frac D{x+1}.$$
Comment: So the nominator can't have higher degree than the denominator?
Comment: No, it cannot. ${}$
Comment: But in school we solved $\frac{2x^3+8x^2-8x-22}{(x+3)^2(x^2+1)}$ and we went straight to partial fractions, we didn't lower the degree of denominator. Could you explain why? And also I use the $Ax+B$ form only when I have no real solutions or also when we have two real solutions?
Comment: In that example, the numerator has degree $3$ and the denominator has degree $4$. So, in that case you are ready to do the partial fraction decomposition.
Answer: A general rule of thumb is to never leave things that can be further simplified. For example,

prefer $\frac{A}{x+1} + \frac{B}{x-1}$ to $\frac{Cx+D}{x^2-1}$
prefer $\frac{A}{x}+\frac{B}{x^2}$ to $\frac{Ax+B}{x^2}$

Of course, you are not obliged to follow this rule to the point - if you see a clear gain to not use, do not use it.
Comment: Okay, but could you please answer my question - do we use the form $Ax+B$ when we have no real solutions and when we have two real solutions?


Partial integration for smooth functions with compact support

Question: Let

$d\in\mathbb N$
$\lambda$ be the Lebesgue measure on $\mathbb R^d$
$\Omega\subseteq\mathbb R^d$ be open

Why can we use partial integration to obtain $$\int_\Omega\phi\Delta\psi\;{\rm d}\lambda=-\int_\Omega\nabla\phi\cdot\nabla\psi\;{\rm d}\lambda\tag 1$$ for all $\phi,\psi\in C_c^\infty(\Omega)$?

The multi-dimensional partial integration is a special case of the divergence theorem. But the divergence theorem in the version that I know only can be applied on compact subsets $K$ of $\mathbb R^d$ with smooth boundary $\partial K$. Smooth boundary means that for all $p\in\partial K$, there is an open set $U\subseteq\mathbb R^d$ with $p\in U$ such that there is a continuously differentiable $F:U\to\mathbb R$ with

$K\cap U=\left\{x\in U:F(x)\le 0\right\}$ and
$F'(x)\ne 0$ for all $x\in U$

Let's so what we've got in the situation of $\phi,\psi\in C_c^\infty(\Omega)$. Suppose we can find a compact $K$ with smooth boundary such that $K\subseteq\Omega$ and $\operatorname{supp}\Delta\psi\subset K$. Then it's easy to conclude that $$\int_\Omega\nabla\phi\cdot\nabla\psi+\phi\Delta\psi\;{\rm d}\lambda=\int_K\nabla\phi\cdot\nabla\psi+\phi\Delta\psi\;{\rm d}\lambda=\int_{\partial K}\phi\frac{\partial\psi}{\partial\nu}\;{\rm d}o=0$$
by the divergence theorem, since $\phi$ vanishes at $\partial K$.

So, can we always find such a $K$? If not, how can we prove $(1)$ instead?
Answer: You do not need to find such a set $K \subset \Omega$!
At first, let us assume that $\Omega \subset \mathbb{R}^d$ is bounded. Then there is an open ball $B_R(0) \subset \mathbb{R}^d$ such that $\Omega \subset B_{R/2}(0)$. For every function $\varphi \in C_c^{\infty}(\Omega)$, we define an extension $\tilde{\varphi} \colon B_R(0) \to \mathbb{R}$ by
\begin{align}
\tilde{\varphi}(x) &:= \varphi(x) &\text{ for } x \in \Omega, \\
\tilde{\varphi}(x) &:= 0 &\text{ otherwise.}
\end{align}
Then $\tilde{\varphi} \in C_{c}^{\infty}(B_R(0))$.
Let $\varphi, \psi \in C_c^{\infty}(\Omega)$. As above, we construct extensions $\tilde{\varphi}, \tilde{\psi} \in C_c^{\infty}(B_R(0))$. As the ball $B_R(0)$ has a smooth boundary, we are allowed to integrate by parts. So we obtain that
\begin{equation}
\int_{\Omega} \varphi \Delta \psi = \int_{B_R(0)} \tilde{\varphi} \Delta \tilde{\psi} = - \int_{B_R(0)} \nabla \tilde{\varphi} \cdot \nabla \tilde{\psi} = - \int_{\Omega} \nabla \varphi \cdot \nabla \psi.
\end{equation}
This proves the claim for bounded domains $\Omega$.
If $\Omega \subset \mathbb{R}^d$ is not bounded, then there is no ball $B_R(0) \subset \mathbb{R}^d$ such that $\Omega \subset B_{R/2}(0)$. However, our construction from above works! This is because  for $\varphi \in C_c^{\infty}(\Omega)$ the support of $\varphi$ is a compact set; in particular, $\text{supp} \, \varphi \subset \mathbb{R}^d$ is bounded. So we find a ball $B_R(0) \subset \mathbb{R}^d$ such that $\text{supp} \, \varphi \subset B_{R/2}(0)$. Now, you can define the same extension $\tilde{\varphi} \colon B_R(0) \to \mathbb{R}$ as above. This proves the claim for unbounded domains $\Omega$.