Asymptotic behaviour of a sequence of functions

Question: In an article I'm reading, $m$ is a natural number,
$$
H_m = 1 + 1/2 + 1/3 + \cdots + 1/m,
$$
the $m$-th Harmonic number,
$$
p_i=\frac{1}{i H_m} \quad \mathrm{for} \quad i \in \{1, \ldots, m\}
$$
(so that the $p_i$ are the values of a probability distribution),
$$
\Theta_m(t)=\prod_{i=1}^m (1-e^{-p_i t})
$$
for $t>0$, and
$$
F_m(x) = -\log \Theta_m(xm \log m H_m),
$$
which I take to mean $-\log \Theta_m(xm (\log m) H_m)$. It is said that for fixed $x$, as $m \to \infty$, we have
$$
F_m(x) \to \infty, \quad \mathrm{if} \quad x<1
$$
and
$$
F_m(x) \to 0, \quad \mathrm{if} \quad x \geq 1.
$$
I have tried to prove this using the bounds
$$
-m \log(1-m^{-xm}) \leq -\log \Theta_m(xm (\log m) H_m) \leq -m \log(1-m^{-x}), \tag{1}
$$
which I derive from
$$
\frac{1}{mH_m} \leq p_i \leq \frac{1}{H_m}, \quad i \in \{1, \ldots, m\}.
$$
Fixing $x > 1$ (my argument doesn't work for $x=1$, which may or may not matter later) and applying L'Hopital's rule to the upper bound in (1), I find that it tends to $0$ as $m$ tends to infinity, which suffices to prove that $F_m(x)$ tends to $0$ as $m$ tends to infinity, as is required.
However, fixing $0<x<1$ and applying L'Hopital's rule several times to the lower bound in (1), I find that it also tends to $0$ as $m$ tends to infinity, which is not sufficient to prove that $F_m(x)$ tends to infinity.
I suppose that my bound $p_i \leq \frac{1}{H_m}$ for all $i$ is not sharp enough.
My next attempt was to use the downward-concavity in $p$ of the function $\log(1-e^{-pt})$, which can be verified by differentiating twice with respect to $p$. This yields
$$
-\log \Theta_m(t) \geq -m \log(1-e^{-\frac{t}{m}}),
$$
hence
$$
F_m(x) \geq -m \log(1-m^{-x H_m}).
$$
Certainly, $m^{-xH_m}$ tends to $0$ more slowly than does $m^{-xm}$, which suggests a better chance of success than with the previous bound. In order to apply L'Hopital's rule to compute $-\lim_{m \to \infty} m \log(1-m^{-x H_m})$ for $0<x<1$, I think I need to extend $H_m$ to the real numbers using
$$
H_m = \psi(m+1)+\gamma,
$$
where $\psi$ is the digamma function and $\gamma$ the Euler-Mascheroni constant. However, according to Wolfram Alpha, the limit when $x=0.9$ is $0$, not infinity, as hoped.
How can I prove that $F_m(x) \to \infty$ when $x<1$ ?
Answer: Concavity of the logarithm tells us  $\log(1-a)\le -a$ for all $a<1$. So $$F_m(x)= -\sum_{i=1}^m\log\left(1-e^{-x(m/i)\log m}\right)\ge \sum_{i=1}^m e^{-x(m/i)\log m}.$$
If $0<x<1$, for values of $i$ in the range $\sqrt x m \le i \le m$ we have $$\sqrt x \le \frac i m \le 1$$ and hence $$
e^{-\frac 1{\sqrt x}}\le e^{-\frac m i }\le e^{-1}$$
and
$$
e^{-\sqrt x\log m }\le e^{-x\frac m i\log m  }\le e^{-x\log m}.
$$
The sum of these lower bounds is $$\sum_{i=\sqrt x m}^m e^{-\sqrt x\log m }\approx (1-\sqrt x)e^{(1-\sqrt x)\log m},$$ which grows without bound as $m\to\infty$.
Comment: That's fantastic ! Thank you very much @kimchi lover. I think there is a trivial typo: Should $a>-1$ be $a<1$ ?
Comment: You're right. Thanks for the catch.
Comment: I really like your proof. It seems that your strategy was to show that sufficiently many terms are sufficiently large.
Comment: I hate to bother you, @kimchi lover, but would you be so kind as to take a look at this follow-up question ? https://math.stackexchange.com/q/3588010/159855
Comment: Will do, but not just now.
Comment: Very many thanks !


Detect when audio.play() has finished

Question: I'm using audio.play() inside my React project to trigger a clip onClick, but I'm having trouble figuring out how to determine when the clip has stopped playing so I can do something after it has finished.
class Soundboard extends Component {
    getAudio = (clipUrl) => {
        var audio = new Audio(clipUrl);
        return audio.play();
    };

    render() {
        return (

 this.getAudio(pathToClip)}
          />

        );
    }
}

Answer:
audio.onended=function()
{
    alert("audio ended");
}

Detect when audio.play() has finished


Too Many index.php processes with high memory usage

Question: I have wordpress site installed over dedicated server in a separate cpanel account. From couple of days this account experiencing high memory usage, high loadtime and freezing frequently. so I have made certain tests to find the culprit

I checked plugin impact through p3 plugin profiler but impact was normal around 25 %
Then I run the top command and sorted the results by Memory. I found many php processes running for this account and consuming memory:

Then I checked which scripts or files these processes are accessing through 'ps -ef | grep career99' command, I found they all were index.php files:

How can I debug this, which is causing this issue?
How I can solve this issue?
Answer: i'm not certain about this, but first make sure you are reading the memory descriptions correctly. linux will clump similar processes together, but often times this is misread as "linux has ate my memory". see this page for more info: http://www.linuxatemyram.com/
once you are sure this is your bottle neck, you might consider a few things.
how is PHP being executed? are you using mod_php, or are you executing it as a CGI? are you using fast cgi? or a fast cgi daemon?
if you are using mod_fcgid, for example, you might need to configure it to correctly destroy children processes that are no longer in use. or set an upper limit.


PHP regexp - how to extract all occurances of a pattern

Question: I have a string that contains multiple WIKI-type tags.  e.g. [[TAG:4567]].  I need to identify/extract all tags from the string so I can perform substitution later.
For example, for this string:
this is a test [[TITLE]] of more test [[LINK:27654]]

I want an array of:
0: [[TITLE]]
1: [[LINK:27654]]

I thought that PHP preg_match might work, but it returns a whole bunch of extra character between the regexp matches.  But I think it only works with one match in the subject string.  This is what I tried:
$subject = "this is a test [[TITLE]] of more test [[LINK:27654]]";
preg_match( '/(?<=\[\[)(.*)(?=\]\])/', $subject, $matches );
print_r($matches);

But it gives me:
Array (
    [0] => TITLE]] of more test [[LINK:27654
    [1] => TITLE]] of more test [[LINK:27654
)

Which isn't what I need.  Is there a simple way to extract the tags?  I'd really like to avoid iterating through the string and extracting manually.
Answer: Looks like an easier (and also correct) regex to solve this would be
/\[\[(.*?)\]\]/

Answer: Try this code snippet here
<?php

ini_set('display_errors', 1);
$subject = "this is a test [[TITLE]] of more test [[LINK:27654]]";
preg_match_all('/\[\[.*?\]\]/', $subject, $matches );
print_r($matches);

Comment: preg_match_all was the key.  Wish I could mark both as answers.


How to make aws crawler recognize new partition structure in s3

Question: I have the structure below in the s3:
s3://landing-zone/api/report/task=log-results/year=2022/month=1/day=1/hour=0/minute=18/file.csv
I want to store all the new files just until hour like:
s3://landing-zone/api/report/task=log-results/year=2022/month=1/day=1/hour=0/file.csv
I tried adding the new files just until hour folder but the aws crawler can't get these new files available to athena.
What is the best way to make it works?
Answer: I suppose that you have partitions year, month, day, hour and minute in the Athena table. Let's say it is tableA. You can create a tableB with exactly the same schema but using partitions year, month, day and hour. Then you do an INSERT AS A SELECT for each 60 minutes to group rows of 1 hour.
INSERT INTO tableB
SELECT col1, col2, SUM(col3)
FROM tableA
GROUP BY col3 <ONLY 60 MINUTES TO GATHER 1 HOUR>;

You will need to do one insert for each 60 minutes. In the end you will get S3 buckets for tableB smaller than tableA.


Show that if $S$ is a finite set with n elements, then $S$ has $2^n$ subsets by using mathematical induction

Question: I don't understand this exercise of mathematical induction. I also have the answer but I still don't get it. The exercise says the following:

Use mathematical induction to show that if $S$
  is a finite set with n elements, then $S$ has $2^{n}$ subsets.

And the answer is:

BASIS STEP: $P(0)$ is true, since a set with zero elements, the empty set, has exactly
  $2^0 = 1$ subsets, since it has one subset, namely, itself.
INDUCTIVE STEP: Assume that $P(k)$ is true, that is, that every set with $k$ elements has $2^k$ subsets. It must be shown that under this assumption $P(k + 1)$, which is the statement that every set with $k + 1$ elements has $2^{k+1}$ subsets, must also be true.
To show this, let $T$
  be a set with $k + 1$ elements. Then, it is possible to write $T = S ∪ \{a\}$ where $a$ is one of the elements of $T$ and $S = T - \{a\}$. The subsets of $T$ can be obtained in the following way. For each subset $X$ of $S$ there are exactly two subsets of $T$, namely, $X$ and $X ∪ \{a\}$. These constitute all the subsets of $T$ and are all distinct. Since there are $2^k$ subsets of $S$, there are $2 · 2^k$ = $2^{k+1}$ subsets of $T$.

I understand everything up to 'which is the statement that every set with k+1 elements has $2^{k+1}$ subsets, must also be true'. I know that we start by evaluating the first element P(0) to see if it's true and we try to show that P(k) is true to then show that P(k+1). But I don't get the part in which T is the union of S and {a} and so on.
Does anyone understand this? Thank you.
Comment: @quasi Yes, thank you very much.
Comment: About the part $T = S \cup \{a\}$, that's just saying that if $T$ has $k+1$ elements, then for any element $a \in T$, the set $T$ is a union of a $k$ element set $S$ and $\{a\}$.
Answer: An example might help . . .

Suppose $k = 3$.

Let $T$ be a set of $4$ elements, say $T = \{a,b,c,d\}$.

Then $T = S \cup \{a\}$, where $S = \{b,c,d\}$ is a set of $3$ elements.

Suppose we've already shown that any set with $3$ elements has $2^3 = 8$ subsets. Thus, we know that $S$ has $8$ subsets.

Each subset of $S$ is also a subset of $T$, so $T$ has those $8$ subsets to begin with.

But for each of the $8$ subsets of $S$, there is a new subset of $T$ obtained by including the element $a$ as an additional element. That yields $8$ more subsets.
Thus, $T$ has $2^3 + 2^3 = 2\cdot 2^3 = 2^4$ subsets.
Answer: Let $A=\{Y\subset T \}$ and $B=C\cup D$ where $C=\{X\cup \{a\}:X\subset S\}$ and $ D= \{X\subset S\}$
$A=B$, and $C$ and $D$ are disjoint and contain the same number of elements, which is $2^k$ by induction.
Answer: Well that is because, you will use the inductive hypotesis.
So, if you want to prove $P(k+1)$, then the set must have $k+1$ elements.
They named that set $T$
So if you take $k$ elements of $T$ and build the subset $S$ with those $k$ elements, then $T = S \cup $ { $a$ }  where $a$ is the element that was not among the chosen $k$


Error after installing mysqlnd_ms

Question: I am working on Amazon EC2 using the Amazon Linux AMI which is based on CentOS. I have installed php54 and php54-mysqlnd.
Then I do a sudo pecl install myslqnd_ms. This installs fine. I add the extension into the php.ini file. Then I start httpd, and when I do in the error log I see:
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/mysqlnd_ms.so' - /usr/lib64/php/modules/mysqlnd_ms.so: undefined symbol: mysqlnd_globals in Unknown on line 0

Googling this lead me to this thread on bugs.php.net and other forum. Neither of which helped me much.
What would be the best solution here? I am trying to stick to stock pre built binaries from the main YUM repo if possible.
Answer: To resolve this issue:
Remove the lines like:
mysqlnd_ms.enable=1
mysqlnd_ms.force_config_usage=1
mysqlnd_ms.config_file=/etc/mysqlnd_ms_cfg.ini
extension=mysqlnd_ms.so

from the php.ini file
Create a new file called /etc/php.d/mysqlnd_ms.ini and put those lines in there and restart php-fpm
service php-fpm restart

Error after installing mysqlnd_ms


Image segmentation by texture? Cannot find any source code

Question: I have been looking for a long time for code to do image segmentation by texture. There seems to be many papers but I cannot find any code. Has anyone come across any code to do this? Either in opencv or any other?
Comment: Thanks, but its not a matter of how easy or hard, its a matter of minimizing my time on the task as I have so many other tasks to do.
Comment: Why you don't want even try to implement something you read in papers? It not so hard. Try gabor filter banks and svm, for instance (less than 1000 lines of code) and works rather good.
Comment: @AndreySmorodov, sorry your answer here is old, I am new with texture image. Could you put any link to that by gabor filter banks and svm, please?
Answer: I found some source code here.
http://www.iro.umontreal.ca/~mignotte/ResearchMaterial/
It seems likely that this will satisfy my need for source code for image segmentation by texture for the moment.
Answer: Just made a repo with code https://github.com/Smorodov/gabor_segmentation
The code is rather old, so may be it will be needed to small modifications to openCV's changes.
It uses kmeans to automatically segment texturrs by clustering.
If you want to use different classifier, you can check, pointsclassifier.cpp example in standaed opencv's examples.
Sample of segmented image:


FFMPEG works on Console but doesn't work in PHP script on Ubuntu

Question: I have this aplication where I need to convert video files to MP4 and then compress it. I'm trying to use FFMPEG to get this to work. Tried the command lines in the console and it works great
Converting
ffmpeg -i teste.avi teste.mp4

Compressing
ffmpeg -i teste.mp4 -acodec mp2 teste.mp4

But when I do the same within a PHP script, it starts yelling that something called GLIBCXX is not installed. This is the error:
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.11' not found (required by /usr/lib/i386-linux-gnu/libjack.so.0)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.9' not found (required by /usr/lib/i386-linux-gnu/libjack.so.0)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /usr/lib/i386-linux-gnu/libjack.so.0)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.9' not found (required by /usr/lib/i386-linux-gnu/libzmq.so.3)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by /usr/lib/i386-linux-gnu/libzmq.so.3)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.11' not found (required by /usr/lib/i386-linux-gnu/libopencv_core.so.2.4)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.9' not found (required by /usr/lib/i386-linux-gnu/libopencv_core.so.2.4)
ffmpeg: /opt/lampp/lib/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by /usr/lib/i386-linux-gnu/libopencv_core.so.2.4)

This is my script
$r = shell_exec("ffmpeg -i $file_path $output_path 2>&1"); //convert
$r = shell_exec("ffmpeg -i $file_path -acodec mp2 $file_path 2>&1"); //compress

I'm running the script on Ubuntu
@edit
I can run, for example, shell_exec('ls')
Comment: How did you install ffmpeg? Why are you running "LAMPP"?
Answer: You are running a XAMPP server, so everything in there is running with the libraries that came with it. The problem is that now you trying to run a program that uses the system libraries and on an environment that has been set up to use a particular another libraries. You have two choices:

Install the LAMP stack on your Ubuntu box from the repository. tasksel makes that a breeze. That way PHP will run in the same environment ffmpeg is running.
Setting the LD_LIBRARY_PATH to the global values inside your PHP script wherever you are going to run ffmpeg. You can find those values if you run ldconfig -v | grep \/.
Answer: What I did to fix this was I went to /usr/lib and searched for libstdc++ (this directory has newer versions) and copied it to /opt/lampp/lib.
I took a backup of the original file and pasted the new file and BOOM! It worked! :)
I hope it works for you too.


Programmatically publishing and unpublishing nodes: anonymous access

Question: We have several nodes that serve as open job postings which need to "open" and "close" on specific dates.
In order to accomplish this, we publish and unpublish them accordingly.
We have a query (based on publish unpublished node programmatically) that successfully updates both the node table and the node_revision table:
$result = db_query('update node n
JOIN field_data_field_jobs_date d ON d.entity_id = n.nid and d.revision_id = n.vid
JOIN node_revision r ON n.nid = r.nid and n.vid = r.vid
# Update the node_revision table
SET r.status = IF(
    (
    CURDATE() >= d.field_jobs_date_value
    AND
    CURDATE() <= d.field_jobs_date_value2
    ),1,0
),
# Update the node table
n.status = IF(
    (
    CURDATE() >= d.field_jobs_date_value
    AND
    CURDATE() <= d.field_jobs_date_value2
    ),1,0
)
# Only update our custom content type
WHERE n.type = \'job_posting\'');

This successfully updates the node status and node revision status in the database.
However, once a node has been published through this method, anonymous users still cannot see it (and are presented access denied if given a direct link to the node).
We have to manually edit each node and hit the save button for the published status to "take." This leads me to believe that we are omitting some sort of call to node access or something similar that updates the permissions on the node appropriately.
Any ideas besides the status field that may be preventing anonymous users from seeing programatically published nodes?
Comment: As a side note, using `db_query()` for anything other that read-only queries (`SELECT`, `SHOW`, `DESCRIBE`, etc) is frowned upon.  Use `db_update().`
Comment: Thanks for the clarification, MPD - we would use db_update but it doesn't really support this complex of a query with IF statements and what not.
Answer: Most probably caching. Directly changing something in the database is, though the fastest, not really the safest / most reliable way of doing things in Drupal.
I'd suggest to use enity_query (or in this case even direct database access) to retrieve node ids of nodes you want to update and then use 'correct' drupal way of doing things -> load all the nodes, individually change their publish status and save them.
Something along these lines...
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}

Answer: The method that you are following to update your nodes/revisions is generally frowned upon by the Drupal community. However, since you seem to know what you are doing and the changes that you perform to the database do not break anything, I can give you a suggestion on how to fix it.
After updating the database table, you can use the node_load and node_save functions to programmatically retrieve and save the node using the proper Drupal way. This, is basically the same thing that you are doing by opening and saving the node.
As to why this is happening, you might check the node_save function's code. Specifically, the fact that you do not update the node access table with something like:
    node_access_acquire_grants($node);

seems like something that could be causing the issue that you are facing.
Comment: Thank you for your suggestion, you are probably correct in your assumptions that it was to do with the access grants. We worked around this by instead of querying for date and using it to publish / unpublish nodes, we simply modified the view we were using to display them filtered by their open and close date. Why we didn't do that to begin with is beyond me.


Defined `tryCatch` function operator incorrect return

Question: I want to define a function operator that will get a plot as input and in case it produces an error it should return another plot.
My try:
handle_plot_error <- function(f) {
    wrapper <- function(...) {
        tryCatch(
            {
                f(...)
            },
            error = function(e) {
                hist(1:3)
            }
        )
    }

    wrapper
}

But when I try:
handle_plot_error(plot(1,1))

it returns:
function(...) {
        tryCatch(
            {
                return(f(...))
            },
            error = function(e) {
                return(hist(1:3))
            }
        )
    }
<bytecode: 0x7ff29dc38668>
<environment: 0x7ff29d9fab00>

Answer: Why are you using wrapper ? You may try :
handle_plot_error <- function(f) {
    tryCatch(
      {
        f
      },
      error = function(e) {
        hist(1:3)
      }
    )
}

where :
#No error plot
handle_plot_error(plot(1, 1)) #returns

and
#Error plot
handle_plot_error(plot(1:5, a = 2)) #returns

Comment: I tried to copy the form from Python decorator definitions. I see I overcomplicated thingies, thanks!
Comment: do you have any idea why `handle_plot_error` function is not working for ggplot2 facets?
Comment: It is working for me when I put `error = function(e) {     ggplot(mtcars, aes(mpg, disp)) + geom_point() + facet_wrap(~cyl)  }`. Do you meant that or something else?
Comment: I mean like this:
```
library(dplyr)
library(ggplot2)

foo <- function(df) {
    df %>%
        ggplot(aes(cyl, mpg)) +
        geom_line() +
        facet_grid(~am)
}

handle_plot_error(foo(tibble())) # simulates empty df as can happen in real scenario
```
Comment: The error comes in the function `foo` itself before going to `handle_plot_error` function. `foo(tibble())`
Comment: Do you have any idea how to solve this? I can also open a new question.
Comment: Can you use the same `tryCatch` approach in the `foo` function? Yeah..I guess it is better to ask this as a new question.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/229190/discussion-between-mihagazvoda-and-ronak-shah).


Can somebody offer an example of a unimodal distribution which has a skewness of zero but which is not symmetrical?

Question: In May 2010 Wikipedia user Mcorazao added a sentence to the skewness article that "A zero value indicates that the values are relatively evenly distributed on both sides of the mean, typically but not necessarily implying a symmetric distribution." However, the wiki page has no actual examples of distributions which break this rule. Googling "example asymmetrical distributions with zero skewness" also gives no real examples, at least in the first 20 results.
Using the definition that the skew is calculated by $ \operatorname{E}\Big[\big(\tfrac{X-\mu}{\sigma}\big)^{\!3}\, \Big]$, and the R formula
sum((x-mean(x))^3)/(length(x) * sd(x)^3)

I can construct a small, arbitrary distribution to make the skewness low. For example, the distribution
x = c(1, 3.122, 5, 4, 1.1)

yields a skew of $-5.64947\cdot10^{-5}$. But this is a small sample and moreover the deviation from symmetry is not large. So, is it possible to construct a larger distribution with one peak that is highly asymmetrical but still has a skewness of nearly zero?
Comment: Do you want the distribution to be unimodal or not? The title says so, but the text barely mentions this point.
Comment: @Dilip Yes, I'd find it more interesting if the distribution were unimodal, since skewness, as a central moment, doesn't really make sense otherwise.
Answer: Consider discrete distributions.  One that is supported on $k$ values $x_1, x_2,\ldots, x_k$ is determined by non-negative probabilities $p_1, p_2,\ldots, p_k$ subject to the conditions that (a) they sum to 1 and (b) the skewness coefficient equals 0 (which is equivalent to the third central moment being zero).  That leaves $k-2$ degrees of freedom (in the equation-solving sense, not the statistical one!).  We can hope to find solutions that are unimodal.
To make the search for examples easier, I sought solutions supported on a small symmetrical vector $\mathbf{x}=(-3,-2,-1,0,1,2,3)$ with a unique mode at $0$, zero mean, and zero skewness.  One such solution is $(p_1, \ldots, p_7) = (1396, 3286, 9586, 47386, 8781, 3930, 1235)/75600$.

You can see it is asymmetric.
Here's a more obviously asymmetric solution with $\mathbf{x} = (-3,-1,0,1,2)$ (which is asymmetric) and $p = (1,18, 72, 13, 4)/108$:

Now it's obvious what's going on: because the mean equals $0$, the negative values contribute $(-3)^3=-27$ and $18 \times (-1)^3=-18$ to the third moment while the positive values contribute $4\times 2^3 = 32$ and $13 \times 1^3 = 13$, exactly balancing the negative contributions.  We can take a symmetric distribution about $0$, such as $\mathbf{x}=(-1,0,1)$ with $\mathbf{p}=(1,4,1)/6$, and shift a little mass from $+1$ to $+2$, a little mass from $+1$ down to $-1$, and a slight amount of mass down to $-3$, keeping the mean at $0$ and the skewness at $0$ as well, while creating an asymmetry.  The same approach will work to maintain zero mean and zero skewness of a continuous distribution while making it asymmetric; if we're not too aggressive with the mass shifting, it will remain unimodal.

Edit: Continuous Distributions
Because the issue keeps coming up, let's give an explicit example with continuous distributions.  Peter Flom had a good idea: look at mixtures of normals.  A mixture of two normals won't do: when its skewness vanishes, it will be symmetric.  The next simplest case is a mixture of three normals.
Mixtures of three normals, after an appropriate choice of location and scale, depend on six real parameters and therefore should have more than enough flexibility to produce an asymmetric, zero-skewness solution.  To find some, we need to know how to compute skewnesses of mixtures of normals.  Among these, we will search for any that are unimodal (it is possible there are none).
Now, in general, the $r^\text{th}$ (non-central) moment of a standard normal distribution is zero when $r$ is odd and otherwise equals $2^{r/2}\Gamma\left(\frac{1-r}{2}\right)/\sqrt{\pi}$.  When we rescale that standard normal distribution to have a standard deviation of $\sigma$, the $r^\text{th}$ moment is multiplied by $\sigma^r$.  When we shift any distribution by $\mu$, the new $r^\text{th}$ moment can be expressed in terms of moments up to and including $r$.  The moment of a mixture of distributions (that is, a weighted average of them) is the same weighted average of the individual moments.  Finally, the skewness is zero exactly when the third central moment is zero, and this is readily computed in terms of the first three moments.
This gives us an algebraic attack on the problem.  One solution I found is an equal mixture of three normals with parameters $(\mu, \sigma)$ equal to $(0,1)$, $(1/2,1)$, and $(0, \sqrt{127/18}) \approx (0, 2.65623)$.  Its mean equals $(0 + 1/2 + 0)/3 = 1/6$.  This image shows the pdf in blue and the pdf of the distribution flipped about its mean in red.  That they differ shows they are both asymmetric.  (The mode is approximately $0.0519216$, unequal to the mean of $1/6$.)  They both have zero skewness by construction.

The plots indicate these are unimodal.  (You can check using Calculus to find local maxima.)
Comment: I have checked, Andy: convolving the discrete solution with a normal distribution does not change the skewness.  When you give that normal distribution a standard deviation around 0.57 or greater, the result is unimodal.  Like the underlying discrete distribution, it continues to have zero mean, zero skewness, and to be asymmetric.  Mixing this in with a standard normal distribution amounts to a controlled movement of mass between the standard normal and the discrete distribution: that might fulfill your request for a "stereotyped" method.
Comment: You're thinking quite well, Macro: we should all be so sceptical.  The trick is to shift tiny amounts spread across wide ranges.  A first-derivative test will enable you to check for possible modes and also provides the basis for a proof that *sufficiently* tiny shifts of this form will *not* produce new modes.
Comment: (+1) Very slick answer. Will this work with continuous distributions though? Wouldn't the shifting potentially create tiny little modes? I may not be thinking straight...
Comment: Thanks for the answer! This is similar to what I was intuitively thinking, though I couldn't put it into words well--that you have to "balance" the mass on each side of the distribution. Makes me wonder if there are stereotyped ways in which one can perform this balancing act.
Comment: One way, Andy, is to start with a discrete solution and then convolve it with a normal distribution.  In this case, the unimodality requirement will force that normal distribution to have a large standard deviation.  Even so, if the convolution does not appreciably change the requisite properties (such as zero skewness), or it it changes it in predictable ways, you have a mathematical handle on the problem.  In some sense my recent edit can be viewed as such an attack, although it's not strictly a convolution (because the three normals have different standard deviations).
Comment: $Pr(X=-2)=0.2$, $Pr(X=0)=0.5$, $Pr(X=1)=0.25$, $Pr(X=3)=0.05$, i.e. $(p_1, \ldots, p_7) = (0,4,0,10,5,0,1)/20$, works and you can reduce $Pr(X=0)$. Some related other small discrete examples $(p_1, \ldots, p_7) = (0,6,7,8,12,2,1)/36$ or even $(p_1, \ldots, p_7) = (0,5,5,5,10,1,1)/27$, both of which I would regard as unimodal and which are clearly asymmetric.  Increase the central value if you want the mode in the centre.
Answer: Here is one I found at https://www.qualitydigest.com/inside/quality-insider-article/problems-skewness-and-kurtosis-part-one.html# which I find nice and reproduced in R: an inverse Burr or Dagum distribution with shape parameters $k=0.0629$ and $c=18.1484$:
$$g(x) = ckx^{-(c+1)}[1+x^{-c}]^{-(k+1)}$$
It has mean 0.5387, standard deviation 0.2907, skewness 0.0000, and kurtosis 2.0000. The source also calls it the "elephant distribution":

My reproduction in R was created with
library(actuar)
library(knotR)

# a nonsymmetric distribution with zero skewness
# see https://www.qualitydigest.com/inside/quality-insider-article/problems-skewness-and-kurtosis-part-one.html#

c <- 18.1484
k <- 0.0629

x <- seq(0,1.5,by=.0001)

elephant.density <- dinvburr(x, k, c)
plot(x,elephant.density, type="l")
polygon(c(min(x),x),c(min(elephant.density),elephant.density), col="grey")
points(0.8,0.8, pch=19, cex=2)

# "ears" created via https://www.desmos.com/calculator/cahqdxeshd
ear.x <- c(0.686, 0.501, 0.42, 0.68)
ear.y <- c(0.698, 0.315, 1.095, 0.983)

myseg(bezier(cbind(ear.x, ear.y)), type="l")

EX <- gamma(k+1/c)*gamma(1-1/c)/gamma(k) # see p6 of https://wwz.unibas.ch/uploads/tx_x4epublication/23_07.pdf
EX2 <- gamma(k+2/c)*gamma(1-2/c)/gamma(k)
EX3 <- gamma(k+3/c)*gamma(1-3/c)/gamma(k)
(skewness <- (EX3 - 3*EX*(EX2-EX^2)-EX^3)/(EX2-EX^2)^(3/2)) # zero to three digits: 0.0003756196

As this output shows, skewness is not quite zero to four digits for these parameter values. Here is a little optimizer for $k$ and $c$:
   # optimize skewness a bit further
    skewval <- 1

while (skewval > 10^(-10)){
  optskew.k <- uniroot(skewness.fun, lower = k*.95, upper = k*1.1, tol=skewval^2, c=c)
  skewval <- optskew.k$f.root
  k <- optskew.k$root

  optskew.c <- uniroot(skewness.fun, lower = c*.95, upper = c*1.1, tol=skewval^2, k=k)
  skewval <- optskew.c$f.root
  c <- optskew.c$root
}

yielding
> print(c)
[1] 18.89306

> print(k)
[1] 0.05975542

> print(skewval)
[1] -1.131464e-15

Comment: Skewness that's zero to three digits (nearly four) was plenty to my mind; it's not like a more precise value will make it look any different. If skewness will cross zero in that vicinity and it's clear what directions to tweak the values in if more accuracy is needed, I reckon that's sufficient. But kudos for the additional effort. (It's a lovely example, by the way.)
Comment: Thank you for the edit. That said, I could not reproduce the skewness of 0.0000 to four digits, obtaining 0.0001245138 instead (see next edit, in the R code).
Comment: One can probably run a simple optimizer to find $c$ and $k$ values such that the skewness is as close to zero as possible. It should be a couple of additional lines or perhaps even one. You already have the loss function analytically computed in your last line, is there a suitable generic optimizer in R?
Comment: Actually, 0.0003756196. 0.0001245138 was already after some initial optimization, given here by mistake. I will have a look.
Comment: @amoeba, I tried to optimize a bit, but I make no claims of having done that in a clever way, I have little experience with optimization.
Comment: I agree that skewness to 3-4 digits is plenty, but I was curious and optimized the skewness using SciPy `optimize` module. I got: c = 0.2362449983942275, k = 10.457877420850977, skewness = 4.720662530517425e-10.
Comment: These values for $c$ and $k$ are in a quite different ballpark than the ones above, which suggests there could be multiple optima. Have you plotted the density to see how it looks like? (Not that the elephant shape is important beyond being fun, though, of course.)
Comment: @ChristophHanck Prof. Dr. Christoph Hanck, Thank you for your nice explanation. I will be grateful to you if you please can share your thoughts regarding [my question](https://stats.stackexchange.com/questions/560373/how-can-i-quantify-the-skewness-kurtosis-entropy-when-all-of-values-of-a-list).
Answer: Consider a distribution on the positive half of the real line which increases linearly from 0 to the mode and then is exponential to the right of the mode, but is continuous at the mode.
This could be called a triangular-exponential distribution (though it does often look a bit like a shark fin).
Let $\theta$ be the location of the mode and $\lambda$ be the rate parameter of the exponential.
As $\lambda\theta$ increases the distribution becomes progressively less skew. As $\lambda\theta$ increases past $\approx 6.15$ the third moment crosses from positive to negative:

Brizzi (2006)$^{[1]}$ refers to this family of distributions as the "two-face" distribution, and discusses this crossover point where the third-moment-skewness is zero. von Hippel (2005)$^{[2]}$ presents an example that's almost at that crossover point here
The thread Non-normal distributions with zero skewness and zero excess kurtosis? has some asymmetric examples, including a small discrete example and another continuous unimodal one:

Discrete unimodal distributions - or equivalently, samples - with zero skewness are quite easy to construct, of large or small size.
Here's an example, which you can treat as a sample or (by dividing the raw frequencies by 3000) as a pmf (the 'x' values are the values taken, the 'n' are the number of times that value occurs in the sample):
x:  -2   -1    0    1    2    3    4    5    6    7    8    9   10
n: 496  498  562 1434    2    1    1    1    1    1    1    1    1

This example is built up from 3-point distributions:
x:          -2              1                  c
n:   c(c-1)(c+1)/6     c(c-1)(c+1)/3 - c       1

across various values of $c$ between 3 and 10. This parameterized (by $c$) 3-point "atom" has $\sum_i n_ix_i =0$ and $\sum_i n_ix_i^3 =0$, which in
turn means that mixtures across various choices of $c$ have zero skewness. (You can't make anything smaller than a distribution across three points that has asymmetry and third central moment zero. A collection of simple pieces over only a few points, such as these make neat building blocks from which larger structures may be made.)
There are all manner of other such "atoms" one can construct, but this example uses only this one kind. To some combination of atoms such as these is added a few symmetrically placed values to fill in remaining holes and guarantee unimodality without destroying the structure of mean and third moment.
$[1]$ Brizzi, M. (2006),
"A Skewed Model Combining Triangular and Exponential Features:
The Two-faced Distribution and its Statistical Properties"
Austrian Journal of Statistics, 35:4, p455–462
http://www.stat.tugraz.at/AJS/ausg064/
$[2]$ von Hippel, P. T. (2005),
"Mean, Median, and Skew: Correcting a Textbook Rule"
Journal of Statistics Education Volume 13, Number 2,
http://ww2.amstat.org/publications/jse/v13n2/vonhippel.html
Comment: Could maybe call it the "Shark-fin" perhaps?
Comment: @Glen_b Totally Shark-fin indeed.
Answer: For zero skewness, we need
$$
\operatorname{E}\Big[\big(\tfrac{X-\mu}{\sigma}\big)^{\!3}\, \Big] = 0
$$
or, equivalently,
$$
\operatorname{E}\Big[\big(\tfrac{X-\mu}{\sigma}\big)^{\!3}\, \Big | X \leq \mu \Big] + \operatorname{E}\Big[\big(\tfrac{X-\mu}{\sigma}\big)^{\!3}\, \Big | X \gt \mu \Big] = 0.
$$
Now, for given mean and variance, pick any two distributions $Y$ and $Z$ with zero mass on the right side of $\mu$ and
$$
\operatorname{E}\Big[\big(\tfrac{Y-\mu}{\sigma}\big)^{\!3}\, \Big] = \operatorname{E}\Big[\big(\tfrac{Z-\mu}{\sigma}\big)^{\!3}\, \Big]
$$
and define $X$ to match $Y$ if left of $\mu$ and $(\mu - Z)$ otherwise. (Don't know the exact notation for this, anyone care to help?)
The resulting distribution will be unimodal if the PDFs of $Y$ and $Z$ are increasing at the left of $\mu$ (in addition to being zero at the right of $\mu$).
Comment: How do you guarantee that the distribution is unimodal?
Comment: Thanks for pointing this out. The PDFs of $Y$ and $Z$ will have to be strictly increasing until $\mu$, and then drop to zero.
Comment: This is the right idea but it still needs some work, because $\sigma$ can change when combining $Y$ and $Z$.
Comment: @whuber: Damn. I knew there *had* to be some pitfall... :-)
Answer: The following discrete distribution is asymmetric and has null skewness: Prob(-4)=1/3, Prob(1)=1/2, Prob(5)=1/6. I found it in the paper of Doric et al., Qual Quant (2009) 43:481-493; DOI 10.1007/s11135-007-9128-9
Comment: +1 It checks out and it's unimodal.  That's the simplest possible example.
Answer: Sure. Try this:
skew= function (x, na.rm = FALSE)
 {
    if (na.rm)    x <- x[!is.na(x)]             #remove missing values
    sum((x - mean(x))^3)/(length(x) * sd(x)^3)  #calculate skew
 }

set.seed(12929883)
x = c(rnorm(100, 1, .1), rnorm(100, 3.122, .1), rnorm(100,5, .1), rnorm(100, 4, .1), rnorm(100,1.1, .1))

 skew(x)
 plot(density(x))

(You did the hard stuff already!)
Comment: @Macro, that's not correct. See, for example, the abstract of Roeder 1994 (JASA) for the well-known result that "the density of two mixed normals is not bimodal unless the means are separated by at least 2 standard deviations". If they are separated by less than this, the mixture is unimodal.
Comment: It's not bimodal... it's horribly *multi* -modal. Try plotting the density; `curve(0.2*(dnorm(x, 1, .1) + dnorm(x, 3.122, .1) + dnorm(x, 5, .1) + dnorm(x, 4, .1) + dnorm(x, 1.1, .1)), 0,10)`
Comment: nice, I like it. +1
Comment: Data generated in this way is certainly not unimodal. All you need to do to see that is cut and paste your code, verbatim. Indeed, a mixture of normally distributed variables will never be unimodal (unless of course, one of the mixture proportions is 1).
Comment: You're right @guest. I'd forgotten about that possibility when I made my post
Comment: @Peter Thanks for the answer! Maybe I'm implementing this wrong, but it seems like the distribution your code produces is bimodal. Do you know of a way to make a unimodal distribution that has skewness of zero but is not symmetric?
Comment: @AndyMcKenzie I don't think that's possible, but am not sure


Add Constraint to Paragraph Field

Question: I'm attempting to follow this documentation to add a custom constraint to a field in a Paragraph but I'm having trouble actually accessing that field.
Currently I have my_content_type with paragraph_field. This field accepts a number of different paragraph types. I'd like to be able to add a constraint to a field on a specific paragraph type that could be added to that field.
I've tried using hook_entity_bundle_field_info_alter, hook_form_alter, and hook_field_widget_form_alter but am having trouble actually accessing the proper field.
Is there a better way to do this?
Answer: @Vecta I hope this help you
function MYMODULE_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  //with a node
  if ($entity_type->id() === 'node') {
    if ($bundle == 'article') {
      if (isset($fields['title'])) {
        // change constraint id
        $fields['title']->addConstraint('UniqueCode', []);
      }
    }
  }
  //with a paragraph
  if ($entity_type->id() === 'paragraph') {
    // use the paragraph machine name
    if ($bundle == 'paragraph_name') {
      if (isset($fields['field_name'])) {
        // change constraint id
        $fields['field_name']->addConstraint('ConstraintId', []);
      }
    }
  }
}

Add Constraint to Paragraph Field


How to serialize a list of generic type which inherit from a non generic class

Question: I have a class structure as follows :
[Serializable]
public abstract class TagConfiguration
{
    public abstract string Name { get; set; }

    // Other abstract properties

    public abstract object GetInitialValue();
    public abstract void SetInitialValue(object value);

    protected TagConfiguration() { }

    // Other methods not useful in the scope of this problem
}

[Serializable]
public class GenericTagConfiguration<T> : TagConfiguration
{
    public override string Name { get; set; }

    // Other abstract properties

    private T _initialValue;
    public T InitialValue
        {
            get => (T)GetInitialValue();
            set => SetInitialValue(value);
        }
        public override object GetInitialValue()
        {
            return _initialValue;
        }
        public override void SetInitialValue(object value)
        {
            _initialValue = (T)value;
        }

    public GenericTagConfiguration() : base() { }

    // Other methods not useful in the scope of this problem
}

This class, as the name implies is for the configuration of a Tag object which looks like this :
[Serializable]
public abstract class Tag
{
    public abstract object GetConfiguration();
    public abstract void SetConfiguration(object value);
    public abstract object GetCurrentValue();
    public abstract void SetCurrentValue(object value);

    protected Tag() { }

    // Some abstract methods
}

[Serializable]
public class GenericTag<T> : Tag
{
    private GenericTagConfiguration<T> _configuration;
    public TagConfiguration Configuration
    {
        get => (GenericTagConfiguration<T>)GetConfiguration();
        set => SetConfiguration(value);
    }
    public override object GetConfiguration()
    {
        return _configuration;
    }
    public override void SetConfiguration(object value)
    {
        _configuration = (GenericTagConfiguration<T>)value;
    }

    private T _currentValue;
    public T CurrentValue
    {
        get => (T)GetCurrentValue();
        set => SetCurrentValue(value);
    }
    public override object GetCurrentValue()
    {
        return _currentValue;
    }
    public override void SetCurrentValue(object value)
    {
        _currentValue = (T)value;
    }

    public GenericTag() : base() { }

    // The same methods from Tag overridden
}

I have to be able to export a List<TagConfiguration> to an XML file but the issue I have is whenever I try to do so, I get an error saying :
Unhandled Exception: System.InvalidOperationException: There was an error generating the XML document.
---> System.InvalidOperationException:The type GenericTagConfiguration[[System.Int32]] was not expected.
Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

I'm using the following code to attempt the export :
List<TagConfiguration> lstTagConf = new List<TagConfiguration>
{
    tagConf,
    tagConf2
};

XmlSerializer xs = new XmlSerializer(typeof(List<TagConfiguration>));
using (TextWriter tw = new StreamWriter(@"C:\Users\Administrator\Documents\listTag.xml"))
{
    xs.Serialize(tw, lstTagConf);
}

QUESTION
The reason I added the Tag class is that I would need to be able to import and export a List<Tag> as well as a List<TagConfiguration>.
Do I need to write an interface to do this ?
Comment: Xml Serialization when you have a base class and an inherited class you need to use XmlInclude.  See : https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlincludeattribute?view=netcore-3.1
Comment: I understand this, but how would I go about including the correct types of GenericTagConfiguration ?
Answer: The answer I found (Thanks to jdweng and this question) was to add the following before the TagConfiguration class :
[XmlInclude(typeof(GenericTagConfiguration<int>)), ...] // as many different T as you would use
[Serializable]
public abstract class TagConfiguration
{
    // Same data
}


If A is a (mxn) matrix, show that A=0 if (x^t)Ay=0 for any vector x in Rm, y in Rn

Question: If $A$ is a ($m\times n$) matrix, show that $A=0$ if $(x^t)Ay=0$ for any vectors $x\in \Bbb R^m$, $y\in \Bbb R^n$
Comment: Show your some efforts
Answer: Let $A=(a_{jk})$, let $e_1,....,e_n$ be the standard basis of $\mathbb R^n$ and let $f_1,...,f_m$ be the standard basis of $\mathbb R^m$ .
Then compute $f_k^tAe_j.$
Answer: Just use the fact that if $e_n$ is the nth vector of the standard basis of $\mathbb{R}^n$ then $e_i^T A e_j = A_{ij}$


Does the pizzicato apply to the 2nd Violins or the Violas?

Question: In the 69th bar of the 1st movement of Tchaikovsky's Symphony No. 1, it says for an instrument to be played in pizzicato, but I'm not sure which one.

The top instrument is the 1st Violins, middle is the 2nd Violins, and bottom is the Violas.
Answer: The pizzicato marking refers to the second violins. Here's the same passage in a different edition:
Comment: Is there any way to tell that from the edition shown in the question, or it is inherently ambiguous there?
Comment: @gidds In the example from the question the marking is much closer to the second violins than to the violas and also closer than the dynamic (dynamics go under the system), so not ambiguous.


Pulling content from other nodes into a Panel Node

Question: I'm using Panel Nodes* to let users create content with varying layouts. I'm wanting to display another node in one of the panels.
When I create the Panel Node and go to create a new Content pane, I click Entity then Rendered Node. However, the Entity dropdown only lists "This node". If I click Node instead and then try to insert a Node Content panel content type, the Node dropdown is still "This node". What am I missing?
I've tried using EntityReference to associate a Panels node with the other content type, but it doesn't increase the options available to me.
Any idea how I'd render a node from another content type in a Panel Nodes Panel?
Thanks!
<code>*</code>Yes, I know I should use Panelizer, but I'm wanting to know if there's a way to do this without converting everything I've done thus far to that.
Answer: When you add an Object to your Panel Pane, you will find in the left column the option to add an "Existing node", choosing this, you can add a node id of the content you want to add.
If you want to dynamically provide different nodes provided by the user input on the node form using a node reference field, you need to add a context to the panel by using this reference field and then the referenced node will also be available.
Comment: Oh. Wow. I totally just thought that was like a "legend" or something. TODAY'S AWARD FOR TOTALLY MISSING THE OBVIOUS GOES TO...! Thanks a whole lot, that's really helpful!


Dynamic 2D array crashes

Question: I am reading from a file (each line wolds 1 word) and putting each line into an array. It crashes when its about to close the file saying (* glibc detected * proj: corrupted double-linked list: 0x0000000002139240 ***).  Also everything but the 1st element was copied correctly (the 1st element was supposed to be "how are you" but was instead "0").  Any help on this is greatly appreciated.
int i = -1;
int numb;
int wsize;
while (fgets(word,30,file)!=NULL)
{
    if (i==-1)
    {
         if(word[strlen(word)-1]=='\n')
         {
             word[strlen(word)-1] = 0;
         }
         numb = atoi(word);
         ptr = malloc(sizeof(char*)*numb);
    }
    else
    {
        if(word[strlen(word)-1]=='\n')
        {
             word[strlen(word)-1] = 0;
        }
        wsize = strlen(word);
        ptr[i] = malloc(sizeof(char*)*wsize);
        strncpy(ptr[i],word,strlen(word));
        size++;
     }
     i++;
}
int j=0;
while(j<16)     //prints to see if they were copied corectly
{               //ptr[0] was the only one that did not copy corectly
    printf("%s\n",ptr[j]);
    j++;
}
fclose(file);
printf("test\n"); //was never printed so I assume it crashes at fclose()
return 1;

Comment: before exiting the program, the code needs to free all those malloc'd areas.  Otherwise a series of memory leaks are created.  While the exiting of the program will (sadly) free all the allocated memory, it is far better to have code cleanup after itself, especially as the programs get larger, run for longer durations, and have more and more allocated memory to free
Answer: The line ptr[i] = malloc(sizeof(char*)*wsize); is wrong, for two reasons:

It should be sizeof(char), not sizeof(char*) (or just omit this, since sizeof(char) is equal to 1 by definition)
If you want to store a string of length wsize, you need to allocate wsize+1 bytes

EDIT — More issues:

What is the purpose of the line size++;? Did you mean wsize++;?
Where does the number 16 come from in while(j<16)? I suggest you try while(j<i) instead.
If main() returns a nonzero value, this signifies that an error occurred. Change this to return 0; unless you have a good reason for returning some other value.

One more:

I just noticed you're using strncpy(). This won't add a terminating '\0' byte to the end of the string because you've asked it to copy a string of length wsize using no more than wsize bytes. Change this line to strcpy(ptr[i],word); and it should work.

After you've done that, you need to remove all the potential buffer overflows from your code. (There are lots of them.)
Comment: Size is the total size of ptr and is a variable that is passed by reference into this function. Wsize is the size of the current word taken from the line.
When testing this I used 16 cause I know there are 16 words. Once this error is fixed this will be removed.
Comment: Thanks for your help so far, but how do I tell where a potential buffer overflow is?
Comment: @npzap If you know there are 16 words, why are you even bothering to store the number of words at the top of your file? Obviously your program is liable to crash if `numb` iz zero because it will still attempt to read in words until it reaches the EOF. Less obviously, it will also crash if `numb` = `(INT_MAX + 1) / sizeof(char*)` due to an arithmetic overflow in the `malloc()` statement. If there are fewer strings in the file than the number declared at the top, then your `printf()` calls will dereference unallocated pointers and cause a segmentation fault.
Comment: I know there are 16 words during my own test, this has to be made for any number of strings.  There will always be the number or words that the number at the top declares.  However thanks for the input about malloc and numb, I realized I was using numb wrong and found the solution.

Dynamic 2D array crashes


Find the last digit of the sum $1!+2!+3!+...+49!$

Question: Is there any formula for finding the last digit of the factorials?
How to approach these type of questions?
Thanks in advance.
Comment: What do $n!$ for $n\ge5$ contribute to the last digit?
Comment: Hint, look the last digit of 1!+2!+3!+4! and 5! separately.
Comment: notice that all factorials are even except for $1!$ and so you are adding odd + even + even + even + ............ + even which is odd.

And so the last digit will be one of $1,3,5,7,9$. this is kinda easier
Answer: First of all, when you see this sort of seemingly intractable problem, don't despair. There's usually a very simple "trick" that makes the problem trivial.
In this case, you have to realise two things:
1) only the sum of last digits contributes to the last digit of the final sum.
2) factorials of larger numbers have a lot of zeroes at the end.
So your problem reduces to deciding the final term you have to consider. Luckily this is a very easy problem. Because:
$5! = 120$
$6! = 720$
and so forth, every factorial after that ending with a zero.
So you only have to consider the sum $1! + 2! + 3! + 4!$.
Even that's simplified by recognising that $3!$ ends with a $6$ and $4!$ with a $4$, so they will sum up to give $0$ as the last digit.
Turns out all you have to consider is $1! + 2!$, which is just $3$.
I wanted to put an exclamation point at the end of the last line to emphasise how easy the whole thing was, but decided not to because it might look like a factorial! :)
Comment: As for proof that $n!$ has a zero for a final digit for all $n\geq 5$, note that for $n\geq 5$ you have $2|n!$ and $5|n!$, (seen either by induction using the definition of factorial that $n!=n\cdot (n-1)!$, or directly using definition that $n!=\prod\limits_{i=1}^n i$).
Comment: @Neil not quite.  Change the statement to be $n\geq 4$ and it will be true.  When $n=2$ you have the final digit is $3$, but when $n=3$ you have the final digit is $9$ (since $1!+2!+3!=1+2+6=9$)
Comment: Nice bro! So can we say that the last digit of $\sum\limits_{x=1}^{n} x!$ where $n\geq 4$ is always $3$ ?
Comment: @JMoravitz Yes, good catch!
Comment: @JMoravitz Oh yeah...sorry my bad!
Answer: well as the comments stated, you should observe that for $n \geq 5$ we have $n!$ is a multiple of $5$. For example $$5! = 5 \times 4 \times 3 \times 2 \times 1 = 24 \times 5$$
and $$6 ! = 6 \times 5! = 6 \times 24 \times 5$$
and so on. Now you should know that any multiple of $5$ is either $0$ or $5$ for instance $5,10,15,20,25,.........$ as you can see.
now $$1! + 2! + 3! + 4! = 1 + 2 + 6 + 24 = 33$$
and $5! + 6! + ..........+49!$ is a mutliple of $5$ as we said.
However, $$5! + 6! + ..........+49!$$ is an even number because they are also a multiple of $2$
And so we have $1! + 2! + 3! + 4!$ is odd
and $5! + 6! + ..........+49!$ is even
and you should know that  odd + even = odd. $$(2k + 1) +2m = 2k +2m + 1 = 2(k +m) + 1$$ which is odd.
And so the sum is odd.
and so $5! + 6! + ..........+49!$ ends with $0$ because it is a multiple of $5$ and an even number.
and $33$ + a number that ends with $0$ is will result in a number with last digit = $3$


Split Python String by single quotation marks

Question: I have a string like this:
text = ['Adult'   'Adverse Drug Reaction Reporting Systems/*classification'   '*Drug-Related Side Effects and Adverse Reactions'   'Hospital Bed Capacity   300 to 499'   'Hospitals   County'   'Humans'   'Indiana'   'Pharmacy Service   Hospital/*statistics & numerical data']

I need to separate this string, where each category (separated by the single quotaions marks is stored in an array). For example:
text = Adult, Adverse Drug Reaction Reporting Systems...

I have experimented with the split function but am unsure how to do it.
Answer: You can do something like this with regex assuming that you don't have constraints that you haven't listed:
>>> s = "'Adult'   'Adverse Drug Reaction Reporting Systems/*classification'   '*Drug-Related Side Effects and Adverse Reactions'   'Hospital Bed Capacity   300 to 499'   'Hospitals   County'   'Humans'   'Indiana'   'Pharmacy Service   Hospital/*statistics & numerical data'"
>>> import re
>>> regex = re.compile(r"'[^']*'")
>>> regex.findall(s)
["'Adult'", "'Adverse Drug Reaction Reporting Systems/*classification'", "'*Drug-Related Side Effects and Adverse Reactions'", "'Hospital Bed Capacity   300 to 499'", "'Hospitals   County'", "'Humans'", "'Indiana'", "'Pharmacy Service   Hospital/*statistics & numerical data'"]

My regex is leaving the ' in the strings -- You can easily remove them with a str.strip("'").
>>> [x.strip("'") for x in regex.findall(s)]
['Adult', 'Adverse Drug Reaction Reporting Systems/*classification', '*Drug-Related Side Effects and Adverse Reactions', 'Hospital Bed Capacity   300 to 499', 'Hospitals   County', 'Humans', 'Indiana', 'Pharmacy Service   Hospital/*statistics & numerical data']

Note, this only works because I'm assuming you don't have any escaped quotes in the string ... e.g. you never have:
'foo\'bar' which is a completely valid way to express strings in many programming situations.  If you do have that situation, you'll need to use a more robust parser -- e.g. pyparsing:
>>> import pyparsing as pp
>>> [x[0][0].strip("'") for x in pp.sglQuotedString.scanString(s)]
['Adult', 'Adverse Drug Reaction Reporting Systems/*classification', '*Drug-Related Side Effects and Adverse Reactions', 'Hospital Bed Capacity   300 to 499', 'Hospitals   County', 'Humans', 'Indiana', 'Pharmacy Service   Hospital/*statistics & numerical data']
>>> s2 = r"'foo\'bar' 'baz'"
>>> [x[0][0].strip("'") for x in pp.sglQuotedString.scanString(s2)]
["foo\\'bar", 'baz']


How do I remove the default node path when using a path alias?

Question: When I add path aliases, how do I remove the system path (/node/[nid]) in Drupal 8, to avoid Google to index the page twice?
Answer: Simple answer: You don't have to. We pretty often are asked about disabling the generic URLs to avoid penalties from search engines.
This however is not necessary. Once using URL aliases, the meta tags for both versions of the node rightfully declare the node/[nid] paths as short URL, and the URL alias as canonical URL. So search engines will index the page using the URL aliases.
Penalties would arise only, if you provide the same content at various places and trying to disguise their connection.
If you still are afraid, you can e.g. make use of the rabbit_hole module.
Answer: We can either:
Stop bots from indexing /node/ by using robots.txt
Or:
Make Drupal 8 do 301 (permanently moved) redirect to the alias automatically by installing the Redirect module (no configuration is required).


Mixed distribution

Question: Bob is a carnival operator of a game in which a player receives a prize worth $W=2^N$ if the player has $N$ successes, $N=0,1,2,3,...$ Bob models the probability of success for a player as follows:
i)$N$ has a Poisson distribution with mean $\lambda$
ii)$\lambda$ has a uniform distribution on the interval $(0,4)$.
Calculate $E(W)$
My attempt,
$$E(W)=E(2^N)$$
$$=P_N(2)$$
$$P_N(z)=E(z^N)$$
$$=E(E(Z^N|\lambda))$$
I'm stuck at here. Please help. Thanks in advance.
Answer: You're in correct path:
$$E[2^N|\lambda]=\sum_{n=0}^{\infty}2^ne^{-\lambda}\frac{\lambda^n}{n!}=e^{-\lambda}\sum_{n=0}^{\infty}\frac{(2\lambda)^n}{n!}=e^{2\lambda}e^{-\lambda}=e^\lambda$$
Then, we calculate $E[e^\lambda]$, which is trivial.

Mixed distribution


Getting error while installing NPM modules in CPanel?

Question: I get an error after installing Node in CPanel, I uploaded my package.json file but whenever I tap the Run NPM install button, it shows an error on the right hand side saying, Web Application is inaccessible by its address http://www.exampleforquestion.com, the operation was not performed.
Answer: You need to stop the application before running npm install.


Can a program tell it is being run under sudo?

Question: I have a program that should behave differently if it is being run under "sudo".  Is there a way it can find out if it was run under sudo?
Update: Someone asked why would I want to do this.  In this case, on a Mac using MacPorts there is output that tells you to cut-and-paste a particular command.  If the MacPorts command was run with "sudo", it should include sudo in the sample command:
$ sudo port selfupdate
--->  Updating MacPorts base sources using rsync
MacPorts base version 2.2.1 installed,
MacPorts base version 2.2.1 downloaded.
--->  Updating the ports tree
--->  MacPorts base is already the latest version

The ports tree has been updated. To upgrade your installed ports, you should run
  port upgrade outdated

^^^^^^^^^ it would be really sweet if it output "sudo port upgrade outdated" instead.  It would be even better if it just did it for you :-)

Comment: This sounds like http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378 . What is it you *really* want to do?
Comment: @sciurus usually the common use-case is in an install script that requires root privileges; if you don't have them just die immediately.
Comment: I'm curious: can you explain how it should behave differently?
Comment: I vaguely remember some command being aware that it's run as root or not... I think the answer is "yes"
Answer: Yes, there are 4 environment variables set when a program is running under sudo:
$ sudo env |grep SUDO
SUDO_COMMAND=/usr/bin/env
SUDO_USER=tal
SUDO_UID=501
SUDO_GID=20

Note that these can be faked by simply setting them.  Don't trust them for anything critical.
For example: In this program we need to tell the user to run some other program.  If the current one was run with sudo, the other one will be too.
#!/bin/bash

echo 'Thank you for running me.'

if [[ $(id -u) == 0 ]]; then
  if [[ -z "$SUDO_COMMAND" ]]; then
    echo 'Please now run: next_command'
  else
    echo 'Please now run: sudo next_command'
  fi
else  echo 'Error: Sadly you need to run me as root.'
  exit 1
fi

Note that it only tests for a SUDO_* variable if it can first prove that it is running as root. Even then it only uses it to change some helpful text.
Comment: @Kevin if someone screws with their environment to fake being at elevated privileges, then they hopefully know what they're doing and will accept the consequences.
Comment: What would I use for "anything critical?"
Comment: This is a perfectly acceptable answer to the question that was asked. The warning needs to be there for people that might try to _prevent_ the use of sudo, rather than just _detect_ it. Prevention should be done using sudo's command aliases to limit what commands the user can run.
Comment: Downvoted because any answer that has to be qualified by "don't trust them for anything critical" is not an answer at all, but an ugly hack.
Answer: This does not answer the question directly but I do not think the right question is being asked here. It appears to me the asker wants a program which will act different presumably if it has certain permissions or not, however I would argue checking for sudo is not the way to do that. Firstly many systems may not implement a "sudo", it is by no means required on Linux or many Unixes.
For example a user may be logged in as root already, making the sudo nonsensical or perhaps the system has non root users who still have capabilities to perform the administrative task that the program may wish to do. Finally perhaps the system has no root or sudo at all and instead uses a mandatory access control system with different capabilities and no catch all superuser to sudo into. Or the user could be sudoed, but into an account that has -less- permissions than their own account for security reasons (I often run untrusted code with a temporary unprivileged user who can only write to ramdisks in order to drop, not raise my permissions). It is overall a bad idea to assume a specific permissions model like sudo or the existence of root or to assume a sudoed user has any particular privileges.
If you want to find out if you have permissions to perform an operation the best way is usually to simply try and do it then check errno for permissions issues if it fails or if it is a multi stage operation that must either all fail or all succeed you can check if an operation will work with functions like the POSIX access function (beware of possible race conditions here if permissions are actively being changed)
If in addition you need to know the real user behind the sudo you can use getlogin function which should work for any interactive session with an underlying terminal and would allow you for example to find who is 'really' running the command for auditing or find the home directory of the real user to save logs.
Finally if what you really want is to find out if a user has root access (Still a bad idea but less implementation specific) you can use getuid to check for a uid of 0 and thus root.
Answer: There are two mechanisms that can be used.

Checking the environment variables can be faked either way, but is the easiest to do.  growisofs doesn't like to run under SUDO, so I unset the SUDO variables in scripts where I use it.   It can be faked the other way.  (The SUDO variable are also carried into the environment for scripts run under the at and batch commands.)
Another way to see if you are running under sudo is to walk the process list from your parent process up looking for sudo.  It would be difficult to hide that you were running under sudo this way, but is more complex.  It is still possible to fake that you are running under sudo.

It is more common to check if you are running as the appropriate user.  The id command can be used to do this.  TomOnTime's script uses the id command to determine if sudo might be required to run the next command.
Comment: *>  It would be difficult to hide that you were running under sudo this way* Couldn't you simply rename the `sudo` binary to something else? Or name some other executable `sudo` to fake the opposite? Not that I'd really expect anyone sane to do that...
Comment: @Bob You would need `root` access to rename the `sudo` executable.  A normal user would not be able to do this.  I did note that you can fake that your are running under `sudo`.  Renaming an existing program would work.  The code required for a dedicated fake `sudo` program is trivial.
Comment: you can just download the sudo binary from somewhere and give it the right permissions...
Comment: @JensTimmerman You need root access to give it right permissions.  If you can just rename it or hard link it.  No need to download it.   If you install it SUID to a target user id (if will work that way), you have to have already compromised the target user id.
Comment: ah, right, it refuses to work without setuid, my bad...
Answer: You can compare effective vs. real user id.
This does not strictly mean it is running undo sudo (could be setuid'd also), but indicates that the program has more rights than the user may expect.
(for example in a program which is normally executed without such rights, but needs to be run with them during installation or to install updates. Then, you can use this to give some warning feedback about that).
Comment: Nope, `sudo` sets both the effective and real id. As opposed to suid, which does not. Here is a trivial C program you can use to test (sorry, the comment will remove newlines, you'll have to add them back): `#include
#include
#include

int main() {
    printf("real = %i, effective = %i\n", getuid(), geteuid());
    return 0;
}`
Comment: ... or, alternatively, `perl -E 'say $<, "\n", $>'`
Answer: You can check the effective UID (EUID) variable, as follows:
if [[ $EUID -eq 0 ]]; then
    echo "running as root"
else
    echo "not running as root"
fi

Comment: I think you might be right. I came here because I didn't understand why `sudo echo $USER` prints the unprivileged user name (the variable is substituted BEFORE the sudo). I actually ended up using your code in my script. Thank you!
Comment: This does not answer the question. The code gives the same output when run as root as it does when run as sudo.
Comment: @StephenC - i think that for the purposes of the OP, there is no difference. IMHO their goal is to identify sudo execution or execution from an authentic root shell without distinction.
Answer: You can touch a file in /root and then if -e it. And if -e is true, rm (checking the error code) it so your test works next time.
Checking the error code (or return code) after the rm prevents someone from handily using sudo powers to create the file to play a prank on you.
Comment: This answer checks if the process has permission to write to `/root` (which is not necessarily the same as running as UID 0), but does not check if it gained those permissions using `sudo`.
Comment: Yes, the "thousand ways to skin a cat"; as I wrote the answer, I thought of another 4 or 5 things, so I wrapped it up.
Answer: I found that this works well for this
[ $(cat /proc/$PPID/loginuid) -ne 0 ] && [ "$USER" == "root" ]

Comment: i fixed the example.  basically checking for the loginuid is not equal to 0, but the user is root.
Comment: This doesn't work when I try it on FreeBSD, Centos7, or MacOS X.  I think you mean "/proc" instead of "/etc". But even with that change, it doesn't work on any of those three.  "$USER" is reset by sudo. Did you mean $SUDO_USER?  Also, did you mean "[[" instead of "["?


How to force forms only through your own submit functions?

Question: If I want a custom submit handler, the usual answer is to add the function call to $form['#submit'], and if need be, $form['actions']['submit']['#submit']. The standard warning is do something like
$form['#submit'][]='my_handler';

instead of
$form['#submit']='my_handler';

because you generally want the form submission to still go through the core form submission handlers.
I have a case where I need to completely manage the form submission process and don't ever want the form to be passed to the core submission handlers. To test that I could do this, I have:
global $user;
module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'my_content_type';
$node_form->uid = $user->uid;
$node_form->name = (isset($user->name) ? $user->name : '');
$form = drupal_get_form('my_content_type_node_form', $node_form);
$form['#submit']='';
$form['actions']['submit']['#submit']='';
$render($form);

I would have thought that since there are no submission handlers, the form shouldn't submit, or even if the page reloaded due to the action attribute in the html form element, that the content wouldn't be added to the database.
But it is.
So how can I keep Drupal from processing a submission through the normal core submission handlers, but still process through custom handlers? (I already know how to write custom form submission handlers, so that's not part of this question.)
Comment: Is the function callback `my_content_type_node_form` something that you defined? Can you post the code for that function. I wonder if it may be a better idea to implement hook_form_alter() once the node form has been built by drupal, and modify the submit handlers in the alter hook, rather than using drupal_get_form to build the form from scratch.
Comment: This code is slightly generalized. But using this generalized code, I would have a content type with the machine name `my_content_type`. Therefore, the standard form to submit new content of that content type is `my_content_type_node_form`. That's not something I defined. That's standard core. So there shouldn't be any difference between:
`function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id=="my_content_type_node_form"){...}`
and
`$form = drupal_get_form('my_content_type_node_form', $node_form);`
Comment: "Shouldn't" is a great word in our line of work :) Try the `hook_form_alter()` method (I would've suggested the same thing) if only to humour us, because it should work. If not, then we can start looking for the real problem
Comment: Oh, submit handlers are always an array BTW, so `$form['#submit']='';` would be `$form['#submit']=array();`. Probably not causing the problem, but worth ruling out. If i had to put money on what the problem is, I'd say that you're removing the submit handlers too late in the process, i.e. after `drupal_get_form` has already cached all of that info
Comment: Now that's interesting. I threw a `function my_theme_form_alter(&$form, &$form_state, $form_id) {
  if($form_id=="my_content_type_node_form"){
    $form['#submit']=array();
    $form['actions']['submit']['#submit']=array();
  }
 }` and on submit, no data hit the database. Thanks! Any idea why using `drupal_get_form` and setting the `#submit`s to `array()` doesn't accomplish the same thing?
Answer: Since I suggested this in my comment (the first in the thread) I'll rephrase as an answer so that you can mark it as correct.
Rather than using drupal_get_form() to build the node edit form (which just doesn't work the way you tried to do it, as there is no such callback my_content_type_node_form as far as I know) and then modifying the $form array, my suggestion is to:

Let Drupal build your node edit form (you can do this by calling the appropriate URL /node/8/edit or /node/add/[type])
Then use the widely documented way of altering a form by implementing
hook_form_alter.

EDIT: Digging a bit more I did find a hook_form function callback for nodes, but it's standard for all nodes - it's implemented in the node.module as node_content_form(). The hook is invoked in node_form() but as far as I can tell (I did some trials) it's the same for all Content Types regardless of their machine name. I think this may be where the confusion started.


Is the solution of the equation $x^x=2$ rational?

Question: Let $x$ be the solution of the equation $x^x=2$. Is $x$ irrational? How to prove this?
Comment: Related: [If $x$ is a positive rational but not an integer, is $x^x$ irrational?](http://math.stackexchange.com/questions/978174)
Answer: If $x$ is rational, $p/q$, then $2^{q/p}$ is rational. That's only possible if $p=1$ and $p/q$ is an integer.
A quick way to write it, assuming $p,q$ are relatively prime:
$$\left(\frac pq\right)^{p/q}=2\implies p^p=2^qq^p$$
But $p$ and $q$ are relatively prime, using unique factorization, we see that $p^p,q^p$ are relatively prime, so $q^p=1$ which means either that $p=0$ (not possible) or $q=1$. If $q=1$, then $p^p=2$, so again by unique factorization, $p=2^k$ and $1=k2^k$, which can't be solved.
Answer: Suppose $x$ is rational. Then there exist two integers $a,b$ such that $$\left(\frac{a}{b}\right)^{a/b}=2 \\ \frac{a}{b} = 2^{b/a}.$$ But that's impossible because the RHS is rational only for $a=1$, which actually makes it also integer, while with $a=1$ the LHS is non-integer for all $b>1$. Checking that $(a,b)=(1,1)$ yields the false identity $1=2$ concludes the proof.
Answer: Suppose $x$ is rational. Clearly $x<2$ and $x>1$, so $x$ is not an integer. Now from this question we obtain that $x^x=2$ is irrational, a contradiction: If $x$ is a positive rational but not an integer, is $x^x$ irrational?


Applying the Cauchy Schwarz Inequality

Question: Let $A = (a_{ij})$ be an $n \times n$ real matrix, $I = (\delta_{ij})$ the $n \times n$ identity matrix, $b \in \mathbb{R}^n$. Suppose that $$\|A - I\|_2 = \left(\sum_{i=1}^n \sum_{j=1}^n (a_{ij} - \delta_{ij})^2\right)^{\frac{1}{2}} < 1$$ 1) Use the Cauchy-Schwarz Inequality to show that the map $T: \mathbb{R}^n \to \mathbb{R}^n$ defined by $T(x) = x - Ax + b$, satisfies $\rho(Tx, Ty) \leq \alpha \rho(x,y)$ for some $\alpha \in (0,1)$, where $\rho$ stands for the unique standard Euclidean distance in $\mathbb{R}^n$.

I know that the CSI in $\mathbb{R}^n$ is defined as $$\left(\sum_{i=1}^n x_i y_i\right)^2 \leq \left(\sum_{i=1}^n x_i^2\right) \left(\sum_{j=1}^n y_j^2\right)$$ but i'm not really sure how we can apply this to our problem. We have the map $T$ defined above with a certain metric property. What can we do with it?
Comment: What is $\rho$?
Answer: Write $Tx = b - (A - I)x$. Then you can see that $Tx - Ty = (A - I)(y - x)$, which implies $\rho(Tx,Ty) \le \alpha \rho(x,y)$, with $\alpha = \|A - I\|_2 < 1$.

Applying the Cauchy Schwarz Inequality


Calculate matrix to power 101

Question: Being given that
A = $\bigl( \begin{smallmatrix} 1  \\ 1  \\ -1 \end{smallmatrix} \bigr)$
and B = $\bigl( \begin{smallmatrix} 1  &2 &-1 \end{smallmatrix} \bigr)$,
Calculate C = $A \cdot B$ and $C^{101}$.
Answer: Hint : $C^{101}=A \cdot (B \cdot A)^{100} \cdot B$
Comment: How does that help??
Comment: $B \cdot A$ is a scalar, then it is easy to compute the $100$th-power. @neonpokharkar
Comment: Also, interpretation: $C^3=AB\cdot AB\cdot AB=A(BA)(BA)B=A(BA)^2B$.
Comment: OH, now i see it!
Answer: $$A.B=\begin{pmatrix}1 &2&-1\\1&2&-1&\\-1&-2&1\end{pmatrix}$$

$$\begin{pmatrix}x&2x&-x\\x&2x&-x\\-x&-2x&x\end{pmatrix}\begin{pmatrix}x&2x&-x\\x&2x&-x\\-x&-2x&x\end{pmatrix}=4\begin{pmatrix}x^2&2x^2&-x^2\\x^2&2x^2&-x^2\\-x^2&-2x^2&x^2\end{pmatrix}$$

now, $$C^2=4\begin{pmatrix}1&2&-1\\1&2&-1\\-1&-2&1\end{pmatrix}$$$$C^3=16\begin{pmatrix}1&2&-1\\1&2&-1\\-1&-2&1\end{pmatrix}$$$$\vdots$$$$C^{n+1}=4^n\begin{pmatrix}1&2 &-1\\1&2&-1\\-1&-2&1\end{pmatrix}$$
Hence,
$$C^{101}=4^{100}\begin{pmatrix}1 &2&-1\\1&2&-1&\\-1&-2&1\end{pmatrix}=4^{100}C$$
Comment: Good answer. The pattern is very clear. A formal induction argument is needed though.
Comment: And why is it wrong, can you elaborate
Comment: Can you recheck now again? I hope all is right
Comment: Made $C^{n-1}\to C^{n+1}$

Calculate matrix to power 101


Add shared contacts to Outlook 2007 address book

Question: Hello we just upgraded from exchange 2003 to 2010.  2010 seems to be pushing people to stop using public folders.  Public folders had the nice feature that you could see the contacts of the public folder in your address book.  I haven't found a way to add shared contacts to the Outlook address book.  How do you do it?  If I am unable to find the solution I will likely have to go through the hassle of migrating the public folders over.  I was having a problem with that so I went the route of shared contacts.
Comment: Just as note - the 2010 "do not use public folders" mantra was pretty much immediately thrown out in 2013, which redid and reintroduced public folders. While wondering why anyone would now update to 2010 (instead of 2013) - I would not bother about "do not use public folders" as long term issue.
Answer: You could create your contact records in the Active directory.  After all it is a directory server.


xpath get the third tr and more in a table

Question: I have this html (just the general case, not the exact html)

how can i get the third tr and more. I mean the third tr, the fourth tr, the fifth tr.... and so on.
what I tried
table/tr[3:]

But I don't know if it is correct or not because the python is not working on my machine right now.
Answer: Use this XPath:
//tr[position() > 2]

Comment: +1 Thanks, I will accept the answer after 14 minutes


Creating JMenuitem's in a for loop

Question: Greeting, I'm trying to do this:
public float a=0;

for(a=1 ; a<100;a++){
        String fuent="font"+String.valueOf((int)a);
        JMenuItem fuent=new JMenuItem(String.valueOf(a));
        fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
        tamano.add(fuent);
        }

But it throws these errors:
cambiar.java:71: error: variable fuent is already defined in constructor cambiar()
        JMenuItem fuent=new JMenuItem(String.valueOf(a));
                  ^

cambiar.java:72: error: cannot find symbol
        fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
             ^

symbol:   method addActionListener(<anonymous ActionListener>)
  location: variable fuent of type String
2 errors
[Finished in 0.5s with exit code 1]

I've trying to do this:
JMenuItem (String)fuent=new JMenuItem(String.valueOf(a));
 JMenuItem System.out.println(fuent)=new JMenuItem(String.valueOf(a));

but none works.
---EDIT----
I think some are confuse about what I want:
String fuent="font"+String.valueOf((int)a);
        JMenuItem fuent=new JMenuItem(String.valueOf(a));//(Here sould go the value of the String, Example "font1")
        fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
        tamano.add(fuent); //(Same Here)

Answer: You defined two different variables with he same name
String fuent ="font"+String.valueOf((int)a);
JMenuItem fuent =new JMenuItem(String.valueOf(a));

Try renaming one or both, for example
String strFuent="font"+String.valueOf((int)a);
JMenuItem miFuent=new JMenuItem(String.valueOf(a));

UPDATED EXAMPLE
JMenuItem fuent=new JMenuItem("font"+String.valueOf((int)a));

Will solve your problems
UPDATED after OP Edits
This will still not work...
String fuent="font"+String.valueOf((int)a); // You have defined fuent as a String
// Here you are trying to define fuent AGAIN as a JMenuItem
// You CAN NOT DO THIS...
// Change one of the variable names
JMenuItem fuent=new JMenuItem(String.valueOf(a));//(Here sould go the value of the String, Example "font1")
fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
tamano.add(fuent); //(Same Here)

This will now work...
String fuent1="font"+String.valueOf((int)a); // You have defined fuent as a String
JMenuItem fuent=new JMenuItem(fuent1);
fuent.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        texto.setFont(texto.getFont().deriveFont(a)); current=a;
    }
});
tamano.add(fuent); //(Same Here)

Comment: The float is public outside the class, the name I know, the problem is that want to name the JMenuItem as the value of the String "Fuent"
Comment: The float has nothing to do with it. You CAN NOT HAVE TWO VARIABLES WITH THE SAME NAME OR LABEL. The only thing you can do is change the variable names. The text you supply to the menu item is irrelevent
Comment: Did you read the edit that I make?... Im trying yo make the JmenuItem have the value of the String... Example:
String hi="Button1";
JMenuItem "Button1"(The value of the String)....
Comment: Did you read the answer.  The text you are passing is irrelevent to your problem. You have two variables of different types named the same. Change one of the variable names and it will work just fine
Comment: If i change the Variable it works... But it will be passing the same JMenuItem to everything... What i mean is that they all will got the last value that "a" has... in this case 99... I will got 99 JmenuItem with the value 99...
Comment: I'm sorry to be so insistent...xD... But cheking at what you edit, is not what i need...

JMenuItem fuenta(Here, the jMenuItem sould be the value of the String, that way, will not rewrite every ActionListener that i make)=new JMenuItem(String.valueOf(a));

Anyways, Thanks in advance.
Comment: Fine remove the line `String fuent="font"+String.valueOf((int)a);` and you menu items will read "1" through "99"
Answer: You should learn the basics of Java, as your code has major basic issues (the float a can't be defined public there, unless it was really somewhere else and you just put it there to show us it). You cannot define the same name for a variable twice; call one fuentMenu and one fuentString or whatever.
Comment: The float is public outside the class, the name I know, the problem is that want to name the JMenuItem as the value of the String "Fuent"

Creating JMenuitem's in a for loop


Why does  operator<< pick the apparently wrong overload?

Question: Consider this code:
#include <iostream>
using namespace std;

class X {
public:
    operator const wchar_t* () const { return L"Hello"; }
};

void f(const void *) {
    wcout << L"f(const void*)\n";
}

void f(const wchar_t*) {
    wcout << L"f(const wchar_t*)\n";
}

int main() {
    X x;
    f(x);

    wcout << x;
}

The output is (compiled with the VS2015 C++ compiler):

f(const wchar_t*)
00118B30

So it seems that the compiler selects the expected const wchar_t* overload for f (as there's an implicit conversion from X to const wchar_t*).
However, it seems that wcout << x picks the const void* overload, instead of the const wchar_t* one (printing an address, instead of a wchar_t string).
Why is this?
P.S. I know that the proper way of printing X is to implement an overload of operator<< like wostream& operator<<(wostream& , const X&), but that is not the point of the question.
Comment: It might not be the point but asking why a program with undefined behavior behaves a certain way doesn't make any sense, even if in your case it doesn't change anything.
Comment: For those complaining about mixing wcout and cout, I changed the code to use wcout instead of cout in the trace messages inside f overloads. Same output.
Comment: Note that the operator which prints `const void*` is a member function, and the one which prints `const wchar_t*` is a non-member function. I'm not familiar enough with the lookup rules to cite why that should matter, but I'm pretty sure it does.
Comment: This might not be it, but your program has [undefined behavior](https://stackoverflow.com/questions/8947949/mixing-cout-and-wcout-in-same-program). You can't mix and match `std::cout` and `std::wcout`.
Comment: @Rakete1111: That's not the point. Feel free to use wcout instead of cout to track the selected overloads of f :)
Comment: @KingThrushbeard: No, printing an object does not yield its address, unless you write a function which does that.
Answer: Because when deducing template arguments the conversion functions are not considered:
// Non-template member function.
basic_ostream& basic_ostream::operator<<( const void* value );

// Template non-member function.
template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os,
                                         const CharT* s );

The second declaration does not consider the conversion operator const wchar_t* () const.
I cannot find the standard quote, cppreference Template argument deduction, Implicit conversions says:

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
Comment: If you remove the non-template it will not even compile, because implicit conversion doesn't happen for template argument deduction. :)


Could not find "store" error in connected component nested in Dialog

Question: I have a connected component that will render fine when wrapped with a
, but when I wrap with Dialog component, I keep getting the dreaded: Could not find "store" in the context of "Connect(MyComponent)". Yes, the root <App /> is wrapped with <Provider /> and the store is fine, all other pages, components, connected items have access to store, just not when rendered in this Dialog.
This has not been a problem in the past, and was obviously hosed as a side effect from some dependency maintenance that was occurring. If I swap the Dialog component's underlying lib from MUI 0.20 to version 3 (via @material-ui/core/Dialog) it works fine. There's something going on with a balance between mui 0.20 and updated react-ish dependencies.
Just wondering if anyone has experienced this?
// Where it's invoked...

<ParentPageComp>
  <Dialog open>
    <MyConnectedComponent />
  </Dialog>
</ParentPageComp>

// What is being attempted to render...

class MyConnectedComponent extends React.Component {
  render() {
    return
Yeppers
;
  }
 }

export default connect(state => ({ blah: state.blah }))(MyConnectedComponent);

Again, if I replace <Dialog> with
, all is normal.
Not sure if this is relevant, but the parent components wrapping the Dialog are async loaded with hooks... even when replacing with code splitting mechanism of react-loadable, I get the same naughty results.
Using:

Material-ui 0.20.2 (yes, the old one)
React 16.8.6
Redux 4.0.1
React-redux 7.1.0
React-router-dom 5.0.0
Comment: RenderToLayer (used by [Dialog](https://github.com/mui-org/material-ui/blob/v0.x/src/Dialog/Dialog.js#L488)) looks like a potential source of the problem: https://github.com/mui-org/material-ui/blob/v0.x/src/internal/RenderToLayer.js#L110
Comment: If you can reproduce this in a [CodeSandbox](https://codesandbox.io/s/new) it will make it easier for someone to try to help.
Comment: Looks like a good reason to upgrade Material-UI.
Comment: upgrade for sure... it's overdue, just balancing hours. For now I have the newer version of cherry picked components running alongside the legacy version components
Answer: Old version can easily block context propagation thru DOM hierarchy. You can manually carry context over <Dialog/> component like this
import { Provider, ReactReduxContext } from 'react-redux';

//...
render() {
    return (
        <ParentPageComp>
            <ReactReduxContext.Consumer>
                {((ctx) => (
                    <Dialog open>
                        <Provider store={ctx.store}>  /* make store available again */
                            <MyConnectedComponent />
                        </Provider>
                    </Dialog>
                )).bind(this) // Dont forget to bind this
                }
            </ReactReduxContext.Consumer>
        </ParentPageComp>
    );
}

Comment: thanks a ton, this was it... while I am upgrading bit by bit, this explained exactly what was going on and helped me understand. I'll be able to push a new test version today thanks to your help
Comment: This solution works for me without bind this (eslint no-extra-bind). Our team discovered this issue after upgrading our app from react-redux v5.x to 7.1.0. We had no issues using the Dialog components before.


$n\#$ (the $n$th primorial) seems very close to $e[(n-1)^n - n^{n-1}]$

Question:
Let $$n\# := P(n) P(n-1) \cdots P(2) P(1) ,$$ where $P(1)$ is the smallest prime, $2$, $P(2) = 3$, and so on. Then, as an example of what is claimed in the above title, $$P(11) = 200\,560\,490\,130, \qquad \textrm{and} \qquad 10^{11}-11^{10}=74\,062\,575\,399,$$ which is very close to $1/e$ times the first number. Does this continue to hold?

If so, I bet it is already known, but I'd like to know where to find it. There may be a connection with the Chebyshev function on Wikipedia, but that seems more akin to $e^{P(n)}$.
Comment: I've taken the liberty of formatting the question this time. Please ensure that the changes preserve the intended meaning and edit accordingly.
Comment: Here's [a reference for MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) you might find useful, which is preferred for writing up and rendering your math text on this site.
Answer: To simplify your expression,
$\begin{array}\\
e[(n-1)^n - n^{n-1}]
&=en^{n-1}[(n-1)(1-1/n)^n - 1]\\
&=en^{n-1}[(n-1)(\frac1{e}-\frac1{2en}+O(\frac1{n^2}) - 1]\\
&=en^{n-1}[\frac{n}{e}-\frac1{2e}+O(\frac1{n})-\frac1{e}+O(\frac1{n}) - 1]\\
&=en^{n-1}[\frac{n}{e}-\frac{3}{2e}-1+O(\frac1{n})]\\
&=n^{n}-n^{n-1}(\frac32+e)+O(n^{n-2})\\
\end{array}
$
According to
https://en.wikipedia.org/wiki/Primorial,
$n\# = e^{n(1+o(1))}
$,
which does not match your expression.
However,
the standard definition of $n\#$
is the product
of the primes up to $n$.
Your definition is
the product of the first $n$ primes.
Since the $n$-th prime
is about $n\ln(n)$,
this gives
$e^{(1+o(1))n\ln(n)}
=(e^{\ln(n)})^{(1+o(1))n}
=n^{(1+o(1))n}
$
and this does match your expression.
Note that
$n^n$ would work just as well,
since
$n^{n-1} = o(n^n)
$
and
$e(n-1)^n
=en^n(1-1/n)^n
=n^n(1+o(1))
$.
Comment: I don't get why you say n^n would work just as well. Putting numbers in for n^n give answers pretty far off.
Comment: Do you have tables of the ratio of the various expressions so we can see how good the approximations are?
Comment: I was just using a pocket calculator, and the formula [(n-1)^n-n^(n-1)]*e gradually improved and got really accurate when n was 10,11 and 12. But at n=6, I think its accuracy was barely better than 30%. For the other approximation, I just noticed that although the formula n^n starts out quite inaccurate, by the time it reaches n=12, its accuracy is about 20%, so perhaps it becomes comparable in accuracy as n-->oo.


limit involving expressions of the form $n^x \log n$

Question: In doing calculations involving computational complexity the following function came up:
$$f(x) = \lim_{N \rightarrow \infty} \frac{\sum_{n=1}^N n^x \log n}{N^{x+1} \log N}$$
for $x \in \mathbb{R}^+$. It appears to be true that
$$f(x) = \frac{1}{x+1}$$
but I am not sure how to prove this. Could anyone suggest an approach?
Comment: You can approximate the sum with $\int_1^N t^x\log t\,dt$. Find the asymptotic behaviour of that (integration by parts can help), and estimate the error of the approximation to see that it is insignificant when divided by $N^x\log N$.
Answer: $f(x) = \displaystyle \lim_{N\to \infty}\dfrac{1}{N\log N}\left(\displaystyle \sum_{n=1}^N \left(\dfrac{n}{N}\right)^x\log n\right)=\displaystyle \lim_{N\to \infty}\dfrac{1}{N\log N}\left(\displaystyle \sum_{n=1}^N \left(\dfrac{n}{N}\right)^x\log\left(\dfrac{n}{N}\right)+\log N\displaystyle \sum_{n=1}^N\left(\dfrac{n}{N}\right)^x\right)= \displaystyle \lim_{N\to\infty}\dfrac{\displaystyle \int_{0}^1 t^x\log tdt}{\log N}+\displaystyle \int_{0}^1 t^xdt=0+\dfrac{1}{1+x}=\dfrac{1}{1+x}$


Nginx X-Frame Options, Iframe Wordpress

Question: Using Wordpress on Nginx.
I am receiving these errors but I can't seem to find out where in my Nginx options I have specified this 'DENY' header.
<code>Multiple 'X-Frame-Options' headers with conflicting values ('SAMEORIGIN, DENY') encountered when loading 'https://beta.com/wp-admin/plugin-install.php?tab=plugin-information&plugin=duplicate-post&'. Falling back to 'DENY'.

Refused to display 'https://beta.com/wp-admin/plugin-install.php?tab=plugin-information&plugin=duplicate-post&' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN, DENY'.

load-scripts.php?c=1&load[]=jquery-core,jquery-migrate,utils,jquery-ui-core,jquery-ui-widget,jquery…:2 Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Sandbox access violation: Blocked a frame at "https://beta.com" from accessing a frame at "null".  The frame being accessed is sandboxed and lacks the "allow-same-origin" flag.
</code>
Any ideas?
In the core files of wordpress functions.php I can see
<code> * Send a HTTP header to limit rendering of pages to same origin iframes.
 *
 * @since 3.1.3
 *
 * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
 */
function send_frame_options_header() {
    @header( 'X-Frame-Options: SAMEORIGIN' );
}
</code>
But I guess that's not the problem since other users would have mentioned it.
Comment: Wordpress might be setting it. Look for the string X-Frame-Options in your wordpress and plugins install.
Comment: there is a mentioning in functions.php but i don't think that's the issue
Comment: looks similar: https://wordpress.org/support/topic/multiple-x-frame-options-headers-with-conflicting-values-sameorigin-deny/
Comment: you are god! that was added by let's encrypt - fixed now :) how can i give you credit !
Comment: happy to help, will copy that answer below in case it disappears from wordpress.org.
Answer: Similar problem was posted to:
https://wordpress.org/support/topic/multiple-x-frame-options-headers-with-conflicting-values-sameorigin-deny/
Answer copied here for future reference, from
https://wordpress.org/support/users/knnleow/
There is duplicate setting in two places for the same config.
I removed the duplicate entry in
<code>/etc/nginx/site-available/default
</code>
config file.
Updated my
<code>/etc/nginx/snippets/ssl-dhparams.conf
</code>
to:
<code>#add_header X-Frame-Options DENY;
add_header X-Frame-Options SAMEORIGIN;
</code>

Nginx X-Frame Options, Iframe Wordpress


Is Google causing problems?

Question: I have been getting the following notice from Google's IP address:

Unable to generate the derived image located at public://styles/large/public/field/image/imagefield_b9xgKB.jpg

Why does it happens? It started a week ago, and now it happens few times in a day. Sometimes the filename varies.
Comment: Do you have an image with that name? Do you use that image style? Have you checked google's webmaster tool to see why it's trying to index that image? Is this Drupal related?
Answer: This is an error saying you have a link to an non-existing resource.
You should use Webmaster Tools to dig deeper, if I remember correctly, it should provide the URL for the page with the bad link.

Is Google causing problems?


Java Regex Anomaly?

Question: I have a list of address such as the following:
Find Dabla Inc at 6889 66th Ave, NY, NY 11884-3773. Call them at (888) 292-1655.
Find Walgreen Drug Stores at 6008 87th Ave, NY, NY 17774-4314. Call them at (888) 999-473
Find Silver Star Restaurant at 6941 99th Ave Ste A, NY, NY 88804-2915. Call them at (888) 851-2799.

I am trying to extract the street address, state, city and zip code from this text via Regex.
Currently, I am using the following to match street address:
    (?<=at\s)\d{3,5}\s\S*\s\w*.*(?=,)

However, I see it inlcudes in match         NY, instead of stopping after the first comma (it only stops after second comma).. Why is it including first comma if I'm using a positive lookahead?
Thannks
Comment: Java.. i thought it was the same for both..
Answer: (?<=at\s)\d{3,5}\s\S*\s\w*.*?(?=,)

                            ^^

Make your regex non greedy.
See demo: https://regex101.com/r/fX3oF6/14
Comment: @KimClinton you can also use `(?<=at\s)\d{3,5}\s+[^,]*` a shortened version
Comment: I tried. I got: "Cannot accept an answer in 11 minutes" :) I will wait a little to accept..

Java Regex Anomaly?


What does this marking mean? The star and swirl with 4312 over it

Question:
What does this notation in the treble clef mean?
Answer: This is the symbol for a "turn" (the swirl, that is). Here's how I would play it:

The turn is positioned over the second half of the note; the "star" is not a star, but a double-sharp symbol, meaning that the "below" note of the turn (G) is a G-double-sharp.
(It usually helps if you name the piece: this is no. 4 in E minor from Chopin's preludes.)
Comment: And to add to this: 4312 is the intended fingering for the swirl.  (The swirl itself, as a conventional ornament, is not written out in full, but the fingering is added by the editors, who have chosen to write it out as it is rather non-obvious.)
Comment: The actual name for this symbol is called a "gruppetto".
Comment: @jjmusicnotes:  I don't think "actual name" is appropriate; "gruppetto" is the Italian term, but in English, it is normally referred to as a "turn". See for example Gardner Read, Music Notation, p. 246