Como remover um array de dentro de outro array filtrando os que tiverem o valor X em uma chave especifica em Nodejs?

Question: Estou iniciando no Node.js e tenho um pouco de dificuldade em lidar com array/json, estou em processo de aprendizado ainda.
Supondo o seguinte array de arrays:
Array base que deverá ser filtrado:
[
   {
      "id": 1,
      "nome":"Jonh Doe",
      "city":"NY",
      "status":"Single"
   },
   {
      "id": 2,
      "nome":"Mary",
      "city":"NY",
      "status":"Single"
   },
   {
      "id": 3,
      "nome":"Tom",
      "city":"CO",
      "status":"Married"
   },
   {
      "id": 4,
      "nome":"Mark",
      "city":"MI",
      "status":"Divorced"
   },
   {
      "id": 5,
      "nome":"Carl",
      "city":"NY",
      "status":"Single"
   },
]

Precisaria salvar em uma variável este mesmo array porém somente onde a chave city for igual a NY. Pesquisei sobre .map, .filter, .reduce, .indexOf porém não consegui chegar a um resultado. Como eu poderia atingir o seguinte resultado:
Array filtrado somente de NY:
[
   {
      "id": 1,
      "nome":"Jonh Doe",
      "city":"NY",
      "status":"Single"
   },
   {
      "id": 2,
      "nome":"Mary",
      "city":"NY",
      "status":"Single"
   },
   {
      "id": 5,
      "nome":"Carl",
      "city":"NY",
      "status":"Single"
   },
]

Answer: Olá, acho que não pesquisou bem, porque filter e map podem fazer isso, de uma maneira até bem simples:

var array = [
   {
      "id": 1,
      "nome":"Jonh Doe",
      "city":"NY",
      "status":"Single"
   },
   {
      "id": 2,
      "nome":"Mary",
      "city":"NY",
      "status":"Single"
   },
   {
      "id": 3,
      "nome":"Tom",
      "city":"CO",
      "status":"Married"
   },
   {
      "id": 4,
      "nome":"Mark",
      "city":"MI",
      "status":"Divorced"
   },
   {
      "id": 5,
      "nome":"Carl",
      "city":"NY",
      "status":"Single"
   },
];

var novoArray = array.filter(x => x.city == "NY");
console.log(novoArray);

Nesse exemplo usei filter, que deve receber uma function ou expressão que avalia cada elemento do array, e retorna true/false para cada elemento, e os elementos onde a condição for true são retornados. Ou seja, os elementos onde city == "NY" são retornados, devolvendo um novo array só com esses elementos.
Comment: Bem explicado Ricardo. Os exemplos que eu via era sempre `var array = [1, 2, 3, 4, 5]` e filtrando um numero especifico ou algo assim, achei que teria grandes diferentes pra remover o array inteiro com base em uma chave. Eu achei que o `.filter` ia remover apenas aquela chave e não o array inteiro. Obrigado.
Answer: Na verdade não é só Node.js é JavaScript no geral. Como você já mencionou, dá para resolver em uma linha só com filter, supondo que seu array inicial se chama cidades:
cidades.filter(i => i.city === "NY")

Versão mais detalhada:
cidades.filter(cidadeIteracao => {
  if (cidadeIteracao.city === "NY") {
    return cidadeIteracao;
  }
});


How to count unique values in pandas column base on dictionary values

Question: I have the below pandas data frame.
d = {'id1': ['85643', '85644','85643','8564312','8564314','85645','8564316','85646','8564318','85647','85648','85649','85655','56731','34566','78931','78931'],'ID': ['G-00001', 'G-00001','G-00002','G-00002','G-00002','G-00001','G-00001','G-00001','G-00001','G-00001','G-00002','G-00002','G-00002','G-00002','G-00003','G-00003','G-00003'],'col1': [671, 2,5,3,4,5,60,0,0,6,3,2,4,32,3,1,23],'Goal': [np.nan, 56,78,np.nan,89,73,np.nan ,np.nan ,np.nan, np.nan, np.nan, 34,np.nan, 7, 84,np.nan,5 ], 'col2': [793, 4,8,32,43,55,610,0,0,16,23,72,48,3,28,5,3],'col3': [500, 22,89,33,44,55,60,1,5,6,3,2,4,13,12,14,98],'Date': ['2021-06-13', '2021-06-13','2021-06-14','2021-06-13','2021-06-14','2021-06-15','2021-06-15','2021-06-13','2021-06-16','2021-06-13','2021-06-13','2021-06-13','2021-06-16','2021-05-23','2021-05-13','2021-03-26','2021-05-13']}
dff = pd.DataFrame(data=d)
dff

    id1     ID      col1    Goal        col2    col3    Date
0   85643   G-00001 671     NaN         793     500 2021-06-13
1   85644   G-00001 2       56.0000     4       22  2021-06-13
2   85643   G-00002 5       78.0000     8       89  2021-06-14
3   8564312 G-00002 3       NaN         32      33  2021-06-13
4   8564314 G-00002 4       89.0000     43      44  2021-06-14
5   85645   G-00001 5       73.0000     55      55  2021-06-15
6   8564316 G-00001 60      NaN         610     60  2021-06-15
7   85646   G-00001 0       NaN         0       1   2021-06-13
8   8564318 G-00001 0       NaN         0       5   2021-06-16
9   85647   G-00001 6       NaN         16      6   2021-06-13
10  85648   G-00002 3       NaN         23      3   2021-06-13
11  85649   G-00002 2       34.0000     72      2   2021-06-13
12  85655   G-00002 4       NaN         48      4   2021-06-16
13  56731   G-00002 32      7.0000      3       13  2021-05-23
14  34566   G-00003 3       84.0000     28      12  2021-05-13
15  78931   G-00003 1       NaN         5       14  2021-03-26
16  78931   G-00003 23      5.0000      3       98  2021-05-13

Also, I have the below dictionary
dic = {'G-00001':{'aasd':['G-00001','85646','85648','345_2','85655','85659','85647'],
'vaasd':['G-00001','85649','34554','85655','22183','45335','8564316']},
'G-00002':{'aasd2':['G-00002','85343','85649','85655','78931','45121','56731']},
'G-00003':{'gsd3':['G-00003','34566','8564312','45121','78931']}}

I want to get a unique count of id1, based on the list inside the dictionary based on theire ID column. For example, if we consider ID - 'G-0002' has only one list aasd2.                     'aasd2':['G-0002','85343','85649','85655','78931','45121','56731']. I want to get how many unique id1's are in the 'G-0002' ID column in pandas' data frame. So it should be for aasd2- 3 values ('85649','85655','56731'). Those are the only three id1 values in pandas for aasd2 in 'G-0002' ID.
So I want to create a table just like below for the list name and count of id1s
listName    count of id1s
aasd            2
vaasd           1
aasd2           3
gsd3            2

or is it possible to get kind a below out put
#Is it possible to get what id1 in each list? for example aasd2-value count 3
#and ['85649','85655','56731'].
ID            id2     Value count        list
G-00002     aasd2     3                 ['85649','85655','56731']
G-00001     aasd      2                 ['85646','85647']
G-00003     gsd3      2                 ['34566','78931']
G-00001     vaasd     1                 ['8564316']

Is it possible to do this in python? Any suggestion would be appreciated. Thanks in advance!
Answer: From my previous answer, I slightly modified the code:
data = []
for g, d in dic.items():
    for k, l in d.items():
        data.extend([(g, v, k) for v in l])
df1 = pd.DataFrame(data, columns=['ID', 'id1', 'id2'])

out = dff.merge(df1, on=['ID', 'id1']) \
         .drop_duplicates(['ID', 'id1']) \
         .value_counts('id2')
print(out)

# Output:
id2
aasd2    3
aasd     2
gsd3     2
vaasd    1
dtype: int64

Update

Is it possible to get what id1 in each list? for example aasd2-value count 3 and ['85649','85655','56731'].

out = (
  dff.merge(df1, on=['ID', 'id1']).drop_duplicates(['ID', 'id1'])
     .groupby(['ID', 'id2'])
     .agg(**{'Value Count': ('id2', 'size'), 'List id1': ('id1', list)})
     .reset_index()
)
print(out)

# Output:
        ID    id2  Value Count               List id1
0  G-00001   aasd            2         [85646, 85647]
1  G-00001  vaasd            1              [8564316]
2  G-00002  aasd2            3  [85649, 85655, 56731]
3  G-00003   gsd3            2         [34566, 78931]

Answer: Look through the dictionary and create a dataframe and merge with dff then take nunique and create a dictionary with the results:
d={}
for k,v in dic.items():
    for k1,v1 in v.items():
        tmp = pd.DataFrame(v1,columns=['id1']).iloc[1:].assign(ID=k)
        d[k1] = tmp.merge(dff[['id1','ID']])['id1'].nunique()

print(d)
{'aasd': 2, 'vaasd': 1, 'aasd2': 3, 'gsd3': 2}

#for output as series
print(pd.Series(d)
aasd     2
vaasd    1
aasd2    3
gsd3     2
dtype: int64


How to pull active user name from drupal 6

Question: Is it possible to pull the active user name or active ldap user from my drupal site, and store this in a separate DB, as i would like to use it because the login limits who can access the site, but I want to know who is submitting x,y,z data into my forms? so at the top of the form maybe a field that pulls their username?
Answer: Drupal 6 supports multiple DBMS connections easily in settings.php (to the same type of DBMS, eg 2 Mysql DBs, not 1 MySQL and 1 SQLServer).
You can use a function like hook_user to track who has logged in and feed that username into your 2nd database using the database api and for instance the db_query function. You also likely need db_set_active.
EDIT
I'm not sure exactly what your trying todo. You can always use php's ldap functions to talk to ldap and look for info on the "user" (if they're not logged in yet I have no clue what you'd grad from ldap ...). You could always use hook_form_alter to assign additional submit handlers on any default drupal form to perform custom tasks.
Having used ldap_integration for D6. You should realllly think about moving the site to D7 as the new ldap module is pretty nice and lets you save off ldap queries as re-runnable things :).
Comment: I wish I could use drupal 7 however the place I'm doing my placement with has too many sites and other project getting developed on drupal 6. Your answer sounds about right, I will have to give it a go on Monday. Thanks


How can you create a list of referenced nodes in a view?

Question: I have a content type on my Drupal 7 site which has a field called field_related, with a type of Node reference (I've installed References). This allows me to select nodes that are related to the one I am editing. I'd like to then display these in a view, but am coming unstuck with the setting up of the view.
I've set up a single document with some related nodes for testing. If I set a relationship up in my view as "Content: Related Nodes (field_related) - reverse", I see a list of the related nodes I defined. But I see these same related nodes on every single page - not just the page they are defined for. ("Require this relationship" is ticked.)
If I set up the relationship as "Content: Related Nodes", nothing appears. I've tried a variety of filters, contextual filters and relationships, but that hasn't helped much.
I'm sure I'm missing something obvious ... can anyone enlighten me?
Some screenshots of the current setup, so you can see what I've got so far:

View

Contextual filter

Relationship
Answer: Got there in the end, thanks to a combination of the (very nice and helpful) Baysaa and keva. This was the method that got there in the end:

Contextual Filter: Content: Nid (set to "do not use a relationship"; default value of "content ID from URL")
Relationship: Content: Related Nodes (with "require this field")
Then, I went to Format and changed Show: Content to anything else. Then I changed it back to Show: Content - this allowed me to select the relationship I defined above (I couldn't define the relationship here without changing Show: Content to something else first).
Comment: Anyone who is looking for solution to use this in Show: Fields: In field settings (for example Content: Title) you can define Relationship from dropdown.
Answer: On the settings of the "Content: Related Nodes" contextual filter, under "WHEN THE FILTER VALUE IS NOT AVAILABLE" have you selected "Provide default value" and set "Content ID from URL"?
EDIT: Sorry I meant under the "Contextual Filter". "Content: Related Nodes" should be a Contextual Filter, not a relationship.
Comment: I've added that, but it hasn't changed anything. I've added some screenshots to the above for clarity.
Comment: Remove the Relationship from the Contextual filter, and remove the Relationship altogether.
Comment: Getting nearer - thanks :). I've removed the relationship and contextual filter, and added a new contextual filter as you described. Unfortunately, it seems to be working in reverse. Instead of looking at my test node (A) and seeing the three related nodes I defined for it (B, C and D), I now see node A listed as a related node on each of B, C and D.
Comment: What's the result of the view when you view Node A? Did you by chance install a module called "Corresponding Node References"?
Comment: On Node A, I see none of the referenced nodes. And no, no module by that name.
Comment: On Node A do you have the "Related" nodereference field? And is Node B, C, and D referenced in that field? If so, I'm sorry I can't help you any further. All I can suggest is double check the View and the Content Type. I've looked at my implementation of Related nodes using Nodereference field and it's setup exactly as I've described it to you. If you DON'T have a nodereference field on Node A, then you should.
Comment: Yes, Node A has the "Related" field (set to "Unlimited", and with Nodes B, C and D showing). Thanks for your help - I'll have another look :)
Answer: It would help to know how you will be using the view. If you just want to show the related nodes (B,C,D) on node A - say in a sidebar block - then your view is getting over-complicated.
Remove the Contextual filters and Relationships you have, then ...
Add field:

Content: Related Nodes
Choose a formatter

Add Contextual Filter:

NID
WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value > Content ID from URL
Comment: Thanks - this was almost there. It gave me the list of related nodes, but I couldn't format them the way I needed to. I did manage to sort this out using a relationship, contextual filter and by applying a relationship to the format block.
Answer: Contextual Filter: Content: Nid select >> Provide Default value >> PHP code
As we will be displaying related nodes block on a node view page for which we want to display related nodes. So we will load that node first and get all the related nids. Then we return the nids in string format like below
'56 + 32 + 112'
$nid = arg(1);
$node = node_load($nid);
$str = "";
$related_nids = $node->field_related_nodes[$node->language];

if(is_array($related_nids) && sizeof($related_nids)){
  foreach($related_nids as $related_nid){
    $str .= ($str)? '+' .  $blog['nid'] :$blog['nid'];
  }
}
return $str;

Also click the More link in contextual filter and check "Allow multiple values"enter code here


proof that equalizer of f and g is an isomorphism if f = g

Question: I found a proposition and a proof in Categorical Closure Operators by Gabriele Castellini saying that:

Let $E \xrightarrow{e} X$, and $f, g : X \rightarrow Y$ be morphisms
such that $e$ is an equalizer of $f$ and $g$. Then $d$ is an
isomorphism if and only if $f=g$.

I understand the $\Rightarrow$ direction, but I'm not sure about the other way, showing if $f=g$, then $e$ is an isomorphism.
The proof in the book says the following:

If $f=g$, then $id_X$ satisfies $f \circ id_X = g \circ id_x$.
Consequently, by definition of equalizer, there is a morphism $X
 \xrightarrow{t} E$ such that $ e \circ t = id_x$. Hence, e is a
monomorphism and a retraction and so an isomorphism.

Specifically, why is there a morphism $X \xrightarrow{t} E$ such that $ e \circ t = id_x$? I don't think that's a part of the definition of being an equalizer. Any guidance on how to understand this part?
Edit:
The definition of equalizer that I am using is the following:
An equalizer of a parallel pair of maps $f, g \rightrightarrows B$ in a cat $\mathbb{C}$ consists of an object E and an arrow $e: E \rightarrow A $ such that (1) $f \circ e = g \circ e$ (2) (the universal mapping property part) For all $h : X \rightarrow A$ with $f \circ h = g \circ h$, there exists a unique $m: X \rightarrow E$ with $e \circ m = h $
Comment: Would you mind adding your source texts' definition of equaliser? The existence of $t$ is given directly and immediately by the equaliser condition on my reading.
Comment: Oooh I see.. Thank you so much! You can also add your comment as the answer (if that's something allowed) so I that I can endorse(?) it. (Not sure about the lingo, I'm a new contributor)
Comment: That is something that is allowed, thanks for trying to be conscious of the rules of Math SE, and welcome! I will type up a short proof for you!
Comment: I added the definition of equalizer to the question. Does my definition imply the part I'm asking about?
Comment: Great! so the existence of $t$ is given by the universal mapping property in the case that $h: = 1_X$, noting that $f \circ h = f = g = g\circ h$. Here we used the fact that $f = g$ by hypothesis and $h$ is an identity map.
Answer: Note that the map $h: X \to X$ given by $1_X$ satisfies equation $(1)$:
$$
\begin{align}
f \circ h &= f & \text{by identity axiom}\\
&= g &\text{by hypothesis }\\
&= g \circ h. & \text{by identity axiom} \tag{1}
\end{align}
$$
As $f \circ h = g \circ h$, it is then immediate by the universal mapping property that there is some (unique) $t:X \to E$ such that $e \circ t = h$. By definition of $h$ then $e \circ t = 1_X$. As required.


Consistent Install Disk Selection in RHEL Kickstart

Question: In my kickstart installation I specify that the operating system should be installed on /dev/sda.
We have some Dell machines in our environment with iDRAC. When virtual media is attached in iDRAC, it maps Virtual CD drives and Virtual Floppy drives as /dev/sda and /dev/sdb leaving my desired installation drive as /dev/sdc. This causes my kickstart installation to fail due to it not being able to find the drive (/dev/sda) I had specified earlier.
Is there any way to specify in kickstart (anaconda) to install on the first "non-removable media", or to keep trying until it finds such device?
Bonus Points: If anyone has a more ideal method of specifying a drive installation destination.
Answer: I've never had this issue... but then again, I don't specify the block device in my kickstarts (which I run with Dell DRAC and HP ILO management).
Have you tried not specifying /dev/sda? I'm assuming you have a RAID controller, so the resulting VD will be the likely install target, no?
If there are other VD's that you wish to ignore, use the --ignoredisk kickstart option. You can also specify /dev/disk-by-id as targets, but that's more complicated.
# The following is the partition information you requested
# Note that any partitions you deleted are not expressed
# here so unless you clear all partitions first, this is
# not guaranteed to work
clearpart --all --initlabel
part /boot --fstype ext4 --size=500
part /usr --fstype ext4 --size=16384 --asprimary
part / --fstype ext4 --size=20480 --asprimary
part /var --fstype ext4 --size=8192
part swap --size=16384
part /tmp --fstype ext4 --size=6144

Edit: From the Red Hat kickstart guide:
Comment: @mr.zog There are multiple ways to specify a disk. Look in `/dev/disk/by-id` or `/dev/disk/by-path`.
Comment: How would you go about filtering in /dev/disk/by-id ? I think not specifying will work for my scenario. Just curious as to what the filtering criteria would be or how you would perform it reliably.
Comment: @rainereality See my edit above.
Comment: Thanks! For some reason I didn't even expect that /dev/disk/by-id option was included in kickstart and thought that it would be a %post script that you would have to write.
Comment: What is Red Hat talking about? I have no idea what "you can instead use any item from /dev/disk" means.


Ansible: how to manage hosts if they are not always online?

Question: My apologies if this question has been asked before, but I may not be using the correct terminology in my searches...
In my spare time I'm managing a limited amount of hosts (desktops and laptops running Debian Stretch) with Ansible. My 'installer playbook' creates a single configuration on all those hosts with different hardware to make management much easier. I'm now manually running an updater role from time to time and every once in a while I find a useful tweak that I then deploy to those hosts that are online. But: some of them rarely come to the office, and if they are available for an update, it's always a hassle to determine which tweaks I still have to deploy on that machine...
Sure, I can:

write an epoch timestamp ({{ ansible_date_time.epoch }}) to a file on each host that can be retrieved and set as a fact
create a new task for each new tweak, adding a tag with the epoch timestamp and a conditional to check whether the epoch-fact > epoch-tag
update the epoch timestamp on the host after a successful playbook run

Is this how it should be done?
Answer:
if they are available for an update, it's always a hassle to determine which tweaks I still have to deploy on that machine...

That is not the way to use Ansible. Your playbooks should be written in a way that it doesn't matter if you have applied a configuration set before ("idempotence"). If they are, you just can apply the latest version of the playbook and your systems should end up in the correct state.
Comment: Hi, thank you for your answer. I know the concept, and I believe my tasks are idempotent, but if I have to run the entire playbook each time, it doesn't strike me as efficient... If this is the correct way to do it in Ansible, then ok.
Comment: In daily operations, I often use the different selectors (tags, hosts etc.) Ansible offers, but for machines I don't see regularly, I would just apply the full playbook.
Answer: This might be a good use-case for ansible-pull. Hosts which are not permanent online could be configured to run ansible-pull when connected to the office network.
However that doesn't change the need to create idempotent playbook and roles. If the running time of a playbook is a issue there is the option to use stat module to set conditions to skip longer running tasks.
Selectors are a option here, but those require manual management. So it might be better to speed up the execution time of playbook itself.


Sufficient statistics for $\mu_1 - \mu_2$

Question: If $ X_1, ..., X_n$ is a random sample from $ X \sim N(\mu_1, \sigma^2)$ and $Y_1,..., Y_n$ is a random sample from $Y \sim N(\mu_2, \sigma^2),$ if the samples are independent and $ \sigma^2$ is known, can we say that $\bar{X}-\bar{Y}$ is sufficient for $\mu_1 - \mu_2$ ?
My guess is that it is true. I thought we could define
$$W_i=X_i-Y_i \sim N(\mu_1 - \mu_2, 2 \sigma^2)$$
n independent random variables and use it to show that $\bar{W} = \bar{X} - \bar{Y} $ is sufficient to the mean. Is that correct?
Thanks
Comment: Consider the case when $X_1,\ldots,X_n$ and $Y_1,\ldots,Y_{2n}$ are your samples... Then what would a sufficient statistic be? There is no rationale in associating $X_i$ with $Y_i$ since the samples are independent.
Comment: It's not clear at all to me what it means for a statistic to be "sufficient for" a particular parameter. See my answer [here](http://stats.stackexchange.com/questions/76743/sufficient-statistic-for-function-of-parameter/76756#76756). However, it also seems in the definition proposed here that this definition may depend on the parameterization.
Comment: Indeed, the statistic is sufficient when based on the difference sample. But there is no argument for reducing the data to the difference sample.
Comment: [We can show](http://mathworld.wolfram.com/NormalDifferenceDistribution.html) how the pdf of the difference distribution looks like. Afterwards, use the factorization theorem to prove the sufficiency.
Comment: @Xi'an That is true. I should have been more careful there.
Answer: Recall that a statistic $T(x)$ is sufficient if the conditional distribution $P_\theta(x|T(x))$ does not depend on $\theta$. In addition, a distribution belongs to the curved exponential family if it can be written as $L(x;\theta)=h(x)\exp\left(c(\theta)^TT(x)-A(c(\theta))\right)$, then $T(x)$ is a sufficient statistic according to the Fisher-Neyman factorization theorem.
Considering the parameter vector $\theta=(\mu_1,\mu_2)$, the likelihood for $X_1,...,X_n,Y_1,...,Y_m$ can be written as:
$$\begin{aligned}
L(X,Y;\theta)=(2\pi\sigma^2)^{0.5n}\exp\left(-0.5\sum((X_i-\mu_1)/\sigma)^2\right)\cdot (2\pi\sigma^2)^{0.5m}\exp\left(-0.5\sum((Y_i-\mu_2)/\sigma)^2\right)
\\=(2\pi\sigma^2)^{0.5(n+m)}\exp\left( -\frac{1}{2\sigma^2}\sum(X_i^2-2\mu_1X_i+\mu_1^2+Y_i^2-2\mu_2Y_i+\mu_2^2) \right)
\\=(2\pi\sigma^2)^{0.5(n+m)}\exp\left( -\frac{1}{2\sigma^2}\left(\sum(X_i^2+Y_i^2)-2\mu_1\sum X_i-2\mu_2\sum Y_i+n\mu_1^2+m\mu_2^2 \right)\right)\\=(2\pi\sigma^2)^{0.5(n+m)}\exp\left( -\frac{1}{2\sigma^2}\sum(X_i^2+Y_i^2)+\frac{1}{\sigma^2}(\mu_1\sum X_i+\mu_2\sum Y_i)-\frac{1}{2\sigma^2}(n\mu_1^2+m\mu_2^2) \right)
\end{aligned}$$
Let $$h(x,y)=(2\pi\sigma^2)^{0.5(n+m)}\exp\left( -\frac{1}{2\sigma^2}(\sum(X_i^2+Y_i^2)\right),\quad c(\theta)=\frac{1}{\sigma^2}\begin{pmatrix}\mu_1\\\mu_2\end{pmatrix},\quad A(z)=\sigma^2(nz_1^2+mz_2^2)$$
we get that the likelihood can be written as
$$L(X,Y;\theta)=h(x,y)\cdot\exp\left(c(\theta)^T\begin{pmatrix}\sum X\\\sum Y\end{pmatrix} -A(c(\theta)) \right)$$
Hence the statistic $T(X,Y)=\begin{pmatrix}\sum X\\\sum Y\end{pmatrix}$ is sufficient. The function $f(a)=\begin{pmatrix}a_1/n\\a_2/m\end{pmatrix}$ is one-to-one and so $\begin{pmatrix}\bar X\\\bar Y\end{pmatrix}$ is also a sufficient statistic. But this doesn't help us for $\mu_1-\mu_2$ so let's try another parametrization:
$$h(x,y)=(2\pi\sigma^2)^{0.5(n+m)}\exp\left( -\frac{1}{2\sigma^2}(\sum(X_i^2+Y_i^2)\right),\quad c'(\theta)=\frac{1}{\sigma^2}\begin{pmatrix}\mu_1-\mu_2\\\mu_2\end{pmatrix},\quad A'(z)=\sigma^2(nz_1^2+mz_2^2-nz_2(2z_1+z_2))$$
and our likelihood is now
$$L(X,Y;\theta)=h(x,y)\cdot\exp\left(c'(\theta)^T\begin{pmatrix}\sum X-\sum Y\\2\sum Y\end{pmatrix} -A'(c(\theta)) \right)$$
Finally the sufficient statistic for $\mu_1-\mu_2$ is $\begin{pmatrix}\sum X-\sum Y\\2\sum Y\end{pmatrix}$ or its transformation $\begin{pmatrix}\bar X-\bar Y\\\bar Y\end{pmatrix}$.


Postgres tsvector with relational tables

Question: I have two simple tables. First is brands and each brand may have a top brand. For example Elseve has a top brand which is Loreal Paris. But Avon has no top brand. And I have a simple products table.
Here is sqlfiddle
Here is brands table.
<code> id |     name     | parent_id | depth
----+--------------+-----------+-------
  3 | Loreal Paris |     null  |     0
  1 | Avon         |     null  |     1
  2 | Elseve       |      3    |     1
(3 rows)
</code>
And  here is products table
<code> id | brand_id |   name
----+----------+-----------
  1 |        1 | Product 1
  2 |        2 | Product 2
(2 rows)
</code>
When I try to get tsvectors, Product 1 document returns null result. But I need to get at least Avon in the document.
<code> product_id | product_name |                     document
------------+--------------+--------------------------------------------------
          1 | Product 1    |
          2 | Product 2    | '2':2 'elsev':3 'loreal':4 'paris':5 'product':1
(2 rows)
</code>
How to solve this problem ?
Thanks to Voa Tsun. I updated query a little bit. I don't need grouping anymore.
<code>select
  products.id as product_id,
  products.name as product_name,
  to_tsvector(products.name) ||
  to_tsvector(brands.name) ||
  to_tsvector(top_brands.name)
    as document
from products
  JOIN brands on brands.id = products.brand_id
  LEFT JOIN brands as top_brands on coalesce(brands.parent_id,brands.id) = top_brands.id;
</code>
Comment: You'll need to use `coalesce()` somewhere, because `to_tsvector()` returns `NULL` on `NULL` input. See f.ex. [how the documentation use multiple columns](https://www.postgresql.org/docs/current/static/textsearch-controls.html).
Comment: http://rextester.com/SQVSTS56141 like here?..
Comment: Hi @pozs . I already used it. Like this to_tsvector(coalesce(string_agg(top_brands.name, ' '))). I know it is not logical. because there is no top_brand record for Avon. So it is useless. if I add top_brand for all brands, and empty top_brand name record for brands which has no top_brand, it will work.
Comment: @OğuzCanSertel you need to use everywhere, where `NULL` is a possibility. Note that your column may be `NOT NULL`, but if you use `LEFT JOIN`, the result set still *can have* `NULL`s. -- NVM I see what you misunderstood (or is this just a typo?): `coalesce()` with only 1 parameter does not do anything effective. You'll need to call with f.ex. `coalesce(..., '')`
Answer: The basic idea is to join id not against null in "parent_id", but "at least against id", as I got from your post.
like here:
<code>   select
      products.id as product_id,
      products.name as product_name,
      to_tsvector(coalesce(products.name,brands.name)) ||
      to_tsvector(brands.name) ||
      to_tsvector(coalesce(string_agg(top_brands.name, ' ')))
        as document
    from products
      JOIN brands on brands.id = products.brand_id
      LEFT JOIN brands as top_brands on coalesce(brands.parent_id,brands.id) =
     top_brands.id
    GROUP BY products.id,brands.id;

    product_id  product_name    document
1   1   Product 1   '1':2'avon':3,4'product':1
2   2   Product 2   '2':2'elsev':3'loreal':4'pari':5'product':1
</code>


Translations of Darboux's "Leçons Sur La Théorie Générale Des Surfaces"

Question: This might be slightly stretching the boundary of acceptable questions, but I think this is the best group to ask.
I'm interested in the classic 1887 texts "Leçons Sur La Théorie Générale Des Surfaces Et Les Applications Géométriques Du Calcul Infinitésimal" by French mathematician Jean Gaston Darboux (and which can be read online in very high quality scans thanks to the University of California here). They were very influential in their time in establishing the fledgling field of differential geometry, and introduced many of its fundamental tools (such as, not surprisingly, the Darboux frame).
My question is, has this work ever been translated into English? I can find many editions of the original French version, but I have been unsuccessful in finding any of the four volumes in English. I've checked the usual suspects (Dover, etc.) and my University's catalogue, but nothing comes up for the straightforward translation of the title (Lessons on the General Theory of Surfaces and the Geometric Applications of Infinitesmal Calculus) or the author's name. Was it retitled, perhaps, in translation?
Secondly, and on a very related note, does anybody know for certain the copyright status of the original work (not any particular subsequent editions)? If this was published in America, I would expect the copyright to expire 70 years after Darboux's death in 1917, but perhaps things work differently in France. The UC site I linked above lists  "Possible copyright status: NOT_IN_COPYRIGHT" but that doesn't sound very reassuring to me. If somebody were to attempt a translation today, would they run into any legal restrictions, or is it essentially in the public domain by now?
Comment: The book is so beautifully written... It'd be a real challenge to translate it and not break that!
Comment: French copyright laws also have the 70 years clause but the matters are a bit more complicated than that (after all, we're speaking of the French bureaucracy here) because some years don't count (due to WW I/II). The original editor no longer exists and there are plenty of new editions of reprints from publishers I never heard of (see amazon, for example). This strongly suggests (to me) that the copyright no longer applies. I couldn't find any evidence that there already is an English translation.
Comment: I remember a similar discussion about the EGAs by Grothendieck. I know that in the end people just started translating the work without worrying much about copyright and that for two good reasons. The first one is that pure mathematics cannot be patented, so copyright laws only apply if you tried to sell the translated work, if you make it available to the public for free, not much can be said. The second reason is that this kind of work should be public and free anyway. So my suggestion in the end would be: start a wiki to translate the document and let the community participate!
Comment: @David Kohler: Thanks very much for your comment; beginning a (possibly crowdsourced) translation effort is exactly what I had in mind, as I hinted not-so-subtly.

Unfortunately, I don't think the copyright situation is quite as simple as you suggest. "copyright laws only apply if you tried to sell the translated work" sounds very suspicious to me. If I "translated" Harry Potter into another language I'm fairly certain I wouldn't be allowed to post it online even for free. But thanks for the encouraging words :) (Plus, I don't see why someone like Dover shouldn't publish it if it was done)
Comment: I'm letting my romantic ideas of pure mathematics protected from copyright law dominate my answer there :) I can understand how work of fiction should be protected, mathematics on the other hand as being a collaborative effort to raise human collective knowledge should be free of copyright in my opinion. After some research I ended up at the same conclusion than @Theo and would start a collective effort protected by some Creative Commons license to avoid nasty people like Dover or Springer. By the way I speak French as well, so I'd be happy to help, keep in touch!
Comment: According to copyright laws, copyright is valid only for 120 years Max. So no problem in translation and it would be a boon for students.
Answer: I don't claim to be an expert in french, but I would be happy to help with translations from french into english. Sometimes, putting words into software like google translate will not be enough. For example, look at this sentence:
Soit $E = (C[0, 1], \mathbf{\mathbb{R}})$ le $\mathbf{\mathbb{R}}$-espace vectoriel des applications continues de $[0, 1]$ vers $\mathbf{\mathbb{R}}$, muni de
la norme $N_\infty$.
It is not hard to translate such as sentence. However, words like "soit" which is the verb "to be" in the third person singular of the subjunctive may mean something else for a translator, where as here it means "given" or "let".
I'd be happy to help you translate specific sentences, but not a whole text!
Ben
Comment: Hey, it looks like I am getting this party started. I've set up a project over at https://github.com/apetresc/Lecons-Sur-La-Theorie-Generale-Des-Surfaces. Can you read through the README and let me know if you'd be interested in volunteering as a Language Reviewer? I'd much appreciate it :) Thanks!
Comment: Thanks David :) I appreciate the offer, and I'll keep in touch with you if I go ahead with this, although my French is pretty strong as well. However, at the moment I'm just trying to determine if a) this has already been done, and b) if there are legal barriers to me doing it.
Comment: Not to be too picky... but (that's the standard introduction to gereat displays if pickiness!) *soit* is in the imperative :)
Comment: @Adrian Petrescu Yeah I'd be willing to help :D
Comment: @D Lim: Great! Please e-mail me at email@example.com so we can coordinate further :)


How to check if array has nested property with defined value

Question: I have an array of complicated objects and arrays in javascript such as:
var array = [
    { "simpleProp": "some value" },
    { "booleanProp": false },
    {
        "arrayProp": [
            { "prop1": "value1" },
            {
                "prop2": {
                    "prop22": "value22",
                    "prop23": "value23"
                }
            },
            { "prop3": "value3" },
            { "booleanProp": true }
        ]
    }
];

I have to know if there is a property with defined value in my array, such as:
   function some(array, property, value) {
        //some logic here
       // return boolean
    };

That is, for my source array the result of this:
var result = some(array, "booleanProp", true)
  - must be TRUE.
I tried to use lodash function _.some(), but it returns false for my array, it appears _.some() can't find deeply nested properties.
It would be very cool if the function may support complicated object as source, not only array.
I'd appreciate any help, thanks.
Comment: I didn't get you.Can you clarify please?
Comment: Debabrata, I want to know if source array has defined property (key/value-pair) like lodash _.some()-function does, but for nested property as I showed before
Answer: You could use an iterative and recursive approach by checking the actual object and if the value is an object iterate the object's keys.

function some(object, property, value) {
    return object[property] === value || Object.keys(object).some(function (k) {
         return object[k] && typeof object[k] === 'object' && some(object[k], property, value);
    });
}

var data = [{ simpleProp: "some value" }, { booleanProp: false }, { arrayProp: [{ prop1: "value1" }, { prop2: { prop22: "value22", prop23: "value23" } }, { prop3: "value3" }, { booleanProp: true }] }];

console.log(some(data, 'booleanProp', true)); // true
console.log(some(data, 'foo', 42));           // false
Comment: Nina Scholz, it works! Thank you very much! I'm sorry that I can't vote your answer (insufficient reputation)
Answer: Above Solution is great but it is not working for Array.
So I've Modified it little bit and now it is working for both Arrays & normal properties. Even In Arrays element's placement can be anything.
const data = {
    "names": [
      {
        "name": {
          'homename': 'Raju',
          'academisName': 'Rajpal',
          'callingName': ['Raj', 'Rajpal', 'Raju']
        },
        "defaultName": "Raj"
      }]
  }

Code for Array:
const some = (object, property, value) => {
  return _.isArray(value) && _.isEqual(_.sortBy(object[property]), _.sortBy(value)) || object[property] === value || Object.keys(object).some(function (k) {
    return object[k] && typeof object[k] === 'object' && some(object[k], property, value);
  });
}

const data = {
  "names": [{
    "name": {
      'homename': 'Raju',
      'academisName': 'Rajpal',
      'callingName': ['Raj', 'Rajpal', 'Raju']
    },
    "defaultName": "Raj"
  }]
}
const some = (object, property, value) => {
  return _.isArray(value) && _.isEqual(_.sortBy(object[property]), _.sortBy(value)) || object[property] === value || Object.keys(object).some(function(k) {
    return object[k] && typeof object[k] === 'object' && some(object[k], property, value);
  });
}
console.log('Result 1', some(data, 'callingName', ["Raj", "Rajpal", "Raju"]));
console.log('Result 2', some(data, 'callingName', ["Rajpal", "Raj", "Raju"]));

Note: that value.sort() will mutate the arrays so I've used  _.sortBy(value), same for object[property]
 console.log(some(data, 'callingName',  ["Raj", "Rajpal", "Raju"]));
 console.log(some(data, 'callingName', ["Rajpal", "Raj", "Raju"]));


How to change Date format without diving to core?

Question: I want to convert dates to Jalali format. The problem is I have to change some of the core files in /includes and /modules. Is it possible to do this without jumping right into the core?
Answer: I think your best bet is Calendar_Systems module that will not do the core changes but everything else needed on the frontend.
Comment: Thanks but it's in development for D7.
Answer: You could set the default timezone for your site at
/admin/config/regional/settings
This will change the output of all dates on your site. You shouldn't have to edit any core files to set your sites timezone.


close child after sigin and reload parent with signin data

Question: Right now i m using window.open() when a user click and a popwindow display login form.
for this i used":

a child.php page displaying in popup, but the problem is that, when i login and page redirect to the parent page and reload, its still showing no user is login.
I used these on child page

and

Is it possible with this to reload parent page with login detail.
Comment: Please check this: http://stackoverflow.com/questions/18321323/submit-form-reload-parent-and-close-child/36855748#36855748 might help someone
Answer: You have to set your login detail in a session variable in child page. Which you can check in the parent page.


Converting lists from csv file to numpy array_csv format

Question: This piece reads a csv file, creates a list and converts the list to a numpy.array:
with open ('infile.csv', 'r') as infile:
    reader = csv.reader(infile)
    reader_list = list(reader)
    reader_array = array(reader_list)

This 2d array shape is:
print reader_array.shape
(2938, 6)

When some other data is added to the csv file (say another 2000 rows by 6 columns) array becomes 1d, probably because of uneven shape. But if I open this csv file, press ctrl+s and accept the Excel incompatible format warning to save the csv, and run the code again it works!
print reader_array.shape
(2938, 12)

I understand that opening and quick saving the csv file changes its format because the file size gets smaller than the original, but cannot figure out how do they differ. The code that creates this csv file is like:
with open ('outfile2.csv', 'wb') as outfile:
    writer = csv.writer(outfile)
    .
    .
    .
    data = loadtxt(fname_...)
    .
    .
    .
    list_.append(sublist_)

for row in izip_longest(*averages_, fillvalue = ['']):
    writer.writerow(list(chain.from_iterable(row)))

output written to csv file is like this:
['1689.000000', '0.000954', '0.007900', '0.017542', '0.057176', 94.164925128317591, '1689.000000', '0.001107', '0.007444', '0.018361', '0.059156', 94.151092414521969]
['1690.000000', '0.001025', '0.007925', '0.018905', '0.060608', 94.165950129377109, '1690.000000', '0.001316', '0.007463', '0.017517', '0.058879', 94.152408118013895]
['1691.000000', '0.001124', '0.008067', '0.017934', '0.058068', 94.167074126395363, '1691.000000', '0.001226', '0.007473', '0.016914', '0.057320', 94.153634253740464]

can someone please explain what happens here? Can I change the format of csv when it's being written such that it works?
Even csv.writer(outfile, dialect='excel') didn't help.
Answer: I am not sure but maybe you can try read binary:
with open ('infile.csv', 'rb') as infile:

Because I know there is some difference dealing with linebreaking between 'r' and 'rb', saving the file in Excel might change some representation of linebreaking.
Also, maybe you can share a sample version of you input file to illustrate.
Comment: Thanks but didn't make any change :(
Comment: @PyLearner Do you mind putting your code somewhere like [pastebin](http://http://pastebin.com) so that I can try something?
Comment: had not heard of it before! :) here's the like [http://pastebin.com/YvFp0RKL]. I think you should paste it to your address bar.
Comment: btw, please see input files in my other q here: http://stackoverflow.com/questions/20339934/python-how-to-write-data-in-new-columns-for-every-file-read-by-numpy
Comment: @PyLearner I am not sure whether I get what you mean. Is this intuitive way of output you want? `for row in averages_:
        for r in row:
            writer.writerow(r)`
Comment: well, the list averages_ contains several lists of lists and the method you suggested was the one I tried firstly but doesn't give the result I want. please see http://stackoverflow.com/questions/20368047/write-several-list-of-lists-in-a-csv-columns-in-python
Comment: @PyLearner So you want every row of the output csv preserves one row of output as one list in `averages_`? Right now your output is like this `['1689.000000', '0.000954', '0.007900', '0.017542', '0.057176', 94.164925128317591, '1689.000000', '0.001107', '0.007444', '0.018361', '0.059156', 94.151092414521969]` in the file? What I know for `csv.writer` is that it requires every cell in the csv to be a `list`.
Comment: In the file each number is printed in a separate cell. With the same code, when there's only 1 input text file, or text files have equal number of rows it works fine. That's why I suspect output csv file could be written in an alternative format.


Which are the file_save_upload() validators?

Question: In the file_save_upload() function, what keys can $validators take? I cannot find answers anywhere.
Answer: You can see the validators in core at the end of this listing:
http://api.drupal.org/api/drupal/includes%21file.inc/group/file/7
the ones starting with file_validate_
Also there's an example of the array structure here: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_validate_picture/7


The weighted sum of two independent Poisson random variables

Question: Using wikipedia I found a way to calculate the probability mass function resulting from the sum of two Poisson random variables. However, I think that the approach I have is wrong.
Let $X_1, X_2$ be two independent Poisson random variables with mean $\lambda_1, \lambda_2$, and $S_2 =  a_1 X_1+a_2 X_2$, where the $a_1$ and $a_2$ are constants, then the probability-generating function of $S_2$ is given by
$$
G_{S_2}(z) = \operatorname{E}(z^{S_2})= \operatorname{E}(z^{a_1 X_1+a_2 X_2}) G_{X_1}(z^{a_1})G_{X_2}(z^{a_2}).
$$
Now, using the fact that the probability-generating function for a Poisson random variable is $G_{X_i}(z) = \textrm{e}^{\lambda_i(z - 1)}$, we can write the probability-generating function of the sum of the two independent Poisson random variables as
$$
\begin{aligned}
G_{S_2}(z) &= \textrm{e}^{\lambda_1(z^{a_1} - 1)}\textrm{e}^{\lambda_2(z^{a_2} - 1)}  \\
&= \textrm{e}^{\lambda_1(z^{a_1} - 1)+\lambda_2(z^{a_2} - 1)}.
\end{aligned}
$$
It seems that the probability mass function of $S_2$ is recovered by taking derivatives of $G_{S_2}(z)$ $\operatorname{Pr}(S_2 = k) = \frac{G_{S_2}^{(k)}(0)}{k!}$, where $G_{S_2}^{(k)} = \frac{d^k G_{S_2}(z)}{ d z^k}$.
Is this is correct? I have the feeling I cannot just take the derivative to obtain the probability mass function, because of the constants $a_1$ and $a_2$. Is this right? Is there an alternative approach?
If this is correct can I now obtain an approximation of the cumulative distribution by truncating the infinite sum over all k?
Comment: The difficulty here is that unless both $a_1$ and $a_2$ are integers, one cannot be sure that $S_2$ takes on integer values only. Thus, you need to find not just $P(S_2 = k)$ for integer values of $k$ but also $P(S_2 = \alpha)$ for each $\alpha$ that can be expressed as $a_1m + a_2n$ for nonnegative integers $m$ and $n$.
Comment: Some *particular* kinds of combinations have names (e.g. [the Skellam distribution](http://en.wikipedia.org/wiki/Skellam_distribution)), but the general case its just compound Poisson, I think. There will be no closed form expression that's simpler than the original sum in general, though I suppose you can just write it as a convolution. When you say 'generate' do you mean 'simulate random values from', or something else?
Comment: Why are you scaling the summands with $a_1$ and $a_2$? The sum is just another Poisson distribution without this. The variables take values in the positive integers, so something like $1$ times the first plus $\sqrt{2}$ times the second is usually quite unnatural, and would let you recover the values of both variables.
Comment: I don't think you can do much better than a brute-force approach which finds the possible values that $S_2$ can take on and then for each $\alpha$, use $$P\{S_2 = \alpha\} = \sum_{a_1m + a_2n = \alpha}P\{X_1=m\}P\{X_2=n\} = \sum_{a_1m + a_2n = \alpha} \exp(-\lambda_1m)\frac{\lambda_1^m}{m!}\exp(-\lambda_2n)\frac{\lambda_2^n}{n!}.$$ For most choices of $a_1$ and $a_2$, I would expect that most sums will reduce to a single term. I expect you know that for $a_1=a_2=1$, $S_2$ is a Poisson random variable with parameter $\lambda_1+\lambda_2$.
Comment: A closely related special case--that of the average of Poisson variates, binned by integers--is treated at http://stats.stackexchange.com/questions/35042/what-is-the-distribution-of-an-average-of-poisson-random-variables.
Comment: @DilipSarwate Is that possible? Is there an other approach to do this?
Comment: @DouglasZare I have to do this... Maybe I have to turn to some kind of bootstrapping method.
Comment: Provided $\lambda_i$ are not terribly small, continuous approximations to this linear combination ought to work well for computing the CDF (such as a Cornish-Fisher expansion).  What can you tell us about the possible values of the $\lambda_i$ and $a_i$?
Comment: You can't provide more context than that you "have to do this?" Is it homework, possibly miscopied?
Comment: @DouglasZare Yes, I don't like to end up doing monte carlo simulations (bootstrapping), so I would really like to obtain at least an approximation.
Answer: Provided not a whole lot of probability is concentrated on any single value in this linear combination, it looks like a Cornish-Fisher expansion may provide good approximations to the (inverse) CDF.
Recall that this expansion adjusts the inverse CDF of the standard Normal distribution using the first few cumulants of $S_2$.  Its skewness $\beta_1$ is
$$\frac{a_1^3 \lambda_1 + a_2^3 \lambda_2}{\left(\sqrt{a_1^2 \lambda_1 + a_2^2 \lambda_2}\right)^3}$$
and its kurtosis $\beta_2$ is
$$\frac{a_1^4 \lambda_1 + 3a_1^4 \lambda_1^2 + a_2^4 \lambda_2 + 6 a_1^2 a_2^2 \lambda_1 \lambda_2 + 3 a_2^4 \lambda_2^2}{\left(a_1^2 \lambda_1 + a_2^2 \lambda_2\right)^2}.$$
To find the $\alpha$ percentile of the standardized version of $S_2$, compute
$$w_\alpha = z +\frac{1}{6} \beta _1 \left(z^2-1\right) +\frac{1}{24} \left(\beta _2-3\right) \left(z^2-3\right) z-\frac{1}{36} \beta _1^2 z \left(2 z^2-5 z\right)-\frac{1}{24} \left(\beta _2-3\right) \beta _1 \left(z^4-5 z^2+2\right)$$
where $z$ is the $\alpha$ percentile of the standard Normal distribution.  The percentile of $S_2$ thereby is
$$a_1 \lambda_1 + a_2 \lambda_2 + w_\alpha \sqrt{a_1^2 \lambda_1 + a_2^2 \lambda_2}.$$
Numerical experiments suggest this is a good approximation once both $\lambda_1$ and $\lambda_2$ exceed $5$ or so.  For example, consider the case $\lambda_1 = 5,$ $\lambda_2=5\pi/2,$ $a_1=\pi,$ and $a_2=-2$ (arranged to give a zero mean for convenience):

The blue shaded portion is the numerically computed CDF of $S_2$ while the solid red underneath is the Cornish-Fisher approximation.  The approximation is essentially a smooth of the actual distribution, showing only small systematic departures.
Comment: Nice use of an often-forgotten tool... and, of course, for either of $\lambda_1$ or $\lambda_2 \leq 5$ or so, the brute force convolution method won't be all that painful.
Answer: Use the convolution:
Let $f_{X_1}(x_1)= \dfrac{\lambda^{x_1}e^{-\lambda}}{x_1!} $ for $x_1 \geq 0$,  $f_{X_1}(x_1)= 0$ otherwise, and
$f_{X_2}(x_2)=\dfrac{\lambda^{x_2}e^{-\lambda}}{x_2!} $ for $x_2 \geq 0$,  $f_{X_2}(x_2)= 0$ otherwise.
Let $Z=X_1+X_2\rightarrow X_1=Z-X_2$, so $$f_Z(z)=\int\limits_{-\infty}^{\infty}\int\limits_{-\infty}^{\infty}f_{x_1,x_2}(z-x_2,x_2)dx_1dx_2$$
The former is known as convolution.
If $X_1$ and $X_2$ are independent,
$$f_Z(z)=\int\limits_{-\infty}^{\infty}\int\limits_{-\infty}^{\infty}f_{X_1}(z-x_2)f_{X_2}(x_2)dx_1dx_2$$
This way you can obtain the distribution of the sum of two continuous random variables.
For the discrete poisson distribution
$$f_Z(z)=\sum\limits_{x_2=0}^{z} \dfrac{\lambda^{z-x_{2}}_1e^{-\lambda_1}}{(z-x_2)!}\dfrac{\lambda^{x_2}_2e^{-\lambda_2}}{x_2!}$$
$$= e^{-(\lambda_1+\lambda_2)}\dfrac{(\lambda_1+\lambda_2)^z}{z!}$$
Which is also a Poisson distribution with parameter $\lambda_1+\lambda_2$
Comment: This appears to answer a different question: namely, how to add two Poisson distributions.  It is the special case $a_1=a_2=1$ (but can be extended to the cases $a_1 = a_2$ without any trouble). But what would you do when $a_1 \ne a_2$?
Answer: I think the solution is the concept of a compound Poisson distribution. The idea is a random sum
$$
S = \sum_{i=1}^N X_i
$$
with $N$ Poisson distributed and $X_i$ and $iid$ sequence independent of $N$. When we restric to the case that $X_i=k$ always, then we can describe $k N$ for a real number $k$ and a Poisson distributed $N$. You get the pgf by
$$
E[s^{k N}] = E[(s^{k})^N] = G_N(s^{k}) = \exp(\lambda(s^k-1))
$$
For the sum $Z = k_1 N_1 + k_2 N_2$ you get
$$
G_Z(s) = \exp(\lambda_1(s^{k_1}-1) + \lambda_2(s^{k_2}-1)).
$$
define $\lambda = \lambda_1 + \lambda_2$ then
$$
G_Z(s) = \exp(\lambda ( \frac{\lambda_1}{\lambda}(s^{k_1}-1)+ \frac{\lambda_2}{\lambda}(s^{k_1}-1)) = \exp(\lambda (\frac{\lambda_1}{\lambda}s^{k_1}+ \frac{\lambda_2}{\lambda}s^{k_1}-1)).
$$
The final interpretation is that the resulting rv is a compound Poisson distribution with intensity $\lambda = \lambda_1 + \lambda_2$ and distribution of the $X_i$ that take the value $k_1$ with probability $\lambda_1/\lambda$ and the value $k_2$ with $\lambda_2/\lambda$.
Having proved that the distributions is compound Poisson we can either use Panjer recursion in the case that $k_1$ and $k_2$ are positive integers. Or we can easily derive the Fourier transform from the form of the pgf and get the distribution back by the inverse. Note that there is a point mass at $0$.
Edit after a discussion:
I think the best you can do is MC. You could use the derivation that this is a compound Poisson distr.

sample N from $Pois(\lambda)$ (very efficient)
then for each $i=1,\ldots,N$ sample whether it is from $X_1$ or $X_2$ where
the probability of the first is $\lambda_1/\lambda$. Do this by sampling  a Bernoulli rv with probability of success $\lambda_1/\lambda$. If it is $1$ then add $k_1$ to the sampled sum else add $k_2$.

You will have a sample of say 100 000 in seconds.
Alternatively you can sample the two summands in your inital representation separately ... this will be as quick.
Everything else (FFT) is complicated if the constant factor k1 and k2 are totally general.
Comment: And the final distribution can be found by the Panjer algorithm if the factors are integers.
Comment: Thanks! I got to $G_{S_2}(z) =  \textrm{e}^{\lambda_1(z^{a_1} - 1)}\textrm{e}^{\lambda_2(z^{a_2} - 1)}$
However, starting from this I would like to find a way to be able to obtain some sort of distribution. You mentioned the Panjer algorithm? However, in this case $a_1,a_2 \in R^1$.
@DilipSarwate Just mentioned that it is impossible to simplify the following
$P\{S_2 = \alpha\} = \sum_{a_1m + a_2n = \alpha}P\{X_1=m\}P\{X_2=n\} = \sum_{a_1m + a_2n = \alpha} \exp(-\lambda_1m)\frac{\lambda_1^m}{m!}\exp(-\lambda_2n)\frac{\lambda_2^n}{n!},$
for generally $a_1,a_2 $.
Comment: Hi Michel, I edited my response. Yes Panjer is of limited use. But you could try a Fourier transform approach. However non-integer units are problematic ... I have to think more about what to do in this case. Either way it is important to note that the result is a compound Poisson distribution (not a "simple" Poisson distribution).
Comment: Hi Richard,
Thanks for your update! Do you mean that I should numerically try to compute:
$Pr(S_2=x) = \frac{1}{2\pi}\int_{\mathbf{R}} e^{-itx}G_{S2}(\mathrm{e}^{it})dt$?
Comment: Something in the way ... If we had a continuous distribution of which we can calculate the characteristic function (as you do), then this leads to a quick and nice result. In our case I need more time to think about it. There should be something easier.
Comment: Ok, I will wait to try to compute this inverse Fourier Transform. Thanks for your help I really appreciate it!
Comment: I thought about it. I think the best you can do is MC. Use the derivation that this is a compound Poisson distr. First: sample $N$ from $Pois(\lambda)$ (very efficient) then for each $i=1,\ldots,N$ sample whether it is from $X_1$ or $X_2$ (the prob of the first is $\lambda_1/\lambda$ .. you can sample a Bernoulli rv for that. If it is $X_1$ then add $k_1$ to the sampled sum else add $k_2$. You will have a sample of say 100 000 in seconds. Everything else (FFT) is complicated if the constant factor $k_1$ and $k_2$ are totally general.
Comment: In fact the distribution is neither discrete nor continuous. The support is given by the linear space $\{a k_1 + b k_2\}$ with $a,b \ge 0$ ... this should be done with MC I guess.
Comment: Hi Richard,

Below I have added the Matlab code I used to generate the distribution numerically. Is this, ok? How would you proceed if you would apply a FFT based method?

%% Parameters

a1 = 0.6;

a2 = 0.2;

lambda1 = 6;

lambda2 = 10;
n=10^6;

%% Random numbers

X1 = poissrnd(lambda1,n,1);

X2 = poissrnd(lambda2,n,1);

S2 = a1*X1+a2*X2;

%% Display
figure(1);
subplot(1,3,1);
hist(X1);
subplot(1,3,2);
hist(X2);
subplot(1,3,3);
hist(S2);
Comment: Hi Michel, I don't have matlab here but I think I can still read it. In short: yes the code looks correct. The easiest thing is 1) generate n (large) samples of $X_1$, then generated n samples of $X_2$ and then you calculate $a_1*X_1 + a_2 X_2$. Forget FFT. MC is just fine. It should produce large samples quickly .. .I can write R Code for it.
Comment: a1 = 0.6
a2 = 0.2
lambda1 = 6
lambda2 = 10
n = 10^8
X1 = rpois(n,lambda1)
X2 = rpois(n,lambda2)
S = a1*X1 + a2*X2

hist(S)a1 = 0.6
a2 = 0.2
lambda1 = 6
lambda2 = 10
n = 10^8
X1 = rpois(n,lambda1)
X2 = rpois(n,lambda2)
S = a1*X1 + a2*X2

hist(S)
Comment: Hi Richard,

The answer is in a comment, so how do I say it is answered? Do you know a good book chapter/tutorial about FFTs and distributions, so I can broaden my knowledge about statistics?
Comment: Hi, I will edit the answer and then you could accept it. Concerning FFT im the context of distributions- mabye this give you a nice intro: http://www.math.ethz.ch/~baltes/ftp/PanjerVsFFTcorrected.pdf


Simple Vim Regular Expression

Question: I am trying to match
^
 ^

But not
^^
 ^

That is, 0 or 1 space followed by exactly one caret. I can't find a way to translate that regex in vim... I currently have / \=\^$ but it matches ^^^ (the last caret).
Answer: /^\s\=\^\^\@!

This is rather confusing because of all the ^ symbols. What you are missing is a negative look-ahead, \@!.
For more information see:
:h /\@!

Comment: You do not need to use parenthesis for look-ahead or look-behind. `\^\@!` and `\%(\^\)\@!` have just the same meaning (not `\^\@!` and `\(\^\)\@!`: here you use capturing parenthesis I assume you don't need).
Comment: @zyX, I have updated the regex accordingly. Thank you.
Answer: ^\s\?\^$

It seems to work to me.

Simple Vim Regular Expression


How to limit interaction terms in logistic regression in R

Question: I am running a logistic regression model with 5 predictor variables. I would like to include an interaction term in this model. However, when I use the formula:
glm(Indroad~A+B+C+D+E + (A*B*C*D*), family=binomial(link="logit"), data=sub.data)

or the formula:
glm(Indroad ~ A*B*C*D*E, family=binomial(link="logit"), data=sub.data)

I am given an output that includes all possible combinations for the interaction term (e.g., A:B, A:C). I am really only interested in the terms A:B:C and A:B:C:D:E.
Is there anyway to limit the interactions that R runs? I have tried without success to use the update command, and have tried to run the same formula with - unwanted interaction terms (both without success).
Comment: Welcome to Cross Validated! See `?formula` & https://stats.stackexchange.com/q/133959/17230.
Comment: Why not just create two separate variables that are equal to the interactions you want, and use those?
Comment: I agree with what @Scortchi points you to in the link to [this question](https://stats.stackexchange.com/q/133959/28500). Please consider whether you should be looking at these high-order interactions without considering the lower-order interactions. That's an important statistical (as opposed to coding) issue.
Answer: (This is mostly a question about how to use R, and thus off topic here.)
In R, if you use * in a formula, it will automatically insert all interaction terms and main effect terms below the interaction you specify.  To specify a only specific interaction term, you need to use : (see here).  That is,
glm(Indroad~A+B+C+D+E + A:B:C + A:B:C:D:E, family=binomial(link="logit"), data=sub.data)

That said, the statistical issue here is that you almost certainly should not include an interaction term (A:B:C:D:E) without including the lower level terms beneath it in the hierarchy.  For more on this, see Including the interaction but not the main effects in a model (of which this is really a duplicate).


How do I check how many connections are open currently on a specific TCP port?

Question: I'm doing some comet benchmarks and would like to see how many open connections I have.
Actually I use netstat:
netstat -ant | grep 8080 | grep EST | wc -l

But it needs around 4-6 minutes to list the number, is there any tool that can do show it in real time?
The number of open connections is between 100'000 - 250'000.
Comment: Based on what you're trying to accomplish, have you considered using NetFlow and an analyzer tool?
Comment: @SpacemanSpiff I hope there is some easy solution, but I will take a look on NetFlow as I'm not sure if is working with a HP switch.
Comment: You know, I wonder if a perfmon or WMI query might bring this data back from the TCP stack faster... still... are you after open ports or active data transfers?
Comment: @SpacemanSpiff I'm after open ports looking
Comment: Maybe an SNMP query?... just throwing out ideas for you.
Comment: @SpacemanSpiff lsof as proposed by ThorstenS was able to show me the number of open connections in 15 sec for above 130'000 open connections. In a next step I will take more detailed information with the use of a network analyzer, for now I'm happy to know where the limit for 1 node.js on a tuned server is -> 130599 connections for 1 instance which is really well :-)
Answer: Don't know if lsof is better, but give this a try:
lsof -ni:8080 -sTCP:ESTABLISHED | wc -l

Comment: actually lsof take 5 sec, but I have 20'000 connections and counting :-) will let you know how long after pass 100K
Comment: update: have some issues with our comet clients, but lsof is much faster 10 sec for 30'000 connections, will update after I fixed the comet issues and was able to check above 100K connections
Comment: update: 15sec to show 130'000 connections - thank you! This do the job for me for more detailed solution a network analyzer must be used.
Comment: wonderfull! You could also use the switch `-t` - perhaps this will give you also a little boost.
Answer: If you just need to see connecton statistics, try ss utility from iproute suite:
# ss -s
Total: 1788 (kernel 3134)
TCP:   1638 (estab 1409, closed 162, orphaned 0, synrecv 0, timewait 127/0), ports 0

Transport Total     IP        IPv6
*         3134      -         -
RAW       0         0         0
UDP       74        69        5
TCP       1476      1444      32
INET      1550      1513      37
FRAG      0         0         0

You also can view detailed information on all established connections like this:
ss -n state established

…or ssh connections only:
ss -n state established '( dport = :ssh or sport = :ssh )'

Some numbers section at the bottom of this page may also interest you.
Comment: @RobertRSeattle by ss source code it seems that this number is read from `tcp_bind_bucket` line of `/proc/slabinfo` file. You may want to compare output of `awk 'NR==2||/tcp_bind_bucket/' /proc/slabinfo` between two of your servers. Further details can likely be found somewhere in kernel sources.
Comment: +1 for not using the deprecated netstat
Comment: I know this is from 6 years ago, but do you or anyone else have a link to something that breaks down the ss status output. I'm specifically curious about the port count at the end of the TCP line. I'm doing some comparison testing between two servers acting as load balancers and on one the port count hovers around 1000 and on the other it's always 0. What specifically is that counting?
Answer: Another option would be to read /proc/net/tcp directly. To see all established TCP connections on, 8080, you would do something like
$ printf %04X 8080
1F90
$ grep :1F90 /proc/net/tcp | grep ' 01 ' | wc -l

If you want to do it in a single process (less IO overhead) and handle corner cases, the following tells you how many ESTABLISHED TCP connections have local port 8080:
$ perl -anle '
          $F[1] =~ /:1F90/ and $F[3] =~ /01/ and $cnt++;
          END { print 0+$cnt }
         '  /proc/net/tcp

If the software on your machine listening on 8080 has IPv6 support, you'll need to read /proc/net/tcp6 also; if the program's using IPv6 sockets, connections will show up there even if they're using IPv4.
Answer: more easy is
#netstat -at | wc -l

It will display number of TCP connection on system...
Comment: This will take longer since you're not using the "n" flag to stop it from looking up all hostnames. It will also show other things than the port 8080 connections that the question was about.


How to add autocomplate data from a source folder?

Question: This is simply code of jqueryui auto complete.

      Tag programming languages:
      <input id="tags" size="50">

How to add data of autocomplete from a folder?
For example i want to add images name as value of autocomplete from a folder.

      Tag programming languages:
      <input id="tags" size="50">

If i use $getJSON what is the code to get files/images name as array? Is there any way to do like this?
Answer:

Comment: Not working. The output of autocomplete not showing.
Comment: change directory path and check if available_tags contains data first
Comment: I did `var availableTags = [];`  to  `var availableTags = ["",];` but it show me values in same/single line..
Comment: Thank you for your answer but still not working need output `" ",` but your output `' ", '`
Comment: I realised my mistake... have updated the answer... check again for last time :)


$\mathbb{Z}_{6}$ isomorphic to $\mathbb{Z}_{2} \times \mathbb{Z}_{3}$?

Question:
Exhibit an isomorphism of the additive groups $\mathbb{Z}_{6}$ and $\mathbb{Z}_{2} \times \mathbb{Z}_{3}$.

i know $\mathbb{Z}_{6} = \{0,1,2,3,4,5\}$ and $\mathbb{Z}_{2} \times \mathbb{Z}_{3} = \{(0;0),(0;1),(0;2),(1;0),(1;1),(1;2)\}$. But how can I construct an isomorphism of these groups? I need help for this problem. Thank all!
Comment: Can you find an element of order 6 in $\mathbb{Z}/2\times \mathbb{Z}/3$
Comment: Map an element with order $6$ in $\mathbb{Z}_6$ into an element with order $6$ in $\mathbb{Z}_2\times\mathbb{Z}_3$. They both are cyclic groups with order $6$.
Answer: Take $\phi:{\Bbb Z}_6\rightarrow{\Bbb Z}_2\times {\Bbb Z}_3:x\mapsto (x\;{\rm mod}\;2,x\;{\rm mod}\;3)$.
Comment: One direction of the bijection uses Chinese remainder theorem?
Comment: Yes, but this particular case is small enough to do by hand.
Answer: There is a more general result which says:
given $n,m \in \mathbb{N}$ such that $gcd(n,m)=1$ then $\mathbb{Z}_n \times \mathbb{Z}_m \simeq \mathbb{Z}_{nm}$. You can prove this by using the map
$\phi: \mathbb{Z}_{nm} \to \mathbb{Z}_n \times \mathbb{Z}_m$ via
$x \to (x mod n, x mod m)$.
Answer: In general , for each abel group whose order is $p_{1}p_{2}...p_{k}$ here $p_{1},p_{2},...p_{k}$ are $k$ distinct primes . Then $A$ is a cyclic group and
$$A \cong \mathrm{Z}/p_{1}p_{2}...p_{k} \cong \prod_{i=1}^{k} \mathrm{Z}/p_{i}$$
To prove this theorem you have to know following lemma , for each abelian group $A$ and prime $p$ denote $A(p)$ is subgroup which contains all elements of order $p^{t}$ for some $t \in \mathrm{N}$ .
Lemma : Assume $A$ is abelian group of order $p_{1}^{t_{1}}...p_{k}^{t_{k}}$ then :
$$A = \prod_{i=1}^{k}A(p_{i})$$
More , you can verify that order of $A(p_{i})$ is $p_{i}^{t_{i}}$
Now I use this lemma to prove theorem above . The first we have : $A = \prod_{i=1}^{k}A(p_{i})$ , each subgroup $A(p_{i})$ has order $p_{i}$ so it's a cyclic group $\mathrm{=>} \mathrm{Z}/p_{i} \cong A(p_{i})$ . Group $\mathrm{Z}/p_{1}p_{2}...p_{k}$ is also an abelian group whose order is equal with order of $A$ $\mathrm{=>} Q.E.D$
Back to your problem . I think it's a trivial check , nothing more . The proof of lemma above can be easy to find on Internet or if you're familiar with Sylow-group  .
Answer: If $G$ and $H$ are finite groups and $(g,h)\in G\times H$ then $|(g,h)|=lcm (|g|,|h|)$. So if $G$ and $H$ are cyclic and of coprime order there is an element $g\in G$ and $h\in H$ with $|h|=|H|$ and $|g|=|G|$. It follows that $|(g,h)|=lcm(|G|,|H|)=|G||H|=|GH|$, so $GH$ is cyclic.


How to use a value from a textbox with OnChange in a new function?

Question: Here is what I am trying to do:

I am getting a value from PHP and putting it in a textbox (function 1). That works fine.
I am trying to use that value in another PHP query (function 2). Does not work fine.

Both functions should start on loading the page and must remain in separate functions. Problem: the result variable of the first function cannot be found in the second one. As I tried to point out inside the code, the variable "seizoen" remains empty in the second function. Any idea what I am doing wrong here or how I can solve this?
<input type="text" id="Seizoen_text" OnChange="getCompetitie()>

<select id="Competitie_list"></select>

window.onload = function() {
    getSeizoen();
    getCompetitie();
};

function getSeizoen() {
    $.ajax({
        type:'POST',
        url:'get_seizoen.inc.php',
        dataType: 'json',
        success: function(response){
            var maxseizoen = response[0]['MaxSeizoen'];
            $("#Seizoen_text").val(maxseizoen);
        }
    });
}

function getCompetitie() {
    seizoen = $("#Seizoen_text").val();
    alert(seizoen);  //  **--> EMPTY !**
    $.ajax({
        type:'POST',
        url:'get_competitie.inc.php',
        dataType: 'json',
        data: {seizoen: seizoen},
        success: function(response){
            $("#Competitie_list").empty();
            var len = response.length;
            for(var i = 0; i < len; i++){
                var competitievorm = response[i]['Competitie'];
                $("#Competitie_list").append("<option value='"+competitievorm+"'>"+competitievorm+"</option>");
            }
        }
    });
}

Comment: That could be it. I thought referencing it in the second function was enough. Any suggestions what I should do here exactly?
Comment: Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)
Answer: The problem is probably the asynchronous calls.
What's happening is getSeizoen() gets called on window load, but it does an ajax call. While the ajax call executes on the server, during this time getCompetitie() is also called.
In getCompetitie() you are populating the variable seizoen = $("#Seizoen_text").val(); but the textbox probably doesn't have the value yet (since its an asynchronous call).
I'd suggest removing the call to getCompetitie() from the window.load event and call it once the first ajax has completed. There are multiple ways to do this but you could do something like:
function getSeizoen()
{
    $.ajax({
        type:'POST',
        url:'get_seizoen.inc.php',
        dataType: 'json',
        success: function(response){
            var maxseizoen = response[0]['MaxSeizoen'];
            $("#Seizoen_text").val(maxseizoen);
            getCompetitie(); // added call here on success
        }
    });
}


Several questions around the exponential law

Question: $\mathrm{DISCLAIMER~:~}$I am not interested in working with compactly generated spaces.
This post is related to this one : Exponential Law for based spaces. I learned about the exponential law for topological spaces quite some time ago, and I thought I understood it well until I decided to reprove it today as I have been using it lately.
What confuses me is that I 'seem' to have proven it with weaker conditions than those stated in the textbooks. To be precise, I think I have shown that there is a natural homeomorphism
$$\mathrm{Map}(X\times Y,Z)\simeq\mathrm{Map}(X,\mathrm{Map}(Y,Z))$$
where $Z$ is any topological space, $X$ is Hausdorff and $Y$ locally compact $no$ $Hausdorff$ $condition$ $required\dots$ In all textbooks I 'm familiar with, none of which feature a proof of the above fact, the extra assumption is made that $Y$ be Hausdorff. The proof I gave is, I think, the one I learnt in Switzer's book (if I remember right) yet I see no need for Hausdorffness in $Y$.
$\mathrm{QUESTION~1:~}$Is $Y$ Hausdorff really necessary?
Also, the reference I am currently using, Algebraic Topology from the Homotopical Viewpoint [Aguilar, Gitler, Prieto, Springer Universitext], exercice $1.3.4$ asks to show that for $X,Y,Z$ topological spaces with $X$ and $Y$ locally compact Hausdorff spaces, composition $$\mathrm{Map}(X,Y)\times\mathrm{Map}(Y,Z)\rightarrow\mathrm{Map}(X,Z),(f,g)\mapsto g\circ f$$ is continuous. Yet I'm pretty sure all you need is for $Y$ to be locally compact$\dots$
$\mathrm{QUESTION~2:~}$ Are all these extra conditions necessary?
Comment: Without Hausdorff, please specify what you mean by locally compact: every point has a base of open sets with compact closure, every point has a base of compact (not open) neighbourhoods, or instead of base you want just one open set with compact closure, or one compact neighbourhood? These are only equivalent under Hausdorff-like conditions...
Comment: I used following definition : every point has a base of compact neighborhoods.
Comment: Ok, so not necessarily compact --> locally compact.
Comment: Yes, this is no longer true (a priori).
Comment: Engelking states this homeomorphism for: any space Y, Z Hausdorff, X locally compact (which includes Hausdorff with him). And for any X,Z Hausdorff, any Y we have an embedding (which need not be onto). Also, the composition map is continuous in the compact open topologies for any X,Z, locally compact Y.
Comment: I proved (I'm pretty sure) that it is onto with my definition of local compactness, and no restriction on $X$ and $Z$.
Comment: For Tychonov spaces the exponential mapping can only be a homeomorphism for locally compact $X$. This is due to Fox (1945) and/or Arens (1946), according to Engelking.
Comment: @OlivierBégassat let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/719/discussion-between-henno-brandsma-and-olivier-begassat)
Comment: You might find somehing at [nLab](http://ncatlab.org/nlab/show/exponential+law+for+spaces)
Comment: In case someone needs a reference by and by: Tammo tom Diecks section on the compact open topology in his algebraic topology book works with the definition of locally compactness which does not include the Hausdorff property.
Answer: As to Question 2, let $\Sigma$ be the composition map $\mathrm{Map}(X,Y)\times\mathrm{Map}(Y,Z)\rightarrow\mathrm{Map}(X,Z)$.
All functions spaces have the compact-open topology, with as a subbase all sets of the form
$\mathrm{M}(C,U) = \{ f: f[C] \subset U \}$, where $C$ is a compact subset of the domain, and $U$ an open subset of the co-domain.
Let $(f,g)$ be a point in $\Sigma^{-1}[\mathrm{M}(C,U)]$, with $C \subset X$ compact and $U \subset Z $ open, and we want to show it's an interior point.
We have by definition $(g \circ f)[C] \subset U$, or $f[C] \subset g^{-1}[U]$. As $g^{-1}[U]$ is open, and $f[C]$ is compact, both in $Y$, and if we assume $Y$ is locally compact (in the sense from the comments), we can find for each $y \in f[C]$ a compact neighbourhood $K_y$ that sits inside $g^{-1}[U]$, and so $f[C]$ is covered by finitely many sets of the form $\mathrm{Int}(K_y)$, say $\mathrm{Int}(K_{y_i})$ for $i=1 \ldots n$ and set $W$ to be the finite union of these.
Then $W \subset \mathrm{Int}(\cup_{i=1}^n K_{y_i}) \subset K:=\cup_{i=1}^n K_{y_i} \subset g^{-1}[U]$ and so $\Sigma[\mathrm{M}(C,W) \times \mathrm{M}(K,U) ] \subset \mathrm{M}(C,U)$ and so we are done, as $(f,g)$ is in $\mathrm{M}(C,W) \times \mathrm{M}(K,U)$.
This convinces me that indeed we only need local compactness (in a rather strong sense) on $Y$ to show continuity of $\Sigma$, but no Hausdorffness.
Comment: yeah, that was also my proof.
Answer: To QUESTION 1: Yes, exponential law can be established without Hausdorff property of the middle space.
In fact the problem consists of four different parts each requiring its own arguments. Let me try to clarify the points.
For sets $ M, N $ denote by $Map( M, N )$ the set of all maps $ M\to N $.
Let $ L $ be another set.
Then there is a bijection
$$ \exp:Map( L \times M, N ) \to Map( L , Map( M, N ))$$
given by the following rule: if $ F \in Map( L \times M, N )$, then $\exp( F ):  L  \to Map( M, N )$ is given by $\exp( F )(t)(x) =  F (t,x)$.
Lemma.
Let $ L , M, N $ be topological spaces.
Then the following statements hold.
(1)
$\exp(C(L \times M, N)) \subset C(L,C(M,N))$, i.e. if $F: L \times M \to N$ is continuous, then $\exp(F): L \to C(M,N)$ is continuous as well.
(2)
The induced map
$$ \exp:C(L \times M, N) \to C(L,C(M,N)) $$
is continuous with respect to the corresponding compact open topologies.
(3)
Suppose $ M$ is locally compact in the sense that for each $x\in M$ and an open neighborhood $ U $ of $x$ there exists a compact subset $ B \subset M$ such that $x\in Int{ B } \subset B  \subset  U $, (notice that it is not required that $ M$ is also Hausdorff).
Then
$$ \exp (C(L \times M, N)) = C(L,C(M,N)),$$
i.e. the above map is a continuous bijection.
(4)
If in addition to (3) $ L $ is a $T_3$-space (again not necessarily Hausdorff) then the map
$$  \exp: C(L \times M, N) \to  C(L,C(M,N)) $$
is a homeomorphism.
Proof.
(1)
Let $ F : L \times  M \to  N $ be a continuous map.
We need to prove that $ f  = \exp( F ):  L  \to C(M,N)$ given by $ f (t)(x) =  F (t,x)$ is continuous.
Let $t\in L $ and
$$
[ B , W ] = \{ g \in C(M,N) \mid g( B )\subset W \}
$$
be an open neighborhood of $ f (t)$ in $C(M,N)$.
We need to find an open neighborhood $ U $ of $t$ in $ L $ such that $ f ( U ) \subset [ B , W ]$
This means that $ f (t)( B ) \subset  W $, that is $t\times B  \subset  F ^{-1}( W )$.
Since $ B $ is compact, there exists an open neighborhood $ U $ of $t$ in $ L $ such that $ U \times B \subset F ^{-1}( W )$.
But this means that for each $s\in U $, $ f (s)( B )\subset W $, i.e. that $ f ( U ) \subset [ B , W ]$.
(2)
Let $ F : L \times  M \to  N $ be a continuous map and $ f  = \exp( F ):  L  \to C(M,N)$ is given by $ f (t)(x) =  F (t,x)$ is continuous.
Let also $A \subset  L $ and $ B  \subset  M$ be compact subsets, $ W \subset N $ be an open set, and
$$
[A, [ B , W ]] = \{
g:  L  \to C(M,N) \mid
g(A)( B ) \subset  W
\}
$$
be an open neighborhood of $ f $ in $C(L,C(M,N))$.
Then $[A\times B ,  W ]$ is an open neighborhood of $ F $ in $C(L \times M, N)$ such that
$$ \exp([A\times B ,  W ]) \subset [A, [ B , W ]]. $$
(3)
Suppose $ M$ is locally compact in the above sense and let $ f :  L  \to C(M,N)$ be a continuous map.
We should prove that $ F  = \exp^{-1}( f ):  L  \times  M \to  N $, $ F (t,x)= f (t)(x)$ is continuous.
Let $(t,x)\in L  \times  M$ and $ W $ be an open neighborhood of $ F (t,x)$ in $ N $.
We need to find neighborhoods $ U  \subset L $ and $V \subset M$ of $t$ and $x$ such that $ F ( U \times V)\subset W $.
Since $ f (t): M\to N $ is continuous, $ f (t)^{-1}( W )$ is an open neighborhood of $x$ in $ M$, whence there exists a compact $ B \subset M$ such that $x\in Int{ B } \subset B  \subset  U $.
Then $[ B , W ]$ is an open neighborhood of $ f (t)$, and since $ f : L \to C(M,N)$ is continuous at $t$, there exists an open neighborhood $ U  \subset L $ of $t$ such that $ f ( U )\subset [ B , W ]$.
This implies that $ F ( U \times B ) \subset  W $.
In particular, one can put $V= Int{ B }$, then we will have $ F ( U \times V) \subset  W $.
(4)
Suppose $ L $ is a $T_3$ space, i.e. for each point $x\in L $ and its open neighborhood $ U $ there exists an open neighborhood $ Z$ such that $x\in Z\subset\overline{ Z} \subset  U $, and $ M$ is locally compact as in (3).
Let $ F \in C(L \times M, N)$, $ f  = \exp( F )$, and $[C, W ]$ be an open neighborhood of $ F $, where $C\subset L \times M$ be a compact subset and $ W \subset N $ is open.
We need to prove that $\exp([C, W ])$ contains an open neighborhood of $ f $ in $C(L,C(M,N))$.
Since $C$ is compact and $ F ^{-1}( W )$ is its open neighborhood in $ L \times M$, there exist finitely many open sets $ U _1,\ldots, U _k \subset  L $, and $V_1,\ldots,V_k \subset  M$, such that
$$
C \subset \cup_{i=1}^{k}  U _i \times V_i \subset  F ^{-1}( W ).
$$
Moreover, since $ L $ is $T_3$ and $ M$ is locally compact, one can assume in addition that
(a) each $V_i =  Int{ B _i}$ for some compact $ B _i \subset M$;
(b) and that
$$
 C \ \subset\ \cup_{i=1}^{k}  U _i \times V_i
 \ \subset \
 \cup_{i=1}^{k} \overline{ U _i} \times  B _i
 \ \subset \
  F ^{-1}( W ).
$$
Let $p: L \times M\to L $, $p(t,x)=t$, be the natural projection.
Then $p(C)$ is compact.
Hence $A_i := \overline{ U _i} \cap p(C)$ is a closed subset of $p(C)$ and therefore compact.
It then follows that
$$ C \subset
\cup_{i=1}^{k} A_i \times  B _i  \subset  F ^{-1}( W ).
$$
This also implies that
$$
 \cup_{i=1}^{k} [A_i, [ B _i, W ]] \ \subset  \exp( [C, W ] ).
$$
This proves that $\exp$ is open and therefore a homeomorphism.

Thus for the proof of (1) and (2) we do not need any assumptions on $L$ and $M$; for (3) we need local compactness of $M$ and for (4) we need an additional $T_3$ property of $L$.


Buscar valor de variável

Question: Pessoal eu tenho um form para cadastro de candidato. Para salvar no banco ele passa os valores pelo javascript para o salvaCandidato.php. To tentando fazer com que ao enviar o form apareça o modal dizendo o protocolo da inscrição que ta na variável $nr_prot em salvaCandidato.php, não estou conseguindo.
index.php

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Observação

Anote seu protocolo

$nr_prot

 O protocolo foi enviado para o email

        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

salvaCandidato.php

  $sqlProt = "SELECT * FROM candidato WHERE cpf_cand = '$_POST[cpf_cand]'";
  $queryProt = mysqli_query($conexao,$sqlProt);
  $fetchProtocolo = mysqli_fetch_assoc($queryProt);
  $nr_prot =  $fetchProtocolo['nr_prot'];
Comment: Você não pode por uma variável do PHP dentro do HTML puro como fez `$nr_prot`. Se o modal abre pelo PHP você precisa usar ``
Comment: Era só pra ilustrar, tentei usar $_SESSION e $_POST, mas não vem
Comment: Você vai ter que colocar o número do protocolo no modal via javascript.
Veja um exemplo $("#modal-body").html('seu numero de protocolo');
Answer: Pode-se fazer da seguinte maneira:
<?php
  $variavelphp = "";
  echo "$variavelphp";
?>

Você vai editar apenas o variaveljs e colocar a sua variavel!
.
Não sei se conseguir te ajudar, mas espero que sim!
Comment: No caso, como vai ficar o varivaljs, não consegui testar, desde já agradeço
Comment: Do seu codigo html  , usar o codigo acima para pegar da variavel js para o php, e para imprimir o que dejesa, usa: , do jeito que apresentaram no comentario alí em cima!

Buscar valor de variável


Can we pass value to annotations at runtime?

Question: We need to create an annotation in java called DateFormat. It will take string dateformat eg.
class  User
{
    @Dateformat("MMM/dd/yyyy")
    private Date birthDate;
}

Here the date format is statically passed as an argument to the annotation. Is there any way we can pass this date format at run time  may be from session.
Please help.
Answer: Directly, no.
But if you have a property-resolution mechanism, you can have something like:
@DateFormat("${birth.date.format}")

And resolve the birth.date.format property when parsing the annotation.
Comment: We will have this date format in the database. Which we will fetch once user logins to the application. Date format is not stored in the properties file. Its stored in the user preference table in the database.
Comment: well, then make your annotation parser load the configuration from the user
Comment: It all depends on how you parse your annotation. How do you parse it, and where?
Answer: The Java Language Spec dictates that an annotation parameter value must be a constant expression. From section 9.6:

An element type T is commensurate with an element value V if and only
  if one of the following conditions is true:

T is an array type E[] and either:

V is an ElementValueArrayInitializer and each ElementValueInitializer (analogous to a variable initializer in an
  array initializer) in V is commensurate with E. Or
V is an ElementValue that is commensurate with T.

The type of V is assignment compatible (§5.2) with T and, furthermore:

If T is a primitive type or String, V is a constant expression (§15.28).
V is not null.
if T is Class, or an invocation of Class, and V is a class literal (§15.8.2).
If T is an enum type, and V is an enum constant.

The key item in this case is the first sub-point of the second block.
Answer: No. What you could do is have an annotation like
@DateFormat(sessionKey = "foo")

The tool/api which uses the annotation would extract the value of the sessionKey attribute, and get the pattern to apply from the session, using given session attribute key.


How can I stop my "headerSticky" and "content" divs from overlapping?

Question: I'm making a page that has three main components: a "headerSticky" header div, "sidenav" left navigation div, and "content" div.
The side navigation is fixed and does not move; but the content div should be scrollable on its own. However, the top of the content div is always overlapped by the header div.
Here is the CSS for the header:
#headerSticky{
position:fixed;
padding:6px;
width: 100%;}

and the content div:
#content {
padding-top: 100px;
float:right;
overflow: auto;
height: 90%;
width: 840px;
padding: 0 20px 20px;}

Any help would be appreciated. Thank you!
Edit: Screen shot of the page. There should be a title for the table at the top (with the "Condition" and "Condition Status" values) that says "Problems," but it is hidden beneath the header:
alt text http://img14.imageshack.us/img14/477/screenshot20100510at611.png
Answer: You can try removing the position from your #headerSticky. If you position something absolute or fixed, any subsequent elements will act as though its not there (in this case creating an overlap). Also, I'm not sure, but I think some of your styles may not be valid.

I hope this helps in some way.
Comment: Unfortunately I need the header to stay in place while the content div scrolls by, so taking off the position makes the header scroll away from the user's view. I'm not sure about some of the styles either; I'm hoping that fixing the positioning issue will clear up some of those issues (: Thanks for your help!
Comment: In that case, simply add margin-top to #content to match the height of #headerSticky. I don't think it is possible to have #content be positioned correctly unless you at least determine the height of #headerSticky.
Comment: I took your advice, and the result was that the extra space (height of headerSticky) was just added on to the very top of the content div, but scrolling down still makes it go behind the header div. Sorry for the complications.
Comment: Try padding-top then?
Also, maybe you could simply add overflow:scroll to #content to make that scroll, if that is the goal.
Answer: The property float:top; doesn't exist. See here: w3c Float property.
Position fixed means that this element will always have the same position, when the screen is scrolled, this will "stick" to the place you have positioned it on screen, so when your content is longer than the screen, the header will overlap it, remove this, add a height.
Remove the floats also, these are your basic layout divs and need more accurate positioning than float.
If you could also post up your HTML markup and the CSS for your other element we could probably help you more :)
Hope some of that helps.
Comment: Removing the floats makes the content div stick to the left side of the page; and thus overlaps the side navigation. I did remove the "float:top" and it had no effect; so it definitely wasn't helping. Thanks for the tip! Sorry, which other element's CSS would be helpful?
Comment: If you could post up your HTML, that would make it much easier to suggest some things that would help fix your problem :).
Answer: I changed around the CSS a bit and this problem has been solved--here is the code that I used for the header:
#headerSticky {
     height: 28px;
    position: absolute;
    top: 0;
     width: 100%;
}

and the content div:
#content {
    height: 100%;
    float:right;
    overflow-y: auto;
    overflow-x: auto;
}

I know this isn't that different from what I originally had, but I started over from scratch with the CSS and the problem is definitely gone.
Thank you everyone who took the time to answer! I really appreciate it.


Mongodb check if connection is ok via Laravel/PHP

Question: I'm using laravel 5.2 and MongoDB 3.2.
I want to test if connection with is ok before my app starts (i can't use DB facade), in the monolog configuration. If connection is not ok, i will use logging in file.
By recommendation, i'm testing MongoClient, Mongo and MongoDB\Client, and using whatever is enabled.
I'm trying to test mongo connect as the following:
$mongoClient = new \MongoDB\Client('mongodb://localhost:27017');
$mongoClient->selectCollection('mydb', 'mycollection');

That's the return:
Client {
    +manager: Manager {#21}
    +uri: "mongodb://localhost:27017"
    +typeMap: [
        array => "MongoDB\Model\BSONArray",
        document => "MongoDB\Model\BSONDocument",
        root => "MongoDB\Model\BSONDocument"
    ]
}

Finnaly, my questions:

Exists a way to use DB facade before app starts?
How and what is the right way to test MongoDB connection with PHP?

If you has another suggestion, i will be thankful.
Comment: Finnaly i get the exception when fire: $mongoClient->mydb->mycollection->findOne(). This solve my problem, but my questions persist. :)
Answer: According to PHP document, the driver connects to the database lazily (http://php.net/manual/en/mongodb-driver-manager.getservers.php), the only way to test connection should be actually execute commands like findOne() stated in yours comment.
In addition, if the name of DB or Collection is uncertain at the point, you can use listDatabases() method which also throws exceptions if connection fails.
Answer: using this way you can check MongoDB connection with PHP:
$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port

Comment: No, this will not trigger any errors or exceptions. (Remember I need to do something that works for the 3 classes I listed)


Treble Clef with optional 8 va bassa?

Question: What is a treble clef with 8 in parentheses used for?

My software (MuseScore 3.x) ignores it (as if it were a treble without any 8). What is the point of this clef? Is it for transposing instruments? Or for repetitions (once with, once without)?
I haven't found any information by searching on engines or this site.
Answer: This is used in vocal music where the line can be sung either at normal treble-clef pitch (usually by a soprano), or at a pitch an octave below that (usually by a tenor or baritone).
It's very often used in vocal music with a single melody line to indicate that everyone sings that line, whether their voice has broken or not, at the pitch appropriate for them.
Comment: It is an answer. Breaking voices is a physiological effect of puberty in males. Perhaps "at the pitch appropriate for them" could have been "at the pitch which is appropriate for them", and of course it doesn't mean substituting a different *note* than the one written; merely a different pitch of that note, like E3 and E4.
Comment: couldn't understand the exact meaning of "Broken"; plus do you mean by "pitch appropriate", that it is possible to sing, for e. g. C#3 instead of E4? Or just E3 instead of E4 (octave down)?
Answer: This notation is used when a part can be played both in the notated octave and an octave lower. Typical use cases are vocal scores, or scores where a melody can be played both with a soprano as well with a tenor instrument. It is still a rather uncommon notation, similar to how the regular ottava markings for clefs are often omitted, simply for the fact that they are expected to be there on tenor instruments anyway, so there is no real reason to write them (similar to how double bass instruments tend not to have an octavation marking.
Comment: So, transposing instruments? And I got it that, perhaps, it is best to notate using this clef when TWO instruments playing same notes at different octaves.
Comment: which instruments are you thinking of specifically?
Comment: @Feliks_WR Possible example: You could have an opera where a part can be played by a Heckelphone, or (if not available) by a regular oboe an octave higher.
Comment: @Lazy you are right! I think that at a large concert, a heckelphone might be availsble, but otherwise, I haven't even heard of it!
Comment: @Feliks_WR This is something you get in Strauss operas. He used the Heckelphone quite often, but then not every orchestra has access to heckelphones.

Treble Clef with optional 8 va bassa?


How to called this.getRowStyle function forcefully in Angular 7?

Question: I'm using getRowStyle function, but it seems it runs only once when the grid is loaded or it is edited. How do I force run this function manually so that row colors are loaded.
conditonalFormatter() {
    this.GridRef.rowConditionalFormatting('red', this.rowFormatData);
}

rowConditionalFormatting(rowColor, rowFormatData) {
    this.rowFormatData = rowFormatData;
    this.getRowStyle = params => {
            for (let i = 0; i < this.rowFormatData.length; i++) {
                const columnHeader = this.rowFormatData[i].Name;
                const operator = this.rowFormatData[i].Operator;
                const cellValue = this.rowFormatData[i].Value;
                if (params.data[columnHeader] == cellValue) {
                    return {background: rowColor };
                }
            }
        }
}

Comment: Please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), otherwise we don't know what you've already tried.
Comment: @Batajus - Please refer abv functon. it get works during on-load but If I called this funntion from somewhere else then this.getRowStye won't get called.
Comment: Can you also share the code snippets where you're calling `this.getRowStyle`
Comment: @Batajus I have called this from diff component by using referance. Thanks.
Comment: Did u try `rowClassRules` ?
Comment: I need to pass dynamic color as well as values where I need to do RowStyle so can't use rowClassRules.
Answer: After several try I am able to acheive my objective as per below code, just call this.getRowStyle outside -
rowConditionalFormatting(rowColor, rowFormatData) {
   this.rowFormatData = rowFormatData;
   this.rowColor = rowColor;
}

 this.getRowStyle = params => {
    for (let i = 0; i < this.rowFormatData.length; i++) {
        const columnHeader = this.rowFormatData[i].Name;
        const operator = this.rowFormatData[i].Operator;
        const cellValue = this.rowFormatData[i].Value;
        if (params.data[columnHeader] == cellValue) {
            return {background: this.rowColor };
        }
    }
 }

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: The code above is __not calling__ `this.getRowStyle`, it's __defining the function__ as _lambda expression_. In this expression the properties of `this.rowFormatData` are  evaluated and return a style dynamically based on matching `params.data[columnHeader]` (i.e. the current cell-value).
Comment: this.getRowStyle itself a function, it called automatically. print params inside console and check. Ref - https://www.ag-grid.com/angular-data-grid/row-styles/
Answer: If you want to manually apply the row styling again, then you will need to refresh Aggrid manually with refreshCells().
Generally, only those rows where data is changed is redrawn and other rows are ignored. In your case, we will need to force aggrid to redraw the rows and hence will have to use force=true
gridApi.refreshCells({
      force: true // skips change detection -> always refreshes the row
   })

You will get gridApi object, in onGridReady callback provided by aggrid.
public onGridReady(params) {
    /**
    * Function is called when grid is instantiated.
    * @param params Ag grid params
    */
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
  }

HTML code:
<ag-grid-angular class="ag-theme-alpine" [columnDefs]="columnDefs [gridOptions]="gridOptions" (gridReady)="onGridReady($event)"></ag-grid-angular>


executing threads in POSIX

Question: I am creating an asynchronous chat application in C. I created two threads, one for receiving and another one for sending as follows.

void* send()
{
...
}

void* receive()
{
...
}

main()
{
..
inid = pthread_create(&incoming,NULL,receive,"Incoming thread");
outid= pthread_create(&outgoing,NULL,send,"Outgoing thread");

..

pthread_join(incoming,NULL);
pthread_join(outgoing,NULL);

..

}

What the problem is, the send and receive functions are called only once and the program terminates. I want both the threads to run forever till the user wishes to exit ( the condition to check for exit is defined in the send function). How to solve this?
Answer: One solution is to have a while(input != exit) type of loop in send.
And make your main to only wait for outgoing thread (which means having pthread_join only for outgoing thread). So, when the user chooses to exit, the main will exit without waiting for the incoming thread.
Secondly, you need to use a blocking receive function in the receive function. So, it is either processing an incoming message or waiting for one.
Another solution is to have a while(input != exit) type of loop in main. Have a message queue defined in which main can queue messages to be sent and the outgoing thread consumes messages from this thread to actually send them.
The outgoing thread is either sending a message or is blocked until the queue has a message in it to be sent.
The input thread behaves in the same way as described in the previous solution.
Comment: @CHID: You can always vote and accept as a token of gratitude;)
Comment: oh sure.. sorry bout the delay ;)

executing threads in POSIX