Dynamic attr in textbox data-bind knockout JS

Question: I need to add dynamic attr in textbox data-bind
<input class="form-control" type="text" data-bind="
  attr:{
    name:$data.FieldName,
    req: !$data.Nullable,
    placeholder:$data.DefValue,
    disabled:$data.Editable != null && !$data.Editable == true,
    required: $data.Nullable != null && !$data.Nullable,
    'data-bv-notempty':$data['data-bv-notempty'],
    'data-bv-notempty-message': $data['data-bv-notempty-message']
  },
  value: $root.selScreen.isEditMode() ? ActualData : ''
">

if I define in array below list then it should add
'data-bv-notempty': $data['data-bv-notempty'],
'data-bv-notempty-message': $data['data-bv-notempty-message']

OR
'data-bv-notempty':'true',
'data-bv-notempty-message': 'This field can not be empty'

like wise
'data-bv-regexp':'true',
'data-bv-regexp-regexp':''^\d*'',
'data-bv-regexp-message': 'This field can only consist of integer value'

What ever I add in Array it should be add in this
data-bind="attr:{
  'data-bv-regexp':'true',
  'data-bv-regexp-regexp':''^\d*'',
  'data-bv-regexp-message': 'This field can only consist of integer value'
}"

Don't want to use jQuery or Observable object
Answer:
Don't want to use jQuery or Observable object

You're posting a question with the tags jquery and knockout.js, but you don't want to use jQuery or observables?
My interpretation of your question (correct me if I'm wrong):

How can one use the attr binding using a combination of properties defined in both the view and the viewmodel?

For example, in your root viewmodel there are some defaults:
this.defaultAttributes = {
  'data-bv-notempty':'true'
};

And you want to add these defaults in your view, while also keeping the possibility to add specific attributes:

I'd suggest you use Object.assign to merge the two:


JQuery Filtering Using Bootstrap Columns

Question: So I have this working fiddle: https://jsfiddle.net/p5ahob32/1/
    $('#filter').keyup(function () {

        var filter = $(this).val(), count = 0;

        $('.col-md-3 a').each(function () {
            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0) {
                $(this).fadeOut();

                // Show the list item if the phrase matches and increase the count by 1
            } else {
                $(this).show();

                count++;
            }
        });

        // Update the count
        var numberItems = count;
        $("#filter-count").text("Number of Clients = " + count);
    });

If you were to type 3 in the search box it would fade out all the other buttons except 3, however you will notice that the 3 button is all the way in the right because it is in a bootstrap column.
My question is how to I make it so that all the searched items will appear stacked nicely together at the top left?
Thank you!
Answer: // change
$(this).fadeOut();

// to
$(this).parent().css("display","none");
// or
$(this).parent().fadeOut()

Answer: get rid of all the rows except the outer one that wraps all the col's and hide parent of the
$(this).parent().fadeOut();
//AND
$(this).parent().show()

DEMO


How to call a module in a block or give a module a block or put module form into a block?

Question: I have a module, and I would like its add form to be put into a block.  So my question is, how would you take a modules page (admin/build/mymodule/add) and give it a block?  So this module will now have its own block in the blocks admin page.  Do you do this by its url, by module, or by form id?
Comment: you want your module to have its own admin config page?
Answer: You can do this with the $form_id and the function drupal_get_form();
You need to create a module and use hook_block():
function mysecondmodule_block($op = 'list', $delta = 0, $edit = array()) {
  switch($op) {
    case 'list':
      return array(array('info' => 'mymodule add block'));
    break;
    case 'view':
      if($delta == 0) {
        return array(
         'subject' => 'Mymodule Add',
         'content' => drupal_get_form('form-id');
        );
      }
    break;
  }
}

Answer: function mysecondmodule_block($op='list',$delta=0,$edit=array()){
  switch($op) {
    case 'list':
       return array(array('info'=>'mymodule add block'));
       break;
    case'view';
       if($delta==0){
         return array(
          'subject'=>'Mymodule Add',
          'content'=> drupal_get_form('form-id');
           );
       }


Counting a 16th note rhythm with breaks

Question: I'm mostly self-taught musically; I've had some formal training, but what I learned back in elementary school never got past 8th notes.  I learned the basics of counting 16th notes (1 e & a...) when picking up drums about a year or two ago, but now I've come upon an interesting issue.
A friend has asked me to teach him bass, and I'm trying my best to avoid simply telling him to "do it by feel" and get him a proper foundation on counting.  In our next lesson I've got a piece picked out that works pretty well as a basic introduction to counting patterns using whole through 8th notes, but it's got two transitional bars in a 16th note pattern that, frankly, I'm not sure how to count out properly.
The bar two bars in question look like the following (taken from the Mega Man 3 boss theme, for reference):

All notes are 16th notes, R = 16th rest
G|---------------------------------------------|
D|-13-13-R-14-14-R-15-15-R-14-14-R-13-14-15-R-o|
A|--------------------------------------------o|
E|---------------------------------------------|

As a result of my lack of training, I have a bad habit of counting notes instead of rhythm, so my instinct tends to run to counting it as either of the following:

12, 12, 12, 12, 123
11, 22, 33, 44, 123

Conversely, based on how I've since learned to count 16th notes, the following pattern is ostensibly the "correct" way to do it:

1 e, a 2, & a, e &, 4 e &

But that seems so ridiculously messy and complex I'm having trouble counting it right at all.
What is the right method for counting these two bars?
Comment: As Dom wrote in his answer, you definitely want to break the habit of omitting counts when there is a rest. Learning to count all the beats and relevant subdivisions is a key ingredient in understanding more complicated rhythms. You might practice counting when listening to music and not even playing.
Answer: That is the correct way to count 16th notes, but you should count all the beats when you play. You don't stop counting because you stop playing and it does make things more complicated especially when something is syncopated like this. For this song you would count all the notes. Below I put the count and bolded what you will play:
1 - e - & - a - 2 - e -  & - a - 3  - e - & - a - 4 - e - & - a
Try to practice this rhythm against a metronome so you can hear an external count so you get use to counting this way. It may also help to think of the time signature as 8/8 for practice purposes so you can count it like this:
1 - & - 2 - & - 3 - & -  4 - & - 5  - & - 6 - & - 7 - & - 8 - &
Some people are intimidated by small subdivisions like 16th notes and counting them like this should help you if counting small subdivisions is the problem.
Answer: I didn't understand your notation, but I have two suggestions for you.

Say "shh" each time there is a rest.
Try rewriting the passage (for your own benefit), replacing each quarter with a half note, each eighth with a quarter, each sixteenth with an eighth, etc.

Counting a 16th note rhythm with breaks


Docker inside LXD starting container process caused "apply caps: operation not permitted"

Question: I got this error when trying to run a docker container inside an LXD container
gpu is required to run this docker container(I think this might have an effect
(base) root@sim2real:~# sudo docker start sim2real_server
Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: apply caps: operation not permitted: unknown
Error: failed to start containers: sim2real_server
(base) root@sim2real:~#

I have configured the lxd container as the following after looking at other answers
lxc config show sim2real
architecture: x86_64
config:
  image.architecture: amd64
  image.description: Ubuntu focal amd64 (20220305_07:42)
  image.os: Ubuntu
  image.release: focal
  image.serial: "20220305_07:42"
  image.type: squashfs
  image.variant: default
  raw.lxc: lxc.cgroup.devices.allow=a lxc.apparmor.profile=unconfined lxc.cap.drop=
    lxc.mount.auto=cgoup:rw:force
  security.nesting: "true"
  security.privileged: "true"
  security.syscalls.intercept.mknod: "true"
  security.syscalls.intercept.setxattr: "true"
  volatile.base_image: 6f1c83cc14bfd1442678132bb67bb62d2eace4473fbf16d4b40c5e3aa8c8993f
  volatile.eth0.host_name: vethf369ca4a
  volatile.eth0.hwaddr: 00:16:3e:a2:1d:23
  volatile.idmap.base: "0"
  volatile.idmap.current: '[]'
  volatile.idmap.next: '[]'
  volatile.last_state.idmap: '[]'
  volatile.last_state.power: RUNNING
  volatile.uuid: 20a1b524-f313-43c9-b0e3-f8f41c18b52a
devices:
  eth0:
    name: eth0
    nictype: bridged
    parent: lxdbr0
    type: nic
  gpu:
    type: gpu
  proxy0:
    bind: host
    connect: tcp:10.241.91.250:22
    listen: tcp:10.178.2.168:6003
    type: proxy
  proxy1:
    bind: host
    connect: tcp:10.241.91.250:4000
    listen: tcp:10.178.2.168:6004
    type: proxy
  sharefile:
    path: /home/share
    source: /home/wzy/Downloads
    type: disk
ephemeral: false
profiles:
- default
stateful: false
description: ""

But the problem still exists, how should I solve it
Answer: I've got exactly the same error message when trying to start some containers using docker-compose INSIDE LXC container.
I found that those containers has configuration
privileged: true

on my docker-compose.yml, which is already given by lxc config.
Removing this line from .yml solved the problem. Hope this helps.
Notes about my environment:

docker: 20.10.14-ce
docker-compose: 1.16.1
LXD/LXC: 5.2 (installed via snap)

refs:

https://github.com/home-assistant/core/issues/64578


What is the KHR Platform header doing?

Question: While working on a project involving OpenGL, I quickly came across GLAD, which is a library that loads all the OpenGL function definitions and constants that are used in the later versions, such as 3.3 (because the operating system doesn't care anymore). If you scroll down to the bottom, under the Options header, you'll find an option called Omit KHR. The only OpenGL tutorials I've found simply say to make sure that its checked, but I'd like to know what it's doing. A quick look into the source seems to show that it loads platform consistent definitions for things like integers, but is this correct? Here's a link to it: khrplatform.h
Admittedly, this is actually for GLFW, but if you want to download it from GLAD or even from the Khronos Group itself, they should be the same.
Answer: The Khronos group maintains several industry standard APIs: https://www.khronos.org/registry/
To keep things simpler Khronos maintains the khrplatform header to be used by other headers maintained by Khronos, defining common data types, tokens and calling convention macros. However:

Adopters may modify this file to suit their platform. Adopters are
encouraged to submit platform specific modifications to the Khronos
group so that they can be included in future versions of this file.
Please submit changes by filing pull requests or issues on the EGL
Registry repository linked above.

Ironically, this makes it a little more complex to integrate since there may be many APIs and vendors (or "adopters") within the same system. How would these modifications be merged? How to make multiple headers co-exist within the same system? What if some vendor relies on the header looking EXACTLY like the original spec? For that reason providing an option to NOT depend on the khrplatform header makes sense. Wouldn't you agree?
Comment: After reading your clear answer, I would very much agree with the final statement and I would also agree to give it a vote and accept it :) After reading that, it makes so much more sense what it's doing.

What is the KHR Platform header doing?


change default postgresql.conf location on ubuntu

Question: I can't seem to find a way to change the default location of postgresql.conf file from /etc/postgresql/14/main/postgresql.conf to my/own/location/postgresql.conf.
I am running postgresql on Ubuntu server.
I tried changing it using the postgres command line as per the docs but it gives the following error:
postgres=# ALTER SYSTEM SET config_file='/my/loc/test/postgresql/14/main/postgresql.conf';
ERROR:  parameter "config_file" cannot be changed

any ideas?
Answer: The PostgreSQL documentation says:

This parameter can only be set on the postgres command line.

So you can only change it when you start the server with
postgres -c config_file=...

This also gives you a clue how to go about it: you have to modify the systemd service file that starts PostgreSQL, ideally by creating a drop-in file in /etc.
Comment: `command not found: postgres`
Comment: There are the Unix commands `find` and `locate`. Also, I didn't suggest that you should start the server manually, I just tried to explain how the parameter is used.


Algebraic Method for Inverse Maps

Question:
Find the image of $x+y=4$ under the mapping $w=z^{-1}$.

I have read of an algebraic method that seems to work (unsure if my answer is correct).
Let $$x+iy=z=\frac{1}{w}=\frac{1}{u+iv}=\frac{u}{u^2+v^2}-i\frac{v}{u^2+v^2}$$
Now upon equating real and imaginary components, $$x=\frac{u}{u^2+v^2}, \ \ y=-\frac{v}{u^2+v^2}$$
Now,
\begin{align}
x+y&=4 \\
\frac{u}{u^2+v^2}-\frac{v}{u^2+v^2}&=4 \\
u-v&=4(u^2+v^2) \\
4u^2-u+4v^2+v&=0 \\
\left(u-\frac{1}{8}\right)^2+\left(v+\frac{1}{8}\right)^2&=\frac{1}{32} \ \ \ \ \ \ \ \text{(upon completing the square)}
\end{align}
Is the method valid? It is very simple. Any advice would be really appreciated
Comment: I don't see any mistakes (except for a typo where you left out the minus sign on $y after the line "equating real and imaginary components.")   What are you unsure of?  I should perhaps say that I didn't check the arithmetic in the last line.
Comment: A bit of geometry allows you avoid handling formulas: The map $z\mapsto z^{-1}$ is an inversion with respect to the unit circle followed by a symmetry with respect to the $X$-axis. The closest point of the line $x+y=4$ to the origin is $(2,2)$ at a distance $4/\sqrt{2}$, by Pythagoras. The inversion of this point will be a point $(1/4,1/4)$ at a distance $\sqrt{2}/4$ from the origin. Reflexion with respect to the $X$-axis would be $(1/4,-1/4)$. The inversion plus reflexion transforms the line into the circle with diameter $(0,0)$ to $(1/4,-1/4)$. It follows that the center is $(1/8,-1/8)$ ...
Comment: ... radius $\sqrt{2}/8$.
Comment: Thank you! This is the explanation I was hoping for. This confirms my reasoning on why this works and not just how.
Answer: The posted proof looks good.
For an alternative algebraic solution without resorting to cartesian:

write the condition $\,x+y=4\,$ as $\,z+\bar z - i(z - \bar z) = 8\,$;
substitute $\,z = 1/w\,$ and simplify to $\,8 w \bar w - (1+i)w - (1-i) \bar w = 0\,$;
rearrange the above to write as $\,\left|8w - (1-i)\right|^2 = 2\,$.
Comment: I was wondering, is the image of the line $x+y=4$ under the mapping $w=z^{-1}$ defined at the origin?
Comment: @Bell If you work strictly in the complex plane then the image is indeed a punctured circle without the origin. But Möbius transformations (including inversion) are often [defined on the *extended* complex plane](https://en.wikipedia.org/wiki/M%C3%B6bius_transformation#Overview), in which case the origin $w=0$ is the image of the point at infinity on the line $x+y=4$.

Algebraic Method for Inverse Maps


The "entity_reference_revisions_entity_view" plugin does not exist

Question: This is related to Paragraphs module in Drupal 8.
I have enabled paragraphs module and Entity Reference Revisions module. Then I created a new paragraph type in Admin> Structure> Paragraph types. After that I added fields to the new paragraph type. After some configuration I tried to add the newly created paragraph type to a content type, in my case article.
But I got the following error:
There was a problem creating field Paragraphs: The "entity_reference_revisions_entity_view" plugin does not exist.
This is a persistent error. As I have rebuild the site from the scratch, and I am getting the same error.
I will appreciated a help.
Comment: see issue https://www.drupal.org/node/2847643
Comment: @4k4 that is the same person, so that issue reference will not help much :)
Comment: Please enable verbose error logging and include screenshots of your field configuration and where/how the error shows up
Comment: Was this issue ever resolved? If so how?
Answer: This looks like a problem when installing the module.
Check this with drush.
drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

Acc. to the error message the plugin is missing. Now reinstall the module:
drush pmu entity_reference_revisions
drush en entity_reference_revisions

and check again:
drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

If the plugin is not discovered report any errors you see.
Only debug this on a test site with no field data in this field type.


Time Series Modelling problems resources

Question: I've read a portion of "Time Series Analysis and Forecasting" by Brockwell and Davis and I feel like I've gained some theoretical background and intuition.
I'm planning on applying for positions where there's supposed to be some Time Series modelling interview problem. Unfortunately I feel like my theoretical experience with the subject would not be enough for the matter.
I'm looking for some resources with example problems with Time Series modelling and predictions, preferably with example solutions in R.
Thanks in advance! Apologies if this has been asked before.
Answer: You asked 'I am looking for some resources with example problems with Time Series modelling and predictions"
I answer  .. look no fUrther that SE... don't limit your scholarly pursuit to a language or a free set of often inadequate tools but pursue "the city on the top of the hill" .
Look for creative/trend-setting examples . There are many on this site and I have been involved in a few that you might find illuminating . Pursue  https://stats.stackexchange.com/users/3382/irishstat for a few interesting and educational discussions that I have been involved in.


Jmeter decompress gzip response

Question: I write performance test script with JMeter, but the target site using gzip to compress response. So Jmeter can't display any response and only show EOFException.
java.io.EOFException
    at java.base/java.util.zip.GZIPInputStream.readUByte(GZIPInputStream.java:269)

To solve this problem. I write JSR223 PostProcessor for decompress response, but my script always show "Not in GZIP format" message.
java.util.zip.ZipException: Not in GZIP format

I don't have any idea about this message. Please help me.
This is my "JSR223 PostProcessor" script.
import java.util.zip.GZIPInputStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

byte[] responseBody = prev.getResponseData();
ByteArrayOutputStream decompressBaos = new ByteArrayOutputStream();
try(InputStream gzip = new GZIPInputStream(new ByteArrayInputStream(responseBody))) {
    int b;
    while ((b = gzip.read()) != -1) {
        decompressBaos.write(b);
    }
}catch(Exception ex){
    log.info("Exception:"+ex);
}

byte[] decompressed = decompressBaos.toByteArray();
prev.setResponseData(decompressed);

Answer: Are you sure the response is in GZIP format? In order to be able to request it in GZIP you need to add HTTP Header Manager and configure it to send Accept-Encoding header with the value of gzip,deflate
Comment: I'm sorry, the real problem is that target site uses Transfer-Encoding: chunked.
I assumed it was a GZIP problem. This issue will be closed.

Jmeter decompress gzip response


For E of finite Lebesgue measure, is $f(t) = \int_E \cos(tx) dx$

Question:
Let $E \subset \mathbb{R}$ be a Lebesgue measurable set with finite measure.  Prove or give a counterexample that
  $$
f(t) = \int_E \cos(tx) dx
$$
  is continuously differentiable.

I proved that f is continuous, and furthermore, f is absolutely continuous on each compact subset and hence is differentiable almost everywhere.
Further, if $E$ is contained in some compact set (up to a null set), then $f(t)$ is analytic and hence infinitely differentiable (as in this question).  However, if $E$ is unbounded more generally, I am not sure how to proceed.  Any help would be appreciated.
Answer: The function need not be differentiable. That is plausible right away because we would expect the derivative to be $-\int_E x \sin tx \, dx$, but this integral need not converge.
For a more precise version, make the additional assumption that $E\subseteq (0,\infty)$ and
$$
|E\cap (L,\infty)| = o(1/L^4)
$$
as $L\to\infty$. I also want to replace the cosine by $e^{itx}$, for convenience. Then
$$
f(t+h)-f(t) = \int_E e^{itx} (e^{ihx}-1)\, dx .
$$
I cut off the integral at $h^{-1/4}$. By our assumption on $E$, the removed part contributes only $o(h)$, so is irrelevant for the computation of the derivative. On $0\le x\le h^{-1/4}$, we have that $e^{ihx}-1=ihx + O(h^{3/2})$. It follows that if $f'(t)$ exists, then
$$
f'(t) = \lim_{h\to 0} i\int_0^{h^{-1/4}} \chi_E(x)xe^{itx}\, dx .
$$
However, it's easy to cook up an $E$ for which this limit fails to exist for a given $t$; just concentrate $E$ near points with $tx\equiv 0 \bmod 2\pi$.
Comment: I'm losing you somewhere between the o's and the integral cut off using h (not sure what that even means).  Could you maybe construct a more explicit counterexample using the idea you are describing?
Comment: @user334137: (1) The "integral $\int_0^{\infty} \ldots$ cut off at $a$" refers to $\int_0^a$; (2) the example is fully explicit in its current version.
Comment: What is an example set E that satisfies both of your requirements though?


Como usar o PHP na linha de comando?

Question: É possível utilizar o PHP na linha de comando? Como funciona o uso da linguagem nesse ambiente? É possível desenvolver scripts e executá-los como scripts escritos em shell?
Comment: Eu uso muito, por sinal. Inclusive, na minha máquina, o editor de código está configurado para chamar o executável diretamente, para facilitar o desenvolvimento sem precisar de um servidor de páginas local rodando o tempo todo. "[Como funciona o uso da linguagem nesse ambiente?](https://pt.stackoverflow.com/posts/361581/revisions)" - dentro do que se pode esperar da linha de comando, funciona normalmente. O que exatamente tem duvida?
Answer: Olá tudo bem? Podemos sim utilizar o php com linha de comando.
Exemplo: vamos usar o php em linha de comando para executar um script que exiba a mensagem "Hello terminal";
No caso você cria o arquivo php, por exemplo de nome 'script.php', coloca a mensagem dentro. Após abre o terminal de onde o seu arquivo está e executa qualquer um dos comandos abaixo (o -f no segundo comando vem de 'file', ou seja, o nome do arquivo; mas os dois fazem a mesma coisa, é somente outra forma de executar):
php script.php
php -f script.php

Exemplo de como ficaria o código:
script.php
<?php

echo "Hello terminal!";

Saída no prompt de comando:

Usando o php com linha de comando temos duas variáveis globais importantes:
argc e argv. O argc é o contador de parâmetros passados e enquanto o argv é um array global contendo os parâmetros passados (por padrão o primeiro índice sempre contém o nome do script que está sendo executado).
Podemos passar os parâmetros e usá-los a nosso favor. Vamos fazer um exemplo de passar dois números e imprimir a multiplicação entre eles, mas se forem passados parâmetros a menos do que o necessário iremos imprimir uma mensagem de erro.
Logo, nosso script fica assim:
<?php

// O primeiro índice é o nome do arquivo logo temos 3 parâmetros: 0 é o nome do arquivo, 1 é o primeiro número e 2 é o segundo número
if ($argc < 2) {
    echo "Parametros invalidos para executar o script!";
    exit(1);
}
$mult = $argv[1] * $argv[2];

echo "\n O resultado da multiplicacao entre os numeros informados eh: $mult";
echo "\n A quantidade de parametros aceitos e que foram informados sao: $argc";
echo "\n Parametros informados para o script:";
print_r($argv);

Nossa saída no terminal fica:

Para saber mais consulte a documentação sobre Php utilizado em linha de comando
Comment: Obrigado pela resposta.
Comment: Importante dizer que, obviamente, a pasta (ou diretório) onde está instalado o PHP deve estar na variável de ambiente PATH do sistema operacional utilizado.
Answer: É possível, tem manual sobre isto. Então é só chamar o interpretador da linguagem passando o script que pretende executar e eventualmente argumentos para ele.
php -f script.php

Coloquei no GitHub para referência futura.
Comment: @isac tem situações que vc tem opções e argumentos, normalmente nesse caso usa `php -opcao1 -f arquivo -opcao2 -opcaoN -- argumento1 argumento2` e só será passado pro PHP o que vier depois do `--`. Já, sem o `-f` até o `--` é tratado como argumento. E, como é PHP, nos dois casos é inconsistente quando você passa alguma coisa antes do `--` que não é uma das opções do PHP  :D (Pelo menos PHP é consistente no que diz respeito a não ser consistente :P )
Comment: Obrigado pela resposta.
Comment: Qual a diferença para com e sem `-f` ?

Como usar o PHP na linha de comando?


How to check if a congruence equation is right or false

Question:
A specific problem I am struggling with is:
$99^{99} \equiv 8 (\textrm{mod}\ 97)$

But we are also having a test with only multiple choice questions on friday and a question can look like this:

Which of the following congruence equations are true/right/correct
#1) $99^{99} +1 \equiv 0 (\textrm{mod}\ 101)$
#2) $99^{99} \equiv 1 (\textrm{mod}\ 98)$
#3) $99^{99} \equiv 8 (\textrm{mod}\ 97)$
#4) $99^{99} +1 \equiv 0 (\textrm{mod}\ 100)$

What is a generell method to always be able to solve this no mater how you mix and tricks with the numbers? (I know about FERMAT'S LITTLE THEOREM, but I don't see how this can solve all of them completely)
Answer: You can't solve all of the above quite the same way. However there are other simple properties of congruences which you can use. $97$ is a prime, as is $101$ which makes things easy (easier for $97$, but note $99\equiv -2 \bmod 101$). For non-primes you can use the Fermat-Euler theorem if you like, and in some, but not all, cases (look this up if you don't know it, it is an extension of Fermat).
Here, though, note that $99\equiv 1\bmod 98$ and $99\equiv -1 \bmod 100$ and it is easy to raise $1$ or $-1$ to any power you choose. So if you are facing a similar question in a test, look to reduce the problem to a simpler one in this way.
Answer: You   have  to reduce the number under the exponent and use lil' Fermat when the modulus is prime:

As $101$ is prime, $$99^{99}\mod 101\equiv (-2)^{99\bmod 100}=(-2)^{-1}\mod 101.$$
Now $2\cdot 51\equiv 1\mod 101$, so $2^{-1}\equiv 51$  and $(-2)^{-1}\equiv -51\equiv 50\mod 101$
As $97$ is prime
$$99^{99}\equiv 99^{99\bmod 96}=99^3\equiv (99\bmod97)^3=2^3\mod 97.$$

For the nonprime moduli, we may have to compute the value of the totient function at these, but it won't be necessary in the present cases:

$99^{99}\mod 98\equiv 1^{99}=1\mod 98$.
$99^{99}\equiv (-1)^{99}=-1\mod 100$.
Answer: Generally it's a good plan to make the absolute value of the base small first, and worry about the exponent next.
Probably the question requiring most thought is #1).
$99 \equiv -2 \bmod 101$, and $101$ is prime so $(-2)^{100} \equiv 1$ from Fermat's little theorem.
IF the assertion were true, then $(-2)^{99}\equiv -1 \bmod 101$, but then we would have $(-2)^{100}\equiv -2\cdot -1 \equiv 2 \bmod 101$ which we know  is not so. So; false.
Being comfortable with the negative version of the congruence can be very useful in these questions.


Como fazer o plano de fundo dentro de uma div ocupar todo o body

Question: Quero colocar uma imagem dentro de uma div que ocupe todo um body, que quando voce aumente a tela com o scroll do mouse, ela continue seguindo o tamanho de toda a tela.
Exemplo de site com plano de fundo assim:
http://www.tecmundo.com.br/
Quando você aumenta a tela com o scroll do mouse, o plano de fundo azul segue o tamanho da tela. Creio eu que esteja dentro da mesma div, com o tamanho exato, mas siga o body com o width.
Já tentei fazer dentro da div:
width:max-body;
width: 1000%; ( Foi a pior de todas, tinha que colocar todos os dados para a esquerda e de acordo com o rolo da tela com o mouse, uma hora nao dava.)
Quem puder ajudar, obrigado. Dúvida simples, porém, é importante, pois posso acessar o algo do body dentro da div e etc.
Se puder fazer com javascript, serve também. HTML, CSS ou Javascript. Obrigado

            //Aqui não tem nada

            //Aqui também não tem nada

           //Aqui é somente para deixar a imagem no início do cabeçário, que começa no top 0%.

                 // Aqui vem as outras informações, como aside, p, textos, imagens, etc

             //Aqui fecha o cabeçário

                    //Fechou o body

Atualmente, meu código está assim. Usei alguns códigos que responderam abaixo, mas não arrumou. Obrigado a quem ajudar
Comment: De qual parte vc ta falando? Seria melhor [edit] a pergunta e por um exemplo do que tentou fazer e o que não está dando certo, fica mais fácil de entendermos. Se for só o cabeçalho, é só por um width:100% na div. E se não funcionar, é por ter alguma coisa errada no aninhamento do CSS, e não com a DIV em si. Não se esqueça de zerar a margem e o padding do body/html
Answer: Não entendi ainda qual a dificuldade, mas segue um exemplo bem simples que já mostra um cabeçalho com largura total e um fundo com imagem totalmente preenchida, não importa o tamanho da página:

body, html {
  margin:0;
  padding:0;
  width:100%;
  height:100%;
}

#cabecalho {
  width:100%;
  height:120px;
  background:#06c;
  color:#fff;
}

#fundo {
  height:80px;
  background:url(http://lorempixel.com/800/400) no-repeat center;
  background-size:cover;
}

      Aqui vem as outras informações, como aside, p, textos, imagens, etc

    Aqui fecha o cabecalho (na verdade no cabeçalho nao era pra ir nem texto, nem aside etc, senão, não é um cabeçalho né? no máximo uns controles pequenos e navegação)

Comment: " Aqui fecha o cabecalho (na verdade no cabeçalho nao era pra ir nem texto, nem aside etc, senão, não é um cabeçalho né? no máximo uns controles pequenos e navegação)
 "
Foi aqui meu erro inteiro, eu estava fazendo o site dentro de um cabeçalho. Não importava o quanto eu aumentava o zoom da tela, ele ficava no tamanho fixo dele. É mais porque eu aprendi a fazer site pela internet, no caso, se um fizesse o site inteiro dentro do cabeçalho, eu segui e estou aqui até hoje fazendo o mesmo. Obrigado, só essa frase me salvou. Bobo, mas salvou . Obrigado, haha
Answer: Se voc^estiver usando alguma div com idéia de container com tamanho de 970px por exemplo, ou qualquer outro valor para dar a largura do site e centralizá-lo, você deve criar uma div com width="100%" dentro dessa div vc colocar uma outra com uma width especifica para centralizar o site no meio.
Por exemplo:

      {AQUI VOCÊ INSERE O CONTEUDO DESEJADO}

Comment: E como o Bacco falou, zere o margin e o padding do seu body! Pois se não ficaram bordar brancas em todo o site!
Comment: Editei a pergunta, se tiver como dar uma ajudinha, bgd
Answer: A idéia é fixar o background no body e centraliza-lo, onde o mesmo não será redimensionando quando der zoom.
Ficaria assim:
body {
  background: url('https://algumaimagem.jpg') no-repeat center center fixed;
  margin: 0 0 100px;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Comment: Eu editei a pergunta, se tiver como dar uma ajudinha, grato.


Como verificar elementos duplicados em array?

Question: Preciso saber se um array no JavaScript tem elementos duplicados.
Tem alguma função na API do jQuery que faz isso? Caso não, como posso proceder?
Comment: O que já tentou ? tem algum exemplo ?
Comment: O que você quer 'fazer' com os duplicados? Remover do array? Salvar em outro array? Apenas printar no console?
Comment: Talvez esta pergunta te ajude: http://pt.stackoverflow.com/questions/99193/valor-em-array-com-a-maior-ocorr%C3%AAncia
Comment: A [Resposta está aqui](https://pt.stackoverflow.com/questions/376160/capturar-elementos-repetidos-de-um-array-javascript), a variável vetor, é onde teria os elementos.
Answer: Com o magia do ES6 é possível resolver seu problema com apenas uma linha de código. Ex:
var a = ["Ceará","Eusébio","Ceará"];
var b = ["JavaScript",">","All"];

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

hasDuplicates(a);//true
hasDuplicates(b);//false

Answer: Não, não existe nenhuma função via jQuery que faça isso.. o mais próximo dessa realidade seria o .unique(), porém só funciona com elementos DOM.
Mas você mesmo pode desenvolver seu próprio método utilizando .each e .inArray.
Dê uma olhada:
var times = ["Flamengo","Vasco","Corinthians","Fluminense","Corinthians","Fluminense","Palmeiras","Vasco"];
var timesNaoDuplicados = [];
$.each(times, function(i, elemento){
    if($.inArray(elemento, timesNaoDuplicados) === -1) timesNaoDuplicados.push(elemento);
});

//Se "printar" o timesNaoDuplicados: ["Flamengo", "Vasco", "Corinthians", "Fluminense", "Palmeiras"]

Se você quiser saber apenas se um elemento está dentro de um array, utilize o .inArray(elemento, Array).
Mais sobre o .inArray aqui.
Em resumo, ele te retorna a posição (index) onde o elemento está dentro do array. Se não achar nada, retorna -1.
Comment: [RESOLVIDO] O seu codigo não me atende, pois eu preciso saber quais os elementos duplicados. Então já resolvi. Achei a resposta no site :http://www.lucaspeperaio.com.br/blog/funcao-javascript-para-eliminar-duplicidade-em-array . Este retorna os elementos duplicados no array
Mas obrigado pela atenção. Segue codigo abaixo:

Array.prototype.duplicates = function (){
    return this.filter(function(x,y,k){
        return y !== k.lastIndexOf(x) ;
    }) ;
}
var duplicados = ['a','b','c','d','a','b'].duplicates();
Comment: [RESOLVIDO] O seu codigo não me atende, pois eu preciso saber quais os elementos duplicados. Então já resolvi. Achei a resposta no site [link] (http://www.lucaspeperaio.com.br/blog/funcao-javascript-para-eliminar-duplicidade-em-array)[/link] . Este retorna os elementos duplicados no array
Mas obrigado pela atenção. Segue codigo abaixo:
'codigo'
Array.prototype.duplicates = function (){
    return this.filter(function(x,y,k){
        return y !== k.lastIndexOf(x) ;
    }) ;
}
var duplicados = ['a','b','c','d','a','b'].duplicates();
'/codigo'
Comment: código no ideone: [retornar somente os valores duplicados de um array](https://ideone.com/sorfs9)


Select all distinct last records of column1 and order by column2 in Linq (Not Working Accordingly)

Question: So I have a table like this:

Now I want distinct ShortCode order by the ID descending. In other words, the distinct last records. Like this:

So I tried GroupBy like:
var data = db.ShortCodes.GroupBy(x => x.ShortCode).Select(x => x.FirstOrDefault()).OrderByDescending(s=> s.ID);

This gave me distinct records but not the last ones, nor ordered by ID descending:

Now I also tried like suggested here
var data = db.ShortCodeManager
               .GroupBy(s => s. ShortCode)
               .Select(g => g.First())
               .OrderByDescending(s => s.ID);

This gave me the error The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.
So I modified to FirstOrDefault() like:
var data = db.ShortCodeManager
               .GroupBy(s => s. ShortCode)
               .Select(g => g.FirstOrDefault())
               .OrderByDescending(s => s.ID);

This also gave me distinct records but not the last records:

So finally I tried like suggested here:
var data = db.ShortCodeManager.Where(a => a.ID > 0).GroupBy(x => x.ShortCode).OrderByDescending(grp => grp.Max(g => g.ID)).Select(a => a.FirstOrDefault());

Again, this gave me distinct records but not the last ones, nor ordered by ID descending:

So how am I to write the query to get the result I want in Linq? Also note, I need more of the distinct last records than ordering by ID descending. If anyone also knows how to write it in raw SQL it might be useful as well.
Comment: The last one is a duplicate since you already have 1820.  I think you want to group by ID and Shortcut, not just Shortcut.
Answer: This LINQ query should work for your case:
var result = db.ShortCodeManager
    .GroupBy(x => x.ShortCode)
    .Select(gr => new { Id = gr.Max(g => g.Id), ShortCode = gr.Key})
    .ToList();

EDIT:
Based on your comment it looks like you need to cast anonymous object result to ShortCodeManagerModel type and then pass it to your view. So, somethin like this:
var result = db.ShortCodeManager
    .GroupBy(x => x.ShortCode)
    .Select(gr => new { Id = gr.Max(g => g.Id), ShortCode = gr.Key})
    .ToList();

var model = result
    .Select(x => new ShortCodeManagerModel { Id = x.Id, ShortCode = x.ShortCode })
    .ToList();

And then pass model to you view.
Comment: I tried this but it seems like the model i send from the controller has chnaged. I get the error `System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType1`2[System.Int32,System.Nullable`1[System.Int16]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Models.ShortCodeManagerModel]'.`  Note in my view I have a model like `@model IEnumerable`
Comment: Hmm. I am not sure if I am missing something here, now I get the error `The entity or complex type 'Models.ShortCodeManagerModel' cannot be constructed in a LINQ to Entities query.`. Note in your 1st answer, when I debug I see that the data it returns is the data I want in the view. But then I get the error I mentioned earlier in the view. As for the updated code, the error occurs in the query it self. Note that the `ShortCodeManagerModel` contains other attributes that I didn't mention as am only interested in the `ShortCode` and `Id` not sure if that makes a difference? Appreciate the help.


Slow AjaxResponse for node content

Question: I am using Drupal 8 so there is very little documentation or benchmarks, but I believe a route I have set up for ajax responses is not as performant as it could be.
This is the route:
next_node.ajax:
  path: '/node/{node}'
  defaults:
    _controller: '\Drupal\next_node\Controller\DefaultController::view'
  requirements:
    _permission: 'access content'
    _format: 'json'
    _access: 'TRUE'

And this is the controller:
class DefaultController extends EntityViewController {
  /**
   * {@inheritdoc}
   */
  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    $build = parent::view($node);

    return new AjaxResponse(\Drupal::service('renderer')->renderPlain($build));
  }
}

I request the content through this function:
jQuery.get( "/node/2?_format=json", function( data ) { /* Do stuff */ });

Is it normal that it takes about a second on average to get a response? Where to optimize the code?
Comment: Maybe you have configured services for development or disabled caching?
Comment: Nope, this is the behaviour with a default install and caching on.
Comment: Then you should do some profiling. Using simple Timer should be sufficient for something quick.
Comment: BTW I am using JsonResponse instead of AjaxResponse where I am passing render array and it takes half a second on local to get Search API results and return rendered array with data from multiple entities and 3 search api queries.
Answer: There are some different things which could be improved in your code, like using dependency injection, better naming etc, but none of these effect performance.
There are some different things which makes it quite trigger to give a good answer to this. Drupal 8 is still in beta and many performance optimizations are being made. The render cache and page cache should be usable in your case making subsequent requests cached and this a lot faster than the initial request. Being logged in / logged out make a big impact as Drupal has a hard time caching for logged in users, but this is nothing new.
That said, it still sounds a bit slow, but hardware, setup etc also have a lot to say.
So long story short, you can't really performance improve your code.
Comment: Hey there, thank you for the answer. Sorry for the sloppy code, this is really just to illustrate my problem. Well the thing is, that the first request is even faster than the following ones (of course caching is on, but I did not try as an anonymous user – good point) which was the real reason I am so irritated… But yeah, you already helped me – thought there might be some general issues I wasn't aware of.

Slow AjaxResponse for node content


Best Commercial Data Recovery Software

Question: What is the best (that you know of) commercial data recovery software?  If a hard drive fails (SATA/ATA/SCSI), what is the best software to use to recover data from it?
edit: the reason I specified "commercial" is because I wanted to illustrate that I'm not the one in need of any kind of backup for myself.  I'm looking for a software that's great that commercial data-recovery centers use.  Yes, I know they use hardware as well as software...but if anyone could point me in the direction of which commercial software they use, then that's what I'm looking for.
Answer: Spinrite
Comment: I appreciate this answer the most as it is the closest that directly answers my question without assuming/concluding anything further.  I thank you for it, GregD.
Answer: If the data is important, turn the drive off and send it to a facility to do the recovery for you.
You need to understand what is wrong with the drive before you power it on or you may do more damage to the rest of the drive.  If you've suffered a head crash or bearing failure, no software in the world will help you and you'll be moving the bad head all over the platter potentially screwing up more of the surface.
A data recovery house will have spare controllers, diagnostic tools, and a clean room and spare heads and bearings and such.  They'll look at your drive and figure out what is wrong with it and fix it then try to read the data.
Comment: Maybe I should have clarified.  I want to be the person doing the recovery.  Thanks though.
Answer: I find rdiff-backup or dirvish works really well.
Comment: Well, that doesn't answer my question.  How do you know whether I'm trying to help a client who has already lost his data?  How would backing up help that situation, and help me get paid?  It wouldn't.  So please try to answer the question directly.
Comment: If you were worth paying, you'd know that stuffing around with it yourself, as someone who obviously doesn't know what they're doing, has a high probability of losing any data that might currently be recoverable.  Sending it off to a data recovery company is The Right Thing To Do.  Also, having backups beforehand is also The Right Thing To Do, and if this isn't a hypothetical question then you've already screwed up royally by not having said backups.
Comment: P.S. In case you're wondering how I know that you obviously don't know what you're doing in the data recovery sphere: most of what data recovery companies do isn't software, it's hardware, and the software they do use is almost all developed in-house.
Comment: Once again: The right thing to do in the Future, has nothing to do with my goal Right Now, nor anything to do with my Question: Retrieving Lost Data
Comment: Also, you didn't suggest sending to a data recovery company in your answer, you simply provided backup solutions which are pointless in my situation right now.  Thanks for caring lots about my future though.
Comment: Aren't these backup methods?  I'm looking for data recovery.
Comment: My point exactly.

Best Commercial Data Recovery Software


Examples of prime ideals that are not maximal

Question: I would like to know of some examples of a prime ideal that is not maximal in some commutative ring with unity.
Comment: sub-rings of $\mathbb{Z}$ and $\mathbb{Z} \times \mathbb{Z}$ and sub-rings in $\mathbb{Z}_n$, but I never thought to check $\{0\}$
Comment: Would still love some more interesting ones....
Comment: yes I think $k \mathbb{Z}$ for $k\in\mathbb{Z}$ is an ideal. Am I wrong? I am confused by your question;why would I say it if I did not think it...If you can't help, please just don't comment. Or, in the vein of your question,do you think you are helping with your questions?
Comment: @tmpys You do appear to be confused about the difference between subrings and ideals, and surely it is not unhelpful to point this out to you? (Although I agree that the sentence "I can't confusing you more than you are" is confusing.)
Comment: Another example is $(x^2-y)$ in $\mathbb C[x,y]$, see [here](http://math.stackexchange.com/questions/73711/example-of-prime-not-maximal-ideal).
Answer: Let $R$ be an integral domain and consider $R[x]/(x) \cong R$.  It's not a field (unless $R$ is), so $(x)$ is not maximal.  Since $R$ has no zero divisors, $(x)$ is a prime ideal.
Comment: Another concrete way to see why (x) is not maximal is by giving an ideal strictly in between (x) and R[x], like (2,x) which contains all polynomials which have constant term even.
Comment: this is how I convinced myself that there were such things, but I still cant think of good clean examples.
Comment: @tmpys: You're going to have to use example rings which contain elements that are neither zero divisors nor units (to make it possible to discriminate between prime and maximal ideals).  How many such rings do you know?
Comment: Note here that $R$ could itself be a suitable polynomial ring, say $K[y]$ for some suitable $K$.
Answer: Take $(0)$, the zero ideal, in $\mathbb{Z}$, which is prime as the integers are an integral domain, but not maximal as it is contained in any other ideal.
Comment: The same example works if $\mathbb Z$ is replaced by any other integral domain, which is not a field.
Answer: A concrete example: $\langle x^2+1\rangle$ is a prime ideal in $\mathbb{Z}[x]$, but is not maximal, since $\mathbb{Z}[x]/\langle x^2+1\rangle$ is isomorphic to the Gaussian integers $\mathbb{Z}[i]$, which is an integral domain that is not a field.
Comment: which is an example of a proper ideal that properly contains $⟨x^2+1⟩$?
Comment: $\langle2,x^2+1\rangle$ should suffice.
Comment: @zjs $(2, x^2+1)=(2, (x+1)(x-1))$, which is not prime. $(p, x^2+1)$ for any prime $p\cong_4 3$ works.
Answer: $\Bbb Z \times \{0\} $ is a prime ideal of $\Bbb Z \times \Bbb Z$, but it is not maximal. It is contained in the proper ideal $\Bbb Z \times pZ$.
Comment: This time, your answer works. In general, the cartesian product of ideals from 2 or more rings is an ideal of the product ring, but it will not be prime unless all but one of the factor ideals is equal to the whole ring, and the remaining factor is prime.
Comment: This is not a prime ideal. A prime ideal of $R \times S$ must either be $p \times S$ for some prime ideal $p$ of $R$ or $R \times q$ for some prime ideal $q$ of $S$.
Comment: Yes, otherwise the quotient will not be a domain.
Comment: @GeoffreyTrang thanks. I will try to think of another example then.
Comment: @GeoffreyTrang how is that?
Answer: There is plenty of interesting examples!
Let $F$ be an algebraically closed field and consider an irreducible polynomial $f(X_1,\dots,X_n)$ in the polynomial ring $F[X_1,\dots,X_n]$. Then the ideal $I$ generated by $f$ is prime and not maximal, by Hilbert's Nullstellensatz.
For the case $n=2$ and $F=\mathbb{C}$ the geometric interpretation is an irreducible curve, for instance the parabola defined by $X_1^2-X_2$ or the circle defined by $X_1^2+X_2^2-1$.
Comment: @reuns The corollary is that maximal ideals are of the form $(X_1-a_1,\dots,X_n-a_n)$.
Comment: By the Nullstellensatz ? Let $f_i  \in F[X_1,\ldots, X_n]$ some polynomials and  $C = \{ a \in F^n, \forall i, f_i(a) = 0\}$ then the Nullstellensatz says the ideal $I = \{ u \in F[X_1,\ldots, X_n], \forall a \in A,  u(a) = 0\}$ is the radical of some ideal generated by the $f_i$.
Answer: We can give several examples. The key facts are:

An ideal $I$ of $R$ is prime if and only if $R/I$ is an integral domain.
An ideal $I$ of $R$ is maximal if and only if $R/I$ is a field.

Various examples (check yourself these examples satisfies your condition)

$R = Q[x,y$] and $I = (x)$
$R = Z[x]$ and $I = (x)$
$R = Z$ and $I = (0)$
Comment: Are $Z$ and $Q$ the integers and rational numbers (respectively)?  If so, the usual notation is to use `\Bbb Z` (i.e. $\Bbb Z$) and `\Bbb Q` (i.e. $\Bbb Q$) for these sets.


What is $ {z_j} $ in this tableau? (Simplex algorithm)

Question: I've hightlighted the section in the tableau I don't understand. Clearly the 28 comes from plugging in the 4 and 2 in the objective function but where do the other numbers in the row come from?

Any help is appreciated.
EDIT:
Oh, the objective function is $$z = 4{x_1} + 5{x_2}$$
Comment: Have you answered your question by yourself ? Or what is your question ? In general it is hard to give an appropiate answer without knowing the previous tables.
Comment: No, I want to know where the entries I've highlighted come from. I haven't done any of the previous tables, that is literally the question. You're given the end result and you have to identify what these things are and be able to complete one which is incomplete.
Answer: You have identified right the objective function. Only the variables $x_1$ and $x_2$ ($\text{decision variables}$) are regarded to calculate $z_j$. And only the decision variables, which are in the basis are regarded. The $\text{slack variables}$ and $\text{artificial variables}$ are not regarded.
Let´s calculate $z_1$ (first column): $c_1\cdot a_{11}+c_2\cdot a_{21}=5\cdot 0+4\cdot 1=4$
And the calculation for $z_4$ (fourth column) is
$z_4=c_1\cdot a_{14}+c_2\cdot a_{24}=5\cdot \left(-\frac{1}{6} \right)+4\cdot \frac{1}{3}=-\frac{5}{6}+\frac{8}{6}=\frac{3}{6}=\frac{1}{2}$


Django passing data to D3 - D3. eachFor is not a function

Question: I have a small project covering the collection of data in a Postgresql database that is connected to a Django Webapp. I'd like to visualize my data using D3.js. I try to adapt two DateFields to extract my data from the db and offer it as a JSON file to D3.
The console.log shows the correct values from the JSON but I am not able to access the data. Apparently, my data is handed over as a string and not as a JSON object. Do you have any idea why this is the case?
My views:
from django.http import JsonResponse
from django.shortcuts import render
from django.core import serializers

from .models import Sonde
from .forms import date_choice

def index(request):
    latest_Measurement = Sonde.objects.order_by('-Date')[:3]

    form = date_choice

    if request.method == 'POST':
        form = date_choice(request.POST)
        startDate = request.POST.get("start")
        endDate = request.POST.get("end")
        print(startDate)
        subsetData = Sonde.objects.filter(Date__range=(startDate,endDate))
        request.session['subsetData'] = serializers.serialize('json',subsetData)
    else:
        form = date_choice()

    context = {
            'latest_Measurement': latest_Measurement,
            'form': form,
            }

    return render(request,'visDat/index.html',context)

def renderData(request):
    subsetData = request.session.get('subsetData')
    return JsonResponse(subsetData,safe=False)

my urls:
from django.urls import path
from django.conf.urls import url

from . import views

#app_name = 'visDat'

urlpatterns = [
    path('', views.index, name='index'),
    url(r'^api/renderData',views.renderData, name='renderData'),
]

My index.html template:
<form action="" method="POST">
{% csrf_token %}

{{ form }}

<input type="submit" value="Submit" />
</form>

If I call the renderData API manually the following JSON is returned:
"[{\"model\": \"visDat.sonde\", \"pk\": 1, \"fields\": {\"Serial\": \"256599\", \"Date\": \"2018-06-26\", \"Temperature\": 12.56, \"Pressure\": 12.35}}, {\"model\": \"visDat.sonde\", \"pk\": 2, \"fields\": {\"Serial\": \"2565599\", \"Date\": \"2018-06-26\", \"Temperature\": 4.5, \"Pressure\": 100.3}}]"

When I run the script, I get the D3 error that eachFor is not a function. The typeof the data is a string and not an object. But I handle it by JsonResponse and serialize it as a JSON object from a Django Query. Do you have any idea how to fix that?
Comment: Did you mean `forEach` is not a function? You're not calling an `eachFor` in your example
Comment: I get the error in this specific line:     data.forEach(function(d) {
        d.Date = parseTime(d.Date);
        d.Temperature =+ d.Temperature;
    });
Answer: My JSON return did not return a JSON but a string. So, I re-encoded it as a JSON:
import json as js

def renderData(request):
    subsetData = request.session.get('subsetData')
    return JsonResponse(js.loads(subsetData),safe=False)


Is a joint image measure of absolutely continuous image measures absolutely continuous?

Question: Let $(X,F,\mu)$ be a measure space, and let $f,g:X\rightarrow\mathbb{R}$ be measurable functions such that the image measures $f(\mu)$ and $g(\mu)$ are absolutely continuous with respect to one-dimensional Lebesgue measure.
Now let $h:X^2\rightarrow\mathbb{R}^2$ be defined by $h(x,y)=(f(x),g(y))$.  Then my question is, is the image measure $h(\mu)$ necessarily absolutely continuous with respect to two-dimensional Lebesgue measure? If not, does anyone know of a counterexample?
Note that this question comes from me trying to better understand joint probability density functions (for non-independent random variables).
Answer: Not true. Take $f=g$. Let $\Delta =\{(x,x):x \in \mathbb  R\}$. If $m_2$ denotes two dimensional Lebesgue measure then $m_2(\Delta)=0$. But $\mu ((f,g)^{-1} (\Delta))=1$ so $\mu (f,g)^{-1}$ is not absolutely continuous w.r.t. $m_2$.
Comment: Thanks for your answer.  By the way, is there a standard name for the relationship between $h(\mu)$ with $f(\mu)$ and $g(\mu)$?  It's not a product measure of the two measures so what is it?
Comment: In probability  theory it is called the joint distribution of $f$ and $g$.


Why aren't the main menu and the secondary menu simply regions?

Question: I noticed that you can put content pretty much anywhere ( where a theme provides regions) using blocks.
This becomes pretty straight forward and makes sense. But then I was trying to find where the "My account" and "Logout" links came from. And after some searching I found out they are configured in the Menus -> Settings admin page.
Now I read the controversy about the misleading help text for the Source for the Secondary links, so this "special" behavior to display secondary links doesn't seem to work anymore in Drupal 7.
So my question is: Why are these "regions", treated separately at all ?
Why not have normal main menu and secondary menu regions ?
Comment: The entire block/region system is a general mess, and as you suggest, the problem is likely historic. One _could_ dig around in the git logs and issue queue to find out, but: Just avoid it all together and use Panels in D6/7. Fortunately D8 will adopt a Panels like style to handle the problem.
Comment: very complicated.....
Comment: It seems everyone is dodging your actual question :) - I'm not really sure why but I find it a bit annoying that they are usually coded differently, instead of being a menu block in a region.
Comment: I bet it's for some historic reasons. I wonder if Drupal 8 will still have them...
Comment: Great comment, someone finally understood the question. Looking forward to D8 then :) To bad I can't award you the bounty...
Answer: So after much research I found that the main menu and secondary menu settings are there for historical reasons. They had proper functionality in Drupal 5 but its usefulness has declined over the release of newer version ( 6 and 7 ) to the point where modern themes ignore them completely in favor of the powerful regions concept.
The included themes ( as others have mentioned ) have these special "regions" still just because no one cares to remove them.
The original idea was to have an easy way to present sub menu links ( secondary menu ) dependent on the what you select in the main menu.
The modern approach is to have a pop-out sub menu ( like Superfish ) this has made the secondary menu feature obsolete.
So much so in fact, that the functionality is broken and no one fixes it.
In summary, the feature is broken and obsolete. I hope someone removes it from Drupal 8.
Answer: I am afraid I can't answer your question. But the Menu Block module might be a solution to your problem.
The module can render menus in a block. It can also render a submenu for the main menu and put it in a separate block.
(If you have child menu items and the parent is the front page, you might need to patch the menu block module. Drupal does not seem to like child menu items of the front page.)
Answer: If you make your secondary links "source" the primary links, then secondary links will automatically show the child menu items of the current active menu item / page.
Regarding menus as regions, you may be mistaking theme regions for page content.
Main menu and secondary menus are page content often placed directly within a theme region.
There's nothing to stop you putting the menus in a block wrapper for Admin > Structure > Blocks administration, then add to a theme region that way.
It just matters what best suits your site design and layouts.
e.g: put menus in blocks
/**
 * Implements hook_block
 * Provide core menus as regular blocks
 */
function example_menus_block_info(){
  $blocks['example_main_menu'] = array(
    'info' => t('example Main menu'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  $blocks['primary_tabs'] = array(
    'info' => 'Local tasks: primary',
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  $blocks['secondary_tabs'] = array(
    'info' => 'Local tasks: secondary',
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  $blocks['primary_secondary_tabs'] = array(
    'info' => 'Local tasks: primary and secondary',
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  return $blocks;
}

/**
 * hook_block_view
 */
function example_menus_block_view($delta = ''){
  $block = array();
  $block['subject'] = ''; // default no title
  switch ($delta) {
    // Our own properly wrapped main menu for panels.
    case 'example_main_menu':
      $main_menu = menu_main_menu();
      $options = array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu',
            'class' => array('links', 'inline', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        );
      $block['content'] = theme('links__system_main_menu', $options);
    break;
  case 'primary_tabs':
    $block['content'] = array(
      '#primary' => menu_primary_local_tasks(),
      '#theme' => 'menu_local_tasks',
    );
    break;
  case 'secondary_tabs':
    $block['content'] = array(
      '#secondary' => menu_secondary_local_tasks(),
      '#theme' => 'menu_local_tasks',
    );
    break;
  case 'primary_secondary_tabs':
    // default, same as core
    $block['content'] = menu_local_tabs();
    break;
  }
  return $block;
}

Clear cache and can then add the menus as regular Drupal blocks.
Comment: Awarded this answer because he put the most work into it and I can't reward myself :)
Answer: Regions are provided by the Drupal theme.
They are declared in the .info file of theme.
I can suggest you are working with the bartik theme.
Secondary menu (like any other menu) can be printed like block or programmatically. You can find $secondary_menu variable in the /themes/bartik/templates/page.tpl.php file at line 143.
If you want to switch off secondary or main menu visit /admin/appearance/settings/ page at your Drupal site and uncheck Main menu or Secondary menu

Why not have normal main menu and secondary menu regions ?

Some themes (for example Fusion) provide special regions for menu from box.
But there is no need in that because you can create you own region wherever you want with few steps:

Declare region in theme .info file
Print your region in page.tpl.php file of you theme
Flush caches

For more details read Theming Guide and Assigning content to regions
Answer: If you want your menus in specific regions you can disable the main menu and secondary menu on your theme settings page.
Every menu in Drupal has a block at the block configuration page.
You can then place the menu blocks in any region you desire. I'm not sure why Drupal by default is not setup like this.
You should also be able to disable the menus when creating a new theme by not specifying it as a feature in the themes info file.
See http://drupal.org/node/171205#features
Comment: I don't want my menus in specific regions, I want to know why these special regions exist in the first place
Answer: Ray, I suspect the answer to your question is the same as to "Why isn't the logo a region?". Postings such as Display a block next to the Logo show that this causes confusion too.
I suspect that in the original Drupal, themes were much simpler. Drupal's authors could have just provided a content area, plus special-purpose spaces such as those for the logo and the two menus, which were enough to implement their original idea of a Web page. Maybe there were no regions yet, but someone then realised that these special-purpose spaces could be generalised thereto.
Most readers will be familiar with the way that programmers implement something and then realise that various special-purpose features can be generalised. Since StackExchange asks for facts rather than opinions, I searched for stuff about how Drupal developed, but found nothing relevant (though I suppose I could look at the code archives). I see from Evolution of Drupal and the Drupal community - SlideShare that Drupal 4.7.0 already had blocks. And that the first Drupal had only a couple of dozen themes, "all ugly".
By the way, I've been experimenting with Devsaran's Venture theme, and that appears to depend on these abnormal non-regions. So they're still used in at least one modern theme. I described my experiences with it at Why can themes (Venture, but perhaps others too) display a main menu even when the main-menu block is disabled?, where I also referred to your answer to your question.


Optimize Entity Framework Generated SQL Server Execution Plan

Question: I have a data structure that is basically a document with a dictionary of tags.  I am attempting to bring back all documents of a given formtype that have a tag named 'Last Name' and a tag value of 'Smith'.  There may be 0..N 'Last Name' tags associated with the document.
I am using the following linq query to try to match a source document to children with matching tags:
DB.Documents
    .Where(doc => doc.FormID == pd.IndexForm.FormID)
    .Where(doc => doc.Document_StringIndex_ReadOnly
                .Join(Fields,
                        dsi => new { FieldName = dsi.FieldName, FieldValue = dsi.StringValue },
                        dsi2 => new { FieldName = dsi2.FieldName, FieldValue = dsi2.StringValue },
                        (dsi, dsi2) => dsi.Document).Count() > 0);

Which generates the following query when output using .ToTraceString()
SELECT
[Project1].*
FROM ( SELECT
    [Extent1].*
    (SELECT
        COUNT(cast(1 as bit)) AS [A1]
        FROM   [dbo].[Document_StringIndex_ReadOnly] AS [Extent2]
        INNER JOIN  (SELECT [Extent3].*
            FROM  [dbo].[Document] AS [Extent3]
            INNER JOIN [dbo].[Document_StringIndex_ReadOnly] AS [Extent4] ON [Extent3].[DocumentID] = [Extent4].[DocumentID] ) AS [Join1] ON (([Extent2].[FieldName] = [Join1].[FieldName]) OR (([Extent2].[FieldName] IS NULL) AND ([Join1].[FieldName] IS NULL))) AND (([Extent2].[StringValue] = [Join1].[StringValue]) OR (([Extent2].[StringValue] IS NULL) AND ([Join1].[StringValue] IS NULL)))
        LEFT OUTER JOIN [dbo].[Document] AS [Extent5] ON [Extent2].[DocumentID] = [Extent5].[DocumentID]
        WHERE ([Extent1].[DocumentID] = [Extent2].[DocumentID]) AND ([Join1].[DocumentID1] = @p__linq__7) AND ([Join1].[FieldName] = @p__linq__8)) AS [C1]
    FROM [dbo].[Document] AS [Extent1]
    WHERE [Extent1].[FormID] = @p__linq__5
)  AS [Project1]
WHERE [Project1].[C1] > 0

If I do a direct substitution of constants for my parameters (as shown below)  the query executes very quickly.  However, if I leave the parameters in place the query takes several minutes.
SELECT
[Project1].*
FROM ( SELECT
    [Extent1].*
    (SELECT
        COUNT(cast(1 as bit)) AS [A1]
        FROM   [dbo].[Document_StringIndex_ReadOnly] AS [Extent2]
        INNER JOIN  (SELECT [Extent3].*
            FROM  [dbo].[Document] AS [Extent3]
            INNER JOIN [dbo].[Document_StringIndex_ReadOnly] AS [Extent4] ON [Extent3].[DocumentID] = [Extent4].[DocumentID] ) AS [Join1] ON (([Extent2].[FieldName] = [Join1].[FieldName]) OR (([Extent2].[FieldName] IS NULL) AND ([Join1].[FieldName] IS NULL))) AND (([Extent2].[StringValue] = [Join1].[StringValue]) OR (([Extent2].[StringValue] IS NULL) AND ([Join1].[StringValue] IS NULL)))
        LEFT OUTER JOIN [dbo].[Document] AS [Extent5] ON [Extent2].[DocumentID] = [Extent5].[DocumentID]
        WHERE ([Extent1].[DocumentID] = [Extent2].[DocumentID]) AND ([Join1].[DocumentID1] = 1015) AND ([Join1].[FieldName] = 'DDKey')) AS [C1]
    FROM [dbo].[Document] AS [Extent1]
    WHERE [Extent1].[FormID] = 22
)  AS [Project1]
WHERE [Project1].[C1] > 0

After generating an execution plan, I learned that if I directly substitute the parameter values, SQL Server performs an index seek, and my query is fast.  As soon as I leave the parameters in place, SQL Server will perform an index scan, and my query times out.  Is there any way to prod SQL server to always seek?  Can I force entity framework to not use parameterized queries?
Comment: What version of Linq to Entities are you using?
Answer: In the generated SQL, this line
[Join1].[FieldName] = @p__linq__8

may be the problem.
If FieldName is varchar(...) and @p__linq__8 is nvarchar(...) then this clause will cause a table scan since the parameter type doesn't match the index type.
When you directly substitute 'DDKey' then the types match so you get an index seek.  Try your query with N'DDkey' and see if you get a table scan.
This is an issue with various versions of Linq to Sql and Linq to Entities, but may be fixed in later releases.
One way to work around the problem if you can't update to the latest version would be to change FieldName to be nvarchar(...).
Comment: Thank You.  Changing my parameters to varchar generates the correct execution plan.  It will take a while to rebuild the table and indexes with nvarchar column types, but it looks like that was my problem.


Favoring one regression line over another

Question: Skip to the end to see the question, this is just background information.
In the industry I work in, it is often desirable to find any line that best models the data as a sort of worst-case scenario. This leads to some conflict in my analysis from one project to another as:

Project 1 has engineering defined slope, an inverse-square root slope, so we just find the intercept that minimizes RSS.
Project 2 has historically been a mixture of pure linear trends and logarithmic trends. - In working on Project 2, it has also been suggested to test an inverse-square root as well, even though this project does not follow the same engineering as Project 1.

The trends above were found in R using the following coding format:
<code>Linear: lm(Y~X)

Logarithmic: lm(Y~log(X))

Inverse Square Root: lm(Y~sqrt(X)^-1)
                     OR
                     lm(Y~sqrt(X^-1))
                     OR
                     lm(Y~1/sqrt(X))

Note: These are all the same, obviously
</code>
Question
My main question is focused on Project 2. Outside of engineering specified instructions like in the first, why should I favor/choose one over the other? Is it possible to lose information if a trend that was previously found with a linear trend is found to have an inverse square root that has a better AIC/BIC score than the linear?
Also, how do other factors help choose the line that best fits? Namely, one p-value is significantly stronger than another, or our ability to believe the trend is more true than the other, aka Power is higher for one than another.
I can not share example data for proprietary related reasons. I might try to generate a random example when I have a little more time.
Answer: When I'm looking at my models, I tend to take an ensemble approach to decide which is more trustworthy. A better AIC/BIC matters, but make sure to also cross validate. Take 10% of your data and set it aside. Train your model with the remaining 90% and predict that 10% you set aside earlier. record the RSS and then re-do the process with another random 10/90 split. After a number of iterations, find the mean and variance of your RSS for each model.
I would then make my decision based on a balance of how close the means are to 0 and how tight the variances are. closer means to 0 means better central tendency, but small variances means better precision. Depending on what your application is, they will hold different weights.
Answer: My statistical take on this is that in order to fit a regression model you have to make assumptions about the errors, for linear regression these are zero mean, constant variance and independent.   You can if you must add in an assumption that the errors are Normally distributed (with zero mean and constant variance).   It used to be semi-common to transform the Y variable to obtain a model where these assumptions were plausible.   So one thing I would be doing if I were you is checking the residual diagnostics, especially the constant variance assumption (residuals on the vertical axis and fitted values (y hat) on the x axis).


Find $r>0$ such that $\mathsf{E}\mathrm{e}^{r\xi} = 1$

Question: Let $\xi:\Omega\to\mathbb{R}$ be a random variable such that $\mathsf{E}\xi < 0$. I would like to find $r>0$ such that $g(r):=\mathsf{E}\mathrm{e}^{r\xi} = 1$.
Maybe you can help me to derive some necessary of sufficient conditions for such $r$ to exist? Say, if $\xi = -1$ then there is no such positive $r$. I tried to investigate the behavior of  $g(r)$ since $g(0) = 1$, but I was not successful in it.
Edited: maybe one of you can help with an example when $\mathsf{P}(\xi>0)>0$ but there is no positive  root of $g(r) = 1$?
Comment: If $\xi \leq 0$ a.e. then there is no such $r \gt 0$. In fact, we have $0 \leq e^{r\xi} \leq 1$, so $Ee^{r\xi} = 1$ implies that $e^{r\xi} = 1$ a.e. Therefore $\xi = 0$ a.e. contradicting $E\xi \lt 0$.
Comment: Concerning the edit, let $\xi+1$ have a Student t distribution with more than 1 df.  Its expectation is $-1$.  Yet, for all $r \ne 0$, $\mathbb{E}[e^{r\xi}]$ diverges, whence there are no roots at all of $g(r)-1$ apart from $r=0$.
Comment: Can you please make the title more specific? Seeing "Solve an equation" on the front page is not very informative.
Comment: @Theo: that's right if $\xi\leq 0$ a.e. thanks, waiting for more general case.
Answer: Let us forget integrability questions for a moment and assume that $\mathrm{e}^{r|\xi|}$ is integrable for every positive $r$. Then the function $g$ is well defined and continuous everywhere.
First step: as you noted, $g(0)=1$ and $g'(0)=E(\xi)$, hence $g'(0)<0$ and $g(r)<1$ for $r>0$, $r$ close to $0$.
Second step: assume that $P(\xi>0)\ne0$ (otherwise, as shown by Theo, the result is false), and choose $x>0$ such that $P(\xi\ge x)=p>0$. Then $\mathrm{e}^{r\xi}\ge\mathrm{e}^{rx}\mathbf{1}_{\{\xi\ge x\}}$ for every nonnegative $r$, hence $g(r)\ge\mathrm{e}^{rx}p$ for every nonnegative $r$, and one sees that $g(r)\to+\infty$ when $r\to+\infty$.
Conclusion: since the function $g$ is continuous, the intermediate value theorem implies that there exists a positive $r$ such that $g(r)=1$.
When $\mathrm{e}^{r|\xi|}$ is not integrable for at least some positive $r$, three different things may happen: $g(r)$ may be infinite except at $r=0$, or finite for every $0\le r<r_0$ and infinite for $r\ge r_0$, for a given finite $r_0$, or finite for every $0\le r\le r_0$ and infinite for $r>r_0$.
The conclusion that there exists a positive $r$ such that $g(r)=1$ would still hold if for example, there exists a positive $r_1$ such that $g(r_1)$ is finite and $g(r_1)>1$. It would fail, for example, if $g(r)$ is finite for every $0\le r\le r_0$ and infinite for $r>r_0$, with $g(r_0)<1$.
Comment: how can it be that $g(r),r\geq r_0$ will become infinite without $\lim\limits_{r\to r_0}g(r) = \infty$?
Comment: Let me try to rescue the question and assume that you ask for an example where $g(r)$ is infinite for every $r>r_0$ while $g(r_0)$ is finite. Here is one: $r_0>0$ and $P(\xi\ge x)\sim x^{-2}\mathrm{e}^{-r_0x}$ when $x\to+\infty$. (By the way, any thoughts on http://chat.stackexchange.com/rooms/741 ?)
Comment: Thank you, with regards to the chat - I'll answer. Btw, I don't think I saw the invitation.
Comment: The *invitation* was automatically communicated to you as a comment addressed to you on http://math.stackexchange.com/q/49597/6179.
Comment: I've responded you in chat.


Como pegar a imagem do input file e exibir em um img

Question: Estou tentando desenvolver um projeto "Meme Generator", usei um input type="file" para procurar uma imagem em alguma pasta, e utilizar essa imagem de fundo para o meme.
Minha dificuldade está em conseguir o caminho completo da imagem no input, e utilizar esse caminho no src da tag img. Gostaria de saber como faço pra achar o caminho da imagem ou se tem outra maneira de colocar a imagem selecionada na tela?

function subtitle() {
  const textInsert = document.querySelector('#text-input');
  textInsert.addEventListener('keyup', () => {
    document.querySelector('#meme-text').innerHTML = textInsert.value;
  });
}

function memeInsert(){
  const memeInput = document.querySelector('#meme-insert');
  const imgMeme = document.querySelector('#meme-image');
  imgMeme.setAttribute('src', 'caminho_da_img.png');
}

MEME GENERATOR

    <input type="text" placeholder="Texto" id="text-input"/>
    <input type="file" accept="image/png, image/jpeg" id="meme-insert">

Comment: Vejam se ajudam com seu gerador de memes [Canvas](https://developer.mozilla.org/pt-BR/docs/Web/API/Canvas_API) ou [SVG](https://developer.mozilla.org/pt-BR/docs/Web/SVG)
Answer: O navegador não expõe o caminho da imagem, é usado uma tecnica de "fakepath". Você até consegue maior controle sobre o diretório/arquivo se utilizar o File System Access API.
Mas, você pode simplesmente usar o File Reader (https://developer.mozilla.org/en-US/docs/Web/API/FileReader?retiredLocale=pt-PT) para ler o arquivo, e ele lido poderá criar um "link fictício" que poderá ser usado no IMG.

const textInsert = document.querySelector('#text-input');
textInsert.addEventListener('keyup', function() {
  document.querySelector('#meme-text').innerHTML = textInsert.value;
});

const imgMeme = document.querySelector('#meme-image');
const memeInput = document.querySelector('#meme-insert');
memeInput.addEventListener('change', function(evt) {
  if (!(evt.target && evt.target.files && evt.target.files.length > 0)) {
    return;
  }

  // Inicia o file-reader:
  var r = new FileReader();
  // Define o que ocorre quando concluir:
  r.onload = function() {
     // Define o `src` do elemento para o resultado:
     imgMeme.src = r.result;
  }
  // Lê o arquivo e cria um link (o resultado vai ser enviado para o onload.
  r.readAsDataURL(evt.target.files[0]);

  // Define o texto (coisa que já tava fazendo, ~estou ignorando problema de segurança~):
  document.querySelector('#meme-text').innerHTML = textInsert.value;
});

MEME GENERATOR

    <input type="text" placeholder="Texto" id="text-input" />
    <input type="file" accept="image/png, image/jpeg" id="meme-insert">

Comment: Note que para o texto exibir dentro da imagem precisará alterar o CSS. Mas, se depois quise baixar a imagem "modificada" (com o texto) terá que utilizar o canvas (ao menos é a forma mais fácil que eu conheço).


How to make a discord bot button that can download the file to the client's local with discord.py

Question: I have made a button in the view class like this:
<code># Create Download Button
downlaodButton = Button(style=discord.ButtonStyle.grey, label='Download', row=1)
downlaodButton.callback = self.download
self.add_item(downlaodButton)

async def download(self, interaction: discord.Interaction):
 # Change Button Color And Accessbility After Clicking it
 self.children[-2].style = discord.ButtonStyle.blurple
 await interaction.response.edit_message(view=self)

 response = requests.get(self.image_url)

 with open('my_photo.png','wb') as f:
   f.write(response.content)
</code>
It does download the photos to my project directory but what I really want is when a user click that button it will start downloading the photo to their computer. Is it possible to implement with discord.py?
Comment: Why would you need to do that when you can just upload the image itself?
Answer: It's not possible with the discord.py api to make a download on a client pc. you can only upload the image in discord or give the user an url where he can download the image. If you use an url you can make it download directly depending on the browser. But the Discord Client won't download anything by clicking on a button.


Probability calculation for bayesian network

Question: I am struggling to understand how Bayesian probabilities are calculated for the following network:

I don't understand how the probability of 0.69 is calculated for the P(C=true|A=T)?
Also, how to calculate the initial probability of 0.19 for P(C=true) when there is no any evidence?
Comment: Good question. However Stackoverflow is for asking programming related questions. Please move it to Cross Validated https://stats.stackexchange.com/. If you think, however, this is programming related question then show us what you have already tried.
Answer: If you are missing a variable in the evidence, you need to sum over all the possible values of that variable (this is called marginalization).
P(C | A, B) = P(A, B, C) / P(A, B)

=>

P(C | A) = P (C, B=T | A) + P(C, B=F | A)
         = P(C | B=T, A) * P(B=T | A) + P(C | B=F, A) * P(B=F | A)

And the same way if you want to have just P(C).
See also this answer
Comment: I'm missing something. From the probability tables, P(C|A)=0.9/0.55+0.45/0.45?
Comment: @hello What are you missing? The tables in your network are the probabilities `P(A)`, `P(B|A)` and `P(C|B,A)`.
Comment: I don't know if it is possible to read from the tables, P(C | B=T, A) = 0.9, P(B=T | A)=0.55, P(C | B=F, A)=0.45 and P(B=F | A) =0.45? The result is not OK, so I'm doing smth wrong.
Comment: @hello Is State0 T of F?
Comment: I think I got the formula slightly wrong, I will check and edit if I find my error.
Comment: I got division and multiplication mixed up in the lower part of the equations. But I still get 0.425 instead of 0.69
Comment: State 0 is false. I've checked this network using the custom Python script I wrote using pomegranate package, as well as the Genie tool, and the correct probability is 0.69. You're right, =0.9*0.55+0.45*0.45 is OK. Thank you!
Comment: Still struggle to calculate P(C) without any evidences, the correct result is 0.19, please let me know if you get the numbers.
Comment: The nearly correct result: P(C)= P(C,A=T, B=T) + P(C,A=T, B=F) + P(C,A=F, B=T) + P(C,A=F, B=F) = 0.9*0.1*0.55+0.45*0.1*0.45+0.45*0.9*0.1+0.1*0.9*0.9 = 0.19


Why are Embeddings in PyTorch implemented as Sparse Layers?

Question: Embedding Layers in PyTorch are listed under "Sparse Layers" with the limitation:

Keep in mind that only a limited number of optimizers support sparse gradients: currently it's optim.SGD (cuda and cpu), and optim.Adagrad (cpu)

What is the reason for this? For example in Keras I can train an architecture with an Embedding Layer using any optimizer.
Comment: It is better to ask such question on [PyTorch forum](https://discuss.pytorch.org/).
Comment: Good idea! So good in fact that I was immediately able to answer my question after searching the PyTorch forums!
Comment: You answer did not really answer you question, i.e., why embedding is implemented as sparse layer.
Comment: Good point. I'll see if I can figure it out and make an update to my answer.
Answer: Upon closer inspection sparse gradients on Embeddings are optional and can be turned on or off with the sparse parameter:

class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, sparse=False)

Where:

sparse (boolean, optional) – if True, gradient w.r.t. weight matrix
  will be a sparse tensor. See Notes for more details regarding sparse
  gradients.

And the "Notes" mentioned are what I quoted in the question about a limited number of optimizers being supported for sparse gradients.
Update:
It is theoretically possible but technically difficult to implement some optimization methods on sparse gradients. There is an open issue in the PyTorch repo to add support for all optimizers.
Regarding the original question, I believe Embeddings can be treated as sparse because it is possible to operate on the input indices directly rather than converting them to one-hot encodings for input into a dense layer. This is explained in @Maxim's answer to my related question.


How do I make a custom pop up for when I click on an asp table element?

Question: I have a table I've dynamically created, and I want to make it so that I see a pop up with a custom image, along with some text taken straight from the table element.
Comment: What have you tried so far? This is an open ended question and we may not know what your skill set is. The answer may be as easy as saying "Lookup how to use jquery or css"
Comment: can you pls show your code ?
Answer: With the limited context you provide, I can't give you a complete solution, but I can at least outline a way to get it running:

Use jQuery and jQueryUI.
Bind a jQuery click event handler to the element.
Use a jQueryUI Dialog to display the popup.
Comment: Thanks, I just stumbled upon using JQuery (i'm mostly a desktop programmer).

How would I bind it exactly?


Dropdown List, when no data in database can't input manually

Question: enter image description hereI'm creating a program, using the dropdown list.
so here is the form "Pilih Unit Mesin", where the machine unit that has the number "Torsi" in the database automatically will appear numbers in the form of "Torsi"
The problem is how if the machine unit has no numbers in database, i hope in the form "Torsi" can be input manually number
Please help, thank you
Pilih Unit Mesin
<select class="form-control" name="id_unit" id="id_unit" required="">

<option value="">nama proyek - unit mesin</option>
<?php foreach ($mesin as $key => $value) :?>
    <?php if ($value['status_unit'] === '0'): ?>
        <option <?php echo $unit_selected == $value['id_unit'] ? 'selected="selected"' : '' ?>
        value="<?php echo $value['id_unit'].'">'.' - '.$value['nama_project'].' - '.$value['unit_mesin'].'</option>'; ?>">
    <?php else: ?>
    <?php endif; ?>
<?php endforeach?>
</select>

Torsi
<select class="form-control" name="torsi" id="torsi" required="">

<?php foreach ($poross as $key => $val) :?>
    <?php if ($val['torsi_poros'] != null): ?>
        <option <?php echo $poros_selected == $val['id_unit'] ? 'selected="selected"' : '' ?>
        class="<?php echo $val['id_unit'] ?>" value="<?php echo $val['torsi_poros'] ?>"><?php echo $val['torsi_poros'] ?></option>
        Kg.mm

        <?php elseif ($val['torsi_poros'] != ""): ?>
        <option <?php echo $poros_selected == $val['id_unit'] ? 'selected="selected"' : '' ?>
                                 class="form-group input-group">
        <input class="form-control" name="torsi" type="text" required="" pattern="^(\+|-)?[0-9].*$">
        Kg.mm

    <?php endif; ?>
<?php endforeach?>
</select>

enter image description here
Screenshot 1:

Screenshot 2:

Screenshot 3:

enter image description here
Comment: Like, if there _is_ data, show the select, and if there _isn't_, show an input?
Comment: Yes it's sir @kerbholz, do you know how to make the coding?
Answer: You could combine multiple array functions to check whether specific key from multidimensional array is not empty :
Torsi
<?php
if (empty(array_filter(array_column($poross, 'torsi_poros')))) {
?>
<input type="number" name="torsi" id="torsi" class="form-control" >
<?php } else { ?>
<select class="form-control" name="torsi" id="torsi" required="">

<?php foreach ($poross as $key => $val) :?>
    <?php if ($val['torsi_poros'] != null): ?>
        <option <?php echo $poros_selected == $val['id_unit'] ? 'selected="selected"' : '' ?>
        class="<?php echo $val['id_unit'] ?>" value="<?php echo $val['torsi_poros'] ?>"><?php echo $val['torsi_poros'] ?></option>
        Kg.mm

        <?php elseif ($val['torsi_poros'] != ""): ?>
        <option <?php echo $poros_selected == $val['id_unit'] ? 'selected="selected"' : '' ?>
        class="<?php echo $val['id_unit'] ?>" value="<?php echo $val['torsi_poros'] ?>"><?php echo $val['torsi_poros'] ?></option>
        Kg.mm

    <?php endif; ?>
<?php endforeach?>
</select>
<?php } ?>

Using array_column to return the values from a single column in the array, then array_filter to discard empty array.
Comment: thank you for answering my question,
when i write the coding as you created my program is still not running, guess there are errors where?
Comment: the fixed view is like the beginning, can't pop up manual input if the data in the database is empty
Comment: so there are no error? could you do a `var_dump($poross);` before the `if()` statement?


Firefox behaving differently to Safari and Chrome with jQuery variable values

Question: I'm using a wonderful plugin computedstyle.js that gets the computed style of objects.
It allows me to manipulate the css of things you shouldn't normally be able to, like constructed images.
I'm able to take an image source which is found in a link, and change the size of the housing div and of the image itself. Usually you can only do that if you know the size of the image.

I construct the image
I size the image
I then size the iframe around it, based on the size of the changed image.

This works in Chrome and Safari, but of course, not Firefox, which in my opinion is fast becoming the new Internet Explorer.
The question, is there a way I can make firefox wait to notice the change and then do the resizing of the iframe?
TO see it work correctly in Chrome and Safari, go to http://syndex.me. And not correctly, Firefox.
Not a must for the question, but if you are wondering what I'm doing, I'm removing the default gallery preview of Tumblrs Photoset Post and replacing it with a single image.
if($(this).find('.html_photoset').length){
    $(".html_photoset").find("iframe").load(function(){
        var myFrame=$(this);
        $(this).contents().find('.photoset_row:not(:first-child)').each(function(){
            $(this).remove();
        })
    var psPre = $(this).contents().find('.photoset_row').find('a').attr("href");
    $(this).contents().find('.photoset_row').children(':not(:first-child)').remove();
        $(this).contents().find('.photoset_row').children(':first-child').children().remove();
        $(this).contents().find('.photoset_row').find('a').append("");
        $(this).contents().find('img').load(function(){
            var myCSS = $(this).getCSS(); //this is the plugin function
            var myY = myCSS.height.slice(0, - 2);
            var myX = myCSS.width.slice(0, - 2);
            $(this).closest(".photoset_row").css({height: myY});
            $(this).closest(".photoset_row").css({width: myX});
            $(this).css({maxHeight: (heightRef-0)});
            $(this).css({maxWidth: "auto"});
                    //after I've made the fixes to the image, I redo it for the iframe:
            var myCSS2 = $(this).getCSS();
            var myY2 = myCSS2.height.slice(0, - 2);
            var myX2 = myCSS2.width.slice(0, - 2);
            myFrame.height(myY2);
            myFrame.width(myX2);
            console.log(myY2);
        })
})
}

Comment: If you're becoming "used to" Chrome and Safari, I would say you're become Webkit-prone. Firefox is not a Webkit browser. Expand your horizons. `:)`
Comment: Fair enough, but this is not a webkit plugin, it's jquery. Actually i believe moz even has some internal computed style manipulators that other browsers don't, so i had to go the plugin route.
Comment: I don't know what you mean by "webkit plugin" when it comes to jQuery. Either a browser supports a specific functionality or it doesn't, *and* that functionality is supported by the code/markup trying to manipulate it.
Comment: What does this getCSS function actually do?  That's not stock jQuery, and your complaint seems to be that it's not returning the data you expect, right?  Also, is the maxHeight/maxWidth stuff you do relevant?  `heightRef` is not really defined anywhere in your snippet, and `auto` is not a valid value of `max-width`....
Answer: This caveat on the .load() jQuery docs page is interesting:

Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load()
  shortcut is to execute a function when an image (or collection of
  images) have completely loaded. There are several known caveats with
  this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

So, to try and mitigate some of these, I would suggest trying to append a random query string to the end of the image href to avoid it being cached, and avoid the src being set to the same as before, etc.
i.e. change the psPre line to:
var psPre = $(this).contents().find('.photoset_row').find('a').attr("href") + '?' + (Math.random() * 1000000);

Comment: Yes, if a URL is different (even if its just the query string, and that query string isn't even used by the page), the browser will think it is a new never-before-seen resource and download it, which circumvents the cache.
Comment: Also, as a general hint, try caching as much as you can in variables when working with jQuery. Any time you have a selector or function chain repeated, cache it in a variable and use the variable instead. This only runs the code once. e.g. in your code, `$(this).contents()`, `$(this).contents().find('.photoset_row')` and  even `$(this)` can all be cached in variables before they are used for the first time. This will speed up the script a bit.
Comment: Interesting, will that really stop caching of the image? If so that's a nice little trick. It doesnt solve the problem though, but it's good to know. I think my issue is that I'm declaring a variable with very fresh data thats created in the lines directly before it, in the same function. I console logged the values of the second variable and basically it still sees the values from three lines before, so I'm pretty sure what i'm looking for is some kind of delay function or comparison tool to see first if the value has indeed changed. Once it's confirmed, it does it's thing.


Como colocar a média na última table no Rails

Question: pessoal eu tenho a seguinte dúvida esse meu código ele incrementa para sempre que tiver uma avaliação ele mostra, mas, a media sempre fica após como se fosse uma nota
<% @registration.matrix.blocks.each do |block| %>

Bloco: <%= block.description %>

                Disciplina
                Faltas Atribuidas
                Prova 1
                Prova 2
                Prova 3
                Prova 4
                Prova 5
                Prova 6
                Prova 7
                Prova 8
                Prova Final
                Média

            <% block.disciplines.distinct.each do |discipline| %>

                <%= discipline.name %>

                    <%= number_of_absences(current_user, discipline) %>

                <% discipline.evaluations.each do |evaluation| %>
                    <%= Evaluate.get_evaluate(current_user.id, evaluation.id).present? ? Evaluate.get_evaluate(current_user.id, evaluation.id).note : '0,0' %>
                <% end %>
                <%= get_media(current_user, discipline) %>

            <% end %>

<% end %>

Então gostaria de saber como eu faço para arrumar o erro, por exemplo eu coloquei a nota 10, ele divide por 8 conforme eu programei, mas a média que é 10/8 já que 10 foi a unica nota que atribui, ela fica 1,25 porém a media fica do lado e não no final, como eu faço para colocar no final na table "média"
Answer: O resultado da média não está aparecendo no final porque você precisa que a quantidade de 	  seja  a mesma quantidade de 	.
No seu exemplo você 12  tags e somente 3 .
Você deve sempre deixar a mesma quantidade e no seu caso você vai precisar a medida que for colocando as notas (prova -> 1,2,3,4,5,6,7,8, final)

                    Disciplina
                    Faltas Atribuidas
                    Prova 1
                    Prova 2
                    Prova 3
                    Prova 4
                    Prova 5
                    Prova 6
                    Prova 7
                    Prova 8
                    Prova Final
                    Média

                <% block.disciplines.distinct.each do |discipline| %>

                    <%= discipline.name %>

                        <%= number_of_absences(current_user, discipline) %>

                    <% discipline.evaluations.each do |evaluation| %>
                        <%= Evaluate.get_evaluate(current_user.id, evaluation.id).present? ? Evaluate.get_evaluate(current_user.id, evaluation.id).note : '0,0' %>
                    <% end %>

                    <%= get_media(current_user, discipline) %>

                <% end %>

Comment: cara até "funcionou" acontece que quando eu atribuo a segunda nota, ai pula e buga kkkk
Answer: Usa o "times" para fazer um laço das vezes que tem repetir o , sendo a diferença entre 8 e o tamanho das notas.
<% discipline.evaluations.each do |evaluation| %>
<%= Evaluate.get_evaluate(current_user.id, evaluation.id).present? ? Evaluate.get_evaluate(current_user.id, evaluation.id).note : '0,0' %>
<% end %>
<% (8 - discipline.evaluations.length).times do %>

<% end %>

só não sei se fica "bonito".


How to add edit link within add to cart form in ubercart drupal 7?

Question: I need to add edit link within add to cart form in ubercart in Drupal 7.
I am using hook_form_uc_cart_view_form_alter() hook but not getting how to add edit link within this hook.
Answer: This is probably confusing due to UC's reliance on TAPIr to render the cart items. Anyway, you can modify data inside in the $form['items'] array to change the output of those elements. For example, if you wanted to add an edit link underneath the product description:
function MYMODULE_form_uc_cart_view_form_alter(&$form, &$form_state) {
  foreach($form['items'] as $key => $value) {
    //Check a TAPIr row for a product associated with an editable nid
    if(is_int($key) && isset($value['nid']['#value']) && isset($value['desc'])) {
      if(node_access('update', $value['#entity'], $user)) {
        $form['items'][$key]['desc']['#markup'] .= l('(EDIT)', 'node/'.$value['nid']['#value'].'/edit');
      }
    }
  }

There might be a cleaner way to do this, but I haven't thought about TAPIr in a while.