Como deixar uma opção como "default" em uma combobox?

Question: tenho uma combobox com diversos "valores". Vou "chumbar" valores, só para exemplo. Combobox:

         Tipo de Nacionalidade
         <select id="comboTipoId" style="max-width: 350px; width: 350px; background-color: #eee; overflow: hidden; max-height: 37px; height: 37px">

         </select>

Function JS que preenche essa combo (aciono essa function no "onload" da página):
function preencherCampos() {

   /* Busca em arquivo o preenchimento do combobox "Tipo Nacionalidade" */
   /* 'Chumbando' JSON... */
   var consultaTipoId = '{ "tab" : "00000007", "descr" : "Tipo da Nacionalidade", "itens" : [{ "seq" : "1", "value" : "NACIONALIDADE - PF", "key" : "1" }, { "seq" : "2", "value" : "RESIDENCIA FISCAL - PF/PJ", "key" : "2" }, { "seq" : "3", "value" : "VISTO DE PERMANENCIA - PF", "key" : "4" }, { "seq" : "4", "value" : "PAIS DE CONSTITUICAO - PJ", "key" : "5" }, { "seq" : "5", "value" : "PAIS DE NASCIMENTO - PF", "key" : "9" }] }';
   var jsonRespostaCTI = JSON.parse( consultaTipoId );
   for(var i = 0; i < jsonRespostaCTI.itens.length; i++) {
      // get reference to select element
      var sel = document.getElementById('comboTipoId');

      // create new option element
      var opt = document.createElement('option');

      // create text node to add to option element (opt)
      opt.appendChild( document.createTextNode(jsonRespostaCTI.itens[i].value) );

      // set value property of opt
      opt.value = jsonRespostaCTI.itens[i].key;

      // add opt to end of select box (sel)
      sel.appendChild(opt);
   }
   ordenarTpNac();
}

Function JS para ordenar a combo em ordem alfabética:
function ordenarTpNac() {
   var itensOrdenados = $('#comboTipoId option').sort(function (a, b) {
      return a.text < b.text ? -1 : 1;
   });

   $('#comboTipoId').html(itensOrdenados);
}

O problema é que, após a ordenação, o valor "default" que aparece pro usuário é "VISTO DE PERMANENCIA - PF" (o último valor). Eu queria que ficasse como "default" o "PAIS DE NASCIMENTO - PF" (chave "9"). Como fazer isso? Tentei colocar algo do tipo if(opt.value === "9") {
                        opt.setected = "selected";
                    } dentro do for da função preencherCampos() mas não deu certo...
Answer: Antes de fazer o append das options, coloque um if para inserir o atributo selected na option cujo valor seja 9:
if(jsonRespostaCTI.itens[i].key == 9) opt.setAttribute("selected", "");

Irá resultar no HTML:
<option value="9" selected>PAIS DE NASCIMENTO - PF</option>

Veja:

function preencherCampos() {

   /* Busca em arquivo o preenchimento do combobox "Tipo Nacionalidade" */
   /* 'Chumbando' JSON... */
   var consultaTipoId = '{ "tab" : "00000007", "descr" : "Tipo da Nacionalidade", "itens" : [{ "seq" : "1", "value" : "NACIONALIDADE - PF", "key" : "1" }, { "seq" : "2", "value" : "RESIDENCIA FISCAL - PF/PJ", "key" : "2" }, { "seq" : "3", "value" : "VISTO DE PERMANENCIA - PF", "key" : "4" }, { "seq" : "4", "value" : "PAIS DE CONSTITUICAO - PJ", "key" : "5" }, { "seq" : "5", "value" : "PAIS DE NASCIMENTO - PF", "key" : "9" }] }';
   var jsonRespostaCTI = JSON.parse( consultaTipoId );
   for(var i = 0; i < jsonRespostaCTI.itens.length; i++) {
      // get reference to select element
      var sel = document.getElementById('comboTipoId');

      // create new option element
      var opt = document.createElement('option');

      // create text node to add to option element (opt)
      opt.appendChild( document.createTextNode(jsonRespostaCTI.itens[i].value) );

      // set value property of opt
      opt.value = jsonRespostaCTI.itens[i].key;

      if(jsonRespostaCTI.itens[i].key == 9) opt.setAttribute("selected", "");

      // add opt to end of select box (sel)
      sel.appendChild(opt);
   }
   ordenarTpNac();
}

function ordenarTpNac() {
   var itensOrdenados = $('#comboTipoId option').sort(function (a, b) {
      return a.text < b.text ? -1 : 1;
   });

   $('#comboTipoId').html(itensOrdenados);
}
preencherCampos()

         Tipo de Nacionalidade
         <select id="comboTipoId" style="max-width: 350px; width: 350px; background-color: #eee; overflow: hidden; max-height: 37px; height: 37px">

         </select>

Comment: Veja, o fato de fazer uma ordenação não muda o option que está selecionado, ele vai continuar selecionado.
Comment: Acho que seria melhor, após popular o select, fazer: `$("#comboTipoId option[value='9']").attr("selected", "");`
Comment: puxa, cara, assim funcionou, joguei esse trecho de código na função que ordena, logo após ela terminar de ordenar e funcionou!!! :) brigadão!
Comment: então, cara, o problema dessa solução é que, depois que acaba o for da função preencherCampos(), a função ordenarTpNac() executada em seguida "bagunça" a escolha do default. Eu vi que no seu exemplo, você chamou a função preencherCampos() embaixo da ordenarTpNac() e, por algum motivo que eu não entendi, funcionou no seu exemplo, mas comigo, a página quebrou porque ficou em laço infinito. Não tem como eu escolher o default dentro da função de ordenação (que é executada "por último")?
Comment: Você está certo, cara, é que eu estava tentando implementar essa mesma alteração numa outra combobox e não deu certo. Acho que é porque o JSON é diferente, e aí, eu tenho que alterar algo na lógica; você pode me ajudar a enxergar o que é?
Comment: vou postar num novo comentário, senão, excede o limite de caracteres... Hehe
Comment: var novoJSON = '{ "tab" : "00000004", "descr" : "Pais", "itens" : [ { "seq" : "45", "value" : "BOTSWANA", "key" : "045", "ufs" : [] }, { "seq" : "46", "value" : "BRASIL", "key" : "046", "ufs" : [ { "seq" : "1", "value" : "RONDONIA", "abrev" : "RO", "key" : "000010", "doc" : [ { "seq" : "1", "value" : "REGISTRO GERAL SEM CPF", "key" : "00007", "emissao" : "S", "venc" : "N", "exp" : [ { "seq" : "1", "value" : "DIRETORIA IDENTIFICAÇÃO CIVIL", "key" : "DIC " } ] } ], "municipios" : [ { "seq" : "1", "value" : "ARIQUEMES", "key" : "0000009393" } ] } ] } ] }';
Comment: esse novoJSON, quando eu parseio e percorro ele, mesmo botando o if que você colocou, não funciona (queria que o Brasil ficasse visível pro usuário, chave "046"). O país fica selecionado na aplicação (já fiz o teste), mas o que aparece para o usuário é o último país ordenado do JSON (o último item do "colchete" "itens"). Lembrando que coloquei só parte desse novo JSON aqui (o mínimo para ficar "inteligível", pelo menos), porque ele é muito grande... Tem todos os países do mundo, mais os estados e municípios do Brasil, com órgãos emissores de documentos, ficaria inviável postar o JSON inteiro.
Comment: Esses JSON's vc tá puxando como? É no PHP, AJAX? Acho que há uma forma melhor de escolher o option padrão.
Comment: Então, eu puxo por uma função. Essa função está num aplicativo Android. É que eu, na verdade, tô fazendo só o front desse aplicativo Android. Aí, uma das exigências é essa: deixar o país Brasil como "default" pro usuário pra facilitar o preenchimento do formulário.


How to move ADUser to child domain while preserving original Object for password replication purposes

Question: So, we have one forest with one domain currently, which is working pretty good.
Now we got a new remote office for 5 users. They should get their own Domain Controller and Domain.
Our original Domain is named company.com and the plan is to create a Child Domain named remote.company.com for the remote office.
The problem is, that the 5 people at the remote office change relatively often (~ -2 people every 2 months; +2 people every 2 months; so it stays pretty much at 5).
How can I get the Users, which get created in the Domain company.com, in the Child Domain remote.company.com, while still preserving the original Object in company.com.
I need the original Userobjects to stay in company.com as a password change automatically connects with this Object.
Second Question: How can I get the two Userobjects to replicate after a password change (to get the new password written to User.company.com to replicate to User.remote.company.com)
As I am pretty new in the business and as new as this in Active Directory Management, I would be glad for all Input I could get.
And if you need more Information, feel free to ask.
Comment: Why do you think you need a dedicated domain for the branch office? This seems quite overkill for just 5 users.
Comment: Ummm... yeah... why do you/they need a new domain?
Comment: They shall get a new one, because I got told they are going to. Sadly I dont make the rules.
Comment: If the people telling you to build a new domain cannot justify it, then they are in no position to be giving such directions. Sorry you have to work in those conditions.
Answer: Because the remote office is a branch of the same organization, a more efficient solution for that scenario is setting up a separate site describing the remote branch network and deploying a read-only domain controller there, with appropriate password replication policies.
In addition, you should deploy at least two domain controllers in the forest. By deploying a single domain controller, you will be subject to a loss of the entire forest if the server experiences a hardware fault.
Comment: The sad thing is, I dont make the rules, I only get told, what I should be doing. And I got told, that they are getting their own small domain, where it does not matter how stupid the idea is. But I do not really know how to conquer my problems described in the above question


Qual a diferença entre a exceção MySQL Trigger e MySQL Event?

Question: Gostaria de criar um agendador de disparo de e-mail, se possível, sem uso do cron, e gostaria de saber se é possível fazer isso através do MySQL.
Pesquisando pela Internet eu vi alguns exemplos de criação de evento sem uso de cron:
CREATE EVENT PurgeLogTable
ON SCHEDULE EVERY 1 WEEK
DO
BEGIN
DELETE FROM `logs` WHERE `LogTime` <= DATE_SUB(CURRENT_TIMESTAMP,INTERVAL 1 WEEK);
INSERT INTO `audit` (`AuditDate`, `Message`) VALUES(NOW(), "Log table purged succesfully!");
END

E um exemplo de disparo de e-mail usando trigger, só não sei se funciona, pois não testei:
CREATE TRIGGER send_emailverifier AFTER INSERT, UPDATE ON tbl_users
FOR EACH ROW BEGIN
SELECT * FROM email_bodies WHERE EmailID = 1;
SELECT * FROM tbl_users WHERE ClientID = @ClientID
INSERT INTO tbl_emailverify VALUES (UUID, tbl_users.ClientID, OLD.CltEmail, NEW.CltEmail)
SELECT concat("To: ",NEW.CltEmail & "," & OLD.CltEmail),
"From: firstname.lastname@example.com",
concat("Subject: ",NEW.subject),
"",
email_bodies.EmailContent
INTO OUTFILE "/inetpub/mailroot/pickup/mail.eml"
FIELDS TERMINATED by '\r\n';
END

Mas minha dúvida é pertinente quanto à maneira de como poderia avisar um disparador de e-mail, para que acione o URL de envio, exemplo:
/enviar-emails/go

Answer: Eles têm propósitos bem diferentes, como a sintaxe apresentada na pergunta já dá uma dica.
O TRIGGER é um recurso antigo dos bancos de dados em geral para disparar - como o próprio nome diz - uma execução de algo quando algo ocorre em uma tabela. Uma mudança nos dados (INSERT, UPDATE, DELETE) provoca a ação secundária.
O EVENT é um recurso relativamente novo que é determinado pelo tempo, é um agendador. É uma forma de garantir que uma ação seja executada de tempos em tempos, independente do que ocorre no banco de dados. Ele é uma espécie de cron do banco de dados.
Então depende do objetivo para disparar o e-mail. Toda vez que um e-mail é inserido ou atualizado na tabela, precisa dispará-lo? Use o TRIGGER, como mostra o código acima. Se o envio - mesmo que seletivamente - deve ser feito de tempos em tempos, independente do que ocorre no banco de dados, use o EVENT.
A ação que ambos executam podem ser basicamente a mesma. Claro que há algumas limitações no EVENT porque ele não está manipulando dados. Por exemplo, ele não tem uma versão velha ou nova do dado que pode ser usado no TRIGGER, mas é uma limitação que não atrapalha porque nem faria sentido ter isto em algo que não está atualizando os dados.
Coloquei no GitHub para referência futura.
Comment: Obrigado pelo esclarecimento.


Computing $\lim_{(x,y)\to(0,0)}(x^2+1)\cdot\frac{\sin y}{y}$

Question: Hi I have a limit with two variables in front of me and the book says directly that it is equal with $1$ but for the life of me I dont understand why?? maybe the answer is stupid but I am excausted and I can't see it! Here is the limit:
$$\lim_{(x,y)\to(0,0)}(x^2+1)\cdot\frac{\sin y}{y}$$
Thanks in advance.
Comment: What have you done so far? Do you have any difficulty with the $x$ part?
Comment: Welcome to math.stackexchange ! It makes the question easier to read if you put the symbols between \$ ... \$ and also prefix math "words" like "lim" and "sin" with a backslash.
Comment: But I am afraid I think this should be marked as a duplicate, unless you are worried about how to deal with $\lim_{(x,y)\to(x_0,y_0)}f(x)g(y)$ when you already know $\lim_{x\to x_0}f(x)$ and $\lim_{y\to y_0}g(y)$
Comment: If not, you are simply asking how to deal with $\frac{\sin y}{y}$. The snag there is that that limit has been dealt with many times before on this site, so the question is just regarded as a duplicate.
Comment: Nice picture of you two together ;) Anyway, hint: $x^2$ goes to $0$ and $\sin y/y$ to $1$, so...
Comment: Thanks everyone! I ddnt see your questions at first. sorry. anyway i have gotten my answer. my snag was obviously that the limit of siny/y as y->0 is 1... duh! thanks again and sorry for not answering
Answer: Perhaps the easiest way to see this is to keep in mind that
$$\lim_{z\to z_0} f(z)g(z)=\lim_{z\to z_0} f(z)\lim_{z\to z_0} g(z)$$
when both limits exist on the RHS.
I hope it is clear that
$$\lim_{(x, y)\to (0, 0)}x^2+1=\lim_{x\to 0}x^2+1=1$$
and
$$\lim_{(x, y)\to (0, 0)}\frac{\sin y}{y}=\lim_{y\to 0}\frac{\sin y}{y}=1.$$
Answer: Hint:
$$\frac{\sin y}{y}\underset{y\to0}{\longrightarrow}1$$
And
$$|f(x,y)-1|=\left|(x^2+1)\left(\frac{\sin y}{y}-1+1\right)-1\right|=\left|x^2\left(\frac{\sin y}{y}-1\right)+x^2+\left(\frac{\sin y}{y}-1\right)\right|\leq x^2\left|\frac{\sin y}{y}-1\right|+x^2+\left|\frac{\sin y}{y}-1\right|$$
Comment: @almagest Not the simplest, of course, but if the OP wants a $\varepsilon-\delta$ proof, he may start with this. Anyway, it's not yet clear what he finds unobvious in the question.
Comment: Is that really the simplest proof of how to deal with products? Maybe it is?
Comment: i told you i am excausted! the answer was obviously a DUH! answer!no need for sarcastic comments. thanks anyway...
Comment: @user3670661 I'm not sarcastic. You have not answered any question asked in comments, so I don't even know what you are supposed to know about limits. It's uncomfortable to try to help people who don't seem to want to participate in the elaboration of an answer to their own question.
Comment: I missed the questions sorry... my snag was obviously that the limit of siny/y as y->0 is 1... and i couldnt see how the final solution is 1
Answer: This function offers two independent blocks whose limits give values in $\mathbb{R} \setminus \{0\}$ so:
$$
\lim_{(x,y) \to (0,0)}(x^2+1)\cdot\frac{\sin y}{y}=\lim_{x \to 0}(x^2+1)\cdot\lim_{y \to 0}\frac{\sin y}{y} =1 \cdot 1=1
$$


Contar valores em múltiplas tabelas relacionadas

Question: Tenho 4 tabelas tbl_Distrito, tbl_Unidade, tbl_Servidor, tbl_Processo.
tbl_Distrito: Cod_Distrito, Nome_Distrito

tbl_Unidade: Cod_Unidade, Nome_Unidade, Cod_Distrito

tbl_Servidor: Cod_Unidade

tbl_Processo: Cod_Unidade

Basicamente eu preciso listar todas as unidade e contar quantas vezes cada unidade aparece na tabela Servidor e na tabela Processo pra conseguir comparar esses valores:
Minha consulta:
SELECT DISTRITO.NOME_DISTRITO,
       UNIDADE.NOME_UNIDADE,
       COUNT(SERVIDOR.UNIDADE_COD_UNIDADE) AS CONTAGEM_1,
       COUNT(PROCESSO_HAS_UNIDADE.UNIDADE_COD_UNIDADE_SOLICITADA) AS CONTAGEM_2
  FROM (DISTRITO INNER
        JOIN(UNIDADE INNER JOIN PROCESSO_HAS_UNIDADE ON
             UNIDADE.COD_UNIDADE =
             PROCESSO_HAS_UNIDADE.UNIDADE_COD_UNIDADE_SOLICITADA) ON
        DISTRITO.COD_DISTRITO = UNIDADE.DISTRITO_COD_DISTRITO)
 INNER JOIN SERVIDOR
    ON UNIDADE.COD_UNIDADE = SERVIDOR.UNIDADE_COD_UNIDADE
 GROUP BY DISTRITO.NOME_DISTRITO, UNIDADE.NOME_UNIDADE;

O problema é que minha consulta está retornando valores iguais para CONTAGEM_1 e CONTAGEM_2.
Answer: Oi,
Acredito que você possa combinar um LEFT JOIN entre tbl_Unidade e tbl_Servidor e entre tbl_Unidade e tbl_Processo
Ficaria assim
select  UNIDADE.Nome_Unidade,
        DISTRITO.Nome_Distrito,
        COUNT(SERVIDOR.Cod_Unidade) AS CONTAGEM_1,
        COUNT(PROCESSO.Cod_Unidade) AS CONTAGEM_2
from    tbl_Unidade UNIDADE
left    join tbl_Servidor SERVIDOR on UNIDADE.Cod_Unidade = SERVIDOR.Cod_Unidade
left    join tbl_Processo PROCESSO on UNIDADE.Cod_Unidade = PROCESSO.Cod_Unidade
join    tbl_Distrito DISTRITO on UNIDADE.Cod_Distrito = DISTRITO..Cod_Distrito
GROUP   by UNIDADE.Nome_Unidade, DISTRITO.Nome_Distrito;

Comment: A ideia foi boa mas também não funcionou, continuou a repetir os valores nas duas colunas de contagem. Acredito que preciso de uma subconsulta.
Comment: Tenta fazer de duas em duas tabelas, depois você junta os joins, o Left join deve trazer mesmo que não encontre a chave extrangeira
Answer: Consegui resolver, segue a solução para os próximos aventureiros:
SELECT DISTRITO.NOME_DISTRITO, DERIVADA.NOME_UNIDADE, DERIVADA.TOTAL_PROCESSO, Count(SERVIDOR.UNIDADE_COD_UNIDADE) AS TOTAL_SERVIDOR
FROM DISTRITO
INNER JOIN ((SELECT UNIDADE.DISTRITO_COD_DISTRITO, UNIDADE.COD_UNIDADE, UNIDADE.NOME_UNIDADE, COUNT(PROCESSO.UNIDADE_COD_UNIDADE) AS TOTAL_PROCESSO
FROM UNIDADE
LEFT JOIN PROCESSO
ON PROCESSO.UNIDADE_COD_UNIDADE = UNIDADE.COD_UNIDADE
GROUP BY UNIDADE.DISTRITO_COD_DISTRITO, UNIDADE.COD_UNIDADE, UNIDADE.NOME_UNIDADE) AS DERIVADA
LEFT JOIN SERVIDOR
ON DERIVADA.COD_UNIDADE = SERVIDOR.UNIDADE_COD_UNIDADE)
ON DISTRITO.COD_DISTRITO = DERIVADA.DISTRITO_COD_DISTRITO
GROUP BY DISTRITO.NOME_DISTRITO, DERIVADA.NOME_UNIDADE, DERIVADA.TOTAL_PROCESSO, DERIVADA.DISTRITO_COD_DISTRITO, DERIVADA.COD_UNIDADE
HAVING (((DERIVADA.TOTAL_PROCESSO)<>0) OR ((Count(SERVIDOR.UNIDADE_COD_UNIDADE))<>0));


Getting 200 status code but response is undefined in react

Question: /*global gapi*/
import React,{Component} from 'react';

import Dashboard from './Dashboard';

import MetaTags from 'react-meta-tags';
import {connect} from 'react-redux';

class AddWebsite extends Component{
  constructor(props){
    super(props);
  }

 queryAccounts() {
    console.log('inside queryAccounts');
    gapi.client.load('analytics', 'v3').then(function() {
    gapi.client.analytics.management.accounts.list()
    .then(function(request,response){
      console.log(response.text);
      if (response.items && response.items.length) {
    // Get the first Google Analytics account.
    var firstAccountId = response.items[0].id;
    console.log(firstAccountId);
  }
  else {
    console.log('No accounts found for this user.');
  }
});

  });
}

  render(){
    return(

      <Dashboard />
          Company Name:
          <input type="text"  id="Company_Name" />
          Website URL:
          <input type="text" id="pwd" />
          Analytics
          <button  onClick={ () => this.queryAccounts() }>Connect to Analytics</button>
        <button type="submit" class="btn btn-default">Continue</button>
      <MetaTags>
      <meta name="google-signin-client_id" content="1133221725-0tke0s65lfp9pq2gk219d2h1mtccn5v7.apps.googleusercontent.com" />
      <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.edit " />
          </MetaTags>

    );
  }
}
export default connect()(AddWebsite);

On the clicking of the button,queryAccounts() is called which should give the list of analytics accounts and the api call is successfully made.The response is set in Chrome Dev Tools but when I am logged in the console, it returns undefined.
The response set in chrome Dev Tools is:
{"kind":"analytics#accounts","username":"firstname.lastname@example.com","totalResults":1,"startIndex":1,"itemsPerPage":1000,"items":[{"id":"106194863","kind":"analytics#account","selfLink":"https://www.googleapis.com/analytics/v3/management/accounts/106194863","name":"My Life Jobs","permissions":{"effective":[]},"created":"2017-09-11T06:39:57.512Z","updated":"2017-09-11T06:42:02.258Z","childLink":{"type":"analytics#webproperties","href":"https://www.googleapis.com/analytics/v3/management/accounts/106194863/webproperties"}}]}

Answer: queryAccounts() {
    console.log('inside queryAccounts');
    gapi.client.load('analytics', 'v3').then(function() {
    gapi.client.analytics.management.accounts.list()
    .then(function(response){
      console.log(response); // try consoling and you will we able to see the response. response is the first arguments not the request
      if (response.items && response.items.length) {
    // Get the first Google Analytics account.
    var firstAccountId = response.items[0].id;
    console.log(firstAccountId);
  }
  else {
    console.log('No accounts found for this user.');
  }
});

Refer this link thoroughly Link
Comment: this is more correct. there is no request argument, just the response argument which is the first and only argument for any Promise.
Comment: Got the Response..Thank You!
Answer: There is no text prop in the response. You could console.log response.items.length.
console.log(response.items.length);


Designating a Column for an Operation in Pandas

Question: I am not a coder, but am working with pandas in python 3 to modify a program someone else wrote to strip HTML out of a column in a CSV file. In the original code, it asked for user input for the column names as in the code at the bottom, but my csv file will always have the same column headings so I would prefer not to have this input step, instead just including the column name in the program itself.
I have tried to replace this line:
col = input("Enter column name: ")

which works exactly the way it is supposed to when I manually input the column name (outputting a new column with the HTML cleaned), with:
col = df['ColumnName']

and many other variations, but whatever I try gives me various errors. What syntax should I use to simply have it operate directly on the column I name rather than requiring the manual input. Thanks so much for the help.
import pandas as pd
import re
import html
def cleanhtml(raw_html):
    cleanr = re.compile('<.+?>')
    cleantext = re.sub(cleanr, ' ', str(raw_html))
    clean = re.sub('\s+',' ',cleantext)
    return html.unescape(clean)
file = input("Enter CSV File name (without '.csv' at the end): ")
d = pd.read_csv("%s.csv" % file )
df = pd.DataFrame(d)
col = input("Enter column name: ")
df[col][0:5]
df['clean'] = df[col].apply(cleanhtml)

Comment: After `col = input("Enter column name: ")`, `col` contains the *name* of the column. If you want it to be static, you should use `col = 'ColumnName'`.
Comment: That did it. Thanks so much, Serge.
Comment: Stack Overflow is not a free code writing service, nor is it meant to provide personalized guides and tutorials. See: [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users.
Answer: instead of manually accepting column names, you can just replace the input command with the name of the column that you want i.e
col = input("Enter column name: ")

with
col = 'columnName'

Comment: Exactly what I needed. Thanks so much.


Volume of intersection of two conical frustums

Question: How can I find volume of intersection of two conical frustums? Both objects are on the same X axis. I'm not sure yet how exactly they will intersect because each frustum is one user on the map and I need to find probability that two users saw each other.
I would appreciate some example because I think I will not get to final solution myself.
Thanks.
Comment: The intersection of two parallel conical frustums on the same axis is either (a) another conical frustum or (b) two conical frustums glued together at their bases. What variables should we assume are a 'given' in the problem - e.g. the radii of the tops and bottoms and their centers' positions on the $x$-axis?
Comment: Anon, yes I have radii for tops and bottoms, and centers (In my case that's latitude and longitude). The height of conical frustums can by any number, I think it doesn't metter for me.
Comment: Is my question so complex that no-one can give me an answer? Or I just need to provide some more details to describe it better? I've spend few days searching in google and on couple forums and can't find any example. Any help would be appreciated.
Comment: I'm sorry, I figured either someone else would answer or you'd figure it out - assuming I understand your question correctly. I'll open my MSPaint and work on an explanation.
Answer: A cone is simply a triangle rotated about an axis to make a solid. We'll place it on the $y$-axis instead of the $x$-axis because it looks better standing upright. Now if you slice a smaller cone off the top, then you're left with a conical frustum. This new solid is now the same as an isosceles trapezoid rotated about an axis down the middle. Therefore, if we take a look at an intermediate slice of the intersection of two frustums, we'll get essentially one of four possible situations (up to otherwise superfluous orientation and proportion):

You can see how in the right two cases, the intersection is two conical frustums glued together, base to base, while in the left two cases the intersection is just another frustum. Do keep in mind, however, that the two main frustums don't necessarily look "upside-down" relative to each other - but they will make one of these situations, regardless. (Actually, I'm lying: there's a fifth possible case where one frustum completely contains the other, but the problem is trivial then... and makes my nice picture less symmetrical.) Instead of going over all four possible situations, I'll only lay out the two tools you need in order to do the problem yourself, hopefully. The first is this:
$\hskip 1.1 in $
If you know the top has length (diameter for the frustum) $A$, and you know the bottom has length $B$, and you know the purple line is $u$ distance down from the top and $v$ distance up from the bottom, then the purple line has length equal to the weighted average $(Au+Bv)/(u+v)$. You can use this to find the base diameters of the intersection frustum based on the top and bottom diameters of the main two frustums.
Lastly, a frustum with top diameter $A$, bottom diameter $B$, and height $h$, has volume that can be calculated with the formula $\frac{\pi h}{12}(A^2+AB+B^2)$. If you don't understand how to resolve your intersecting frustums problem now, tell me where you're stuck and I'll try to elaborate.
Comment: Anon, thank you for such detailed explanation. I think I've solved my problem, at latest I'm getting some result.


Bit Error Rate - Multiple Bernoulli trials with different probabilities

Question: If you transmit a sequence of bits over some line, errors may creep in. For instance, if the Bit Error Rate of this line is 1%, on average, every 1 out of 100 bits will flip to the opposite value.
For a single transmitted bit, this relates to a Bernoulli trial with $p=0.99$ for being a 'success' and $q=1-p=0.01$ for a failure.
If this same bit is transmitted over two identical lines, there are two pathways of getting a correct result: two correct transmissions or two wrong transmissions (flipping the bit twice). The probability, therefore, is $p*p+q*q$.
Following this sequence for multiple transmissions, we get:
$$
\begin{array}{r¦c¦c}
\textbf{ }&\textbf{correct}&\textbf{wrong}\\
\textbf{1}&p&q\\
\textbf{2}&p^{2}+q^{2}&2pq\\
\textbf{3}&p^{3}+3pq^{2}&3p^{2}q+q^{3}\\
\textbf{4}&p^{4}+6p^{2}q^{2}+q^{4}&4p^{3}q+4pq^{3}
\end{array}
$$
The parameters in front of each term seem to relate to Pascal's triangle. Furthermore, the 'correct' descriptions are 'symmetric' in q (even exponents), while the 'wrong' ones are 'anti-symmetric' (odd exponents). Can somebody explain the connection, and is there perhaps a general function which describes this series?
My real question is the following: what if the bits are transmitted across different lines $i$ each with a different BER $p_i$. The table then becomes:
$$
\begin{array}{r¦c¦c}
\textbf{ }&\textbf{correct}&\textbf{wrong}\\
\textbf{1}&p_{1}&1-p_{1}\\
\textbf{2}&2p_{1}p_{2}-p_{1}-p_{2}+1&p_{1}-2p_{1}p_{2}+p_{2}\\
\textbf{3}&4p_{1}p_{2}p_{3}-2p_{1}p_{2}-2p_{2}p_{3}-2p_{3}p_{1}+p_{1}+p_{2}+p_{3}&etc.
\end{array}
$$
Is there a general function which describes this behaviour? Can someone explain anything more about this series? Does this have a name?
Answer: In the case of the repeated Bernoulli trials with identical probabilities, I believe the connection between this concept and Pascal's triangle can be visualised using the following graph.

If we start at the top and define 'correct' to be a step to the right (bit does not flip) and 'wrong' to be a step to the left (the flipping of a bit), we can see there are 4 pathways to arrive at a 'wrong' result where the bit has flipped only once.
Similarly, there are 6 ways to arrive at a 'correct' bit which has flipped twice within 4 transmissions.
Therefore, the total probability of getting a correct answer is the sum of alternating Pascal's numbers, starting at the far right, moving to the left, each time skipping one number, and multiplying by the appropriate $p$'s or $q$'s.
This is the link with the 'symmetry' and 'anti-symmetry' mentioned in the original post.


Displaying information with mysql fetch array?

Question: I'm trying to pull information from a table in mysql 'ptb_stats'. This is being pulled through 'user_id' specific so that each member of the site can only see their stats.
So far all that is happening is i'm getting the image echoed" on the page and the information being pulled just says array?
Any suggestions where im going wrong please?
Thanks
This is the function:
function get_stats() {
            global $connection;
            global $_SESSION;
            $query = "SELECT  s.location, s.nationality, s.hobbies, s.role, s.friends, s.height, s.weight
                        FROM ptb_stats s
                        WHERE user_id = \'$profile_id\'";

                        $stats_set = mysql_query($query, $connection);
            confirm_query($query, $connection);
            return $stats_set;
        }

This is the fetch array:
 <?php
        $stats_set = get_stats();

        while ($stats = mysql_fetch_array($stats_set)) {

            ?>

    <?php echo "" ?>
      <?php echo " $stats"?>
      <?php echo "" ?>
      <?php echo " $stats"?>
      <?php echo "" ?>
      <?php echo " $stats"?>

      <?php echo "" ?>
      <?php echo " $stats"?>
      <?php echo "" ?>
      <?php echo " $stats"?>
      <?php echo "" ?>
      <?php echo " $stats"?>

<?php
        }

        ?>

Comment: you didn't pass $profile_id to getStats function
Comment: ok sorry i'm new to sql. how do i do that?
Comment: and you are always echoing  instead of  etc
Comment: thanks but now when i change it i get this error message:                Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PTB1/includes/mod_profile/mod_profile.php on line 285
Comment: this is whats on line 285:

  while ($stats = mysql_fetch_array($stats_set)) {
Comment: may be you are not getting proper resource object. use mysql_num_rows before while loop. fyi http://php.net/manual/en/function.mysql-num-rows.php
Answer: $stats is an array with all your results. You need to define which values you want to display like that :
<?php echo $stats['location']; ?>

Futhermore, you should write your code like this way :
<?php
    $stats_set = get_stats();
    while ($stats = mysql_fetch_assoc($stats_set)) :
?>

    <?php echo $stats['location']; ?>

<?php endwhile; ?>

EDIT
You need to use mysql_fetch_assoc instead of mysql_fetch_array (or specify MYSQL_ASSOC)
http://php.net/manual/fr/function.mysql-fetch-assoc.php
Comment: that didnt work :( still getting same error: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/PTB1/includes/mod_profile/mod_profile.php on line 285
Comment: Code above is correct, you have a sql request problem : bad connection, sql syntax error, .... What is confirm_query? Check error using mysql_error after your mysql_query function : http://php.net/manual/fr/function.mysql-error.php
Comment: What do you mean by "is $stats_set"? After mysql_query() (if no error) $stats_set is a ressource, but when you are using in the mysql_fetch_assoc function it is not. Possibilities are : mysql error somwwhere or something bad happends to $stats_set in your confirm_query() function


Probability of n random numbers under a threshold

Question: If we choose N random numbers between 0 and 1 (uniformly distributed), what is the probability that at least n will be under some threshold t?
For example I want to know if I have a list of 1,000,000 numbers between 0 and 1, what's the probability that at least 50 of them will be under 0.75?
Comment: What did you try and how far did you get?
Comment: First, try to solve your problem for some familiar values where the answer will be easy do find. For example, it's easy to solve your problem for $N=n=1$, and only slightly more difficult for $n=N=2$. Now, try to solve the problem for $n=1,N=2$ and look at what you get.
Comment: @5xum I got as far as: let p(1,1,t)=t; p(N,n,t)=t*p(N-1,n-1,t)+(1-t)*p(N-1,n,t); answer then is p(N,n,t); But how do I get a non-recursive solution?
Answer: The idea is to regard each choice of uniformly distributed random number $U_i \sim \operatorname{Uniform}(0,1)$ where $i = 1, 2, \ldots, N$, as associated with a Bernoulli trial $B_i \sim \operatorname{Bernoulli}(p)$, where $$B_i = \begin{cases}1, & 0 \le U_i < t \\ 0, & t \le U_i \le 1. \end{cases}$$  That is to say, $B_i = 1$ if and only if the random number $U_i$ is less than the threshold $t$.
Therefore the success parameter $p$ of the Bernoulli trial is $$\Pr[B_i = 1] = \Pr[U_i < t] = \frac{t}{1-0} = t, \quad 0 \le t \le 1.$$  The total of all these (independent) Bernoulli trials is $$T = B_1 + B_2 + \cdots + B_N \sim \operatorname{Binomial}(N, t).$$
Now in order to get a probability that at least $n$ out of $N$ of the $U_i$s are less than $t$, this is simply equivalent to the probability that $T \le n$:  $$\Pr[T \ge n] = \sum_{k=n}^N \Pr[T = k] = \sum_{k=n}^N \binom{N}{k} t^k (1-t)^{N-k}.$$  This sum furnishes the exact probability of the desired event for a given $N$, $n$, and $t$.
However, if $\min(n,N-n)$ is very large, then this sum (or its complementary probability) will have many terms and be unwieldy to compute.  In such a case, the normal approximation (with continuity correction) to the binomial distribution is desirable:  $$\Pr[T \ge n] \approx \Pr\left[ Z \ge \frac{n - Nt - \frac{1}{2}}{\sqrt{Nt(1-t)}} \right] = 1 - \Phi \left( \frac{n - Nt - \frac{1}{2}}{\sqrt{Nt(1-t)}}\right),$$ where $Z \sim \operatorname{Normal}(0,1)$ is a standard normal random variable, and $\Phi(z) = \Pr[Z \le z]$ is the cumulative distribution function of $Z$ whose values can be looked up in a standard normal table.
For your example of $N = 10^6$, $n = 50$, $t = 0.75$, the probability of such an event is about $1 - 4.00871338379431228438 \times 10^{-601806}$.  The normal approximation gives $1 - 4.23635959294153500 \times 10^{-651360},$ which is also very close to $1$.
Answer: Every choice of a number results in a 'success' if the number is under the threshold and a failure if not. Assuming that the numbers are independently chosen you deal with binomial distribution having parameters $N$ and $t$. If $X$ denotes the number of successes then you are looking for $P(X\geq n)$


virtual directories in iis7.0 got deleted in windows 2008

Question: After  installing iis6.0 metabase compatibility and iis6.0  console in the iis7.0 ,i am not able to create new virtual directory in Default website( which is marked with a small red mark).
when i  right click on" Default website",it generates following message box
"there was an error while performing this operation...the application '/' does not exist."
and i am working in the windows 2008 environment .can any one help me in getting back my old virtual directories in default website?
Answer: That sounds like the config file has a bad entry.  If you click around your sites and vdirs in IIS Manager you will probably get an error there too when you click on the bad folder.  See if you can delete it and create it again.
If you can't, take a look at c:\windows\system32\inetsrv\config\applicationHost.config and look for the bad vdir and manually clean up the config.  Make sure to save a copy of the file before you start, or run appcmd add backup BeforeSabashTroubleshooting.
Answer: Had the same problem, error on default web site.
I open "applicationHost.config" file and remark config for Default IIS site was missing undet Sites -> Default Web Site
I've add this and it works now
<code><application path="/">
      <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
</application>
</code>


WebRTC ICE connection fails using Angular between safari and firefox even when ice candidates are gathered

Question: Calling from Firefox 61.0.1 to Safari 11.1.2 results in ICE connection failed after all of the candidates are gathered in the Angular 5.x app.
The app is using webrtc-adapter to add cross-browser support.
Tested browsers:

FireFox 61.0.1
Opera 54
Safari 11.1.2 + mobile Safari
Chrome 67
Edge 42

Platform: macOS High Sierra 10.13.6
All other browsers combinations works.
Here are the webrtc logs from firefox:
<code>insert 'ice' (registry) succeeded: ice

insert 'ice.pref' (registry) succeeded: ice.pref

insert 'ice.pref.type' (registry) succeeded: ice.pref.type

insert 'ice.pref.type.srv_rflx' (UCHAR) succeeded: 0x64

insert 'ice.pref.type.peer_rflx' (UCHAR) succeeded: 0x6e

insert 'ice.pref.type.host' (UCHAR) succeeded: 0x7e

insert 'ice.pref.type.relayed' (UCHAR) succeeded: 0x05

insert 'ice.pref.type.srv_rflx_tcp' (UCHAR) succeeded: 0x63

insert 'ice.pref.type.peer_rflx_tcp' (UCHAR) succeeded: 0x6d

insert 'ice.pref.type.host_tcp' (UCHAR) succeeded: 0x7d

insert 'ice.pref.type.relayed_tcp' (UCHAR) succeeded: 0x00

insert 'stun' (registry) succeeded: stun

insert 'stun.client' (registry) succeeded: stun.client

insert 'stun.client.maximum_transmits' (UINT4) succeeded: 7

insert 'ice.trickle_grace_period' (UINT4) succeeded: 5000

insert 'ice.tcp' (registry) succeeded: ice.tcp

insert 'ice.tcp.so_sock_count' (INT4) succeeded: 0

insert 'ice.tcp.listen_backlog' (INT4) succeeded: 10

insert 'ice.tcp.disable' (char) succeeded: \000

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) has no stream matching stream 0-1531925753097790 (id=25769803783 url=http://localhost:4242/call/1 aLevel=1

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) has no stream matching stream 0-1531925753097790 (id=25769803783 url=http://localhost:4242/call/1 aLevel=2

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) no streams with non-empty check lists

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) no streams with pre-answer requests

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) no checks to start

Unrecognized attribute: 0x802b

STUN-CLIENT(srflx(IP4:10.0.8.47:57340/UDP|turn.example.com:443)): Received response; processing

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate srflx(IP4:10.0.8.47:57340/UDP|turn.example.com:443)

Write buffer not empty for IP4:0.0.0.0:443/TCP 44 - already armed (@0x160026df4), not connected

STUN-CLIENT(relay(IP4:10.0.8.47:57340/UDP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:57340/UDP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

Unrecognized attribute: 0x802b

STUN-CLIENT(srflx(IP4:10.0.8.47:53521/UDP|turn.example.com:443)): Received response; processing

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate srflx(IP4:10.0.8.47:53521/UDP|turn.example.com:443)

STUN-CLIENT(relay(IP4:10.0.8.47:57340/UDP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:57340/UDP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:63335/UDP lifetime=3600

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:57340/UDP|IP4:0.0.0.0:63335/UDP)

Write buffer not empty for IP4:0.0.0.0:443/TCP 44 - already armed (@0x1600291f4), not connected

STUN-CLIENT(relay(IP4:10.0.8.47:53521/UDP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:53521/UDP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

STUN-CLIENT(relay(IP4:10.0.8.47:53521/UDP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:53521/UDP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:50605/UDP lifetime=3600

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:53521/UDP|IP4:0.0.0.0:50605/UDP)

Firing write callback (0)

Invoking writable_cb on connected (44)

Writable_cb IP4:0.0.0.0:443/TCP (0 (0x1600291f4) pending)

Firing write callback (0)

Invoking writable_cb on connected (44)

Writable_cb IP4:0.0.0.0:443/TCP (0 (0x160026df4) pending)

UpdateBufferedAmount: (tracking 1): 0, waiting: no

UpdateBufferedAmount: (tracking 1): 0, waiting: no

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

UpdateBufferedAmount: (tracking 2): 0, waiting: no

UpdateBufferedAmount: (tracking 2): 0, waiting: no

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:58399/UDP lifetime=3600

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:0/TCP|IP4:0.0.0.0:58399/UDP)

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:56773/UDP lifetime=3600

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:0/TCP|IP4:0.0.0.0:56773/UDP)

ICE(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default) Trickle grace period is over; marking every component with only failed pairs as failed.

ICE-PEER(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default)/STREAM(0-1531925753097790 (id=25769803783 url=http://localhost:4242/call/1 aLevel=0)/COMP(1): All pairs are failed, and grace period has elapsed. Marking component as failed.

ICE-PEER(PC:1531925753097790 (id=25769803783 url=http://localhost:4242/call/1:default): all checks completed success=0 fail=1

TURN(relay(IP4:10.0.8.47:57340/UDP|turn.example.com:443)): deallocating

TURN(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)): deallocating

TURN(relay(IP4:10.0.8.47:53521/UDP|turn.example.com:443)): deallocating

TURN(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)): deallocating

UpdateBufferedAmount: (tracking 3): 0, waiting: no

UpdateBufferedAmount: (tracking 3): 0, waiting: no

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:173 function nr_socket_multi_tcp_create_stun_server_socket skipping UDP STUN server(addr:)

/builds/worker/workspace/build/src/media/mtransport/third_party/nICEr/src/net/nr_socket_multi_tcp.c:617 function nr_socket_multi_tcp_listen failed with error 3

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): failed to create passive TCP host candidate: 3

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) has no stream matching stream 0-1531926015943360 (id=25769803783 url=http://localhost:4242/call/1 aLevel=1

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) has no stream matching stream 0-1531926015943360 (id=25769803783 url=http://localhost:4242/call/1 aLevel=2

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) no streams with non-empty check lists

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) no streams with pre-answer requests

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) no checks to start

Unrecognized attribute: 0x802b

STUN-CLIENT(srflx(IP4:10.0.8.47:55447/UDP|turn.example.com:443)): Received response; processing

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate srflx(IP4:10.0.8.47:55447/UDP|turn.example.com:443)

Write buffer not empty for IP4:0.0.0.0:443/TCP 44 - already armed (@0x14d18e5f4), not connected

STUN-CLIENT(relay(IP4:10.0.8.47:55447/UDP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:55447/UDP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

STUN-CLIENT(relay(IP4:10.0.8.47:55447/UDP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:55447/UDP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:56397/UDP lifetime=3600

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:55447/UDP|IP4:0.0.0.0:56397/UDP)

Unrecognized attribute: 0x802b

STUN-CLIENT(srflx(IP4:10.0.8.47:57093/UDP|turn.example.com:443)): Received response; processing

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate srflx(IP4:10.0.8.47:57093/UDP|turn.example.com:443)

Write buffer not empty for IP4:0.0.0.0:443/TCP 44 - already armed (@0x14d18fdf4), not connected

STUN-CLIENT(relay(IP4:10.0.8.47:57093/UDP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:57093/UDP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

STUN-CLIENT(relay(IP4:10.0.8.47:57093/UDP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:57093/UDP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:60501/UDP lifetime=3600

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:57093/UDP|IP4:0.0.0.0:60501/UDP)

Firing write callback (0)

Invoking writable_cb on connected (44)

Writable_cb IP4:0.0.0.0:443/TCP (0 (0x14d18fdf4) pending)

Firing write callback (0)

Invoking writable_cb on connected (44)

Writable_cb IP4:0.0.0.0:443/TCP (0 (0x14d18e5f4) pending)

UpdateBufferedAmount: (tracking 1): 0, waiting: no

UpdateBufferedAmount: (tracking 1): 0, waiting: no

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Error processing response: Retry may be possible, stun error code 401.

UpdateBufferedAmount: (tracking 2): 0, waiting: no

UpdateBufferedAmount: (tracking 2): 0, waiting: no

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:50309/UDP lifetime=3600

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:0/TCP|IP4:0.0.0.0:50309/UDP)

STUN-CLIENT(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)::TURN): Received response; processing

TURN(relay(IP4:10.0.8.47:0/TCP|turn.example.com:443)): Succesfully allocated addr IP4:0.0.0.0:62199/UDP lifetime=3600

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) pairing local trickle ICE candidate turn-relay(IP4:10.0.8.47:0/TCP|IP4:0.0.0.0:62199/UDP)

ICE(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1): peer (PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default) Trickle grace period is over; marking every component with only failed pairs as failed.

ICE-PEER(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default)/STREAM(0-1531926015943360 (id=25769803783 url=http://localhost:4242/call/1 aLevel=0)/COMP(1): All pairs are failed, and grace period has elapsed. Marking component as failed.

ICE-PEER(PC:1531926015943360 (id=25769803783 url=http://localhost:4242/call/1:default): all checks completed success=0 fail=1

+++++++ END ++++++++
</code>
Answer: The problem happens because both <code>zone.js</code> and <code>adapter-js</code> are putting their wrappers on top of various RTC methods.
The solution is to add the line below, at the end of the <code>polyfills.ts</code> file.
<code>import 'zone.js/dist/webapis-rtc-peer-connection';
</code>
More info:

https://github.com/angular/zone.js/issues/883
https://github.com/angular/zone.js/issues/920
https://github.com/angular/zone.js/issues/948
https://github.com/angular/zone.js/issues/1019


Why the probability of a sequence is simply the multiplication?

Question: In studying the random walk in one dimension I had a doubt on basic probability. The point is the following: we consider a random walk with $N$ steps consiting of $n_1$ steps to the right and $n_2$ steps to the left. The probability that one step will be to the right is $p$ and the probability one step will be to the left is $q = 1-p$. Also, it is considered each step is independent of the last one.
The book states, however, that the probability of getting any one sequence with $n_1$ steps to the right is simply $p^{n_1}q^{N-n_1}$, that is, multiplying $p$ by itself $n_1$ times.
Why is that? I know from probability that if $A$ and $B$ are independent events then $P(A\cap B) = P(A)P(B)$ and the result would follow.
But I can't see how this relates to the present case. Indeed, $A,B$ as above are events of the same sample space $S$, but on the random walk problem it seems we have two sample spaces:

The sample space $S_1$ of the experiment of watching one step. Then $S_1 = \{-1,1\}$ being $-1$ to the left and $1$ to the right, and we have $P(\{-1\}) = q$ and $P(\{1\}) = p$.
The sample space $S_2$ of the experiment of watching $N$ steps. Then $S_2 = \{(i_1,\dots, i_N) : i_k = -1,1\}$ that is all sequences of steps or to the right or to the left.

How from this could we deduce that the probabilty of any sequence with $n_1$ steps to the right, that is any sequence $(i_1,\dots, i_N)$ with $n_1$ $1$'s appearing is $p^{n_1}q^{N-n_1}$?
Comment: A sequence of length $N$ that has $n_1$ steps to the right has $N-n_1$ to the left. Any particular such sequence has probability $p^{n_1}q^{N-n_1}$.
Comment: Yes @AndreNicolas, but how can I prove this?
Comment: Do you mean how do we prove that if $A$ and $B$ are independent then $\Pr(A\cap B)=\Pr(A)\Pr(B)$? From the formal point of view, this is the definition of independence. In a concrete situation, we have to decide whether the assumption of independence is reasonable. Note that the formula I gave is somewhat different from the one in the OP.
Comment: I mean how to use this fact to prove the formula for the probability of getting $n_1$ steps to the right. I'm not being able to do it because as I explain on the question it seems to exist more than one sample space on the problem. And also, your formula is right, consulting the book I wrote the wrong formula, thanks for pointing it out.
Comment: Let $A_i$ be the event we go to the right at step $i$, and $B_i$ be the event we go to the left. We want $\Pr(C_1\cap C_2\cap \cdots \cap C_N)$, where $n_1$ of the $C_i$ are $A_i$ and $N-n_1$ of the $C_i$ are $B_i$.
Answer: The correct way to define the random walk is to consider independent identically distributed random variables $\xi_n$, with $P(\xi_n=+1)=p$ and $P(\xi_n=-1)=1-p$, and then consider the sum $X_n=\xi_1+\dots+\xi_n$ which gives you the position of the random walk started at $0$ at time $n$.
You can think of the sample space as being sequences of $N$ coin-flips of an unfair coin. If it's heads ($\xi_n=+1$) you move right, if it is tails ($\xi_n=-1$) you move left.
The probability that you have a particular sequence of (at least) $n_1$ steps to the right, say the first steps from time $1$ to $n_1$ are to the right,  is
$P(\xi_1=1,\xi_2=1,\dots,\xi_{n_1}=1)= P(\xi_1=1)P(\xi_2=1)\cdots P(\xi_{n_1}=1)=p^{n_1}$
Similarly, the probability of any particular sequence consisting of at least $n_1$ steps to the right is $p^{n_1}$.
Comment: Thanks for answering @DimitriosNt, it makes more sense this way really, but just one problem. I wrote the formula wrong, the book really states that it should be $p^{n_1}q^{N-n_1}$. How this follows from that idea you presented?
Comment: As I wrote, my formula gives you the probability that you have AT LEAST $n_1$ steps to the right. If you want to have precisely $n_1$ steps to the right this means that the rest $N-n_1$ steps are to the left, i.e. $\xi_i=-1$ for $N-n_1$ $i$'s. Therefore using the same idea and independence you can derive the reslt $p^{n_1}q^{N-n_1}$


Disable Log4j INFO-level logging when using FOP

Question: How can I remove the INFO level logging when generating PDF files using FOP?  I have this in my log4j.properties file:
log4j.logger.org.apache.fop = WARN
but I'm still getting these for each PDF file that is created:
[INFO] Using com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser as SAX2 Parser
[INFO] setting up fonts
Any ideas?  I looked @ this entry but it didn't answer my question:
Filter unwanted INFO-Messages from Logger
Answer: Are you sure the log entry is (a) from a class in org.apache.fop and (b) from log4j?
It may be a log output from one of FOP's sub packages like batik.
You can change your log4j appender layout to show the class of origin (e.g.,
<code>log4j.appender.stdout.layout.ConversionPattern=%d %5p (%F:%L) - %m%n
</code>
), then you will know.


Interpolation vs nonlinear Regression

Question: I was playing with the concept of Interpolation in Python and ended up with this plot:
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x = np.linspace(0, 10, num=11, endpoint=True)
cosx = np.cos(-x**2/9.0)
linearInterpolateFunction = interp1d(x, cosx)
cubicInterpoloateFunction = interp1d(x, cosx, kind='cubic')

xnew = np.linspace(0, 10, num=41, endpoint=True)
plt.plot(x, cosx, 'o', xnew, linearInterpolateFunction(xnew), '-', xnew, cubicInterpoloateFunction(xnew), '--')
plt.legend(['Original Data', 'Linear Interpolate', 'Cubic Interpolate'], loc='best')

The way Cubic Interpolation models the function made me think of nonlinear modeling approaches and nonlinear Regression.
Could you please explain to me what are the differences between the two (nonLinear Regression and Cubic Interpolation) and  and if I could use Cubic Interpolation for modeling my data? what are the pros and cons to this? If you could provide me with applicable examples, that'd be great.
by the way, I've seen this answer to my question before but does its example on why you better use Regression still count even when using Cubic Interpolation instead of Linear Interpolation ?
Thanks...
Comment: Cubic interpolation that honours data points is equivalent to a model with as many parameter values as distinct data points. A perfect fit, but no kind of explanation, yet possibly useful for prediction. Note, however, even in your fairly well-behaved data example, cubic interpolation's willingness to go roller-coaster. In contrast most models provide some kind of smooth structure that mimics general patterns in the data, not exact details.
Comment: Yes, the example stands perfectly for this case too. You just impose some additional smoothness constraints (in the case of cubic interpolation).
Comment: Although I'm unsure which of regression, interpolation, nonlinear regression, and cubic splines "the two" refers to, it's important to be aware of their different purposes.  Some of these methods aim at *understanding* or *explanation* and others at *prediction.*  "Interpolation" is usually meant in the sense of "predict a response at intermediate values of the regressors."
Comment: so... can I use Interpolation for prediction with a high level of confidence compared to other methods? or my example is just too good to show the flaws in Interpolation? if it is flawed, could you please show me an example where Interpolation is flawed compared to (for example) nonlinear regression methods?
Comment: I found my answer but the only thing still bugging me is if we could use Cubic Interpolation when trying to predict inside the domain of the original function ? could it be as good as other methods?
Comment: If your software allows you to extrapolate, cubics can shoot up or down, as your graph implies. Usually considered dangerous. But that's true of most extrapolation methods. What's more they typically depend on nearby points only.
Answer: I was completely unaware of one important fact : Interpolation only works in the data domain it was provided with. in this case it is 11 points between 0 and 10... anything out of this domain results in an error...
Just changing this :
xnew = np.linspace(0, 10, num=11, endpoint=True)

to this :
xnew = np.linspace(0, 11, num=11, endpoint=True)

results in an error...
Interpolation seems to be unable to take even 1 more step than what it was already provided with... if I try to Interpolate out of the domain range, I will get an error (which makes sense to me now!).
Thank you all... I wasn't aware of the fundamental characteristics of Interpolation... Sorry!

Interpolation vs nonlinear Regression


A conjecture relating to the limit of a sequence of matrix determinants

Question: Let $(a_n)$ be a sequence. We define the sequence $(b_n)$ to be $b_n=\det(A)$ where $A$ is a square matrix of order $n$ such that
$$A_{1,1}=a_1,\dots,A_{1,n}=a_n \\
\vdots\\ A_{n,1}=a_{n^2-n+1},\dots,A_{n,n}=a_{n^2}
.$$
I conjecture that if $(a_n)$ converges to a real number (or maybe even bounded) then $(b_n)$ converges to zero. The reason for this conjecture is simple. It seems to be the "limit version" of the fact that if you have a square matrix with all the entries being the same then the determinant is zero.
Any thoughts?
Comment: In light of Alex Ravsky's counterexample below, the best way I can think of to fix this conjecture is to say that if $(a_n) \in \ell^2$, then $b_n \rightarrow 0$ by [Hadamard's inequality](https://en.wikipedia.org/wiki/Hadamard%27s_inequality) (since eventually the norm of every row after the first will be small if $(a_n) \in \ell^2$).
Comment: I don't quite like your analogy, as we certainly will never have all entries the same. However, given $\epsilon$, there is $N$ so that for $n>N$, the entries of the *last two rows* of the $n\times n$ matrix will be within $\epsilon$ of one another. Think about a row operation to get the last row with the absolute value of its entries $<\epsilon$. But I don't see a universal upper bound on the $n$ cofactors of those entries. Do you?
Comment: $\ell^2$ is the set of sequences $(a_n)$ such that $\sum_{n=1}^{\infty} a_n^2 < \infty$. The useful part for Hadamard's inequality is that for every $\varepsilon > 0$ there is $N$ such that $\sum_{n=N}^{\infty} a_n^2 < \varepsilon$.
Comment: @MichaelJesurum What does $ \ell^2$ mean?
Answer: There exists the following counterexample for the conjecture. Let $a_1=a_2=1$ and $n(1)=0$. Suppose that we already constructed the members $a_1,\dots,a_{2^{n(k)}+1}$ for some natural $k$. Let these members constitute the first row of the square matrix. Fill all entries of the first column of the matrix  but the first by zeroes. Finally, fill its bottom right corner by any Hadamard_matrix of order $2^{n(k)}$, multiplied by $2^{-n(k)/2}$. Then the matrix will have the determinant $1$. Finally, pick any $n(k+1)$ such that
$2^{n(k)}+1$ is not smaller than the number $N$ of already determined members of the sequence $(a_n)$ and
put $a_{N+1}=\dots =a_{2^{n(k+1)}+1}=0$.
Comment: @user1551 Thanks for your kind words. Right, we do not need $a_2=1$, but we need to assign to $a_2$ some value in order to stard the induction with $n(1)=0$.
Comment: Nice construction, but why do you need $a_2=1$?
Comment: @user1551 Whoops! Thanks for the correction


How to validate/match data from different files in C#

Question:
I'm creating a fake flight tracker for a project and need to check that the sum of lines in a Flight.csv file (all the individual flights) matches a the numOfFlights variable in an Airport.csv file. How can I cross-examine this data from the two files w/out having to merge them?

Here is relevant code, lmk if more is necessary to figuring out the problem.
static void Main()
    {
        Flight[] flight = new Flight[1000];
        Airport[] airport = new Airport[1000];
        int flightCount = 0;
        int airportCount = 0;

        ReadFlightFile(ref flight, ref flightCount);
        ReadAirportFile(ref airport, ref airportCount);

        int numRecords = flightCount;

        OutputFlightMenu();
        string userInput = "----";
        while (userInput != "exit")
        {
            userInput = ReadLine().ToLower();
            Clear();
            OutputFlightMenu();
            switch (userInput)
            {
                case "passengers":
                    //Stuff
                    break;
                case "time":
                    //Stuff
                    break;
                case "average":
                    //Stuff
                    break;
                case "sub":
                    OutputSubMenu();
                    string userInput2 = "----";
                    while (userInput2 != "quit")
                    {
                        userInput2 = ReadLine().ToLower();
                        Clear();
                        OutputSubMenu();
                        switch (userInput2)
                        {
                            case "flight":
                                //Stuff
                                break;
                            case "count":
                                //Stuff
                                break;
                            case "airline":
                                //Stuff
                                break;
                            default:
                                WriteLine("Invalid input. Please try again.");
                                break;

                        }
                    }
                    Clear();
                    WriteLine("====Exiting System===");
                    break;
                case "report":
                    //Stuff
                    break;
                default:
                    WriteLine("Invalid input. Please try again.");
                    break;
            }
        }
        Clear();
        WriteLine("=====Goodbye=====");
        ReadKey();

    }

    public static void ReadFlightFile(ref Flight[] flight, ref int flightCount)
    {
        string path = "Flight.csv";
        FileStream fs = new FileStream(path, FileMode.Open);
        StreamReader sr = new StreamReader(fs);
        while (sr.Peek() > -1)
        {
            string line = sr.ReadLine();
            string[] flightArray = line.Split(',');

            flight[flightCount] = new Flight(int.Parse(flightArray[0]), flightArray[1], int.Parse(flightArray[2]),
                int.Parse(flightArray[3]), int.Parse(flightArray[4]));

            flightCount++;

        }

    }
    //Basic Read Method
    public static void ReadAirportFile(ref Airport[] airport, ref int airportCount)
    {
        string path = "Airport.csv";
        FileStream fs = new FileStream(path, FileMode.Open);
        StreamReader sr = new StreamReader(fs);
        while (sr.Peek() > -1)
        {
            string line = sr.ReadLine();
            string[] airportArray = line.Split(',');

            airport[airportCount] = new Airport(int.Parse(airportArray[0]), airportArray[1], airportArray[2],
                int.Parse(airportArray[3]), DateTime.Parse(airportArray[4]));

            airportCount++;
        }
    }

Here is the data from the respective files:
Flight.csv:
3446,Delta,91,120,120
2789,United,34,56,78
9078,American,200,240,210
9079,American,67,156,165
4567,Southwest,89,89,91
6799,Delta,95,67,55
1265,United,102,187,175
8421,American,12,191,191
3332,Southwest,78,45,44
Airport.csv:
9000,ATL,Atlanta,9,12/9/2017
As you can see, the numOfFlights element in the airport array (9) DOES match the sum of the flights.

For the intents of this project, I already know that the data will match, but I need to be able to validate that.
Thank you to anyone who can help.
Comment: `As you can see, the numOfFlights element in the airport array (9) DOES match the sum of the flights.` I can't see that. Can you break down how you came to that conclusion?
Comment: just compare your `numOfFlights` with `flightCount`
Comment: Please explain *in words* what you're trying to do. "cross-examine the data" doesn't mean anything, and it's not at all clear from your code what your intentions are. Is there a problem with your code? Does it crash or not compile, or what?
Comment: @mjwills Certainly! The fourth element in the Airport.csv (9) matches the literal total # of flights in the Flight.csv.
Comment: Is there only one Airport record in the file? What if there are more? If there can't be more, why use an array?
Answer: airport.Where(o=>o.numOfFlights==flightCount) will return the airports that has the numOfFlights equal to flightCount. And you should use List instead of array to store the Flight and Airport
Answer: This is much simpler than you are making it.
To Count the number of lines in Flight.csv, you can use the following:
int lineCount = File.ReadAllLines("Your/Path/To/Flight.csv").Count();

If you have headings you should -1
To get the number of flights in the Airport.csv, just open it, split into an array, and grab the number like so:
string[] AirportContents = File.ReadAllText("Your/Path/To/Airport.csv").Split(',');
int flightsToday = Convert.ToInt32(AirportContents[3]);

If there are headings you can put the file contents into a List and read the second item[1] (But you didnt put headings in your example so)
Once you have those 2 numbers you can do anything you want with them.
Answer: Better style to have your Read methods accept a file name and return a List or array (where the size of the collection is your Count value):
public static IList<Flight> ReadFlightFile(string filePath)
{
    var result = new List<Flight>();
    foreach(var line in File.ReadLines(filePath))
    {
        string[] flightArray = line.Split(',');

        result.Add(new Flight(int.Parse(flightArray[0]), flightArray[1], int.Parse(flightArray[2]),
            int.Parse(flightArray[3]), int.Parse(flightArray[4]));

    }
    return result;
}

//Basic Read Method
public static IList<Airport> ReadAirportFile(string filePath)
{
    var result = new List<Airport>();
    foreach(string line in File.ReadLines(filePath))
    {
        string[] airportArray = line.Split(',');

        result.Add(new Airport(int.Parse(airportArray[0]), airportArray[1], airportArray[2],
            int.Parse(airportArray[3]), DateTime.Parse(airportArray[4]));
    }
    return result;
}

Do that, and you can add this to your other code:
static void Main()
{
    var flights = ReadFlightFile("Flight.csv");
    var airport = ReadAirportFile("Airport.csv");

    if (airport[0].numOfFlights == flights.Count)
    {
        //things match
    }
    else
    {
        //things don't match
    }

    // rest of your code is down here:

}


Find the inverse of a matrix with a variable

Question: $$X=
\begin{pmatrix}
2-n & 1 & 1 & 1 & \ldots & 1 & 1 \\
1 & 2-n & 1 & 1 & \ldots & 1 & 1 \\
\vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
1 & 1 & 1 & 1 & \ldots & 2-n & 1 \\
1 & 1 & 1 & 1 & \ldots & 1 & 2-n\end{pmatrix}_{n\times n}
$$
Which means that the matrix with the size of $n\times n$ have $n-2$ along the diagonal and $1$ everywhere else.
Help please, I am stuck with this problem.
Comment: How is this matrix infinite if you say it is $n\times n$?
Comment: sorry, I dont know how that infinite got there. editing right away.
Answer: Hint: Use the Sherman–Morrison formula on $$X=\text{diag}(1-n)_{n\times n}+\begin{pmatrix} 1\\ \vdots \\1\end{pmatrix}_{n\times 1}\begin{pmatrix}1 & \ldots &1 \end{pmatrix}_{1\times n}.$$
Answer: HINT: Let $B$ be the $n\times n$ matrix of ones. Then $XB=B$, so
$$X(B-I)=XB-X=B-X=(n-1)I\;,$$
where $I$ is the $n\times n$ identity matrix.
By the way, manually calculating the inverses for $n=2$ and $n=3$ was enough to suggest what the answer ought to be, and discovering the argument suggested above was then quite easy.
Comment: @GitGud: Thanks for letting me know.
Comment: I took the liberty of naming the matrix in the question as  $X$, in the question.
Answer: If you see in terms of systems rather than matrices, you must solve
$X(x_1,x_2,\ldots,x_n)=(y_1,y_2,\ldots,y_n)$ where the $y_i$ are given
and the $x_i$ are the unknowns.
Adding everything up, you obtain
$$
x_1+x_2+\ldots +x_n=y_1+y_2+\ldots y_n (1)
$$
Then, comparing (1) with the $i$-th equation gives you the value of
$x_i$.


Use Fisher's Exact Test or a Hypergeometric Test?

Question: I'm looking to test for set enrichment and I'm wondering whether a fisher's exact test or hypergeometric test is more appropriate (and, if there isn't a straightforward answer, what the relative merits are).
To lay out an example problem, I have a set of 400 objects, 150 of which belong to class A. I draw 50 objects, and there is an overlap of 15.
I could lay this out as a matrix (15, 50-15, 150-15, and 400 - 50 - 150 + 15) and use this matrix to calculate a fisher's exact test. Alternately, I could use the hypergeometric distribution in R and do phyper(15, 150, 400-150, 50).
Is one of these preferably to the other and, if so, why? Thanks!
Comment: I don't understand the difference.  Under the null hypothesis of no association and fixing the marginal totals Fisher's test statistic has a hypergeometric distribution.
Answer: Hypergeometric test assesses the extremeness of observing x or more of "good" cases (overlap) and thus same as a one-sided Fisher's exact test (where the alternative hypothesis is "greater" in R jargon). If you do not care about the directionality then you can use two-sided Fisher's exact test.
Answer: Just a comment to show the result of R commands, both approaches being the same.
<code>> phyper(15, 150, 400-150, 50)
[1] 0.1549789
> fisher.test(matrix(c(15, 50-15, 150-15, 400 - 50 - 150 + 15), nr = 2),
              alternative = "less")$p.value
[1] 0.1549789
</code>


Implementations of JavaScript stream ciphers?

Question: Are there any free to use implementations of stream ciphers available for JavaScript?
Especially interested in HC-128, Salsa20/12 or SOSEMANUK as these are recommended by The eSTREAM Project
Answer: Section D of Symmetric Cryptography in Javascript refers to a "Javascript implementation of Salsa20/12" but I can't find the implementation on their github repo.

We compared Javascript AES with a Javascript implementation of
  Salsa20/12 [20], one of the fastest eSTREAM ciphers. A native x86
  implementation of Salsa20/12 is about 5 times faster than a native
  implementation of 128-bit AES. Surprisingly, Table VII shows that when
  both algorithms are implemented in Javascript, Salsa 20/12 is
  comparable in speed to AES. We believe that this discrepancy is
  primarily due to Javascript's lack of 128-bit SIMD instructions or of
  64-bit registers, and secondarily due to Salsa20/12's larger state
  spilling to memory.
Answer: This is the version Kevin Hakanson was referring to: https://gist.github.com/dchest/4126510 . It has a pretty decent I/O throughput (110MB/s), and seems to follow the spec to the letter. I have not, however, tested it, as I have no reference to test it against besides looking at the ops and compare them to the RFC...so use at your own risk!
Comment: (For SOSEMANUK, I doubt you'll find an implementation in pure JS, as one part of the cipher is a round of Serpent - and I'm not sure if anyone has written this. I'll write it if I have some spare time)
Answer: I'm not sure about any JavaScript implementations of those, but if you have a serverside implementation, you can think about sending it to your server via an ajax request (over https) and getting the result as the response.  :)
Comment: This would be significantly slower than running it in JS. Not just this, but it also exposes you to potential MITM attacks in specific cases.


Language pages are triplicated

Question: Our website was developed with Drupal and we only have a small set of Spanish language pages on a primarily English website.
My question is, I'm getting THREE pages generated for every one page:

.com/node/11
.com/espanol/node/11
.com/conveniences/gift-cards -- all of these use the same English content.

The dev team says this is working as intended as long as there is no Spanish content, we get a Spanish URL as well.
We apparently have 3x the pages now because of this.
Is there something we can do?
Comment: If the content is the same, and you have proper rel canonical links in place, you will be good at least for SEO. But it might further help to write some redirect rules to help from all three pages getting indexed in google. If there is a common pattern to these replications, you can use path patterns to create redirects
Comment: Can't really say too much about "works as intended" without more info.
Comment: You heard the dev team, so whats the issue...? You have 3 URLs that point to 1 (English) page. Its not saved 3 times in the dstabase.
Comment: Because all three pages are in Google for no good reason. If it's not in Spanish, why does it make a Spanish URL with English content? Makes no sense.
Answer: As already stated in comments, you have one page but more than one link/path to access it. From the SEO perspective it is something to consider, eventhough Drupal "knows" this is the same content.
The /node/11 is the base URI for your English content, you can't be without it, it's a Drupal internal.
/conveniences/gift-cards is the path alias of the /node/11. It is usually created with the help of Path or Pathauto modules to improve the URIs for better UX and better SEO. They're usually coupled with Global Redirect or Redirect modules that automatically and permanently redirect to the alias. This way search engines only ever see one URI for this content.
/espanol/node/11 This link comes from Multilingual features, actually the specific way you have them configured. It's important to distinguish two independent parts of the website that can be translated: Interface and Content. Roughly speaking, Content is what usually goes into a node, and Interface is everything else surrounding the node.
Multilingual sites need a way to determine which Interface language to display, and which Content exactly when a request is made (a link clicked). Usually this is done by constructing links that contain both information. The language prefix is being used to determine the Interface language, and what follows it is a normal path to some content.
The /espanol/ is the language prefix and is telling Drupal to display the interface in Spanish language. /node/11 is the content path and is telling Drupal to pull the contents of node 11 from the database. When you put that together you have Spanish interface, but you're looking at English content. This might be the case for a Spanish translator: they are using their native language as the default interface language, but they might want to edit the English content.
In D7 every translation is a new node, but in D8 all translations of the same node share the NID, so some configuration might differ there.
Multi-Language Link and Redirect (MultiLink) module can help with some multilingual link handling, automatically changing the output of links to point to the translation of the content based on the current interface language, so you don't mix interface and content languages, unless you create it like that on purpose in menus.
The way to correctly tell search engines about pages being translations of one another is through hreflang: Hreflang.
Comment: Thank you for explaining. I'll pass along your answer to the dev team.

Language pages are triplicated


How to use '||' in if-else statement in iphone appllication?

Question: if((([txtFldO1.text length] == 0 ) || ([txtFldO2.text length] == 0 ) ||
([txtFldO3.text length] == 0 ) || ([txtFldO4.text length] == 0 ) ||
([txtFldO5.text length] == 0 )) && (([txtFldR1.text length]== 0) ||
([txtFldR2.text length]== 0) || ([txtFldR3.text length]== 0) || ([txtFldR4.text length]== 0) || ([txtFldR5.text length]== 0)))
    {
             //alert
             //return
         }

This statement does not work. It does access all of the propeties. Could anyone tell me why?
I need to access one txtFldO and one txtFldR.
Comment: @Nilesh: How does it not work? What error messages do you get? @Paska: No there isn't.
Comment: Is there a [code] tag!!!
Comment: @WTP correct :), but I suggest to indent code...
Comment: This functionality would be cleaner with more descriptive variable names, and a loop instead of repeated syntax in a long if clause.  For example, something like: BOOL aFieldIsEmpty = NO; for (int i = 0; i < numFields; ++i) if ([textField[i] length] == 0) aFieldIsEmpty = YES; /* then outside the for loop */ if (aFieldIsEmpty) { /* react to a field being empty */ }  Hard to code in comments here!
Answer: To access properties, try SELF
self.txtFld00.text.length
Answer: It should be like this.
if([txtFldO1.text length] == 0 || [txtFldO2.text length] == 0 || [txtFldO3.text length] == 0 || [txtFldO4.text length] == 0){

// Code here

}

You don't need to put parentheses before condition. Just put one parentheses like above example.
Hope this help.


AVPlayer playing even though rate property is 0

Question: This other SO post suggests when the rate property for an AVPlayer is 0, it means the AVPlayer is no longer playing. We use the observer code below to loop a video, but sometimes invoking the pause function on the player fails to break the looping. When debugging, the rate property evaluates to 0.
1) Is the linked SO post wrong, in that a rate value of 0 does not mean the player is paused?
2) Is the continuous looping, even after the pause function is invoked, some kind of race condition where the pause function comes after the playerItemDidReachEnd notification is already issued?
NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)

private func playVideo() {
    player.seekToTime(kCMTimeZero)
    player.actionAtItemEnd = .Pause
    player.play()
}

Answer: when setting up the player:
player.actionAtItemEnd = AVPlayerActionAtItemEnd.None

NSNotificationCenter.defaultCenter().addObserver(self,
                                                 selector: "playerItemDidReachEnd:",
                                                 name: AVPlayerItemDidPlayToEndTimeNotification,
                                                 object: player.currentItem)

this will prevent the player to pause at the end.
in the notification:
func playerItemDidReachEnd(notification: NSNotification) {
    let p: AVPlayerItem = notification.object as! AVPlayerItem
    p.seekToTime(kCMTimeZero)
}

this will rewind the movie.
Don't forget to unregister the notification when releasing the player.