Sync Servers with DRBD

Question: assume if I synchronized two servers and I used DRBD, and after I synced them I installed application on both, if I wanted to add a third server. is that possible? since I think I should create block device and use it in the installation and that is made during configuration of the DRBD on both servers
if yes, is that (add more servers in future) also applicable to NextCloud servers?
Thanks
Answer: As it was mentioned already, DRBD isn't greatest solution especially if you have a requirements for further scale.
I believe that the best solution on Linux would be Ceph Cluster - https://en.wikipedia.org/wiki/Ceph_(software) with its native cluster aware file system CephFS.
For the configuration of an HA storage on Windows, take into account StarWind VSAN Free, which can be deployed in cloud as well (Asure/AWS).
Comment: Ceph is super-scalable! You can add new OSD and rebalance your data every single moment.
Comment: Hi, when you said **"the best solution on Linux would be Ceph Cluster"** does that include `Ubuntu 16.04` ? since i had troubles before of not supported application with Ubuntu
Comment: also is it scalable in future?
Comment: by the way my case is that i have Amazon EC2 instances and i already configured them in High Availability mode but what i need to do is to use something like DEBD to install some applications and for loggings, so i would have these application working as a one on the EC2 instances cluster that i already have configured, is Ceph Cluster fit for that scenario?
Answer: Yes, you can absolutely do that! See:
https://docs.linbit.com/doc/users-guide-83/s-three-nodes/
The only problem you need to have cluster-aware file system or do active-passive-passive mode with file system remount on failover (in this case only one node can have operational write-capable application). Good cover story is here:
https://forums.starwindsoftware.com/viewtopic.php?f=5&t=1392
P.S. DRBD isn't greatest solution we have for HA storage these days, so I'd encourage to take a look at something more OS-specific.
Comment: You can use non-clustered file system with non-readable second replica.
Comment: It's not even clear what exactly OP wants to synchronize, and a cluster file system is a minimal requirement to even read DRBD resource on the second server, as a secondary device can't be even read (so, with DRBD, active/passive setups are not possible).
Comment: DRBD has autopromote features in DRBD 9, so any attempt to access the data on the secondary server after the primary has failed will result in the secondary promoting to primary. DRBD is one of the most generic replication tools out there. It replicates at the block level, and almost everything gets put down to a block device at some point... Sure, if you have something specific (like database replication for example), use that, but otherwise I'd be surprised if DRBD doesn't fit the bill.
Comment: This is what I was trying to tell to @Sven. P.S. Thanks for downvote, I appreciate that! :(
Answer: DRBD 9 can scale to 31 replicas of your data, so 32 nodes. DRBD 8 was limited to 4 nodes through stacking, but it was still possible. You can certainly start with 2 nodes, and then add a third with DRBD 8 or 9.
DRBD is in the mainline Linux kernel, so unless NextCloud is only providing distros that remove DRBD from the kernel, it will be and work there.
There seem to be some misconceptions flying around about DRBD in this thread: You don't need any cluster aware filesystems for DRBD in Active-Passive mode. You would in Active/Active, same as with a shared block device on a SAN. Also, DRBD 9 scales pretty well with up to 32 nodes per cluster, with fancy ways to increase that number.
Comment: @ibr Ceph needs many nodes to get reasonably high performance, it just starts with 3 nodes as a minimum and I'd say 8 is a reasonable number to put into production. DRBD is 2-node solution by design so... It's basically apples to oranges :)
Comment: after there has been mention by *batistuta09* about Ceph, im thinking to shift to it instead of DRBD, is really Ceph better that DRBD?, also the installation of Ceph is not as straight forward as DRBD, after reading Documents still can tell if osd node is a server node or not, and does Ceph or with Ubuntu 16 EC2 instances or not? .....thanks
Comment: Honestly, you're probably best off trying both in your situation and deciding for yourself. With Ceph there will have to be some form of locking across nodes to prevent concurrent access, which usually comes with a performance impact, but it would be hard to gauge without trying.
Comment: @BaronSamedi1958: DRBD 8 is two nodes by design, DRBD 9 is up to 32 nodes by design ;) They're two completely different softwares. LINBIT has taken to calling DRBD 9: "LINBIT SDS", and DRBD 8: "LINBIT HA".
Comment: OK so assuming i have two nodes running now, after 6 months i wanted to add another node, how to add it? because honestly in the installation guide it seems that its one time configuration and i didn't find any reference on how to add more nodes in future at DRBD.....with the consideration i have AWS RDS as DB for all instances and S3 bucket as storage, thanks
Answer: Unless you use a specialized cluster-aware file system, you can't use DRBD to sync file systems of two running servers.  The reason is that both servers would think they have exclusive access to the file system and overwrite changes made by the other one. Total file system loss will be the result.
Nextcloud works very differently, but is also not really suitable to sync general file systems of two servers, because it's really easy to make conflicting changes in the same file.  In some cases, it could be used to sync data directories, but you have to be aware how Nextcloud works and how your application work to see if this could work out.
-- Edit
If you goal is to cluster a Nextcloud installation, DRBD is not a very good solution, as you could use it only for a small part of what makes up a Nextcloud server. Things like the SQL database can not be clustered in this way.
Read https://docs.nextcloud.com/server/9/admin_manual/operations/scaling_multiple_machines.html
Comment: No need for cluster aware filesystems with DRBD. DRBD is "shared nothing clustering", so you're more likely to diverge data than corrupt it, but DRBD 9 has quorum features that will help prevent even that. You can certainly replicate a database with DRBD as well btw...
Comment: Thanks sven for the answer, but I didn't get exactly what do you mean by "sync general file systems of two servers", my case is installed NextCloud servers and to "Mirror Sync" client's files, is that what you meant?......also it seems you know DRBD well, so one more question, does it work with AWS EC2 (Ubuntu) instances?
Comment: I think what you meant is that syncing two servers using the NextCloud, but actually I need to Sync two servers that is installed on them NextCloud, so the case is to sync between two servers that contain NextCloud, then add another server that contains NextCloud, also I found this [article](https://help.ubuntu.com/lts/serverguide/drbd.html) does it work with EC2 or there is another approach? thanks
Comment: well, there is the trick, since I already use an AWS RDS as database for all NextCloud servers, and S3 bucket as a primary storage for all servers as well, so I only need DRBD for NextCloud installation so they work as one :)
Comment: @MattKereczman: We come back to the question what exactly OP wants to achieve. HA with failover would work without a cluster FS, but if the goal is load-balancing (where all clients needs RW access to the data store), you would need a cluster FS to make use of DRBD (IIRC, in DRBD8 you can't even mount a non-primary DRBD volume).
Comment: @Sven: Sure; that's still true about DRBD. However, there is a lot of speculation about what OP wants to do, when really, he just asked a very simple question of whether you can add a node to a DRBD cluster, and whether that still works in NextCloud deployments.
Comment: Hi, i have the following, AWS EC2 instances, and database for them is AWS RDS, and their primary storage is S3, now i ONLY found this guide on how to make the instances works as one server(Synced) is this [article](https://help.nextcloud.com/t/nexcloud-server-sync/2165) forgetting Pacemaker and Corosync i already havemade HA cluster to EC2s, but as you can see in the article IT'S required by NextCloud to use Storage Sync for *installation* so honestly right now, i don't know which to use? Ceph or DRBD?......thanks

Sync Servers with DRBD


Erro em INNER JOIN Mysql e exibição em JSON

Question: Olá
Eu preciso exibir os resultados de um SELECT com INNER JOIN em formato JSON, minha query esta funcionando, pois testei dentro do PHPMYADMIN, mas na minha pagina não funciona, já testei de tudo, oque pode ser ? Alguem me ajuda a achar o erro ? Deve ser algo muito simples.
Meu SQL
    -- phpMyAdmin SQL Dump
    -- version 4.6.4
    -- https://www.phpmyadmin.net/
    --
    -- Host: 127.0.0.1
    -- Generation Time: May 30, 2017 at 01:45 PM
    -- Server version: 5.7.14
    -- PHP Version: 5.6.25

    SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
    SET time_zone = "+00:00";

    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
    /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
    /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
    /*!40101 SET NAMES utf8mb4 */;

    --
    -- Database: `projeto001`
    --

    -- --------------------------------------------------------

    --
    -- Table structure for table `compras`
    --

    CREATE TABLE `compras` (
      `id` int(100) NOT NULL,
      `username` varchar(100) NOT NULL,
      `projeto` varchar(100) NOT NULL,
      `produto` varchar(100) NOT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `compras`
    --

    INSERT INTO `compras` (`id`, `username`, `projeto`, `produto`) VALUES
    (1, 'Fulano', 'Projeto Novo', 'produto01');

    -- --------------------------------------------------------

    --
    -- Table structure for table `empresa`
    --

    CREATE TABLE `empresa` (
      `id` int(100) NOT NULL,
      `username` varchar(100) NOT NULL,
      `projeto` varchar(100) NOT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `empresa`
    --

    INSERT INTO `empresa` (`id`, `username`, `projeto`) VALUES
    (1, 'Fulano', 'Projeto Novo');

    -- --------------------------------------------------------

    --
    -- Table structure for table `estoque`
    --

    CREATE TABLE `estoque` (
      `id` int(100) NOT NULL,
      `produto` varchar(100) NOT NULL,
      `quantidade` varchar(100) NOT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    --
    -- Dumping data for table `estoque`
    --

    INSERT INTO `estoque` (`id`, `produto`, `quantidade`) VALUES
    (1, 'produto01', '100');

    --
    -- Indexes for dumped tables
    --

    --
    -- Indexes for table `compras`
    --
    ALTER TABLE `compras`
      ADD PRIMARY KEY (`id`);

    --
    -- Indexes for table `empresa`
    --
    ALTER TABLE `empresa`
      ADD PRIMARY KEY (`id`);

    --
    -- Indexes for table `estoque`
    --
    ALTER TABLE `estoque`
      ADD PRIMARY KEY (`id`);

    --
    -- AUTO_INCREMENT for dumped tables
    --

    --
    -- AUTO_INCREMENT for table `compras`
    --
    ALTER TABLE `compras`
      MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
    --
    -- AUTO_INCREMENT for table `empresa`
    --
    ALTER TABLE `empresa`
      MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
    --
    -- AUTO_INCREMENT for table `estoque`
    --
    ALTER TABLE `estoque`
      MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
    /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
    /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
    /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Meu Código
    <?php

    $projeto = $_GET['projeto'];

    //PDO is a extension which defines a lightweight, consistent interface for accessing databases in PHP.
    $db=new PDO('mysql:dbname=mydatabase;host=localhost;','username','password');
    //here prepare the query for analyzing, prepared statements use less resources and thus run faster
    $nome = addslashes(filter_input(INPUT_GET, 'nome', FILTER_SANITIZE_SPECIAL_CHARS));

    //Produtos
    $row=$db->prepare("SELECT empresa.username, empresa.projeto, compras.username, compras.projeto, compras.produto, estoque.produto FROM `empresa` AS empresa LEFT JOIN `compras` AS compras ON compras.`username` = empresa.`username` AND compras.`projeto` = empresa.`projeto` LEFT JOIN `estoque` AS estoque ON compras.`produto` = estoque.`produto` WHERE empresa.projeto = 'Projeto Novo' and compras.username = 'Fulano'");

    $row->execute();//execute the query
    $json_data=array();//create the array
    foreach($row as $rec)//foreach loop
    {
    $json_array['empresa.username']=$rec['empresa.username'];
    $json_array['empresa.projeto']=$rec['empresa.projeto'];
    $json_array['compras.username']=$rec['compras.username'];
    $json_array['compras.projeto']=$rec['compras.projeto'];
    $json_array['compras.produto']=$rec['compras.produto'];
    $json_array['estoque.produto']=$rec['estoque.produto'];
    //here pushing the values in to an array
    array_push($json_data,$json_array);

    }

    //built in PHP function to encode the data in to JSON format
    echo json_encode($json_data);
    ?>

Valew
Comment: Qua erro você obtém?
Comment: Dizer que não está funcionando é muito abrangente. Qual é o erro/resultado que está obtendo e qual era o esperado?
Comment: então o problema é que nada é exibido na tela, teria que exibir o resultado com uma formatação JSON.
Answer: Olá, coloque antes do json_encode o seguinte código:
header('Content-Type: application/json');

Isto serve para que a resposta seja no formato json, sem isto, sua resposta é considerada uma página web.
Obs.: Você não pode ter nenhuma saída de conteúdo antes de setar o header, caso já tenha dado saída em algum conteúdo, receberá uma mensagem de aviso/erro do php.
Comment: Então, meu código esta funcionando, pois já testei com um SELECT simples, mas agora nada aparece utilizando o SELECT com INNER JOIN, talvez o erro esteja na hora de exibir os dados na tela.
Comment: É provável que esteja recebendo algum erro do PHP. Adicione estas linhas no início do código para exibi-los:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Com isto, conseguiremos ter uma ideia melhor do erro que está ocorrendo.
Comment: Não deu erro nenhum.
Comment: de um var_dump($json_data) e diga o que retorna.
Answer: Tente este código, fiz uma alteração, adicionei a variável $linhas e o fetchall.
<?php

//Produtos
$row=$db->prepare("SELECT empresa.username, empresa.projeto, compras.username, compras.projeto, compras.produto, estoque.produto FROM `empresa` AS empresa LEFT JOIN `compras` AS compras ON compras.`username` = empresa.`username` AND compras.`projeto` = empresa.`projeto` LEFT JOIN `estoque` AS estoque ON compras.`produto` = estoque.`produto` WHERE empresa.projeto = 'Projeto Novo' and compras.username = 'Fulano'");

$row->execute();
$json_data=array();
$results = $row->fetchAll();

foreach($results as $rec)
{
    $json_array['username']=$rec['username'];
    $json_array['projeto']=$rec['projeto'];
    $json_array['produto']=$rec['produto'];

    //here pushing the values in to an array
    array_push($json_data,$json_array);
}

//built in PHP function to encode the data in to JSON format
header('Content-Type: application/json');
echo json_encode($json_data);

Comment: Eu testei o código, mas não funcionou, o problema é que o array esta vindo vazio, será que o problema esta no SELECT, talvez as aspas simples ?
Comment: abduzeedo, tem como colar o SQL da sua base, vou replicar e consigo resolver. Uma dúvida, quando você cola o SQL que está aí acima direto no banco e executa, volta algum resultado?
Comment: Editei o código e inseri o meu SQL para criar o Banco de Dados, creio que assim fica mais fácil para me ajudar. Obrigado
Comment: Olá Bruno. Tudo Bem ? Qual será o erro ?
Comment: Atualizado o código, fiz o import da sua base e corrigi o código, agora está funcional.
Comment: Obs, retirei a string de conexão. O mais importante ali que estava faltando é "$results = $row->fetchAll();", sem essa linha, você estava tentando ler o conteúdo da string da consulta e não no objeto retornado da consulta. Também as colunas do array retornado estavam incorretas. O nome da coluna não é acompanhado pelo nome da tabela, a não ser que coloque um alias para cada coluna com os nomes que estavam anteriormente.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/59569/discussion-between-abduzeedo-and-bruno-rigolon).


Centralizer of projections

Question: Let $H$ be a Hilbert space and $p, q$ self-adjoint projectors in $B(H)$,
 i.e. $$p^2=p=p^* \space \text{ and } \space q^2=q=q^*.$$ Suppose they have the same centralizers $C(p)=C(q)$.
 Is it true that $p=\pm q$?
 Here $C(x)=\{y\in B(H) : yx=xy\}$.
Maybe I am asking a well known result but I couldn't find anything about this problem in the literature.
Comment: I think you want to say "Is it true that $p = 1 - q$ or $p = q$". Minus a projection is not a projection.
Answer: Look in Vaughan Jones notes, Exerise 2.1.13. $A$ and $A^\ast$ preserve a subspace $K$, ie $A K \subset K$ and $A^\ast K \subset K$ iff $[A,P_K] = 0$, where $P_K$ is the orthogonal projection onto $K$.

Centralizer of projections


multiple select value foreach in php

Question: Ok i have the problem! :)
I have a two same name select in my page ( if statement handling ) and i forgot add value options for one.... my bad :) Thanks for replys!

I have a multiple selection in my page:
<select multiple="multiple" name="diff[]">
   <option value="1">Easy</option>
   <option value="2">Medium</option>
   <option value="3">Hard</option>
</select>

And i want to get the option-s value so:
foreach($_POST['diff'] as $key) {
 echo $key;
}

I want to option values but i get this values ->   Easy, Medium, Hard.
How i can acces the value="" attribute ?
Thanks dudes!
Comment: You should get the value in the `value` attribute. Show us how you post your form.
Comment: Have you tried assigning names to the different options using the names="" tag in HTML?
Answer: Your code should work, I guess the problem is how you post it.
Here is a little sample code, tested on my server. It gives the desierd ouput:
Edited Code:
<form class="form-inline" method="POST" action="">
    <select multiple="multiple" name="diff[]">
       <option value="1">Easy</option>
       <option value="2">Medium</option>
       <option value="3">Hard</option>
    </select>
    <button type="submit" class="button" name="mentes" id="mentes" title="Mentés az adatbázisba">Send</button>
</form>

<?php
if(!empty($_POST["diff"])) {
    foreach($_POST['diff'] as $key) {
        echo $key;
    }
}
?>

When I select "easy" and press "Go" -> Output: 1
This works for all the other inputs as well.
Comment: My submit button :

My form :

I use select2 Jquery, maybe ?
Comment: Kinda sure its because of that. Because even if I replace my submit button with your code it works perfectly. Edit: Code edited.

multiple select value foreach in php


Why can't a wildcard type parameter is Scala be bound?

Question: I have a typed pair class:
class TypedPair[T]

and I want to apply a certain function to a heterogeneous sequence of them:
def process[T](entry: TypedPair[T]) = {/* something */}

Why doesn't this work?
def apply(entries: TypedPair[_]*) = entries.foreach(process)

It fails with the error:
error: polymorphic expression cannot be instantiated to expected type;
 found   : [T](TypedPair[T]) => Unit
 required: (TypedPair[_]) => ?
         def apply(entries: TypedPair[_]*) = entries.foreach(process)

I don't recall getting into this problem in Java...
Comment: Funny enough, adding a dummy parameter to `process` makes it compile: `def process[T](dummy: Boolean, entry: TypedPair[T]) = {}` followed by `def apply(entries: TypedPair[_]*) = entries.foreach(process(true, _))` doesn't cause an error… Am I missing something here?
Answer: The compiler has problems figuring out the anonymous method in this case. When you added the dummy parameter, you also changed the syntax to help the compiler with it, so the following will work:
def apply(entries: TypedPair[_]*) = entries.foreach(process(_))

Answer: You have declared an existential type:
def apply(entries: TypedPair[_]*) = entries.foreach(process)

is equivalent to
def apply(entries: TypedPair[t] forSome { type t }*) = entries.foreach(process)

I'm not sure if this is what you intended or not.


Show this limit is equal to one without using the L'Hôpital rule

Question: Show that
$$\lim_{x\to\pi} \frac{\pi -x}{\sin(x)}=1$$
Although this can be easily solved with L'Hôpital but I need to do it using some algebric simplification. So far I have tried turning $\sin(x)$ to $-\sin(x-\pi)$, breaking into two separate fractions and some of my mates have tried other approaches but no one can figure this out. Can someone point me in the right direction?
Comment: $$\pi-x=y$$ https://math.stackexchange.com/questions/75130/how-to-prove-that-lim-limits-x-to0-frac-sin-xx-1
Answer: \begin{align}\lim_{x\to\pi}\frac{\pi-x}{\sin x}&=-\frac1{\lim_{x\to\pi}\frac{\sin(x)-\sin(\pi)}{x-\pi}}\\&=-\frac1{\sin'(\pi)}\\&=1\end{align}
Comment: Nice hat    $ \ $
Comment: How did u get sin'(pi)?
Comment: By definition,$$\sin'(a)=\lim_{x\to a}\frac{\sin(x)-\sin(a)}{x-a}.$$
Comment: Sir thanks for the effort but i could accept only one answer and the other one was easier to understand
Answer: Since $ \sin(x- \pi)= -\sin x$ we have
$$ \lim_{x  \to \pi} \frac{\sin x}{\pi-x}=\lim_{x \to \pi} \frac{\sin ( x - \pi)}{x-\pi}= \lim_{t \to 0} \frac{\sin t}{t}=1.$$
Answer: Using the known limit $$\lim_{\color{blue}\theta\to\color{blue}0}\frac{\sin\color{blue}\theta}{\color{blue}\theta},$$ we have
$$\lim_{x\to\pi}\frac{\pi-x}{\sin x}=\lim_{\color{blue}{\pi-x}\to\color{blue}0}\frac{\color{blue}{\pi-x}}{\sin(\color{blue}{\pi-x})}=1.$$


Gerar em PDF latex o BEKK e diagnoseBEKK do pacote 'mgarchBEKK'

Question: Estou querendo gerar em PDF no latex as funções BEKK e diagnoseBEKK do pacote mgarchBEKK, só que ele sai todo desconfigurado. Segue do dados:
> head(LOG1)
     [,1]     [,2]
[1,] 3.129256 3.288402
[2,] 3.148093 3.292126
[3,] 3.151220 3.284664
[4,] 3.145901 3.280911
[5,] 3.140324 3.295837
[6,] 3.143793 3.295837

> dput(head(LOG1, 20))
structure(c(3.12925604926495, 3.14809347817882, 3.15122000536595,
3.14590053886684, 3.14032413879594, 3.14379279514427, 3.15001885787015,
3.15575581137615, 3.1871339647665, 3.17698029293942, 3.1650185553098,
3.15712199430691, 3.15808523968012, 3.1424437880591, 3.11208598177176,
3.12253114789199, 3.15877485557127, 3.16054905970894, 3.17276954280673,
3.18961151256573, 3.28840188751681, 3.29212628660779, 3.2846635654062,
3.28091121578765, 3.29583686600433, 3.29583686600433, 3.29620716780452,
3.30688670219091, 3.32143241319329, 3.31418600467253, 3.29953372788566,
3.31600253559892, 3.31418600467253, 3.30027146307219, 3.2846635654062,
3.28840188751681, 3.30431930668567, 3.30431930668567, 3.34215484102837,
3.33932197794407), .Dim = c(20L, 2L))

Quando eu gero a função BEKK:
> estimated1 <- BEKK(as.matrix(LOG1),c(1, 1))
H IS SINGULAR!...
H IS SINGULAR!...
H IS SINGULAR!...
H IS SINGULAR!...
H IS SINGULAR!...

e a função diagnoseBEKK, eu gostaria de gerar em tabela stargazer os "C estimates", "ARCH estimates" e "GARCH estimates"
> diagnoseBEKK(estimated1)
Number of estimated series :  5282
Length of estimated series :  2641
Estimation Time            :  6.374574
Total Time                 :  7.716886
BEKK order                 :  1 1
Eigenvalues                :  13.62364 1.016955 0.7921524 0.09844105
aic                        :  -206.238
unconditional cov. matrix  :  677.4441 -669.5645 -669.5645 661.1839
var(resid 1 )                :  0.5140241
mean(resid 1 )               :  0.6797914
var(resid 2 )                :  0.4907388
mean(resid 2 )               :  0.6919167
Estimated parameters       :

C estimates:
          [,1]        [,2]
[1,] -0.06893851 -0.07384558
[2,]  0.00000000  0.01378535

ARCH estimates:
         [,1]      [,2]
[1,]  0.3166768  1.250476
[2,] -1.2402237 -2.175200

GARCH estimates:
        [,1]       [,2]
[1,] -1.726880 -1.3451395
[2,]  1.316612  0.9358533

asy.se.coef                :

C estimates, standard errors:
       [,1]         [,2]
[1,] 0.03257374 0.0331921785
[2,] 0.00000000 0.0004459779

ARCH estimates, standard errors:
        [,1]      [,2]
[1,] 0.1476386 0.1501182
[2,] 0.1460898 0.1473559

GARCH estimates, standard errors:
        [,1]      [,2]
[1,] 0.5575840 0.5634912
[2,] 0.5514318 0.5570802

E ainda pede para clicar em "continue", que eu também gostaria de tirar para não atrapalhar na hora de gerar o PDF
Called from: diagnoseBEKK(estimated1)
Browse[1]> c
Called from: diagnoseBEKK(estimated1)
Browse[1]> c

Comment: Em vez de postar as funções de um pacote que nós podemos obter, por favor **edite a pergunta** com as intruções que tentou, como chmaou essas funções e com a saída de `dput(dados)` ou, se a base for muito grande, de `dput(head(dados, 20))`? Nota: `dados` é o nome da base, por exemplo de um data.frame.
Comment: Ok Rui, fiz as devidas alterações.
Comment: Muito melhor. Mas falta o código, como está a usar as funções que estão a causar problemas, como está a chamá-las.
Comment: Acho que coloque a informação que solicitou, se entendi bem. Obrigado Rui
Answer: Pode criar uma tabela latex para cada matriz de estimativas com a seguinte função. Não vou usar o pacote stargazer mas sim o pacote xtable, que é mais simples e que para este problema chega bem.
A saída da função é uma lista com as tabelas latex, uma por cada membro da lista.
library(mgarchBEKK)
library(xtable)

mgarchBEKKlatex <- function(x, digits = 4, ...){
  out <- vector("list", length = sum(c(1, x$order)))
  out[[1]] <- xtable(x$est.params[[1]],
                     caption = "C estimates:",
                     digits = digits, ...)
  if (x$order[2] > 0) {
    caption <- "ARCH estimates:"
    for (count in seq_len(x$order[2])) {
      out[[count + 1]] <- xtable(x$est.params[[count + 1]],
                                 caption = caption,
                                 label = paste("order:", count),
                                 digits = digits, ...)
    }
  }
  if (x$order[1] > 0) {
    caption <- "ARCH estimates:"
    for (count2 in seq_len(x$order[1])) {
      out[[count2 + count + 1]] <- xtable(x$est.params[[count2 + count + 1]],
                                 caption = caption,
                                 label = paste("order:", count),
                                 digits = digits, ...)
    }
  }
  out
}

estimated1 <- BEKK(LOG1, c(1, 1))

tabelas <- mgarchBEKKlatex(estimated1)

tabelas[[1]]
#% latex table generated in R 3.6.1 by xtable 1.8-4 package
#% Mon Aug 12 20:28:18 2019
#\begin{table}[ht]
#\centering
#\begin{tabular}{rrr}
#  \hline
# & 1 & 2 \\
#  \hline
#1 & 6.1491 & 6.4497 \\
#  2 & 0.0000 & 0.0040 \\
#   \hline
#\end{tabular}
#\caption{C estimates:}
#\end{table}

Gerar em PDF latex o BEKK e diagnoseBEKK do pacote ‘mgarchBEKK’


Prove if $\{B_n\}$ are events such that $\sum_{i=1}^nP(B_i)>n-1 \Rightarrow P(\bigcap_{i=1}^n B_i)>0.$

Question: In the case when $n=2$, we have that if
$$P(A\cup B)>1, \text{ then }$$
$$P(A\cup B)=P(A)+P(B)-P(A\cap B)>1-P(A\cap B),$$
from here, we have that If $P(A\cap B)=0$, then $P(A\cup B)>1 !!$, so, necesarily, $P(A\cap B)>0.$
In the case when $n>1$, I think that inclusion-exclusion formula can be used in a similar way as in case when $n=1$, but I can't conclude the proof.
Comment: The base case you gave is not when $n=1$, but when $n=2$.  For $n=1$, it is simply saying that $P(B_1)>1-1$ implies $P(B_1)>0$.
Comment: My hint is: find a bound on $\sum_{i=1}^n P(B_i^c)$, where $X^c$ is the complement of $X$.  Then use *subaddtitivity* $P\left(\bigcup_{i=1}^n B_i^c\right)\leq \sum_{i=1}^n P(B_i^c)$.
Answer: From $\sum_{i=1}^nP(B_i)>n-1$ we obtain $$\sum_{i=1}^nP(B_i^c)<1$$also since $P(\bigcup _{i=1}^nB_i^c)\le \sum_{i=1}^nP(B_i^c)$ (union bound) we obtain $$P(\bigcup _{i=1}^nB_i^c)<1$$or $$1-P(\bigcup _{i=1}^nB_i^c)>0\implies P\Bigg((\bigcup _{i=1}^nB_i^c)^c\Bigg)>0\implies P(\bigcap_{i=1}^nB_i)>0$$


Proof of Levy's theorem and tightness

Question: I am trying to understand the proof behind Levy's theorem. The statement is as follows

Theorem: Let $(X_n)_{n\in \mathbb N}$ be a family of random variables, $(\mu_n)_{n\in \mathbb N}$ their distributions and $(\varphi_n)_{n\in \mathbb N}$ their characteristic functions.
Suppose that for every $t \in \mathbb R$
$$\lim_{n\to \infty}\varphi_n(t)= \varphi(t)$$
and that $\varphi$ is continuous in $0$. Then there exists a distribution $\mu$ such that $\varphi$ is $\mu$'s characteristic function and $(\mu_n)_{n \in \mathbb N}$ converges weakly to $\mu$.

The proof that I have been provided with shows that the family $(\mu_n)_{n\in \mathbb N}$ is tight through an integral argument.
From my (limited) knowledge in probability, Prokhorov's theorem states that if the family $(\mu_n)_{n\in \mathbb N}$ is tight then there exists a distribution $\mu$ and a subsequence of the given family $(\mu_{\kappa_n})_{n\in \mathbb N}$ that converges weakly to $\mu$, but there is no general result about the convergence of $(\mu_n)_{n \in \mathbb N}$.
Supposing that we have shown that $(\mu_n)_{n\in \mathbb N}$ is tight, we can conclude that there exists a sequence $\kappa_n$ such that
$$\lim_{n\to \infty}\varphi_{\kappa_n}(t)=\varphi(t)$$
but

How can we conclude that $(\mu_n)_{n \in \mathbb N}$ converges weakly to $\mu$?
Answer: Here are the pieces you are missing, I think:

Prokhorov's theorem actually says that $\textit{every}$ subsequence of your $(\mu_n)_{n \in \mathbb{N}}$ has a sub-subsequence converging in the weak topology to some probability measure.
By your condition on the sequence $(\phi_n)_{n \in \mathbb{N}}$ converging to $\phi$, every one of the sub-subsequences of $(\mu_n)_{n \in \mathbb{N}}$ must converge to the measure $\mu$ whose characteristic function is $\phi$.
In a Polish space, the topology of weak convergence is metrizable.

That means limits are unique, and the sequence $(\mu_n)_{n \in \mathbb{N}}$ converges weakly to a probability measure $\mu$ if and only if each subsequence has a further subsequence converging weakly to that measure --- true because of steps 1, 2.

Proof of Levy's theorem and tightness


Bar and line graphs overlaying on same figure, containing groups, and by another group

Question: I am attempting to create a figure that essentially has a bar graph corresponding to one group and a line graph for another group, but where there are two groups within each of the formerly described groups. I have tried various ways of using twoway and binscatter but have not been able to achieve what I would like.
I am including a picture of what I would like to create: https://i.stack.imgur.com/OdO1W.png
I imagine it might take some reshaping, but it might not. If anyone has any leads, I would definitely appreciate it. If color could be left to the user's desire, that would be even better. Although I think the data is shaped so that one could create the graph "automatically" by referring to the categories, it might be possible to reshape the data and use county-year as the categorical variable.
The code to develop the dataset:
clear
set obs 16
g month = _n
g year = 2000
replace year = 2010 if month > 8
g cost = runiform(0, 100)
g country = "USA" if _n <= 4
replace country = "China" if _n > 4 & _n <= 8
replace country = "USA" if _n > 8 & _n <= 12
replace country = "China" if _n > 12 & _n <= 16
replace month = month - 4 if month>4 & month<=8
replace month = month - 8 if month>8 & month<=12
replace month = month - 12 if month>12 & month<=16

Comment: I recommend re-posting on Statalist or Stack Overflow with a clearer explanation of what should be lines and what should be bars.
Answer: This is in my view off-topic on CV -- please see advice on software-related questions in the Help Center -- but while I am waiting to see if others also vote that way I find the question unclear in any case. The following won't fit well in a comment.
Here is a shorter equivalent of your code, and I set the seed for reproducibility.
clear
set seed 1234
set obs 16
g year = cond(_n > 8, 2010, 2000)
bysort year: g country = cond(_n > 4, "China", "USA")
bysort year country : gen month = _n
g cost = runiform(0, 100)

list , sepby(year country)

     +-----------------------------------+
     | year   country   month       cost |
     |-----------------------------------|
  1. | 2000     China       1   94.72316 |
  2. | 2000     China       2   5.222337 |
  3. | 2000     China       3   97.43183 |
  4. | 2000     China       4   94.57484 |
     |-----------------------------------|
  5. | 2000       USA       1   18.56478 |
  6. | 2000       USA       2   94.87334 |
  7. | 2000       USA       3   88.25376 |
  8. | 2000       USA       4   94.40776 |
     |-----------------------------------|
  9. | 2010     China       1   8.942585 |
 10. | 2010     China       2   75.05445 |
 11. | 2010     China       3   94.84983 |
 12. | 2010     China       4   11.21626 |
     |-----------------------------------|
 13. | 2010       USA       1   48.09064 |
 14. | 2010       USA       2   97.63448 |
 15. | 2010       USA       3   12.54975 |
 16. | 2010       USA       4   76.55025 |
     +-----------------------------------+

Your sketch has some data points joined by lines and some shown by bars, but there is here just one response variable cost, so I am at a loss to understand the logic there.


Synchronize of ScheduledFuture.cancel() method

Question: Code below is cutted example from "Programming Concurrency on the JVM: Mastering Synchronization, STM, and Actors" book
I don't understand why author synchronizing stopEnergySource method, which just cancels ScheduledFuture task, which represented by replenishTask variable? There are no other methods that use this variable.
Is it desirable practice to synchronize Future.cancel calls or it just needed for ScheduledFuture?
public class EnergySource {
  //...
  private static final ScheduledExecutorService replenishTimer =
    Executors.newScheduledThreadPool(10);
  private ScheduledFuture<?> replenishTask;

  private EnergySource() {}

  private void init() {
    replenishTask = replenishTimer.scheduleAtFixedRate(new Runnable() {
      public void run() { replenish(); }
    }, 0, 1, TimeUnit.SECONDS);
  }

  public static EnergySource create() {
    final EnergySource energySource = new EnergySource();
    energySource.init();
    return energySource;
  }

  public long getUnitsAvailable() {
    //...
  }

  public long getUsageCount() {
    //...
  }

  public boolean useEnergy(final long units) {
    //...
  }

  public synchronized void stopEnergySource() { // what for **synchronized** is?
    replenishTask.cancel(false);
  }

  private void replenish() {
    //...
  }
}

Comment: That does not make much sense...
Comment: The `ScheduledFuture` does not need that `synchronized` keyword. Even worse, if that's the only `synchronized` code inside that class, that synchronization has no effect which makes it even more misleading.
Comment: After looking at the full code, I can tell you that the usage of `AtomicLong` inside the `replenish()` method is also broken ("check-then-act" anti-pattern).
Comment: This is not very good code... I'd say it is a mistake.
Comment: So `Future.cancel()` do not need to be synchronized at all, or it depends?
Comment: Any feedback on my answer?
Answer:
There are no other methods that use this variable. Is it desirable practice to synchronize Future.cancel calls or it just needed for ScheduledFuture?

I believe that the author of the code is trying to force memory barriers in case a different thread is trying to call stopEnergySource() that started the job in the first place.
However, if this was the case then the init() method should also be synchronized because they are not doing a safe publishing of the replenishTask field.  That field is not final and the compiler is allowed to have create(...) return but continue the construction and initialization of the EnergySource object a later.
If multiple threads were creating and stopping these objects, you could easily get a NPE in stopEnergySource(...), even with the synchronized keyword on it.


When playing ice hockey and giving a pass at the blue line, who should go first?

Question: I didin't know how to clearly express my question, so here are a few explanation.
I'm currently playing in a small hockey club at a quite low level, and we always do this exercise where all the players are at one end of the rink (where the pucks are on the picture). One player on each side rushes to the blue line, only one having the puck. Then, each one crosses the other one behind the blue line, and the one who holds the puck gives it to the other one. Then, they enter the zone and shoot on the goalie. This exercise takes place on only one half of the rink. We often do this at warmup before a play.
So, my question is : which one of the two guys should be the closest to the attack zone when crossing the other one? The puck holder? The receiver?
On the picture, should 1 give it to 2 and wait a bit to avoid an offside, or should 2 give it to 1 for him to enter the zone quickly?
When we play, some say option #1, others say option #2, and it ends up in big "hugs" at the blue line, when we bump into each other. ;)

Sorry for my poor english...
Answer: I do this drill all the time in my hockey league.
If you think about a normal NHL style break out, the center usually takes the puck up ice, breaks the offensive zone, and then passes the puck to the trailing / waiting winger.
This exercise (though only being half the rink) is simulating that same play I mentioned above. It is simulating the center (in your case the player with the puck) entering the zone and passing it immediately to the winger (in your case the player without the puck).
Since this is simulating the well known "breakout" in hockey where the center skates in, breaks into the offensive zone and then passes the puck, in your scenario...

The person with the puck should cross over and enter the zone first
The center should then pass the puck to the trailing winger
The center should then rush the net
The winger should either shoot the puck or look for a cross crease pass directed towards the center (Not in your scenario but maybe something to take up with your coach)


Why is a batsman out, when the impact is outside off, on an umpire's call?

Question: Can a batsman be given out when the ball impacts outside the line, having pitched outside off and with an indication that it would have hit the stumps?
The original decision of the umpire on the field was Out, and the batsman made a referral to the Umpire Decision Review System.
Comment: Was the batsman playing a shot? What was the decision on the field? Did the umpire or the players instigate the review?
Comment: Yes, he was playing a shot, and the on-field decision was out. The batsman went for the review. There were two reds apart from the impact which was outside off.
Comment: Could you give more details of the specific incident you're referring to? As UDRS was available, I'm guessing it was a major match.
Comment: Yes it was during the 1st test between SL and Ind in Kolkatta few days ago. But I could not remember which instance though.
Answer: The ball neither needs to pitch nor strike inline, if it was coming from outside off into the stumps, in order to give Out, Leg before wicket.
This is the basis of the original decision. The two flags for Pitching - inline and Impact - inline only some green if they are actually inline, even though that is not always necessary for Leg before wicket. As long as the third and important flag (Wickets - hitting) is green, the correct decision is Out.
See Law 36, part 1.2 for the pitching and part 1.4 for the contact.
Note that this assumes "the striker has made no genuine attempt to play the ball with the bat". As this aspect of the law comes outside the scope of UDRS, it must be assumed the umpire decided no genuine attempt to play the ball was made.
Comment: @Kulasangar If the on-field umpire thinks the batsman wasn't playing a stroke and the ball wasn't leg side, then it's only the 'hitting' part of the DRS system that matters. If that says hitting, it's out, if it says missing it's not out, if that says umpire's call, then they keep the original decision.
Comment: Thanks @Nij. In order to clarify what you said, you mean that even though the impact is green when the other two **(pitching outside off and hitting the stumps)** are red, it'll be given out. If so, is it because of the umpire's call or the ball hitting the stumps?
Answer: @Kul if he was playing a shot, for him to remain out (i.e. On field call stays):

Ball needs to pitch in line with stumps or outside off stump (or can also be umpire's call, i.e. half pitching on leg stump, half pitching outside leg stump)
Impact must be in line with the stumps or umpire's call
The ball must hit the stumps or be umpire's call

If no shot was offered, the only change is:

Impact is irrelevant
The ball still cannot pitch outside leg stump (to avoid negative bowling creating a wicket)

I haven't actually seen this incident, but those are the scenarios. Hope this answers your question.


Inline sessions what are they?

Question: I just got back from a talk. I overheard the term "inline sessions" which should be an alternative to cookie sessions. Do you guys know what that is and if it can be implemented in PHP?
Answer: They are probably talking about sessions whose key is persisted through form or query string parameters.
PHP used to have a setting to enable this transparently. It would basically parse your HTML and add a  SESSID variable to the end of every href and form action.
This meant if cookies were disabled, the session could still be persisted.
I think things like Ajax has deprecated this functionality.
Comment: It's a bad idea to adopt inline sessions because they stump search engine spiders, giving the impression of effectively infinite duplicate content, which gets you a very bad ranking indeed.
Comment: i thought about this as well - google was 0 relevant links about this term, so thats probably it.

Inline sessions what are they?


How to make a webform block specific template?

Question: i would to make a custom tpl for a webform in a block.I get is ID but actually i can't it to works.what the way to do this ? what si the folder / files structure to do this ?
i'm on drupal 6 and webform 3.x
thanks
EDIT: this my code for node-webform.tpl

<div class="node<?php if ($sticky) { print " sticky"; } ?><?php if (!$status) { print " node-unpublished"; } ?>">

     <?php if ($title): /*insertion du titre de la page et style differencié*/?>

<?php print $title; ?>

    <?php endif; ?>

    <?php  print $node->field_image_deco_lycee[0]['view'] /*Image deco page lycee*/ ?>

     <?php if ($submitted) { ?>
    <?php print $submitted?>
  <?php }; ?>

    <?php print $node->content['body']['#value']; ?>

    <?php print $node->content['webform']['#value']; ?>

    <?php if ($links): ?>

 <?php print $links; ?>

  <?php endif; ?>

     <?php if ($terms) { ?>
    <?php print $terms?>
  <?php }; ?>

     <?php print $picture; ?>

           <?php if ($node->field_vue_actus_lycee[0]['view']): ?>

           <?php  print $node->field_vue_actus_lycee[0]['view'] /*Vue actus du lycée*/ ?>

           <?php endif;?>

    <?php if ($terms): ?>

<?php //print $terms; ?>

    <?php endif;?>

  <?php if ($picture) { print $picture; }?>

  <?php if ($page == 0) { ?>
    <?php if ($title) { ?>

<a href="<?php print $node_url?>"><?php print $title?>

    <?php }; ?>
  <?php }; ?>

Answer: You need to copy (not move) sites/all/modules/webform/templates/webform-form.tpl.php to sites/all/themes/yourTheme/templates/webform-form-nid.tpl.php (obviously replace yourTheme and nid) and clear caches.
Comment: is it block id the same as webform id in this case ?
Comment: Oh sorry, it should be the node id of the webform. But yes, what you said is correct. Editing my answer now.
Comment: actually i have a node-webform.tpl + webform-form.tpl files.It seem that if i wuould to make a specific webform tpl, i must add a page-webform-ID.tpl to my theme files,not ? what kind of files do you use to do this ?
Comment: As I said in my answer, you must copy the existing `sites/all/modules/webform/templates/webform-form.tpl.php` to `sites/all/themes/yourTheme/templates/webform-form-nid.tpl.php`. For instance, if your theme is called marinelli and your webform node id 100, the full path becomes `sites/all/themes/marinelli/templates/webform-form-100.tpl.php`.
Comment: yes i understand that, but i get issue because i'm using node-webform.tpl otherwise.i think about a conflict between node-webform and webform-form.Or perhaps i need to create both files for my webform block ?
Comment: No, you do not need node-webform.tpl.php at all.
Comment: ok,it's better but how can i add html + css to the webform-form.tpl  as i do with the node-webform.tpl ? because the webform-form.tpl is all php code inside..i edit the fist post to show what's in my node-webform.tpl
Comment: You can copy that (not move for testing purposes) to `sites/all/themes/yourTheme/templates/webform-form-nid.tpl.php` and clear caches. After making sure it works as expected, you can move node-webform.tpl.php elsewhere.
Comment: after testing, the form isn't display, so i go to find a code example for this kind of file.the tpl is the right one.But the others forms are not styled because node-webform is missing..
Comment: need to print the webform title into my webform-form-ID.tpl but i d'on't find how..someone knows ?
Comment: Why do you need to? You normally shouldn't.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/21403/discussion-between-kartagis-and-webmaster-pf).


How to allow for webpack-dev-server to allow entry points from react-router

Question: I'm creating an app that uses webpack-dev-server in development alongside react-router.
It seems that webpack-dev-server is built around the assumption that you will have a public entry point at one place (i.e. "/"), whereas react-router allows for an unlimited amount of entry points.
I want the benefits of the webpack-dev-server, especially the hot reloading feature that is great for productivity, but I still want to be able to load routes set in react-router.
How could one implement it such that they work together? Could you run an express server in front of webpack-dev-server in such a way to allow this?
Comment: I have an extremely hacky version of something here, but it is fragile and only allows simple routes to match: https://github.com/natew/react-base (see make-webpack-config) and (app/routes.js)
Answer: You should set historyApiFallback of WebpackDevServer as true for this to work. Here's a small example (tweak to fit your purposes):
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');

var config = require('./webpack.config');

var port = 4000;
var ip = '0.0.0.0';
new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    historyApiFallback: true,
}).listen(port, ip, function (err) {
    if(err) {
        return console.log(err);
    }

    console.log('Listening at ' + ip + ':' + port);
});

Comment: This should be the accepted answer. From the webpack dev server docs: _"If you are using the HTML5 history API you probably need to serve your index.html in place of 404 responses, which can be done by setting historyApiFallback: true"_ If I understand the question correctly this will solve the problem.
Comment: @smnbbrv No probs. It actually uses [connect-history-api-fallback](https://www.npmjs.com/package/connect-history-api-fallback) underneath and you can pass an object with the middleware specific options if you want  instead of just `true`.
Comment: OR if you're using the cli, `webpack-dev-server --history-api-fallback`
Comment: You will miss the statusbar on top of your index.html, but this works great :)
Comment: Any idea how to do this with webpack-dev-middleware?
Comment: @DonnyP webpack-dev-middleware doesn't do anything do anything with connect-history-api-fallback so you will have to connect it separately to your setup.
Comment: The comment from @Levi comment, above, worked for me!
Comment: Awesome, thank you! For those also using webpack.config.js, just add the "historyApiFallback: true" to the "devServer" object
Answer: I set up a proxy to achieve this:
You have a regular express webserver that serves the index.html on any route, except if its an asset route. if it is an asset, the request gets proxied to the web-dev-server
your react hot entrypoints will still point directly at the webpack dev server, so hot reloading still works.
Let's assume you run webpack-dev-server on 8081 and your proxy at 8080. Your server.js file will look like this:
"use strict";
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./make-webpack-config')('dev');

var express = require('express');
var proxy = require('proxy-middleware');
var url = require('url');

## --------your proxy----------------------
var app = express();
## proxy the request for static assets
app.use('/assets', proxy(url.parse('http://localhost:8081/assets')));

app.get('/*', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

# -----your-webpack-dev-server------------------
var server = new WebpackDevServer(webpack(config), {
    contentBase: __dirname,
    hot: true,
    quiet: false,
    noInfo: false,
    publicPath: "/assets/",

    stats: { colors: true }
});

## run the two servers
server.listen(8081, "localhost", function() {});
app.listen(8080);

now make your entrypoints in the webpack config like so:
 entry: [
     './src/main.js',
     'webpack/hot/dev-server',
     'webpack-dev-server/client?http://localhost:8081'
 ]

note the direct call to 8081 for hotreload
also make sure you pass an absolute url to the output.publicPath option:
 output: {
     publicPath: "http://localhost:8081/assets/",
     // ...
 }

Comment: It would be easier just to use a built-in [webpack proxy](https://webpack.github.io/docs/webpack-dev-server.html#proxy) instead. Thus you don't interfere in the server itself, you leave the server _pure_. Instead, you just do a little (3-5 lines) addition to webpack config. Thanks to that you modify only dev scripts for dev purposes and leave the production code (server.js) in peace (unlike in your version) and imo that's the proper way to go.
Comment: This answer is still correct though a bit dated. More straightforward ways are available now, look for `historyApiFallback`.
Comment: One question, sort of unrelated so I can open a new question if need be but I notice that now the console output from the webpack dev server isn't streamed.  Before, you could watch it compile and see the percents rise, now it just block outputs after compilation.
Comment: Nice done. This is exactly how it should be done. I added a note about the `output.publicPath` option, which should be an absolute url too.
Comment: Thanks, what do you have in assets? In my case the bundle.js dir is called `dist`. I'll keep it as that unless anything else is supposed to go in there? My app is in a folder called `app` - should they be in the same place?
Comment: This fixes the issue: 'webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr', found @ https://github.com/glenjamin/webpack-hot-middleware/issues/37
Comment: how do you make the `server.js` clean for production use?
Comment: @jalooc that is interesting to me. My understanding is that from a `package.json` script command you run `webpack-dev-server` using some `webpack.dev.config` where you specify the `devServer.proxy` option to point to your original local express server. But how do you start both webpack-dev-server **and** your express server from package.json script command?
Comment: @superjos in this case the express server is started independently of webpack. But of course you can join the two commands with something like `&&` and put it to package.json.
Comment: thanks for quick reply. In the meantime I found other answers mentioning [parallelshell](https://www.npmjs.com/package/parallelshell). `&&` as it is would not work in that case.
Comment: @jalooc that sounds interesting, why don't you offer it as an answer rather than a comment?
Comment: This is the best approach I've seen. Thanks for sharing.
Also, what are the last two entries in the entry array for? I left them out and everything seems to work fine
Answer: For anyone else that may still be looking for this answer.  I put together a simple proxy bypass which achieves this without much hassle and the config goes into the webpack.config.js
I am sure there are much more elegant ways to test for local content using regex, but this works for my needs.
devServer: {
  proxy: {
    '/**': {  //catch all requests
      target: '/index.html',  //default target
      secure: false,
      bypass: function(req, res, opt){
        //your custom code to check for any exceptions
        //console.log('bypass check', {req: req, res:res, opt: opt});
        if(req.path.indexOf('/img/') !== -1 || req.path.indexOf('/public/') !== -1){
          return '/'
        }

        if (req.headers.accept.indexOf('html') !== -1) {
          return '/index.html';
        }
      }
    }
  }
}

Comment: Thanks for the code! Is there a difference between this and just adding "historyApiFallback: true" to the same devServer object? (outside from the obvious of being able to further customize it). Just curious
Answer: If you're running webpack-dev-server using CLI, you can configure it through webpack.config.js passing devServer object and using the historyApiFallback option:

module.exports = {
  entry: "index.js",
  output: {
    filename: "bundle.js"
  },
  devServer: {
    historyApiFallback: true
  }
}

This will redirect to index.html everytime it 404 is encountered.
NOTE: If you're using publicPath, you'll need to pass it to devServer too:

module.exports = {
  entry: "index.js",
  output: {
    filename: "bundle.js",
    publicPath: "admin/dashboard"
  },
  devServer: {
    historyApiFallback: {
      index: "admin/dashboard"
    }
  }
}

You can verify that everything is setup correctly by looking at the first few lines of the output (the part with "404s will fallback to: path").
Answer: For a more recent answer, the current version of webpack (4.1.1) you can just set this in your webpack.config.js like such:
const webpack = require('webpack');

module.exports = {
    entry: [
      'react-hot-loader/patch',
      './src/index.js'
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: ['style-loader','css-loader']
            }
        ]
    },
    resolve: {
      extensions: ['*', '.js', '.jsx']
    },
    output: {
      path: __dirname + '/dist',
      publicPath: '/',
      filename: 'bundle.js'
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ],
    devServer: {
      contentBase: './dist',
      hot: true,
      historyApiFallback: true
    }
  };

The important part is historyApiFallback: true. No need to run a custom server, just use the cli:
"scripts": {
    "start": "webpack-dev-server --config ./webpack.config.js --mode development"
  },

Answer: I'd like to add to the answer for the case when you run an isomorphic app (i.e. rendering React component server-side.)
In this case you probably also want to automatically reload the server when you change one of your React components. You do this with the piping package. All you have to do is install it and add require("piping")({hook: true}) somewhere in the beginning of you server.js. That's it. The server will restart after you change any component used by it.
This rises another problem though - if you run webpack server from the same process as your express server (as in the accepted answer above), the webpack server will also restart and will recompile your bundle every time. To avoid this you should run your main server and webpack server in different processes so that piping would restart only your express server and won't touch webpack.
You can do this with concurrently package. You can find an example of this in react-isomorphic-starterkit. In the package.json he has:
"scripts": {
    ...
    "watch": "node ./node_modules/concurrently/src/main.js --kill-others 'npm run watch-client' 'npm run start'"
  },

which runs both servers simultaneously but in separate processes.
Comment: Does this mean some files are being watched twice? Such as the shared isomorphic/universal files?
Answer: historyApiFallback can also be an object instead of a Boolean, containing the routes.
historyApiFallback: navData && {
  rewrites: [
      { from: /route-1-regex/, to: 'route-1-example.html' }
  ]
}

Answer: May be not in all cases, but seems the publicPath: '/' option in the devServer is easiest solution to fix deep routes issue, see: https://github.com/ReactTraining/react-router/issues/676
Answer: This worked for me: just simply add the webpack middlewares first and the app.get('*'... index.html resolver later,
so express will first check if the request matches one of the routes provided by webpack (like: /dist/bundle.js or /__webpack_hmr_) and if not, then it will move to the index.html with the * resolver.
ie:
app.use(require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
}))
app.use(require('webpack-hot-middleware')(compiler))
app.get('*', function(req, res) {
  sendSomeHtml(res)
})


Como exibir formulário de um BD Access diretamente em um site?

Question: Quero colocar as informações de um <code>.mdb</code> em um site, para disponibilizá-lo ao público.
Quando aberto no Access, possui formulários para realizar consultas.
Eu posso ter um site que exibe diretamente esses formulários na tela?
Ou eu teria que criar novos formulários e puxar as informações diretamente das consultas?
Comment: É possível se você usar Sharepoint.
Comment: Mas no SharePoint é necessário ser um usuário, não? Parece que não é possível ter acesso anônimo, e eu precisaria disso para abrir para o público em geral.
Comment: Você pode disponibilizar para acesso anônimo. Porém o Sharepoint não é tão "acessível" pois você precisa investir no seu ambiente ou usar o Sharepoint online (que não é algo muito barato)
Comment: Estou vendo aqui que o SharePoint online cobra por usuário. Quer dizer que eu vou ter que pagar por cada usuário que fizer acesso anonimamente?
Comment: Infelizmente não conheço muito o Sharepoint online, não sei te responder.
Comment: Se a estrutura não é grande e sua demanda de acesso for baixa converta sua base para o sql express ou my-sql, o access não foi feito para acesso via web.
Comment: Pretende abrir um formulário de consulta ou para preencher com dados na base de dados?
Answer: Pelo que entendi você gostaria de exibir o formulário access diretamente em uma página web em ASP correto?
Se for isso digo que não é possível, o que você pode fazer é converter os dados seja de uma tabela ou consulta do access para o formato HTML estático podendo escolher um modelo de documento HTML ou usar o layout próprio do access, para isso bastando apenas clicar com o botão direito do mouse em cima da tabela/consulta e selecionar exportar dados para o formato HTML.
Agora se você quiser algo dinâmico, você pode criar um servidor vinculado no SQL SERVER com seu MDB e a partir dai criar relatórios com o REPORTING SERVICES e disponibilizá-los no seu site.


How to use SAX to get CDATA content

Question: I'm trying to parse a big XML file to get all outer XML tag content, something like this:
<string name="key"><![CDATA[Hey I'm a tag with & and other characters]]></string>

to get this:
<![CDATA[Hey I'm a tag with & and other characters]]>

Although, when I use Nokogiri's SAX XML parser I only get the text without CDATA and with characters escaped, like this:
Hey I\'m a tag with & and other characters

This is my code:
  class IDCollector < Nokogiri::XML::SAX::Document
    def initialize
    end

    def characters string
        puts string # this does not works, CDATA tag is not printed
    end

    def cdata_block string
      puts string
      puts "<![CDATA[" + string + "]]>"
    end
  end

Is there any way to do this with Nokogiri SAX?
Comment: It's not exactly clear what you're trying to do: read or generate the CDATA block? You won't get `Hey I'm a tag with & and other characters` because it's a block, not a tag or element. `<![CDATA[` is effectively the tag but it's processed out and only its content is returned.  http://stackoverflow.com/q/2784183 might help. I can't duplicate getting the encoded result.
Comment: My final goal is to port some xml tags with their inner content to other files. Although, both file large and I have to use SAX or else I have an memory exception
Answer: It's not clear what you're trying to do, but this might help clear things up.
A <![CDATA[...]]> entry isn't a tag, it's a block, and is treated differently by the parser. When the block is encountered the <![CDATA[ and ]]> are stripped off so you'll only see the string inside. See "What does <![CDATA[]]> in XML mean?" for more information.
If you're trying to create a CDATA block in XML it can be done easily using:
doc = Nokogiri::XML(%(<string name="key"></string>))
doc.at('string') << Nokogiri::XML::CDATA.new(Nokogiri::XML::Document.new, "Hey I'm a tag with & and other characters")
doc.to_xml # => "<?xml version=\"1.0\"?>\n<string name=\"key\"><![CDATA[Hey I'm a tag with & and other characters]]></string>\n"

<< is just shorthand to create a child node.
Trying to use inner_html doesn't do what you want as it creates a text node as a child:
doc = Nokogiri::XML(%(<string name="key"></string>))
doc.at('string').inner_html = "Hey I'm a tag with & and other characters"
doc.to_xml # => "<?xml version=\"1.0\"?>\n<string name=\"key\">Hey I'm a tag with & and other characters</string>\n"
doc.at('string').children.first.text # => "Hey I'm a tag with & and other characters"
doc.at('string').children.first.class # => Nokogiri::XML::Text

Using inner_html causes HTML encoding of the string to occur, which is the alternative way of embedding text that could include tags. Without the encoding or using CDATA the XML parsers could get confused about what is text versus what is a real tag. I've written RSS aggregators, and having to deal with incorrectly encoded embedded HTML in a feed is a pain.
Comment: Actually I prefer this (Nokogiri::XML::CDATA.new) to what I answer. Also, thanks for the described answer it helped :)
Answer: After a while checking the documentation, I think this is only possible by building a new CDATA content with the help of Nokogiri, something like this:
  tmp = Nokogiri::XML::Document.new
  value = tmp.create_cdata(value)
  r = doc.at_xpath(PATH_TO_REPLACE)
  r.inner_html = value

How to use SAX to get CDATA content


Reconciling sample size calculations using Cochran's formula and Wald test

Question: This is quite a basic question but I could not find a clear answer elsewhere.
If we wish to draw a simple random sample to determine the estimated proportion of an attribute in the population, given a desired level of precision and confidence level, the Cochran's formula is often used:

This formula says that a sample of N= 384 is needed to estimate the prevalence at 95% CI and 5 pp Margin of Error (assuming null p = 0.5).
However, Stata has no direct command for a Cochran's formula sampling. Instead, one can use the Wald test comparing a proportion to a reference value as below:
Code:
<code>power oneproportion 0.5 0.55, test(wald) continuity
</code>
The above command gives an N of 797, for the same level of precision and Margin of Error.
Clearly, I am misunderstanding something here. Could you please help? Thanks!
Answer: You can find the equations used by Stata at https://www.stata.com/manuals/pss.pdf (page 710). The difference with Cochran formula is that Stata uses 2*z(1-a/2) for two-sided CI's and z(1-a) for one-sided CI's. Now, if anyone could give references supporting Stata's variation over Cochran formula, I would be truly grateful.


onFlush listener, getting entity Id for a scheduled entity insertions

Question: I have a listener for onFlush event.
public function onFlush(OnFlushEventArgs $args) {
   $em = $args->getEntityManager();
   $uow = $em->getUnitOfWork();
   foreach ($uow->getScheduledEntityInsertions() as $entity) {
     $id = ...
   }
}

I would like to get the Id of the $entity. If I call getId() then return null. Is there any way to finish the flushing inside this listener and get the $entity's Id?
Thank you advance
Comment: If the database is generating the id then there won't be an id until **after** the entity has been inserted.
Comment: The database generates the id, but I don't know that "onFlush" event is before or after database writing operation.
Comment: You should use [postFlush](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#postflush)
Comment: I tried postFlush, but I can't find a way how to identify new entities there. Do you know how to decide is it a created/new entity or not?
Comment: we looked for the same a while ago and didn't manage it via a listener, so our services are handling that right now.
Comment: It depends on your logic. Why do you need to know if an entity is a new one?
Comment: I want to write into log table every times when entity created/modified/deleted and I need to know which entity had effected
Comment: Look at http://stackoverflow.com/questions/28589633/symfony2-doctrine-postflush
Comment: @VladimirCvetic there is no solution there, only theorical debutes, am I right?
Answer: Accessing the ID before the SQL INSERT command is executed is impossible but you can access the MySQL table's auto increment value with some tricky ways like this:
$classMeta = $em->getClassMetadata($className);
if ($classMeta->rootEntityName !== $className) {
    // if the Entity is inherited, only root entity table may have auto increment ID
    $classMeta = $em->getClassMetadata($classMeta->rootEntityName);
}
$tableName = $classMeta->getTableName();

$conn = $em->getConnection();
$stmt = $conn->prepare("SHOW TABLE STATUS LIKE '".$tableName."'");
$stmt->execute();
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
$id = $result['Auto_increment'];

Be aware using this:

this solution is hacky, auto increment value may differ from inserted ID
your MySQL user must have permission to run this SQL command
Comment: yeah, it's very close to a good solution, and it's works most cases (95%) but as you mentioned before, auto increment may be different fromt the value you've asked from the query. But it's a good point, thank you!
Answer: I resolved the problem of missing IDs in onFlush by creating 2 hooks: onFlush and postFlush. The onFlush collects the entities directly (PHP copies pointers, not objects in memory), so after UOW is done with insertions, the IDs appear in the objects.
Therefore
public function onFlush(OnFlushEventArgs $eventArgs): void
    {
        $objectManager = $eventArgs->getObjectManager();
        $uow = $objectManager->getUnitOfWork();

        $this->dataSyncQueuer->handleEntityUpserts($uow->getScheduledEntityInsertions());
...

This is how you can store the insertions in onFlush:
private function promiseUpsertOperation(object $entity): void
    {
        $this->queue[] = function () use ($entity) {
            $this->wallFeedStorage->upsert($entity);
        };
    }

This is what you do later in postFlush:
public function postFlush(PostFlushEventArgs $eventArgs): void
    {
        $queue = $this->queuer->getQueue();

        foreach ($queue as $closure) {
            $closure();
        }
    }

Works for me!


Which is the equivalent of php drupal format_interval for javascript?

Question: I want to use with JavaScript and Drupal.t() the equivalent of format_interval().
With PHP I would use the following code.
print t("!date ago", array("!date" => format_interval(time() - $lastActivity, 1)));

What would the equivalent in JavaScript be?
Comment: The `t` method is a Drupal text sanitizing and translating equivalent to the `t()` PHP function from Drupal core.
Answer: Drupal doesn't implement a JS version of format_interval(); this is a rough (minimally tested) port:
Drupal.formatInterval = function(interval, granularity, langcode) {
  granularity = typeof granularity !== 'undefined' ? granularity : 2;
  langcode = typeof langcode !== 'undefined' ? langcode : null;

  var units = {
    '1 year|@count years': 31536000,
    '1 month|@count months': 2592000,
    '1 week|@count weeks': 604800,
    '1 day|@count days': 86400,
    '1 hour|@count hours': 3600,
    '1 min|@count min': 60,
    '1 sec|@count sec': 1
  },
  output = '';

  for (var key in units) {
    var keys = key.split('|');
    var value = units[key];
    if (interval >= value) {
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), keys[0], keys[1], {}, { langcode: langcode });
      interval %= value;
      granularity--;
    }

    if (granularity == 0) {
      break;
    }
  }

  return output.length ? output : Drupal.t('0 sec', {}, { langcode: langcode });
}

Some random results using the above (they seem to match up to the PHP function as expected):

3643       => 1 hour 43 sec
92900      => 1 day 1 hour
2592000    => 1 month
9331200    => 3 months 2 weeks
297605232  => 9 years 5 months
Answer: Clives implementation is doing well. However, Drupals javascript aggregator needs to parse all javascript files for translatable strings.
As Clive uses dynamic values for Drupal.formatPlural this won't work here.
So here's another implementation with working translation:
Drupal.formatInterval = function(interval, granularity) {
  granularity = typeof granularity !== 'undefined' ? granularity : 2;
  output = '';

  while (granularity > 0) {
    var value = 0;
    if (interval >= 31536000) {
      value = 31536000;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 year', '@count years');
    }
    else if (interval >= 2592000) {
      value = 2592000;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 month', '@count months');
    }
    else if (interval >= 604800) {
      value = 604800;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 week', '@count weeks');
    }
    else if (interval >= 86400) {
      value = 86400;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 day', '@count days');
    }
    else if (interval >= 3600) {
      value = 3600;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 hour', '@count hours');
    }
    else if (interval >= 60) {
      value = 60;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 min', '@count min');
    }
    else if (interval >= 1) {
      value = 1;
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), '1 sec', '@count sec');
    }

    interval %= value;
    granularity--;
  }

  return output.length ? output : Drupal.t('0 sec');
}


Unable to start PostgreSQL

Question:
could not connect to server: No such file or directory    Is the server
  running locally and accepting connections on Unix domain socket
  "/var/run/postgresql/.s.PGSQL.5432"?

I uninstalled and installed postgresql but nothing works for me.
$ sudo service postgresql start
 * Starting PostgreSQL 10 database server
 * Failed to issue method call: Unit email@example.com failed to load: No such file or directory. See system logs and 'systemctl status email@example.com' for details.

systemctl status postgresql
Failed to issue method call: No such interface 'org.freedesktop.DBus.Properties' on object at path /org/freedesktop/systemd1/unit/postgresql_2eservice

$ psql -V
psql (PostgreSQL) 10.4 (Ubuntu 10.4-2.pgdg14.04+1)

Comment: Make sure you add your server to your `PostgreSQL\9.4\data\pg_hba.conf` file
Comment: What was the issue, did u solve it. I have exacly the same problem
Comment: I am facing the same issue. Does anybody know the answer?
Comment: Is it a new installation or an upgrade? Is this on linux? I also advise to move the question to https://dba.stackexchange.com/ since the question is not related to programming.
Comment: @Salini I answered the question.
Comment: @Salini - if you are encountering this issue in Windows, see [Unable to connect to server: postgresql...](https://stackoverflow.com/questions/51954332/unable-to-connect-to-server-postgresql-on-ubuntu-in-windows-subsystem-for-linux/51955476#51955476)
Answer: This problem /var/run/postgresql/.s.PGSQL.5432 is about permission,
did you change the database directory?
if yes so you need to give write and read permission to the postgres
sudo chown -R postgres:postgres <directory_path>

or

sudo chmod -R 777 <directory_path>

case you cannot use remote access, on pg_config edit this line listen_addresses = 'localhost' to listen_addresses = '*'
and in the pg_hba.conf insert this line:
host    all  all  0.0.0.0/0  md5

Unable to start PostgreSQL


Too many notes in measure?

Question: I'm composing a song. The song is in 4/4. In the bass clef, I have two half notes, one occurring on beat one and the other on beat three. Since each note rings out for half of the measure, I want to put in a quarter on beats two and four. This will make six beats, though--won't it? I thought of perhaps putting quarter rests on beats one and three beside the quarter notes to show that they are separate voices. I don't know if that will work. I'm confused. Can you help me?
Answer: Yes, that's basically how having two voices on one stave works.
Comment: Tried to edit your great answer @LaurencePayne but the edit was too short to be accepted. Isn't the singular form 'staff' and the plural 'staves'?
Comment: Depends where you are.  For some reason I (in London, UK) chose the American form!

Too many notes in measure?


How do I insert only unique elements in array using Prisma for MongoDB?

Question: I have written a query to insert an ID into an array field. It's possible that users try to click twice, or anyhow that the same ID can be inserted twice, which is what I want to avoid. It was possible to achieve this using native MongoDB, but I am not able to find how to do this using Prisma. Below is my code. Any help will be appreciated!
<code>await this.prisma.finderEntity.upsert({
                where: { userId },
                create: {
                    ...body,
                    isActive: true,
                    isDeleted: false,
                    missingItemIds: [missingItemExists.id],
                },
                update: {
                    missingItemIds: {
                        push: missingItemExists.id,
                    },
                },
            })
</code>
Answer: in your prisma schema you just have to have to add an
@@unique annotation on the wanted property or properties.
Your question is not really accurate but I believe you will find better explanations then I can give you here :
Prisma article about working with id/unique constraint
Comment: I did not use the @unique annotation on the array field, also unsure if it can be used like that. I will add it, test it, and let you know. Thank you


Maximum clique in intersection graph of $3$-element subsets of a $9$-element set?

Question:
How big is the largest collection of $3$-element subsets of $\{1,\ldots,9\}$ such that every pair of sets intersects nontrivially?

I have a hard time visualizing the problem, or getting a grip on it. I
have found a few lower and upper bounds in different ways, the
tightest I can get is that it is between $28$ and $44$, but every slight sharpening requires increasingly tedious work. Is there a better approach than brute-forcing
this with a computer or many hours of paperwork?
Bonus question: Is there any nice construction of such a maximal collection of subsets?
Answer: The general theorem you are looking for here is the Erdős–Ko–Rado theorem, which states that for $n \geq 2r$, the largest size of an intersecting family of $r$-element subsets of $\{1, \ldots, n\}$ is ${n-1 \choose r-1}$.
Answer: You can solve the problem via integer linear programming as follows.  Let binary decision variable $x_i$ indicate whether node $i$ is selected. Let $E$ be the edge set. The problem is to maximize $\sum_i x_i$ subject to linear constraints $x_i + x_j \le 1$ for $i < j$ with $(i,j)\not\in E$.
28 turns out to be optimal:
<code>259 100000011
261 100000101
262 100000110
265 100001001
266 100001010
268 100001100
273 100010001
274 100010010
276 100010100
280 100011000
289 100100001
290 100100010
292 100100100
296 100101000
304 100110000
321 101000001
322 101000010
324 101000100
328 101001000
336 101010000
352 101100000
385 110000001
386 110000010
388 110000100
392 110001000
400 110010000
416 110100000
448 111000000
</code>
Comment: Hmm, why the downvote? This answer provides both a solution approach and an optimal solution.


Peer to peer communication over internet implementation in java

Question: I am trying to build a system in java, where one computer acts as the server and the other one as the client and connect them together (i.e send data b/w them) on the public network. Here is my pseudo code -
Server.java
<code>ServerSocket server = new ServerSocket(55955);
Socket socket = server.accept();
</code>
Client.java
<code> Socket socket = new Socket("<ip address of server>", 55955);
//code to send and receive response from server
</code>
The code works fine if I have my server and client running on my computer.But if i run the server on a different machine (a friend's pc on the internet) and try to use that ip on the client running my machine, its not working. I did a lot of googling and did not find a appropriate solution other than opening up  the firewall or ports on the machine.

Is there any other option to connect b/w the computers on the internet without any forwarding or opening the ports ?
There are a few peer to peer systems (eg: skype)etc that does the same thing I am trying to achieve (and in my best of my knowledge its without opening any ports on the host machine). Please correct me if I am wrong.

Thank you.
Comment: 1. Connection without forwarding/opening could be possible if this specific machine is exposed to the Internet without any protection by firewall or NAT - and this is almost improbable nowadays. 2. Skype uses TCP port 443 which is just open by default.
Comment: these links https://stackoverflow.com/questions/1694144/can-two-applications-listen-to-the-same-port  https://serverfault.com/questions/653513/how-to-handle-multiple-apps-via-port-443  provide some details how this can be done.
Comment: @AlexRudenko Thank you. Sorry I am newbie on networking. One question that arise to my mind is that if it listens on tcp port 443, how can it differentiate b/w other requests. For eg: If I have another application such as Zoom, which also listens on port 443. How can we differentiate ?
Comment: Thank you. TCP or UDP hole punching will help me.
Answer: Thank you. I am adding the solution which I was finally able to work with.
This can be achieved using NAT Hole punching.
Found these awesome articles which explains the approach.

Peer-to-Peer Communication Across Network Address Translators
How Skype gets around firewalls


Trigonometric problem: $2^{\sin{x}} + 2^{\cos{x}} \ge 2^{(1-1/{\sqrt2})}$

Question: Show that:
$$\large2^{\sin{x}} + 2^{\cos{x}} \ge 2^\left({1-\frac{1}{\sqrt{2}}}\right)$$
This looks like an am gm problem to me where we should be using the fact that am is more that or equal to gm but I am having problem solving this equation after this:
$\large\left(2^{\sin{x}} + 2^{\cos{x}}\right)/2 \ge \sqrt{2^{\sin{x}+\cos{x}}}$
Please solve the sum step wise. Thanks
Answer: By the am-gm inequality,
\begin{align}
\frac{2^{\sin x}+2^{\cos x}}{2}
&\ge 2^{\frac{1}{2}(\sin x+\cos x)}\\
\end{align}
Multiplying both sides of the inequality by $2$ yields
$$2^{\sin x}+2^{\cos x}\ge2\cdot 2^{\frac{1}{2}(\sin x+\cos x)}$$
Since $\color\red{\sin{x}+\cos{x}=\sqrt{2}\sin(x+\pi/4)}$, we have
\begin{align}
RHS
&=2\cdot2^{\frac{1}{2}(\sin{x}+\cos{x})}\\
&=2^{1+\frac{1}{\sqrt{2}}\sin(x+\pi/4)}\\
&\ge2^{1-\frac{1}{\sqrt{2}}}
\end{align}
as $-1\le \sin(x+\pi/4)\le 1.$
Hence
$$\color\red{2^{\sin x}+2^{\cos x}}\ge 2^{1+\frac{1}{\sqrt{2}}\sin(x+\pi/4)}\ge \color\red{2^{1-\frac{1}{\sqrt2}}}$$
Comment: Sir I can't understand the last step of the solution .
Comment: 2⋅212(sinx+cosx)=21+12√sin(x+π/4)≥21−12√
Hence
2sinx+2cosx≥21−12√
Comment: I have edited the answer. Let me know if you still have doubts.
Answer: Deriving to find the extrema, you get
$$\ln2\cos x\ 2^{\sin x}-\ln2\sin x\ 2^{\cos x}=0,$$
which has the obvious solutions $\sin x=\cos x$, i.e. $x=\frac\pi4+k\pi$.
The corresponding function values are $2\ 2^{\pm1/\sqrt2}$, of which the smallest is $2^{(1-1/\sqrt2)}$. The bound is tight.
(Remains to prove that these are the only roots.)
Comment: I am sorry I don't know extrema so I can't understand your answer.


The initial phrase in Mozart's Alla Turca

Question: In the initial phrase, if I just saw the melody, I would have been sure that, in the third full measure, the melody switches to (V). Yet the accompaniment stays firmly in (i) and it sounds great. Does this technique have a name and why does it sound so good? Are there any other well-known pieces that do that?
Comment: It could be that it stays in `i` because that makes it sound more like the style of Turkish music that Mozart sought to evoke.
Answer: In general, the stubborn keeping of one (often, but not always, bass-) note/harmony against melodies that don't really fit on it is called pedal point.
But I definitely would hesitate to call this a pedal. What's actually going on is that Mozart is (arguably, rather bluntly) appropriating the stereotypical "eastern" double harmonic minor scale, which has a characteristic ♯ⅳ degree whilst clearly being in minor (definitely not Lydian). In fact, notice how the last beat in bar two literally clashes C and E with D♯, which is enharmonic to a minor and major third simultaneously:
X:1
L:1/16
M:2/4
K:C
%%score T1 B
V:T1           clef=treble
V:B            clef=bass
% 1
[V:T1] z4       (fe"!"^de    | .b2)
[V:B]  (A,2.[C2E2]) .[C2E2].[C2E2] | A,2

That's something that doesn't really happen in classical music (ever?).
What happens a lot in classical music though is that sharpened degrees are used as leading notes into another tonic. Specifically here, Mozart is no doubt playing with the listener's expectation that the ♯ⅳ note should lead to the dominant, like
X:1
L:1/16
M:2/4
K:C
%%score T1 B
V:T1           clef=treble
V:B            clef=bass
% 1
[V:T1] z4       (fe^d2)          | e4
[V:B]  (A,2.[C2E2]) .[C2E2](B,A,) | (^G,2.[B,2D2]) .[B,2D2].[B,2D2]

and as you noticed the melody seems to confirm that by going into B·A·G♯, but not really – actually the whole bar 3 acts more like a mere turn ornament on the note A, as it were
X:1
L:1/16
M:2/4
K:C
%%score T1 B
V:T1           clef=treble
V:B            clef=bass
% 1
[V:T1] z4       (fe^f^g)    | !turn!a4 !turn!a4
[V:B]  (A,2.[C2E2]) .[C2E2].[C2E2] | (A,2.[C2E2]) .[C2E2].[C2E2]

Comment: Also, most lower neighbors (classically) are half steps below the main note and usually requires the lower note to be sharped. An exception is the lower neighbor to scale step 7. (I've never found that lower neighbor to sound good sharped or not.) A whole step lower neighbor gives a kind modal feel to an ornament.
Comment: You mean ⅵ? That would probably be heard as ♭ⅶ instead.
Comment: @leftaroundabout it can't be ♭ⅶ if it's the lower neighbor of ⅶ.
Comment: "That's something that doesn't really happen in classical music (ever?)": it's not particularly uncommon, but it's also not what's happening here: the harmony is A minor, so it's an augmented fourth and a perfect fifth simultaneously, not a minor and major third. But the augmented fourth arises as a chromatic lower neighbor: an embellishment, not a structural tone. For one part to have such an embellishment while another part holds the structural tone is unremarkable.
Comment: As an example: Bach's cantata BWV 4, *Christ lag in Todesbanden* has, in the second movement (Verse 1), measure 12, at the second half of beat 4, the pitches A2, F#3, D4, E4, A4, and D#5 sounding sumultaneously, the last as a chromatic lower neighbor of E5.
Comment: @phoog the "doesn't...happen in classical" referred to the blue-note interpretation. – Yes, the augmented fourth is perfectly unspectacular, however I disagree about the embellishment bit. A tight chromatism of ♭6-5-♯4 _was_ still something of a weirdness in Mozart's time. Sure, you find tons of that in Tchaikovsky or so, but that was later on. — As for the Bach example: first off, I don't see any D♯ in that bar, are you maybe misreading the original score with all those weird movable C-clefs? –but even if, that's still nothing as overtly pseudo-oriental as what Mozart did in the Rondo.
Comment: @leftaroundabout the D# is in the second violin part, the next to last note (the score I'm reading only uses C clefs for the viola parts). I chose that movement to look for an example because of the violin figure's similar shape to the sonata (with a rest in place of the upper neighbor). But there are plenty of earlier examples of chromatic upper and lower neighbors in close proximity. The first movement of Bach's wedding cantata (202) has more than one example (mm 6-7, m 31). For a Mozart example, see the cadence of the *Rex tremendae* in the *Requiem.*
Answer: The melody of the first four bars is firmly based on A minor. Each of the sixteenth-note turns starts one note above the main note, and the main notes form an A minor triad. The only slightly unusual note is the D sharp, but that in combination with the F gives the piece the "Turkish" flavor.
Answer: The melodic line in the first 4 bars is built on an A minor triad. Here you can see how it appears in the urtext:
Comment: @leftaroundabout they did, in this context.  In some contexts they played it like a normal eighth note. Why do you think it silly?
Comment: They probably wrote it that way to make the harmonic structure clear.
Comment: Good point! And, I've often wondered if Mozart and his contemporaries really played such appogiature _just like a normal sixteenth_. That always seemed silly to me.
Comment: OP here. This answer makes sense from mostly a theoretical point of view. But from the practical point of view that reflects how the piece is played, the downbeat notes in the third phrase are (leap from an upbeat E)  B G# B G#. If that's not the E chord with some decorations in-between...
Comment: @phoog because then _why not just write a sixteenth_? Although, yeah, "make the harmonic structure clear" is actually a good enough reason. Still – how certain is the historical record actually on this, did they literally recommend to replace the graces with full sixteenths to students?
Comment: @Wynne I don't see how your comment is any less theoretical or more practical than the previous comments. We are all talking theory here -- and there's nothing wrong with that! The LH makes it clear that the chord is still A minor in this bar. In this context, the Bs and G#s are accented non-harmony notes. Just like the earlier Bs, G# and D in the tune.
Comment: @Wynne the figure B-A-G♯-A has A as the center, so the A is quite strong so you do not need to look at it as an E chord.
Comment: @leftaroundabout - The small initial appoggiatura 16th notes (and 8th notes) I've seen, like in the picture, are typically not accented, unlike the usual first notes of beats. Now *that's* a way to interpret this passage....
Comment: @LaurencePayne indeed, I have heard that grace notes were used to avoid violating some rule or other of counterpoint (which probably is roughly the same as "making the harmonic structure clear").
Comment: @leftaroundabout see my previous comment.  As to the historical record, see page five of https://www.google.com/books/edition/Guida_di_musica_being_a_complete_book_of/9m4jsXTuQScC, which was published a year after the sonata in question.  The grace note takes half the value of an undotted note and two thirds of the value of a dotted note (allowing for an engraving error on the explanation of the appoggiatura applied to a quarter note).
Comment: @Dekkadeci on the contrary, because it occurs on the strong part of the beat, an appoggiatura generally *is* supposed to be accented, at least in the 18th century.
Answer: Yes, it could go to E7 in bar 3.  But it stays on Am instead.  And all we can really say about that is 'composer's choice'.  Both are fine.   And a few other moves would have been fine too.
This parsimonious use of harmonies is characteristic of early Classical music. The longer you stay on one chord, the more dramatic when you eventually DO use another one - even one as seemingly obvious as a V.   Simple, and clever.


Amazon S3 - Cloudfront & Heroku CSS not rendering

Question: i have successfully made asset pipeline setup on Heroku with Amazon S3. All link are OK, files are uploaded on S3, Bucket is shared like distribution, you can click and open file...
I checked content type on amazon and it is text/css ....
But CSS want render o_O ...
Here is the link: http://stormy-mist-3168.herokuapp.com/excursions
Thanks!
Comment: does it work locally? There seems to be something funny with your html - I don't see any opening body tag until line 297 and even then it is closed one line later after the gmap div.
Comment: I'll check that, thanks for pointing out. It works localy but only when assets are local.
Comment: Well i fixed "body" thing, it works localy when assets are local, but for 2 days i can't get damn app to pull those images and css from amazon ... Files are there... I just can't see why... :(
Answer: I believe this is a stylesheeting problem - for starters try removing your colorbox stylesheet and recompile and push to Heroku, from my quick testing I found a problem in there somewhere.
Comment: You save my 2 days of frustrations, I'm going now to celebrate new year. Thank you sir Beynon !
Comment: If you have time to wrote few words about how did you manage to find this error, just for community. Thanks !
Comment: Trial and error. I saved your html and css locally - then took out chunks of the css file until I got it to render correctly, then put bits back in at a time - I think it was only a single line of the colorbox css that was messing it up infact.


Prove that $\log(1/(1-x)) = \sum_{i=1}^\infty \frac{x^i}{i}$

Question: I wish to prove that $$\log \left(\frac{1}{1-x} \right) = \sum_{i=1}^\infty \frac{x^i}{i}.$$
The source I'm following (Notes on generating functions by Michel Goemans, MIT 18.310, Section 8) says to this can be performed by integrating both sides of:
$$
\frac{1}{1 - x} = \sum_{i=0}^\infty x^i
$$
On trying this, I get upto:
\begin{align*}
&\frac{1}{1 - x} = \sum_{i=0}^\infty x^i \\
&\int \frac{1}{1-x}dx = \int\sum_{i=0}^\infty x^i dx \\
&\int \frac{1}{1-x}dx = \sum_{i=0}^\infty \int x^i dx \\
&-\ln(|1-x|) + C = \sum_{j=1}^\infty \frac{x^{j}}{j} + D \qquad \text{(set $j \equiv i + 1$)} \\
\end{align*}
which is clearly not what we were going for. I don't understand what I'm doing wrong. Any help would be appreciated. I'm primarily interested in the proof of the equality. It'd be cool if someone could show me how to prove this from the integral.
Comment: I mean, isn't it what you are trying to prove? Consider your last equation: $$-ln(|1-x|)=ln \left(\frac{1}{|1-x|} \right)$$ and since the series you began with only converges for $x\in(-1,1)$, then $|1-x| = 1+x$ $\forall x\in(-1,1)$. Therefore, you only need to consider the constant now: $$\sum_{j=1}^\infty \frac{x^j}{j} = ln \left(\frac{1}{1-x} \right) + C$$ Noting that when $x=0$ the sum becomes 0 and that $ln(1)=0$ you have $0=0+C$ therefore $C=0$ and you have your result
Comment: Recall that $-\ln (x)=\ln\left(\frac1x\right)$ and that the constants of integration are arbitrary so they can be combined into one. You could then substitute $0$ and note that $\ln 1=0=\sum 0 + K$, where $K$ is the combined constant.
Comment: Ah, right :) Thanks @Rafa and @Jam!
Answer: There's a much simpler proof, starting from the basic formula:
$$\ln(1-x)=-\sum_{i=1}^\infty \frac{x^i}{i}\qquad (|x|<1),$$
and using that $\;\ln\Bigl(\dfrac1{1-x}\Bigr)=-\ln(1-x)$.


Dynamically created image button click event is not fired

Question: On dynamically created table based on some condition i've added imagebutton dynamically. parallelly i want to add event for this image button click but the click event is not getting fired. here is my code snippet.
<code>    private void createTable()
    {
        TableRow tableRow = new TableRow();
        TableCell ImageCell = new TableCell();
        ImageButton imgBtndeleteAttr = new ImageButton();
        imgBtndeleteAttr.ID = "imgbtn_" + i.ToString() + j.ToString();
        imgBtndeleteAttr.CssClass = "deleteDynamic";
        imgBtndeleteAttr.OnClientClick = "javascript:return confirm('Do you want to delete this Attribute?');";
        imgBtndeleteAttr.Click += new System.Web.UI.ImageClickEventHandler(imgBtndeleteAttr_Click);
        ImageCell.Controls.Add(imgBtndeleteAttr);
        tableRow.Cells.Add(ImageCell);
    }
</code>
and here is the event
<code>    protected void imgBtndeleteAttr_Click(object sender, ImageClickEventArgs e)
    {

        ClientScript.RegisterClientScriptBlock(this.GetType(), "lnk",
           "<script type = 'text/javascript'>alert('Image button Clicked');</script>");
    }
</code>
Comment: Do you call `createTable()` on the `Page.IsPostBack`?  All dynamically created controls must be **recreated** on the post-back, otherwise they don't exist and the event handler isn't created
Comment: no. i cant call the createTable() on the Page.IsPostBack or page load becouse the table and controlls want to generate based on user select parameter
Comment: If there will only ever be **one single** dynamic item, then just create it normally and set `Visible="false"` in the markup - then you can change it in the code to `.Visible = true;` when required.  If there are multiple, then you're in a world of pain that I don't have time to explain
Answer: Its a bad idea to use dynamic controls in asp. The controls have to be recreated on postback. So if you create a button dynamically and click it, postback happens and event is triggered but due to postback the button which triggered the event is destroyed and the raised event is discarded.
Comment: Then may i know how to handle this type of process in asp.net. if we want to create and implement some dynamic control means what is the best way to achieve it
Comment: there is no clean way to handle this. you will have to create the control before hand and set  Visible=false. else if the condition to create the buttons is data driven i would use a datalist
Comment: In my case data driven is not possible. also the datalist too. i cant hide the controlls in pageload. becouse it should generate based on user input. if there is any other way to do this.?
Comment: You can create a datatable with one column and 1 row. put any value into it . then bind it with datalist which contains the button. your button is created and you can make it do what ever you want. This is what i actually did to create a dynamic button


How to display a variable in callback hook_menu?

Question: I'm creating a page with Hook_menu and I would like to display the user agent that page. This is my code to generate my page.
/**
 * Implements hook_menu().
*/
function custom_module_menu() {
    $items = array();
    $items['custom_module'] = array(
        'title' => 'My Custom Module',
        'description' => t('Best Custom Module'),
        'page callback' => 'custom_module_back',
        'access arguments' => array('administer site configuration'),
    );
    return $items;
}

function custom_module_back(){
        $output =  array(
            'first_para' => array(
                '#type' => 'markup',
                '#markup' => '
Test
 '
            ),
        );
        return $output;
    }

I try to set a variable like this $user_agent = $_SERVER['HTTP_USER_AGENT']; and then call it after the p tag.
Like this
function custom_module_back(){
            $output =  array(
                'first_para' => array(
                    '#type' => 'markup',
                    '#markup' => '
Test
 ' $user_agent,
                ),
            );
            return $output;
        }

And this did not work.
How can I display a variable into a callback ?
Comment: I am closing this question since the issue is caused by wrong syntax. PHP doesn't recognize `'Test ' $user_agent` as valid code.
Answer: Based on your code, it should be written as
$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '
Test
 ' . $user_agent,
  ),
);

rather than
$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '
Test
 ' $user_agent,
  ),
);

You need the period to concatenate the your string and variable.
Edited - Full working module
/**
 * Implements hook_menu().
 */
function testing_menu() {
  $items = array();
  $items['custom_module'] = array(
    'title' => 'My Custom Module',
    'description' => t('Best Custom Module'),
    'page callback' => 'testing_back',
    'access arguments' => array('administer site configuration'),
  );
  return $items;
}

function testing_back(){
  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  $output =  array(
    'first_para' => array(
      '#type' => 'markup',
      '#markup' => '
Test
 ' . $user_agent,
    ),
  );
  return $output;
}

Comment: I forgot to post it but I already try this out and did not work. I even re-install the module and I got and Drupal error.
Comment: Post edited with full module code. What's the error?
Comment: I was setting up the `$user_agent = $_SERVER['HTTP_USER_AGENT'];` out-side the callback. Thank you