Slow download speeds (own debian mirror)

Question: I am using ftpsync to have a local version of the debian packages for all of our debian clients.
Internally, the traffic from the mirror is at our normal LAN speeds (100 MB/s); however, when a client is off-site, the speed is in the range of 80-200KB/s.
Is there a setting to limit the traffic to external clients? What ports sould be open on the firewall?
Comment: Well...if you're hosting this mirror locally and your external clients are grabbing it, you're limited to your Internet connection speeds...
Comment: Just out of interest, do you really want to provide a mirror?  Are you geographically isolated?  If not, you might find a cahceing proxy more beneficial -> http://packages.debian.org/wheezy/apt-cacher-ng and http://www.unix-ag.uni-kl.de/~bloch/acng/
Comment: @NathanC Host is 100mbit upload and client is 15mbit download.
Comment: @sgtbeano I do not want caching, I wanted a full mirror. There is no sense having 100 connections to a debian main mirror when I can limit it to 1 connection once a day. Especially since I have the resources available.
Comment: @AWippler Even still, how many clients are pulling from this external mirror? 100mbit can be exhausted quite quickly and you'd run into this limitation. Distance and latency also plays a role.
Comment: @NathanC 14 hops from client to host (Verizon DSL to Cogent Fiber). 0% network usage on the host at the time apt-get is performed on the client.
Comment: @AWippler Forgive my ignorance, but it is not clear for me what are you willing to get: increase speed of external clients? or limit it? or give preferences to some external clients before others?
Comment: @AWippler - I think you misunderstand me.  By using apt-catcher-ng you will only have a low number of connections to the main mirror.  Once an package is cached, all other clients then access the local cache.
Comment: @Veniamin Yes, increased speed of external clients. No matter which external internet connection I use, the mirror only pushes out packages at 80-120KB/s. This is with the mirror's network with 0% use.
Comment: @AWippler 100KB/s - is a not so bad speed on 14-hops distance. You can start with pure end-to-end network performance measurements using iperf. If the results will be the same, consider steps for tcp perfomance tuning.
Answer: you can run...
"netstat | grep -i ftpsync"
...on the server and then allow the ports that it uses to the firewall.  if that doesnt turn up enough info you can google about netstat to better tune you search for active ports.
but if you are using the same protocol offsite as onsite that inst your issue unless the offsite firewall restricts requests initiated by clients inside the network which isnt a super normal thing for most routers unless otherwise configured to do so (most off the shelf routers/"modems" will automatically open ports that clients request traffic on).
for limiting bandwidth to external clients i cant help you. there might be mention in the ftpsync documentation, if you can find any. a quick google turned up a 404 and something on the Debian website about making a mirror with it.
to test that it isnt just the network being sad you can try copying a file between the networks with a different protocol, like scp, and check the speed on that. then possibly check speed domain vs. ip (if you have a domain setup).


Criar divs com textos e imagens

Question: Tenho conhecimento muito básico em html e css, por isso quero a ajuda de vocês para a construção de alguns pontos do layout abaixo usando HTML e CSS.
O img  trata de uma imagem de tamanho 100px por 100px.
Observação: O  texto A,B e F tem que ter um espaço entre as imagens e  estar centralizado conforme a imagem abaixo.
O texto C,D e F,  tem que estar embaixo da imagem, porém centralizado conforme é mostrado.

Conto com a ajuda de vocês !
Obrigada.
No codigo abaixo iniciei a implementação, porém não sei como deixar igual ao demonstrado acima quanto  ao espaço e pular linha para cada imagem dos Texto A    e Texto B.

 Ler

 Ler

Comment: Bem vinda ao sopt. O que você já tentou?
Comment: Entendo, mas seria interessante você tentar, no site, a gente está sempre disposto a ajudar quem precisa, porém pedir coisas prontas é meio que aproveitar da boa vontade de quem quer te ajudar. :/ Comece primeiro clicando nas tags html e css para ver outros conteudos para ter uma noção do que está fazendo, ai quando tiver uma base, edite a pergunta e adicionae-a, assim fica mais facil ajudar :)
Comment: Diego Obrigada,  melhorei a pergunta, realmente já pesquisei na net e etc o que ocorre aqui é q tah faltando pratica
Answer: O comando para centralizar verticalmente em css é line-height.
Dá uma olhada no código abaixo e veja se lhe atende.

.linha {
  display: table;
  margin: 5px;
  }

.img  {
    width: 100px;
    height: 100px;
    border: solid 3px #000;
  float: left;
}

.texto_img {
  width: 100px;
  height: 100px;
  line-height:100px;
  float: left;
}

.celula {
  float: left;
  margin: 2px;
  }

.legenda {
    text-align: center;
  width: 100px;
  }

img 01

Texto A

Img 02

Texto B

Img 03

Texto C

Img 04

Texto D

Img 05

Texto

Img 06

Texto F

Comment: Eduardo Mendes, Muito Obrigada! Exatamente oque eu precisava ;), Boa Noite.
Comment: Maravilha. Que bom que lhe serviu. Depois marca a resposta como útil para você.

Criar divs com textos e imagens


Requests and connections double on node 4.1.2

Question: We're currently in the process of updating from node 0.10 to node 4.1.2 and we're seeing some weird patterns. The number of connections to our postgres database doubles1 and we're seeing the same pattern with requests to external services2. We are running a clustered app running the native cluster API and the number of workers is the same for both versions.
I'm failing to understand why upgrading the runtime language would apparently change application behaviour by doubling requests to external services.
Comment: Your question requires a unique research. It is not likely the issue is known to anyone, especially considering just how fresh NodeJS 4.x is.
Comment: Which node package are you using to access postgres?
Comment: `pg` v4.4.1. I also opened an [issue on their repo](https://github.com/brianc/node-postgres/issues/871) but I don't think the problem is coming from there.
Comment: They released 4.4.2 to cater for some issues around Node 4.x support. Have you tried it yet? What makes you think the problem isn't coming from there? I would suspect the pg package first.
Comment: According to `pg`'s author nothing has changed in terms of connection pooling for a long time. Also the 2nd graph I posted is of external HTTP requests which also seem to double and have nothing to do with postgres. I'm now suspecting the app clustering but no evidence anything is "doubled" right now.
Comment: You're probably right. I was hoping someone would have seen this scenario already and could help.
Comment: It's interesting really and a good research object. But please bear in mind that this is somewhat anticipated since between `0.10.0` and `4.2` lie 2.5 years. The language has changed a lot. Also this is a [really good read](https://github.com/nodejs/node/wiki/API-changes-between-v0.10-and-v4)   as a starting point.
Comment: @chris911 You have any updates on this?
Comment: Not yet. Will probably deploy once more next week on node latest.
Comment: Have you considered that the change may be the way New Relic is tracking things in Node? I would reach out to them. The New Relic agent hooks in at a very low-level and could be causing side effects.
Comment: Yeah that was one of my first idea. When I posted this New Relic didn't officially support Node 4. Numbers were the same when they released a client with official support for Node 4 though. Months later we figured that the number of DB connections on Node 4 is actually the expected number. For some reasons it seems with 0.10 we were underusing our ressources and available connections. As for the number of HTTP requests to external service we just assumed it was a change in the tracking code and moved on. All is fine and we've been on node 4 for a couple months now.
Comment: You may have been affected by a change that landed in 0.12.0. From https://nodejs.org/en/blog/release/v0.12.0/: "HTTP maxSockets are no longer limited to 5. The default is now set to Infinity with the developer and the operating system given control over how many simultaneous connections an application can keep open to a given host."
Answer: I ran into something similar, but I was getting double file writes. I don't know your exact case, but I've seen a scenario where requests could almost exactly double.
in the update to 4.1.2, process.send and child.send has gone from synchronous to asynchronous.
I found an issue like this:
var child = fork('./request.js');
var test = {};

child.send(small request);
child.send(large request);
child.on('response', function (val) {
    console.log('small request came back: ' + val);
    test = val;
});

if(!test){
   //retry request
} ...

So where as previously the blocking sends has allowed this code to work, the non-blocking version assumes an error has occurred and retries. No error actually occurred, so double the requests come in.
Comment: Interesting. We're using [throng](https://github.com/hunterloftis/throng/blob/master/lib/throng.js) to do clustering and fork the whole app. There's no retry logic in there.
Answer: One of the interesting things I've noticed with 0.12 and 4.x is the change in garbage collection.  I've not used the pg module before so I don't know internally how it maintains it's pools of if it would be affected by memory or garbage collection.  If you haven't defined default memory setting for node you could try giving that a shot and see if you see any other results.
node --max_old_space_size <some sane value in MB>
Comment: After more investigation I doubt the problem is coming from postgres and the connection pool. What is worrying is really the number of outgoing HTTP requests which lies in the application logic and doesn't use any external lib.


I want the output as json from the object input, as mentioned below by using for loop

Question: By taking a as input want b as output using javascript,
    input: var a = {"xyz", "abc", "123"};
    output: [{name: "123"}, {name: "abc"}, {name: "123"}];

Comment: Is `a` an `Array`? Why is `"xyz"` not set as a value of an object though `"123"` is set as a value twice? No `for` loop appears at Question.
Comment: Typo error---input: var a = ["xyz", "abc", "123"];
output: [{name: "xyz"}, {name: "abc"}, {name: "123"}];
Comment: `var a = {"xyz", "abc", "123"}` is not a valid `javascript` object. Do you mean `var a = ["xyz", "abc", "123"]`?
Comment: yes var a = ["xyz", "abc", "123"];
Comment: What have you tried so far? Can you post the javascript code you've written to solve this problem?
Answer:

var a = ["xyz", "abc", "123"]
let output = a.map( (e) =>  {return {name:e}} )
console.log(JSON.stringify(output));

Considering you want
input: var a = ["xyz", "abc", "123"];
output: [{name: "xyz"}, {name: "abc"}, {name: "123"}];

Below is the solution:
let output = a.map( (e) => {
        return {"name":e}
})
console.log(JSON.stringify(output));

Comment: you could shorten it to `a.map(e => ({ name: e }))`
Answer: Guess a is an array. If so, i'am recommend to use forEach or map for this purpose.
There is example with for loop.

var a = ["xyz", "abc", "123"],
    newArr=  [];
for(var i = 0; i< a.length; i++){
    newArr.push({name: a[i]})
}
console.log(JSON.stringify(newArr));
Comment: it is not returning expected output.


Ideal of a field

Question: Let $F$ be a field. Show that  $S$ be a non empty subset of $F^{n} $ then
$ I(S) =$ {  $    f(x) \in F[x] \hspace{0.1in} \vert  \hspace{0.1in}f(s) = 0  \hspace{0.1in}   \forall  s \in S  $ }
is an ideal of $F[x]$
Comment: I think it is a matter of applying the definition.
Comment: What have you done so far?
Comment: I am stuck.I tried by taking kernel of a ring but couldn't do much.
Comment: Is $x$ understood as $(x_1,\ldots,x_n)$ here?
Answer: The ideal-idea is fine. For fixed $s$, the evaluation $F[x]\to F$, $f\mapsto f(s)$ is a ring homomorphism.
Comment: @sammath By definition of $F[x]$ via its universal property: For every ring hom $F\to A$ and every map $x\to A$ there exists a unique ring hom $F[x]\to A$ such that ...
Comment: Could you please elaborate ?

Ideal of a field


Parse .conf file using python

Question: I have a file called clients.conf .
Here is its content :
client: {
    # client data
    name: "James"
    information: {
        age: "32"
        adress: "258 Arthur Street"
    }
    email: email@example.com
    certification: {
        status: "expired"
        id: 12345324
    }
}

I would like to parse it using python 2.7 (or 3.x).
Here is the code I am using, it doesn't detect any section in the file:
config = ConfigParser()
with open('clients.conf') as stream:
    stream = StringIO(stream.read())
    config.readfp(stream)

print(config.sections())

The print.sections() at the end provides an empty array.
Comment: Yeah, `ConfigParser` is meant for INI style files - what you have is nothing like that. Your file has nested blocks and mixed `=`s and `:`s and unquoted string literals and quoted strings and `#` comments..... you'll need to write a parser yourself.
Comment: @DecowVR One good reason might be that the input data is not JSON.
Comment: @DecowVR No, no it won't.
Comment: Where did you get this file? Can you also double-check whether the email field is unquoted as in your example..?
Comment: why not to use `json`?
Comment: @AKX `stream.read().replace("\n", ",")` and it will become a json :( (omiting comments)
Comment: My bad, the file doesn't contain any "=", I corrected the question.
Comment: Some fields are quoted and some are not :( All I know is that it is a .conf file.
I am a beginner to using such files
Answer: It looks like an HJSON document, you can parse it using the hjson module.
import hjson

with open("client.conf", 'r') as f:
    conf = hjson.load(f)

print(conf["client"]["name"])  # James
print(conf["client"]["email"])  # firstname.lastname@example.com

Parse .conf file using python


DOM removing selected child nodes

Question: I have a dom element with html inside chat contains some html elements I'd like to remove, while still keeping some tags that are ok.
I try to iterate through child elements all child elements and delete those that need to be removed
foreach ($node->getElementsByTagName('*') as $element)
    if ($element->nodeName != 'br')
        $node->removeChild($element);

But this throws a Not Found Error exception which not being caught causes a fatal error.
How would I solve this problem ?
Answer: Use the following instead to remove the node:
$element->parentNode->removeChild($element);

Comment: not working for me  , now showing any errors as well.
Answer: getElementsByTagName('*') finds all descendent elements, not child elements.  So some of the $element you want to remove are not children of $node, hence the failure.
I'm not 100% sure what your intention is here, but most likely you just want to remove certain immediate children. In this case, do the following:
$nodestoremove = array();
foreach ($node->childNodes as $n) {
    if ($n->nodeType===XML_ELEMENT_NODE and $n->nodeName!=='br') {
        $nodestoremove[] = $n;
    }
}
foreach ($nodestoremove as $n) {
    $node->removeChild($n);
}
unset($nodestoremove); // so nodes can be garbage-collected

echo $node->C14N(); // xml fragment after removal

Note that we make two passes: one to identify the nodes to delete, and a second pass to delete. This is because childNodes is an active list, so we can't iterate through it forwards as we delete. (Although we could iterate through it backwards.)

DOM removing selected child nodes


Divisão matemática precisa

Question: Na calculadora Windows: 9/3,0001 = 2.999...
No meu programa: 9/3,0001 = 3;
Gostaria de obter esse nível de precisão usando C.
Vide trechos do meu programa:
double op(double num1, double num2, char c)
{
      if(c == '/')
      {
        if(num2 == 0)
        {
            printf("operacao nao pode ser realizada");

            exit(1);
        }
        else
            num1 = (num1)/num2;
      }

      ...

      printf("%.3lf\n", num1);

      return num1;
}

int main()
{
   double num1,num2;

   char c;

   scanf("%lf", &num1);

   scanf("%lf", &num2);

   scanf(" %c", &c);

   num1 = op(num1, num2, c);

   ...

   return 0;
}

Como fazer?
Comment: O -1.#QNAN0 error é Negative Quiet Not a Number
Answer: Existem diversos posts sobre isto aqui no site (esse por exemplo). Você não consegue fazer isto em nenhuma linguagem com número com ponto flutuante binário que é o caso de float e double. Você precisa montar uma estrutura de dados ou tratar os dados de uma forma diferente. Normalmente é a forma decimal ou monetária. Comumente os números são tratados como se fossem inteiros e apresentados com casas depois da vírgula.
A precisão obtida com ponto flutuante binário tem pequenas falhas que são bem aceitas em diversas situações e trabalha com a vantagem de ser extremamente rápido. Uma das situações em que ele não pode ser usado é quando valores monetários estão sendo usados. Mas qualquer caso em que seja exigida precisão absoluta.
Não tem nada que resolva o "problema" do ponto flutuante. Pode usar um dado com muitas casas decimais de precisão que não vai resolver a questão.

Como formatar valores monetários com C++?
Valor decimal MySql
Melhor tipo de dados para trabalhar com dinheiro?
Que tipo de dados (double, float ou decimal) eu deveria usar para representar moeda em .NET com C#?
Manipular preço em controle de estoque
Como representar dinheiro em JavaScript?
Diferença de performance e situação de uso de tipos numéricos
Qual a forma correta de usar os tipos float, double e decimal?

Em inglês (as melhores referências sobre o assunto):

https://floating-point-gui.de/
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Essas respostas não são específicas para C mas o conceito é o mesmo para todas as linguagens porque é a forma como o processador funciona.
Qualquer outra forma só criará uma ilusão de que a divisão foi feita corretamente.
A calculadora do Windows resolve a questão na programação dela. O software entende que a precisão é necessária e lida com os dados desta forma. Curiosidade: Divida 10 por 3 e depois multiplique o resulta por 3 na calculadora do Windows. Depois limpe tudo e digite o resultado da divisão na mão. Pode por quantas casas você quiser na dízima. (3,33333333333333). A multiplicação por 3 dá resultado diferente. O software controla isso.
Coloquei no GitHub para referência futura.
Comment: Nossa, parecia uma pergunta simples, tem um oceano por detrás.
Comment: Muito interessante, obg!
Answer: Se você realmente quer precisão exata para operações com ponto flutuante, terá que utilizar uma biblioteca tal qual a GMP. O usuário @Maniero deu uma introdução razoável sobre aonde encontrar mais informações sobre ponto flutuante (que não é um problema da linguagem C em sí, e sim do modo como ponto flutuante é implementado dentro do processador).
A biblioteca GMP, de GNU Multi-Precision Library, é uma biblioteca open source, para trabalhar com números com precisão arbitrária, sejam eles inteiros, fracionais ou de ponto flutuante.
É muito simples trabalhar com ela, e a documentação é bem completa, além da biblioteca estar disponível para todas as principais plataformas e arquiteturas.
Mais informações em The GNU Multiple Precision Arithmetic Library.
Comment: Eu estava procurando ela :)
Answer: No seu exemplo,
9/3.0001 ~ 2.99990000333322222592
Assim, a resposta arredondada a 3 casas decimais é de facto 3.000.  O seu programa está correto, dentro dos limites de precisão que especificou.  Se quiser o resultado com mais casas de precisão, deve indicá-lo no printf:
printf("%.9lf", num1);  // com 9 casas de precisao

O tipo double tem precisão suficiente para cerca de 15 algarismos significativos (não quer dizer que sejam 15 casas decimais, depende de quantos algarismos significativos tem na parte inteira do número).  Se de facto precisar de mais do que isso, então poderá usar outro tipo de representação, como foi sugerido noutras respostas.
Para cálculo científico (em engenharia, física, outras ciências experimentais) é usual usar-se representações em vírgula flutuante (como o double) porque os próprios dados são geralmente imprecisos.  Assim, os resultados calculados a partir desses dados também não podem ser muito precisos.  Se tirou uma medida de comprimento usando uma régua com resolução de 1 décimo de mm, então a medida observada de 3.0001 m pode de facto ser 3.00013 m ou 3.000098.  A observação tem um erro que poderá ser de +/-0.00005 m.  Se fizer a divisão de duas medidas com essa margem de erro, também o resultado vem afetado de um erro da mesma ordem de grandeza.  Assim, não é significativo mostrar o resultado com mais algarismos significativos do que os que tem nos operandos.
Em muitas aplicações, é raro ter-se dados com mais de uma dezena de algarismos significativos, pelo que a precisão de um double costuma ser mais que suficiente.
Answer: Se você sempre quer resultados numéricos exatos, isso é intrinsecamente impossível de se conseguir, usando computadores ou não. Por exemplo, qual o resultado "exato" da raiz quadrada de 2 ? O resultado é um número irracional, portanto não tem uma representação numérica exata. Existem muitos outros números assim, um número infinito na verdade. :) (Existem até mesmo números racionais de tamanho infinito, que são as dízimas periódicas.)
Especificamente quanto aos computadores, mesmo para números racionais nem sempre é possível obter uma representação númerica "exata". É só pensar em um número grande, por exemplo 1234567890[5 repetições]. Não é possível representar este número de forma exata em uma variável double da linguagem C, simplemente por que não cabe em uma variável double...
Que eu saiba, existem (pelo menos) três maneiras de contornar parcialmente as limitações matemáticas dos computadores e linguagens atuais.
A primeira maneira é utilizar uma biblioteca matemática de "precisão infinita". Essas bibliotecas são muito utilizadas atualmente, porque são necessárias para criptografia computacional (principalmente criptografia de chave pública, usada nas "conexões seguras" em sites do tipo https://). Obviamente essas bibliotecas continuam tendo limitações na representação numérica de números irracionais, mas utilizam um método para armazenar números que torna possível cálculos com números "grandes", como 1234567890[5 repetições] que citei acima, ou como as chaves de 1024 ou 2048 bits muito usadas em criptografia de chave pública.
A segunda maneira é trabalhar com biblioteca de números fracionários. Desta maneira, é possível trabalhar naturalmente com dízimas periódicas e com certos tipos de números irracionais.
A outra maneira é trabalhar com matemática simbólica, onde se utilizam símbolos para números irracionais conhecidos, como e, pi, etc. Normalmente se usa alguma aplicação específica para isso, como o "Wolfram Mathematica" (e programas open source similares), ou linguagens específicas, como (se não me engano) R, Julia, etc. Com certeza existem também bibliotecas para matemática simbólica para liguagens como C, Python, etc, é só uma questão de procurar.

Divisão matemática precisa


Adding two outcomes and comparing with a third outcome

Question: I did two experiments, with component A and component B respectively, and the outcome that I have is "mass loss" for those two components. Now, there is a third experiment where both components are used together and there is a combined mass loss. Lets call it C. I'm trying to perform stats to see if the A+B is greater than or equal to C. Each experiment has 5 samples each. Is it appropriate to iteratively sum the samples of A and B to get a combined mass loss and then compare it with C using a t-test? What other statistical test would you recommend?
Comment: Are samples for A, B and C independent? Or are you performing A, B and C experiments on the same specimens?
Comment: The samples of A, B and C are independent..
Answer: Since A, B and C are independent (according to comment), A+B and C are independent and therefore a t-test for independent samples is adequate to tell if mean of A+B is different from mean of C. However, I wouldn't sum iteratively observations from A and B (A1+B1, A2+B2...). I would sum all possible pairs in A and B (A1+B1, A1+B2...). Alternatively, variance of A+B could be computed summing variances of A and B.
Of course, assumptions of t-test must hold for A+B and C, but if A and B are normal, A+B will be normal, too.


How do I programmatically check whether a custom entity is stored in external database?

Question: In Drupal 8, how do I programmatically check whether a custom entity is stored in the external database using the entity ID?
Do we have any method/service to check whether a custom entity is stored in an external database using the entity ID?
Comment: Cross-posted on https://www.drupal.org/project/drupal/issues/2995238
Answer: Presuming you have configured the external database correctly inside settings.php you have to use db_set_active('MYEXTERNALDATABASE'), then do your DB query to check for your ID and when you're done db_set_active('default') set the active database back.
db_set_active

Sets a new active database.
Comment: Hi @leymannx: Thanks. please guide me how to do that in system.install file as per this thread - https://www.drupal.org/project/drupal/issues/2995238 because it is core file.
Comment: @vignesh.rajendran11 - Which is a totally different question. Please ask a new question.
Comment: Hi @leymannx: it's okay but your answer is not relevant for our question because we are expecting the method/service to get database details of custom entity. Anyways thanks for help.


Angular4 ng-content gets built when ngIf is false

Question: I have a problem with the new ng-content transclusion.
Let's say I have a component my-component that, in its ngOnInit() function does some heavy operation on load (for now, just a console.log()).
I have a wrapper, that displays the content via transclusion (my-wrapper.component.html).
<ng-content></ng-content>

If I set the surroundings up like this, the log statement doesn't show:
<my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>

I assume, the my-wrapper component does not get built, so the content is ignored.
But if I try to move the logic into the my-wrapper component like this (my-wrapper.component.html):
<ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>

I always see the console.log() output. I guess, the my-component gets built and then stored away until the *ngIf becomes true inside my-wrapper.
The intention was to build a generic "list-item + detail" component. Say I have a list of N overview-elements (my-wrapper), that get rendered in a *ngFor loop. Every of those elements has its own detail component (my-component) that is supposed to load its own data, once I decide to show more infos to a specific item.
overview.html:
<ng-container *ngFor="let item of items">
    <my-wrapper>
        <my-component id="item.id"></my-component>
    </my-wrapper>
</ng-container>

my-wrapper.component.html:

Click for more

    <ng-content></ng-content>

Is there a way to tell Angular, to ignore the transcluded content until it is necessary to be added to the page? Analogously to how it was in AngularJS.
Comment: https://stackoverflow.com/questions/41652919/instantiate-transcluded-components-depending-on-their-dom-state-in-angular-2
Comment: I would suggest instead of adding condition on wrapper  add the condition to child component to stop the execution
Answer: Based on the comment of @nsinreal I found an answer. I find it to be a bit abstruse, so I'm trying to post it here:
The answer is to work with ng-template and *ngTemplateOutlet.
In the my-wrapper component, set up the template like this (my-wrapper.component.html):

Click for more

    <ng-container *ngTemplateOutlet="detailRef"></ng-container>

Note, that the [hidden] there is not really necessary, it hides the "raw" template of the child until it decides it is done loading. Just make sure, not to put it in a *ngIf, otherwise the *ngTemplateOutlet will never get triggered, leading to nothing happening at all.
To set the detailRef, put this in the component code (my-wrapper.component.ts):
import { ContentChild, TemplateRef } from '@angular/core';

@Component({ ... })
export class MyWrapperComponent {
    @ContentChild(TemplateRef) detailRef;

    ...
}

Now, you can use the wrapper like this:
<my-wrapper>
    <ng-template>
        <my-component></my-component>
    </ng-template>
</my-wrapper>

I am not sure, why it needs such complicated "workarounds", when it used to be so easy to do this in AngularJS.
Answer: By doing this:
<my-wrapper *ngIf="false">
    <my-component></my-component>
</my-wrapper>

You are not calling MyComponent component, because the *ngIf is false. that means, that not calling it you are not instancing it and, therefore, not passing through its ngOnInit. And that's why you are not getting the console log.
By doing this:
<ng-container *ngIf="false">
    <ng-content></ng-content>
</ng-container>

You are inside the component, you are just limiting what to render in your template, but you already instanced your component and, therefore, you passed through your ngOnInit and you get your console log done.
If, you want to limit something (component call with selector or a ng-content or even a div) until you have some data available, you can do the following:
datasLoaded: Promise<boolean>;

this.getData().subscribe(
       (data) => {
            this.datasLoaded = Promise.resolve(true); // Setting the Promise as resolved after I have the needed data
       }
);

And in your template:
<ng-container *ngIf="datasLoaded | async">
   // stuff here
</ng-container>

Or:
<my-component *ngIf="datasLoaded | async">
   // Didn't test this one, but should follow the same logic. If it doesn't, wrap it and add the ngIf to the wrapper
</my-component>

Comment: I don't think this works in my case. The intention was this: I have a list of overview-data, that get rendered in a `*ngFor`-loop (`my-wrapper`). For every overview-item I have a second "detail" component (`my-component`), that is supposed to load its own data (by ID of the overview-item), once I toggle the parent (the `*ngIf`). If I try your approach, all the details will fire immediately, causing hundreds of expensive API calls. I guess I could integrate the `my-component` more into `my-wrapper`, but this makes it less generic, which is disappointing.
Answer: It's because Ng content happens at the build time and when you pass the content it is actually not removed or recreated with the ngIf directive. It is only moved and the component is instantiated .
Answer: I encountered this problem recently as well but settled on a different solution than the currently accepted one.
Solution (TL;DR)
(Solution is for AngularDart; I figure it's similar in Angular though)
Use a structural directive; tutorials linked below.
Instead of:
<my-wrapper>
  <my-contents></my-contents>
</my-wrapper>

your usage becomes:

  <my-contents></my-contents>

which is shorthand for the following (in AngularDart; I think Angular uses <ng-template>)
<template myWrapper>

    <my-contents></my-contents>

</template>

The MyWrapper directive logic is similar to NgIf except it has its own logic to compute the condition. Both of the following tutorials explain how to create an NgIf-like directive and how to pass it your own inputs using the special microsyntax (e.g. *myWrapper="myInput: expression"). Note that the microsyntax doesn't support outputs (@Output), but you can mimic an output by using an input that is a function.
Tutorial for Angular
Tutorial for AngularDart
Caveat: Since this is just a directive, it shouldn't do anything more complicated than instantiating a template ref at the appropriate time and maybe specifying some DI providers. For example, I would avoid trying to apply styles or instantiating a complex tree of components in the directive. If I wanted to create a list component, I would probably take the @ContentChild(TemplateRef) approach described in another answer; you would lose the asterisk shorthand for creating <template> but you would gain the full power of components.
My problem
My team owns an app that's part of a larger web application with other apps owned by other teams. Our components assume they can inject a MyAppConfiguration object, but this object can only be injected after it is loaded with an asynchronous request. In our app this is not a problem: we have a "shell" component that hides everything behind an ngIf until the configuration is loaded.
The problem is when other teams want to reference our components. We don't want them to duplicate the "wait until configuration is loaded" logic every time, so I tried creating a wrapper component that can be used like so:
<my-app-wrapper>
  <my-app-component></my-app-component>
</my-app-wrapper>

The wrapper injects a service object and hides its contents behind an ngIf until the service says that the configuration is loaded.
Like the question poster, I discovered that the ng-content approach doesn't work as intended: while the contents are correctly hidden from the DOM, Angular still instantiates the components causing dependency injection to fail.
The solution that I settled on was to rewrite the wrapper component as a structural directive.


swiftui list - snap scrolling

Question: i have a fullscreen list of element.
    VStack{
        List {
           ForEach(books, id: \.id) { book in
             Text(book.title)
               .background(Color.yellow) // text background
               .listRowBackground(Color.blue) // cell background
           }
           .frame(height: UIScreen.main.bounds.height)
         }

    }
    .background(Color.red)
    .edgesIgnoringSafeArea(.all)

Is possible to snap every cell on top when scrolling? I have no idea how to do this.
Thank you!
Comment: what do you mean by `snap` ? Snapshot?
Comment: sorry .... when you scroll next row go to directly on top. Scroll is not free. Thanks!
Answer: You can use DragGesture and ScrollViewReader to create a snapping List in SwiftUI.
We are calculating the velocity to move the list.

Here is a full sample Code:
struct SampleSnappingListView: View {
enum ScrollDirection {
    case up
    case down
    case none
}
@State var scrollDirection: ScrollDirection = .none

var body: some View {
    VStack {
        ScrollViewReader { reader in
            List {
                ForEach(0...20, id:\.self) { index in
                    ZStack {
                        Color((index % 2 == 0) ? .red : .green)
                        VStack {
                            Text("Index \(index)")
                                .font(.title)
                        }
                        .frame(height: UIScreen.main.bounds.height/2)
                    }
                    .clipShape(Rectangle())
                    .id(index)
                    .simultaneousGesture(
                        DragGesture(minimumDistance: 0.0)
                            .onChanged({ dragValue in
                                let isScrollDown = 0 > dragValue.translation.height
                                self.scrollDirection = isScrollDown ? .down : .up
                            })
                            .onEnded { value in
                                let velocity = CGSize(
                                    width:  value.predictedEndLocation.x - value.location.x,
                                    height: value.predictedEndLocation.y - value.location.y
                                )
                                if abs(velocity.height) > 10 {
                                    withAnimation(.easeOut(duration: 0.5)) {
                                        let next = index + (scrollDirection == .down ? 1 : -1)
                                        reader.scrollTo(next, anchor: .top)
                                    }
                                }
                            }
                    )

                }
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
            }
            .listStyle(.plain)

        }
    }
  }
}

struct SampleSnappingListView_Previews: PreviewProvider {
   static var previews: some View {
      NavigationView {
        SampleSnappingListView()
            .navigationTitle("Snapping list")
            .navigationBarTitleDisplayMode(.inline)
    }
  }
}

UPDATE:
For some reason, in new SwiftUI versions, velocity is calculating differently, so I made it smaller: abs(velocity.height) > 10 . Please set it according to your project

swiftui list - snap scrolling


Default to "no limit" for maximum number of options in field type select

Question: The number of cities and sectors "small cities" in Moldova is around thousand,so we have already exceeded the arbitrary 100 limit without half-trying.
The limit causes problems when we translate the options.
We get message translations were saved successfully, however going back to translation noting is saved.
Looking into server logs we found out there is a problem with max_input_vars in php.ini

2016/02/02 11:37:26 [error] 1310#0: *199007 FastCGI sent in stderr:
  "PHP message: PHP Warning:  Unknown: Input variables exceeded 1000. To
  increase the limit change max_input_vars in php.ini. in Unknown on
  line 0"

We updated the php.ini file and set the max_input_vars = 5000. After that the Error above disappeared, however we are still unable to save the translations and there is no error in the server console logs.
Is there anything we can do about this problem.
Answer: Try to increase  post_max_size value or disable the limit by setting it to 0


Who was the first motorsport driver to perform 'shoey' - drinking alcohol out of a shoe, on podium?

Question: Drinking beer out of one's own shoe is a ritual sometimes undertaken at parties and events in Australia, where it is referred to as a "shoey".
Jack Miller celebrated his maiden MotoGP victory by drinking from his boot during the podium ceremony of the Dutch Grand Prix in Assen.

Daniel Ricciardo has also performed shoeys on the podium (twice).

Valentino Rossi has also performed shoey for his 2nd place on San Marino GP.

So, my question is,
Who was the first motorsport driver to perform 'shoey' on podium?
Answer: The shoey made its way to major motorsport for the first time in 2015.
It all started with V8 Utes driver Ryal Harris, who performed the very first motorsport shoey at the Perth round of the series in 2015.

From goldcoastbulletin.com.au article,

"Yeah, I was definitely the first one to do it,".
"A couple of weeks before Perth I was on the beers with my mates and we were doing shoeys at my mate's house and I just said, 'If I get on the podium in Perth, I will do a shoey on the podium'."

But When V8 Supercar driver David Reynolds did a shoey after winning the second Saturday race at Darwin's Hidden Valley later that year, it got mainstreamed (at least in Australia).

After this Jack Miller, Daniel Ricciardo and Valentino Rossi have performed 'shoey' to make it a global phenomena.
References: carthrottle.com, foxsports and wheelsmag.com.au.

Who was the first motorsport driver to perform ‘shoey’ - drinking alcohol out of a shoe, on podium?


Laravel Notifications: Mail (Mailgun) Response on NotificationSent event

Question: I am using Mailgun as a mail driver in my laravel application, as well as nexmo for SMS purposes.
What I am trying to achieve is to maintain the delivery status of the notifications that are sent either via Mailgun or Nexmo. Incase of Nexmo I am able achieve this, since I get the nexmo MessageId in the NotificationSent event that is fired after processing a notification.
However in the event instance for email, the response is empty.
Any idea what I am missing or, how I can retrieve the mailgun message-id?
Answer: I have found a workaround that does the job for now. Not as neat as I want it to be, but posting for future references incase anyone needs this.
I have created a custom notification channel extending Illuminate\Notifications\Channels\MailChannel
class EmailChannel extends MailChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {

        if (! $notifiable->routeNotificationFor('mail')) {
            return;
        }

        $message = $notification->toMail($notifiable);

        if ($message instanceof Mailable) {
            return $message->send($this->mailer);
        }

        $this->mailer->send($message->view, $message->data(), function ($m) use ($notifiable, $notification, $message) {
            $recipients = empty($message->to) ? $notifiable->routeNotificationFor('mail') : $message->to;

            if (! empty($message->from)) {
                $m->from($message->from[0], isset($message->from[1]) ? $message->from[1] : null);
            }

            if (is_array($recipients)) {
                $m->bcc($recipients);
            } else {
                $m->to($recipients);
            }

            if ($message->cc) {
                $m->cc($message->cc);
            }

            if (! empty($message->replyTo)) {
                $m->replyTo($message->replyTo[0], isset($message->replyTo[1]) ? $message->replyTo[1] : null);
            }

            $m->subject($message->subject ?: Str::title(
                Str::snake(class_basename($notification), ' ')
            ));

            foreach ($message->attachments as $attachment) {
                $m->attach($attachment['file'], $attachment['options']);
            }

            foreach ($message->rawAttachments as $attachment) {
                $m->attachData($attachment['data'], $attachment['name'], $attachment['options']);
            }

            if (! is_null($message->priority)) {
                $m->setPriority($message->priority);
            }

            $message = $notification->getMessage(); // I have this method in my notification class which returns an eloquent model
            $message->email_id = $m->getSwiftMessage()->getId();
            $message->save();
        });
    }
}

I am still looking for a solution to achieve this with NotificationSent event.
Answer: When looking at the code (MailgunTransport)  it will do the following
    $this->client->post($this->url, $this->payload($message, $to));
    $this->sendPerformed($message);
    return $this->numberOfRecipients($message);

Since the Laravel contract requires the implementation to send back the number of e-mails send.
Even if you would be able to get into the mail transport it doesn't store the response from for this reason it not possible to catch the message id.
What you could do is to implement your own (or look in packagist) to adapt mail client but this is not a perfect solution and will require some ugly instanceof checks.
Comment: Thanks @ken, I actually worked it around by extending the MailChannel. Will be posting it as an answer in a bit.


Why is cardinality of reals not $\aleph_0 \cdot 2^{\aleph_0}$?

Question: The real numbers in the interval $[0,1]$ can be put in one-to-one correspondence with the (uncountable) power set of the natural numbers, $2^{\mathbb{N}}$, and from this we know that the real numbers are uncountable since every subset of a countable set is also countable. I have seen this proof also used to show that the cardinality of the real numbers is that of $2^{\mathbb{N}}$, however, what troubles me is that this leaves out the integer component of real numbers, which have cardinality $\aleph_0$. It would seem to me that if we take into account all real numbers we must take into account the cardinality of those in the interval $[0,1]$ and the integers, which would be the product of both cardinalities, $\aleph_0 \cdot 2^{\aleph_0}$. What am I misunderstanding here?
Comment: Why stop there? We have N_0 for the first digit and then from the second digit after the decimal 2^N_0 choices.
Answer: You are right that $|\mathbb R|=\aleph_0\cdot 2^{\aleph_0}$.
What you are missing is that $\aleph_0\cdot 2^{\aleph_0}$ is the same cardinality as $2^{\aleph_0}$ itself.
(Multiplication of infinite cardinal numbers behaves weirdly: Under the axiom of choice $\kappa\cdot\lambda=\max(\kappa,\lambda)$ for all infinite cardinals $\kappa$ and $\lambda$, and it may be weirder yet -- though not in the particular case of $\aleph_0\cdot 2^{\aleph_0}$ -- if we don't assume the axiom of choice).
Comment: Regarding the parenthetical paragraph, it may be worth pointing out that the equality $\aleph_02^{\aleph_0}=2^{\aleph_0}$ does not require the axiom of choice.
Comment: @AndrésE.Caicedo: Good point; I've tried to make it clearer.
Comment: Perfect answer, thank you! For reference, I am studying Szekeres' "Modern Mathematical Physics" and multiplication of infinite cardinals is not covered. Also, thanks to those who fixed up my MathJax.


Cannot get mouseover to work, don't understand JavaScript well enough

Question: I have looked on Google, and everywhere in the forums. Just learning JavaScript, so any help is appreciated. When I put .wav in the parameters it says error, don't know if that makes a difference anyway.
In the head:

In the body:

Okay, I found that yes the cellowav doesn't belong in the parameter, or the string and the sound will play automatically with the embed tag in html. I was missing the closing -"- in the string fixed that. Changed the functions parameters from (cellowav) to (soundfile) and in the string + cellowav + to

soundfile +.

Comment: Not to be rude, but if a website randomly plays a sound without visible cause, I close the tab and never go there again...
Comment: Well `embeded src` should be `embedded src`, for one.
Comment: You're currently getting `` or rather, you're not: I don't thing variables can contain dots.
Comment: @TheGuyOfDoom I think not even that, `cellowav.wav` is probably `undefined`
Comment: myeah, probably. I assume it'll try to use `cellowav` as an object, which it isn't
Answer: You're missing a " at the end of innerHTML=... in your function.
Furthermore you can't include cellowav.wav that way. You need to put in the url to the file there.
Should be looking something like this:

Comment: I think `"cellowav.wav"` is meant to be `"+ cellowav +"`
Comment: @ajax333221 Thanks for the hint. Edited the answer accordingly.
Comment: Thank you for such a quick response. I actually wrote the question out wrong i have it as embed in the code. I am confused, do i not put cellowav, or cellowave.wav in the ()parameter at all, and cellowav.wav is in the root folder. I tried cellowav in the string and still nothing.
Comment: Firefox says cellowav is undifined. so how do I get the function to call a .wav file? without putting in the cellow.wav. I have looked at sites that make a sound when you rollover a link, and that is what I am trying to accomplish. Thanks for the help.
Comment: @Rontonimo The call would be as you wrote in your question with just one change `playSound` is to be written with a capital `S` like in your function definition. If the wave file is present it should work then.
Answer: It's unclear what you're actually trying to do, but cellowav.wav doesn't need to be brought out of the string; it's a constant:
"<embeded src=\"cellowav.wav\" hidden=\"true\" loop=\"false\" />

Also, you're not closing your <embed> tag's string. Notice the last double quote here:
"<embeded src=\"cellowav.wav\" hidden=\"true\" loop=\"false\" />" // <-- Quote

You have also misspelled embed. You've written embeded instead.
"<embed src=\"cellowav.wav\" hidden=\"true\" loop=\"false\" />"

Comment: Thank you too for a very fast response. I just wrote embed wrong in question. cellowav.wav is in the root folder with the index.html file Thanks for the explanation on the closing parenthesis not used to the way javascript looks.


Export an inherited process in Devops via APIs

Question: I would like to export an inherited process in Devops via APIs. I found this API
But after calling this API, I recieve the following response:
<code>{
    "$id": "1",
    "innerException": null,
    "message": "The feature is disabled. Contact your Azure DevOps Server administrator.",
    "typeName": "Microsoft.TeamFoundation.Framework.Server.FeatureDisabledException, Microsoft.TeamFoundation.Framework.Server",
    "typeKey": "FeatureDisabledException",
    "errorCode": 0,
    "eventId": 3000
}
</code>
It sounds to me, to achieve this aim something should be enabled.
Does any one know what should I enable and in which place?
Answer: This feature is not available for the Inherited process. You may use it for On-premises XML process.
Available APIs for the inherited processes you may find here: Processes.


Why variables created with querySelector(All) are empty?

Question: In the Vue data object there are the following variables defined:
  data: function() {
    return {
      sails: document.querySelectorAll('.sail'),
      sailsGroup: document.getElementsByClassName("sail"),
      nameDisplay: document.querySelector('#name'),
      lines: document.getElementById("lines"),
      texts: document.getElementById("texts")
    }
  },
(...)

Then, there is this showData() method, in the very same Vue object:
showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},
(...)

When the method above is called from mounted() hook, it gives: ReferenceError: nameDisplay is not defined at VueComponent.showData. The error appears in case of nameDisplay and sails variables, so the ones assigned with document.querySelector(All) methods. Calling them with this only gives empty array/value.
Why is it so? How to define variables to have them accessible?
Comment: data is returning an object, and it looks like you're expecting variables called sails, sailsGroup to be defined instead of someObject.sails, someObject.sailsGroup, etc.
Comment: Please show your markup
Comment: Use `this.nameDisplay` instead of just `nameDisplay`.
Comment: @RoyJ: it gives "null" for nameDisplay and an empty array for sails.
Comment: @AbreQueVoy Are you calling `data()` before the DOM is loaded?
Comment: @Barmar: the DOM should have been loaded when "mounted()" hook gets triggered, right? Besides, all of the DOM elements are defined above the script location in my template.
Answer: showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},

This references variables in some outer scope. But if those are actually attributes you set up in data, then you need to use this.name instead:
showData() {
  console.log(this.sails);
  console.log(this.sailsGroup);
  console.log(this.nameDisplay);
  console.log(this.lines);
  console.log(this.texts);
},

Note that if those elements are elements that are inside the Vue component's template, then it's unlikely that you will find any elements since the component (and its data) is constructed before the component is actually mounted to the DOM. So the querySelectorAll calls run before the component is rendered.
In that case, you should either initialize the data later (once the component has been mounted), or use component refs instead.


Show that $x^{(k)} \not\to x$ in the $l_\infty$ norm

Question:
Given a fixed element $x\in l_1$, show that $x^{(k)} = (x_1,x_2,\ldots,x_k,0,0,\ldots,0)$ converges to $x$ in the $l_1$ norm. Show that $x^{(k)} \to x$ in the $l_2$ norm as well. Produce a counterexample to show that $x^{(k)}\not\to x$ in the $l_\infty$ norm.

I'm struggling with the last part, i.e. the counterexample. I am showing my work for the remaining parts:
$$y_k = \|x-x^{(k)}\|_1 = \sum_{i=k+1}^\infty |x_i - x^{(k)}_i|$$
and
$$z_k = \|x-x^{(k)}\|_2 = \left(\sum_{i=k+1}^\infty |x_i - x^{(k)}_i|^2 \right)^{1/2}$$
Clearly $y_k,z_k$ are decreasing and non-negative, so $y_k \stackrel{k\to\infty}{\longrightarrow} 0$ and $z_k \stackrel{k\to\infty}{\longrightarrow} 0$.
I don't know how to proceed in the $l_\infty$ norm case.
Thanks a lot!
Answer: hint: maybe you can get $x^{(k)}$ not to converge at all and therefore it especially can't converge to $x$.
possible solution:

Take $x = (1,1,1,\ldots) \in \ell^\infty$. Now
 \begin{align*} \|x^{(N)}-x^{(M)}\|_\infty = 1 \end{align*}
 for all $M,N \in \mathbb{N}$ with $M > N$. This means $x^{(k)}$ is not a cauchy sequence and therefore it cannot converge.

edit:
If you had $x=(x_n)_{n\in\mathbb N}\in\ell^{1}$ you would get $|x_n| \to 0$ as $n\to\infty$ and therefore
$$
\|x-x^{(k)}\|_\infty = \sup_{n\in\mathbb{N},\ n>k} |x_n| \to 0
$$
as $k\to\infty$ so you wouldn't be able to find a counterexample. Phrased in other words your statement also holds for the space $(c_0, \|\cdot\|_\infty)$ of sequences that converge to 0.
Regarding your proofs of the other statements: A real sequence being decreasing and non-negative isn't enough for convergence to 0 (take for example $1+\frac 1 n$), but I think you know that and just phrased it wrong. It probably becomes clearer if you just take a power:
$$
\|x-x^{(k)}\|_{\ell^p}^p = \sum_{n=k+1}^\infty |x_n|^p \to 0
$$
as $k\to\infty$ for $p\in [1,\infty[$.
Comment: Ohh, I see! So $x\in l_\infty$. I was thinking $x\in l_1$. Would my proof with the $l_2$ norm actually go wrong if I assume $x\in l_1$, by the way? I think now I understand that for each of the three cases I should have taken $x\in l_1,l_2,l_\infty$ respectively. Correct?
Comment: @strawberry-sunshine I added some more explanation. I don't see anything that would go wrong if you take $x\in\ell^1$ for your $\ell^2$ norm, but that probably isn't what you want to show...
Comment: @strawberry-sunshine another node to my last comment: one can show that $\ell^1 \subseteq \ell^2$, but for example $(\frac 1 n)_{n\in\mathbb N} \in \ell^2 \setminus \ell^1$, so taking $x\in\ell^1$ technically wouldn't suffice to prove it in all generality but the proof would stay the same anyways


ThreeJS: Create Triangle Strip

Question: I know this has been asked multiple times, but I can't seem to find the right answer for me.
Here is where I am: https://codepen.io/normanwink/pen/VXpbLj
I'm creating a grid according to window size and storing it in an array. Then I traverse through that array and try to create some kinda triangle mesh.
const gridSize = 50;

// some other code...

var gridX = Math.ceil(windowX / gridSize);
var gridY = Math.ceil(windowY / gridSize);

// render grid
for (var y = 0; y < gridY; y++) {
    var currentY = y * gridSize;
    grid[y] = [];

    for (var x = 0; x < gridX; x++) {
        var currentX = x * gridSize;
        grid[y].push(new THREE.Vector3(currentX, currentY, Math.random() * 100));
    }
}

// create triangle strip
for (var y = 0; y+1 < grid.length; y++) {
    var current = grid[y];

    for (var x = 0; x+1 < current.length; x++) {
        var arrayPosition = x + y;

        // triangle
        var v1 = grid[y][x];
        var v2 = grid[y+1][x];
        var v3 = grid[y][x+1];

        geom.vertices.push(v1);
        geom.vertices.push(v2);
        geom.vertices.push(v3);

        geom.faces.push( new THREE.Face3( arrayPosition, arrayPosition + 1, arrayPosition +2 ) );

    }
}

var obj = new THREE.Mesh( geom, material );
scene.add(obj);

This code is supposed to create the mesh. But for some reason I can't figure out, it just runs through the first Y coordinates and disregards the following grid points.
I believe the issue is somewhere inside the create triangle strip loop, but I can't find it. Can someone help out?
Thanks!
Answer: I think your var arrayPosition = x + y; is wrong.
I think you want something like ((y*current.length)+x)*3
Comment: I updated the Codepen. This is the right direction, but it's still wrong :D
Comment: Ahhh, wait! This was correct. I was wrong. Thank you!

ThreeJS: Create Triangle Strip


Setting Pointer References

Question: I have a rehash function for a hash table like so:
int hash_rehash(hash_table *ht) {
    list *l = hash_list(ht); // creates a linked list of hash table members
    hash_table *nht = hash_createTable(ht->buckets * 2, ht->maxLoad, ht->hash); // new hash table with 2x the buckets
    unsigned int i = 0;
    list_node *c = l->head;
    hash_destroyTable(ht); // destroy the old hash table
    for (; i < l->size; i++, c = c->next) {
        hash_insert(nht, c->data); // loop through linked list to re-insert old hash table members
    }
    *ht = *nht; // reference of old hash table = reference of new hash table?
    list_destroyList(l);
    return 0;
}

However if I destroy the old hash table I run into a SIGABRT error when reading out all the members of the new table because nht is using the same memory I allocated for ht. What's the correct way to change the old hash table ht to reference the new hash table nht?
Answer: Accept a hash_table ** instead of a hash_table *. Then if your caller has a hash_table *ht, they will call hash_rehash(&ht), allowing the function to modify ht.
Comment: does every function that calls hash_rehash also have to accept hash_table **?
Comment: @user2506293 depends how it's using it, but very possibly yes.

Setting Pointer References


React filter method without mutating state

Question: My current state has this:
state = { items : [{id: 1, text: 'test words'}, {id: 2, text: 'another test'}]

Here's my function to remove objects from the array, trying to avoid mutating state.
handleRemove(passedInId) {

  const myItems = this.state.items

  const newArray = myItems.filter(item => item.id !== passedInId)

  this.setState(prevState => ({
    items: prevState.items = newArray
  }))

  console.log('handle remove runned', passedInId, myItems, newArray)

}

It works perfectly but would like to know if it's not anti-pattern before moving on with my life
Many THANKS!!
Comment: is there a reason for calling `prevState` and not just doing `this.setState(items: newArray)`?
Comment: Not sure, does this.setState(items:newArray) avoid state mutations? The docs show lots of prevState stuff
Answer: Your function is almost right, and you have the right idea. You don't need to use the version of setState that takes a mutator function in your case, instead just do:
handleRemove(passedInId) {

  const myItems = this.state.items

  const newArray = myItems.filter(item => item.id !== passedInId)

  this.setState({
    items: newArray
  })

  console.log('handle remove runned', passedInId, myItems, newArray)

}

To be honest, this is simple enough that a one liner will do:
handleRemove(passedInId) {
  this.setState({items: this.state.items.filter(item => item.id !== passedInId)})
}

Comment: Thorough explanation...THANKS!
Answer: This is an anti-pattern. React handle state change and your object will not be mutated. This is what setState is for. I'm guessing that you don't want to update your state to avoid re-rendering your component. You can create a class variable and update it like you want without triggering a re-render. Something like this:
class MyComponent extends React.Component {
  constructor(props) {
    this.state = {};
    this.items = [{id: 1, text: 'test words'}, {id: 2, text: 'another test'}];
  }

  handleRemove(passedInId) {
    this.items = this.items.filter(item => item.id !== passedInId)
  }
}

Comment: I've never seen this pattern before. The pattern I typically see re: class variables is to use `this.someValue` in cases where you will need to attach a ref and almost nothing else. Mainly DOM-related references and never stateful stuff.

Generally I use the pattern from the accepted answer, but in a Redux context. That `filter` method would be written in an action and then used as the return value in a reducer.
Comment: You're totally right. I almost always use the pattern from the accepted answer too. But when reading the question, I thought the author wanted to filter the items without triggering any action or render. Also, base the question's code, you cannot tell if the filter is the app concern or the component concern, so you can't say the method will normally be handled by redux.
Comment: what do you mean by "React handle state change and your object will be mutated".  Thanks for your help!
Comment: Well, you object won't be mutated, but a new object is created each time. So doing an equal operator will never return true since it's a new object. But doing setState will never mutate your object.


How to use application config file in C#?

Question: I am trying to use a config file in my C# console application. I created the file within the project by going New --> Application Configuration File, and naming it myProjectName.config. My config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SSDirectory" value="D:\Documents and Settings\****\MyDocuments\****" />
</appSettings>
</configuration>

The code to access it looks like this:
private FileValidateUtil()
    {
        sSDirFilePath = ConfigurationSettings.AppSettings["SSDirectory"];
        if (sSDirFilePath == null)
            Console.WriteLine("config file not reading in.");
    }

Can anyone lend a hint as to why this is not working? (I am getting the error message.)
Thanks!!
badPanda
Comment: Sorry about that ambiguity everyone. When I mentioned an error message, I meant the console.writeline statement that said 'config file not reading in'

I apologize for the confusion.
Answer: You can't change the name from app.config and expect ConfigurationManager to find it without providing it more information.  Change the name of myProjectName.config back to app.config, rebuild, and you will see a file in the bin folder called myProjectName.exe.config.  Then your call to ConfigurationManager.AppSettings should work correctly.
Answer: check the documentation
http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
Answer: First off, use ConfigurationManager instead of ConfigurationSettings.
Second, instead of saying "doesn't work", which provides no useful information, tell us what you're seeing. Does it compile? Does it throw an exception at runtime? Does your PC start to smoke and smell like melting plastic?
Try this:
    public string GetSSDirectory()
    {
        string sSDirFilePath = string.Empty;

        if (!ConfigurationManager.AppSettings.AllKeys.Contains("SSDirectory"))
        {
            Console.WriteLine("AppSettings does not contain key  \"SSDirectory\"");
        }
        else
        {
            sSDirFilePath = ConfigurationManager.AppSettings["SSDirectory"];
            Console.WriteLine("AppSettings.SSDirectory = \"" + sSDirFilePath + "\"");
        }

        return sSDirFilePath;
    }

Comment: I actually did say that it was throwing the error message in the if statement, but thank you for your answer.


how to find the zero root of only one equation with two arguments by Newton-Raphson's method?

Question: The two dimensional Newton-Raphson method is to find a zero root $(x_0,y_0)$ which satisfy
\begin{array}{*{20}{c}}
  {f\left( {{x_0},{y_0}} \right) = 0} \\
  {g\left( {{x_0},{y_0}} \right) = 0}
\end{array} by iteration.
However, now I have only one equation $f(x,y)=0$ and I want to find its zero root $(x_0,y_0)$, what improvement should I do to the the Newton-Raphson method?
If I add another equation $g(x,y)=0$, then the determinant of Jacobian matrix will be zero and the inverting of the Jacobian matrix wouldn't exist.
Answer: $$
{\rm f}\left(\vec{r}\right)
+
\delta\vec{r}\cdot\nabla{\rm f}\left(\vec{r}\right) \approx 0
$$
$$
{\rm f} + \left(\delta x\quad\delta y\right){{\rm f}_{x} \choose {\rm f}_{y}} \approx
0
$$
$$
{\rm f}\left({\rm f}_{x}\quad{\rm f}_{y}\right)
+
\left(\delta x\quad\delta y\right)
\left({\rm f}_{x}^{2} + {\rm f}_{y}^{2}\right) \approx
0
$$
$$
\left(\delta x\quad\delta y\right)
\approx
-\,
{{\rm f}\left({\rm f}_{x}\quad{\rm f}_{y}\right)
 \over
\left({\rm f}_{x}^{2} + {\rm f}_{y}^{2}\right)}
$$
$$
\left\lbrace%
\begin{array}{rcl}
\delta x
& \approx &
-\,
{{\rm f}\left(\vec{r}\right)
 \over
 \left\lbrack{\partial{\rm f}\left(\vec{r}\right)\over\partial x}\right\rbrack^{2}
 +
 \left\lbrack{\partial{\rm f}\left(\vec{r}\right)\over\partial y}\right\rbrack^{2}
}\,
{\partial{\rm f}\left(\vec{r}\right)\over\partial x}
\\[3mm]
\delta y
& \approx &
-\,
{{\rm f}\left(\vec{r}\right)\,
 \over
 \left\lbrack{\partial{\rm f}\left(\vec{r}\right)\over\partial x}\right\rbrack^{2}
 +
 \left\lbrack{\partial{\rm f}\left(\vec{r}\right)\over\partial y}\right\rbrack^{2}
}\,
{\partial{\rm f}\left(\vec{r}\right)\over\partial y}
\end{array}\right.
$$
Equivalent to
$$
\delta\vec{r}
\approx
-\,{\nabla{\rm f}\left(\vec{r}\right)
 \over
 \left\vert\nabla{\rm f}\left(\vec{r}\right)\right\vert^{2}}
\,{\rm f}\left(\vec{r}\right)
$$


Absolute Risk more than 100%

Question: Is it possible for the absolute risk to be more than 100%?
I read the definition of absolute risk is the number of events (good or bad) in treated or control groups, divided by the number of people in that group.
So if one of the individuals in the group has numerous adverse events, couldn't this make the absolute risk more than 100%?
Answer: The absolute risk is the probability of an event happening to a person. It can never be more than 100%.
However, if an event can only happen once to a person then the absolute risk is the expected number of events that will happen to a person. If an event can happen more than once, then the risk is no longer the expected number of events.
If the risk is 100%, that implies it WILL happen (to each person). If it happens to me 10 times, and it happens to 9 people zero times, you can't say that it happened to everyone.

Absolute Risk more than 100%


With Chart js, I am trying to color every 7th vertical (x axis) grid line (representing each week beginning visually)

Question: The function(context) does not appear to be running, if I use an array it works, but trying to build this as a formula does not.  Feel like it is something basic as I am new to java.
xAxes: [{
        ticks: {
          stepSize: 1,
          min: 1, //minimum tick
          max: chartArray.length, //maximum tick
          beginAtZero: true,
        },
        gridLines: {
          color: function(context) {
          var index = context.dataset.data[index];
          return index %7 ? 'red' :  // draw every seventh line red
          'green';
        },
          lineWidth: 2,
        },
        display: true,
        type: 'linear',
        position: 'right',
      }]

Answer: This is not possible in V2, in the new upcomming release of V3 you can do this. You have to adjust your logic slightly to
 return context.index % 7 ? 'red' : 'green';

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      y: {
        gridLines: {
          color: (context) => {
            return context.index % 7 ? 'red' : // draw every seventh line red
              'green';
          },
          lineWidth: 2,
        },
        display: true,
        type: 'linear',
        position: 'right',
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

  <canvas id="chartJSContainer" width="600" height="400"></canvas>


Analytics on a PHP API

Question: I recently completed my first API in PHP. It is hosted at a public URL and accessed by a couple of my own mobile apps and websites. Based on a couple of parameters passed in, it pulls some data from my database and returns some JSON.
I would like to know some details about how often the API is accessed, and by what kind of clients.
Can I use google analytics for this? I have used it successfully on some websites in the same domain, but when I include the analytics php link and access the API, nothing is recorded.
Any gotchas I could be missing? Or is Google analytics only useable on web pages?
Answer: Google analytics isnt just for montiring websites, you can also use it to monitor mobile applications.
You might be able to monitor your API with the Measurement Protocol this should let you send info about the preformance of your api, and log the things you are talking about.
Note: I havent tried it but would love to hear from you if this works.

Analytics on a PHP API


Mapa mostrando local de procura swift

Question: Galera, gostaria de saber como posso fazer com que o meu mapa mostre o lugar que foi procurado e centre o view neste ponto. Consegui fazer com a localização atual da seguinte forma:
self.mapDisplay.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true) //Linha de seguir o mapa

Porém eu preciso com o resultado do endereço pesquisado, o que eu deveria usar?
Update 1:
Primeiro eu criei um Geocoder:
var geocoder = CLGeocoder()

Depois usei o método de buscar uma string de endereço e colocar na variável placemark. E usando as propriedades disponíveis nessa variável usei o placemark.location.coordinate.latitude e o placemark.location.coordinate.longitute:
 geocoder.geocodeAddressString(address,{(placemarks: [AnyObject]!, error: NSError!) -> Void in
                if let placemark = placemarks?[0] as? CLPlacemark {

 let location = CLLocationCoordinate2D(latitude: placemark.location.coordinate.latitude, longitude: placemark.location.coordinate.longitude)
                    self.mapView.region = MKCoordinateRegionMakeWithDistance(location, 350, 350)
                    self.mapView.centerCoordinate = location

}

Comment: Você já possui esse método de encontrar as coordenadas a partir do endereço ou é a partir daí que você precisa?
Comment: É a partir dai que eu preciso, eu não possuo o método.
Answer: Como fazer o mapa mostrar local de procura usando coordenadas sem api externo
Primeiro eu criei um Geocoder:
var geocoder = CLGeocoder()

Depois usei o método de buscar uma string de endereço e colocar na variável placemark. E usando as propriedades disponíveis nessa variável usei o
placemark.location.coordinate.latitude e o placemark.location.coordinate.longitute:

 geocoder.geocodeAddressString(address,{(placemarks: [AnyObject]!, error: NSError!) -> Void in
                if let placemark = placemarks?[0] as? CLPlacemark {

 let location = CLLocationCoordinate2D(latitude: placemark.location.coordinate.latitude, longitude: placemark.location.coordinate.longitude)
                    self.mapView.region = MKCoordinateRegionMakeWithDistance(location, 350, 350)
                    self.mapView.centerCoordinate = location

}

Comment: Se essa é a solução correta marque ela
Answer: Bom, como você precisa primeiro encontrar ainda as coordenadas, talvez a resposta seja um pouco ampla, mas resumindo, no próprio iOS não existe um método que você passe o endereço e ele te retorne latitude e longitude então você precisa primeiro buscar uma alternativa, como o Google Geocoding API.
Basicamente consiste em você passar um endereço e receber um JSON, que possui vários parâmetros e dentre eles a latitude e longitude. Por exemplo:
http://maps.googleapis.com/maps/api/geocode/json?address=Av+Paulista+4000,+Sao+Paulo,+SP&sensor=true

Se você acessar esse endereço vai encontrar os parâmetros que precisa e com eles em mãos (após fazer uma requisição com NSURLConnection e etc), para centralizar este ponto no mapa, crie o objeto CLLocationCoordinate2D, defina a região e então aponte o centro. Assim:
let location = CLLocationCoordinate2D(latitude: lat, longitude: lng)

mapDisplay.region = MKCoordinateRegionMakeWithDistance(location, 900, 900)
mapDisplay.centerCoordinate = location

Bom, é basicamente esse o caminho que você deve tomar. Se precisar de mais detalhes quanto à requisição, você pode fazer uma busca ou criar outra pergunta, acredito que já existem alguns bons exemplos com esse tipo de requisição de serviço.
Para colocar um marcador no mapa, é algo assim:
let annotation: MKPointAnnotation! = MKPointAnnotation()
annotation.coordinate = location

mapDisplay.addAnnotation(annotation)

Comment: Mas sem usar o googleapi qual seria o método caso eu tivesse as coordenadas?
Comment: Já com as coordenadas, é só usar esse código, onde `lat` e `lng` na primeira linha são os seus valores em double, que vai centralizar o mapa.
Comment: Consegui sem precisar o google api, irei demostrar meu procedimento quando eu editar a pergunta.
Comment: Tem razão, é possível mesmo obter as coordenadas sem utilizar serviço externo. Erro meu, sua solução é melhor mesmo.
Comment: Brigado, mas não seria possivel sem sua ajuda! Tem algum jeito de colocar agora um "alfinete" nessa cordenada?
Comment: Sim, bem simples. Fiz uma edição na minha resposta sobre como adicionar um marcador.
Comment: @Skal Você poderia postar sua solução para o geocoding como resposta, em vez de deixar na própria pergunta? É mais condizente com o formato do site, e deve ajudar outras pessoas com a mesma dúvida. Obrigado!

Mapa mostrando local de procura swift


If $f^{2}-3f+2id=0$, how to show that $E=\ker(f-id)\bigoplus \ker(f-2id)$?

Question: Suppose $E$ a vector space and f an endomorphism.  $f^{2}-3f+2id=0$, show that $E=\ker(f-id)\bigoplus \ker(f-2id)$.
My first approach was to take $y \in E$ and show that it is decomposed in such way:
$$y=x_{1}+x_{2}\:with\:x_{1}\in\:\ker(f-id)\:and\:x_{2}\in\:\ker(f-2id)$$
But didn't get far with this.
I attempted another approach that consisted in showing first that $\ker(f-id)\cap \ker(f-2id)= \left \{ 0 \right \}$, and then showing that the sum of dimensions of $\ker(f-2id)$ and $\ker(f-id)$ equals to the dimension of E. But I don't understand how I can find the dimension of $\ker(f-id)$, $\ker(f-2id)$ and of $E$ itself.
Any help will be appreciated.
Comment: Note that $(f - \operatorname{id})\circ (f - 2\operatorname{id}) = f^2 - 3f + 2\operatorname{id} = (f - 2\operatorname{id}) \circ (f - \operatorname{id})$.
Answer: Suppose $v\in E$ can be written as $v=x+y$, with $x\in\ker(f-\mathit{id})$ and $y\in\ker(f-2\mathit{id})$, so $f(x)=x$ and $f(y)=2y$.
Then $f(v)=f(x)+f(y)=x+2y$. Hence
$$
y=(x+2y)-(x+y)=f(v)-v
$$
so $x=v-y=2v-f(v)$. This tells us what $x$ and $y$ should be.
Now prove that, for all $v\in V$,
$$
2v-f(v)\in\ker(f-\mathit{id}),
\qquad
f(v)-v\in\ker(f-2\mathit{id})
$$
so
$$
v=(2v-f(v))+(f(v)-v)\in\ker(f-\mathit{id})+\ker(f-2\mathit{id})
$$
(Hint: $(f-\mathit{id})((f-2\mathit{id})=0=(f-2\mathit{id})(f-\mathit{id})$.)
Finally, try proving
$$
\ker(f-\mathit{id})\cap\ker(f-2\mathit{id})=\{0\}
$$

You cannot determine the dimensions of the kernels: the only conclusion you can draw is that their sum equals the dimension of $E$. Indeed, let $\{e_1,\dots,e_n\}$ be a basis for $E$ and, for $1\le k\le n$, define a linear map $f_k\colon E\to E$ by
$$
f_k(e_i)=\begin{cases}
e_i & \text{if $1\le i\le k$} \\[4px]
2e_i & \text{if $k<i\le n$}
\end{cases}
\quad(i=1,2,\dots,n)
$$
Then $f_k$ is a linear map satisfying $f_k^2-3f_k+2\mathit{id}=0$ and $\dim\ker(f-\mathit{id})=k$.
Comment: I think you ment I need to prove that for all $v \in V$, $f(v)-v \in \ker(f-2id)$, right?
Comment: @JohnMayne Yes, typo. Thanks.
Comment: I managed to do the booth proofs. In order to prove that $2v-f(v)\in\ker(f-id)$ I supposed that $v\in E$ and then by using the function, I managed to show that $f(2v -f(v))-(2v-f(v))=0$ thus $2v-f(v)\in\ker(f-id)$. I made the same approach for  $f(v)-v \in \ker(f-2id)$. To prove the $ \ker(f-id) \cap \ker(f-2id)=\left \{ 0 \right \}$, I simply assumed $x\in\ker(f-id) \cap \ker(f-2id)$ and showed that it's equal to $\left \{ 0 \right \}$. But I am still confused about what would look like the base of E? How do I determine that? How do I find the dimension of E?
Comment: @JohnMayne That's correct. I added a comment about the dimensions: they can be whatever, provided their sum is $\dim E$.
Comment: If I understood correctly I can choose $k$ whichever I want, unless I have some indication on the dim of E? And also, is the dimension of $\ker(f-id)$ necessarily equal to dimension of $\ker(f-2id)$? And finally, is there anything I can fish from this that would tell me something about the matrix of the application $f$?
Comment: @JohnMayne $k$ can be anything from $0$ to $\dim E$.
Answer: Hint: Does this remind you of the primary decomposition theorem? The proof of it's first part ($V = ker(f_1^{n_1})\bigoplus$$ker(f_2^{n_2})\bigoplus...\bigoplus$$ker(f_k^{n_k})$) doesn't use the fact that the polynomial under consideration is minimal. It only assumes that $f_1$,$f_2$,...,$f_i$ are co-prime and that f=$f_1^{n_1}*f_2^{n_2}*...*f_k^{n_k}$ annihilates T. So, you can use it's proof.


How to delay an observable in Angular 6 / Typescript

Question: I have the following method GetCurrentUserDelayedTest that i wanted to put a delay on. I have left the original implementation here GetCurrentUser to demonstrate how i was originally using it:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { User } from '../models/user';

export class UserService {

    // Normal method without delay
    public GetCurrentUser(): Observable<User>
    {
        return of(new User(""));
    }

    // Method with delay attempt at code
    public GetCurrentUserDelayedTest(): Observable<User>
    {
        var observable = new Observable<User>((observable) => {
            setTimeout(() => {
                return observable.complete();
            }, 2000);
        });

        observable.subscribe(() => {
            return of(new User(""));
        });

        return observable;
    }
}

I'm trying to delay the method from returning its data by 2 seconds.
What am i doing wrong? I'm brand new to angular 6 and typescript.
I'm calling it like this:
this.userService.GetCurrentUserDelayedTest()
    .subscribe((currentUser) => {
        this.loadingGameState = false;
    });

The "Loading App" part remains on screen (no errors are thrown) rather than updating the view to show "Welcome"

Loading App

  Welcome

Edit:

Argument of type 'Promise' is not assignable to parameter of type 'OperatorFunction'.
  Type 'Promise' provides no match for the signature '(source: Observable): Observable'.
Answer: you can use delay function
public GetCurrentUserDelayedTest(): Observable<User>
{
    return of(new User(""))
       .pipe(delay(2000));
}

Comment: do you import `delay` from 'rxjs/operators'?
Comment: you can check this page http://reactivex.io/documentation/operators.html#categorized
Comment: Argument of type 'Promise' is not assignable to parameter of type 'OperatorFunction'.
  Type 'Promise' provides no match for the signature '(source: Observable): Observable'.
Comment: I don't seem to have that choice in my import quick actions (VsCode)
Comment: Ah, well... adding it works, thanks man. where can i find out how to do this thing in the future? is there source for this, i struggled to find such a thing :)
Answer: A more detailed example using HttpClient:
of(null).pipe(
  delay(2000),
  flatMap(() => {
    return this.http.post<any>(url, params);
  })
);

Answer: https://stackblitz.com/edit/angular-mznw5m?file=src%2Fapp%2Fuser.service.ts
Use in the declaration of the Observable observable.next() so you can trigger the subscribers.
Comment: Ahhh, good to know what was wrong with my initial implementation. Thanks!
Comment: the link is broken


Why isn't this java code working?! Generic Stack

Question: I am new to Generics in java and I really need help in this code
it is not compiling i dont know why!
The stack class is:
 public class GenericStack<Item>{
    public class Stack {

        private Node first=null;

        private class Node {
            Item item;
            Node next;
        }

        public boolean IsEmpty()
        {
            return first==null;
        }

        public void push (Item item)
        {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
        }

        public Item pop ()
        {
            Item item=first.item;
            first=first.next;
            return item;
        }
    }
}

and here is the main
public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    GenericStack<Integer> ob = new GenericStack<Integer>();
    ob.push(5);
    obpush(10);
    ob.push(15);
    while (!ob.IsEmpty())
    {
        int x=ob.pop();
        StdOut.print(x);
    }

  }
}

now the error is:
  The method push(int) isn't defined for the type GenericStack<Integer>

Where did i go wrong?! can anyone explain please to me
Thank you in advance
Comment: `GenericStack` doesn't have the method `push`, only the nested class `Stack` has it.
Comment: Because there is no method which accepts int argument ie push(int).
Comment: I think you are thinking about [Autoboxing](http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html)
Answer: Your GenericStack class has no methods. Get rid of the nested class structure and use the generic type parameter for Stack directly:
public class Stack<Item> {

    private Node first=null;

    private class Node {
        Item item;
        Node next;
    }

    public boolean IsEmpty()
    {
        return first==null;
    }

    public void push (Item item)
    {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }

    public Item pop ()
    {
        Item item=first.item;
        first=first.next;
        return item;
    }
}

Answer: Because method push is defined in class GenericStack.Stack, not GenericStack.  To make it work replace
GenericStack<Integer> ob = new GenericStack<Integer> ();

with
GenericStack<Integer>.Stack ob = new GenericStack.Stack ();

Comment: Since it is not a static inner class you need to have a live instance of the enclosing class. so that your second statement should be GenericStack.Stack st=outerClassObject.new Stack();
Answer: The main issue with your code is that you mixed 2 public classes, just changed a little your code, have fun !!
GenericStack.java
public class GenericStack<Item> {

    private Node first = null;

    private class Node {
        Item item;
        Node next;
    }

    public boolean IsEmpty() {
        return first == null;
    }

    public void push(Item item) {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }

    public Item pop() {
        Item item = first.item;
        first = first.next;
        return item;
    }

}

TestGenericStack.java
public class TestGenericStack {

    public static void main(String[] args) {

        GenericStack<Integer> ob = new GenericStack<Integer>();
        ob.push(5);
        ob.push(10);
        ob.push(15);
        while (!ob.IsEmpty()) {
            int x = ob.pop();
            System.out.println(x);
        }

    }
}

Answer: class GenericStack<Item>{
    class Stack {

        private Node first=null;

        private class Node {
            Item item;
            Node next;
        }

        public boolean IsEmpty()
        {
            return first==null;
        }

        public void push (Item item)
        {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
        }

        public Item pop ()
        {
            Item item=first.item;
            first=first.next;
            return item;
        }
    }
}

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    GenericStack<Integer> ob = new GenericStack<Integer>();
    GenericStack<Integer>.Stack st=ob.new Stack();
    st.push(5);
    st.push(10);
    st.push(15);
    while (!st.IsEmpty())
    {
        int x=st.pop();
//        StdOut.print(x);
        System.out.println(x);
    }

  }
}

You are calling methods of the inner class. So that using object of outer class you cannot directly call the methods of the inner class. See above code for that.
Hope this helps.
Answer: Get rid of the extra coating of class Stack from GenericStack.
Thanks!
Comment: This is unnecessary. There is such a thing as [autoboxing](http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html) in Java, after all.
Comment: Not only is it unnecessary but it's also a waste of memory. `new Integer(5)` creates a new object while `Integer.valueOf(5)` or just `5` both allow for reuse of an existing instance of `Integer`.


Twitter Bootstrap 4 navbar-toggleable-*

Question: Given the code below is the supposed behavior that the button is hidden at lg and xl; while the collapsed content is only toggeable at md or is it toggeable from md downto xs?  Can someone help explain this?

  <button class="navbar-toggler hidden-lg-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2">
    ☰
  </button>

    Responsive navbar

        Home (current)

        Features

        Pricing

        About

Comment: Alpha software. It's liable to be broken.
Answer: It becomes toggleable at medium and is from medium down.
The navbar-toggleable-* means that *from * down it is able to be toggled*.
I have been working with this today, and that is the behavior that I have seen and is described in bootstrap docs
Answer: Used navbar-expand- This means it always in collapsed mode

Twitter Bootstrap 4 navbar-toggleable-*


foreach loop with SelectSingleNode always returns the first node

Question: I am trying to get the inner text of each domain node from an httpxml response.
I save the response to a string and load to XmlDocument. But using the code below or variations of it I either get "CorpDomainMyDomain aaaa" or just "CorpDomain aaaa".
I have tried various iterations of domain and domains and cannot get the domains individually.
I would have thought that
XmlNodeList elemList = xmlDoc.SelectNodes("//DAV:domains", nsmgr);

would have created a list of each of the Domain elements but it doesn't seem that way.
The xml:
<?xml version="1.0" encoding="UTF-8" ?>
  <multistatus xmlns="DAV:">
   <response>

    <propstat>
        <prop>
            <domains>
                <domain logindefault="1" type="internal"><![CDATA[CorpDomain]]></domain>
                <domain type="internal"><![CDATA[MyDomain]]></domain>
            </domains>
        </prop>
    <status>HTTP/1.1 200 OK</status>
    </propstat>
</response>

My code snippet
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("DAV", "DAV:");
XmlNodeList elemList = xmlDoc.SelectNodes("//DAV:domains", nsmgr);

foreach (XmlNode node in elemList)
{
  strNode = node.SelectSingleNode("//DAV:domains", nsmgr).InnerText;
  responseString = strNode+" aaaa  ";
}

return responseString;

Comment: For clarity, what *exactly* is your expected output?
Comment: The expected output is CorpDomain aaaa MyDomain aaaa – at the end of the day I will be putting CorpDomain and MyDomain into a Combobox drop down on my main form. Currently just looking at getting the individual items
Comment: I could be going blind, but it appears that you are replacing the entire `responseString` on each iteration through the loop: `responseString = strNode+" aaaa  ";`. Are you sure you didn't mean e.g. `responseString = responseString + strNode + ...;`?
Comment: You are correct that I was over wrting the string. responseString += resolved it. This is just for the quick test. Final will be something like conbobox.Add.Item(responseString)
Comment: Glad you got that resolved. Voting to close as off-topic (typo). You may also want to refer to https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ if you come across a similar issue in the future.
Comment: @IainGalloway Hi Iain - even if the OP does fix the typo you've mentioned, his use of XPath to parse his document is incorrect, and results in the concatenated (and repeated, once the typo is fixed) output of `CorpDomainMyDomain aaaa`. I've clarified this in my answer - i.e. no, please don't close as a typo - incorrect root level pathing in a loop is a common issue in Xml document parsing and this might be of use to future readers.
Answer: (Even after you've fixed the responseString += strNode issue that Ian picked up on, When you loop through the domain elements under the domains parent, you shouldn't again use // - that will reset the context to the root of the document.
e.g. if your XmlDocument looks like:
<?xml version="1.0" encoding="UTF-8" ?>
  <multistatus xmlns="DAV:">
   <response>
    <propstat>
        <prop>
            <domains>
                <domain logindefault="1" type="internal">domains1-domain1</domain>
                <domain type="internal">domains1-domain2</domain>
            </domains>
        </prop>
        <prop>
            <domains>
                <domain logindefault="1" type="internal">domains2-domain1</domain>
                <domain type="internal">domains2-domain2</domain>
            </domains>
        </prop>
       <status>HTTP/1.1 200 OK</status>
    </propstat>
   </response>
</multistatus>

your code would in fact scrape the combined text nodes of all child nodes of just the first domains element, i.e. something like (where aaaa is your delimiter):

domains1-domain1 aaaa domains1-domain2 aaaa

Instead, you should just provide the relative pathing from parent to child, i.e. just domain in your case. Assuming that there are N domains parent elements each with M domain child elements, if you stop at the parent nodes, you will need a second level of iteration through the child nodes:
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("DAV", "DAV:");
XmlNodeList elemList = xmlDoc.SelectNodes("//DAV:domains", nsmgr);
foreach (var domains in elemList)
{
    foreach (var domain in domains.SelectNodes("DAV:domain", nsmgr))
    {
       strNode = domain.InnerText;
       responseString = strNode+" aaaa  ";
    }
}
return responseString;

But if you don't need to retain a reference to the parent for other purposes, you could also do this in one step by flattening out the child nodes directly. For large xml documents with many nodes, it would also be a good idea to avoid the string concatenation problem, e.g. with a StringBuilder:
var sb = new StringBuilder();
foreach (XmlNode node in xmlDoc.SelectNodes("//DAV:domains/DAV:domain", nsmgr))
{
    var strNode = node.InnerText;
    sb.Append(strNode); // do the same for delimiter
}
// use sb.ToString() here.

Comment: Thank you, I have gone with the 2nd approach for now. Now onto understanding more about LING to XML for reading bits of a 5000 line dirty XML file and extracting some of the childnodes of the parent node based on a known child node element.
Comment: Sorry but I had tried that and it only returnsthe first domain node not the 2nd. result is
CorpDomain aaaa
Comment: For the 2nd example not using sb the result is
MyDomain aaaa so this is writing the 2nd node but not the first or it may be overwriting the first will test that further.
Comment: @Hammertime apologies - I wasn't paying enough attention to detail in my first answer - it would have continually selected the first child `domain` in each `domains` tree. I've fixed. The second approach should work irrespective - just make sure you're initializing the StringBuilder outside of the loops.
Comment: In the 2nd approach, you can go directly to `//DAV:domain`, provided there aren't any other elements named `domain` underneath different parents which you need to exclude.


Using both domain users and local users for Squid authentication?

Question: I'm working on a Squid proxy which needs to authenticate users against an Active Directory domain; this works fine, Samba was correctly set up and Squid authenticates users via ntlm_auth. Relevant lines in squid.conf:
auth_param ntlm program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp
auth_param ntlm children 5
auth_param ntlm keep_alive on
acl Authenticated proxy_auth REQUIRED
http_access allow Authenticated
http_access deny all

Now, I need a way to allow access to users which don't have a domain account. I know I could create an "internet user" account in the domain, but this would allow access, although limited, to domain resources (file shares, etc.); I need something that will allow only Internet access.
The ideal solution would be using a local account on the proxy server, either a Linux account or a Squid one; I know Squid supports this, but I'm unable to have it use both domain authentication and Squid/local authentication if domain auth is unsuccesful.
Can this be done? How?
Answer:
Now, I need a way to allow access to users which don't have a domain account.  Can this be done?

Yes.

How?

You can use an "external" ACL helper, which allows you to roll your own mechanism.  See the Squid wiki "Multiple Source" entry for more details.  This bit of pseudo-code lifted straight from there:
auth_param basic program /usr/local/bin/my-auth.pl
external_acl_type myAclType %SRC %LOGIN %{Proxy-Authorization} /usr/local/bin/my-acl.pl
acl MyAcl external myAclType
http_access allow MyAcl

... where my-auth.pl is a bit of perl script that performs the actual authentication, and returns OK or ERR as the result.
Comment: I had actually thouthg about this... but I'd like to know if there was some built-in way to do it.
Comment: There are several helper modules in `/usr/lib/squid` (or `/usr/lib64/squid` for 64-bit) that may be of interest to you.  Unfortunately, the one that looked to be most promising - `squid_unix_group` - requires that you not be using shadow passwords, which I'm assuming at this point you probably are (most installations do this out-of-the-box).  If you have an LDAP install separate from AD, `squid_ldap_auth` might be promising too.
Answer: create a restricted domain user (isolated OU). from squid, create a squid ldap auth that will allow the user to use internet.


How to grab text from .odt file

Question: I need to grab all text from odf files (open document format) in C#. I found AODL library, and installed it.
I visited AODL's page https://wiki.openoffice.org to find examples on how to do the task I need, but they were all unsuccessful. For a reason that I can't imagine, all examples build new document, and there's no example in how to load a document and grab all the text (something like OpenXML). Do you guys know any reference that can guide me?
My "try"
var doc = new AODL.Document.TextDocuments.TextDocument();
        doc.Load(@"C:\path/to/Sample.odt");

But I can't figure out how to iterate with the doc document.
Comment: If you're struggling getting access to your .odt file, you could save your file as a .docx first, then use a Word lib to read it.
Comment: You don't really need a library. Just save the file as .docx in OpenOffice.
Comment: Have you considered using the Novacode DocX Library? I have used this in the past to create or manipulate word documents. Here is a link for it on codeplex:

https://docx.codeplex.com/
Comment: I need it to read odf (open office) files, and I think DocX just reads .docx files
Comment: Do you know a library that converts from odt to docx or doc or rtf?
Comment: Well, it seems that AODL library can export to html. It's just a work around and I can survive with this for the next days. Still, I'd still want to open the odf files. It can't be hard, is just open source!
Comment: I'm doing the operations in real time. This is my site https://www.kennistranslations.com/wordcount. Users upload documents, I read them and grab all the text and then I perform a wordcount, so I'm not using any external executable programs.
Answer: Finally, I figured out. This is the method I created to extract all the text. Maybe is not complete, because I don't know all the parts that form the .odt file. This method grabs headers and footers, textboxes and paragraphs and concatenate it with return carriage separator. You need the AODL package, that can be installed through package manager console: PM> Install-Package AODL. And add
using AODL.Document.TextDocuments;
using AODL.Document.Content;

at the top of your program.
///
    /// Gets all plain text from an .odt file
    ///
    /// <param name="path">
    /// the physical path of the file
    /// </param>
    /// <returns>a string with all text content</returns>
    public String GetTextFromOdt(String path)
    {
        var sb = new StringBuilder();
        using (var doc = new TextDocument())
        {
            doc.Load(path);

            //The header and footer are in the DocumentStyles part. Grab the XML of this part
            XElement stylesPart = XElement.Parse(doc.DocumentStyles.Styles.OuterXml);
            //Take all headers and footers text, concatenated with return carriage
            string stylesText = string.Join("\r\n", stylesPart.Descendants().Where(x => x.Name.LocalName == "header" || x.Name.LocalName == "footer").Select(y => y.Value));

            //Main content
            var mainPart = doc.Content.Cast<IContent>();
            var mainText = String.Join("\r\n", mainPart.Select(x => x.Node.InnerText));

            //Append both text variables
            sb.Append(stylesText + "\r\n");
            sb.Append(mainText);
        }

        return sb.ToString();
    }

How to grab text from .odt file


How to add text over a overlapping div tag

Question: I like to add a div tag overlapping a div tag and add a text over the overlapped div tag. here is the code. . please help.
.center_prod_box{
     border-radius: 15px;
     width:190px;
     height: 260px;
     float:left;
     text-align:center;
     padding:0px 0px 5px; 0;
     margin:0px 5px 0px 0;
     border:1px #000000 solid;
}

 .product_title{
     background:#cdf895;
     border-radius: 15px;
     textalign:center;
     font-size:12px;
     margin: 7px 5px;
     font-weight:bold;
     color:#ffffff;
     padding:5px 5px 5px 15px;
  }

Hello

          Amul Butter

Answer: For that you can use position: absolute; for the overlapping div. And add any text to that div.
That will be something like this:

  The text to be added, will be written here! :)

You can use class or id to style them! In your image, you are using position: absolute; for image tag too. Use either position: relative; if you want to place the text on that image. Or you can use z-index for them, to place them one on other!
Edit: Text align is a bug in IE7: http://haslayout.net/css/Text-Align-Bug
Comment: ya Afzaal. . .But the text aligned differs in IE7 and firefox/chrome
Answer: You want to place the div with class offertext somewhere else on the page? Also, it's better to get rid of all your inline css and the last
 is one too many.
Comment: ya sure. . .Joris the text in the overlapped div is mis aligned in ie7 which differs from chrome/firefox