Como chamar um ID no HTML mais de uma vez?

Question: Como chamar um id mais de uma vez ?

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Agenda</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <link rel="stylesheet" href="css/w3.css">

<?php
error_reporting (E_ALL & ~ E_NOTICE & ~ E_DEPRECATED);
// definições de host, database, usuário e senha
$host = "localhost";
$db   = "agenda";
$user = "root";
$pass = "";
// conecta ao banco de dados
$con = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR);
// seleciona a base de dados em que vamos trabalhar
mysql_select_db($db, $con);
$consulta = $_GET['consulta'];
// cria a instrução SQL que vai selecionar os dados
$query = sprintf("SELECT id, NOME, EMAIL, TELEFONE, TELEFONE2, TELEFONE3, TELEFONE4, EMPRESA, ENDERECO FROM contatos WHERE `contatos`.`NOME` LIKE  '$consulta'");
// executa a query
$dados = mysql_query($query, $con) or die(mysql_error());
// transforma os dados em um array
$linha = mysql_fetch_assoc($dados);
// calcula quantos dados retornaram
$total = mysql_num_rows($dados);
?>

   <button class="btn btn-success center">Novo Contato</button>
   <button  class="btn btn-info center">Atualizar</button>
   <button class="btn btn-warning center">Editar</button>
   <button class="btn btn-danger center">Sair</button>

  O Modo de edição está  ATIVO

<form method="GET" action="busca.php?consulta=<?$consulta?>">
Buscar:
<input type="text" value="<?=$consulta?>" id="consulta" name="consulta" maxlength="255" required />
<button type="submit" class="btn-primary"></button>
</form>

   Nome
   Email
   Telefones
   Empresa
   Endereço

   Deletar
   Editar

<?php
 // se o número de resultados for maior que zero, mostra os dados
 if($total > 0) {
  // inicia o loop que vai mostrar todos os dados
  do {

?>

   <?=$linha['NOME']?>
   <?=$linha['EMAIL']?>
   <?=$linha['TELEFONE']?>

   <?=$linha['TELEFONE2']?>

   <?=$linha['TELEFONE3']?>

   <?=$linha['TELEFONE4']?>
   <?=$linha['EMPRESA']?>
   <?=$linha['ENDERECO']?>

  <a href="#" onclick="javascript: if (confirm('Você realmente deseja excluir este Contato ?'))location.href='excluir.php?id=<?=$linha['id']?>'" style="margin-left:13px">
   <a href="#" onclick="javascript: location.href='troca.php?id=<?=$linha['id']?>'" style="margin-left:13px">

<?php
  // finaliza o loop que vai mostrar os dados
  }while($linha = mysql_fetch_assoc($dados));
 // fim do if
 }
?>

<?php
// tira o resultado da busca da memória
mysql_free_result($dados);
?>

Nesta página o id tst só é exibido quando clicar em editar, porém não é possível chamar o id mais de uma vez. Soluções?
PS: Ignorem a parte de PHP E Mysql
Comment: Por qual motivo quer chamar mais de uma vez?
Comment: Troque o ID para class, qual a necessidade de chama-lo mais de uma vez? explique melhor sua duvida
Comment: Para fazer outras partes desaparecerem também que no caso é o editar e excluir no final da tabela............
Answer: IDs são atributos que não podem ser repetidos, isto porque ID significa "Identidade", ou seja dois elementos não podem ter a mesma identidade.
Talvez o ideal seria criar um ID para cada um, para ajustar você pode trocar o getElementById por outro atributo qualquer, como um atributo customizado HTML5 chamado data-, vamos chamado de data-toggle="...", a função deve ficar assim:
var modoedicao = false; //Inicia como false, modo edição "desligado"

function muda(id){
   modoedicao = !modoedicao;//Alterna entre edição e leitura

   var els = document.querySelectorAll('[data-toggle]');

   for (var i = 0; i < els.length; i++) {
        if (modoedicao) {
           array[i].className = 'aparece';
        } else {
           array[i].className = 'esconde';
        }
   }
}

E os elementos HTML devem ficar assim:

Comment: Obrigado amigo aqui funcionou perfeitamente muito obrigado........


Lower Bound on Rank of a Boolean Matrix

Question: Let $M$ be a Boolean Matrix, i.e. $M \in \{0,1\}^{n\times m}$. I want to figure out a tight lower bound for rank of the matrix $M$.  Rank of a matrix is defined here(wikipedia) for your reference. In this particular question, I also have the following constraints that no two rows are same.
There are many algorithms to find rank of the matrix. But I want a bound just by looking at these properties of the given matrix.
Answer: Suppose there are $n$ rows and $m$ columns, and no two rows are the same.
If the rank is $r$, there are $r$ columns whose entries determine those of the other columns.  Thus we must have $n \le 2^r$, or $r \ge \lceil \log_2(n) \rceil$.
This bound is tight, in that as long as $m \ge \lceil \log_2(n) \rceil$ we can find an $n \times m$ matrix with rank $\lceil \log_2(n) \rceil$ and all rows distinct.  Namely, if
$k = \lceil \log_2(n)\rceil$, there is a $2^k \times k$ matrix whose rows are all members of $\{0,1\}^k$.  Take a subset of $n$ of these rows that includes all possible $(k-1)$-tuples in the first $k-1$ columns with $0$ in the $k$'th, and another $n - 2^{k-1}$ distinct rows having $1$ in the $k$'th column.  All other columns are all $0$.
Comment: Thank you very much. It answers my question precisely.

Lower Bound on Rank of a Boolean Matrix


Arm package: BayesGLM prior

Question: I am modelling a logistic binomial response with around 10 (continuous and categorical) explanatory variables.
I would like to model it as a bayesian glm and had a look at the bayesglm function on ARM (package).
The package says: modeling with independent normal, t, or Cauchy prior distribution for the coefficients.
So since I have both categorical and continuous independent variables followed by a binary response variable, would a cauchy or normal distribution be best suitable (I had previously thought a beta would be best since my response variable was binomial)?
A bit lost on what prior scale and prior df to use from the package.
Can I please get some help and advice on what distribution (and values) I should use.
Can I also ask, are there any other ways I can compute a bayesian model to make predictions? thank you
Answer: As described in Bayesian logit model - intuitive explanation? thread, logistic regression can be described as a linear combination
$$ \eta = \beta_0 + \beta_1 X_1 + ... + \beta_k X_k $$
that is passed through the link function $g$:
$$ g(E(Y)) = \eta $$
where the link function is a logit function
$$ E(Y|X,\beta) = p = \text{logit}^{-1}( \eta ) $$
where $X_1,\dots,X_k$ are the predictor variables and $Y$ is a target variable. What we want to estimate is $\beta_0,\beta_1,\dots,\beta_k$ parameters. When using Bayesian approach, for estimating some parameter of interest we start with defining a prior that describes out out-of-data knowledge about the parameter, and then use the prior combined with the likelihood function (that tells us what the data says about the parameter) to obtain a posterior (i.e. estimate of distribution of the parameter). So we choose priors for parameters and normal, $t$, Cauchy etc. are perfectly fine priors for parameters of regression model or generalized linear model. Beta distribution is inappropriate choice for usual regression model since it would imply that estimated parameters must be bounded in $[0,1]$ interval (you are probably confusing it with beta-binomial model).
The parameters for priors are different story. You need to choose them based on your out-of-data knowledge about the parameters, so this is a problem-specific choice. If you have no a priori knowledge, you can use a weekly informative prior, e.g. normal distribution centered at zero with large variance.
Comment: thank you. i understand the prior option now.

but how could I assign a prior to categorical variables?
I also have gender as a variable, is it still ok to use a normal prior for gender?
Comment: @Silver as I wrote, you do not assign priors to variables in here, but to regression parameters. You do not have different kind of regression parameters for different variables.
Comment: sorry, I'm not that clever and my mind just can't seem to get this right.
I think I understand what you mean now: the prior is the guess for the coefficients
but can you help me with an example:
I know the coefficient for men will be positive/higher (compared to women) and lower for children (compared to adults), how will I set the parameter and prior? or would it be better to sue a non-informative prior since I can't give exact numerical guesses for coefficients?

thank you for the help
Comment: Hi @Tim, do we then, interpret the results the same way as in the classical approach? Example if `genderM` is -0.30, then do we say male patients are 0.74 times *less likely* to be ... as compared to female patients. *or*  male patients have an *odds* of 0.74 times that of female patients in .... Which term is more appropriate?
Comment: @HNSKD the interpretation in [Bayesian](https://stats.stackexchange.com/questions/163034/bayesian-logit-model-intuitive-explanation) and non-Bayesian logistic regression is exactly the same. The difference is that in the Bayesian case you have extra information about the uncertainty of the parameters.

Arm package: BayesGLM prior


async and await in inside app.js file in Node?

Question: <code>app.get("/", function (req, res) {
  async function showData() {
    const res = await fetch("api.openweathermap.org/data/2.5/weather?q=Berlin&appid={apiID}");
    const data = await res.json();
    console.log(data);
  }
})
</code>
//Here when I run node app.js this should log the data inside terminal but I am getting error.
Comment: Why are you using await before res.json()?  could you please explain?
Comment: here await before res.json() is similar to .then. Basically I am using await before res.json() to get the response in JSON format after await the API url link.
Answer: Fetch returns a response stream.
Checkout the answer to this question. Use request-promise/request module or handle the stream returned by fetch.
Comment: In link I saw we are require("request") module to fetch API call. Since in plane JS we don't need to require any module we directly use fetch function and .then() is used to get the date. And in the asked question I am trying follow the same procedure without using request module. Thanks!
Comment: Ok. Try using stream to get data and then in res.on('end',callback) process it, or log it. And I could be inferring this perhaps from the incomplete code, but are you calling showData() somewhere?


Question about Borel sigma algebra

Question: I have a question regarding singletons (unit set) in a Borel-sigma algebra:
Lets say that K is a σ-algebra on a random range [0,100]:
A. Is it true that i can take any singleton in this range [0,100] , lets take for example {5}
and claim that it is an event in the Borel σ-algebra - k  ?
B. If my previous question ('A') is indeed true, does it follow from the next explanation:
we can consider the decreasing sequence of events (a-1/n,a+1/n) where n goes to infinity.
Since any σ-algebra is closed under intersections of countable number of events we get that $\lim_{n->infinity} (a-1/n,a+1/n)$=a is in the σ-algebra, which in out case is 'K'.
Where in our case we would have take 'a' to be 5.
Please correct me if i am wrong with the assumption that the last sequence of events is countable.
Answer: $\lim_{n \to \infty} \cap_{n=1}^\infty [0,1/n] = \{0\}$
$\lim_{n \to \infty} \cap_{n=1}^\infty [100-1/n,100] = \{100\}$
For $a \neq 0,100$
$\lim_{n \to \infty} \cap_{n=1}^\infty [a-1/n,a+1/n] = \{a\}$
Thus, all singletons are contained in $K$. Note that all $[a,b]$ where $0\leq a \leq b \leq 100$ are in the Borel sigma algebra to begin with.
A simpler explanation is that the Borel sigma algebra is the one generated by all open sets. Since sigma algebras are closed under complements, the Borel sigma algebra also contains all closed set, since a set is closed if and only if its complement is open. Singletons are closed sets (in a T1 space, which every metric space is). It is easy to write the singleton as a complement of the open set $((-1,a)\cap [0,100])\cup (a,101) \cap [0,100])$ which is open, since it is the union of two open sets in $[0,100]$.
Comment: Thx, it helped me understand the Borel sigma algebras a bit better.

And just another thought, a 'yes' will suffice if it is true:
Since sigma-algebras are closed under intersections we can get sets which are not continuous by lets say, take the complement of (14,15) and get the set [0,14]Union[15,100].
Comment: By continuous, you presumably mean connected (which in $\mathbb{R}$ means intervals). And the answer is "Of course". Your Borel sigma algebra contains the Cantor set, for example. Or the rational numbers between 0 and 100 inclusive. There are many examples (in fact, "most" of the Borel sets are not nice ones you'd think of off the top of your head - even the open sets, which generate the Borel sigma algebra, are not all intervals (though they can be written as a countable union of disjoint open intervals)).

Question about Borel sigma algebra


Change image object on template using Brother print Android SDK

Question: I have set up label printing from our app using the b-PAC Android SDK (Java). Using the code below I can replace the text from my template with what I want.
// Start creating P-touch Template command print data
Boolean val= myPrinter.startPTTPrint(6, null);
Log.i("print", "startPTTPrint "+val);

// Replace text
myPrinter.replaceText("abcde");

// Trasmit P-touch Template command print data
PrinterStatus status=myPrinter.flushPTTPrint();

I am now trying to replace an image object within the template. I know it can be done in VBScript using:
bpac.Object ob = doc.GetObject("Photo");
ob.SetData(0, @"C:\Photo\635466380534236711.png", 4);

I can't find any Java examples of this within the b-PAC 3.1 SDK help guide and I have only just began coding in Java so I am very much a novice.
Does anyone have experience with the Brother SDK/Java who can point me in the right direction?
Thanks!
Comment: Did you ever find a solution to this?
Comment: I am also looking for a solution to this if anyone has managed it
Comment: I'm looking for the same. Any leads on this?
Comment: I am looking for the same. Any leads guys?
Answer: I got this working
Basically I have a template that I copy to an new file on which I make the changes
The image object in the template is called imgPart, the other objects are textblocks
Dim m_partNum As String = "12345"
Dim m_PartName As String = "Plate Special 1 x 2" & vbCrLf & "4 Studs"
Dim m_PartImage As String = "c:\Danny\myLego\Labels\PartImages\3033.png"
Dim m_template As String = "c:\Danny\myLego\Templates\PRINTME.lbx"
Dim m_target As String = "c:\Danny\myLego\Templates\" & m_partNum & ".lbx"
Dim doc As bpac.DocumentClass = New bpac.DocumentClass
Try
   File.Copy(m_template, m_target, vbTrue)
   If doc.Open(m_target) <> False Then
      doc.GetObject("imgPart").SetData(0, m_PartImage, 4)
      doc.GetObject("txtPartName").Text = m_PartName
      doc.GetObject("txtPartNum").Text = m_partNum
      doc.Save()
      doc.Close()
         Else
          MsgBox("Open Error on Receipt with error")
   End If
Catch ex As Exception
   MsgBox("Error occurred :  " & ex.ToString)
End Try


Creating a page only to be accessed by registered users

Question: at my site tobynews I have users that would be registered as an "author." What I'd like to do is create a page such as an "Author's Resources" page that would only be accessible by someone who is registered as an author through the site. I'm not exactly sure how to approach this, other than trying to connect to the database's user table with a form. Any help is greatly appreciated.
Answer: You could do that using Drupal's role based access control system.
For example, assign the role of "author" to the author users.
You can then restrict access to the "Author Resources" page by user role.
e.g

Create a page using the Views module and adding an access restriction.
Create a page using hook_menu and restrict access to that role in the "access callback"
Answer: Or (following on from David Thomas' answer) if you are using Panels you can restrict access by roles.


Create URL aliases for Entityform submissions

Question: I have the Entityform module installed on a Drupal 7 portal and I've created a new entityform type (let's call it "Preview").
When I land on the list of "Preview" submissions, each submission View link points to [host]/[drupal_base]/entityform/[entityform_id]
What I'd like to get is to change "entityform" term in that url path with something like "preview" term, so that I'll have [host]/[drupal_base]/preview/[entityform_id]
I tried to define a URL alias from the admin configuration panel, but from what I've understood, I can't define an alias with a dynamic [entityform_id] (maybe using a kind of placeholder). Am I wrong about this?
I'm not so skilled in Drupal, so I wonder if there's a way to achieve that result?
Answer: Note: This answer only applies specifically for the input form (I misunderstood the question above)
I was able to accomplish this by using simply modifying the entityform made configuration.

Go to /admin/structure/entityform_types
Click on the edit link for the entity form you wish to change
Scroll to the bottom and in the URL path settings set the specific custom paths that you wish
Save

It's that easy and it works for both the preview and the actual form :)
Comment: Thanks for your answer, but that path works for accessing the "form page". I'd like to override the submission View link
Comment: Ahhh shoot sorry I understand now! Your right the only thing that I can suggest is to you log a bug since that has not been added to the functionality sorry for misunderstanding
Comment: hey no problem mate, thanks a lot for your effort ;)
Answer: You can dynamically create URL aliases for Entityform Type submissions by using the contributed Pathauto and Pathauto Entity modules.
Here's how:

Download, install and enable the Pathauto and Pathauto Entity modules (if they aren't already)
Within Pathauto, enable the Entityform Submission entity type at:
Administration > Configuration > Search and Metadata > URL Aliases > Entities
admin/config/search/path/entities

Create a new default Pathauto pattern for Entityform Submissions using the following replacement patterns:
[entityform:type:label]/[entityform:entityform-id]

The [entityform:type:label] token is the key ingredient and corresponds to the Entityform Type's name or label (e.g. "Preview") and will be lowercased and hyphenated in the alias (e.g. /preview/1234).

Save the Pathauto configuration

Once this is complete, all new Entityform Type submissions will no longer use the default path registered by the Entityform module (i.e. /entityform/1234) and instead use the new alias pattern we defined (i.e. /preview/1234).
You can use the "Bulk Update" feature in Pathauto to add/update/delete any pre-existing Entityform Submissions aliases.
Answer: Pathauto_entity

You can select the entities to be enabled in Home » Administration »
  Configuration » Search and metadata » URL aliases » Entities tab, and
  they will appear in Home » Administration » Configuration » Search and
  metadata » Patterns, where you can define the desired aliases for
  them.
Make sure to define those patterns before trying to create new URL
  aliases (including bulk update), as otherwise they won't be created.
If the Entities tab does not appear, it means that the site has no
  custom entities defined, apart from the standard content types,
  taxonomies, comments and users.


DNS (named) zone file loads correctly but does not resolve

Question: I have a very strange problem that I not able to figure out.
On my server I host two applications with two different domains:
1. onlinelogistics.eu
2. resursecrestine.org
I also host a DNS server (fedora server) that I configured to resolve these two domains.
The problem is that only the first domain resolve and the other does not.
The zone file for 'onlinelogistics.eu' is:
onlinelogistics.eu.     IN      SOA     ns1.onlinelogistics.eu. root.onlinelogistics.eu. (

                        1194130303

                        10800

                        3600

                        604800

                        38400 )

@       IN      NS      onlinelogistics.eu.

onlinelogistics.eu.     IN      NS      ns1.onlinelogistics.eu.

onlinelogistics.eu.     IN      NS      ns2.onlinelogistics.eu.

ns1.onlinelogistics.eu. IN      A       184.108.40.206

ns2.onlinelogistics.eu. IN      A       22.214.171.124

onlinelogistics.eu.     IN      A       184.108.40.206

www.onlinelogistics.eu. IN      A       184.108.40.206

ftp.onlinelogistics.eu. IN      A       184.108.40.206

m.onlinelogistics.eu.   IN      A       220.127.116.11

*.onlinelogistics.eu.   IN      A       18.104.22.168

                        IN      A       126.96.36.199

onlinelogistics.eu.     IN      MX      10 ASPMX.L.GOOGLE.COM.

onlinelogistics.eu.     IN      MX      20 ALT1.ASPMX.L.GOOGLE.COM.

onlinelogistics.eu.     IN      MX      20 ALT2.ASPMX.L.GOOGLE.COM.

onlinelogistics.eu.     IN      MX      30 ASPMX2.GOOGLEMAIL.COM.

onlinelogistics.eu.     IN      MX      30 ASPMX3.GOOGLEMAIL.COM.

onlinelogistics.eu.     IN      MX      30 ASPMX4.GOOGLEMAIL.COM.

onlinelogistics.eu.     IN      MX      30 ASPMX5.GOOGLEMAIL.COM.

onlinelogistics.eu.     IN      TXT     "v=spf1 a mx a:onlinelogistics.eu ip4:220.127.116.11 ?all"onlinelogistics:~

Now, for the other domain I did a copy/paste and replaced onlinelogistics.eu with "resursecrestine.org" but still the domain is not found.
The comand "whois resursecrestine.org" finds the nameservers (ns1.resursecrestine.org) so I am sure the problem is with the DNS server not being able to find the address.
Any ideas are highly appreciated!
Thank you!
Comment: You might want to replace your original IP addresses and names with placeholders...
Comment: Very bad advice for PEra: quite the contrary, use REAL names if you want people to help.
Comment: You did not mention the name server software you use. BIND ?
Answer: Have you created the zone in your named.conf file? i.e.:
zone "resursecrestine.org" {
        type master;
        file "resursecrestine.org";
};

According to a dig +trace, it does resolve...and checking via browser, it loads. So is this resolved?
; <<>> DiG 9.2.4 <<>> +trace resursecrestine.org
;; global options:  printcmd
.                       306040  IN      NS      A.ROOT-SERVERS.NET.
.                       306040  IN      NS      B.ROOT-SERVERS.NET.
.                       306040  IN      NS      C.ROOT-SERVERS.NET.
.                       306040  IN      NS      D.ROOT-SERVERS.NET.
.                       306040  IN      NS      E.ROOT-SERVERS.NET.
.                       306040  IN      NS      F.ROOT-SERVERS.NET.
.                       306040  IN      NS      G.ROOT-SERVERS.NET.
.                       306040  IN      NS      H.ROOT-SERVERS.NET.
.                       306040  IN      NS      I.ROOT-SERVERS.NET.
.                       306040  IN      NS      J.ROOT-SERVERS.NET.
.                       306040  IN      NS      K.ROOT-SERVERS.NET.
.                       306040  IN      NS      L.ROOT-SERVERS.NET.
.                       306040  IN      NS      M.ROOT-SERVERS.NET.
;; Received 316 bytes from 172.18.251.240#53(172.18.251.240) in 1 ms

org.                    172800  IN      NS      B0.ORG.AFILIAS-NST.org.
org.                    172800  IN      NS      B2.ORG.AFILIAS-NST.org.
org.                    172800  IN      NS      A0.ORG.AFILIAS-NST.INFO.
org.                    172800  IN      NS      D0.ORG.AFILIAS-NST.org.
org.                    172800  IN      NS      C0.ORG.AFILIAS-NST.INFO.
org.                    172800  IN      NS      A2.ORG.AFILIAS-NST.INFO.
;; Received 439 bytes from 184.108.40.206#53(A.ROOT-SERVERS.NET) in 61 ms

resursecrestine.org.    86400   IN      NS      ns4.afraid.org.
resursecrestine.org.    86400   IN      NS      ns3.afraid.org.
resursecrestine.org.    86400   IN      NS      ns1.afraid.org.
resursecrestine.org.    86400   IN      NS      ns2.afraid.org.
;; Received 180 bytes from 188.8.131.52#53(B0.ORG.AFILIAS-NST.org) in 42 ms

resursecrestine.org.    3600    IN      A       18.104.22.168
resursecrestine.org.    86400   IN      NS      ns1.afraid.org.
resursecrestine.org.    86400   IN      NS      ns4.afraid.org.
resursecrestine.org.    86400   IN      NS      ns3.afraid.org.
resursecrestine.org.    86400   IN      NS      ns2.afraid.org.
;; Received 196 bytes from 22.214.171.124#53(ns4.afraid.org) in 29 ms

Answer: No, unlike what you say, resursecrestine.org works, it is onlinelogistics.eu which fails:
% check_soa onlinelogistics.eu
There was no response from ns2.onlinelogistics.eu
There was no response from ns1.onlinelogistics.eu
% check_soa resursecrestine.org
ns4.afraid.org has serial number 1001120004
ns1.afraid.org has serial number 1001120004
ns2.afraid.org has serial number 1001120004
ns3.afraid.org has serial number 1001120004

First thing to do, with every daemon running on Unix: check the log file! BIND, for instance, gives comprehensive information about the zones it loaded or failed to load. This would address greeblesnort's suggestion.
Also, "does not resolve" is not sufficiently precise. Test with dig @your-name-server and report the actual result.
Finally, your zone files would be simpler to read and easier to manage with relative names.
Answer: Have you got the ip address for the nameservers correct?  checkdns.net reports the nameservers (18.104.22.168) aren't responding.  If this ip address is correct, then likely Bind failed to start because you have errors in your zonefile or named.conf.local.  Check both of these using named-checkconf and named-checkzone.
Comment: And, above all, read BIND log file!


Kubernetes + CRI-O + Fluent-Bit

Question: We like to use the EFK stack for centralised logging of containers running in Kubernetes with CRI-O.
The recommended DaemonSet looks like this:
kind: DaemonSet
metadata:
  namespace: logging
  name: fluent-bit
  labels:
    component: fluent-bit-logging
    version: v1
    kubernetes.io/cluster-service: "true"
spec:
  selector:
    matchLabels:
      component: fluent-bit-logging
  template:
    metadata:
      labels:
        component: fluent-bit-logging
        version: v1
        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: fluent-bit
        image: fluent/fluent-bit:0.12.17
        volumeMounts:
        - name: varlog
          mountPath: /var/log
        - name: varlibdockercontainers
          mountPath: /var/lib/docker/containers
          readOnly: true
        - name: fluent-bit-config
          mountPath: /fluent-bit/etc/
      terminationGracePeriodSeconds: 10
      volumes:
      - name: varlog
        hostPath:
          path: /var/log
      - name: varlibdockercontainers
        hostPath:
          path: /var/lib/docker/containers
      - name: fluent-bit-config
        configMap:
          name: fluent-bit-config
      serviceAccountName: fluent-bit
      tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule

The config-map:
apiVersion: v1
kind: ConfigMap
metadata:
  name: fluent-bit-config
  namespace: logging
  labels:
    k8s-app: fluent-bit
data:
  # Configuration files: server, input, filters and output
  # ======================================================
  fluent-bit.conf: |
    [SERVICE]
        Flush         1
        Log_Level     info
        Daemon        off
        Parsers_File  parsers.conf
        HTTP_Server   On
        HTTP_Listen   0.0.0.0
        HTTP_Port     2020

    @INCLUDE input-kubernetes.conf
    @INCLUDE filter-kubernetes.conf
    @INCLUDE output-elasticsearch.conf

  input-kubernetes.conf: |
    [INPUT]
        Name              tail
        Tag               kube.*
        Path              /var/log/containers/*.log
        Parser            docker
        DB                /var/log/flb_kube.db
        Mem_Buf_Limit     5MB
        Skip_Long_Lines   On
        Refresh_Interval  10

  filter-kubernetes.conf: |
    [FILTER]
        Name                kubernetes
        Match               kube.*
        Kube_URL            https://kubernetes.default.svc:443
        Kube_CA_File        /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        Kube_Token_File     /var/run/secrets/kubernetes.io/serviceaccount/token
        Kube_Tag_Prefix     kube.var.log.containers.
        Merge_Log           On
        Merge_Log_Key       log_processed
        K8S-Logging.Parser  On
        K8S-Logging.Exclude Off

  output-elasticsearch.conf: |
    [OUTPUT]
        Name            es
        Match           *
        Host            http://elasticsearch-master
        Port            9200
        Logstash_Format On
        Replace_Dots    On
        Retry_Limit     False

  parsers.conf: |
    [PARSER]
        Name   apache
        Format regex
        Regex  ^(?<host>[^ ]*) [^ ]* (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^\"]*?)(?: +\S*)?)?" (?[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)")?$
        Time_Key time
        Time_Format %d/%b/%Y:%H:%M:%S %z

    [PARSER]
        Name   apache2
        Format regex
        Regex  ^(?<host>[^ ]*) [^ ]* (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^ ]*) +\S*)?" (?[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)")?$
        Time_Key time
        Time_Format %d/%b/%Y:%H:%M:%S %z

    [PARSER]
        Name   apache_error
        Format regex
        Regex  ^\[[^ ]* (?<time>[^\]]*)\] \[(?<level>[^\]]*)\](?: \[pid (?<pid>[^\]]*)\])?( \[client (?<client>[^\]]*)\])? (?<message>.*)$

    [PARSER]
        Name   nginx
        Format regex
        Regex ^(?<remote>[^ ]*) (?<host>[^ ]*) (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^\"]*?)(?: +\S*)?)?" (?[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)")?$
        Time_Key time
        Time_Format %d/%b/%Y:%H:%M:%S %z

    [PARSER]
        Name   json
        Format json
        Time_Key time
        Time_Format %d/%b/%Y:%H:%M:%S %z

    [PARSER]
        Name        docker
        Format      json
        Time_Key    time
        Time_Format %Y-%m-%dT%H:%M:%S.%L
        Time_Keep   On

    [PARSER]
        Name        syslog
        Format      regex
        Regex       ^\<(?<pri>[0-9]+)\>(?<time>[^ ]* {1,2}[^ ]* [^ ]*) (?<host>[^ ]*) (?<ident>[a-zA-Z0-9_\/\.\-]*)(?:\[(?<pid>[0-9]+)\])?(?:[^\:]*\:)? *(?<message>.*)$
        Time_Key    time
        Time_Format %b %d %H:%M:%S

What should we adjust to get fluent bit to parse the correct logs? (Currently it doesn't parse anything). /var/lib/docker/containers exists but is empty..
Answer: Nevermind, there was an error within the config-map (see post above) - the host must not contain the protocol (http) - just the hostname.
All working as expected now.

Kubernetes + CRI-O + Fluent-Bit


matlab to python coding

Question: I have this code in MATLAB and I am trying to convert it in Python.
 yc(1:45)=-2;
 yc(46:90)=2;
 yc(91:136)=-2;
 yc(137:182)=2;

I don't know how to convert it in python thnx for helping me
Comment: What is `yc` and what argument does it take?
Answer: Direct Equivalent
The direct equivalent, using numpy would be:
>>> import numpy as np
>>> yc = np.empty(182)
>>> yc[:45] = -2       # Equivalent to, yc[0:45] = -2
>>> yc[45:90] = 2
>>> yc[90:136] = -2
>>> yc[136:] = 2       # Equivalent to, yc[136:182] = 2

Where np.empty creates an array with random values, of given shape. Then we proceed to assign different values by accessing in slices.
Alternate Way
You can also try with np.arange and np.select:
>>> yc = np.arange(182)
>>> yc = np.select(condlist=[
                       yc < 45, (45 <= yc) & (yc < 90),
                       (90 <= yc) & (yc < 136), yc >= 136
                   ],
                   choicelist=[-2, 2, -2, 2])

>>> yc

array([-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
       -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
       -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,  2,  2,  2,  2,  2,  2,
        2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
        2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
        2,  2,  2,  2,  2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
       -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
       -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
        2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
        2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
        2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2])

Here np.arange creates an array with values ranging from 0 to 181 (182 values in total), and we create a new array substituting different values in the array according to different conditions.
Things to keep in mind:

MATLAB starts indexing from 1, whereas python starts from 0.
You need to pre-allocated an array in order to assign via slices.

Helpful Links:

Numpy indexing
Numpy for MATLAB users

matlab to python coding


ASP .Net Gridview bind to data only when clicking update

Question: Here's how I want the control to work. Click edit on a row in gridview. There's a textbox in one of the columns, I would like it to be blank even though there's data in the database for that column, but when I click update I would like whatever new text the user entered to update the database for that column. It would be one-way databinding, but the other way?
Answer: Here's how I did it using an sql datasource with the select,update and delete methods generated.
First, you'll need to make any column that you want to edit like this a template field with an item template and and edit item template:
<code><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        DataKeyNames="ID" DataSourceID="SqlDataSource1"
        onrowupdating="GridView1_RowUpdating">
    <Columns>
    <asp:TemplateField HeaderText="City" SortExpression="City">
        <ItemTemplate>
           <asp:Label runat="server" Text='<%# Eval("City") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
           <asp:TextBox runat="server"  ID="txtCityEdit" Text=""></asp:TextBox>
        </EditItemTemplate>
     </asp:TemplateField>
     </Columns>
</asp:GridView>
</code>
Next handle the gridview's on update event:
<code>    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //find the value control who's value you want
        TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCityEdit");

        //since we are not using a bound column for city we need to explicitly insert the value
        //into the update parameter.
        SqlDataSource1.UpdateParameters["City"].DefaultValue = tb.Text;
    }
</code>
Even if you are using something other than an SQL Datasource this should be the basic solution.
Comment: That didn't work exactly for me, but definitely got me on the right track! My biggest problem was getting the value of the textbox out of the template field since intellisense wouldn't give it to me.

I tried using the UpdateParameters like your example, but got a null reference error, then I tried adding my new one to the collection and that didn't work either.

I ended up added my new value to the "NewValues" collection and it worked.
Answer: <code>// Find notes textbox
TextBox tb = (TextBox)MyActiveReferrals.Rows[e.RowIndex].FindControl("NotesTextBox");
e.NewValues.Add("Notes", tb.Text);
</code>
I used a linq data source.


Use RELATED and FILTER to cross reference two tables in DAX?

Question: I have two tables in power pivot, a order header and a order detail.  I would like to identify on the header, with a true/false flag, if a particular class of item is on the order detail.
Order Header Table
Order ID    Order Amt   *Has HBG*
100041328   10.24        1
100041329   34.57        0
100041330   25.89        1

Order Detail Table
Order ID    SKU       Dept
100041328   1749988   HBG
100041328   9102272   SAC
100041329   1325344   SOA
100041329   4255337   LAF
100041329   7541744   SOC
100041330   7862194   HBG
100041330   3829646   HAS
100041330   3399937   EAR

I'm using the order ID to establish a relationship between the two tables.  I should think that some sort of combination of FILTER and RELATED would allow me to flagorder 100041328 and 100041330 as having products in the HBG department but I keep getting errors.  Any thoughts on how these could be flagged?
Answer: You can count the number of rows on the detail table using COUNTROWS inside a CALCULATE statement which changes the row context to filter context. Add an additional filter for Dept and return 1 or 0 depending on how many entries have been found. You can display the 1 or 0 as True/False.
=
IF (
    CALCULATE (
        COUNTROWS ( DetailsTable ),
        DetailsTable[Dept] = "HBG"
    )
        > 0,
    1,
    0
)

Comment: Yep, that's exactly it!  Thanks.


How to manipulate DOM using Node js?

Question: I am new to javascript and Node.js but I am trying to figure out if there is an alternative to document.getElementById() in Node that has the same function. If it cannot be done in Node, is it possible to create a pure js file to manipulate the DOM and a separate Node file. For extra information, what I am trying to do is to convert csv lines into a json object and then update the webpage with new information which is why I want to use document.getElementById().
Comment: The DOM exists in your browser. Node runs on any computer where node is installed, but WITHOUT a browser. The DOM is created from html, so you could create html with node that eventually becomes the DOM. Or you could open and control a browser with node (puppeteer perhaps?) with which you could modify the DOM. Or you could have a frontend html that communicates with a backend-server that is run by node, and do the changes with the frontend but provide data for the changes with node. I think that is a pretty exhaustive list of how to manipulate the DOM with node. (All indirectly.)
Answer: document.getElementById() is a function that exists in a browser.  There is no such function in nodejs.
It is possible to get a 3rd party module that will parse an HTML web page, create a DOM and then allow you to access the DOM programmatically to see what's in the web page.   Cheerio and Puppeteer are two such 3rd party modules, each with differing levels of features.  Puppeteer actually uses the Chromium browser engine and can even run Javascript in the page and generate screenshots.  Cheerio parses the HTML and lets you access just what it creates (without Javascript running).
It sounds like maybe you're a bit confused about how web pages work.  A browser running on the end user's computer loads a web page.  Once the page is loaded, at that point the server's job is done. The web page exists only in the browser on the user's computer.  The server can't directly, on its own, change that web page.
To change that web page (without reloading it), you would have to have supporting Javascript code in the web page (that runs in the user's browser).  For example, you could have your Javascript make an Ajax call from the web page that would request certain data from the server.  When the server gets that request, it could generate the data and return JSON back to the browser.  The Javascript in the browser would then receive that JSON, parse it into a Javascript object and then use the DOM to insert new objects into the existing web page based on the data it received.
Note that all changes to the existing web page in the browser are made by  the Javascript running in the web page in the user's browser, not directly by the server.  The server can supply data, but cannot directly change the user's web page itself.  Of course, the user could request an update page and the browser would request a new version of the whole page and the server could then supply a page that had different data in it, but that would involve reloading the whole page.
There are also template engines that exist for nodejs so that when your server is generating a web page, the template engine can help you create a set of HTML for that web page that incorporates dynamic data.  This doesn't dynamically  change a web page that is already sitting in a browser being displayed.  Instead, it helps you generate a web page from scratch that incorporates dynamic data into the web page when it is first downloaded.  Examples of templates engines that work with Express in nodejs are Pug, EJS, Nunjucks, handlebars and many others.

How to manipulate DOM using Node js?


Let $G = \langle x, y \mid x^{7} = y^{3} = e,\; yxy^{−1} = x\rangle$. What is $|G|\,$?

Question:
Let $G = \langle x, y \mid x^{7} = y^{3} = e,\; yxy^{−1} = x\rangle$. What is $|G|\,$?

What I've done so far:
$$yxy^{-1} = x \implies yx = xy.$$
The group $G$ is an abelian group. I can only think that $|G| = 21$, because I don't know how else to proceed.
Answer: Claim: $G\cong C_7\times C_3$. Start with the map from the free group on two generators $F_2$ to $C_7\times C_3$ given by $x\mapsto(1,0)$ and $y\mapsto (0,1)$. Verify that $x^7$, $y^3$, and $yxy^{-1}x^{-1}$ are in the kernel of this map, so we have an induced quotient $f\colon G\to C_7\times C_3$. By Von Dyck's theorem (or directly) we know $f$ is surjective. Now argue that $|G|$ is at most $21$: every element can be written $x^my^n$ with $0\le m\le 6$ and $0\le n\le 2$.
Comment: $C_7\times C_3\cong C_{21}$
Comment: $G$ has order at most $21$ since every element is of the form $x^ny^m$. On the other hand $f$ being surjective implies $G$ has at least $21$ elements. This implies $|G|=21$ and $f$ is an isomorphism.


Eclipse : switch workspace from svn to git (code already migrated)

Question: I have a workspace that points to an SVN repository(Eclipse Mars).
The code under this repository has been migrated to git.
How can I point to this new git repository without breaking my current workspace?
Answer: What I would do is:

Close eclipse.
Save the whole directory on a zip, just in case.
Save all your local change from the revisión you are working on. What I would call stash your changes in git terms
inside the directory of the project, run : git init .
Set a remote to the svn clone you made on git
run git fetch --all
Find on git the exact same revision you are working on svn
Run git checkout --force the-revision-id

At this point, you could delete .svn because you are already switched to git. When starting eclipse, it should just show stuff as if you are working on git, no svn.


Is there a term for the relationship between these two functions?

Question: Suppose we have a function $f(x)= \frac{x-2}{x^2-4}$ and another function $g(x)=\frac{1}{x+2}$. These functions are identical at all points except for $x=2$. Is there a term to describe the relationship between $f(x)$ and $g(x)$?
Comment: You can say $g$ is an extension of $f$.
Comment: Well $\Gamma_f \subset \Gamma_g$, that's something.
Comment: In particular I would call it an extension by continuity
Comment: @AndrewTawfeek Thanks. Also what does gamma mean in that?
Comment: It is established to say that $f$ has a removable singularity at $2$.  $g$ is the function with that singularity removed, but I don't know a term for the relationship.
Answer: Yes: defining a function that fills in the holes in $f$ is known as removing its discontinuity. You could say that $g(x)$ is $f(x)$ with its discontinuity removed.
Say that $\overline{f}$ is the function $f$ with its discontinuities filled. Then
$$\overline{f}(x)=\lim_{u\to x} f(u)$$


entity export not serializing node

Question: I am trying to use entity export to move existing entitys from a live to dev site. I tried the code below and it returned NULL int(1)
However, when I did a dump of the $node object, it did dump the object correctly, so I know that the entity exists
$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'events')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC');
$result = $query->execute();

$nids = array_keys($result['node']);
//var_dump($nids, 1);
$node = node_load($nids[0]);
var_dump($node,1);

//dpm(entity_get_info());
$entity  = entity_export('node', $node);
var_dump($entity,1);
Answer: The entity_export function comes with the following caveat:

Note: Currently, this only works for entity types provided with the entity CRUD API.

This means that if your entity type does not come with this, a call to entity_export() will return NULL.
This seems to be the case with node.
I am not sure, but I think the core team never got around to adding CRUD API to core entities.
If you inspect a node entity with dpm(), there is nothing. If you do:
 debug($node->delete, 'node->delete');

it prints NULL.
Comment: I assumed that node would, as it comes with drupal core. Is this not the case? If not, is there a different way of exporting it?

entity export not serializing node


Confusion about definition of topology

Question: So, as of recently, I've become interested in topology and, in trying to find a reasonable generalization of a topology, have stumbled across lattices. I've found that the join and meet operations of subsets $A \subset X$ can be neatly expressed as the supremum and infimum operations of elements of the lattice $V=\mathcal{P}(X)$, respectively.
Applying this to a topology $\mathcal{T}$on a space $X$, we can see that meet and join are well-defined on $\mathcal{T}$, and hence $\mathcal{T}$ itself becomes a lattice.
So far so understandable, but I got terribly confused when I read about complete lattices. Let $(V, \wedge, \vee)$ be a lattice. $V$ is said to be complete if and only if $\forall U \subset V \, \exists \, sup(U), \, inf(U) \in V$. In particular, it is enough to require the existence of one of these two, because $sup(U) = inf \lbrace x \in V: (\forall y \in U: x \leq y)\rbrace$.
My thought was this: Since topologies generalize so nicely to lattices, and every set of open subsets of $X$ has a supremum by the definition of topology, what should stop me from defining the infimum for any (not just a finite) set of open subsets of $X$ using the method above?
$\bigcap_{j \in J} W_j = \bigcup\lbrace U \subset X \text{ open}, \forall j \in J: U \subset V_j \rbrace$
The worst that can happen is that there is no element in that set, hence the union is empty. But even in that case, by the definition of topology, the empty set is open in $X$, which makes me wonder why infinite intersections of open subsets are generally not defined to be open. Are they just not relevant? In "most of the cases", the intersection is going to be empty anyway. Or have I maybe misunderstood something about the definition of lattices? I'd be grateful if somebody took the time to explain this to me.
Comment: That would be the interior of the intersection, topologically. That's definitely open.
Comment: Not an answer to this question, but might also be of your interest: [When a lattice is a lattice of open sets of some topological space?](https://math.stackexchange.com/questions/2606153/when-a-lattice-is-a-lattice-of-open-sets-of-some-topological-space)
Answer:
which makes me wonder why infinite intersections of open subsets are generally not defined to be open

It seems that your misunderstanding lies here: the infima of infinite collections of open subsets, in the lattice of open subsets of a topological space, are typically not the intersection: they are the interior of the intersection. For example, taking the Euclidean topology on $\mathbb R$, the intersection of the collection $\{(-\tfrac1n-1,1+ \tfrac1n)\}_{n \in \mathbb N_+}$ is $[-1, 1]$, but its infimum in the lattice of open subsets is $(-1, 1)$.
Generally, the relation between the finite meet ($\land$) and join ($\lor$) and their infinite counterparts is often not obvious.
It's very important that not all intersections of collections of open sets are also open, since this would lead to trivial structures on the majority of interesting topological spaces. (Exercise: every $T_1$ space for which this is true has the discrete topology.)
Comment: You can't define the general infimum as the intersection, because the infinite intersection is typically not open, and thus that operation lands you outside the lattice we are talking about (which is the lattice of opens). You could redefine the notion of topology to demand that all intersections of open subsets are open, but then you're just no longer talking about topology and you get much less interesting objects (in fact, you've more or less defined equivalence relations in a roundabout way).
Comment: So you are saying that the lattice of open subsets is complete if it is endowed with join as a supremum and the interior of the intersection as the infimum, whereas with the plain intersection as the infimum it would be not complete? **What exactly breaks** if I define the infimum to be the mere intersection? I'm sorry if this is too vague, I can't put it more precisely at the moment, as I seem to be having a mental blockade.
Answer: Well, yes, the open sets form a complete lattice, with meet operation as you suggested, or equivalenty,
$$\bigwedge_{i\in I} A_i=\mathrm{int}(\bigcap_{i\in I} A_i)\,. $$
This is just the intersection operation whenever $I$ is finite. But if $I$ is infinite, this might result in a smaller set than ordinary intersection.
In our prototype of Euclidean space $\Bbb R^n$, the intersection of concentric open balls with arbitrarily small radius will be just a one point set, and we don't want to regard that 'open'.

Confusion about definition of topology


How to find cube root of single digit numbers?

Question: I know methods of solving cube root of big numbers but they dont work with single digits. Suppose I need to find the cube root of 4 , How would I do that?
Comment: What is your method for big numbers?
Comment: I know a numeric method of finding a cubic root using square root
Answer: Suppose you have a super fast method for big number but for some unknown reason, it doesn't work on single digit.
Note that $$4000 = 4 \times 1000$$
$$4000^\frac13=4^\frac13\times 10$$
$$4^\frac13 = \frac{4000^\frac13}{10}$$
You can also consider binary search.
Answer: You can use logarithms if you want,
For eg :$Z = 4^{\frac13}$
$\ln Z= \frac13\ln4$
$\ln Z = \frac13(1.38629436112)$
$\ln Z = 0.46209812037$
$Z = e^{0.46209812037}$
$Z = 1.587401$
This works for any number ,big and small.Also  I used a calculator to find $\ln$ values if you want to do it by hand , you can use a log book and use base 10 instead .
Answer: You can't really, at least not efficiently. If all you're allowed to do is division then your only option is trial and error: guess a cube root and divide your original number by that twice. If the result is too small then try a larger guess; if it's too large then try a smaller guess. Once you have upper and lower bounds for your guess you can then bisect the range each time (a.k.a. binary search) to narrow it down to the answer. But you'll be doing a lot of division.
For example let's consider the cube root of 5, and make an initial guess of 1.5. (1^3 = 1, 2^3 = 8, so seems reasonable?) Let's work to three decimal places. We can then divide 5 by 1.5 twice:
5 / 1.5 = 3.333, 3.333 / 1.5 = 2.222
If it were the cube root we'd get 1.5 again, but it's too big. So we need to divide by something larger:
5 / 1.6 = 3.125, 3.125 / 1.5 = 1.953 - result too big, try larger
5 / 1.7 = 2.941, 2.941 / 1.7 = 1.730 - result too big, larger still
5 / 1.8 = 2.778, 2.778 / 1.8 = 1.543 - result too small
We now have an upper bound, so the cube root is between 1.7 and 1.8. We then bisect this range:
5 / 1.75 = 2.857, 2.857 / 1.75 = 1.633 => try smaller: range is 1.7 to 1.75 => 1.725
5 / 1.725 = 2.899, 2.899 / 1.725 = 1.680 => smaller
5 / 1.713 = 2.919, 2.919 / 1.713 = 1.704 => smaller
5 / 1.707 = 2.929, 2.929 / 1.707 = 1.715 => larger
5 / 1.71 = 2.924, 2.924 / 1.71 = 1.710 => matches to 3 d.p.
So the cube root of 5 is 1.710 to three decimal places, using only long division. But that took us 18 divisions. (I'm glad I didn't have to do that by hand!)
If you really did need to do this by hand I'd suggest Newton-Raphson: it should converge a lot faster.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).


Show messagebox after data insertion

Question: I am new to vb.net (VS 2008) & need a help. I am feeding data from windows form to mysql dbase..
upon successful data insertion it sud show "data added" in msgbox
how to do it ?>
Please help.
This is my button code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Manage("insert into pExpenses(expdate,exptype,expamount) values('" & txtExpDate.Text & "','" & txtExpType.Text & "'," & txtExpAmount.Text & ")")
    End Sub

On clicking, data is fed to the database but i need a confirmation in the form of messagebox. Please help.
Comment: google is your friend http://goo.gl/6FSab
Comment: You are opening yourself up to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) problems if you do not use prepared statements.
Answer: As you stated, you are using MySQL database as back-end for you VB.net application. If you are calling manage() function to insert data, Look for ".ExecuteNonQuery()" function calling to insert the data. This ExecuteNonQuery() function always return the number of rows affected during the command execution. Assign that return value to an Integer variable, Check if it is greater than 0, then show the message.
Dim insRet as integer = <MySqlCommandobject>.ExecuteNonQuery()
If insRet>0 then
messagebox.show(insret & " Record(s) Successfully Inserted")
else
messagebox.show("Records not inserted")
End If

Show messagebox after data insertion


Tossing a coin infinite times

Question: Suppose we have a fair coin. We are going to define an experiment.
A single coin is tossed infinite times.
Now, imagine it this way - if a coin is tossed $n$ times, the probability of getting $\frac{n}{2}$ heads decreases as $n$ increases. However, what happens when $n$ tends to $\infty$ ? Many sources tell me, if a coin is tossed infinite times, I would get equal heads and tails. However, when it is tossed a finite number of times, I see that the probability of getting a equal number of heads and tales decreases, as the number of tosses increase. How does it suddenly increase and become $50$ percent, when the number of tosses become infinite ?
For two tosses, probability of getting equal number of heads and tails is $0.5$. For 4 tosses, this becomes $0.375$. For a hundred tosses, it becomes $0.08$. We can clearly see, even though equal head and tail is the most probable, it is less likely to occur.
However, when we take infinite tosses, we are expected to get equal heads and tails, so the probability jumps up to $0.5$ again ?
How is this possible ? Is there something wrong with my reasoning ?
Comment: You appear to distinguish between "most probable" and "most likely", though I don't know what distinction you see.  Keep in mind that there is a difference between the limiting behavior of the average and the results of any particular trial.  If you throw a fair die lots of times, the average score is $3.5$ which is not a possible score on any single trial.
Comment: @lulu i'm distinguishing between most probable and most likely in the following way : Suppose, we toss a coin $n$ number of times you are expected to get an equal number of heads or tales, as the probability of getting this is the maximum, it lies in the center of the distribution. However, we also know, that the collective probability of not getting equal heads and tales is a lot more than getting that particular outcome. So, it is more likely that we would not get that, and get something else. Hence, most probable and most likely in this case is not the same.
Comment: It sounds like you are referring to the [mode](https://en.wikipedia.org/wiki/Mode_(statistics)) by "most probable," but it's not exactly clear what you mean by "most likely."
Comment: That's a very eccentric distinction.  I think you should refer to it differently.  To be clear:  in any continuous distribution, no single instance has positive probability.  For large numbers of tosses, your coin distribution is very nearly continuous (i.e. it is very well approximated by continuous distributions).
Comment: But, really, I think that you are confused by the distinction between the limiting behavior of the average and the results of any trial. If you just consider simple Bernoulli trials  (which yield $0$ or $1$ with equal probability) the limiting average is $\frac 12$, which is an impossible outcome on any single trial.
Comment: @lulu I've edited my question. The first part was quite misleading I agree. This second part is where my confusion truly lies. If we do $n$ tosses, the probability of getting equal number of heads and tales decreases, as $n$ increases. However for infinite tosses, we expect to get same number of heads and tales.
Comment: Yes, that's correct.  But so what?  As I said, the average behavior in the limit may be quite different from the result of any particular case.
Comment: Maybe you'd prefer some statement of this form:  For any fixed $\epsilon>0$ we have $P(X\in [.5-\epsilon,.5+\epsilon])\to 1$ as $n\to \infty$, where $X$ is the proportion of Heads tossed.
Comment: @lulu is there any proof for that ? I know it has something to do with the law of large numbers, but I can't seem to prove it.
Comment: This follows from the [central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem)
Answer: Having an equal number of heads and tails is not an event that we expect. Actually there is another branch of mathematics known as design interference. If you would get more frequently exactly the same number of heads and tails, that would violate the basic assumptions i.e. the axioms of probability that the things are happening independently.
When we say we expect that the number of heads and tails is equal, we actually have in mind a normal distribution where after as you call it an infinite number of attempts you would create a bell like shape that is centralized around equal number of heads and tails and with a very precise shape of the percentage of other possible outcomes. So precise, actually, that any deviation inevitably means a rigged coin or loaded die or whatever other crooked mechanism has been employed or was simply present.
Without any doubt.
Notice that when you talk about an infinite number of attempts, you cannot talk about an equal number of heads of tails and compare it with other outcomes. Can you say that the outcome was one head less towards infinity? Yet, that is an event as well that you could track. What would you find? That the number of such precise outcomes has a probability equal to $0$.
For this reason, when we talk about infinity we use other means for example a histogram that would say a percentage of events or something similar that will not vanish as we go towards the infinity. For example, the percentage of outcomes where the total number of tails is within $20$% of the number of heads. Then and only then you can talk about the most probable set of events, but not one single event.
Because design interference is similar to probability and share many of its principles, yet it still reveals a gap in our understanding of probability, you have to be really careful when you assume that things are happening totally by chance. Otherwise you could easily confuse things and forget to check if your test is really random or it was influenced by something, like a rigged die.
This is the reason why you are going to be kicked out of a casino as soon as the pattern of wins even resembles something that is not pure luck even when it is pure luck. $2^{36}$ is a lot of money even if expressed in cents, and trust me I myself can trick any roulette to get at least $0.1$% of that if there would be no guards to kick me out forever as soon as they would notice the tricks I would use(, and 700.000 dollars is still a lot of money for one night).

Tossing a coin infinite times


Making the react native app stripe to live mode

Question: I am working on react native app and the app is using the test mode stripe and I am also making the test stripe to live,
I have a simple question, Is there anything I have to change while making the stripe to live mode,

I changed the switch to live in the stripe dashboard.
I changed the key and secret in app and server.

Do I also have to change something else?
And what are these and why and how are they used and where can I find these in the dashboard.
merchantIdentifier: 'merchant.com.stripe.react.native',
urlScheme: 'stripe-example',

Answer: The testmode toggle in the Stripe dashboard has no impact on what mode your integration is operating in, it only changes what data you're viewing in the dashboard. When the toggle is on, the Stripe dashboard will display the testmode data for your account, and when it is off you will see livemode data.
The secret and publishable key that you provide dictate what mode your integration will operate in, and are likely the only values that you need to change.  source
The merchantIdentifier is not a value that you find, but rather is one that you set when you're registering for an Apple Merchant ID. It is an optional parameter that you can omit if you're not planning to accept Apple Pay payments. source
urlScheme is an optional parameter that is only needed if you're planning to manually handle the 3DS authentication flow rather than rely on the pre-built functionality that Stripe provides. source
Comment: Thank you i have also found some info about the merchant identifier (used for apple pay),
https://stripe.com/docs/apple-pay?platform=react-native, I will ask you some question if I need them.
Comment: I just want to confirm that, do I also need to change something else to make the stripe live, I changed the keys.
Comment: Changing the keys is the primary driver, are you not seeing your requests being made against livemode after changing the keys, or do you see something else to suggest that changing the keys wasn't enough to toggle the mode of operation for your integration?


How do I have menu linked content not on main page?

Question: My web site is the first drupal site I have made.  And after I made it, I left it to do other work -- like write the blogs for the site.  I cannot remember how I set up the content pages that link to menu selection that do not appear as content on the main page.
The best way to explain what I am talking about is with a screen capture.  I have added menu items to my main menu.  I do not remember how I did it in the past.  I want to add content and have it linked to the main menu (this option is available to me when I create the content) but I do not want them to appear as stories on the main page.
The circled areas in this screen shot shows the menu item I just added and the corresponding item on the main page that I do not want to be there.  How do I remove it from the main page?
I am thinking that perhaps I should not have added it as a "content" but something else? If so, what and how?
http://www.arguemax.com/images/problems/12-6-2015/Capture_001.PNG
Answer: When you create the Content, be sure to uncheck "Promoted to front page" in the option menu shown at the bottom, under Published options. See image.

If you want this option by default for a specific content type (for example, for Articles) you will need to go to Structure > Content types and edit that content type's Publishing options to uncheck Promoted to front page. This will become the default option when you create a new Article.
Answer: To fix this issue edit the content and just you need to unchecked the promoted to font page options under publishing options tab at the end of edit page.
Comment: To fixed it for all content of any content types do as @argiepiano mentioned. It's better to unchecked this option whenever you create new content types.


Evaluating matrix integral

Question: Context: This integral is part of the calculation of the step response to a linear system using the convolution equation, found in this book (pg. 150).
The part that is bugging me is the following integral:
$$
\int_{0}^{t} e^{A(t-\tau)} d \tau,
$$
where $A$ is a matrix and $e^{A(t-\tau)}$ is the matrix exponential.
My approach was:
$$
\int_{0}^{t} e^{A(t-\tau)} d\tau = \int_{0}^{t} e^{At}e^{-A\tau} d\tau = e^{At}\int_{0}^{t} e^{-A\tau} d\tau = -e^{At}A^{-1}(e^{-At} - I),
$$
where I used the property that $e^{A+B} = e^{A}e^{B}$ when $AB=BA$.
However, the author does the following:
$$
\int_{0}^{t} e^{A(t-\tau)} d \tau = \int_{0}^{t} e^{A\sigma} d\sigma = A^{-1}(e^{At} - I).
$$
I do not understand why my approach is wrong and why the author is allowed to do what he did.
Comment: $t$ and $\tau$ are scalars.
Answer: We assume of course that $A$ is invertible. The author uses the substitution $\tau = t - \sigma$ , the identity $A^{-1} A = I$, the linearity of the integral and the property $\frac{\mathrm{d}}{\mathrm{d} t} \mathrm{e}^{t A} = A \mathrm{e}^{t A}$ of the matrix exponential to get
\begin{align}
\int \limits_0^t \mathrm{e}^{(t-\tau) A} \, \mathrm{d} \tau &= \int \limits_0^t \mathrm{e}^{\sigma A} \, \mathrm{d} \sigma = \int \limits_0^t I \,  \mathrm{e}^{\sigma A} \, \mathrm{d} \sigma = \int \limits_0^t A^{-1} A
 \,\mathrm{e}^{\sigma A} \, \mathrm{d} \sigma \\
&=  A^{-1} \int \limits_0^t A \, \mathrm{e}^{\sigma A} \, \mathrm{d} \sigma =  A^{-1} \left[\mathrm{e}^{\sigma A} \right]_{\sigma = 0}^{\sigma=t} =  A^{-1} \left(\mathrm{e}^{t A} - I\right) \, .
\end{align}
Note that since we have $ A^{-1} \mathrm{e}^{t A} = \mathrm{e}^{t A} A^{-1}$, your answer is not wrong, but completely equivalent:
$$ - \mathrm{e}^{t A} A^{-1} \left(\mathrm{e}^{-t A} - I\right) = - A^{-1} \mathrm{e}^{t A} \left(\mathrm{e}^{-t A} - I\right)= A^{-1} \left(\mathrm{e}^{t A} - I\right) \, . $$
Comment: I failed to realize that $ A^{-1} \mathrm{e}^{t A} = \mathrm{e}^{t A} A^{-1}$, which can easily be proved using the definition of the matrix exponential. Thanks!

Evaluating matrix integral


A probability problem, with percentages.

Question: Could anyone help solving this problem?
When asking a  group of people about three books $A, B,C$ it was found that:
36% of them read book $A$ , 39% read book $B$ and 40% read book $C$. And 15% read $A$ and $B$, 9% read $C$ and $B$ and 11% read $A$ and $C$. And 5% read the three books $A$ and $B$ and $c$.
1- find the percentage of people who don't read any of the books.
2- find the percentage of people who read two books only.
3-  find the percentage of people who read one book only.
4- Assuming that the population is 500 persons, how many people read the book $A$ only?
Thanks.
Comment: Easiest way to solve these problems is to make a Venn diagram.
Comment: What did you try?
Comment: We have the following probabilities:
$P(A)=0.36$, $P(B)=0.39$ and $P(C)=0.4$
Comment: OK, that's a start.  So if $A$ is the event of reading book A, then what is the event $A'$?
Comment: and $P(A\bigvee B\bigvee C)=P(A)+P(B)+P(C)-P(A \bigwedge B)-P(A \bigwedge C)-P(C \bigwedge B)-P(A \bigwedge B \bigwedge C) =0.36+0.39+0.4-0.15-0.11-0.09-0.05=0.75$
Comment: @sososos  You should really put this in your post! It shows you are making some effort and it helps us see where you are getting stuck.
Comment: $P(A^')=1-0.36=0.64$
Comment: so percentage of people who don't read any of the books is:
$1-P(A \bigcup B \bigcup C)=1-0.75=0.25$
Comment: I am stuck in finding the probability laws which are useful in my previous problem
Comment: Check your signs, you have a sign flip there.
Answer:
Suppose A is the Red-yellow-pink cricle, and B is the Green (and neighbors) cricle, and C is Blue
the white region is $A\cap B\cap C = 5\%$
The Yellow and White together are $A\cap B = 9\%$
So the Yellow region is  $A\cap B = 9\% - 5\% = 4\%$
You have enough information to fill out all 8 regions.
If you want to take a more algebraic approach
you could say that the Grey region is $A'\cap B' \cap C'$
$(1 - A)\cap (1 - B)\cap(1 - C) = 1 - A - B - C + A\cap B +  A\cap C +  B\cap C - A\cap B \cap C = 1 -0.36-0.39-0.40+0.15+0.09+0.11-0.05$
Comment: $P(A\bigcap \acute{B}\bigcap \acute{C})=0.15$ and $P( \acute{A} \bigcap B \bigcap \acute{C})=0.2$ and $P(\acute{A}\bigcap \acute{B}\bigcap C)=0.25$
Comment: $P(A\bigcap \acute{B}\bigcap \acute{C})+P( \acute{A} \bigcap B \bigcap \acute{C})+P(\acute{A}\bigcap \acute{B}\bigcap C)=0.6$ is the percentage of people who read only one book, am I right?
Comment: $P(A\bigcap B \bigcap \acute{C})+P(A \bigcap \acute{B} \bigcap C)+P(\acute{A}\bigcap B\bigcap C)=0.1+0.06+0.04=0.2$ is the percentage of people who read two books, am I right?
Comment: That looks correct.
Comment: $P(A\bigcap \acute{B} \bigcap \acute{C})=0.15$ so we have $0.15*500=75$ persons read the book $A$ only. right? :)
Answer: Here is a start:

So you know that 5% read all three books.  The yellow highlighted area is the people who read A and B (and may or may not read book C), which you are told is 15%. So, how many people read book A and B, but not C? That would be 15%-5%=10%.  You can also use the formula:
$P(A \cap B) = P(A \cap B \cap C) + P(A \cap B \cap C')$
So given that $P(A \cap B \cap C)=0.05$ and $P(A \cap B) = 0.15$, you can derive that $P(A \cap B \cap C')=0.15-0.05=0.10$
OK, so now do that for all other areas!
Comment: $P(A\bigcap \acute{B} \bigcap C)=0.11-0.05=0.06$ and $P(\acute{A}\bigcap B  \bigcap C)=0.09-0.05=0.04$
Comment: OK, good!  So fil in those percentages into the Venn diagram, and given that $P(A)=0.40$, compute the area that is inside $A$, but outside $B$ and $C$. .. So that would be $P(A \cap B' \cap C')$.  And then do the same for $B$ and $C$
Answer: enter image description here
1-  the percentage of people who don't read any of the books. 30%
2- find the percentage of people who read two books only. 35%
3- find the percentage of people who read one book only. 30%
4- Assuming that the population is 500 persons, how many people read the book A only? 5 persons


Measure network latency through firewall?

Question: We are trying to use RDP across a very high-latency VPN.   I'd like to measure the latency at each point in the network, but I'll settle for measuring end-to-end latency if that's the only number I can get.
Unfortunately, our network team blocks ping and pretty much everything else.   The only ports that I know for sure are open are 22 (ssh) and the Remote Desktop port which I believe is 135.
Does anyone know of a tool where I can specify a port to measure latency between two hosts?  I have complete control of the machines on each end, it's only the network in the middle I have no control over.
Comment: You can employ the `tcpping`/`nmap`/`tcptraceroute` and many more.
Comment: 1. RDP is port 3389. 2. Try this for testing latency of "real" traffic - http://www.ixiacom.com/products/display?skey=qcheck
Comment: I downloaded the ixia "qcheck" product and it looks cool, but I couldn't get it to work over anything but its native port, which is blocked by the firewall I have to go through.   And Ixia won't talk to you unless you've bought one of their commercial products - even the user manual is behind a paywall!!   So, no help there.
Answer: I finally found the answer I was looking for by downloading the PSTools package from Microsoft:
http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx
The PsPing.exe tool is (I guess) the same as tcping and I was able to run a windows-based SSH server on my box behind the firewall and connect to that over port 22:
psping -4 -n 100 -h 192.168.123.123:22

This gave me a nice histogram list of just how stinky my VPN connection is:
TCP connect statistics for 192.168.123.123:22:
  Sent = 100, Received = 100, Lost = 0 (0% loss),
  Minimum = 108.31ms, Maxiumum = 463.88ms, Average = 126.08ms

Latency Count
108.31  87
127.03  9
145.74  0
164.45  1
183.17  0
201.88  0
220.60  0
239.31  0
258.02  0
276.74  0
295.45  0
314.17  1
332.88  0
351.59  0
370.31  0
389.02  0
407.74  1
426.45  0
445.16  0
463.88  1


Issue trying to insert records in temporary tables

Question: I have an issue trying to insert records in temporary tables
I have a temporary table #TmpCapacityTable
CapacityDate    InstallerCode   WorkAreadID FoxtelCodeID    value
2/8/12      BAW     7       1510        3
2/8/12      BAW     7       1508        3

Second temporary table #TmpAdjustmentTable
CapacityDate    InstallerCode   WorkAreadID fFoxtelCodeID   value
2/8/12      BAW     7       1510        1
2/8/12      BAW     7       1508        1
2/8/12      BAW     7       1509        1

I need to insert into #TmpCapacityTable those rows that are not in but there are in #TmpAdjustmentTable, in the sample only code 1509
I'm using
Insert into #TmpCapacityTable
select * from #TmpAdjustmentTable
    where #TmpAdjustmentTable.CapacityDate not in (select #TmpCapacityTable.CapacityDate from #TmpCapacityTable)
    and   #TmpAdjustmentTable.WorkAreadID not in (select #TmpCapacityTable.WorkAreadID from #TmpCapacityTable)
    and   #TmpAdjustmentTable.InstallerCode not in (select #TmpCapacityTable.InstallerCode from #TmpCapacityTable)
    and   #TmpAdjustmentTable.FoxtelCodeID not in (select #TmpCapacityTable.FoxtelCodeID from #TmpCapacityTable)

but it doesn't work, I can't see what the problem is
Can Someone help me pleaseeee!!!
Thanks in advance
Eliana
Comment: If you post code, XML or data samples, **PLEASE** highlight those lines in the text editor and click on the "code samples" button ( `{  }` ) on the editor toolbar to nicely format and syntax highlight it!
Answer: INSERT INTO TmpCapacityTable(CapacityDate, InstallerCode, WorkAreaID, FoxtelCodeID, value)
    SELECT  ta.CapacityDate, ta.InstallerCode, ta.WorkAreaID, ta.FoxtelCodeID, ta.value
      FROM  #TmpAdjustmentTable ta
            LEFT OUTER JOIN #TmpCapacityTable tc
                ON  ta.CapacityDate     = tc.CapacityDate
                AND ta.InstallerCode    = tc.InstallerCode
                AND ta.FoxtelCodeID     = tc.FoxtelCodeID
     WHERE  tc.value IS NULL

Comment: NOW I have the following problem whit it!!


Cython speedup isn't as large as expected

Question: I have written a Python function that computes pairwise electromagnetic interactions between a largish number (N ~ 10^3) of particles and stores the results in an NxN complex128 ndarray.  It runs, but it is the slowest part of a larger program, taking about 40 seconds when N=900 [corrected].  The original code looks like this:
import numpy as np
def interaction(s,alpha,kprop): # s is an Nx3 real array
                                # alpha is complex
                                # kprop is float

    ndipoles = s.shape[0]

    Amat = np.zeros((ndipoles,3, ndipoles, 3), dtype=np.complex128)
    I = np.array([[1,0,0],[0,1,0],[0,0,1]])
    im = complex(0,1)

    k2 = kprop*kprop

    for i in range(ndipoles):
        xi = s[i,:]
        for j in range(ndipoles):
            if i != j:
                xj = s[j,:]
                dx = xi-xj
                R = np.sqrt(dx.dot(dx))
                n = dx/R
                kR = kprop*R
                kR2 = kR*kR
                A = ((1./kR2) - im/kR)
                nxn = np.outer(n, n)
                nxn = (3*A-1)*nxn + (1-A)*I
                nxn *= -alpha*(k2*np.exp(im*kR))/R
            else:
                nxn = I

            Amat[i,:,j,:] = nxn

    return(Amat.reshape((3*ndipoles,3*ndipoles)))

I had never previously used Cython, but that seemed like a good place to start in my effort to speed things up, so I pretty much blindly adapted the techniques I found in online tutorials.  I got some speedup (30 seconds vs. 40 seconds), but not nearly as dramatic as I expected, so I'm wondering whether I'm doing something wrong or am missing a critical step.  The following is my best attempt at cythonizing the above routine:
import numpy as np
cimport numpy as np

DTYPE = np.complex128
ctypedef np.complex128_t DTYPE_t

def interaction(np.ndarray s, DTYPE_t alpha, float kprop):

    cdef float k2 = kprop*kprop
    cdef int i,j
    cdef np.ndarray xi, xj, dx, n, nxn
    cdef float R, kR, kR2
    cdef DTYPE_t A

    cdef int ndipoles = s.shape[0]
    cdef np.ndarray Amat = np.zeros((ndipoles,3, ndipoles, 3), dtype=DTYPE)
    cdef np.ndarray I = np.array([[1,0,0],[0,1,0],[0,0,1]])
    cdef DTYPE_t im = complex(0,1)

    for i in range(ndipoles):
        xi = s[i,:]
        for j in range(ndipoles):
            if i != j:
                xj = s[j,:]
                dx = xi-xj
                R = np.sqrt(dx.dot(dx))
                n = dx/R
                kR = kprop*R
                kR2 = kR*kR
                A = ((1./kR2) - im/kR)
                nxn = np.outer(n, n)
                nxn = (3*A-1)*nxn + (1-A)*I
                nxn *= -alpha*(k2*np.exp(im*kR))/R
            else:
                nxn = I

            Amat[i,:,j,:] = nxn

    return(Amat.reshape((3*ndipoles,3*ndipoles)))

Comment: Numpy is a C library. And uses BLAS for doing algebra, so it's pretty fast. I don't really understand how cython internals works, but being numpy already C code, the gain in speed is in anything "not numpy".
Comment: Maybe look into profiling/annotating your code to see where the bottlenecks are: http://docs.cython.org/src/quickstart/cythonize.html#determining-where-to-add-types
Comment: You can try to type the your numpy arrays, so that the compiler knows the types inside the arrays. Not sure how big the difference will be, though. You may want to run a profiler on the python code to see where you are actually losing the speed. If most of the time is spent in numpy routines, you will not gain much by using cython.
Comment: My guess (but not take it for granted) is that the most time difference is in the range(dipoles). Try to use the faster numpy.arange() and see how near you go respect to cython.
Comment: I assumed that enough of the line-by-line operations inside the nested loop required the direct invocation of the Python interpreter and that those lines were therefore likely the dominant cost relative to Numpy -- but maybe not?
Comment: What is the correct way to type a numpy array in the above case?  Do I replace np.ndarray with the actual dtype in the cdef statements?
Comment: Switching to np.arange() did save me another 5-10%
Answer: The real power of NumPy is in performing an operation across a huge number of elements in a vectorized manner instead of using that operation in chunks spread across loops. In your case, you are using two nested loops and one IF conditional statement. I would propose extending the dimensions of the intermediate arrays, which would bring in NumPy's powerful broadcasting capability to come into play and thus the same operations could be used on all elements in one go instead of small chunks of data within the loops.
For extending the dimensions, None/np.newaxis could be used. So, the vectorized implementation to follow such a premise would look like this -
def vectorized_interaction(s,alpha,kprop):

    im = complex(0,1)
    I = np.array([[1,0,0],[0,1,0],[0,0,1]])
    k2 = kprop*kprop

    # Vectorized calculations for dx, R, n, kR, A
    sd = s[:,None] - s
    Rv = np.sqrt((sd**2).sum(2))
    nv = sd/Rv[:,:,None]
    kRv = Rv*kprop
    Av = (1./(kRv*kRv)) - im/kRv

    # Vectorized calculation for: "nxn = np.outer(n, n)"
    nxnv = nv[:,:,:,None]*nv[:,:,None,:]

    # Vectorized calculation for: "(3*A-1)*nxn + (1-A)*I"
    P = (3*Av[:,:,None,None]-1)*nxnv + (1-Av[:,:,None,None])*I

    # Vectorized calculation for: "-alpha*(k2*np.exp(im*kR))/R"
    multv = -alpha*(k2*np.exp(im*kRv))/Rv

    # Vectorized calculation for: "nxn *= -alpha*(k2*np.exp(im*kR))/R"
    outv = P*multv[:,:,None,None]

    # Simulate ELSE part of the conditional statement"if i != j:"
    # with masked setting to I on the last two dimensions
    outv[np.eye((N),dtype=bool)] = I

    return outv.transpose(0,2,1,3).reshape(N*3,-1)

Runtime tests and output verification -
Case #1:
In [703]: N = 10
     ...: s = np.random.rand(N,3) + complex(0,1)*np.random.rand(N,3)
     ...: alpha = 3j
     ...: kprop = 5.4
     ...:

In [704]: out_org = interaction(s,alpha,kprop)
     ...: out_vect = vectorized_interaction(s,alpha,kprop)
     ...: print np.allclose(np.real(out_org),np.real(out_vect))
     ...: print np.allclose(np.imag(out_org),np.imag(out_vect))
     ...:
True
True

In [705]: %timeit interaction(s,alpha,kprop)
100 loops, best of 3: 7.6 ms per loop

In [706]: %timeit vectorized_interaction(s,alpha,kprop)
1000 loops, best of 3: 304 µs per loop

Case #2:
In [707]: N = 100
     ...: s = np.random.rand(N,3) + complex(0,1)*np.random.rand(N,3)
     ...: alpha = 3j
     ...: kprop = 5.4
     ...:

In [708]: out_org = interaction(s,alpha,kprop)
     ...: out_vect = vectorized_interaction(s,alpha,kprop)
     ...: print np.allclose(np.real(out_org),np.real(out_vect))
     ...: print np.allclose(np.imag(out_org),np.imag(out_vect))
     ...:
True
True

In [709]: %timeit interaction(s,alpha,kprop)
1 loops, best of 3: 826 ms per loop

In [710]: %timeit vectorized_interaction(s,alpha,kprop)
100 loops, best of 3: 14 ms per loop

Case #3:
In [711]: N = 900
     ...: s = np.random.rand(N,3) + complex(0,1)*np.random.rand(N,3)
     ...: alpha = 3j
     ...: kprop = 5.4
     ...:

In [712]: out_org = interaction(s,alpha,kprop)
     ...: out_vect = vectorized_interaction(s,alpha,kprop)
     ...: print np.allclose(np.real(out_org),np.real(out_vect))
     ...: print np.allclose(np.imag(out_org),np.imag(out_vect))
     ...:
True
True

In [713]: %timeit interaction(s,alpha,kprop)
1 loops, best of 3: 1min 7s per loop

In [714]: %timeit vectorized_interaction(s,alpha,kprop)
1 loops, best of 3: 1.59 s per loop

Comment: @GrantPetty Yes, you need to ignore those warnings as we are setting those values anyway at the end. Also, you are right, it's the trade off with vectorization that you are using a lot more memory, but that's essentially why vectorization is that good, because it stores all those elements in memory and does everything in one go.
Comment: This works very well and is also a great education for me in ways to vectorize.  One issue though:  warnings are generated concern dividing by zero, presumably corresponding to the case that i=j, since R is then 0.  Any way to accomplish the same thing without generating those warnings?  I realize that the affected elements of the array get overwritten in the last line before the return, so maybe I just have to force myself ignore them.
Comment: One other comment:  the vectorized version appears to require a fair bit more memory than the original version, so when I raise N to 9000, the process seems to want at least 50 GB ( there is 16 GB in my machine).  Maybe this is an unavoidable tradeoff with vectorization.


PrimeFaces p:schedule start and end time on all views

Question: I recently upgraded from PrimeFaces 3 to PrimeFaces 5 and my calendar no longer shows the correct display.  I see that PrimeFaces wraps around FullCalendar.io.
In prime faces 3 I could use the time format
timeFormat=hh:mmtt {- hh:mmtt}
to render a start and end time on ALL EVENTS regardless of which view (day, agendaDa, month etc).
Is there a way to do this in Primefaces 5?
Comment: Thanks for referring to the [other Stackoverflow question](http://stackoverflow.com/questions/23884636/pschedule-wrong-timeformat-with-primefaces-5-0) btw... And did you try a newer version? 5.0 is 'old' to...
Answer: Looks like there is an open bug report on github for this:
https://github.com/primefaces/primefaces/issues/190


Erro de dateTime

Question: Estou pegando uma data de dois dateTimes diferente e concatenando em uma variável só, porém quando vou escrever o conteúdo dessa variável fica da seguinte forma:
Período: System.Windows.Forms.DateTimePicker, Value: 20/07/2017 15:52:45 Até System.Windows.Forms.DateTimePicker, Value: 20/07/2017 15:52:45
 String dataTime = tempoInicialEXP.Text + " Até " + tempoFinalEXP.Text;

Answer: você tem que utilizar a propriedade Value do DateTimePicker:
Exemplo:
tempoInicialEXP.Value.ToString();
tempoInicialEXP.Value.ToString("dd/MM/yyyy HH:mm");
tempoInicialEXP.Value.ToShortDateString();

Erro de dateTime


How do i convert a date column using SAS Macro?

Question: I am a SAS Developer. I currently have a script that will read from a table column that is in datetime format. In this script, it looks something like this:

data a; batch_dttm = '01Jan2011:00:00:00'dt; run;
proc sql; select batch_dttm format=16.0 into:batch_dttm from a; quit;

So when I assign it to macro variable, it is actually assigning the value of 2930485 into batch_dttm.
The problem is, when I want to resolve this &batch_dttm in another job at a later stage, i have to use this:

input(&batch_dttm,16.0)

to convert 2930485 into date.
I don't want to resolve in this way as this is the only Macro variable that has to be resolved with this input function. I want to assign 01Jan2011:00:00:00 (as text?) in PROC SQL INTO statement so that i dont have to use input conversion anymore.
I want to call &batch_dttm as datetime format in another script. I only want to resolve the datetime using "&BATCH_DTTM"dt instead of input(&batch_dttm,16.0). I believe there is a step to convert 01Jan2011:00:00:00 into text without changing it to 2930485. Is there anyway to do so?
How can I add 1 more step to make me resolve the macro in below script:

"&batch_dttm"dt
Answer: Why do you think you need to add the INPUT() function?  You can just use the value of the macro variable to generate the number of seconds, 2930485 in your example, into your code.
SAS stores datetime values as a number of seconds, so these two expressions are the same:
where batch_dttm = 2930485 ;
where batch_dttm = '01JAN2011:00:00:00'dt ;

Which means you can just use code like this to use your original macro variable.
where batch_dttm = &batch_dttm ;

If you do need to have the human friendly text in the macro variable, perhaps to use in a title statement, then just change the format you use when creating the macro variable.
select batch_dttm format=datetime20. into :batch_dttm trimmed ...
...
title "Data as of &batch_dttm";
where batch_dttm = "&batch_dttm"dt ;

You can also use %sysfunc() to call PUTN() to change the existing number of seconds into that style if you want.
select batch_dttm format=32. into :batch_dttm trimmed ...
...
title "Data as of %sysfunc(putn(&batch_dttm,datetime20.))";
where batch_dttm = &batch_dttm ;

Answer: Like this?
proc sql;
    select put(batch_dttm, datetime20.) into:batch_dttm from a;
quit;

%put &batch_dttm;

Comment: I want to call &batch_dttm as datetime format in another script. I only want to resolve the datetime using "&BATCH_DTTM"dt instead of input(&batch_dttm,16.0).


Family of maps from inverse system to another space

Question: The universal property of an inverse limit $\lim_{\leftarrow} X_\alpha$ allows one to define from a compatible system of maps $\psi_\alpha: Y \rightarrow X_\alpha$ a unique map $\psi: Y \rightarrow \lim_{\leftarrow} X_\alpha$ making the obvious diagrams commutative.
I'm interested in the case of maps in the opposite direction, i.e. when does the family $\phi_\alpha: X_\alpha \rightarrow Z$ defines a map $\phi: \lim_{\leftarrow} X_\alpha \rightarrow Z$?
Answer: I guess it will certainly be the case whenever you'll have $\phi_\alpha = \phi_\beta\circ \psi^\alpha_\beta$, where $\psi^\alpha_\beta:X\alpha\to X_\beta$ is the bonding map of the inverese system $\{X_\alpha\}$, $\alpha \ge\beta$.
In fact this follows by the same argument which one can use to prove the case you provided as motivation... You can represent $Z$ as the limit of the trivial inverse system $\{Z_\alpha\}$, where $\alpha$ belongs to the same indexing set as in the case for $\{X_\alpha\}$, all $Z_\alpha$ are $Z$ itself, and the respective projections are identities. Then if $\phi_\alpha = \phi_\beta\circ \psi^\alpha_\beta$ holds, your family of mappings satisfies the definition of a morphism ov inverse systems over the same indexing set. Every such morphism has the limit.


$Av = 0\iff v \perp\mbox{ rows of }A$. Why is this the case?

Question: This question is to better my general understanding of the proof of the following theorem:
Theorem: Let $A$ be an m x n matrix. Let $W = \mbox{Rowspace}(A) = \mbox{Span}\{\mbox{rows of A}\}$. Then $W^{\perp} = \mbox{Nullspace}(A) = \mbox{Kernal}(A) = \{v\in\mathbb{R}~|~Av = 0\}$.
Proof: $v\in\mbox{Nullspace}(A)\iff Av = 0\iff v\perp\mbox{ rows of }A\iff v\in W^{\perp}$
I don't see where the middle '$\iff$' comes from, i.e. I don't understand why $Av = 0\iff v \perp\mbox{ rows of }A$.
Any clarification would be much appreciated, thank you.
Answer: If $A=\begin{bmatrix}r_1\\r_2\\...\\r_m\end{bmatrix}$, then $Av=\begin{bmatrix}r_1\cdot v\\r_2\cdot v\\...\\r_m\cdot v\end{bmatrix}=0\iff r_i\cdot v=0$ for $1\le i\le m$.
Answer: Let $A_j$ , $j\in \{1,\ldots,m\}$ denote the rows of $A$.
$$Av=0 \Longleftrightarrow \left(\begin{array} &A_1\\ A_2\\ \vdots\\ A_m\end{array}\right) v =\left(\begin{array} &0\\0\\ \vdots\\ 0\end{array}\right )\Longleftrightarrow A_j \cdot v=0 \text{ for } j\in 1,\ldots m $$
$$\Longleftrightarrow A_j\perp v \text{ for } j\in 1,\ldots m $$
Comment: Any other ios 8.2 user who sees the parentheses shifted down?
Comment: I also had problems in firefox during the creation. It only looks finde if I add a & sign to the first and only to the first row. I haven't tried the matrix environments though.
Answer: $(\Rightarrow)$ Suppose that $Av=0$. From the definition of matrix multiplication the $i$-th component of the zero vector is obtained by the scalar product from the $i$-th row of the matrix $A$, that we call $A_i$, and the vector $v$, i.e
$<A_i,v> = 0$ for all $i=1 \ldots m$. So the vector $v$ is orthogonal to all rows of matrix $A$.
($\Leftarrow$)The vice versa follows as above.


Length of a bernoulli process to get a fixed amount of tails

Question: I have the following Bernoulli process:

Initial state: H = 0, T = 0
I launch a coin where probability of head is p.
If I get head, then H = H + 1. If I get tails, then T = T + 1.
I repeat the experiment until T = t_0.

Given that, I want to know how many times I have to keep this Bernoulli process going until getting $t_0$ tails (for example, $t_0 = 100$). Since $t_0$ is a constant and $n = H + t_0$, that is, I guess, the same as asking for the probability distribution of $H$ given $t_0$ tails.
The point is to generate a random number for $H$ from its probability distribution given $p$ and $t_0$ without actually running the iteration.
Answer: What you want is negative binomial distribution which

models the number of successes in a sequence of independent and identically distributed Bernoulli trials before a specified (non-random) number of failures (denoted $r$) occur.

In your case, $r=t_0$ and tails are the "failures".