Why can the equation Ax = b not be solved for every b

Question:
Let $A$ be a $3 \times 2$ matrix . Explain why the equation $A\vec{x} = \vec{b}$ cannot be solved for every $\vec{b}$ in $\mathbb{R}^3$. What about a $4 \times 3$ matrix?

I'm not sure how to answer this.. I know that a $3 \times 2$ matrix only has 2 pivot columns and could therefore only have 2 pivot positions maybe? I also know that the third row would have to be like maybe infinitely solutions or? I'm not really sure how to explain it
Comment: What if the last equation was $0=1$?
Comment: Essentially yes, what happens is that the image of $A$ (viewed as a map) is at most a plane (or it might only be a line or even just a point in the most degenerate case). The reason has to do with the concept of *rank* of a matrix. A $3\times 2$ matrix cannot have rank$>2$, hence the image cannot be all of $\mathbb{R}^3$. (Thus there exists some $b$ such that $Ax=b$ has no solution).
Comment: **Hint:** Would you be able to solve it if $A$ were in row-echelon (or reduced row-echelon) form?
Comment: well then I would have $\begin{bmatrix}1&0\\0&1\\0&0\end{bmatrix}$ right @Omnomnomnom ?
Comment: And wouldn't that mean that I have **infinitely many solutions** ?
Comment: Then that would mean no solution!
Comment: So a 3x2 cannot be solved because there could be a possibility of no solution ?
Comment: Hint: The vector $x$ lives in $\mathbb{R}^2$, thus the map $A:\mathbb{R}^2\rightarrow\mathbb{R}^3$ is mapping the plane into 3D space, and it is a linear map. What might the image of $\mathbb{R}^2$ look like in $\mathbb{R}^3$?
Comment: oh wait its like saying the domain is the dimensions in 2d space and then its saying its co domain is in 3d space so everything wouldnt map right right?
Comment: I'm assuming the same rules apply in a 4x3 matrix? thank a matrix rank cannot be > 3?
Comment: You're right about the rank. I also want to point out that the reason that the rank is always less than or equal to the dimension of the domain is that the image of a linear transformation (i.e. the column space of the matrix) is spanned by the images of the basis vectors of the domain. (So if your domain is $\mathbb R^2$, as for a $3\times 2$ matrix and you look at the standard basis $e_1,e_2$, then the column space of $A$ will be spanned by $Ae_1, Ae_2$, so it can have dimension at most $2$.)
Answer: Consider the linear transformation $T:\mathbb{R}^{2}\rightarrow \mathbb{R}^{3}$ deined by $$T(X)=AX.$$ Now existence of solution for $AX=b$ means that $b\in\mathbb{R}^{3}$ has preimage under $T$ and which is not possible for every vector of $\mathbb{R}^{3}$ as $T$ can't onto. Same is true for the matrix mention by you.
Answer: $A$ is a matrix and $b$ a vector. what   means the equation $Ax=b$
has solutions or not?
possesses solutions means that the vector $b$ is in the sub space
spanned by the column vectors of $A$. If $B$ is the matrix
obtained by concatenating $A$ and $b$, then this is equivalent to
$rank (A) = rank (B)$; by negation so that $Ax = b$ admits no
solution iff  $b$ is not in the space generated by the columns of
$A$ ie $rank (B) = rank (A) +1$
In the case of a non-square matrix there is an infinity of $b$ in
the space that satisfies $rank (A) = rank (B)+ 1$ and also an
infinity of $b$ that satisfies $rank (A) = rank ( B)$.


Wireless setup for my Aironet 1260

Question: I have a new Aironet 1260.  I've read that I shouldn't setup WEP for wireless.  Any recommendations on how this should be configured?  Should I setup 802.1X?  I assume I need to setup a radius server.  Where should I start?
Comment: This is a bad question, no doubt. But I'm not entirely sure the close votes are warranted.
Comment: If 802.1x is what you want, implement that. If you're happy with WPA2-PSK, then go with that. Unfortunately we can't tell you what you need.
Answer:
I have a new Aironet 1260. I've read that I shouldn't setup WEP for wireless.

You read correctly. WEP can be cracked in seconds (and you can't use RADIUS with it). You want WPA2 with AES for encryption.

Any recommendations on how this should be configured?

You can configure this via the web interface or the CLI for that access point. I suggest you read the manual. It's detailed and gives you everything you need to know.

Should I setup 802.1X?

This depends on whether you want everyone to share a key (not very secure, no audit trail). Or if you want each person to log on with their own credentials.

I assume I need to setup a radius server.

Only if you want to do 802.1x. If you have Windows Servers, you can install IAS (Server 2003) or NPS (2008 + 2008 R2). These packages allow you to do RADIUS auth against your Active Directory, if you have one. If you don't have Windows Server, you can set up something like FreeRADIUS on *nix or any of the dozens of alternatives.

Where should I start?

By reading the documentation.
Comment: Just to add, if you opt not to use dot1x and just stick with a pre-shared key using WPA2 and AES, make it long. Currently the only methods I'm aware of to break this is using dictionary crack so a very long key is somewhat descent (for now). Cisco also makes Access Control Servers that run a Radius server and TACACS+ server that work very very well with Cisco AP's and controllers if you do go that route.

Wireless setup for my Aironet 1260


Shall I censor or rather remove other causes in cause-specific survival analysis?

Question: I am doing Cox regression models and KM plots for a data set where the end point is death.  In addition there is information about whether the death was cancer-specific or not.  So I have three categories:

No death, last seen is the date of censor
Death - cancer-specific
Death - other cause

What I would like to know is what to do with category 3 data when I am looking at cancer-specific survival as my endpoint.  Do I censor that data at the date of death OR do I just remove that data from the dataset?
Comment: Is your main research Q more about length of time until cancer or about the causes of the three different outcomes?  If the latter, you might try a multinomial logistic regression.
Comment: Length of time before death after treatment is the main research question
Answer: Category 3 should be censored, not removed.  Removing them would be similar to removing those in category 1 instead of censoring.  The fact that those people were alive and did not die from cancer is useful information.
You should also look at all cause mortality in addition to the cancer specific.  There is a chance that some of the non-cancer deaths were indirectly influenced by the cancer (increased stress leads to heart problems, believing they are going to die anyways leads to risky behavior, etc.)
Competing risks models could also be informative (just make sure that you understand what assumptions you are making).


Non-repeating chord progression in pop verse progression

Question: I am having trouble understanding a pop song verse progression that I came across.
Please see the following screenshot of the sheet music:

Here are the two main things I notice:
1) The first "phrase" (Am F F/E Am7 Cmaj7 Em) is harmonically more dense than the latter (Am F C Em); and
2) These are two different chord progressions played back to back in the same verse--yet they are not different sections.
I love the way it sounds and I am wondering if this has a name or if there is any theory that indicates how to construct such a chord progression.  Do the nuances of the "first" progression have any harmonic function in terms of leading us to the "second"?
Any insight on this progression is appreciated!
Thanks.
Answer: I think these would be called passing chords. The first verse is Am F F/E Am7 Cmaj7 Em, and it contains Am F C Em. So I think the main progression would be Am F C Em, and the first verse is just adding a little and varying the harmonic rhythm to create more movement (i.e. by adding F/E and Am7 between the F and C chords).


codeigniter template assistance

Question: Hello all im new to codeigniter and new to the hole template system.
så i hope some one will help me out and maybe look at my code and see if i can do something better so i can learn something new :).
i have try to install this template system
williamsconcepts.com/ci/codeigniter/libraries/template/index.html
but i just cant get it to work, so i found this template system
maestric.com/doc/php/codeigniter_template
but i dont know how to add a sidebar and footer function to it.
and i have try for 3 days now and just dont know what to do :/.
You can not see my project any longer here https://github.com/SimonJ/Hip-hop-project
Best Regards Sjmon
Comment: Welcome to the site.  Please refer to the FAQ.  This site is for reviewing working code, not for fixing issues.  You're question is better asked on StackOverflow most likely.
Answer: Your question should be asked on Stackoverflow.com - but I'll answer it for you anyway as I know when questions are moved so too are comments and answers.
I haven't used the abvoe two mentioned template libraries, but if you try Phil Sturgeon's template library you might find it easier: http://philsturgeon.co.uk/code/codeigniter-template
Sidebars and footers would be view partials. Basically a view partial is a view stored in a variable. You technically don't need a templating system to do this as you can simple go:
<code>$data['header']  = $thos=>load->view('header', '', TRUE); // Returns a view as data
$data['sidebar'] = $this->load->view('sidebar', '', TRUE); // Returns a view as data
$data['footer']  = $this->load->view('footer', '', TRUE); // Returns a view as data

$this->load->view('content', $data);
</code>
Then in your content view file which in this case is called content.php located in your application/views directory you could go:
<code><?php echo $header; ?>
<?php echo $sidebar; ?>
<?php echo $footer; ?>
</code>
I however do recommend Phil's library as it is a lot nicer than storing views in variables.

codeigniter template assistance


Trazer registro sql mesmo não tendo o acento necessário

Question: Preciso trazer um registro chamado Vidraçaria em uma pesquisa, como posso trazer este registro escrevendo apenas Vidracaria na pesquisa?

Ou trazer água buscando apenas agua

A pesquisa funciona normal quando a palavra é escrita corretamente, com ou sem acento.
Estou usando like() para buscar as informações nos registros mysql
Comment: Já vi essa pergunta e não consegui ter nenhum resultado
Answer: Use uma função para retirar os acentos da palavra buscada e do que está no banco. Desta forma irá encontrar a palavra com ou sem acentos:
function tiraacentos($i){
   return preg_replace(array("/(á|à|ã|â|ä|Á|À|Ã|Â|Ä)/","/(é|è|ê|ë|É|È|Ê|Ë)/","/(í|ì|î|ï|Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö|Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü|Ú|Ù|Û|Ü)/","/(ñ|Ñ)/","/(ç|Ç)/","/(ý|ÿ|Ý)/"),explode(" ","a e i o u n c y"),$i);
}

Na query você usa a função no nome da tabela do BD e no termo buscado:
$palavra = $_POST['palavra'];
"SELECT * FROM tabela WHERE ".tiraacentos(NOME DA TABELA)." LIKE '%".tiraacentos($palavra)."%'"

Answer: Você pode utilizar um collation diferente em tempo de execução para remover os acentos:
...
WHERE nome like '%vidracaria%' collate utf8_general_ci

Ou para o caso do erro apontado:
...
WHERE nome like '%vidracaria%' collate utf8mb4_general_ci

Comment: Traz a seguinte mensagem do HeidiSQL "Collation 'utf8_general_ci' is not valid for character set 'utf8mb4'"
Comment: @R.Wegner Tente o mesmo comando acima mas troque utf8_general_ci por utf8mb4
Comment: Não retornou nenhum erro, mas também não retornou nada


Adding validator to a number of fields

Question: I have a number of fields added to multiple content types. Using the Field validation module takes much time, so I decided to validate them programmatically. Which hook should I use to validate fields?
Answer: You'll need to add a hook_form_alter(), check the form ID matches one of those that you're interested in, then add a validation handler to the form. The validation handler will perform your validation against the form fields. Something like
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form_ids = array(
    'article_node_form',
    'page_node_form'
  );

  if (in_array($form_id, $form_ids)) {
    $form['#validate'][] = 'MYMODULE_field_validate_callback';
  }
}

function MYMODULE_field_validate_callback($form, &$form_state) {
  if (empty($form_state['values']['field_x'][LANGUAGE_NONE][0]['value'])) {
    form_set_error('', 'Field X cannot be empty.');
  }
}

I don't know of another way to do this as hook_field_validate() is only called for the module that implements the field type.
Comment: Thanks. my site is multilingual. LANGUAGE_NONE currently works but should I always use it?
Comment: I think you'd get away with checking the language of the node, something like `$langcode = $form['#node']->language`...but I'm not totally sure

Adding validator to a number of fields


Como reproduzir query com subqueries do MySQL no hibernate?

Question: Estou utilizando JPA 2.0 e tentando reproduzir esta query no hibernate , mas não estou conseguindo visualizar como fazer.
Fiz na linguagem do Mysql
SELECT totalassociado,
       totalcriticado,
       items.item_codigo_item,
       items.item_data_item,
       items.item_descricao,
       items.item_status,
       items.empresa,
       items.usuario_nome,
       Associado.usuario_codigo,
       items.usuario_codigo
FROM   (SELECT Count(item.`codigo`)          AS TotalAssociado,
               item.`codigo_item`            AS item_codigo_item,
               item.`data_item`              AS item_data_item,
               item.`descricao`              AS item_descricao,
               item.`status`                 AS item_status,
               item.codigo_empresa,
               usuario.`codigo`              AS usuario_codigo,
               usuario.`nome`                AS usuario_nome,
               usuario.`permissao`           AS usuario_permissao,
               tecnico_item.`codigo_tecnico` AS tecnico_item_codigo_tecnico,
               tecnico_item.`codigo_item`    AS tecnico_item_codigo_item
        FROM   `item` item
               INNER JOIN `tecnico_item` tecnico_item
                       ON item.`codigo` = tecnico_item.`codigo_item`
               INNER JOIN `usuario` usuario
                       ON tecnico_item.`codigo_tecnico` = usuario.`codigo`
        GROUP  BY usuario.codigo,
                  item.codigo_empresa) AS Associado,
       (SELECT Count(item.`codigo`)          AS TotalCriticado,
               item.`codigo_item`            AS item_codigo_item,
               item.`data_item`              AS item_data_item,
               item.`descricao`              AS item_descricao,
               item.`status`                 AS item_status,
               usuario.`codigo`              AS usuario_codigo,
               usuario.`nome`                AS usuario_nome,
               usuario.`permissao`           AS usuario_permissao,
               tecnico_item.`codigo_tecnico` AS tecnico_item_codigo_tecnico,
               tecnico_item.`codigo_item`    AS tecnico_item_codigo_item
        FROM   `item` item
               JOIN `tecnico_item` tecnico_item
                 ON item.`codigo` = tecnico_item.`codigo_item`
               JOIN `usuario` usuario
                 ON tecnico_item.`codigo_tecnico` = usuario.`codigo`
        WHERE  item.status = 'CRITICADO') AS Criticado,
       (SELECT item.`codigo`                 AS item_codigo,
               item.`codigo_item`            AS item_codigo_item,
               item.`data_item`              AS item_data_item,
               item.`descricao`              AS item_descricao,
               item.`status`                 AS item_status,
               item.codigo_empresa           AS Empresa,
               usuario.`codigo`              AS usuario_codigo,
               usuario.`nome`                AS usuario_nome,
               usuario.`permissao`           AS usuario_permissao,
               tecnico_item.`codigo_tecnico` AS tecnico_item_codigo_tecnico,
               tecnico_item.`codigo_item`    AS tecnico_item_codigo_item
        FROM   `item` item
               JOIN `tecnico_item` tecnico_item
                 ON item.`codigo` = tecnico_item.`codigo_item`
               JOIN `usuario` usuario
                 ON tecnico_item.`codigo_tecnico` = usuario.`codigo`) AS items
WHERE  Associado.usuario_codigo = items.usuario_codigo

Alguém poderia dar uma ideia / ajuda?
ainda não consegui fazer a complicação está justamente em passar para jpql ou hql na hora de utilizar a sintaxe comecei assim:Query query = manager
            .createQuery(
                    "select m,d from (select m from Item m left join  m.tecnicos t "
                            + "where (m.status ='CRITICADO' or m.status ='JUSTIFICADO') and t.codigo=:codigo ) as m,"
                            + "(select d from Item d join d.tecnicos t where t.codigo=:codigo) as d",
                    Object[].class).setParameter("codigo", 3L);

    List<Object[]> items = query.getResultList();
    System.out.println("---Impressão de Items----");
    int i = 0;
    for (Object[] item : items)
        System.out.println(++i + " ITem  : "
                + ((Item) item[0]).getDescricao() + "Quantidade ===>  "
                + ((Item) item[1]).getDescricao());
}e recebi a mensagem:2014-03-21 11:46:25,161 ERROR [org.hibernate.hql.internal.ast.ErrorCounter] line 1:17: unexpected token: m

2014-03-21 11:46:25,162 ERROR [org.hibernate.hql.internal.ast.ErrorCounter] line 1:17: unexpected token: m
line 1:17: unexpected token: m ou ( retirando o mapeamento m
Comment: Poderia compartilhar conosco o que você já tentou no Hibernate? Você fez por meio de uma query HQL? Se sim, poderias postar a query e o erro que você encontrou?
Comment: ainda não consegui fazer a complicação está justamente em passar para jpql ou hql na hora de utilizar a sintaxe
Comment: coloquei acima o que tentei.
Answer: Você pode utilizar o HQL (Hibernate Query Language) para este fim - o HQL possui uma sintaxe muito próxima do SQL e também suporta sub-query's:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries
Ainda assim, no HQL você terá que fazer algumas adaptações, tais como:

Sintaxe do Join;
Alterar o nome das tabelas para o nome completo das classes Pojo (remover os delimitadores / crase);
Das colunas relacionadas na cláusula WHERE e que são mapeadas como chave-estrangeira deverão receber as respectivas classes POJO como parâmetros;


What theory underpins how arpeggiators work?

Question: Arpeggiators are fairly common in dance music, particularly trance. In this example you can see he is pressing just one key and letting the keyboard do the rest for him, and it changes up and down.
How does this tie in with the theoretical side of music or chords to pick complimentary chords?
Answer: The machine just follows rules.
Just looking at the video, I guess the rules are these:

Follow a pattern (like a drum machine) for the tempo and rhythm of the notes.
Follow a pattern based on a setting as to whether the arpeggio goes up and repeats, goes down and repeats, or goes up and down.
Change the arpeggio only at the beginning of each measure.
At the beginning of the measure:

4a. if only one key is pressed, arpeggiate a major chord with that note as the root.
4b. If two notes a major third apart are played, arpeggiate a major chord with the lower note as the root.
4c. If two notes a minor third apart are played, arpeggiate a minor chord with the lower note as the root.
4d. If more than two notes are played, arpeggiate that chord.
Again, I'm just guessing, there can be more complex rules.  The system could allow you to set the key, and then build a chord only on notes within the key.  In this way, in the key of C, playing an A would result in an A minor chord.
An even more complex system could have a database of examples and use a Markov-chain or Bayesian method.  These are a strictly mathematical technique, and (surprisingly) can be much easier and more effective than programming musical theory into the machine.  Markov chains were used in the 1950's to program computers to automatically compose music.
Those methods work something like this:  Suppose the key is C, the last time the chord changed was three measures ago, the current chord is G7, and the user presses E.  In the past, under those circumstances, if the new chord had an E, 90% of the time it was C major, 8% it was A minor, 2% it was C# minor.  For predictability, pick C major every time; for automatic composition, pick C major with 90% probability, A minor with 8% or C# minor with 2%.
Most likely the Roland arpeggiator does NOT do that, but if you like to program and have a system that has a MIDI keyboard for input and can play MIDI output you can try writing programs to do this.
Postscript:  You may find it surprising that pure math can work as well as or better than music theory for doing something like this, but this just shows that there was a good reason that in ancient and Medieval times Music was considered to be a branch of Mathematics.
Answer: Arpeggiators repeat a rhythmic pattern. One not can be programmed to trigger a chord that gets repeated rhythmically. OR (more commonly), arpeggiators repeat individual notes of a played and sustained chord that is being triggered in sequence. So, if you are holding a C major triad down on the keyboard, the arpeggiator will run through all the notes in that chord, one at a time (not play the chord as a chord), sync'd to a tempo. So it will play the C, then E then G. The order in which the notes are played can be defined, as can the rhythm, as can the range - meaning the arpeggiator can go up multiple octaves or down multiple octaves, triggering the various C's, E's and G's within that range (say you select 2 octaves, then you'll have a low c, as well as a higher c being triggered). The order that the notes get triggered can also be defined. So it may not go C, E, G, C, E G. It could go E, C, G, C, E, G or G, E, C, G, E, C. Etc. Again, these notes can be played with triplet quarter note values, as eigth notes, as swung eighth notes, as dotted quarter notes, as half notes or any combo of anything note length value you can think of.
An arpeggio in classical music refers to playing the notes that make up a chord, separately and in sequence. A BAZILLION compositions employ arpeggios. Think Chopin, or Beetoven Piano music. The left hand outlines chords while a melody is played in the right hand.  Arpeggiators automate this fundamental methodology of opening, or prolonging chordal/harmonic functions.
Modern synthesizers have taken that traditional arpeggio and expanded on it - by using gating and more. Where chords essentially can be triggered (common in trance for example) and repeat certain rhythmic patterns - this technically isn't an arpeggio, but the audio is triggered in the same way that arpeggiators traditionally function, so it falls under "arpeggiator" type plug-ins.


one-point compatification of $X$

Question: A topological space is called $T_B$ if every compact subset is closed.
Let $X$ be countable and $T_B$ and $X^* = X \cup \{\infty\}$ be one-point compatification of $X$.
We want to show that when $X$ is countable , $T_B$ space and sequential space. then $X^*$ is $T_B$. So we consider compact subset $B$ of $X^*$. We must consider two cases:
(1):$\infty \not\in B$
(2):$\infty \in B$
For the first case, it is easy to show that $X^*$ is $T_B$.
For the second case, if $\infty \in B$ and $B$ is not closed in $X^*$, so $C\cap X$ is not closed in $X$ and not sequential closed.then there is a sequence $\{ x_n \}$ s.t converge to $ a \not\in B$.....

could you help me how to reach a contradiction ?
Answer: $\newcommand{\cl}{\operatorname{cl}}$You can't show that $X^*$ is $T_B$ by looking at one case; what you mean is that in the first case it's easy to show that $B$ is closed in $X^*$. Now you have a compact set $B\subseteq X^*$ such that $\infty\in B$, you're assuming that $B$ is not closed in $X^*$, and you want to reach a contradiction.
Let $C=B\cap X$; since $\infty\in B$, $C$ is not closed in $X$. $X$ is sequential, so $C$ is not sequentially closed, and there is a sequence $\langle x_n:n\in\omega\rangle$ in $C$ converging to some $x\in X\setminus C$. The set $\{x\}\cup\{x_n:n\in\omega\}$ is compact (why?), so it's closed in $X$, and therefore $\{x_n:n\in\omega\}$ is relatively closed in $B$. Now use the fact that $X$ is $T_B$: this implies that $X$ is $US$, i.e., that convergent sequences have unique limits, from which it follows that $\{x_n:n\in\omega\}$ is a discrete subset of $B$. Thus, $\{x_n:n\in\omega\}$ is a closed, discrete subset of $B$, contradicting ... what?
Comment: (1) what do you mean "**relatively closed**""?(2) is $x$ an accumulation point of $ \{ x_n : n \in \omega \}$?(3) is $\infty$ an accumulation point of $ \{ x_n : n \in \omega \}$?(4) if $\{x_n:n\in \omega\}$ is a closed, discrete subset of B, contradicting with compactness B?
Comment: @Ebi: (1) You should recognize that term by now: it means that the set is closed in the relative topology (also called the *subspace topology*) on $B$. (2) Yes, since $\langle x_n:n\in\omega\rangle\to x$ and $x\notin\{x_n:n\in\omega\}$. (3) Yes, though it doesn't matter. (4) Yes, exactly.
Comment: $A = \{ x\} \cup \{x_n :n \in \omega \}$ is closed in $X$. so $X^* - A$ is a nbh at $\infty$, how is $\infty$ accumulation point of $\{x_n:n \in ω\}$?
Comment: @Ebi: Sorry: for some reason I wrote *Yes* when I meant *No*. But it really doesn't matter at all for the argument.
Comment: @BrianM.Scott: fwiw I made it through several university courses in topology without having heard the term "relative topology" or "relatively closed". It was always just "subspace topology" and "closed" to me.
Comment: @Ben: Although the screen name is different, I'm reasonably certain that this isn't the first time that I've explained the term to the OP. I've no objection to the term *subspace topology*, but *closed* is simply wrong: it must be *closed in the relative/subspace topology* or *closed in* $B$ (or whatever the subspace in question is). And I have a serious bone to pick with any text that (or instructor who) fails to mention both of the common terms, whichever one then gets used.
Comment: @BrianM.Scott: pick all the bones you want, I'm just saying it happens :) (and yes, I would say "closed in $B$" if I wanted to be precise, but to me that is just using the term "closed" together with a specification of the topology it is closed in) [edit: in fairness, it's possible that someone once told me about "relative" to mean "subspace". But everyone then used "subspace", so I've entirely forgotten the former term if I ever knew it].
Comment: @Ben: The point is that in that setting you *have* to specify the topology, because it's not the default topology. If you just say *closed*, you're saying *closed in the whole space*. I grant that sometimes the context makes it pretty clear that the relative topology is intended, but it's still better to avoid the formal ambiguity — **especially** for beginners!

one-point compatification of $X$


Are static variables with [ThreadStatic] attribute shared between AppDomains

Question: I have a variable named as [ThreadStatic] , will it shared across 2 app domains?
Answer: No. Effectively types in different AppDomains are completely separate types. The static variables are unrelated to each other, whether or not [ThreadStatic] is applied.


Visual Studio Code - Criar vários arquivos ao mesmo tempo

Question: existe alguma maneira de criar multiplos arquivos no visual studio code? por exemplo;
em new file, se eu digitar   Navbar/index.js ele cria a pasta Navbar com o arquivo index.js,
teria alguma sintaxe como, NavBar/{index.js, styles.css}
para criar os dois arquivos ou mais simultaneamente sem necessidade plugins?
Comment: Cara tem uma extensão muito levinha e simples de usar que vai te ajudar, da uma olhada na resposta que deixei mais detalhes e fiz um exemplo simples de como usar... é tão útil e fácil que eu mesmo estou usando agora rss
Answer: Como vc pode ver nesse issue do projeto no GitHub ainda não existe nativamente essa opção no VS Code https://github.com/Microsoft/vscode/issues/310
MAS...... exitem uma extensão que vc consegue fazer isso:

Primeiro vc instala a extensão
Depois de instalada vc da um ctrl+shift+p e clica em "Create File" ou "Create Folder"
Agora vc pode criar seus arquivos, ex: /path/subpath/file1.js > file2.css > file3.html

Link da extensão: https://marketplace.visualstudio.com/items?itemName=ritwickdey.create-file-folder


On a core of the Neumann Laplacian

Question: Let $\Omega$ be a bounded domain of $\mathbb{R}^d$. We define the Sobolev space $H^1(\Omega)$ by
\begin{align*}
H^1(\Omega)=\{f \in L^2(\Omega,m) \mid |\nabla f| \in L^2(\Omega)\}.
\end{align*}
Here, $m$ denotes the Lebesgue measure on $\Omega$, and $\nabla f$ is the distributional gradient of $f$. The Neumann Laplacian $(L,\text{Dom}(L))$ on $\Omega$ is defined as
\begin{align*}
\text{Dom}(L)&=\left\{f \in L^2(\Omega,m) :  H^1(\Omega) \ni g \mapsto \int_{\Omega}\nabla f\cdot \nabla g\,dm \text{ is continuous on $L^2(\Omega,m)$}\right\} \\
-\int_{\Omega}g Lf\,dm&=\int_{\Omega} \nabla f\cdot \nabla g\,dm,\quad f \in \text{Dom}(L),\,g \in H^1(\Omega).
\end{align*}
Question. When $\partial \Omega$ is Lipschitz, we define
\begin{align*}
C=\left\{g \in C^2(\overline{\Omega}) :\frac{\partial g}{\partial n}(x)=0,\quad \sigma\text{-a.e.} \right\}
\end{align*}
Here, we denote by $n$ the inward unit normal vector on $\partial \Omega$, and $\sigma$ is the surface measure on $\partial D$. Can we show that
$\{(g,Lg) \mid g \in C\}$ is a dense subspace of $\{(f,Lf) \mid f \in \text{Dom}(L)\}$ with respect to the $L^2$-norm? This means that $C$ is a core of $(L,\text{Dom}(L))$.
Although this fact should be valid, I do not know the proof.
Please let me know if you have any references.
Comment: Would this follow if you can show that $C$ is dense in $H^1(\Omega)?$ If so the following related question may help: https://math.stackexchange.com/a/3996523/149608.
Answer: What helped me understand how things work with cores is the following consideration:

The set of finite linear combinations of eigenfunctions of a selfadjoint operator (say with compact resolvents, for simplicity) forms a core for the operator.

Now take your question for example. Let $$E=\{e\ : \ e \text{ is a finite linear combination of eigenfunctions of L}\}\subseteq \mathrm{D}(L).$$ Now, $$\{(e,L e) \ : \ e \in E\}$$
is a dense subset of $$\{(f,Lf) \ : \ f \in \mathrm{D}(L)\},$$
because of the density of the eigenfunctions in the domain. In particular, your question is now whether $$E \subseteq C =C^2_\mathrm{neu}(\Omega).$$
Now we have reduced this fairly abstract problem to a very concrete one. Pick any $\lambda\in(-\infty,0]$ (the Laplacian is a negative operator) and suppose that $e_\lambda \in L^2(\Omega), \|e_\lambda\|=1$ solves
$$\Delta e_\lambda = \lambda e_\lambda.$$
What is the regularity of $e_\lambda$?
This kind of question is what Laplacians are build for, and maybe you already know that eigenfunctions are smooth. If not, to see this we can restate the problem as
$$e_\lambda=(-\Delta +1)^{-1}\big( (1-\lambda) e_\lambda\big).$$
Now one can estimate
$$\|e_\lambda\|_{H^2_{\mathrm{neu}}} = \bigg\|(-\Delta +1)^{-1} \big( (1-\lambda) e_\lambda\big)\bigg\|_{H^2_{\mathrm{neu}}} \leq C(1-\lambda) \|e_\lambda\|_{L^2} =C(1-\lambda) ,$$
where the constant $C>0$ depends on how you define the $H^2_{\mathrm{neu}}$ norm (choose your favourite version of Sobolev space). Iterating this inequality you find that $e_\lambda \in H^{2m}_{\mathrm{neu}}$ for any $m\in\mathbb{N}$. Then by Sobolev embedding you find that $e_\lambda \in C^{\infty}_{\mathrm{neu}}(\Omega)\subseteq C$.
A final note: this proof uses a lot of nontrivial tools, such as Sobolev embeddings, spectral decompositions etc.. With it I am not aiming for a simple direct proof (no doubt possible with some approximation via $C^2$ functions), but I hope it gives the idea of what's going on.
Comment: Eigenfunctions of the Neumann Laplacian are in $C^2(\Omega)$ by the Sobolev embedding theorem, as you showed. But why are they in $C^2(\bar \Omega)$? I think that's a more delicate question, where one needs to take the boundary regularity into account.
Comment: The existence of derivatives on the boundary follows from the trace theorem: https://en.wikipedia.org/wiki/Trace_operator#Trace_theorem
Comment: The trace theorem does not imply $H^2(\Omega)\cap C^2(\Omega)\subset C^2(\bar \Omega)$, which you would need to answer my question. For example, let $\Omega=\{x\in \mathbb{R}^d : |x|<1,x_1,\dots,x_d>0\}$. Then $u(x)=|x|^\gamma$ is in $H^2(\Omega)\cap C^2(\Omega)$ if $\gamma>2-\frac{d}{2}$, yet $u$ is not even in $C(\bar \Omega)$ if $\gamma<0$.
Comment: But $e_\lambda \in H^m_{\mathrm{neu}}(\Omega)$ for all $m\in\mathbb{N}$. See the "case $p=\infty$" in the wikipedia page. By the way, I understand your example, but your function does not lie in the \textbf{Banach} space $C^2(\Omega)$ in the sense of the Wikipedia page, and in the sense of my answer (the second derivative blows up at the boundary, so the norm is infinite). It would be more appropriate to replace $C^2(\Omega)$ with $C_{\mathrm{loc}}^2(\Omega)$ in your example.
Comment: @Kore-N Thank you for your comment (sorry for the rate reply). I found your proof using eigenfunctions interesting.

On a core of the Neumann Laplacian


RSQM - polling manually?

Question: We are currently restructuring one of our largest projects. The whole project is set up in an Node.js / PHP mixed envorinment and is quite distributed. This is why we are planning to use queueing for various services. We are extensively using Redis in this system, so I came across RSMQ (http://smrchy.github.io/rsmq/) which I am trying to implement. My question is: How do I actually implement a worker task or similar using this queue?
As far as I understand it, it's quite similiar to SQS without any overhead - which I like, but I am not quite sure how to really get work done with it.
So far my approach (simplified) looks like this:
<code>RQ = require("rsmq");
queue = new RQ( {host: "127.0.0.1", port: 6379, ns: "nDispatch"} );

queue.receiveMessage({qname:"mq"}, function() {
   // code here
});
</code>
But the question is - do I have to poll the queue manually? Is there no message event or similar?
Answer: RSMQ itself does not implement any kind of worker, and ist stripped down to the core functionalities of a queue (which in my opinion is the correct approach).
While you could implement everything yourself of course, I'd recommend using the additional module rsmq-worker (http://smrchy.github.io/rsmq/rsmq-worker/) which provides the basic worker skeleton for your application.
They provide a simple but usable example on their site:
<code>  var RSMQWorker = require( "rsmq-worker" );
  var worker = new RSMQWorker( "myqueue" );

  worker.on( "message", function( msg, next ){
      // process your message
      next()
  });

  // optional error listeners
  worker.on('error', function( err, msg ){
      console.log( "ERROR", err, msg.id );
  });
  worker.on('exceeded', function( msg ){
      console.log( "EXCEEDED", msg.id );
  });
  worker.on('timeout', function( msg ){
      console.log( "TIMEOUT", msg.id, msg.rc );
  });

  worker.start();
</code>
I have used and implemented it this way and it works really well. The worker does the polling for you and offers error events which should be enough to get you going.

RSQM - polling manually?


Determing in a survey which people have likely lied

Question: You have data for each person on their BMI, age, weight, etc... (it doesnt actually matter, just a number of variables on their characteristics).
You then ask people to fill out a survey whether they have diabetes or not, and you know that 20% of them have lied to you.
What are the common techniques to determine which people have lied? Ie whats the good data and bad data.
Comment: How do you know 20% have lied? I think this question needs more context. Presumably you have a model linking diabetes to your predictors? Then look for the people whose answers are most discordant with that model?
Comment: @kjetilbhalvorsen the question says that 20% have lied. I think that the problem is set to have multiple approaches and no necessarily right answer
Comment: @kjetilbhalvorsen like how would you quantify most discordant with your model? how do you know you havent trained your model using false data?
Comment: "The question says that 20% have lied" implies that this is a self-study question.
Comment: how does this question valid the "seek to understand the concepts are welcome" criteria?
Answer: Let $X_i$ denote the covariates for the $i^{th}$ person and let $Y_i$ denote their observed response ($1$ if they say they have diabetes and $0$ otherwise). The true unobserved (latent) responses can be modeled using logistic regression (or something similar).
$$Z_i \stackrel{\text{ind}}{\sim} Bern(p_i)$$
where $p_i = (1+\exp(-\beta X_i))^{-1}.$ The observed responses are then equal to
$$Y_i = \xi_iZ_i + (1-\xi_i)(1-Z_i)$$
where $\xi_i$ is an indicator which is equal to $1$ if they told the truth and $0$ if they told a lie. You also have the constraint
$$\frac{1}{n} \sum_{i=1}^n \xi_i = 0.8.$$
The likelihood function conditional on the latent responses is straightforward
$$L(\beta | Z, X) = \prod_{i=1}^n p_i^{Z_i}(1-p_i)^{1-Z_i},$$
but the likelihood function for the observed data $Y$ is much less straightforward
$$L(\beta | Y, X) = \prod_{i=1}^n \left(p_i^{Y_i}(1-p_i)^{1-Y_i}\right)^{\xi_i}\left(p_i^{1-Y_i}(1-p_i)^{Y_i}\right)^{1-\xi_i}$$ This is exactly the time of problem that the EM algorithm was designed for. I would look into the EM algorithm to try to estimate the model parameters as well as the latent responses. Intuitively however, I would not be surprised if the parameters are unidentifiable, requiring additional modeling assumptions to be made.


Is this approach to solve this probability problem correct?

Question: An urn contains 3 red and 7 black balls. Players $A$ and $B$ withdraw balls from the urn consecutively until a red ball is selected. Find the probability that $A$ selects the red ball. $A$ draws the first ball, then $B$, and so on. There is no replacement of the balls drawn.
Let $A^F$ denote the event that $A$ draws a black ball. Similarly for $B$.
My answer will be $A$ + $A^F.B^F.A$ +...
This is possible as long as the black balls aren't exhausted. I got 4 such terms which I added and my answer is $0.3+0.175+0.0833+0.025=0.5833$
Is this correct?
Is there an easier way to do this?
Comment: 0.3 is correct but it is not correct after that. A gets a second turn only if both A and B fetch black balls in the first round. So, (7/10 x 6/9 x 3/8) will be the second turn similarly calculate till his 4th turn.
Comment: Never mind. My calculation mistake :) then your approach is fine.
Comment: But the term that you wrote (7/10 x 6/9 x 3/8) equals 0.175? I'm confused.
Comment: Okay okay! Thank you!
Answer: Following your method, I compute the probability that $A$ wins on his first turn, $A$ wins on his second turn, etc. to be

$3/10$
$0.175$
$0.08333...$
$0.025$

which agrees with the probabilities you found. The other way you can do this question is to see that this probability is same as the probability that a random arrangement of the 10 balls has the leftmost red ball in an odd-numbered position.
The number of ways to arrange 7 black and 3 red balls is $10 \choose 3$. The number of ways to arrange the balls with the leftmost red ball in an odd position is
$$ {9 \choose 2} + {7 \choose 2} + {5 \choose 2} + {3 \choose 2} = 70 $$
The final answer is then $70 / 120 = 0.58\dot{3}$.
Comment: This is cleaner and less tedious, thanks!


Count data with largely varying sample sizes. Can I get anything from the data?

Question: I only have categorical data, between two groups, with more than three categories per data set.
Here are some actual examples of the data:
Comparing (https://www.strawpoll.me/4380945/r) to (https://www.imdb.com/poll/M43-BGuMniY/results?ref_=po_sr) or (https://strawpoll.de/ygx16fa) to (https://www.imdb.com/poll/T8dGOnA-1ck/results?ref_=po_sr). Alternatively here is a much shorter distribution I threw together:
(I want to compare group 1 to group 2 in the example)

There are 22 of these surveys, half of them representing opinions on movies and half representing opinions on video games. But all of them vary between the samples and some of them have some very small counts at the very bottom of the distribution (some less than 5, but some larger than 1000). All I want to know is if the two groups have different preferences, or have different distributions. Is there any test I can run?
Comment: Forget Yates' correction as a cure for your low expected counts. See my comment about combining the last three categories into one. // Doing the computations by hand or on a calculator may be a bit tedious, but maybe not a waste of time for a beginner. **However,** nothing is stopping you from emulating my R code right now. No need to know "all about" R before using needed parts. (The worst that can happen is that you crash R and have to restart your computer.)
Comment: I'm trying R right now and I'm getting the hang of it. Thank you!
Comment: Glad to hear that! Lots of online tutorials for various procedures in R.
Comment: Would a Yate's correction work for the data less than 5? Then could I report the discrepancy in sample size and say no strong inference should be made?
Answer: In principle, it seems you'd want to use a chi-squared test
to see if the two groups tend to have the same
distribution of category counts.
In practice, sparse
data as in the last few categories of your first
dataset make it impossible to do a 'standard'
chi-squared test. In particular, several expected cell
counts are smaller than five. (Some authors are OK
with a few counts as low as three as long as all the rest
are higher than five---questionable for your first dataset.)
Fortunately, the implementation of chisq.test in R
simulates reasonably accurate P-values for tests in
many such problematic situations. The simulation is OK
for the table as a whole, but if the null hypothesis of
homogeneity is rejected, any ad hoc tests
trying to identify specifically which categories differ
must be limited to categories with higher numbers
of expected counts.
Here is output from chisq.test for your first dataset:
x1 = c(45, 16, 9, 7, 5, 3, 1, 0)
x2 = c(23, 75, 145, 85, 23, 13, 9, 5)
TBL = rbind(x1, x2);  TBL
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
x1   45   16    9    7    5    3    1    0
x2   23   75  145   85   23   13    9    5
chi.out = chisq.test(TBL, sim=T)
chi.out

        Pearson's Chi-squared test
        with simulated p-value
        (based on 2000 replicates)

data:  TBL
X-squared = 127.6, df = NA, p-value = 0.0004998

The simulated P-value is much smaller the 0.05, so
there are highly significant differences among categories
for the two groups.
The chi-squared statistic $Q$ is composed of 16 components
as follows:
$$Q = \sum_{i=1}^2\sum_{j=1}^8 \frac{(X_{ij} - E_{ij})^2}{E_{ij}} = 127.6,$$
where the $X_{ij}$ are observed counts from the contingency table.
chi.out$obs
   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
x1   45   16    9    7    5    3    1    0
x2   23   75  145   85   23   13    9    5

Also, the expected counts, based on the null hypothesis,
are computed in terms of row and column totals from
the contingency table, approximately as follows:
round(chi.out$exp, 2)
   [,1]  [,2]   [,3]  [,4]  [,5]  [,6] [,7] [,8]
x1 12.6 16.87  28.54 17.05  5.19  2.97 1.85 0.93
x2 55.4 74.13 125.46 74.95 22.81 13.03 8.15 4.07

Because of the low expected counts in the last two
categories, the chi-squared statistic does not
necessarily have (even approximately) the distribution
$\mathsf{Chisq}(\nu = (r-1)(c-1) = 7).$ This is the
reason for we needed to simulate the P-value of this test.
[A traditional (pre-simulation) approach might be to
combine the last three categories into one.]
The Pearson residuals are of the form
$R_{ij}=\frac{X_{ij}-E_{ij}}{\sqrt{E_{ij}}}.$
That is, $Q = \sum_{i,j}R_{ij}^2.$ By looking
among the  $R_{ij}$ with largest absolute values,
one can get an idea which categories made the
most important contributions to a $Q$ large enough
to be significant:
round(chi.out$res, 2)
    [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]
x1  9.13 -0.21 -3.66 -2.43 -0.08  0.02 -0.63 -0.96
x2 -4.35  0.10  1.74  1.16  0.04 -0.01  0.30  0.46

So it seems that comparisons involving categories
A, C, and E may be most likely to show significance.
(A superficial look at the original contingency table
shows that these categories have large and discordant
counts.)
In order to avoid false discovery from multiple tests
on the same data, you should use some method of
of choosing significance levels smaller than 5% for
such comparisons. (One possibility is Bonferroni's method; perhaps using 1% instead of 5% levels.)

Addendum: Comparison of Cat A with sum of C&D. Output from Minitab.
This is one possible ad hoc test. It uses
a simple $2 \times 2$ table that you should be able to
compute by hand. You can check your expected values in
the output below.
Data Display

Row  Cat  Gp1  Gp2
  1  A     45   23
  2  C&D   16  130

Chi-Square Test for Association: Cat, Group

Rows: Cat   Columns: Group

         Gp1     Gp2  All

A         45      23   68
       19.38   48.62

C&D       16     130  146
        41.62  104.38

All       61     153  214

Cell Contents:      Count
                    Expected count

Pearson Chi-Square = 69.408, DF = 1, P-Value = 0.000

Very small P-value suggests that Gp 1 prefers Cat A
while Gp 2 prefers Cats B & C.
Comment: I'll be honest, I have just learned about the chi-square test. I'll be learning R in a couple of months but this is honestly beyond me right now. I guess I'll stick to descriptives. Thank you anyways! I appreciate the help!
Comment: See Addendum with _ad hoc_ test on part of first dataset, as suggested in Answer. Output from Minitab. Enjoy.


Is my solution correct for this measure-concentration related task?

Question: I'm reading the book "Concentration inequalities" by Boucheron, Lugosi, Massart. There is an exercise section after each chapter. I've tried to solve one and would like to understand, whether it would be correct proof or not.
The original task is: Let $MZ$ be a median of the square-integrable random variable $Z$ (i.e. $P\{Z\ge MZ\}\ge\frac{1}{2}$ and $P\{Z\le MZ\}\ge\frac{1}{2}$). Show that $|MZ-EZ|\le\sqrt{Var(Z)}$.
So the solution seems to be simple, my idea is to use Chebyshev's inequality in the following way:
$P\{|X-EX|\ge MX-EX\}\le \frac{Var(X)}{(MX-EX)^2}$. At the same time the probability at the lhs of the inequality is not greater than $1$, i.e.$P\{|X-EX|\ge MX-EX\}\le 1$. Using this, we can write $1 \le \frac{Var(X)}{(MX-EX)^2}$, and therefore $|MX-EX|\le\sqrt{Var(X)}$.
Am I missing something? Also, couple of questions:

Why are we told about square-integrability of $X$? Just to confirm that variance of this variable exists, i.e. $\int (X-\mu)^2f(x)dx$ is bounded?
I have not used the fact that $P\{Z\ge MZ\}\ge\frac{1}{2}$, but it seems like I don't need it. Have I missed something?

Thank you.
Answer: Your proof is incorrect, since you are arguing that $a\le b$ and $a\le c$ implies that $b\le c$. By your reasoning you could prove that $\operatorname{Var}(X)\ge M^2$ for every $M$, since it "follows" from the fact that $P(|X-EX|>M)\le \frac{\operatorname{Var}(X)}{M^2}$.
For a hint at proving the stated inequality, you can use the fact that the median minimizes $E|Z-c|$ over all $c$, so in particular choose $c:=E(Z)$:
$$
E|Z-MZ|\le E|Z-E(Z)|\tag1
$$
Now find a way to relate the LHS of (1) to $|E(Z-MZ)|$ and the RHS of (1) to $\operatorname{Var}(Z)$.
The requirement that $Z$ be square-integrable isn't strictly necessary, since the inequality you are proving becomes vacuous if $\operatorname{Var}(Z)=\infty$.

EDIT: Here is a proof that the median minimizes $E|Z-c|$ over all real $c$.
For simplicity, assume the median is zero (consider $Z':=Z-MZ$). Assume first that $c\ge0$. Argue that in this case, $|y-c|-|y|=c$ when $y\le 0$, and $|y-c|-|y|\ge -c$ when $y>0$, so that
$$
E(|Z-c|-|Z|)I(Z\le0)=cP(Z\le0)\tag2$$
and
$$E(|Z-c|-|Z|)I(Z>0)\ge -cP(Z>0).\tag3$$
Add (2) and (3) to obtain
$$E(|Z-c|-|Z|)\ge c\left[ P(Z\le0)-P(Z>0)\right]=c[2P(Z\le0)-1]\ge0,\tag4$$
the last inequality following from the fact $Z$ has median zero. Conclude $E|Z-0|\le E|Z-c|$. The case $c\le0$ can be reduced to the previous case by considering $-Z$ and $-c$.


Como acessar um container dentro de outro container em Jquery?

Question: Estou fazendo uma função para modificar esses grupos de botões, porém não sei como acessar containers dentro de containers com Jquery.

  <button aria-label="Right">Right</button>
  <button aria-label="Left">Left</button>
  <button aria-label="Center">Center</button>
  <button aria-label="Expand">Expand</button>

Consigo acessar esse container com $(selector), porém quero no caso excluir o botão com o aria-label="Expand". Pensei intuitivamente em
$(selector)[0].$("[aria-label=\"Expanded\"]").remove(), porém deu erro de sintaxe. Como faço para acessar um container dentro de outro container em Jquery?
Answer: Tente utilizar da seguinte forma:
$('.buttons').find('[aria-label="Expand"]').remove();

Estamos selecionando todos os filhos da div que contém a classe buttons com o seletor $('.buttons'). Após isso, pedimos para encontrar o elemento que contenha o atributo aria-label="Expand", depois de encontra-lo basta remover com a função remove().
Answer: É bem simples, utilize a estrutura do css

$(document).ready(function(){

$("#resultado").text($('.buttons button[aria-label="Expand"]').attr("aria-label"));
//oque você quer
$('.buttons button[aria-label="Expand"]').remove();
});

  <button aria-label="Right">Right</button>
  <button aria-label="Left">Left</button>
  <button aria-label="Center">Center</button>
  <button aria-label="Expand">Expand</button>


Show that $\frac{X_{n}}{c_{n}}\rightarrow 0$ almost surely

Question: Suppose $X_{n}$ is any sequence of (real-valued) random variables defined on a common probability space $(\Omega,\mathcal{F},\mathbb{P})$. Show that there exists a sequence $c_{n}\rightarrow \infty$ such that  $\frac{X_{n}}{c_{n}}\rightarrow 0$ almost surely. The key is to use the Borel Cantelli lemma, but I am not able to formulate pairwise independent events $A_{n}$ such that $\sum\limits_
{n=1}^{\infty}\mathbb{P}(A_{n})=\infty$ implies $\mathbb{P}(A_{n}~\text{i.o.})=1$, where i.o. stands for infinitely often.
Just a few small hints would be greatly appreciated.
Answer: Use (or reprove) the extended form of Borel Cantelli, which says that if there exists a decreasing sequence $\epsilon_i\rightarrow 0$ such that $\sum_i P(|X_i|>\epsilon_i)<\infty$, then $X_i$ converges to 0 almost surely. You can pick any such sequence $\epsilon_i$, such as $\epsilon_n=1/n$, and then pick a corresponding $c_n$ sequence, that decreases $P(|X_n|>c_n/n)$ sufficiently fast.
Comment: Can you post a link to this extended form pls, I can't find it.
Comment: Thank you so much!! Will try the problem with this.
Answer: First note that if $X_n$ is real valued then
\begin{equation}
\mathbb{P}[X_n=\infty] = 0. \hspace{2cm}(1)
\end{equation}
Let $\{c_n\}$ be an increasing and unbounded sequence $(c_n \nearrow \infty)$. Define $E_n = \Big \{\omega\in \Omega : |X_n(\omega)| > \frac{c_n}{n}\Big\}$. Then, in order to get a contradiction, Suppose that there is no sequence of positive numbers ${c_n}$ such that $$\mathbb{P}[E_n] ≤ 2^{−n},$$
i.e. for every $N\in\mathbb{N}$, setting for a fixed $n$ $$A_N:= \Big \{\omega\in \Omega : |X_n(\omega)| > \frac{N}{n}\Big\}, $$
and $$A_\infty:= \Big \{\omega\in \Omega : |X_n(\omega)| = \infty \Big\},$$
it follows that $$\mathbb{P}[A_{N}] > 2^{-n}.$$
From there, proving that the sequence $\{A_N\}$ is decreasing and $A_\infty = \bigcap_N A_N$, you can show that $\mathbb{P}[A_\infty]>0$ $\hspace{0.3cm}(\longrightarrow\longleftarrow )$ since $(1)$ implies $\mathbb{P}[A_\infty]=0$. Thus, there exists a sequence with characteristics as mention above such that
$\mathbb{P}[E_n] \leq 2^{-n}$.

So, using comparison criterion for series shows that $\sum_{n=1}^\infty \mathbb{P}[E_n] < \infty$, which is all necesary to use     Borel - Cantelli lemma to get $\mathbb{P}[\limsup E_n] = 0$. This implies that
$0 \leq \frac{|X_n|}{c_n} \leq \frac{1}{n} \longrightarrow 0$ almost everywhere $(\omega \notin \limsup E_n)$ having in mind that $\mathbb{P}\Big[\Big(\limsup E_n\Big)^c\ \Big] = 1$, this complete the proof.


P(A) - P(B), do I have to remove the ∅ from the resulting set?

Question: If I have a set $A = \{1, 3\}$ and a set $B = \{2, 4\}$ where $P(A) = \{∅, \{1\}, \{3\}, \{1, 3\}\}$ and $P(A) = \{∅, \{2\}, \{4\}, \{2, 4\}\}$
if I do $P(A) - P(B)$, do I get a set like $\{\{1\}, \{3\}, \{1, 3\}\}$?
This is the original problem, it is the 5.b.
I'm doing practice because I have a test
Comment: Basically your question is "is the empty set which is a subset of $A$ the same empty set which is a subset of $B$?" I'm inclined to say the answer is "yes" assuming that both $A$ and $B$ are understood as subsets of the same outer universe (e.g. $\mathbb{R}$).
Comment: @Ratsiev Here it makes sense to think of them as being in the same universe, be it $\mathbb{R}$ or $\mathbb{N}$ or whatever. Sorry if my remark confused you, your class almost certainly intends for you to think of every $\emptyset$ as the same (as is the case in pure set theory, at the very least).
Comment: In the original problem, it doesn't say if they are on the same universe, now that I read it again
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: Your solution is correct. The empty set that is an element of $\mathcal P(A)$ is the same as the empty set that is the element of $\mathcal P(B)$, so removing all elements of $\mathcal P(B)$ eliminates it from $\mathcal P(A)$ and leaves the rest because there are no other elements shared.


Find all possible values of $\lambda$ which satisfy the given equation.

Question: The question is to find the values of a real number $\lambda$ for which the following equation is satisfied for all real values of $\alpha$ which are not integral multiples of $\pi/2$
$${\sin\lambda\alpha\over \sin\alpha}-{\cos\lambda\alpha\over \cos\alpha}=\lambda-1$$
All I could do was to guess some values that just came to mind by observation, like $-1,1,3$
What should be a more mathematical way to find all possible values of $\lambda$?
SOURCE: KVPY 2015 SB stream
Comment: KVPY 2015 is now over, btw.
Answer: Cross multiplying gives
$$
\sin((\lambda - 1)\alpha) = \frac{(\lambda -1)}{2}\sin(2\alpha) \qquad (\ast)
$$
Since both sides are continuously differentiable (as functions of $\alpha$), we obtain
$$
\cos((\lambda - 1)\alpha) = \cos(2\alpha)
$$
At $\alpha = \pi/4$, we get
$$
\cos((\lambda - 1)\pi/4) = 0
$$
$$
\Rightarrow \lambda -1 \in \{2,-2,6,-6,10,-10, \ldots\}
$$
Also $\lambda = 1$ is clearly a solution to $(\ast)$, so we get
$$
\lambda \in \{1,3,7,11,\ldots\}\cup\{-1,-5,-9,\ldots\}
$$
Comment: Why did you put $\alpha=\pi/4$?
Answer: To validate as an identity for all real $\alpha$
$$
\sin((\lambda - 1)\alpha) = \frac{(\lambda -1)}{2}\sin(2\alpha) \qquad
$$
we are allowed to take small $\alpha$ values  $ \sin x \approx x $
A root as stationary point/ singular solution exists for all  $\alpha$ is obtained as :
$ \lambda - 1=0 , \lambda = 1 $
For other solutions around  this point we have to numerically find roots like for the roots of : $ \tan x = a \cdot x ,$  tangent curve cutting variable slope line.
Shall add to this soon.


Do closure and intersection of open sets commute when composed with the interior?

Question: In the Wikipedia article on the interior operator it is stated that on a complete metric space $X$ one has for every sequence of open sets $(A_i)_{i\in \mathbb N}\subset X$ the relation
$$
\mathrm{Int}\Big(\bigcap_{i}\overline A_i\Big)=\mathrm{Int}\Big(\overline {\bigcap_{i}A_i}\Big).
$$
Now I wonder whether the finite version of this relation, i.e., for any two open sets $A,B\subset X$ to have
$$
\mathrm{Int}\big(\overline A\cap \overline B\big)=\mathrm{Int}\big(\overline {A\cap B}\big),
$$
does actually hold in any topological space $X$. If so, it should be found in some elementary textbooks, perhaps as an exercise. I searched for a while but it turned out that searching for relations like this is extremely inconvenient - one obtains hundreds of results which are similar but different from the wanted relation. On the other hand, I guess that (if the relation holds in general) there should be an easy direct proof based on playing around with the operations interior, closure, intersection, union, and complement. Since I don't have enough time for  this game I'm asking directly for a reference.
Answer: Yes, it's a standard fact used in the theory of so-called regular-open sets (sets such that $\operatorname{int}(\overline{U})=U$; your sets of the form "interior of closure" are regular open..) and forms part of the proof that those sets form a Boolean algebra under the operations $U \land V = U \cap V$, $U \lor V = \operatorname{int}(\overline{U \cup V})$ and $\lnot U = \operatorname{int}U^\complement$. I think Halmos proves it in his Boolean algebra book, and it's also in Engelking somewhere, I'm sure.
As $\overline{A \cap B} \subseteq \overline{A} \cap \overline{B}$, because $A \subseteq \overline{A}$ and likewise for $B$, so $\overline{A} \cap \overline{B}$ is a closed superset of $A \cap B$, so it contains $\overline{A \cap B}$ too. Taking interior on both sides gives the easy inclusion (we don't need anything on $A$,$B$):
$$\operatorname{int}(\overline{A \cap B})\subseteq \operatorname{int}(\overline{A} \cap \overline{B})$$
For the reverse inclusion we can use a small lemma that for an open $U$ and any $A$ we have $\overline{U \cap A} = \overline{U \cap \overline{A}}$. Think about it.
Answer: Here is a proof of the other direction.
It suffices to show that $\operatorname{int}(\overline{A}\cap\overline{B})\subseteq \overline{A\cap B}$, because $\operatorname{int}(\overline{A}\cap\overline{B})$ is open, so if it's a subset of some set, it's a subset of the interior of it.
Since $\overline{A\cap B}=\overline{A\cap\overline{B}}$, it suffices to show $\operatorname{int}(\overline{A}\cap\overline{B})\subseteq \overline{A\cap\overline{B}}$.
Let $x\in\operatorname{int}(\overline{A}\cap\overline{B})$.  Let $W$ be an open neighborhood of $x$.  Then so is $V=W\cap\operatorname{int}(\overline{A}\cap\overline{B})$.  Since $x\in\overline{A}$, there exists some $y\in V\cap A$.  Since $V\subseteq \overline{B}$ then $y\in V\cap A\cap\overline{B}\subseteq W\cap A\cap\overline{B}$.  This was for an arbitrary open neighborhood $W$ of $x$ - proving that $x\in \overline{A\cap\overline{B}}$.
To show $\overline{A\cap B}=\overline{A\cap\overline{B}}$, let $U$ be an open set.  If $U\cap A\cap B\ne\emptyset$ then certainly $U\cap A\cap\overline{B}\ne\emptyset$.  Conversely, if $U\cap A\cap\overline{B}\ne\emptyset$, let $t\in U\cap A\cap\overline{B}$.  Since $U\cap A$ is an open neighborhood of $t$ and $t\in\overline{B}$ then $U\cap A\cap B\ne\emptyset$.  We've shown that $U\cap A\cap B\ne\emptyset$ iff $U\cap A\cap\overline{B}\ne\emptyset$ for any open set $U$.  This proves that $\overline{A\cap B}=\overline{A\cap\overline{B}}$.


How to unittest every class with the same public API in a module with python?

Question: I have a module which parses different file formats like CSV, XLS, HTML, etc.
The different formats contains exactly the same information, so I made different classes for parsing different file types. These classes have the exact same public API, and obviously have the same base class like this:
class BaseParser(object):
    def countTotalValues(self):
        pass

    def countItems(self):
        pass

class CSVParser(BaseParser):
    def __init__(self):
        """Init data, check for errors, etc.."""

    def parse(self):
        """ parses the data and set the result dictionaries like self.values, self.items, etc."""

class XLSParser(BaseParser):
    """ Ha exactly the same public API as CSVParser and set the same inner values. """
    pass

Is it a good idea to unit test each of the classes at once with the same values ?
I have been doing this:
class TestParserClasses(unittest.TestCase):
    def setUp(self):
        self.instances = []
        for class_, file_ in PARSER_CLASSES:
            self.instances.append(class_(file_))

    def tearDown(self):
        del self.instances

and define every unit test this way:
    def test_count_total_values_without_parameter(self):
        for parser in self.instances:
            parser.parse()
            self.assertEqual(Decimal('9216.84'), parser.countTotalValues())

    def test_count_items_without_parameter(self):
        for parser in self.instances:
            parser.parse()
            self.assertEqual(128, parser.countItems())

Is it okay to do this? If yes, how to unit test all of them with the same TestCases at once without
    for parser in self.instances:
        parser.parse()

So I want to write unittest like this:
def test_count_total_values_without_parameter(self):
    self.assertEqual(Decimal('9216.84'), parser.countTotalValues())

def test_count_items_without_parameter(self):
    self.assertEqual(128, parser.countItems())

applied to every class. Is it possible ?
Comment: This seems more or less similar to http://stackoverflow.com/questions/16305985/unit-test-suite-in-python. To answer your question if you should test multiple implementations in one test, I'd say no, because this doesn't give you the info which of them failed and which didn't.
Answer: Have you considered creating a base TestCase and subclassing it for each of the classes you wish to test?
Create it like this, containing your actual test methods, and keep it in a separate module that does not match the test module pattern (by default, test*.py) so unittest won't discover it:
import unittest

class BaseTestCase(unittest.TestCase):
    def test_count_total_values_without_parameter(self):
        self.assertEqual(Decimal('9216.84'), self.parser.countTotalValues())

    # …more tests…

Now, in your test modules, do something like this:
import basetest

class TestCSVParser(basetest.BaseTestCase):
    def setUp(self):
        self.parser = CSVParser()

class TestXLSParser(basetest.BaseTestCase):
    def setUp(self):
        self.parser = XLSParser()

Comment: @Walkman Thank you, but I would suggest going ahead and writing up your own answer with your preferred solution and accepting it.  There are definitely multiple ways to do this one.
Comment: This will run three tests: `BaseTestCase.test_count...`, `TestCSVParser.test_count...` and `TestXLSParser.test_count...`, because `BaseTestCase` will be autodetected as testcase in and of itself. The simple remedy is to write a mixin class with the `test_count_...` function and use multiple inheritance from both `unittest.TestCase` and `baseTestCase`.
Comment: @UlrichEckhardt That was why I kept `BaseTestCase` in a separate module. I created a simpler version of this to verify before making my post and `python -m unittest discover` did not pick up the `basetest` module; only the child testcases in the `test` module were picked up, since it matches the `test*.py` glob (see http://docs.python.org/2/library/unittest.html#test-discovery)
Comment: With @UlrichEckhardt's suggestion, this is great !
Comment: I updated the answer with @UlrichEckhardt 's suggestion and will accept it if you approve my edit.
Comment: Sorry zigg, you are right and I should have read the whole thing completely.
Comment: Ulrich I like your solution better, as this would be in the same file,  giving better overview of the test at a first glance, so if you write an answer with it, I accept that.
Comment: Actually, I would like to see a solution where everything is in *one* file where `BaseTestCase` subclasses `unittest.TestCase` (because my IDE can help me with autocomplete assert.Equal, etc methods) and the other classes subclasses `BaseTestCase` but `BaseTestCase` will not be tested (as it's not really complete without `setUp`. Can you provide me an example to this ? That would be the perfect solution for me :)


Alinhamento de campos no bootstrap

Question: Boa noite. Em uma das páginas do meu site, mudei a posição dos campos input para que ficassem ao lado das labels, originalmente era assim: http://tratspay.com/app/editar-produto.html . Após a minha modificação ficou assim: http://tratspay.com/app/editar-produto-teste.html porém os campos ficaram desalinhados como podem ver, gostaria de saber como alinhá-los.
Answer: O que acontece é que por padrão a label do Bootstrap tem um margin-bottom: .5rem;. Vc tem que remover esse margin-bottom para o label alinhar com o input corretamente como vc pode ver na imagem abaixo:
Com a margem padrão

Removendo a margem padão

Minha sugestão é que vc coloque no label a classe nativa m-0, essa classe vai zerar o margin-bottom da label
Comment: Bom dia, Hugo. Mais uma vez, obrigado pela força! Na verdade as labels já estão do jeito que eu quero, o que eu quero alinhar são os forms. Só consigo editar todos de uma vez? Não dá pra editar cada um individualmente de forma que todos fiquem alinhados?
Comment: @IgorRosa acho que não entendi bem o que vc quer dizer com esse alinhamento o que vc quer alinhar aonde mais precisamente? Achei que vc queria alinhar a label verticalmente com o input....
Comment: Acho que não estou sabendo explicar direito rs. A label com os nomes já estão alinhadas com os campos ao lado, porém, cada campo de inserção de dados está de um tamanho diferente, deixando uma estética esquisita no site, eu gostaria de deixar esses campos do mesmo tamanho. Se você observar na página que estou editando: http://tratspay.com/app/editar-produto-teste.html, dá pra visualizar o que estou tentando explciar.
Answer: Boa tarde meu caro, eu poderia te ajudar bastante você me autoriza lhe enviar um layout melhorado?
Esta comentendo alguns erros o uso de table já não é mais boa pratica a muito tempo
Posso te ajudar mostrando como seu codigo pode ficar mais curto e mais responsivo, posso ajudalo vai me demandar uns 30 minutos?
Acabei fazendo aqui bem rapido essa atualização olhei seu layout e essa estrutura que fiz pode te resolver todos esses problemas, analise e ve se lhe cabe bem, alem de estar em boa pratica fica um pouco mais limpo de ver o codigo em si.
Deixei o fundo azul para destacar bem essa propriedade eh a classe bg-prymary de resto pode colocar tudo direto que vai alinhar como você pretende !

    <form>

          ID de Produto:

            <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="123451234">

          Key de Integração:

            <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="123445123">

          Tipo de Produto:

            <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="Produto Físico">

          Tipo de de Cobrança:

            <input type="text" readonly class="form-control-plaintext" id="staticEmail" value="Produto Físico">

          Nome do Produto :

            <input type="text" class="form-control" id="nomeProduto" placeholder="Nome do Produto :">

            Descrição do Produto:

                <input type="text" class="form-control" id="descProduto" placeholder="Descrição do Produto :">

            Email de Suporte :

                <input type="text" class="form-control" id="emailSuporte" placeholder="Email de Suporte :">

            Valor

                <input type="text" class="form-control" id="valor" placeholder="0,00">

            Categoria

                <input type="text" class="form-control" id="categoria" placeholder="Categoria">

            Quantidade Máxima Por Compra :

                <input type="text" class="form-control" id="qnt_max" placeholder="0,00">
                Limite de Produtos que um clliente pode fazer na mesma compra.

            Produto entre via:

                <input type="text" class="form-control" id="via" placeholder="Produto entre via:">

      </form>

O layout que te enviei vai se ajustar a tela e a qualuquer resolução q vc colocar.
Espero ter ajudado e qualquer tipo de dúvida me chame
Comment: Sua intenção é nobre, mas isso não responde a pergunta. Além do mas caso ele esteja planejando enviar esse documento por email ou controlar melhor uma impressão, o mais indicado é a tabela mesmo. Logo vc vai ter uns pontos e vai poder comentar nas perguntas. Não use o campo de resposta para fazer comentários.
Comment: Ops hugo desculpe acabei fazendo e enviando antes de ver seu comentario, mas tomei alguns cuidado espero poder ajudar abraço
Comment: Da forma que o Henrique explicou deu certo em partes aqui, consegui alinhar os campos mas bugou o conteúdo das abas, o conteúdo da segunda aba ficou misturado com o do primeiro.

Alinhamento de campos no bootstrap


APP_URL do .env registar URL inteira (além do dominio) da aplicação

Question: Tenho um servidor com um dominio onde existem varias aplicações Laravel, pro exemplo, o caminho da aplicação1 fica assim: https://dominio.com/aplicacao1/public
O problema é que quando boto no APP_URL=https://dominio.com/aplicacao1/public o app_url só gera as rotas com o dominio, por exemplo se eu gerar url('foo/bar') o link vai ficar https://dominio.com/foo/bar (desconsiderando o caminho da aplicação - aplicacao1/public)...
Alguem já viu este problema?
Comment: Isso te ajuda amigo? https://pt.stackoverflow.com/questions/57830/laravel-5-remover-public-da-url
Answer: É possível que você tenha que criar subdomínios pra cada aplicação.
Ex: https://aplicacao1.dominio.com.br
https://aplicacao2.dominio.com.br
Comment: Seria uma solução, mas no caso não da pra ser assim pq são varias aplicações de pessoas diferentes e não é em uma hospedagem "profissional", daria muito trabalho fazer subdominios para todas as aplicações...


Generated random samples of dependent ratios

Question: The question is simple, however I am stuck:
I am trying to generate samples of ratios of "detections" vs "non-detections":
Say I counted 10 stars, and I could detect 8 stars. My detection ratio thus is 8/10.
Since this is a counting experiment, I would have naively assumed that both are Poisson variables and I can simply generate:
sample_classified = np.random.poisson(8, size=100)
sample_total      = np.random.poisson(10, size=100)

ratio = sample_classified/sample_total

this than can give me ratios that are greater than one, if the sample_classified > sample_total. That is however not logical since I can't have more classified stars as than there are in total.
The drawn samples should reflect that the ratio 8/10 is determined from an experiment, i.e. their histogram should peak at that value.
What is the correct PDF to sample from in that case?
Comment: You have to assume a true average detection probability, and make an assumption about whether the detection of each individual star is an independent Bernoulli trial.
Comment: This question might be more suited to stackoverflow.
Answer: I think I would do a sort of hierarchical model, like this:

First, choose the denominator via a Poisson distribution:

array_length = 100
sample_total = np.random.poisson(10, size=array_length)

Next, loop through sample_total and choose a binomially-distributed integer from $0$ to the total:

# Pre-allocate array for speed.
binomial_probability = 0.8
sample_classified = np.zeros(array_length, dtype=np.int64)
for i in range(array_length):
    limit = sample_total[i]
    sample_classified[i] = np.random.binomial(limit, binomial_probability)

This assumes a binomial distribution for the number of classified stars, once the Poisson total has been determined. Only you can tell us if that's a good assumption. But this code guarantees that, for each total, the number of classified stars will be less than or equal to the total.
Comment: You need to get our of your head the notion that "able to count" means Poisson. That just isn't true. What you're saying indicates binomial with $p=0.8.$ I will adjust my answer accordingly.
Comment: Sure! If you say "expected values", then you are implying an underlying distribution - otherwise you can't compute an expected value. Which distribution does the detected stars come from?
Comment: Dear Adrian, I will specify my question in a second. However, this is not want I want to do. The number of detected stars (8) and the number of total star are expected values. So my samples should include that "knowledge".
Comment: I count them, thus I would have assumed that they too are Poisson distributed?
Comment: Not sure I follow you, there. I could just as easily count the numbers in a discrete uniform distribution such as I used above. The Poisson distribution is particularly good for predicting how many events will occur at a particular time, when in a small time interval, the probabilities are equal. So I could definitely see using Poisson for the sample totals. But here's the problem: you have a hard cutoff, as you've mentioned, that says you can't classify more stars than the total. The Poisson does not act like that, and so it is unsuitable for that distribution.
Comment: Here's perhaps another way of thinking about it: given a particular total of stars, how many of them would you expect to be able to classify or detect? I would say your main options are binomial, hypergeometric, or discrete uniform. jwimberly has hinted that perhaps binomial would be the right distribution. In that case, you would need to decide what the probability of detecting a single star is (your $p$ parameter).
Comment: If I have a given total amount of stars I would expect to have:
0.8=8/10
If I had 20 total stars, that expected ratio should still be 0.8. But I am wondering what the shape of that distribution is, since both numbers are "counted", i.e. poisson


how to store data into the database and generate the sum using codeigniter

Question: I create this form, and when I press the save button, the number of calculations from each row will appear in the column nilai. And I want to store each column in the database.
and heres the code:
<?php foreach ($siswa as $row){

                    echo "
  $row->nis
                                ".  strtoupper($row->nama)."
                                <input type='int' id='tugas_1".$row->nis."' value='".  chek_tugas1($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='tugas_2".$row->nis."' value='".  chek_tugas2($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='tugas_3".$row->nis."' value='".  chek_tugas3($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='tugas_4".$row->nis."' value='".  chek_tugas4($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='nilai_akhir".$row->nis."' value='' class='form-control'>
";
                }
            ?>

Comment: Note that a database table is not a spreadsheet. Seriously consider normalising your schema.
Answer: If save button is form submit event, consider to do the operation on the server-side. Otherwise, just call every function at the  iteration and sum them up.
<?php foreach ($siswa as $row){

                    echo "
  $row->nis
                                ".  strtoupper($row->nama)."
                                <input type='int' id='tugas_1".$row->nis."' value='".  chek_tugas1($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='tugas_2".$row->nis."' value='".  chek_tugas2($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='tugas_3".$row->nis."' value='".  chek_tugas3($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='tugas_4".$row->nis."' value='".  chek_tugas4($row->nis, $this->uri->segment(3))."' class='form-control'>
                                <input type='int' id='nilai_akhir".$row->nis."' value='".(chek_tugas1($row->nis, $this->uri->segment(3))+chek_tugas2($row->nis, $this->uri->segment(3))+chek_tugas3($row->nis, $this->uri->segment(3))+chek_tugas4($row->nis, $this->uri->segment(3)))."' class='form-control'>
";
                }
            ?>


Open a specific View node with a link in an image

Question: I'm stumped. I'm not even sure how to ask the right questions to search out an answer.
What I have is a View of User Account images in a gallery. So far so good. I have another view of all User Account fields data presented as a node. So far so good there as well.
I want to click on the User Image in the gallery and go directly to that User's node in the other view.
The problem is not with attaching a URL to an image, but enabling sequential URLs to call the correct View node.
I feel like I'm missing some organizational overview understanding here. Maybe it's simple and I'm a doof.
Thanks for any insight.
Answer: From what I gather there are two possible approaches to this:

Either add a field for Link and then "Rewrite Results" to the content by referencing the node_id. Or do the rewrite on the image itself to the appropriate node_id. You might have to massage the urls for the other View or find a pattern to make this work.
Add a relationship to the gallery view to the Node that contains the UA fields. Add this relationship to the image field and then work it that way.

Hope this helps!


What are best practices for creating node relationships?

Question: In Drupal 7, what are the best ways of creating relations between nodes?
Say I have a number of articles about famous writers. I want to build an alphabetical list of them using Views. As writers often have pseudonyms, I want these pseudonyms to appear in the list too but creating a node for a pseudonym that is identical to its respective Writer node in all aspects except title sounds like not quite good idea.
I thought a bit and came up with 2 node types, Writer and Writer_Pseudonym:

Writer

Title
Body
All other fields

Writer_Pseudonym

Title
Target Node Id

Now I want to build a view in which nodes of type Writer_Pseudonym will display body text of their target nodes:

Title: Doe, John (Writer)
Body: John Doe, also known as Evil John, is a writer that became famous after creating an autobiographical novel "Foobar".
Title: Evil John (Writer_Pseudonym)
Body: John Doe, also known as Evil John, is a writer that became famous after creating an autobiographical novel "Foobar".

Is it possible to do it with Views? And if not, are there any other ways to establish relations between nodes while being able to use fields of target nodes?
Comment: How well does this example relate to your actual use case? Because the best relationship solution depends on the size, complexity, and frequency of said types and relations.
Comment: @Merrick I'd say this example relates to the actual use case quite well. I need these "pseudonyms" for only one node type, they are not very frequent (probably one in 7-10 nodes needs a "pseudonym") and "pseudonym" needs to load no more than a couple of fields from its target node.
Answer: Your best bet for this kind relationship is going to be Taxonomy. You can create a free tagging vocabulary (exactly like the vocab that is initialized with the Article content type in a standard profile D7 install) and as these "Authors" come up with a need for a "Pseudonym" you just tag that node with it's term.
Views supports most every use case (if not all) you can imagine working with Taxonomy.
Because Taxonomy is core it's further developed and easier to use than alternative relationships (references, hierarchy, etc).
For the above example, you'd could configure the view to display all (full, teaser) or part (fields) of the "Author" content type based on being tagged with the relative "Pseudonym". Views are a little daunting at first but if you keep playing with them, you'll soon realize their immense capability.
Just comment if you need clarification on any of the above...


OLS with Lagged DV

Question: I am interested in building an OLS model with a lagged (lag 1) DV as a right-side explanatory variable. This is relatively straightforward in R, however my problem is the rest of the data. I have six separate data frames of countries that each measure the same three variables of interest (lets say: Y, $X_1$, $X_2$), and these dataframes fall into one of two categories (1 or 2).
It has been suggested to me that I pool all of these countries together into one model and include a dummy variable as opposed to running a model on each dataframe. However, I am unclear as to how to pool the time series data in such a way that maintains the structure (i.e., maintaining the categories of  each country). It seems that any configuration will involve multiple variables for each country and not at all what has been suggested.
Is it best to add the variables data together and simply have one summed column of data per category per variable? Or, is it the case that the only data that needs to be in time-series format is the DV and the other data ($X_1$ and $X_2$) can be in non-time-series format?
Answer: When you pool data like this you still treat each one data point as one data point in the pooled data; it is best not to aggregate results at this early stage since that involves a loss of information.  You should be able to obtain a pooled data frame for your countries using some simple manipulations of data frames in R.  If you already have six data frames each containing three columns of the same variables, all you need to do is to add a Country column to each data frame and then use rbind to bind the rows together in a single data frame.  Here is an example of how to do this:
#I will assume you have six data frames called DF1-DF6
#I will take the column names to be VarY, Var1 & Var2

#Add Country variable to each data frame
#Countries used here are just an example
DF1$Country <- rep('USA',     nrow(DF1));
DF2$Country <- rep('England', nrow(DF2));
DF3$Country <- rep('France',  nrow(DF3));
DF4$Country <- rep('Canada',  nrow(DF4));
DF5$Country <- rep('Germany', nrow(DF5));
DF6$Country <- rep('Spain',   nrow(DF6));

#Create pooled data frame DF and convert Country to a factor variable
DF <- do.call("rbind", list(DF1, DF2, DF3, DF4, DF5, DF6));
DF$Country <- factor(DF$Country);

OLS with Lagged DV


Summing up an ArrayList with multiple types

Question: I am having trouble summing up my ArrayList that I made in my class Treasureroom which is in my class Accountant. I have an ArrayList with type Valuable as you can see in the code below. I need to be able to sum up all the int elements from within the Accountant class.
Accountant
package Accountant;
import java.util.Iterator;
import java.util.Random;

import ValuableFactory.Valuable;
import rw.RWMonitor;
import rw.Treasureroom;

public class Accountant implements Runnable {
    private Treasureroom treasureroom;
    private static final int MAX_WAIT_TIME = 10000; // 3 seconds
    private static final int MAX_WORK_TIME = 5000; // 2 seconds

    private static final Random random = new Random();
    private int no;
    private RWMonitor monitor;
    private Treasureroom resource;

    public Accountant( int no, RWMonitor monitor, Treasureroom resource ) {
        this.no = no;
        this.monitor = monitor;
        this.resource = resource;
    }

    public void run() {
        while(true) {
            try {
                Thread.sleep(random.nextInt(WAIT_TIME));
            }
            catch (InterruptedException ex) {
            }

            System.out.println("Accountant counts: " + resource);

            monitor.acquireRead();

            //System.out.println("Accountant counted: " + valuable);

            try {
                Thread.sleep(random.nextInt(MAX_WAIT_TIME));
            }
            catch (InterruptedException ex) {
            }

            for (int i = 0; i > resource.)
                System.out.println("Accountant counted: " + resource.getValueRead());

            monitor.releaseRead();

            try {
                Thread.sleep(random.nextInt(WAIT_AGAIN));
            }
            catch (InterruptedException ex) {
                // TODO: handle exception
            }
        }
    }

 //System.out.println("The total sum of TreasureRoom is " + Thread.currentThread().getName());
 //TreasureRoom.releaseRead();

}

Treasureroom
package rw;

import java.util.*;
import ValuableFactory.*;

public class Treasureroom {
    ArrayList<Valuable> valuables = new ArrayList<Valuable>();

    public Valuable getValueWriter() {
        return valuables.remove(0);
    }

    public void updateValue(Valuable valuable) {
        valuables.add(valuable);
    }

    public boolean removeValue(Valuable valuable) {
        return valuables.remove(valuable);
    }

    public Valuable getValueReade() {
        for (int i=0; i<valuables.size();i++) {
            return valuables.get(i);
        }
        return null;
    }
}

Valuable
package ValuableFactory;

public class Valuable implements ValuableFactory {
    private String name;
    private int value;

    public Valuable(String name, int value) {
        this.name = name;
        this.value = value;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int getValue() {
        return value;
    }
}

Comment: `valuables.stream().mapToInt(Valuable::getValue).sum()`
Comment: But where do you put it, because i can not call the ArrayList in the "Accountant" class
Comment: What is your `getValueReade()` method in `Treasureroom` supposed to do? It will always return the first `Valuable` in the room or `null` if it's empty.
Answer: Your Accountant class instantiates your Treasureroom object in its constructor, meaning that to loop through the ArrayList inside the Treasureroom object using an Accountant object you would need a method in Accountant that calls a method in Treasureroom.
Accountant
public int getTreasureSum()
{
    return resource.sumTreasure();
}

Treasureroom
public int sumTreasure()
{
    int sum = 0;

        for(int i = 0; i < valuables.size(); i++)
        {
            sum+= valuables.get(i).getValue();
        }

    return sum;
}

Also in your Accountant class you have an unused Treasureroom object
private Treasureroom treasureroom;


Examples of strongly convex loss functions

Question: This is a reference request.
Strong convexity of the loss function is often used in theoretical analyses of convex optimisation for machine learning. My question is, are there important / widely used loss functions (or cost functions) being used in machine learning in practice? I know of the logistic loss for classification, and the square loss for regression. Are there any others?
Answer: Another example is Hinge loss used in SVM.
Related post
Also, L1 related loss: least absolute loss.
Combination between L1 and L2 regularization (https://en.wikipedia.org/wiki/Elastic_net_regularization).


Cannot read matched of undefined when using router file

Question: So I have a simple router file, that imports different routes for different parts of my website, so:
general.js (one of my route files)
import Home from '../../components/home/home'

const routes = [{
    name: 'home',
    path: '/',
    component: Home
}]

export default routes

router.js
import Vue from 'vue'
import Router from 'vue-router'
import GeneralRoutes from './general'

Vue.use(Router)

const routes = Array.prototype.concat(
    GeneralRoutes
)

const router = new Router({
    mode: 'history',
    routes
})

router.beforeEach((to, from, next) => {
    if (to.meta.requiresAuth) {
        next({replace: true, name: 'login'})
    }
    next()
})

export default router

That is my router, now in my app.js, I simply use it like so:
import Vue from 'vue'
import Router from './core/routes/router'

new Vue({
    el: '#app',

    data: () => ({
        user: ''
    }),

    Router,
});

But this is throwing an error saying the following:

[Vue warn]: Error in render: "TypeError: Cannot read property
  'matched' of undefined"

When I console.log the router, I get the following:
Answer: router is lowercase
import Vue from 'vue'
import Router from './core/routes/router'

new Vue({
    el: '#app',
    data: () => ({
        user: ''
    }),
    router: Router
});


How to (re)send email from a file using mutt or mail?

Question: I have set up exim4 to deliver a copy of all outgoing mails to a local maildir in case something goes wrong. Now something's gone wrong and I need to resend some of the mail from the local maildir.
The emails have their full headers (inc. Return-Path, To, From, Subject etc.) and body (MIME).
Is there a way to do this:
$ somemailcommand <theemail

and have it make a new attempt to deliver it?
I've tried mutt -H theemail which looked promising (although it starts an interactive UI) but the emails came through blank.
I've tried mail email@example.com <theemail but that just sent the headers in the body. I'm on Debian Linux.
Answer: You can use bounce function (default bound to b key) to resend message and keep original headers.
To do so:

a) bounce single message

just press b

b) bounce multiple messages

tag messages you want using t or T<PATTERN> (see patterns in mutt manual)

then ;b then You'll be asked to fill e-mail address
Bounce tagged messages to:
Comment: Thanks, it's the "from a file" bit I'm stuck on. I am not using mutt as an email account client, I just want to use it's sending features. Is this method available if the email is in a stand-alone file (and not in an inbox somewhere)?
Comment: Doesn't work if you would like to bounce to all people included initially in the Cc list (need to copy'n'paste manually all those addresses). Any better option? Seems `Esc` + `e` does the trick.
Answer: sendmail -t < messagefile
This command extract To: from email file, and send mail to it.


Evaluate the volume of $A_r=\{(x,y,z): x^2+y^2+z^2\le r^2; x^2+y^2+z^2\le 2zr \}$

Question:
Evaluate the volume of
  $$A_r=\{(x,y,z): x^2+y^2+z^2\le r^2;\, x^2+y^2+z^2\le 2zr \}.$$

I use spherical coordinates so i found $\theta \in [0,\pi], \phi \in [0,2\pi]$ but for $\rho $ i have two choise: $ \rho \le r$ or $\rho \le 2r \cos \theta$. Have I to divide the range of $\theta$ ?
$$\int_{0}^{2\pi} \int_{0}^{\pi/3} \int_{0}^{r} {\rho}^2 \sin \theta\dots+\int_{0}^{2 \pi} \int_{\pi/3}^{\pi} \int_{0}^{2r\cos \theta}....?$$
Comment: In the second integral the range of $\theta$ is from $\pi/3$ to $\pi/2$ (not $\pi$). See my answer below.
Answer: Hint. The inequality $x^2+y^2+z^2\le 2zr$ can be written as
$$x^2+y^2+(z-r)^2\leq r^2.$$ Therefore $A_r$ is the intersection of two balls of radius $r$: one is centered at $(0,0,0)$ and the other at $(0,0,r)$.
In spherical coordinates  you need to split the evaluation into two parts:
$$V=\int_{0}^{2\pi} \int_{0}^{\pi/3} \int_{0}^{r} {\rho}^2 \sin \theta  d\rho d\theta d\phi
+\int_{0}^{2 \pi} \int_{\pi/3}^{\pi/2} \int_{0}^{2r\cos \theta}{\rho}^2 \sin \theta d\rho d\theta d\phi.$$
Note that in your formula, in the second integral, the range of $\theta$ is from $\pi/3$ to $\pi/2$ (not $\pi$).
We may also use cylindrical coordinates:
$$V=\int_{\rho=0}^{\sqrt{3}r/2}\left(
\int_{z=r-\sqrt{r^2-\rho^2}}^{z=\sqrt{r^2-\rho^2}}\left(\int_{\theta=0}^{2\pi}d\theta\right) dz\right)\rho d\rho.$$
Comment: The result is $(5/12) \pi r^3$?
Comment: @Wauzl Thank you for pointing out!
Comment: @GiuliaB. Yes, the result is correct!! Did you try also the cylindrical coordinates? Any further doubt?
Comment: if I want calculate $\int_{A_r} z^2 dx dy dz $ do I use cylindrical coordinates?
Comment: @GiuliaB. You can use both cylindrical and spherical coordinates.
Comment: The result is $(\pi/6) r^4$?
Comment: I calculate $(5/48) \pi r^5$.Is it right?
Comment: @GiuliaB. My result is different...
Comment: What do you have?
Comment: The integrale is the same  of V but i integrate the function$\rho^4 (\cos\theta)^2 (\sin\theta) $ in both integrals
Comment: Fine. So, edit your question by adding the new integral $\int_{A_r} z^2 dx dy dz$ and write a couple of steps of your evaluation.
Comment: I have the sum of two  integrals: the result of first is $ (7/60)\pi r^5$
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/69155/discussion-between-robert-z-and-giulia-b).


\Drupal::database()->select with Expression used as Condition

Question: I am trying to execute this query:
<code>'SELECT sd.entity_id AS entity_id, WEEK(node__field_start_date.field_start_date_value) AS week, YEAR(node__field_start_date.field_start_date_value) AS year
FROM
{node__field_start_date} sd
INNER JOIN {node__field_plane_reservation} pr ON sd.entity_id = pr.entity_id
WHERE (sd.bundle = :db_condition_placeholder_0) AND (pr.field_plane_reservation_target_id = :db_condition_placeholder_1) AND (week = :db_condition_placeholder_2) AND (year = :db_condition_placeholder_3)'
</code>
And I am using this piece of code:
<code>    $database = \Drupal::database();
    $query = $database->select('node__field_start_date', 'sd')
  ->fields('sd', ['entity_id']);

    // Expressions
    $query->addExpression('WEEK(sd.field_start_date_value)', 'week');
    $query->addExpression('YEAR(sd.field_start_date_value)', 'year');

    // Conditions
    $query
  ->condition('sd.bundle', 'reservation', '=')
  ->condition('pr.field_plane_reservation_target_id', $refPlane, '=')
  ->condition('week', $weekNo, '=')
  ->condition('year', $weekYr, '=');

    // Join Tables
    $query->join('node__field_plane_reservation', 'pr', 'sd.entity_id = pr.entity_id');
</code>
And whenever I execute it, it give me the error:
Unknown Column 'week' in query or Unknown column 'year'.
How do I use a condition with a pseudo column created with an expression?
Answer: <code> // Where Expressions
    $query->where('WEEK(sd.field_start_date_value) = :weekNo', array(':weekNo' => $weekNo));
    $query->where('WEEK(sd.field_start_date_value) = :weekYr', array(':weekYr' => $weekYr));
</code>
Apparently this can be achieved with $query->where();


Unable to merge two Eloquent collections

Question: I have a table named messages in my database and, it has five columns as:
id | sender_id | receiver_id | message | sent_at

And, in my model User, I have a function that looks like this:
    public function messages(){

      $sent_messages = $this->hasMany(Message::class, "sender_id");

      $received_messages = $this->hasMany(Message::class, "receiver_id");

      $messages = $sent_messages->merge($received_messages);

      return $messages;

    }

I opined that it would work but it didn't. The error I get is:
BadMethodCallException with message 'Call to undefined method Illuminate/Database/Query/Builder::merge()'

So, what did I do wrong and what can I do to get all the messages if its either sent by me or received by me?
Comment: please refer, i hope this will helpful https://stackoverflow.com/questions/24184069/laravel-merge-relationships
Answer: In order to have a Collection you must use the ->get() method. Otherwise you have the relation objects and you can't merge them ;)


Python 3x - Error: "object" is no defined em lista

Question: estou aprendendo a programar em python e estou com esse seguinte problema em um exercício. Ao rodar o código acontece este seguinte erro:
vogal = (a,e,i,o,u)
NameError: name 'a' is not defined.

Ja tentei resolver digitando alguns outros códigos, escrevendo o mesmo código de outras formas e mesmo assim continuo com o erro.
    vogal = [a,e,i,o,u]

    letra = input("Digite uma letra: ")

    if letra in vogal:

    print('esta letra é uma vogal')

else:

print('esta letra não é uma vogal')

Comment: Se a intenção era que a,e,i,o,u fossem strings, valores literais, coloque os mesmos entre aspas: ```vogal = ["a","e","i","o","u"]```
Comment: Opa, deu certo, muito obrigado, não tinha prestado atenção neste pequeno detalhe. acabei achando que era um problema mais complicado mas não. Abraços
Answer: O correto seria:
vogal = ('a','e','i','o','u')

O motivo é que, em Python (e em linguagens de programação no geral), quando você deseja utilizar uma string ela deve ser digitada entre aspas.
Sem utilizar as aspas a palavra digitada será entendida como uma variável, e não existe variável a declarada no seu código.

Python 3x - Error: “object” is no defined em lista


Can't find the conf directory in Hadoop

Question: I'd like to install Hadoop on an EC2 instance running Ubuntu 16.04 (for learning purposes). I'm trying to follow the instructions on https://hadoop.apache.org/docs/r1.2.1/single_node_setup.html. I'm at the step

In the distribution, edit the file conf/hadoop-env.sh to define at least JAVA_HOME to be the root of your Java installation.

I've downloaded the 3.0.0-beta1 version as a binary (using wget http://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.0.0-beta1/hadoop-3.0.0-beta1.tar.gz followed by a tar xzf of that file). However, I don't see any conf directory in the directory thus extracted:
ubuntu@ip-172-31-83-170:~/hadoop-3.0.0-beta1$ ls
bin  include  libexec      NOTICE.txt  sbin
etc  lib      LICENSE.txt  README.txt  share

Did I do something wrong?
Answer: It would appear that this question is answered in Hadoop release missing /conf directory. The place to look is /etc/hadoop:
ubuntu@ip-172-31-83-170:~/hadoop-3.0.0-beta1/etc/hadoop$ ls
capacity-scheduler.xml            kms-log4j.properties
configuration.xsl                 kms-site.xml
container-executor.cfg            log4j.properties
core-site.xml                     mapred-env.cmd
hadoop-env.cmd                    mapred-env.sh
hadoop-env.sh                     mapred-queues.xml.template
hadoop-metrics2.properties        mapred-site.xml
hadoop-policy.xml                 shellprofile.d
hadoop-user-functions.sh.example  ssl-client.xml.example
hdfs-site.xml                     ssl-server.xml.example
httpfs-env.sh                     user_ec_policies.xml.template
httpfs-log4j.properties           workers
httpfs-signature.secret           yarn-env.cmd
httpfs-site.xml                   yarn-env.sh
kms-acls.xml                      yarn-site.xml
kms-env.sh

This contains the hadoop-env.sh file referred to in the instructions.
Comment: You should also use the Single Node Setup from the same release.  http://hadoop.apache.org/docs/r3.0.0-beta1/hadoop-project-dist/hadoop-common/SingleCluster.html
Answer: The configuration folder is in your ${HADOOP_HOME}/etc/hadoop
Where ${HADOOP_HOME} is your hadoop installation directory

Can't find the conf directory in Hadoop