Chamando função delete no botão com onclick

Question: Quero aperta o botão APAGAR e exclui X dados do banco de dados
esse é o meu tipo_produto.php
<?php require("header.php"); ?>
<?php require("menu.php"); ?>

<?php
require ("model/tipo_itens.php");
$modTipoItens = new TipoItens();
$registros = $modTipoItens->getAll();

?>

Categorias

         <button type="button" class="btn btn-success" onclick="window.location.href='tipo_produto_novo.php'">Nova Categoria</button>

                    #	 Nome	 Descrição

                <?php foreach ($registros as $registro) { ?>

                        <?php echo $registro['id_tipo']; ?>	 <?php echo $registro['nome']; ?>	 <?php echo $registro['descricao']; ?>

                            <button type="button" onclick="editar(<?php echo $registro['id_tipo']; ?>)" class="btn btn-primary">Editar</button>
                            <button type="button" onclick="delete(<?php echo $registro['id_tipo']; ?>" class="btn btn-danger">Apagar</button>

                <?php } ?>

<?php require("footer.php"); ?>

Quando eu clicar no button APAGAR, quero excluir o item selecionado pelo ID.
esse é o meu controller tipo_itens.php
<?php
require ("../model/tipo_itens.php");
call_user_func($_GET['acao']);

function inserir(){
    $modTipoItens = new TipoItens();
    $resultado = $modTipoItens->inserir($_POST);
    header('Location: /exemplo/tipo_produto.php');
    exit;
}

function editar(){
    $modTipoItens = new TipoItens();
    $resultado = $modTipoItens->editar($_POST);
    header('Location: /exemplo/tipo_produto.php');
    exit;
}

function delete(){
    $modTipoItens = new TipoItens();
    $resultado = $modTipoItens->delete($_POST);
    header('Location: /exemplo/tipo_produto.php');
}

?>

e essa é a minha função delete no model tipo_itens.php
   function delete($id){
      $conexao = mysqli_connect('localhost','root', '', 'estoque');
      $id = (int) $id;
      $result = mysqli_query($conexao,"delete from tipo_itens where id_tipo= ".$id);
      return $result;
   }

Não to conseguindo enviar o parametro do ID quando clico no botão e executar a função delete do meu model/tipo_itens.php
Comment: Experimente assim: Editar Apagar Indique que erro aparece se não der.
Answer: Vamos por partes. Há um erro de sintaxe aqui:
<button type="button" onclick="delete(<?php echo $registro['id_tipo']; ?>"
class="btn btn-danger">Apagar</button>

Pois falta fechar o parentese ()) em delete(<?php echo $registro['id_tipo']; ?>). Resolvendo isso ainda haverá um problema relacionado ao uso da palavra reservada delete. Isso pode ser resolvido mudando o nome da função de delete() para, por exemplo, remover().Então fica assim:
<button type="button" onclick="remover(<?php echo $registro['id_tipo']; ?>)"
class="btn btn-danger">Apagar</button>

Como você não colocou a implementação da função remover() (antigo delete()), imagino que também seja um dos problemas. Então, para enviar a variavel id passada para a função remover (usando o metodo post do http) é necessario (mais interessante) usar ajax. Uma forma nativa de fazer isso em javascript é utilizando a api fetch. Aplicando ao seu caso a implentação da função remover, usando a api fetch, ficaria assim:

Arquivo tipo_itens.php:
<?php
if(isset($_POST['id'])){
    echo 'Operação realizada com sucesso! Recebido id ' . $_POST['id']
        . ' usando a ação ' . $_GET['acao'];
}


How to tell the difference between a difficult passage and a lack of technical skill?

Question: I'm working through a piano study (Burgmuller Op. 109, "La Separation" if it matters).  I'm using this study to gain a better handle on large jumps in the LH and rapid chord changes.  I think it's done quite well, but there are a few short passages, about 2 bars, where I often make mistakes when trying to play at speed.  I can play through the passages if I'm going slower, and I know that it's just a matter of time before I get them down.
And therein lies the issue:  I like the piece, but it's not one of my favorites.   I really chose it for the technical skills it develops.  I feel as though the piece has served its purpose, and that I would probably get more out of moving on to another piece that has a similar focus.  However, I'm not sure if I can distinguish between: "These bars are just difficult" compared to "I lack the technical skills to play them properly".  If it's a technical problem, then I should stick with this piece until I master the technical skill, yes?  On the other hand, if it's just a difficult passage, then presumably getting it perfect won't really move me any closer to my goals.
If my goal is to be able to learn any piece faster, should I move on to another study to more fully challenge myself, or should I stick with this one until it's perfect?  Or, in other words: if I stick with this piece, will I essentially just be getting better at playing it, without much benefit to my general skill set?
Comment: 'Difficult' is relative and subjective. What you found difficult 5 yrs ago is not so for you now. Your technical ability has changed. So it's a 'difficult' question to give an answer to.
Comment: "This piece is difficult" and "I lack sufficient skill to play this piece" is really exactly the same thing. The point you should ask is: will continuing to practice these two particular bars really help me develop my jumping ability, or only these two particular chords?"
Comment: @MichaelStachowsky - I haven't seen anyone else mention it yet but it doesn't sound like you've explored the possibility of continuing to work on this piece while moving onto another. You don't have to work on a single piece at a time by any stretch. I'd recommend setting aside a little of your time to practice this passage during each session and choosing another piece to focus on more generally.  That way you can keep moving forward with something else while still developing the skill necessary to play this section at tempo. Working a couple pieces at once can actually be more constructive.
Comment: @MichaelStachowsky - Excellent.  I definitely believe in a diversity of study to best approach learning but it's important to do so properly so you don't spread yourself too thin and miss out on what you could learn.  I find that I often do better to have a couple pieces at a time. It seems to make me do better at each of them.  There's also a lot that has been studied about practicing away from your instrument through visualization, so it's worth a try to visualize yourself playing the difficult parts while you're away from the instrument.
Comment: You didn't say exactly which passages cause the trouble, but looking through the score I would guess they might be the places where you need to move *both* hands around the keyboard *independently*, rather than only one hand moving, or both moving in a synchronized manner. That is certainly a useful general skill - not something specific to just this study.
Comment: In fact yes. Somewhere around bar 8 or so is a rather abrupt set of chord changes in both hands. LH plays octaves so it's a bit simpler but even so
Comment: @Basstickler: that's what the plan is now.  I feel that I should continue to progress while also working on the sticky points (also in order to progress :-P) in order to avoid getting bored
Answer: If you can play "all the piece except for a short passages", then don't waste time playing the whole piece - just work on those passages!
Make up your own technical exercises based on just those passages - e.g. repeat them in different keys, or shifted up/down an octave, or whatever.
Saying "these bars are just difficult" is just a cop-out for "I don't have the skill to play them yet". And the cop-out won't improve your playing - but the tough question you have to face up to is, "Do I really want to improve, or do I just want a nice excuse for not being good enough to play this very well?" Only you can give an honest answer to that!
Comment: Paraphrasing Twyla Tharp in "The Creative Habit" (strongly recommended!) -  the average artist practices what they do well; the exceptional artist practices what they do badly.
Comment: A tough but absolutely true answer.  I think I needed that kick :-)
Comment: There's nothing *wrong* about saying "this piece is too difficult for me, but I still enjoy playing it badly" - so long as that is an honest description of the situation. Of course it's much easier for an "amateur" to take that position than for a "professional" - or an aspiring professional.
Comment: Good answer; it's only difficult because you lack the skills that would make it easy.  I do disagree slightly with your comment though -- continuing to play something poorly will lead to bad habits that are harder to break than to learn it properly out of the gate (and will affect your playing in future pieces as well).  Which is not an absolute "wrong" of course, but still harmful.  I'd suggest slowing it down until it can be played well, as slowly as necessary -- and if that is absurdly slow, it indicates a skill gap large enough that you'd want to find something easier to work on first.
Answer: Difficult and lack of technical skill are the same thing. Practice gives one better technical skill (maybe with some lessons to learn what and how to practice.) Last month's difficult passage becomes a pattern that can be read at sight next month.


What is this "┌─3─┐" notation called? What is the count?

Question:
I am trying to help my wife work out the naming of this notation. Its from the Doctor Who theme and is accompanied after some triplets for the trumpets
Measure is 4 beats, what is the count?
Answer: Those are simply triplets. Think of it as :

But with the first two triplets tied:

Which results in your notation:

(since two eighths equal one quarter).
If you wanted a more specific name for it, you could say 'a quarter and an eighth triplet'
These two notes are to be played on the count of one quarter (one beat if your time signature is 4/4)
Answer: This seems like  triplets where the second triplet beat is skipped. Just the first and third division of that triplet is played. it goes like this when dividing each beat in triplet :
<code>1     2
1 2 3 1 2 3
x   x x   x               (play something on each x's)
</code>
This rhythm is commonly used in blues and jazz music and is named "shuffle beat" in those musical genres contexts.


Autoindex cuts off end of directory path; workaround needed

Question: I'm trying to set up a sort of shared hosting with nginx where each user has a public_html directory. Requests to /~username are aliased to /home/domain-users/username/public_html. Problem is, I also want autoindexing enabled. With the config below added into a server block, requests to specific files like /~username/test.txt work fine; they are aliased to /home/domain-users/username/public_html/test.txt. However, when trying to request /~username or ~/username/, I get a 404 and /var/log/nginx/error.log reveals that autoindex is for some reason attempting to list files in /home/domain-users/username/public_htm (note the missing "l": the path is truncated.)
Since being able to access /~username without a trailing slash as a directory is not vital, I tried removing $public_html_path/ from the try_files directive. Then, even when requesting /~username/, autoindex is not called. Perhaps a literal trailing slash is required in try_files for autoindex to function.
# For requests to "/~username" without a trailing slash
set $public_html_path "";
# Lazy quantifier at the end allows processing requests to "~/username". We add the trailing slash later in try_files
location ~ ^\/\~(?<user_home_folder>[^\\n\/]+)(?<public_html_path>\/.*)?$ {
    alias /home/domain-users/$user_home_folder/public_html;
    autoindex on;
    try_files $public_html_path $public_html_path/ =404;
}

My research has yielded scant results, the closest being this StackOverflow question. Since this appears to be a bug in NGINX that's unlikely to be fixed (the last comment was well over a year ago) I'm looking for a workaround. Using the root directive instead of alias would be perfect, except then autoindex removes the critical /~username/ part of the URI, thinking that the files it lists are in the web root since, in a way, they are. Even hacky workarounds will be very much appreciated... Thanks!
Answer: When using alias with a regular expression location, you need to reconstruct the entire pathname in the alias value. See this document for details.
location ~ ^/~(?<user_home_folder>[^/]+)(?<public_html_path>/.*)?$ {
    alias /home/domain-users/$user_home_folder/public_html$public_html_path;
    autoindex on;
}

Using try_files and alias together can cause complications due to this issue. But, the default behaviour is virtually identical to the try_files statement in your question.
Comment: Amazing! I feel kinda dumb now...


Getting gpsd address for ntpd

Question: I'm working through some tutorials for setting ntpd clock from gpsd. The guides that I'm working from list adding something like this:
server 127.127.46.0
fudge 127.127.46.0 time1 0.0 time2 0.0 refid GPS

to /etc/ntp.conf however every tutorial seems to use a different ip e.g. 127.127.28.0 or 127.127.40.0 etc.
What do these addresses correspond to, and how can I find out the correct one to use?
Answer: It seems that the loopback ip-address range 127.127.0.0/16 is used by NTPD to represent drivers for specific clocks. The third octet is the number of the specific driver as found on the list of drivers here and should probably correspond to either your actual clock or to how you want to interact with gpsd.
The fourth octet is the "unit number", which was originally meant to be used in case there were multiple devices on a system supported by the same driver, although in some cases it gets used differently.
As far as I can tell no driver actually connects over TCP/IP to that loopback address, it appears a NTPD quirk to name/represent drivers as loopback ip-addresses.
The pseudo IP-address 127.127.28.0 therefore indicates a specific driver in NTPD, specifically driver 28, the shared memory driver SHM and is one way gpsd and ntpd can interact.
127.127.46.0 denotes a different driver, driver 46, the GPSD NG client driver a specific client driver to interact with gpsd.
Comment: Correct. The fourth octet is the "unit number", which was originally meant to be used in case there were multiple devices on a system supported by the same driver, although in some cases it gets used differently. In the case of driver 46, `127.127.46.`x instructs gpsd to open `/dev/gps`x, which serves the original purpose, but the high bit is overloaded for a special purpose.
Answer: All IPv4 addresses in the 127/8 netblock are reserved for host loopback. However, only 127.0.0.1 is commonly used.
RFC 5735, section 3.

127.0.0.0/8 - This block is assigned for use as the Internet host
loopback address.  A datagram sent by a higher-level protocol to an
address anywhere within this block loops back inside the host.  This
is ordinarily implemented using only 127.0.0.1/32 for loopback.  As
described in [RFC1122], Section 126.96.36.199, addresses within the entire
127.0.0.0/8 block do not legitimately appear on any network anywhere.
Having different addresses used for different purposes when all addresses end up in the same place is useful:

for traffic separation e.g. in firewall rules
for any services that do not support virtual hosting

Generally speaking, as long as your system routing tables are set up to allow for 127/8 as loopback, you can use any 127/8 address you want, as long as you are consistent on the server and client sides.

Getting gpsd address for ntpd


Is it possible for a piece of music to be in multiple keys at the same time?

Question: I was wondering if it is possible (would possibly sound good) to have a piece of music be using multiple keys simultaneously. For example having the melody use a different key to the harmony. Would this just sound awful or has it been done before?
Comment: Arguably, "Sweet Home Alabama" is in D or in G. Find the notes that would ruin the ambiguity — in the case of D and G, that would be F and F# — and either use neither or add in enough of both that it isn't clear. The fewer notes the scales have in common, the harder it would be to maintain ambiguity, I would guess.
Answer: This is possible - in its fully-fledged form it's called Polytonality. Plenty of examples on that page.
Another less extreme technique that is more common but could still be described as 'multiple keys at the same time' is modal mixture - using chords and notes from two different keys with the same tonic (e.g. using chords and notes from F minor and F major in the same piece).
It is also possible for a chord progression to be tonally 'ambiguous', neither quite in one key or another (perhaps having the listener hear hints towards more than one tonic).
Answer: It's a bit of a vague question, as most music can be seen to move from key to key. Example in key C, a piece may well modulate for a short time into, say, key Am, or key F. So, from that point of view, the answer's yes, multiple keys in one piece. Orchestral works are known to modulate into several keys other than their original from start to end.
But maybe that's not what you envisage. The Blues does this simultaneously. A piece in key A often contains notes from key A minor. It's the essence of Blues playing. As an aside, I sometimes get students to play a solo in key B♭ while I play in key C. It works o.k., as the B♭ and E♭ notes over C provide that Blues sound. As with even the diatonic notes, played in inappropriate places, they won't sound cohesive at best, good at worst.
On the same lines, a piece in, say, key A♭ major can move subtly into any mode of A♭ - A♭ Aeolian, A♭ Dorian. This entails retaining the same root but changing the feel by changing the other notes associated with that root.
Or, another ploy: keeping the same notes (as in C Ionian), but moving into D Dorian, F Lydian etc., a very common idea.
As far as playing an accompaniment in key A♭, and playing a melody in key B minor goes - well, in the hands of real musicians, it could work, but generally speaking, the results will be called cacophony - at least by myself.
Comment: This is a good answer but I'd say that if you force yourself into the western box you'll always come to this conclusion.  What about look at non-western music described in western terms?  That might not be fair but could yield example of music that seems to be in more than one key at the same time if for no other reason than the scale used covers two keys.
Answer: i sometimes solo "off the 5th" or "off the 4th" in pentatonic scales . example being (in key of A) you can play D major pent, E major pent, D blues pent or E blues pent against the A and sound "fresher" (or at least interestingly different) as well as the A major pent and A blues pent against the A. playing a step below the root is the same as playing "off the 5th" when playing a step below the A major pent scale (it puts you playing in the E blues scale). however, it sounds awful to my ear when i'm playing a step below the blues scale. you are then playing a flat 3rd, a flat 7th, a flat 9 and an augmented 5th. maybe jazz guys would gig it, but i don't much care for it. i'm just an old blues and rock picker
Answer: Check out Fanfare for St Edmundsbury by Benjamin Britten. Three trumpets, each playing in a different key. So clever.


Verificar o type com jquery

Question: Bom tenho dois botões em um formulário, sendo eles:
<button type='reset' onclick="history.back()">CANCELAR</button>
<button type='submit'>ok</button>

Tenho o seguinte jquery que identifica o clique no botão e envia o formulário:
$(document).ready(function () {
    $("button").click(function () {

            // Envia formulário
            $("form").submit();

    });
});

Preciso que o $("form").submit(); senha executado apenas quando o botão clicado for type='submit'.
é possível fazer isso com jquery?
Comment: Um botão `type='submit'` já faz submit do form. Parece-me que estás a usar jQuery sem necessidade? ou esta é uma versão reduzida do teu código?
Comment: Esta em uma versão reduzia.
Answer: Use um seletor de atributo:
$("button[type=submit]").click(function () {
   $("form").submit();
});

Comment: Só mais uma dúvida, como submeter apenas o formulário que o botão corresponde? Tenho algumas página que possui mais de um formulário, é possível fazer o botão identificar qual o formulário que ele esta e o enviar?
Comment: @HugoBorges por padrão um botão do tipo `submit` já submete o form em que está inscrito. Porém caso você queira fazer isso por jquery, podes fazer [**assim**](https://jsfiddle.net/nage574f/2/), usando o método [`closest`](https://api.jquery.com/closest/).
Comment: para vc entender melhor o que estou fazendo vou postar o código mais completo, https://jsfiddle.net/t5wmdkwp/5/ . Estou tentando fazer com que o botão fique desabilitado por 2 segundos. porém o `prop('disabled', true)` impede o envio do `form`, eu resolvo isso com o `$("form").submit()` só que o botão envia apenas o ulmo `form` sendo que ele tem que enviar o `form` que pertence ao botão. Entendeu melhor meu problema?
Comment: Bom o `closest.` resolveu o problema. Olha como ficou. https://jsfiddle.net/t5wmdkwp/9/ Mais uma vez, muito obrigado.
Answer: Acredito que alterando o tipo do botão de reset para button já seja o suficiente, o código ficaria desta maneira:
<type='button' onclick="history.back()">CANCELAR</button>

Comment: acho que vc não entendeu bem a pergunta.

Verificar o type com jquery


The expected value for a function of an exponential r.v X

Question: For an exponential r.v $X$  with parameter $\lambda >0$, I try to find the expected value of $e^{X/2}$.
I think this is possible through the moment generating function but I want to do it following the definition so
$$\mathbb{E} \left(e^{X/2}\right) = \lambda \int_0^{\infty} e^{x/2}e^{-\lambda x} dx=  \lambda \int_0^{\infty} e^{-\frac{x}{2}(2\lambda -1)} dx = \dots $$
Then how to continue and which constraints to consider?
Comment: $$ \int_0^\infty e^{-ax}dx = \begin{cases} \frac{1}{a} & ,\textrm{if }a >0 \\ +\infty&, \textrm{otherwise}\end{cases} $$
Comment: @ChargeShivers very clever, straight from the exponential pdf identity, very nice.
Answer: $$\mathbb{E}[e^{x}] = \lambda \int_{0}^{\infty} e^{-x(2\lambda - 1)/2} \mathop{dx} = \lambda\left(\frac{e^{-x(2\lambda - 1)/2}}{(1-2\lambda)/2}\right)\Big|_{0}^{\infty} =  \boxed{\frac{2}{2\lambda - 1}}$$
The constraints are $\lambda > 1/2$.
Comment: yes thank it is a normal integration! it is my mistake but anyway thanks a lot
Comment: Yup, just normal integration. There are no tricks here.


Gerando um arquivo que é saída de um comando apenas se uma condição for satisfeita

Question: Seja o comando:
top -o %MEM -b > file.txt

Gostaria que em file.txt só estivem os valores que estivem entre dois períodos de tempo, como por exemplo:
entre 07 de Abril de 2017 07h e 07 de Abril de 2017 12h. É possível? Desta forma, eu teria um arquivo apenas com as entradas que me interessam.
Gostaria de guardar num arquivo apenas as entradas que estiverem entre 07 de Abril de 2017 07h e 07 de Abril de 2017 12h!!!
Comment: `cat /var/log/apache.log /var/log/anaconda.log | grep jeff` só vai pegar as linhas que tenham `jeff`. Leia sobre `grep` e pipe
Comment: Não entendi sua pergunta. A condição é relacionada a algum valor emitido pelo `top`?
Comment: Nao! gostaria de guardar num arquivo apenas as entradas que estão entre 07 de Abril de 2017 07h e 07 de Abril de 2017 12h!!!
Comment: De onde você pega essa informação? Você quer rodar o script apenas nesses horários segundo o clock do computador?
Comment: seria um horario que eu informasse a ele. Poderia usar Unix time para facilitar. Poque top -o %MEM -b > file.txt gera muita coisa que não me interessa. Quero só a informação entre datas que eu informe!
Comment: É possível fazer isso?
Comment: Você quer fazer um agendamento, que não tem nada a ver com parâmetros de função. Achei essa fonte aqui em inglês que pode te ajudar: https://www.howtogeek.com/101288/how-to-schedule-tasks-on-linux-an-introduction-to-crontab-files/
Comment: nao! top -o %MEM -b > file.txt irá gerar um arquivo com o uso de memoria e CPU com inúmeros dias e horarios que nao me interessam! eu queria fatiar o arquivo antes de ser gerado para guardar apenas o intervalo acima!
Comment: Então a saída do `top` tem alguma informação relevante de data? Se tiver, por preguiça eu usaria um `grep ` para selecionar
Comment: Não entendi!Poderia dar exemplo?
Comment: O problema é que ele demora muito para gerar o arquivo. gostaria de dizer ao comando top que só guarde no arquivo entre os periodos que informei
Answer: Imagino eu que o grep não vá resolver nesse caso, porém você pode com shell script pegar linha por linha do conteúdo do top, daí vai de voce criar uma lógica para pegar a hora e comparar por exemplo:
suponhamos que a linha vem assim: drwxrwxrwx victor:victor hh:mm:ss nomeArquivo
isso é um exemplo apenas você poderia pegar essa linha e quebrar nos espaços, depois pegar o 3 elemento que seria hh:mm:ss e dai quebrar no ':' dai voce teria separado hora, minuto e segundo, depois disso voce poderia comparar a hora é igual ou maior que 07? ou a hora é menor ou igual a 11? e dai colocar essa linha no arquivo final, a lógica eu tenho certeza que funciona, porém estou enferrujado em shell script e não vou poder te fornecer o código :/
Answer: Não ficou completamente claro o que pretendes...
Obviamente não conseguimos analisar a memória usada no passado.
Comecemos por guardar o uso de memória
(com top) desde a atualidade até daqui a 2horas. Para tal sugeria
que:

definíssemos um intervalo de amostragem (exemplo 30 segundos)
definíssemos um número de amostras (120 * 60s /30s = 240)

top -o '%MEM' -d 30 -n 240 -b > file.txt
... analisar_e_limpar file.txt > resumo.txt

(top tem muitas opções que permitem esconder, acrescentar campos, etc).
Se pretendermos começar o registo algures no futuro, podemos usar a cron-tab ou usar o comando "esperar ..." : sleep ...; top ...
Comment: Usando `> file.txt ` voce vai sobrescrever o que tiver no arquivo e colocar o novo conteudo, usando `>> file.txt` voce vai concatenar o conteúdo novo com o que já está no arquivo
Comment: como seria com crontab? eu queria monitorar  e guardar, na proxima segunda, terça e quarta-feira de 07h às 15h
Comment: @EdS, procura os detalhes em `man 5 crontab` mas seria algo como editar a cron tab (`crontab -e`) e adiionar-lhe uma linha como `0 7 * * mon,tue,wen /home/EdS/script`  (não testado) em que escolhias a amostragem e quantidade pretendidas
Comment: Qual a diferença entre fazer > file.txt e >>file.txt ??


How to pass variables to a theme template file from EntityAPIController::buildContent()

Question: I may be going about this incorrectly, if so please point me in the right direction.
I currently have a custom entity type and I'm adding the display fields via a controller class that extends EntityAPIController. I want to attach some content from elsewhere (non-entities) to the display of this custom entity.
I have an implementation of hook_theme:
function module_theme($existing, $type, $theme, $path) {
  return [
    'module_plugin_instance' => [
    'template' => 'module-plugin-instance',
    'path' => $path . '/templates',
      'variables' => [
        'instance_id' => NULL,
      ],
    ],
  ];
}

Then, in EntityTypeController::buildContent() I have:
$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance'
];

Where I'm failing is I can't figure out how to pass variables to the theme template here.  The dummy html I'm putting in the template renders fine, just no variables.  I've tried several different things, but I can't seem to get $instance_id to my template - what am I doing wrong?
Answer: You can provide theme variables through properties, e.g.:
$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance',
  '#instance_id' => 'foo',
];


ExpressJS - Sequelize - Query Results Not Populated in Object

Question: I have a route set up that conducts the following sql query:
Executing (default): SELECT `id`, `pattern`, `color`, `imageUrl`, `imageSource` FROM `images` AS `images` WHERE `images`.`pattern` = 'solid' AND `images`.`color` = 'navy-blue';

which when tested on my local database works and provides results, but I can't seem to populate my image object to then be used within my view. I feel like I'm passing it as a function parameter in the wrong place, but I'm not sure and my console.log(image); is not coming back with a response.
router.get('/:pattern/:color/result', function(req, res, image){

    console.log(req.params.color);
    console.log(req.params.pattern);

    Images.findAll({
        where: {
            pattern: req.params.pattern,
            color: req.params.color
        },
        attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource']
    }),
        console.log(image);
        //console.log(doc.descriptions_id);
        res.render('pages/result.hbs', {
            pattern : req.params.pattern,
            color : req.params.color,
            image : image
        })
});

Here is my model:
var Sequelize      = require('sequelize');
var sequelize = new Sequelize('db', 'admin', 'test', {
    host: 'localhost',
    port: 3306,
    dialect: 'mysql'
});

var Images = sequelize.define('images', {
    pattern: {
        type: Sequelize.STRING,
        field: 'pattern'
    },
    color: {
        type: Sequelize.STRING,
        field: 'color'
    },
    imageUrl: {
        type: Sequelize.STRING,
        field: 'imageUrl'
    },
    imageSource: {
        type: Sequelize.STRING,
        field: 'imageSource'
    },
    description_id: {
        type: Sequelize.INTEGER,
        field: 'description_id'
    }
});

module.exports = Images;

Answer: You should use Promises
router.get('/:pattern/:color/result', function(req, res, image){
  console.log(req.params.color);
  console.log(req.params.pattern);

  Images.findAll({
    where: {
        pattern: req.params.pattern,
        color: req.params.color
    },
    attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource']
  }).then(function(image){
    console.log(image);
    //console.log(doc.descriptions_id);
    res.render('pages/result.hbs', {
        pattern : req.params.pattern,
        color : req.params.color,
        image : image
    })
  });
});


How to find derivative of softmax function for the purpose of gradient descent?

Question: I'm trying to understand back propagation algorithm for multiclass classification using gradient descent. I'm using https://www.cs.toronto.edu/~graves/phd.pdf . The output layer is a softmax layer, in which each unit in that layer has activation function:

Here, ak is the sum of inputs to unit 'k'.
Differentiating the above equation, the author has achieved this result.

I'm confused by the delta kk' and i have never seen anything like it.
Another question is do we consider  the summation while taking the derivative, why or why not?
https://math.stackexchange.com/questions/945871/derivative-of-softmax-loss-function is a bit relevant, but the result of differentiation is different.
Comment: https://en.wikipedia.org/wiki/Kronecker_delta.  Why not work it out for yourself in the case $K=2$? In a simpler notation with $x=a_1$ and $y=a_2$, find the $x$ and $y$ derivatives of $$\frac{e^x}{e^x+e^y}.$$ Then it will be obvious what the author means.
Comment: @She which book is this from?
Comment: @ToussaintLouverture here : https://www.cs.toronto.edu/~graves/phd.pdf
Answer: As whuber points out, $\delta_{ij}$ is the Kronecker delta https://en.wikipedia.org/wiki/Kronecker_delta :
$$
\begin{align}
\delta_{ij} = \begin{cases}
0\: \text{when } i \ne j \\
1 \: \text{when } i = j
\end{cases}
\end{align}
$$
... and remember that a softmax has multiple inputs, a vector of inputs; and also gives a vector output, where the length of the input and output vectors are identical.
Each of the values in the output vector will change if any of the input vector values change. So the output vector values are each a function of all the input vector value:
$$
y_{k'} = f_{k'}(a_1, a_2, a_3,\dots, a_K)
$$
where $k'$ is the index into the output vector, the vectors are of length $K$, and $f_{k'}$ is some function. So, the input vector is length $K$ and the output vector is length $K$, and both $k$ and $k'$ take values $\in \{1,2,3,...,K\}$.
When we differentiate $y_{k'}$, we differentiate partially with respect to each of the input vector values. So we will have:

$\frac{\partial y_{k'}}{\partial a_1}$
$\frac{\partial y_{k'}}{\partial a_2}$
etc ...

Rather than calculating individually for each $a_1$, $a_2$ etc, we'll just use $k$ to represent the 1,2,3, etc, ie we will calculate:
$$
\frac{\partial y_{k'}}{\partial a_k}
$$
...where:

$k \in \{1,2,3,\dots,K\}$ and
$k' \in \{1,2,3\dots K\}$

When we do this differentiation, eg see https://eli.thegreenplace.net/2016/the-softmax-function-and-its-derivative/ , the derivative will be:
$$
\frac{\partial y_{k'}}{\partial a_k} = \begin{cases}
y_k(1 - y_{k'}) &\text{when }k = k'\\
- y_k y_{k'} &\text{when }k \ne k'
\end{cases}
$$
We can then write this using the Kronecker delta, which is simply for notational convenience, to avoid having to write out the 'cases' statement each time.
Answer: The author's formula violates the Einstein convention, since repeated indices imply summation.
A better way to write the result is
$$
 \frac{\partial y}{\partial a} = {\rm Diag}(y) - yy^T
$$
where the Diag function creates a diagonal matrix by putting the vector $y$ along the main diagonal and zeros elsewhere.

If you wish to use the summation convention, you'll need to define a third-order tensor $T_{ijk}$ whose elements are equal to 1 when $i=j=k,\,$ and zero otherwise.
With this tensor you can write
$$
\frac{\partial y_i}{\partial a_j} = T_{ijk}\,y_k - y_i\,y_j
$$
where the repeated index $k$ is summed.
Answer: First thing to remember is that when you differentiate an ($n,1$) vector $y$ with respect to a ($n,1$) vector $a$, you get an ($n,n$) matrix, who's first column is the the differentiation w.r.t. $a_1$, 2nd w.r.t $a_2$ ... etc. all the way to $a_n$.
\begin{pmatrix}
 \frac{\partial y_1}{\partial a_1} & \frac{\partial y_1}{\partial a_2} & \frac{\partial y_1}{\partial a_3} & \cdots & \frac{\partial y_1}{\partial a_n} \\
 \frac{\partial y_2}{\partial a_1} & \frac{\partial y_2}{\partial a_2} &\frac{\partial y_2}{\partial a_3} & \cdots & \frac{\partial y_2}{\partial a_n} \\
 \vdots  & \vdots& \vdots & \ddots & \vdots \\
 \frac{\partial y_n}{\partial a_1} & \frac{\partial y_n}{\partial a_2} & \frac{\partial y_n}{\partial a_3} & \cdots & \frac{\partial y_n}{\partial a_n}
 \end{pmatrix}
Now, since $y_i = \frac{e^{a_i}}{\sum_je^{a_j}}$, let's see the general form of it's derivatives:
$$\frac{\partial y_i}{\partial a_i} = \frac{e^{a_i} \sum_je^{a_j} - e^{a_i}e^{a_i}}{(\sum_je^{a_j})^2} = \frac{e^{a_i}}{\sum_je^{a_j}} \frac{\sum_je^{a_j} - e^{a_i}}{\sum_je^{a_j}} = y_i(1-y_i) = y_i - y_i y_i\\
\frac{\partial y_i}{\partial a_k} = \frac{- e^{a_i}e^{a_k}}{(\sum_je^{a_j})^2} = -\frac{e^{a_i}}{\sum_je^{a_j}}\frac{e^{a_k}}{\sum_je^{a_j}} = -y_i y_k
$$
So, you can separate the matrix into 2 matrices:
$$ \left (
\begin{matrix}
  y_1 & 0 & 0 & \cdots & 0 \\
  0 & y_2 & 0 & \cdots & 0 \\
  \vdots  & \vdots& \vdots & \ddots & \vdots \\
  0 & 0 & 0 & \cdots & y_n
  \end{matrix} \right) -
\left (
\begin{matrix}
  y_1 y_1 & y_1 y_2 & y_1 y_3 & \cdots & y_1 y_n \\
  y_2 y_1 & y_2 y_2 & y_2 y_3 & \cdots & y_2 y_n \\
  \vdots  & \vdots& \vdots & \ddots & \vdots \\
  y_n y_1 & y_n y_2 & y_n y_3 & \cdots & y_n y_n
  \end{matrix} \right)
 $$
You can see that the first matrix correspond to the first term in your equation $y_k \delta_{k k'}$ and the end matrix correspond to the 2nd term $y_k y_{k'}$.
You can check this blog post for more information including graphs and code. And also this YouTube video I made which explains it.
Answer: This is the partial derivative of the softmax function $y_{k'}$ with respect to its activation $a_k$. Someone on this site has already written an excellent answer that explains the full evaluation of this derivative, just with slightly different notation:
Derivative of Softmax with respect to weights

I'm confused by the delta kk' and i have never seen anything like it.

As others have mentioned, the Kronecker delta function $\delta_{kk'}=1$ when the indices match (i.e. $k=k'$) and is $0$ elsewhere. It's a handy way to "select" only part of the multivariate input when performing derivatives over multiply-connected paths like a neural network.
Think of it almost like an if-else statement for a particular link. Also, it's not the only way you can represent this mathematically - some texts use an indicator function like $I[k=k']$ to represent the same logic.
In our case, the partial derivative of the specific activation $y_{k'}$ (indexed by $k'$) is not just with respect to any activation, but to the specific activation $a_k$ indexed by $k$. That's why a lot of the terms in the partial derivative are set to $0$ when $k \ne k'$, using the Kronecker delta.

Another question is do we consider the summation while taking the
  derivative, why or why not?

If I understand your question correctly - we do consider the summation in the denominator, $\sum_{k'=1}^K e^{a_k{k'}}$. The derivation I linked to above shows how that is done.

https://math.stackexchange.com/questions/945871/derivative-of-softmax-loss-function
  is a bit relevant, but the result of differentiation is different.

It is indeed related, but focusses on a different partial derivative. If you had a Loss function $L$ that is a function of your softmax output $y_{k'}$, then you could go one step further and evaluate this using the chain rule
$$\frac{\partial L}{\partial a_k} = \frac{\partial L}{\partial y_{k'}} \frac{\partial y_{k'}}{\partial a_k}$$
The last term in the above, $\frac{\partial y_{k'}}{\partial a_k}$, is what you are focussing on in your question, while the question you linked to is trying to evaluate $\frac{\partial L}{\partial a_k}$. So they are related but focussed on different terms.


How to Read and Write from the Serial Port

Question: I just started learning how to send and receive data from my hardware through the C# GUI.
Can anyone please write a detail how to read data from the serial port?
Comment: The other way around: the linked post is a duplicate of this one. Please use this question as the canonical duplicate.
Comment: possible duplicate of [Managing serial ports in C#](http://stackoverflow.com/questions/7275084/managing-serial-ports-in-c-sharp)
Answer: SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files.  It even covers the pin assignments on the port itself.
Example Code:
using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace SerialPortExample
{
  class SerialPortProgram
  {
    // Create the serial port with basic settings
    private SerialPort port = new SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One);

    [STAThread]
    static void Main(string[] args)
    {
      // Instatiate this class
      new SerialPortProgram();
    }

    private SerialPortProgram()
    {
      Console.WriteLine("Incoming Data:");

      // Attach a method to be called when there
      // is data waiting in the port's buffer
      port.DataReceived += new
        SerialDataReceivedEventHandler(port_DataReceived);

      // Begin communications
      port.Open();

      // Enter an application loop to keep this thread alive
      Application.Run();
    }

    private void port_DataReceived(object sender,
      SerialDataReceivedEventArgs e)
    {
      // Show all the incoming data in the port's buffer
      Console.WriteLine(port.ReadExisting());
    }
  }
}

Comment: Hi, I am trying the same but that event handler method does not get called!
Comment: @mrid Yes! I just Disconnected the device and had a cup of tea and then started! In other case it might be issue with the connector that you are using.
Comment: @PrashantPimpale were you able to resolve your issue ?
Answer: I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and
SerialPort.BaseStream-source for deep understanding.
I created and use code that shown below.

The core function
public int Recv(byte[] buffer, int maxLen)
has name and works like "well known" socket's recv().
It means that

in one hand it has timeout for no any data and throws TimeoutException.
In other hand, when any data has received,

it receives data either until maxLen bytes
or short timeout (theoretical 6 ms) in UART data flow

.
public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        ///
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        ///
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        ///
        /// Private property returning positive only Environment.TickCount
        ///
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }

        ///
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data,
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout.
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes,
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception
        ///
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property,
            /// the routine throws TimeoutException
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout;
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0;
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0)
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {
                throw new TimeoutException();
            }
            else
            {
                return totalReceived;
            }
        } // Recv()
    } // Uart

Comment: Yep, especially ReadAsync is much more convenient.
Answer: Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.
Moreover, you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:
var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needed abstract methods and
// overrides needed virtual methods.
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information:

Top 5 SerialPort Tips article by Kim Hamilton, BCL Team Blog
C# await event and timeout in serial port communication discussion on StackOverflow


Reliable alternative to waitfor() in Perl

Question: Here is the snippet of my script which will wait for string "username: " and print the username to login, huge chunk of boot-up message gets printed before "username: " appears, sometimes the script is missing to find the it and returning saying "Failed to find username:", especially when some spilled over boot-up messages get printed after "username: " prompt line, so is there a more reliable way to do this? Thanks.
my %words = (
   username => 'user1',
   username_string => 'username: $',
);
( $prematch, $match ) = $obj->{comm}->waitfor(Match => "/$words{username_string}/",Errmode => "return");
if ( !defined $match ) {
    print "Failed to find username:";
    return;
}
else {
  $obj->{comm}->print( $words{username} );
}

$obj is an object of Net::Telnet
Comment: waitfor() is obviously a method for some Class.  Helping you would be easier if we knew which Class that was...
Comment: Looks like it comes from [`Net::Telnet`](https://metacpan.org/pod/Net::Telnet)
Comment: yes, sorry, it comes from NET::Telnet, I am still understanding the script which I am updating.
Answer: in fact i do not know which kind of object is related to your $obj. assuming it could be Net::Telnet maybe this could help you:
perl-telnet-does-not-wait-for-the-end-of-the-previous-command
Futhermore:
( $prematch, $match ) = $obj->{comm}->waitfor(Match => "/$words{username_string}/",Errmode => "return");

maybe it is a better approach to capture the cmd output into an array variable
my @lines = $telnet->cmd($comm);
for (my $line: @lines) {
    # your matching goes here..
}

or try this:
$t = new Net::Telnet(Host =>"192.168.0.1", Timeout => 5,Port => "1701", Prompt => '/>\$ $/');
$t->print($comm);
$t->waitfor('/username: $/i');
print "result=", $s;


OpenVPN server log - what is the "us=" identifier following the timestamp?

Question: I use OpenVPN 2.3.10 in server mode, with logging set to verb 4.
In the log, every line begins by a timestamp (Mon May 11 10:40:10 2020) and then us=, followed by a 5- or 6-digit number. What is this us identifier? Is it the microsecond (μs) part of the timestamp, or something else? I cannot find this in the documentation and cannot discern any pattern or meaning in the values.
Answer: Yes, it's the microseconds, you can see that in the code:
if (show_usec && tv.tv_usec)
{
    buf_printf(&out, " us=%ld", (long)tv.tv_usec);
}

https://github.com/OpenVPN/openvpn/blob/f57431cdc88f22fa4d7962946f0d3187fe058539/src/openvpn/otime.c#L133
 const bool show_usec = check_debug_level(DEBUG_LEVEL_USEC_TIME);

https://github.com/OpenVPN/openvpn/blob/948b4f938a02dee78fb5246bcd44bc0162619b2d/src/openvpn/error.c#L339


how to add a cck field for youtube embed code?

Question: I have created a content type. I want to add a cck field to the content type where I can paste the youtube video embed code.
So that when I display the value of that field, a youtube video should display where I should be able to click on the play button and the video should play then.
Any module or any other idea for this problem?
Answer: Use Drupal's Embedded Media Field. Here is a quote about it (from the module's project page):

This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.
The module is only an engine, and requires a supported module to function. These include 'Embedded Image Field', 'Embedded Video Field' and 'Embedded Audio Field'. These modules are included in the contrib folder of the module, so they can be easily activated from the module administration page.
Comment: I install this module but it is not working.
Comment: @Ahmad What problem are you having?
Comment: I have installed the module. and then add a cck field of type file and select the widget "embedded media field". then I add a content of that content type and place the youtube video embed code which is the iframe code. It gives me this error "Found no valid media with that url."
Comment: you should only add the video URL eg http://www.youtube.com/watch?v=1BUZMlogs9s
Comment: I also tried this. but I get the same error.
Comment: I have installed the video embed field module with the emfield module and it worked for me.


REST access denied to vote

Question: I have enabled the following modules on the site: VotingApi, Like&DisLike, Rest, RestUI and other depending modules
I use POSTMAN as my client and write my GET and POST request from it.
I have Resource "Content" and "Vote" enabled with all methods, auth and format.
I have created a REST Export view of the content and vote.
When I try to GET and/or POST to create a content I was able to do it successfully.
But when I use POST to vote on the content, I get a 403 response. I have provided a correct credentials on it, with header same as content has.
In Drupal browser logs, it says:
<code>Type    access denied
Date    Friday, June 30, 2017 - 07:12
User    Anonymous (not verified)
Location    http://example.com/entity/vote
Referrer
Message /entity/vote
Severity    Warning
Hostname    172.17.0.1
</code>
Here is my POST request:
<code>{
    "type": [
        {
            "target_id": "like"
        }
    ],
    "entity_id": [
        {
            "target_id": 2
        }
    ],
    "value": [
        {
            "value": 1
        }
    ],
    "value_type": [
        {
            "value": "points"
        }
    ],
    "user_id": [
        {
            "target_id": 1
        }
    ]
}
</code>
Answer: You probally haven't added permissions for anonymous user to do a GET/POST request to the given endpoint. Go to permissions, search for rest and enable "Access GET on [rest resource]" (Access GET on Node rest resource resource)

REST access denied to vote


How to increase the height, width of the table layout?

Question: I wanted to know how to increase the size of the table layout??I have placed the textviews and edittext  in table rows that appear on the left side of the screen. I wanted to design similar to this
Comment: Post your layout here
Answer: You can use       android:minHeight="60px" or assign the width/height to fill_parent.


Telegram bot check if user online

Question: How can I check is user online or not, if I have users chat Id? I tryed bot.userStatus(myChat); but this is wrong.
Comment: https://stackoverflow.com/questions/38131042/getting-the-users-last-seen-from-a-telegram-bot/48506509#48506509
Comment: @Qualcomm that's an answer but this question should not be considered as "duplicate".
Answer: Telegram Bot APIs don't offer any methods or object's attribute in order to get the user status, whether if he's online or not.
Your chatbot is able to gather user's information as soon as he wrote a message to the chatbot: these informations are the User's object fields as described into the Telegram Bot API documentation.
According to the available fields, user status (online, offline, etc.) unfortunately is not (yet) available.
According to another question posted here, it seems that getting the user status is possible via Telegram API so that creating a Telegram registered application which is not the same thing of using a Telegram Bot.

Telegram bot check if user online


Bootstrap Modal Bringing Up Slider when not necessary?

Question: http://puu.sh/4k57Z.png
When I open up a modal using bootstrap it unnecessarily brings up a slider bar on the side.
Is there anything in CSS that would be causing this?
How can I make it not do this?
CSS for the modal
.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1040;
  display: none;
  overflow: auto;
  overflow-y: scroll;
}

Answer:
When I open up a modal using bootstrap it unnecessarily brings up a
  slider bar on the side. Is there anything in CSS that would be causing
  this?

This: overflow-y: scroll;.
A value of scroll says to "show a scrollbar regardless of whether or not you need to do so".

This value [that is, scroll] indicates that the content is clipped and that if the user
  agent uses a scrolling mechanism that is visible on the screen (such
  as a scroll bar or a panner), that mechanism should be displayed for a
  box whether or not any of its content is clipped. This avoids any
  problem with scrollbars appearing and disappearing in a dynamic
  environment.

Source
You can omit that property entirely and the preceding overflow:auto will cause a scrollbar if one is needed.
Comment: Yeah.. Could there be another reason?
Comment: Another style in the document? If you haven't already, use the browser tools to see what styles are being applied to the modal.
Comment: .modal fade, .modal-dialog, .modal-content, .modal-header


What is the difference between active and setFocus() in bright script?

Question: I'm new to Roku world, I'm writing the two textboxes. TextEditbox1 active = true to display a cursor and down key to press, Another texteditbox2 active = true that time texteditbox1 is hidden then Texteditbox2 cursor is displayed. The issue is that. The similar operation I perform with two-button using setFocus() instead of active. it's perfectly working. But I tried to maintain the down key and up key with two textboxes using the Active attribute. It is possible?
I Tried to below things.
TextEditBox1  active = true cursor is displayed

TextEditBox2 active = true cursor is displayed and TextEditBox1 cursor is hidden

I same operation with two-button it's working successfully.
Button1 setfocus true focus is available

Button2 setfocus true focus is available and Button1 setfocus is hidden

Answer: This is stupid BUT:

active only shows that blinking cursor in the TextEditBox

when

setFocus() gives it actual focus, when TextEditBox processes keyPress event

In my opinion, the only way to use it properly is to imitate focusing on that component, by setting active=true without really giving it, because it blocks all the key events. You might make a wrapper-component, which receives focus and then sets active=true without passing it down. And(for example) such component would show KeyboardDialog when the user presses the 'OK' button.
UPD:
clearOnDownKey="false" might save you from this pain
Comment: Here I successfully maintain But, First I'm in the textbox and open dialog box to store value and press down key to set button focus. again I press UP key to Focus textbox and again down key. Here value automatically remove and focus not transfer.
Comment: Thank you this is working for me. I set clearOnDownKey="false". is not removing data from textbox. thank you again


Apache2 on Ubuntu 16.04: Default configuration for FileETag

Question: I have a question regarding the ETag configuration with Apache 2.4. The Apache documentation (https://httpd.apache.org/docs/2.4/en/mod/core.html#fileetag) states that the default value for FileETag is INode MTime Size. However, I am not able to confirm this behavior with my setup.
I am running a Ubuntu 16.04 server with Apache 2.4 from the default repositories. My plan was to prevent Apache from using the inode to generate ETags, because of CVE-2003-1418.
However, I noticed that a FileETag -INode did not change the generated ETag (example: c83-54a250499ffc0). So I tried with FileETag +INode and a new block appeared (ac2981-c83-54a250499ffc0). With FileETag INode only the Inode was returned (ac2981).
I tried the same with the official httpd Docker image (https://hub.docker.com/_/httpd/) and noticed the same behavior.
First I assumed that Ubuntu modifies its Apache package, but the Docker image compiles from source and has the same behavior.
So, what is going on here? Is the default value in the Apache documentation wrong? I just want to be sure if I need extra configuration or if I can trust on the default value.
Answer: You're exactly right - inode was removed from the defaults for the same security reason you're citing, though the documentation was apparently never updated.


Program that automatically does ipconfig/release and then ipconfig/renew on a timer

Question: As the title says, I want to create a program that automatically does ipconfig/release and then ipconfig/renew, every few minutes. I usually do this in the command prompt, but it would be much more convenient if a program could automate this. I was just wondering where I could even begin to create this program? Or is it impossible to automate this?
Answer: untested and likely incomplete for a .cmd file that can be called at startup or login or by task scheduler.  It will need administrator rights.
<code>@echo off

:infiniteloop
ipconfig /release
ipconfig /renew
timeout /t 200
goto :infiniteloop
</code>


O que tem de errado na minha pilha dinâmica?

Question: Estou tentando fazer uma pilha dinâmica, e por algum motivo tem algo de errado na função init. Está dando o seguinte erro:

warning: conflicting types for 'init'

#include <stdio.h>
#include <stdlib.h>

typedef struct TipoCelular
{
    int elemento;
    struct TipoCelular *prox;
}elementoPilha;

typedef struct TipoTopo
{
    elementoPilha *Topo;
}Pilha;

int main()
{
    Pilha *p;

    init(p);

    if(empty(p))
        printf("Pilha vazia\n");

    return 0;
}

void init(Pilha *p)
{
    p->Topo = NULL;
}

int empty(Pilha *p)
{
    if(p->Topo == NULL)
        return 1;

    return 0;
}

Answer: É porque vc usou a função init() antes de ela ser definida.
Coloque a definição dela antes da função main ou deixe onde ela está e adicione apenas o protótipo dela antes da main.
void init(Pilha *p);
/* ... */

Comment: Declarei os protótipos, mas ao compilar dá:  .exe parou de funcionar.
Comment: Agora que percebi. O `*p` no seu `main`  não é uma `Pilha`, é um ponteiro apenas. Tente substituir por `Pilha p` e ao passá-lo como argumento, use `init(&p)` e `empty(&p)`. Aqui um exemplo: https://repl.it/@wldomiciano/Exemplo-em-C
Comment: Deu certo. Obrigado!


When is a variety defined by two quadratics irreducible?

Question: How do we check if the variety defined by two homogeneous irreducible polynomials of degree $2$ in ${\mathbb C}[X_1, X_2, \ldots, X_n]$ is irreducible ?
Is there a nice condition for such things ? I guess  this might be hard to do for general varieties, but what if the number of generators is 2 ? Are things simpler then ?
Answer: An intersection of two quadrics is not integral (i.e., reducible or non-reduced) of codimension 2 if and only if there is a linear combination of these two quadrics which has rank at most 2.
One direction is easy, because a quadric of rank 2 is a union of two hyperplanes. For the other direction, note that the intersection has degree 4 (in the projective space), so, if it is not integral, it has a component of degree at most 2. This component has to be a quadric of dimension n-2, and the linear space of quadrics passing through it contains a space of rank 2 quadrics as a hyperplane.
Comment: Does this generalize to higher degree polynomials (with an appropriate notion of rank) ?
Comment: I don't think so.


Prove that a blockmatrix is positive definite

Question: Let $A, B \in \mathbb{R}^{n \times n}$ be symmetric and positive definite matrices. Define: $$C = \begin{pmatrix} A_{11}B & A_{12}B & \cdots & A_{1n}B\\
\vdots & \vdots & \ddots & \vdots \\ A_{n1}B & A_{n2}B & \cdots & A_{nn}B \end{pmatrix} \in \mathbb{R}^{n^2 \times n^2}$$
Show that $C$ is symmetric and positive definite.
The proof that $C$ is symmetric is simple since it is a direct consequence of $A^T = A$ and $B^T = B$. The problem is to prove that $C$ is positive definite.
Let $x \in \mathbb{R}^{n^2}\setminus \{0\}$ with $x = (x_1,\dots,x_n)^T$ and $x_i \in \mathbb{R}^n$. I'd like to reduce the problem of $x^TCx > 0$ so that I can use the assumptions. Computing the regular formula for $x^TCx$ ended in a chaos for me, is there any simpler way to prove this?
Answer: This is called the Kronecker product and is denoted by $A\otimes B$.
One can show that the eigenvalues of $C$ are given by:
$$\{\lambda_C\}=\{\lambda_A\}\{\lambda_B\}$$
That is, eigenvaues of $C$ are all products of eigenvalues of $A$ and $B$.
So for $\{\lambda_A\},\{\lambda_B\}>0$, we get $\{\lambda_C\}>0$.
To prove:
$$\begin{align} (A\otimes B)(x\otimes y)&=Ax\otimes By\\
&=\lambda_Ax\otimes\lambda_By\\
&=\lambda_A\lambda_B(x\otimes y)
\end{align}$$
It is also not difficult to show that
$$(A\otimes B)^T=A^T \otimes B^T$$
which can be used to conclude that the Kronecker product is a symmetric matrix when $A$ and $B$ are symmetric.
Comment: Thank you, especially for the proof with the eigenvalues. I just checked the definition of the Kronecker product for matrices vectors $(x \otimes y) = (x_1y,x_2y,\dots,x_ny) \in \mathbb{R}^{n^2}$ and then this proof is a lot easier than my computation with 4 irritating sums.
Comment: You're welcome!


Using RxJs map to convert one type of array to another type of array

Question: In my Angular application I use HttpClient to get json data from server. However, I need to do some conversion to the returned data at the client-side.
So I try to convert an array of Type A returned from the server to an array of Type B with the following code snippet.
this.http.get<any[]>(this.env.accounts.url.accountTypes).pipe(map(e => {
    console.log(e); // print the retuned array not a single item
    return {'label': e.name, 'value': e.id}
  }
)).subscribe(data => {
  this.accountTypes = data;
  console.log(this.accountTypes); // prints {label: undefined, value: undefined}
});

I must be doing this wrong, but I cannot figure out what is wrong here.
The server returns an array like:
[
  {name: "Name 1", id: 1},
  {name: "Name 2", id: 2},
  {name: "Name 3", id: 3},
]

And I need to convert it into the following format
[
  {label: "Name 1", value: 1},
  {label: "Name 2", value: 2},
  {label: "Name 3", value: 3},
]

Can somebody please point out what is wrong in my code and how to fix it.
Comment: As you correctly noticed e is an Array and not a single item. With e.name and e.id you are trying to return name and id of the array! You need to map the content of the array too.
Comment: @NicholasK, of course, I know AnguarJs is predecessor o  Angular and have a number of differences. But I don't understand what tags you want me to add here.
Comment: @NicholasK, you are right. I had entered `angularjs` instead of `angular`, he has corrected it.
Answer: You are confusing Array.map, with RxJS's map operator.
As stated on the RxJS documentation for the map operator, the purpose of Map is to

Apply projection with each value from source.

What you can do instead, is this:
this.http.get<any[]>(this.env.accounts.url.accountTypes)
  .pipe(
    map(res => {
      // insert logic
      const data = res.map(obj => ({
        label: obj.name,
        value: obj.id
      }));
      return data;
    })
  )).subscribe(data => {
    this.accountTypes = data;
    console.log(this.accountTypes); // prints {label: undefined, value: undefined}
  });

Answer: As mentioned in the comment please also map the array content
return e.map(entry => {'label': entry.name, 'value': entry.id});

Answer: You can transform the data using the map operator:
var result = [];
x.map(e => {
  const obj = {};
  obj['label'] = e.name;
  obj['value'] = e.id;
  result.push(obj);
})

Answer: Of course there are many solutions but Model Adapter can be a generic solution.
// app/core/adapter.ts
export interface Adapter<T> {
    adapt(item: any): T;
}
export class AccountType {
//.....
}
export class AccountAdapter implements Adapter<AccountType> {

    adapt(item: any): AccountType {
        return new AccountType(
            item.id,
          --  item.name,
          ++  item.value,
        );
    }
}

export class AccountService {
    private baseUrl = 'http://api.*';
    constructor(
        private http: HttpClient,
        private adapter: AccountAdapter,
    ) { }

    list(): Observable<AccountType[]> {
        const url = `${this.baseUrl}/`;
        return this.http.get(url).pipe(
            // Adapt each item in the raw data array
            map((data: any[]) => data.map(item => this.adapter.adapt(item))),
        );
    }
}

this example may help more


In the following queuing problem what assumption led the author to assume the probability of each task happening at 1/180

Question: I am going through this algorithms and data structure course
which implements a queue DS to simulate a printing queue. Following is the solution described:
To model this situation we need to use some probabilities. For example, students may print a paper from 1 to 20 pages in length. If each length from 1 to 20 is equally likely, the actual length for a print task can be simulated by using a random number between 1 and 20 inclusive. This means that there is equal chance of any length from 1 to 20 appearing.
If there are 10 students in the lab and each prints twice, then there are 20 print tasks per hour on average. What is the chance that at any given second, a print task is going to be created? The way to answer this is to consider the ratio of tasks to time. Twenty tasks per hour means that on average there will be one task every 180 seconds:
20  / 1 ℎ × 1 ℎ / 60  × 1  / 60  = 1  / 180

For every second we can simulate the chance that a print task occurs
by generating a random number between 1 and 180 inclusive. If the
number is 180, we say a task has been created.

Note that it is possible that many tasks could be created in a row or we may wait quite a while for a task to appear. That is the nature of simulation. You want to simulate the real situation as closely as possible given that you know general parameters.
I have doubt in the assumption that probability of each task is 1/180. Shouldn't probability for each task 1/20 since there are 20 tasks in total? It could be the considered average per second rate but how is this probability of each task happening every second?
Answer: The reasoning in the tutorial is simple, if you have 20 tasks in 3600 seconds = 1 hour, assuming uniform distribution, then the probability of having a task in a particular second will be $20/3600 = 1/180$.
Note that this logic assumes a second can have at most one task. When the number of tasks is small and time resolution is high, this is logical and a simple approximation. Normally, if we are to choose a particular second for each task independent of others, having at least one task at a chosen second is calculated as below, where we also account for collisions:
$$1-\left({3599\over3600}\right)^{20}\approx 0.00554\approx\frac{20}{3600}$$
Comment: Yeah that's true but I assume any second can have up to 20 tasks.
Comment: I made a mistake so re-writing it. Is it ok to say that the probability is equivalent to the probability of putting at least 1 ball (out of 20) in one of the 3600 bins. Actually it should be $\frac{\binom{20}{1}+\binom{20}{2}+..+\binom{20}{20}}{\binom{3600}{1}+\binom{3600}{2}+...+\binom{3600}{20}}$
Comment: No, if you calculate this, you'll see that it's much much closer to $0$. I think your way of counting things is flawed.
Comment: If you assume that  only 1 task can occur per second then the probability becomes really easy. It's simply $\frac{\binom{20}{1}}{\binom{3600}{1}}$ but if that assumption isn't true then it becomes difficult.
Comment: If that assumption is not true, the answer is the formula I gave in the end of my post. It's still simple to write, but a bit harder to calculate; while simple to approximate.
Comment: I realize that my previous way of counting is also wrong. I didn't take into account how will the remaining 19 tasks will be distributed when there is 1 task in the desired bin, similarly to remaining 18, 17,...and so on.
Comment: So, have you understood my answer, and what the tutorial thinks?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/102880/discussion-between-coddy-and-havent-u-reinstated-monica-yet).
Comment: @Coddy we are interested if a particular second has any tasks in it. We find the probability of that second having no tasks and subtract from 1. We have 20 tasks, and we have 3599 possibilities for each one, which means $3599^{20}$ different ways of placing those 20 tasks with leaving the particularly selected second free. The total number of possibilities are $3600^{20}$ since for each task we have $3600$ possibilities.


Automação de cadastros (MySQL)

Question: Olá, pessoal!
Estou com um problema e preciso da ajuda de vocês para bolar uma solução.
Minha situação é a seguinte: Existe uma página .php que vai ser acessada diariamente por várias pessoas, essa página vai executar um script .sql e retornar um valor... Só que aí é onde está o problema...
Preciso criar um sistema de fila de espera, algo assim, porque o .sql não pode ser executado ao mesmo tempo por várias pessoas.
Alguma ideia de como prosseguir?
Agradeço desde já!
Answer: Voce precisa criar uma tabela no DB chamada fila com os valores dos usuarios e o campo espera de valor 1 e 0 por ordem de chegada.
Antes do usuario usar o seu script ele entra nessa tabela com o valor 0, se ele for o primeiro da lista o valor dele sera 1 e ele usara o script. Apos o uso ele tem que ser deletado desta tabela.
Além disso os usuarios que estao em espera tem que ser informados disso em uma pagina e esta pagina tem que ter um auto refresh a cada 1 minuto por exemplo para que seja feito uma nova verificaçao no banco de dados
Veja a tabela:
fila

id,
  email, espera

verificar.php
<code>    <?php

    // verifica se existe algum usuário usando o sistema
    $selecionaUsuariosUsandoSistema = mysql_query("SELECT * FROM fila WHERE espera = 1");

    // verifica se existe algum usuário na fila
    $selecionaUsuariosEspera = mysql_query("SELECT * FROM fila WHERE espera = 0");

    if(mysql_num_rows($selecionaUsuariosUsandoSistema) == 0 && mysql_num_rows($selecionaUsuariosEspera) == 0){

        // se não existir o usuario usando o sistema ou na fila, ele será inserido no banco de dados depois redirecionado direto para o sistema

        mysql_query("INSERT INTO fila(id, email, espera) VALUES (0, '$emailUsuario', 1)");

        header("Location: diretoParaOScript.php");

    } else {

        // se existir algum usuario na fila ou no sistema ele sera inserido no banco de dados com valor 0 e redirecionado para página espera.php

        mysql_query("INSERT INTO fila(id, email, espera) VALUES (0, '$emailUsuario', 0)");

        header("Location: espera.php");

    }

    ?>
</code>
espera.php
<code>   <?php

$selecionaUsuariosEspera = mysql_query("SELECT email FROM fila ORDER BY id");
$usuariosEmEspera = mysql_fetch_array($selecionaUsuariosEspera);

$emailUsuario = 'firstname.lastname@example.com';

//verifica se o email do usuário é o próximo da fila

if($emailUsuario == $usuariosEmEspera[0]){
    //se for o próximo, ele edita o valor do usuário para 1 e redireciona para o sistema
    mysql_query("UPDATE fila SET espera = '1' WHERE email = '$emailUsuario'");

    header("Location: diretoParaOScript.php");

} else {

   ?>
   <html>
   <head>
    <meta http-equiv="refresh" content="60">
    </head>
   <body>

aguarde...

    </body>
    </html>

   <?php } ?>
</code>
Depois que o usuário fechar o sistema ele tem que ser deletado da tabela
Outras considerações...
Criei este método para dar uma luz para você, pois não sei como funciona o seu sistema.
você tem que considerar algumas coisas como:

E se o usuário fechar o navegador antes de usar o sistema, vai parar a fila?
talvez métodos com cookies e outras sessions sejam necessários para verificar se o usuário está acessando o sistema, se ele ainda está na fila e descartá-lo se não.

boa sorte
Comment: Entendi Andrei, achei a sua solução muito boa, a ideia de criar uma db para a fila de espera e tudo mais. Na verdade eu só estou analisando a lógica mesmo, ainda não decidi em qual linguagem vou fazer o código. Muito obrigado! Era isso que eu precisava ;)
Comment: Tranquilo @Wesley, não esqueça de aprovar a resposta se te ajudou. =) abraço

Automação de cadastros (MySQL)


What is the cost of reconstructing a discrete probability distribution within a given error?

Question: I'm aware that there are several methods to estimate the probability distribution from samples (e.g. density estimation methods). However, I haven't been able to find the actual asymptotic costs of these methods, and I'm not sure whether these methods can be applied to the case of discrete probability distributions.
Given a discrete probability distribution $p$ on $[n]\equiv \{1,...,n\}$, I'm looking for the number of samples required to construct a distribution $q$ on $[n]$ such that $\|p-q\|_1\le\epsilon$ ($\|\cdot\|_1$ denoting here the $\ell_1$ distance).
In other words, how many samples are needed to estimate the correct probability distribution within a given error $\epsilon$?
I've recently read the statement (in this paper, second paragraph of introduction) that the cost of doing this is $\Theta(n/\epsilon^2)$, but if this is a well-known result I haven't been able to find a good explanation for it.
I suppose the naive reconstruction method would be to build the histogram corresponding to the samples (that is, count the fraction of samples corresponding to each $i=1,...,n$). However, I'm not sure whether this method is optimal for the purpose, or how many samples would be required to achieve a given estimation error with it.
Estimates using distances other than the $\ell_1$ one are of course also welcome.
Answer: Upon some reflection, here is what I think might be a possible solution.
Suppose the true distribution is $\newcommand{\bs}[1]{{\boldsymbol{#1}}}\bs p\equiv(p_1,...,p_n)$, and we are drawing $N>0$ samples from it.
This amounts to be drawing samples from the multinomial distribution, call it $\mathrm{Multinomial}(N,\bs p)$.
If $X\sim \mathrm{Multinomial}(N,\bs p)$, then the possible outcomes of $X$ are (representable by) sequences of $N$ integers $x_i\in[n]\equiv \{1,..., n\}$, with $i=1,...,N$.
Because our goal is to estimate $\bs p$, we are interested in the number of times each $k\in [n]$ occurred in a given instance of $X$.
Denote the corresponding estimator with $\hat N_i$.
We know that
$$\mathrm{Pr}(\hat N_i = N_i) = \binom{N}{\bs N}\bs p^{\bs N}
\equiv \binom{N}{N_1\cdots N_n} p_1^{N_1}\cdots p_n^{N_n},$$
where $\binom{N}{\bs N}\equiv \frac{N!}{N_1!\cdots N_n!}$ denotes the associated
multinomial coefficient.
The problem at hand can be formalised as the task of looking for a good estimator for the parameter $\bs p$. The intuition of using the histogram of the distribution for the purpose can be formalised in the choice of the estimators
$$\hat p_i \equiv \frac{\hat N_i}{N}.$$
We can then compute the first moments, to find:
$$\mathbb E[\hat p_i] = \frac{\mathbb E[\hat N_i]}{N} = p_i \qquad \text{(the estimator is unbiased)}, \\
\mathrm{Var}[\hat p_i] = \frac{\mathrm{Var}[\hat N_i]}{N^2} = \frac{p_i(1-p_i)}{N}.$$
We can now compute the estimator corresponding to the trace distance between estimated and true distribution. For $n=2$, this reads
$$\|\hat{\bs p}-\bs p\|_1 = |\hat p_1 - p_1 | + |\hat p_2-p_2| = 2|\hat p_1 - p_1|,$$
and thus, from Chebyshev's inequality, we have
$$\mathrm{Pr}(\|\hat{\bs p}-\bs p\|_1 \ge \epsilon) \le
\frac{2\mathrm{Var}[\hat p_1]}{\epsilon^2}
= \frac{2p_1 (1-p_1)}{N \epsilon^2}.$$
Without making more assumptions about the probability distribution, we should probably take the worst-case scenario, and thus replace this with an identity. Shuffling terms around, we can then say that, in the worst-case scenario, to estimate a binary probability distribution $(p_1,p_2)$  with probability $t$ of committing an additive error $\epsilon$, we need a number of samples
$$N \ge \frac{2p_1(1-p_1)}{t\epsilon^2}.$$
If $p_1$ is unknown, as it would be in this context, we can again take the worst-case scenario, and get the bound $N\ge \frac{1}{2t \epsilon^2}$.
More generally, we can consider the total variation distance $\delta(P,Q)$. This equals the maximum difference between the probabilities that $P$ and $Q$ assign to any given event.
We can then define the corresponding estimator, call it $\hat\delta=\hat\delta(\bs p)$, in the naive way:
$$\hat\delta(\bs p) = \max_{S\subseteq[n]}\sum_{i\in S} (\hat p_i-p_i)\equiv \max_{S\subseteq [n]}[\hat p(S) - p(S)],$$
where the maximum is taken over all subsets of $[n]\equiv\{1,...,n\}$.
Therefore, for all $S\subseteq [n]$, we have
$$\mathrm{Pr}(|\hat p(S) - p(S)|\ge \epsilon) \le \frac{\mathrm{Var}[\hat p(S)]}{\epsilon^2}.$$
We thus conclude that
$$\mathrm{Pr}(|\hat \delta(\bs p)| \ge \epsilon) \le \frac{\max_{S\subseteq [n]}\mathrm{Var}[\hat p(S)]}{\epsilon^2}
= \frac{1}{N\epsilon^2} \max_{S\subseteq [n]} C(S,p),$$
where
$C(S,p) \equiv \sum_{i\in S} p_i (1-p_i -2 \sum_{j>i} p_j)$.
Maximising $C(S, p)$ over $S$ and $p$, we again get a bound of the form $N\ge C/t\epsilon^2$, as in the previous case.
Comment: The last bit in your argument is unjustified - you can't conclude from the analysis presented that the chance of $\delta$ being large is controlled in this way because as far as I see nothing is handling the maximisation over $S$ in your argument. However this is not too hard - by Hoeffding's inequality, for any one $S$, the probability that $\hat{p}(S) - p(S)> \varepsilon$ is bounded as $\exp(-C N\varepsilon^2)$ where $C$ is a uniform constant. Then by the union bound $\mathbb{P}(\max_S \hat{p}(S) - p(S) > \varepsilon) \le |S| \exp(-CN\varepsilon^2) \le \exp( n - CN\varepsilon^2)$.
Comment: Also the linear dependence on $n$ is necessary in a minimax sense - consider the case where the laws may be uniform on some set $T \subset [1:n]$ of size $n/2$. Observing $o(n)$ samples can tell you at most $o(n)$ of the support points, which means that you have no way to distinguish between two slightly overlapping laws of this type, which means $\Omega(1)$ error in TV.
Comment: Oh, correction to the first comment, $|S|$ should be $|2^{[1:n]}| = 2^n$, which is merely the number of possible $S$.
Comment: @stochasticboy321 thanks. I don't quite understand your argument though. I tried to add details to the statements in the last part of the answer. Do you think it makes more sense now? Still, Hoeffding might provide a better bound, I agree with that
Comment: No, that wasn't the point I was making - it's that you actually need to control $\mathbb{P}(\max_S \hat{p}(S) - p(S) \ge \varepsilon)$, while your analysis only controls $\max_S \mathbb{P}(\hat{p}(S) - p(S) \ge \varepsilon)$ (where $p(S) = \sum_{i \in S} p_i$ and similarly $\hat{p}$). The latter quantity is quite different from the former. The difference is similar to the difference between convergence in probability and convergence almost surely. Basically the worst $S$ can depend on the data (and so, on $\hat{p}$), which is not being accounted for in your argument.
Comment: If you want to use Tchebycheff, then at least union bound based analyses give very poor performance of $\mathbb{P}(\max_S \hat{p}(S) - p(S) \ge \varepsilon) \le 2^n/N\varepsilon^2$ - the dependence on $n$ is exponentially worse. The real utility of Hoeffding is that deviations are controlled exponentially well, which lets union bound based analyses to get to the optimal control on the sample complexity (how big $N$ needs to be in terms of $n,\varepsilon$), at least up to constants.
Comment: I see, that makes sense. One question though: once you have the $\exp(n-CN\epsilon^2)$ dependence, how do you turn this into a bound on $N$? Taking logs I'd get something like $\log t\le n - CN\epsilon^2$ which doesn't give a lower bound on $N$
Comment: An upper bound on probability of error of $\eta$ follows if $\exp(n - CN\varepsilon^2) < \eta,$ which occurs if $N \ge \frac{n + \log(1/\eta)}{C \varepsilon^2}$.
Comment: @stochasticboy321 oh I see, you take the reciprocal and then the log; that works. By the way, if you want to write these things as an answer I'll gladly accept it. Also, I suppose these are standard calculations in some context? Do you know some reference where they are presented/discussed?
Answer: As the sample sizes increases, density estimators do tend to come ever closer to the distribution of the population from which the sample was randomly samples. (However, depending on the kernel and bandwidth used, ECDFs can be
computationally intricate.)
Here is an illustration using samples of size 50, 500, 5000 from a gamma distribution with shape 5 and rate 0.1, so that the population mean is 50. The default kernel density estimator (KDE) in R was used to compute the density estimators (red). However, I am not sure how you propose to measure the fit of the KDE to the (possibly unknown) population density.
set.seed(2021)
x1 = rgamma(50, 5, .1)
x2 = rgamma(500, 5, .1)
x3 = rgamma(5000, 5, .1)

 par(mfrow=c(3,1))
 hist(x1, prob=T, ylim=c(0,.022), col="skyblue2", main="n=50, GAMMA(6,.1)")
  lines(density(x1), lwd=2, col="red")
  curve(dgamma(x,5,.1), add=T, lwd=2, lty="dotted")
 hist(x2, prob=T, ylim=c(0,.022), col="skyblue2", main="n=500, GAMMA(6,.1)")
  lines(density(x2), lwd=2, col="red")
  curve(dgamma(x,5,.1), add=T, lwd=2, lty="dotted")
 hist(x3, prob=T, ylim=c(0,.022), col="skyblue2", main="n=5000, GAMMA(6,.1)")
  lines(density(x3), lwd=2, col="red")
  curve(dgamma(x,5,.1), add=T, lwd=2, lty="dotted")
 par(mfrow=c(1,1))

I don't know your goals, but it may be worth mentioning
that empirical CDFs (ECDFs) of samples often show a
better fit to population CDFs than histograms or density estimators show to population PDFs. Additionally, the
Kolmogorov-Smirnov test statistic $D$ measures the maximum
vertical distance between ECDF and CDF. As for computations cost, the ECDF essentially involves only sorting observations (and possibly plotting).
ks.test(x1, pgamma, 5, .1)

        One-sample Kolmogorov-Smirnov test

data:  x1
D = 0.089923, p-value = 0.7801
alternative hypothesis: two-sided

ks.test(x2, pgamma, 5, .1)

        One-sample Kolmogorov-Smirnov test

data:  x2
D = 0.037263, p-value = 0.4912
alternative hypothesis: two-sided

par(mfrow=c(1,2))
 plot(ecdf(x1), col="skyblue", main="n=50")
  curve(pgamma(x,5,.1), add=T, lwd=2)
 plot(ecdf(x2), col="skyblue", main="n=500")
  curve(pgamma(x,5,.1), add=T, lwd=2)
par(mfrow=c(1,1))

Comment: thanks. The goal is to be able to make statements about the number of samples required to estimate a distribution within a given error (defining some type of distance between the distributions). As shown in my answer, one way I thought about was considering an estimator for the total variation distance between the distribution and computing bounds for the probability of said distance being larger than a set amount. This way you can make statements of the form "you require at least this number of samples to estimate the distribution within this and this accuracy".
Comment: I have no idea if these sort of calculations are standard or not though, which was part of the reason for the question
Comment: Everything in my answer is more or less standard. Recommend using CDFs. There are various ways of quantifying distances between CDFs. One is max vertical distance as in K-S tests. Another is 'area between' CDFs. // You might want to look into 'goodness-of-fit= tests generally. Each sample will have its own quirks, but you may want to investigate 'power and sample size' of GOF tests. Power is probability of finding a specific kind of difference if it exists. Start by seeing what others have done before you try to invent the wheel again.
Comment: but CDFs are for continuous distributions no? I'm asking about discrete ones here. The K-S test you mention measures total vertical distance, which sounds like it would behave similarly to the total variation distance in the discrete case. But these are statistical tests. As far as I understand these answer different questions. I'm simply looking for a way to know the number of samples needed to get an estimation with a given accuracy. I thought this was an extremely basic question in this context, albeit I'm failing to find a straightforward answer (probably because I don't know the keywords)


Is there a unique computer identifier that can be used reliably even in a virtual machine?

Question: I'm writing a small client program to be run on a terminal server. I'm looking for a way to make sure that it will only run on specified server and in case it is removed from the server it will stop functioning.
I understand that there are no methods to make it 100% secure, none the less I want to make it difficult for most power users to be able to do it.
I was looking at different Unique Identifiers like Processor ID, Windows Product ID, Computer GUID and other UIs. Because the terminal server is a virtual machine, I cannot locate anything that is completely unique to this machine.
Any ideas on what I should look into to make this mostly secure. I do not have time or the need to make it as secure as possible, because it will defeat the purpose of the application itself.
I do not want to user MAC address. Even though it is unique to each machine it can be spoofed by following instructions found on internet.
As far as Microsoft Product ID, because our system team clones VM servers and we use corporate volume key, I found already two servers that I have access to that have same Product ID Number. I have no Idea how many others out there that have same Product ID
Alternatively instead of trying to identify the machine, I might be better off by identifying the user and create group based permission handled through AD for access to this software.
Comment: I'm pretty confident less than 1% of people will work that out.
Comment: How does everyone have such precise data for the number of people who can spoof a MAC address? Apparently it's 5%... I had no idea.
Comment: I do not want to do a MAC address, any poweruser who can google can spoof it.

http://www.mydigitallife.info/2008/06/30/how-to-change-or-spoof-mac-address-in-windows-xp-vista-server-20032008-mac-os-x-unix-and-linux/
Comment: The MAC address ought to be unique even in a VM? -  http://stackoverflow.com/questions/3443093/what-is-a-good-unique-pc-identifier
Answer: By design, uniquely identifying a virtual machine is difficult; anything that allowed you to uniquely identify it would imply that it was not fully virtual (because cloning a virtual machine should produce an identical machine).

Create a heartbeat application on the host machine that communicates with the VM via a loopback network adapter.
Have the heartbeat application refuse to run if it is not able to uniquely identify the host machine.
Have the main application refuse to run if the heartbeat application is not running.

You will need to find a way to ensure that the heartbeat application cannot be spoofed too easily.
It is not possible to protect the terminal program 100%.  This question is equivalent to trying to prevent software piracy.
Answer: The best thing I've found is the BIOS UUID - but it's far from perfect for your use case.
The SMBIOS UUID available inside the VM is also used by the VMware hypervisor and management tools as VirtualMachine.config.uuid (See: the uuid property on this page). This means it is guaranteed to be unique on a particular host, or in a particular vCenter. However, it can be duplicated on separate hosts or separate vCenter installations.
Also, the BIOS UUID on a virtual machine is mutable. It can be changed through the API (though not easily through the client).
This probably approaches your 95% mark, as it would take some special effort and setup to duplicate the VM exactly.
However, from a virtualization-enablement perspective (including things like VM disaster recovery, and future upgrades of virtualization software): using a hardware ID like the UUID or MAC address causes all sorts of problems. When they want to rev the OS version underneath your software, usually by creating a new virtual machine, they would need to manually edit the VM config for both servers to change the UUID to match. Using the MAC, if they change the network architecture, your software requires that VM to be a special case. These things just cause headaches for a virtual admin (but they might be the exact headaches you're trying to cause - only you know for sure).
I'd recommend using the permissions-based approach you mention, or even a concurrent-licensing server if necessary. But I'm coming from a heavily-virtual background where hardware-tied licenses are a headache already.
Answer: Simplest solution is to use the mac address, but note that it is easily changed on Windows by editing the registry. I'd say less than 5% of people know how to do that though.
Here's how to get the mac address in C#:
<code>System.Net.NetworkInformation.NetworkInterface.GetPhysicalAddress();
</code>
Comment: No one can do that in Windows, which is what the question seems to imply. ;-)
Comment: I was referring to the use of `ifconfig`, which you've now removed from your answer. I'm aware that the MAC can be spoofed under any operating environment.
Comment: @Cody I originally assumed Linux (yes, I didn't read the tags, naughty me! :P ) but changed it. Question does not imply anything about mac addresses, it doesn't even mention it.
Answer: You can tie the license to the MAC address of the network card (or cards, if there are several).
Of course, changing the network card would then stop your software from working.
If/When TPM becomes standard on servers, you should be able to use it to authenticate the server.
Answer: You can get the PC's MAC Address as shown here: http://www.java2s.com/Code/CSharp/Network/GetMacAddress.htm
Of course, this approach is not without flaws.  There are other approaches listed in this post, which is similar, but not an exact duplicate: What's a good way to uniquely identify a computer?
Comment: Note, I think that the answer in the StackOverflow post I linked to deserves some upvotes. The accepted answer is very good, particularly the caution about it being an ongoing chore.
Answer: expanding on the macaddress approach. you could use the macaddress with an md5 function around it with a SALT that was only known to the system owners. this way, the macaddress is useless without knowing the SALT.
just my tuppence worth.. :)
[edit]  - see also here for c# example on hashing/salting etc:
MD5 hash with salt for keeping password in DB in C#
http://www.obviex.com/samples/hash.aspx
Answer: If you want 95% I'd go with the Mac ID - it can be spoofed, but by default is unique for the machine.
Comment: http://www.mydigitallife.info/2008/06/30/how-to-change-or-spoof-mac-address-in-windows-xp-vista-server-20032008-mac-os-x-unix-and-linux/

i would consider this to be easilly done by more than 5 percent of people.
Comment: according to a recent statistic the computer literacy in the US is 20%. I'd imagine less than a quarter of those can spoof a MAC address. I'd just re-word your question.


How to use predicate on object's array of objects values in iOS

Question: I have an Exit object.
Every Exit has an array of Category objects.
Objects look like this :
Category: (id, name)
Exit: (id,name,number,...,NSArray(Categories),...)
I want to use NSPredicate to filter out exits by Category name they have in Category array, but I'm not sure how exactly to write it down.
If I'd wanted to filter out Exits by Exit name, for example, I would do this
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.exitName = %@", name];
NSArray *results = [exits filteredArrayUsingPredicate:predicate];

But I'm not sure how to get into the Categories array and search by Category Name.
Any suggestions ?
Comment: Try this, `NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.categories.name CONTAINS[c] %@", name];`
Comment: `categories` is an NSArray and does not have a name property.
Answer: Try this
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.exitName.category_name CONTAINS[c] %@", name];
NSArray *results = [exits filteredArrayUsingPredicate:predicate];

Comment: SELF is an exit, category_name isn't a property of the name of exit.
Comment: In the predicateformat, SELF can be seen as an instance of Exit. Exit doesn't have a property exitName, the property is name. This name property doesn't have a property category_name. This predicate won't work.
Answer: Try this predicate
NSPredicate *matchingCategory = [NSPredicate predicateWithFormat:@"SUBQUERY(categories, $c, name CONTAINS[cd] %@).@count > 0", categoryName];

Explanation
The SUBQUERY() function creates an array of objects which match the given sub-predicate.  In this case, that sub-predicate is name CONTAINS[cd] %@.  The way it works is by iterating over the collection (first param), assigning the name $c (second param) to refer to each element and then testing to see if the sub-predicate matches that element.  If it matches, it's added to the array.
After the SUBQUERY() completes, the array is aggregated using the @count property.  If there were any matches (@count > 0), the overall predicate on the exits will match the exit being tested.
Comment: A subquery is too complicated.
Comment: Also, filtering all categories and then checking the count is inefficient.
Comment: A solution which works is too complicated, but you don't have any alternative?  What's the point of your comment, exactly?  And the predicate is turned into SQL, which runs quite efficiently.  Why do you think otherwise?
Comment: See my answer for an alternative. SQL isn't mentioned in the question.
Comment: I thought I read core data somewhere in the question.  I apologize for that.  Your answer has the unfortunate problem of not actually working.


Criar um pdf no android

Question: Tenho um byte[] que é um pdf.
uso a seguinte classe pra tentar converter ele.
<code>    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_teste);

    byte[] bytes = getIntent().getByteArrayExtra("pdf");

    String fileName = "out.pdf";
    String filePath = Environment.getExternalStorageDirectory().toString();

    try {
        // Create file
        File someFile = new File(filePath, fileName);
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);

        Intent target = new Intent(Intent.ACTION_VIEW);
        target.setDataAndType(Uri.fromFile(someFile), "application/pdf");
        target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        Intent intent = Intent.createChooser(target, "Open File");
        startActivity(intent);
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        Toast.makeText(this, "Não foi possível abrir", Toast.LENGTH_LONG).show();
    }

}
</code>
Mas quando vou abrir no leitor de pdf diz que o arquivo está corrompido ou danificado.
Comment: Navegando pelo gerenciador de arquivos do celular, você encontrou o pdf criado?
Comment: Não consigo achar a pasta do app no emulador
Comment: Verifica se você ta com permissões de `WRITE_EXTERNAL_STORAGE ` e `READ_EXTERNAL_STORAGE `
Comment: está com as permissões garantidas
Comment: mudei a pasta de destino para o cartão sd, ai diz que o pdf está corrompido
Comment: Pode ser permissão das seguranças do Android, tente utilizar as seguintes linhas de código: `String fileName = "fileName.pdf"; File file = new File(Environment.getExternalStorageDirectory(), fileName);` talvez utilizando o `Environment` de certo
Comment: @Gaspar fiz assim mas na hora de abrir diz que o documento está danificado ou corrompido
Comment: eu não entendi a linha `byte[] bytes = getIntent().getByteArrayExtra("pdf");` o `getIntent()` pega a Intent da Activity atual, talvez você precise puxar a intent de um método externo, verifique [esta resposta](https://stackoverflow.com/a/48914651/3681565)
Comment: @Gaspar essa linha tá certa, ele pega o byte[] da activity anterior. Atualizei a pergunta com o novo código
Answer: Resolvido de uma maneira simples. O Código estava praticamente certo, só faltava o decode pra base64.
Adicionei essa linha depois de pegar o byte[] da activity anterior
<code>byte[] decodedString = Base64.decode(bytes, Base64.DEFAULT);
</code>
Comment: que bom, obrigado por compartilhar a resposta

Criar um pdf no android