How to change the style of the tab in android tabhost?

Question: I want to change the style of the tab in android tabhost, I don't want to change the color of background only, but the whole style ( to make rounded corners for example) .
Answer: In TabHost you can put a Button or any other widget with a preferred style, even with rounded corners
Button myButton = new Button(this);
myButton.setText("My Button");
myButton.setBackgroundColor(Color.TRANSPARENT);
myButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.my_button_drawable_top, 0, 0);
TabHost.TabSpec myButtonTab = mTabHost.newTabSpec("tab1").setIndicator(myButton).setContent(intentPlayList);
mTabHost.addTab(myButtonTab);


Area rate and circumference of an ellipse

Question: For a circle with radius $r$, we have $\frac{dA}{dr}=\frac{d}{dr}\pi r^2=2\pi r=C$. But for an ellipse with $a=r$ and $b=2r$, $\frac{dA}{dr}=\frac{d}{dr}2\pi r^2=4\pi r\ne C$. Shouldn't the area of the ellipse change by its circumference?
Comment: As you are taking the values of a and b accurately. It is not the case. Also you can't find accurately the perimeter of an ellipse. I think the main reason is this.
Answer: The reason why $\frac{dA}{dr}=C$ works for the circle is that (loosely speaking) increasing the radius by $dr$ adds a "stripe" of constant "width" around the circle, therefore the added area is (at the limit) proportional to $dr$. This does not happen for an ellipse, however, where the "stripe" becomes thicker around the endpoints of the longer axis, as can be seen in the drawings below.

For the full math behind this intuition, see for example this answer to Why is the derivative of a circle's area its perimeter (and similarly for spheres)?.
Answer: I recommend the article by J. Tong, Area and perimeter, volume and surface area, College Math. J. 28 (1) (1997) 57. He shows that for any region where the area can be written as $A(s)=cs^2$ and the perimeter as $L(s)=ks$, you can set $x=(2c/k)s$, and you will get $A′(x)=L(x)$. That means that by careful parametrization, the above holds for rectangles and ellipses, too.


PHP quote within 2 different quotes

Question: I have a problem with quotes. I can't use " or ' for $gname. What can I do for this.
$new_post = array( 'post_content' => ' ..CODES.. $result = mysqli_query($con,"SELECT * FROM wp_games WHERE name = $gname "); ..CODES..
I'm trying to create a post on wordpress.I have a plugin to use php on posts. [insert_php] is this plugin. And I also can't use quote like \" ... \" .Here is more code.
$new_post = array(
'post_content' => '[insert_php]$con=mysqli_connect("localhost","root","","wordpress");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
 $result = mysqli_query($con,"SELECT * FROM wp_games WHERE name = '$gname' ");
while($row = mysqli_fetch_assoc($result)) {
echo $row["name"];
}

mysqli_close($con);
[/insert_php]',

Comment: That is broken on so many levels - very messy and prone to rampant PHP and/or SQL injection. In any case, see [PHP strings](http://php.net/manual/en/language.types.string.php) for how quotes can be escaped in a PHP-string context. (Where, like a bad remake of Inception, the inner string literal is two levels deep..)
Comment: Post your actual code, I don't help to answer pseudos, it just keeps us guessing till the cows come home.
Comment: http://stackoverflow.com/help/how-to-ask
Comment: Also, "I have a plugin to use php on posts" <- please don't do that, either; it sounds like a recipe for disaster. Wordpress has enough security holes of its own without making it even easier to `eval()` code.
Answer: You can create a single quote using chr(39) and append it to the string. You should also escape the contents of $gname
mysqli_query($con,"SELECT * FROM wp_games WHERE name = " . chr(39) . mysqli_real_escape_string($con, $gname) . chr(39));

Comment: The problem is there is a single quote after post_content and a double quote in mysqli_query. So I can't use any quote for $gname.
Comment: @NaimBerkTumer I updated my code with a workaround to get single quotes into the string without using the single-quote character.

PHP quote within 2 different quotes


How to set text in the middle of secondary tile WP 8.1

Question: I am trying to create a secondary tile that will display a string in it. I am building the app for windows phone 8.1. I have the following code for the tile but I would like the text in the center of the app:
SecondaryTile("TestTile",
               numDays + " days",
               tileActivationArguments,
               blankPic,
               TileSize.Square150x150);

Is there a way to accomplish this or to build an image from the text to display?
Solution:
XAML
<Grid x:Name="TextGrid" Width="150" Height="150" Background="Red">
    <TextBlock x:Name="numDay" FontSize="36" />
</Grid>

C#
NumDay.Text = numDays + " days"
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(TextGrid);

I used this code to create my image and then set it as background picture in SecondaryTile.
Comment: If you want any more control over the content, then you need to render image and use it for tile.
Comment: Can you point me to a direction of how to accomplish this?
Comment: http://stackoverflow.com/questions/20107640/set-secondary-tile-backgroundimage-from-image-in-isolated-storage
Answer: Creating custom tile with image is rougly done in these steps:
1) Render your image. WriteableBitmap class can render UIElement you pass to it:
            WriteableBitmap wb = new WriteableBitmap(300, 300);

            wb.Render(myGrid);

            wb.Invalidate();

So you need to construct your tile from UI elements like container + controls. In your case it would be for example Grid (with max width) and aligned TextBlocks
2) Once you have this image, save it as PNG (for better quality) into folder

"isostore:/Shared/ShellContent/"

otherwise your tile cannot access it.
3) Now all you need to do is create StandardTileData and set BackgroundImage to your newly created image.
You can also download and use IsoStoreSpy while debugging. It can show you your phone's internal storage. So you can see whether and how the image been rendered.
Comment: wb.Render wasn't valid for wp 8.1 But this pointed me to the right direction. I used `RenderTargetBitmap.RenderAsync(grid)` Thanks @Filip


How to not display redundant information in table Views?

Question: In a custom module of mine (Drupal 8.2.6), I have two custom entities A and B with a one to many relationship from A to B.
I use Views (table view) to display content of A and B and by default I get this:
Field1 (from A) Field2 (from B)
xxx aaa
yyy bbb
yyy ccc
zzz ddd
I'd like to NOT display yyy the second time.
How can I do that?
[Edit] just an example, instead of what is (by default) on the left, I'd like what is on the right of the picture:
Comment: What exactly you want instead of yyy bbb, yyy ccc?Those two results are different (result, row in your table, is Field1 AND Field2), that is why there are both of them. From Views point of view, there is no redundancy there.
Comment: I'd like the "redundant" information (i.e. yyy in my example) to be blank.
See the example I added to my question.
Answer: You can try Views Field View module.

Create a "secondary" view of Field2 contextualy filtered by
relationship with EntityA.
In your main view, use Field1 and new Views Field of your "secondary" view (this field type is added by module).
Set up that new Views Field in your view to pass proper argument to "secondary" view contextual filter (and therefore show relevant Field2s related to EntityA)
Answer: Finally I found another solution using Rewrite Results.
Depending on another field (which can be hidden), I output 'nothing' or 'the content':


format decimal by specifying a particular format

Question: Is there a way to format a number in python like below:
DecimalFormat("00000.00000").format(getSettlmentPrice()).replace(".", "")

This is how it is done in java.
Comment: could you provide an example input and expected output
Comment: input is some float like .8333 or 1.55 and the output should be like 00000.83330 or 00001.55000.                                                                    It should be always 10 digits with 5 before decimal and 5 after.
Answer: print "%11.5f" % settlementPrice

The format is for total width (including the decimal point), then the number of decimal places to keep.  See format


Como cria um menu "ocultável"?

Question: Tenho um Toolbar, e quero fazer uma barra de configurações nela. Porém, para que não ocupe espaço, gostaria que fosse possível ocultar/minimizá-lo, algo parecido com o chat do teamviewer.
Meu ToolBar (esta dentro de uma tela principal)
Container contentPane = this.getContentPane();
contentPane.add(toolBar, BorderLayout.SOUTH);
toolBar.setFloatable(false);// não deixa ToolBar mudar de lugar.
JLabel label = new JLabel("  Configurações   ");
toolBar.add(label);
toolBar.add(botaoConfig);
botaoConfig.addActionListener(this);
botaoConfig.setPreferredSize(new Dimension(30, 30));

Vou colocar uma ilustração para ajudar no entedimento:

Exemplo bem resumido:
package testes;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToolBar;

public class TelaSistema extends JFrame implements ActionListener {

    public JDesktopPane jdp = new JDesktopPane();
    public JMenuBar jmb = new JMenuBar();
    public JMenu jmCadastros = new JMenu("Cadastros");
    public JMenuItem jmiEstado = new JMenuItem("Estado");
    JToolBar toolBar = new JToolBar();
    JButton botaoConfig = new JButton("Config");

    public TelaSistema() {

        Container contentPane = this.getContentPane();
        contentPane.add(toolBar, BorderLayout.EAST);
        toolBar.setFloatable(false);// não deixa ToolBar mudar de lugar.
        JLabel label = new JLabel("  Configurações   ");
        toolBar.add(label);
        toolBar.add(botaoConfig);
        botaoConfig.addActionListener(this);
        botaoConfig.setPreferredSize(new Dimension(30, 30));
        toolBar.setBackground(new Color(230, 230, 230));

        // setSize(800, 600);
        setExtendedState(MAXIMIZED_BOTH);
        setTitle("Sistema");
        getContentPane().add(jdp);
        setJMenuBar(jmb);
        jmb.add(jmCadastros);
        adicionaJMenuItem(jmCadastros, jmiEstado);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void adicionaJMenuItem(JMenu menu, JMenuItem item) {
        menu.add(item);
        item.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {

    }
    public static void main(String[] args)
    {
        TelaSistema tela = new TelaSistema();
    }

}

Comment: Tem como adicionar um **[mcve]** dessa sua tela com a barra?
Comment: Olá acredito que a sua dúvida é a mesma que essa: http://stackoverflow.com/questions/31601900/javafx-how-to-create-slide-in-animation-effect-for-a-pane-inside-a-transparent
Comment: @Phrxn essa pergunta é sobre javafx, a solução lá dificilmente vai servir para essa,
Answer: O mais próximo que consegui fazer para simular esta barra foi utilizar do recurso de zerar a largura da JToolBar toda vez que o botão fosse clicado.
Para controlar melhor quando contrair e quando expandir, substitui o Jbutton por um JToggleButton,  pois este possui 2 estados(selecionado e não selecionado), bastando apenas alterar a largura da toolbar conforme o estado deste componente.
Para usar, basta instanciar a classe abaixo como um JPanel, passando seu JToolBar como parâmetro, e em seguida, adicionar na sua tela:
    JPanel barPanel = new ToolBarPanel(toolBar);
    contentPane.add(barPanel, BorderLayout.EAST);

Segue a classe ToolBarPanel:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

/**
*
* @author diego.felipe
*/

public class ToolBarPanel extends JPanel implements ItemListener {

    private final JComponent barComponent;
    private final int prefwitdh;
    private final int MINIMUM_WIDTH = 0;
    private JToggleButton botaoConfig = new JToggleButton(">>");

    public ToolBarPanel(JComponent toolBar) {
        this.barComponent = toolBar;
        this.prefwitdh = barComponent.getPreferredSize().width;
        this.setLayout(new BorderLayout());

        botaoConfig.addItemListener(this);
        botaoConfig.setPreferredSize(new Dimension(30, 30));
        botaoConfig.setMargin(new Insets(0, 0, 0, 0));
        botaoConfig.setFocusable(false);

        this.add(botaoConfig, BorderLayout.WEST);
        this.add(toolBar, BorderLayout.CENTER);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {

            barComponent.setPreferredSize(new Dimension(MINIMUM_WIDTH, 0));
            ((AbstractButton) e.getSource()).setText("<<");

        } else if (e.getStateChange() == ItemEvent.DESELECTED) {

            barComponent.setPreferredSize(new Dimension(prefwitdh, 0));
            ((AbstractButton) e.getSource()).setText(">>");

        }
        revalidate();
    }
}

Veja em funcionamento no seu código:

Do jeito que está, ele reduz o toolbar a largura 0, mas caso você queira que, mesmo minimizado, seja exibido um tamanho minimo maior que zero, basta alterar o atributo MINIMUM_WIDTH para o tamanho desejado.
Comment: Era isso mesmo ! Muito Obrigado.

Como cria um menu "ocultável"?


Radius of curvature and continuous functions

Question: Let $\kappa (x)$ be radius of curvature function for a continuous function $f(x)$.
Is it necessary that $\kappa(x)$ will have extrema when $f(x)$ does. And the nature of extrema is opposite to that of $f(x)$
$ $
That means If $f(x)$ has maxima, then $\kappa (x)$ has a minima.
$ $
Following link contains a graph :
https://www.desmos.com/calculator/ps9wp1ykzm
$f(x)$ is the black curve.
If you know any other noteworthy property about $\kappa(x)$ do point out. I am trying to understand $\kappa(x)$ functions.
Comment: What is $\kappa(x)$?
Comment: I mentioned in the heading
Comment: Took the liberty of transporting that information to the body of the question.
Answer: You say "radius of curvature", but the expression reported in the link is based on the "curvature" that is $1/R$.
The formula for the (signed) curvature is
$$
\kappa(x)=\frac{f''(x)}{\{1+[f'(x)]^2\}^{3/2}}
$$
so that
$$
\kappa'(x)=\frac{f'''(x)\{1+[f'(x)]^2\}-3f'(x)[f''(x)]^2}{\{1+[f'(x)]^2\}^{5/2}}
$$
and as you can see it does not vanish, in general, when $f'(x)=0$.
Also in your case, $f'(x)=0$ in $0$ and $\pm 1$, while $\kappa'(x)=0$ in $0$ and in two point $x\approx\pm1.01444$.
Answer: Take a curve whose radius of curvature increases monotonically as you move along it, such as a logarithmic spiral.
Orient it such that it is horizontal at some point $P$.
In some neighborhood of $P$ the curve will be the graph of a function.
This function has an extremum at $P$, but (by our initial choice) its radius of curvature keeps increasing past $P$, and so in particular doesn't have an extremum there.


Finding coefficient of a function

Question:
Consider the generating function   $g(x)=\frac{(1+x)(x^2+x^3+x^4+x^5)^2}{(1-x)^4}$
Determinate the coefficient of $x^{15}$

First of all I'm very new in Discrete Mathemathics, I'm taking this subject for the first  time. I got some exercises from my teacher and I'm trying to do them. I have no idea how to start on this type of problem. Any help would be great. Thanks in advance.
Comment: You could start by considering what are the ways to obtain $15$ summing integers.
Answer: HINT
If you have a sequence $A = (a_n)_{n \in \mathbb{N}}$, the function
$$
G(x) = \sum_{n=0}^\infty a_n x^n
$$
is called the generating function for the sequence $A$.
You are looking for the coefficient of $x^{15}$ in $g(x)$ you are given. Construct its MacLaurin series, and you will get the coefficient.
It will help to know a couple useful generating functions, e.g.
$$
\frac{1}{1-x} = \sum_{n=0}^\infty x^n
$$
Answer: Hint...You could start by extracting the factor $x^2$ and simplifying the expression, so that you are looking for the coefficient of $x^{13}$ in the expansion of $$\frac{(1+x)^3(1+x^2)^2}{(1-x)^4}$$
So now you have seven terms to find and add up...
Comment: How did you get to that expression? How did you extract $x^2$?
Comment: Yes and I simplified the larger bracketed term using the formula for the sum of a geometric series

Finding coefficient of a function


GridView Sorting without AJAX?

Question: I'm trying to enable sorting for my gridview without AJAX, and having difficulty because when I call sorting it is running PageLoad again and never fires the Sorting event.
Any guides on how I do GridView sorting without AJAX?
Answer: If you are using jQuery there is a plug-in:  http://tablesorter.com
Comment: Thanks the the link, I will save it!

Due to my odd list of requirements, I have to work within very specific versions of .net without use of AJAX or JQuery.

I did manage to find a solution though :) thanks anyway!

GridView Sorting without AJAX?


Probability that there are at least two consecutive heads

Question: Please check my approach for this probability problem

Suppose I have a fair, two-sided coin. If I roll it $5$ times, what is the probability that there are at least two consecutive heads?

Please check my approach:
There are $2^5=32$ possible situations. Now, I want to find the probability that there are no consecutive heads, and subtract that from $1$.
Now, I can't have $4$ or $5$ heads, because there is a guarantee that there will be at least one set of consecutive heads.
For $3$ heads, there is only one possibility I can think of, $HTHTH$.
For $2$ heads, if my first head lands first, then my second head could land third, fourth, or fifth. If heads #1 lands second, them my second could land fourth or fifth, and if the first heads lands third, the second can land fifth, so we have $6$ possibilities.
For $1$ head, it can land anywhere, so there are $5$ possibilities.
Computing the probability, we get $6+5+1=12$ possibilities with NO consecutive heads, so the probability that we get no consecutive heads is $\frac{12}{32}=\frac38$, so the probability we DO get consecutive heads is $\boxed{5/8}$.
Am I doing this correctly? If so, is there a better way to do this? If not, what went wrong?
Answer: Good job. You almost got it all. You forgot the possibility of getting $0$ heads,  the answer should be $1-\frac{13}{32}=\frac{19}{32}$.
Here's another approach.
Suppose we roll the coin $n$ times, what is the number of configuration such that there are no consecutive heads? let the number of such configuration be $f(n)$.

The configuration can start with a tail, then follow by $n-1$ tosses with no consecutive heads.
The configuration can also start with a head and then tail, then followed by $n-2$ tosses with no consecutive heads.

$$f(n)=f(n-1)+f(n-2)$$
Note that  $f(1)=2$, $f(2)=3$.
Hence, we have a shifted Fibonacci sequence.
$$f(n)=\frac{(1+\sqrt5)^{n+2}-(1-\sqrt5)^{n+2}}{2^{n+2}\cdot \sqrt5}$$
The probability that you are looking for is
$$1-\frac{f(n)}{2^n}=1-\frac{(1+\sqrt5)^{n+2}-(1-\sqrt5)^{n+2}}{2^{2n+2}\cdot \sqrt5}$$
For your problem, we can quickly look up for the $7$-th Fibonacci number.
$$1,1,2,3,5,8,13.$$
Hence the answer should be $$1-\frac{13}{32}=\frac{19}{32}$$
Answer: Directly:
$$\begin{align}&P(HH***)+\\
&P(THH**)+\\
&P(TTHH*)+P(HTHH*)+\\
&P(TTTHH)+P(THTHH)+P(HTTHH)=\\
&\frac1{4}+\frac18+\frac2{16}+\frac3{32}=\frac{19}{32}.\\
\end{align}$$
Answer: As an alternative approach, model the sequence of flips as an absorbing Markov process with transition matrix $$P=\begin{bmatrix}\frac12&\frac12&0\\\frac12&0&\frac12\\0&0&1\end{bmatrix}.$$ The third, absorbing state corresponds to getting two heads in a row. We're looking for $\Pr(X_5=3 \mid X_0=1)$, which is just the $(1,3)$ entry of $P^5$. It's not a terrible amount of work to compute $$P^5 = \begin{bmatrix}\frac14&\frac5{32}&\frac{19}{32}\\\frac5{32}&\frac3{32}&\frac34\\0&0&1\end{bmatrix}$$ (the last row never changes, so you can omit quite a few multiplications) which gives the probability as $\frac{19}{32}$.


LINQ Group By com múltiplos campos

Question: Estou tentando retornar campos após uma junção entre coleções, mas estou obtendo o seguinte erro:

foreach statement cannot operate on variables of type
  'AnonymousType#1' because 'AnonymousType#1' does not contain a public
  definition for 'GetEnumerator'

var lst = from p in Produto.produtos
        join c in Produto.categorias
        on p.IdCategoria equals c.IdCategoria
        group p by new { c.IdCategoria, c.Categoria }
            into g
            orderby g.Key.Categoria
            select new { ID = g.Key.IdCategoria, CategoriaNome = g.Key.Categoria, TotalItem = g.Count() };

foreach (var categ in lst)
{
    Console.WriteLine("ID: {0}, Categoria: {1}, Total Item: {2}", categ.ID, categ.CategoriaNome, categ.TotalItem);
    foreach (var item in categ)
    {
        Console.WriteLine("\t\tID: {0}, Produto: {1}", item.IdProduto, item.Produto); // Linha com o Erro
    }
}

Comment: Melhorei minha resposta. Veja agora se te atende.
Answer: Isto devolve List<n'>, em que n' é um tipo anônimo:
var lst = from p in Produto.produtos
        join c in Produto.categorias
        on p.IdCategoria equals c.IdCategoria
        group p by new { c.IdCategoria, c.Categoria }
            into g
            orderby g.Key.Categoria
            select new { ID = g.Key.IdCategoria, CategoriaNome = g.Key.Categoria, TotalItem = g.Count() };

Isto itera sobre List<n'>:
foreach (var categ in lst)
{ ... }

E isto você tenta iterar sobre n' que não é "iterável":
foreach (var item in categ)
{ ... }

Portanto, o erro.

EDIT
Segundo seu comentário na outra resposta, você quer agrupar por categorias. Portanto, modifique sua sentença para:
var lst = from p in Produto.produtos
    join c in Produto.categorias
    on p.IdCategoria equals c.IdCategoria
    group p by new { c.IdCategoria, c.Categoria }
        into g
        orderby g.Key.Categoria;

O primeiro foreach fica assim:
foreach (var categ in lst)
{
    Console.WriteLine("ID: {0}, Categoria: {1}, Total Item: {2}", categ.Key.IdCategoria, categ.Key.Categoria, categ.Count());
    ...

O segundo fica igual:
foreach (var item in categ)
{
    Console.WriteLine("\t\tID: {0}, Produto: {1}", item.IdProduto, item.Produto);
}

Comment: Normalmente quando vejo questões sobre tipos anônimos, vejo a turma usando `dynamic`. Obrigado pela sugestão. Já alterei.
Comment: De nada :) Na verdade, as duas coisas são bem distintas. Com tipos anónimos, mantemos *static typing*, ou seja, só podemos aceder a propriedades/métodos que realmente existam. Se tentarmos um acesso inválido, o compilador não vai deixar fazer build, ex: `var a = new { str = "uma string" }; a.propriedadeInvalida;`
Comment: Com `dynamic`, todos os acessos a essa variável vão ser compilados dinamicamente *quando o programa for corrido*. Ou seja, se houver algum erro no código, so vamos saber quando a excepção for lançada. O código pode ter 15 erros, mas vai compilar na mesma.
Comment: Esse código nao envolve `dynamic` de todo. O resultado da primeira query é uma `List`, em que `n'` é um tipo anonimo.
Answer: Vamos mudar tudo.
var lstCategorias = (from p in Produto.categorias select p).ToList();
foreach (var categoria in lstCategorias)
{
     var lstProdutos = (from p in Produto.produtos where p.IdCategoria=categoria.ID select p).ToList();
    Console.WriteLine("ID: {0}, Categoria: {1}, Total Item: {2}", categoria.ID, categoria.CategoriaNome, lstProdutos.Count);
    foreach (var item in lstProdutos)
    {
        Console.WriteLine("\t\tID: {0}, Produto: {1}", item.IdProduto, item.Produto); // Linha com o Erro
    }
}

Explicando:
Obtendo as categorias
var lstCategorias = (from p in Produto.categorias select p).ToList();

Iterando com foreach
foreach (var categoria in lstCategorias)

Filtrando os Produtos da categoria dentro do foreach
var lstProdutos = (from p in Produto.produtos where p.IdCategoria=categoria.ID select p).ToList();

Imprimindo o resultado
Console.WriteLine("ID: {0}, Categoria: {1}, Total Item: {2}", categoria.ID,
categoria.CategoriaNome, lstProdutos.Count);

Novo foreach para listar os produtos da categoria
foreach (var item in lstProdutos)
{
    Console.WriteLine("\t\tID: {0}, Produto: {1}", item.IdProduto, item.Produto); // Linha com o Erro

Comment: O ideal é você explicar sua resposta, para entendermos melhor.
Comment: Cigano, não deu certo. Ele dá erro com a mesma mensagem só que agora no segundo Foreach:    foreach (var item in categ)
    {
        Console.WriteLine("\t\tID: {0}, Produto: {1}", item.IdProduto, item.Produto); // Linha com o Erro
    }
Comment: @KellySoares Esta resposta não é minha. Aliás, não sei qual o seu objetivo. Seria legal você editar sua resposta e explicar o objetivo pra que eu possa melhorar a resposta.
Comment: Eu quero listar os grupos de categoria no primeiro FOREACH e no segundo quero listar os produtos que fazem parte deste grupo.
Comment: Tá dificil hein brothen...
Comment: Vou fazer outro tópico com uma estrutura aproximada.

LINQ Group By com múltiplos campos


Grafana graph hover list shows data point from previous date

Question: When you create a line chart in grafana you can hover the line to see the data points exact values. However if a metric for a specific time is null it gets the first metric from a previous date.

I'm asking myself: Am I doing something wrong, or is this just how grafana works.
How can I change this behaviour so I only show the data in the hover tooltip from the date that is actually hovered.
Answer: well, i think this is how it works. why do you want that? maybe you can use alternative ways
Answer: The issue is your using the connected option to handle your null values which enables the toot tip to snap to the closest previous value (or only value in time range).
Click edit on your panel and go to visualization settings. Under Stacking & Null value options change Null value from connected to null.
The go down to the legend options and under Hide series enable the option to hide null values in series (With only nulls).
The tool tip will now show no data values for series that don't have data at a time. The tradeoff is now your series won't be connected and the will be gaps in the visualization.


Accessing Views inside fragment

Question: I'm having troubles accessing the Views that within my Fragment. In the example below, I can't access the 2nd button that is within the Fragment (e.g., findViewById appears to return NULL and the app crashes when I try b2.setText("test") ), but when I directly add it in the activity_main.xml, it does work.
Here is the code:
MainActivity.java
public class MainActivity extends Activity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button fragmentButton = (Button)findViewById(R.id.iMainButton);

    FragmentManager fm = getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.iMainInnerLLContainer, new TestFragment());
    ft.commit();

    final Button b2 = (Button)findViewById(R.id.iTestFragmentInnerButton);
    if(b2 == null) { Log.d("MainActivity.java:", "b2 is null"); }
    else { Log.d("MainActivity.java:", "b2 is NOT null"); }

    fragmentButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // do stuff here
        }
    });
}

}

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/iMainRootLinearLayoutContainer"
android:orientation="vertical"
>

<Button
    android:id="@+id/iMainButton"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="Add fragment..."
/>

<LinearLayout
    android:id="@+id/iMainInnerLLContainer"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:orientation="vertical"
>

</LinearLayout>

</LinearLayout>

TestFragment.java
public class TestFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.ltestfragment, container, false);
}
}

ltestfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/iTestFragmentOuterLinearLayout"
>

<Button
    android:id="@+id/iTestFragmentInnerButton"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="This is my test fragment button."
/>
</LinearLayout>

I think I'm missing something very basic here and I would appreciate some insight on what that might be.
Thank you in advance!
Comment: Hmm, this is getting weirder: I got it to work by adding the fragment to an actual  tag. However, shouldn't it work just the same when adding a fragment to a ViewGroup?
Answer: I think you need to set up a textchangelistener in your fragment.
public class FragmentA extends Fragment {

TextChangeListener listener;

public interface TextChangeListener {
    public void onTextChange(CharSequence newText);
}

public void setTextChangeListener(TextChangeListener listener) {
    this.listener = listener;
}

Then, in your activity, set up the listener :
public class ActivityAB extends FragmentActivity {

FragmentA fragmentA;
FragmentB fragmentB;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ab);

    FragmentManager manager = getSupportFragmentManager();
    fragmentA = (FragmentA) manager.findFragmentById(R.id.fragmentA);
    fragmentB = (FragmentB) manager.findFragmentById(R.id.fragmentB);

    fragmentA.setTextChangeListener(new TextChangeListener() {

        @Override
        public void onTextChange(CharSequence newText) {
            fragmentB.updateTextValue(newText);
        }
    });
}

}
Comment: I'm sorry, I don't know how to implement what you are suggesting in my example. There is no text in it and you use _findFragmentById_, which I don't think I can even use because I'm not using a  container (so which id would I use?). Plus, I thought I should generally be able to access the elements of my activity.
Comment: I've tried some more to get your code to work for my example above, but I fail at this line: [ fragmentA = (FragmentA) manager.findFragmentById(R.id.fragmentA); ] ... which was my problem from the beginning - I can't find my Views/Fragments and therefore don't even get to set up the ChangeListener.
Answer: Implement an interface to listen to the events of a fragment from its activity.
Code in Fragment:-
   public class TestFragment extends Fragment
   {
       public interface OnClickListener
       {
            public void onButtonClicked(<data type><data>);
       }

       b2.setOnClickListener(new OnClickListener() {
       @Override
            public void onClick(View v) {
            listener.onButtonClicked(<<pass some values here>>);
            }
       });
   }

Code in Main:-
   MainActivity extends FragmentActivity implements TestFragment.OnClickListener,
   {
        @Override
        public void onButtonClicked(<<receive the pased data here>>) {

        //do some stuff here with the received data after the button is clicked
    }
   }

Comment: I tried to get this to work, but this line is the crux of the matter that I can't solve: [ _b2.setOnClickListener(new OnClickListener()_ ]. Where and how to get b2, especially in the fragment?
Comment: //in the createView method add this line                                                                b2 = (Button) view.findViewById(R.id.iTestFragmentInnerButton);

Accessing Views inside fragment


Invalid or corupt jarfile

Question: I tried to create a jar file from a java project, which uses some external jars. I created a lib folder and put all the jars I need there.
I run the project in eclipse by adding all the jars in the lib folder to the Build Path and it works ok.
When I try to create the jar with ant from build.xml, it seems ok, no error is shown.
When I try to run the jar, I get the message "Invalid or corupt jarfile".
In build.xml:
I define the path to use for compiling:
<path id="project.classpath">
     <fileset dir="${lib}">
         <include name="**/*.jar"/>
     </fileset>
</path>

This is the target for the compilation:
<target name="compile" depends="init" description="compile the source " >

    <javac srcdir="${src}" destdir="${build}">
          <classpath refid="project.classpath"/>
    </javac>
</target>

And this is the target for making the jar file:
<target name="dist" depends="compile" description="generate the distribution" >
      <mkdir dir="${dist}"/>

      <jar jarfile="${dist}/MyProject-${DSTAMP}.jar" basedir="${build}">
          <manifest>
            <attribute name="Main-Class" value="${main}" />
            <attribute name="Class-Path:" value="lib/**/*.*"/>
          </manifest>
          <fileset dir="${src}" includes="images/**/*.*" />
       </jar>
       <echo file="${dist}/start.bat" message="java -jar MyProject-${DSTAMP}.jar" />
  </target>

Can you please tell me what have I done wrong?
Answer: First remove the colon after Class-Path: to match
<attribute name="Class-Path" value="lib/**/*.*"/>

Then I suggest reading
HOWTO Create MANIFEST.MF Classpath From Ant or better using Manifestclasspath
Comment: It worked with the manifestclasspath. The problem was indeed that the jar names were way too long than the 72 characters allowed.
Comment: Lines in MANIFEST.MF are wrappable.   I too think the culprit is the extra colon.
Comment: +1 for the Manifestclasspath.  Haven't looked at the new goodies since 1.6.2, so this is a nice addition.
Answer: I don't think your Class-Path attribute should have a trailing colon specified in your build.xml.
Try using
jar tvf {jarname}

from the command line, and see if that can expand your jar file, and whether it contains what you expect (the above will simply dump the table of contents, but is a useful check)
EDIT: Changed to reflect the feedback below
Comment: I also tried this version:

 And still didn't work
Comment: If you look in your manifest file, you'll see that written in. But are the classes actually in your .jar file ?
Comment: I opened the jar and it seemed to include everyting. At least all the classes and files in the project.

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 11.0-b15 (Sun Microsystems Inc.)
Main-Class: controller.Client
Class-Path:: lib/**/*.jar
Comment: Yes, the classes are in the jars included.
Comment: Note the double colon in Class-Path
Comment: If I don't inlude the Class Path in the manifest file, then I get the exception NoClassDeffFoundError
Comment: Brian, you were right. The colod was the problem. Now I get the NoClassDefFoundError. I search the jar for that class and it's there. I also use some other classes in the application (before the one which generates the problem) from the same jar and I get no exception.

Do you have any ideea why is this happening?
Comment: You may want to check that classes referenced IN the class that you're getting the NoClassDefFound error are also there. Otherwise the class can't be loaded/constructed properly.
Comment: They are there. By the way, is there a problem if I use threads in those classes?

Invalid or corupt jarfile


Do ajax requests works if JavaScript is disabled in the browser?

Question: I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions.
If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax?
Find a below a sample button click event:
  $("#renameCategory").live('click', function (event) {
         if ($.trim($("#CategoryNewName").val()) == "") {
             alert("Please enter a category name");
             return;
         }
         var selectedCategory = $("#SelectedCategoryId").val();
         var newCategoryName = $("#CategoryNewName").val();
         var postData = { categoryId: selectedCategory, name: newCategoryName };
         $.ajax({
             type: "POST",
             url: '@Url.Action("UpdateCategoryName", "Category")',
             data: postData,
             dataType: "json",
             success: function (data) {
                 $('#' + selectedCategory).text(newCategoryName);
                 $("#selectedCategoryText").html(newCategoryName);
             },
             error: function () { alert('error') }
         });
     });

How can I handle this?
Answer: Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the  tag href like so:
Click Me!

$("#renameCategory").on('click', function (evt) {
        //To prevent the link from sending the default request
        //call preventDefault() on the jQuery event object
        evt.preventDefault();
        //
        if ($.trim($("#CategoryNewName").val()) == "") {
             alert("Please enter a category name");
             return;
         }
         //GET THE URL FOR THE AJAX REQUEST
         var actionUrl = $(this).attr('href');
         //
         var selectedCategory = $("#SelectedCategoryId").val();
         var newCategoryName = $("#CategoryNewName").val();
         var postData = { categoryId: selectedCategory, name: newCategoryName };
         $.ajax({
             type: "POST",
             url: actionUrl,
             data: postData,
             dataType: "json",
             success: function (data) {
                 $('#' + selectedCategory).text(newCategoryName);
                 $("#selectedCategoryText").html(newCategoryName);
             },
             error: function () { alert('error') }
         });
     });

You will also need to check for ajax requests in your Controller like below:
public ActionResult UpdateCategoryName() {
    ...

    if(Request.IsAjaxRequest()) {
        return Json(yourData);
    }

    return View();
}

This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
Answer: Ajax call works when javascript is enabled.
You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application.
Answer: If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp
View stackoverflow's page source to see how they use noscript
Answer: If JavaScript is disabled in the browser, the
You have JavaScript disabled in your browser. Please enable it.

Answer: Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in.
It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run.
The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow.
All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended.


C are pointers erased after function call ends?

Question: I have learned that whenever a function ends, every local variable declared inside of it is erased. That's why we must use malloc when declaring an array.
But when I think about that again when a function ends what is really erased (in case I defined an array) is the pointer to that array and not the array itself, So we could simply solve the former problem by returning the pointer.
Here is a look at my code, why did it work while my professor said "we must use malloc"?
#include <stdio.h>

int * test ()
{
    int arr[3]={4,5,6};
    return arr;
}
int main() {
    printf("Hello, World!\n");
    int *arr=test();
    printf("%d",arr[1]);
    return 0;
}

Edit: I'm working according to the C99 standard if that does make a difference.
Comment: `malloc` gives long-lasting storage.  Your local `arr` only exists while `test` runs.
Comment: Your code invokes *undefined behavior*. It's that simple. The lifetime of `int arr[3]` in `test` ceases once `test` exits, and any reference to said-memory thereafter is UB. In `main`, `printf("%d",arr[1]);` derefernces a pointer that has no "there" there. Whether it "works", "appears to work", etc. is irrelevant. It's wrong. [Read this Q&A](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794).
Comment: It's unclear what you mean by "erased". The memory isn't guaranteed to be *cleared*/*overwritten*. It will be *freed*, and thus no longer valid to access.
Comment: Your stack has not overwritten the memory where arr is stored in the example. Call another function after assigning the arr or assign a few variables and you will overwrite that memory.
Comment: You return the pointer, the value of where in memory the data is, but the data may not be there because the stack frame associated to the function does not exist anymore. Thus, it will lead to undefined behaviour.
Answer: Option 1:
Change it to static
 static int arr[3]={4,5,6};

Lifetime of a static variable is throughout the program. So we can always create a local static array and return it.
Option 2:
Create a struct
  struct wrapper {
     int arr[3];
  };

The reason this is, array members of structures are deeply copied.


Simple Appplication of Law of Iterated Expectation

Question: Consider a randomized experiment (AB test), where $n$ units are randomized into the treatment group $T_i=1$ and control group $T_i=0$. Let $M_i\in P$ denote the observed value of a continuous variable that is realized after the exposure to the treatment where $P$ is the support of $M_i$. $D_i$ is a binary variable. $F$ represents the distribution function. Can we re-write the expression:
$x=\int \{\mathbb{E}(Y_i|T_i=1, M_i=m, D_i=1) - \mathbb{E}(Y_i|T_i=0, M_i=m, D_i=1)\}\mathrm{d} F_{M_i|D_i=1}(m),$
into
$ x = \mathbb{E}(Y_i|T_i=1, D_i=1) -  \mathbb{E}(Y_i|T_i=0, D_i=1)$
by using the law of iterated expectations?
Answer: I believe, you can; we can think over $E[Y_i|T_i=1,D_i=1]$ first. By the law of iterated expectations, we have $$E[Y_i|T_i=1,D_i=1] = E[ E[Y_i|T_i=1,D_i=1,M_i] ]
\\ =\int{E[Y_i|T_i=1,D_i=1,M_i=m]\ \ f_{M_i|D_i=1}(m)dm}$$ assuming independence of $M_i$ and $T_i$ given $D_i$. Finally, we have $f_{M_i|D_i}(m)dm=dF_{M_i|D_i=1}(m)$. So, for the first summand, you have exactly the same expression and for the second summand this follows exactly the same way.
Comment: how can "independence of Mi and Ti given Di" be reasonably assumed if OPs says "Let Mi∈P denote the observed value of a continuous variable that is realized after the exposure to the treatment"?


Join only first matching record from joining table without duplicate

Question: I have two tables, 1. (inbox) keep delivery reports, 2. (outbox) keep send SMS. I can't add foreign key, and change datebase structure.
inbox
id    number       smsdate
--    ----------   -------------------
1     600600600    2013-08-16 11:51:18
2     700600600    2013-08-16 11:51:16
3     600600600    2013-08-16 11:51:14
4     900600600    2013-08-16 11:51:12

outbox
id      number       processed_date
---     ----------   -------------------
167     600600600    2013-08-16 10:51:10
288     700600600    2013-08-16 09:51:10
356     600600600    2013-08-16 08:51:10
473     900600600    2013-08-16 07:51:10
536     600600600    2013-08-16 06:51:10

I would now join the report of sent messages. I can do it in such a way that comparing the number and date of dispatch of the table outbox, with the same number and the nearest date of receipt of the table inbox. I am sure that the reports will be in order.
If i use
SELECT outbox.id, inbox.id, outbox.number, inbox.number,
   outbox.processed_date, inbox.smsdate FROM outbox
LEFT JOIN inbox ON inbox.number= outbox.number
   AND inbox.smsdate >= outbox.processed_date
GROUP BY outbox.id
ORDER BY outbox.id DESC;

I'm getting strange results and reports are duplicated. For if I have 3 sent, and 2 received, for the same number, it should be one empty. And instead of a blank for the latter, it duplicates my previous one.
I tried to add.
GROUP BY outbox.id, inbox.id

But it was even worse.
It is a way to solve this?
Desired output:
output
outbox.id    inbox.id
---------    ----------
   167         NULL
   288          2
   356          1
   473          4
   536          3

Comment: what is your desired output?
Comment: Why you are grouping it with outbox.id?
Comment: I do not know, I tried them all. I just want to connect to the table so that the closest date to the same number of inbox, was matched to the id of the outbox, but only once, because if it has been used for this number, then let him seek another with the closest date.
Answer: My approach is to use a correlated subquery to get the inbox id, and then join back to the inbox table to pull the columns you want:
select o.id, iid, o.number, i.number, o.processed_date, i.smsdate
from (select o.*,
             (select i.id
              from inbox i
              where i.number = o.number and
                    i.smsdate >= o.processed_date
              order by i.sms.date
              limit 1
             ) iid
      from outbox o
     ) o left outer join
     inbox i
     on o.iid = i.id
ORDER BY outbox.id DESC;

Comment: Look: http://sqlfiddle.com/#!2/4b47b/5  I have only 11 reports, and 23 sends. But results give me 20 reports to sends, more duplicate. One report can only fit into one message, the one whose date is closest to the date of dispatch.
Comment: @Damonsson . . . I think your description of the problem is incomplete.  The only description is that the closest date is the one to be used, not that you are looking for some sort of one-to-one match between the tables.  And, I have no idea what a "report" is.  Your tables are called "inbox" and "outbox".
Comment: The table outbox are outgoing SMS and Table inbox are delivery reports for the messages. I just want to match the delivery report to the SMS. However, I have no idea how to do it. If I, for example, five delivery reports for the phone number and 10 sent messages to this number. I want that for these five have assigned delivery report, and for the rest just null, taking into account the fact that the report must be dated later than the sent message.
Comment: @Damonsson . . . In your SQL Fiddle data, outbox rows 3 and 4 both match back to inbox id 5 -- as my query finds.  I'm tempted to say that you should just delete this question, and formulate another one that actually explains what you want to accomplish (along with the SQL Fiddle).  If you just modify this question, you do a disservice to anyone who has answered this version of it.
Answer: Try this::
SELECT outbox.id, inbox.id, outbox.number, inbox.number,
   outbox.processed_date, inbox.smsdate FROM outbox
LEFT JOIN inbox ON inbox.number= outbox.number
   WHERE inbox.smsdate >= outbox.processed_date


Does the last delivery still count when a match is resumed after an interruption?

Question: In a limited overs match, the scores were tied after the end of the "regular" overs, so a Super Over was being played to decide the winner. Both teams had agreed to resume the match the next day if it was interrupted due to rain, bad light or similar. The third ball of the Super Over was a full toss which was edged and caught cleanly. The square leg umpire did not call a no ball.
The batsmen asked the square leg umpire if it was a no ball, but the umpire stated that he was not able to see the ball. The batsmen continued to argue with the umpire until the match was eventually called off due to bad light.
Does the third ball, and the wicket, count when the match is resumed?
Comment: Edited for readability - this a good laws question.
Comment: Why would it not count? The law does not say that a ball is counted only when the batsman finishes arguing with the umpire.
Answer: The third ball was completed, so it counts. There is nothing in Law 3, in particular Section 9, "Suspension of play in dangerous or unreasonable conditions" which even hints at the idea that a ball might not count if runs are scored or a wicket falls.
More generally, I'm concerned that you're letting your players run the game, rather than the umpires. There is absolutely no way that players should be arguing with umpires over whether a ball was a no ball or not - that is solely for the umpires to decide, and players should accept the decision. Doing anything else is dissent.


In Python, how to represent a class in the same way named tuple does?

Question: I initially wrote some code, making use of a named tuple:
from collections import namedtuple

Count = namedtuple('Count', 'input_number multiple_of count remainder')

def get_count(input_number: int, multiple_of: int) -> Count:
    '''
    >>> get_count(100, 10)
    Count(input_number=100, multiple_of=10, count=10, remainder=0)
    >>> get_count(5, 6)
    Count(input_number=5, multiple_of=6, count=0, remainder=5)
    >>> get_count(999, 90)
    Count(input_number=999, multiple_of=90, count=11, remainder=9)
    '''
    count = input_number // multiple_of
    remainder = input_number % multiple_of
    return Count(
        input_number=input_number,
        multiple_of=multiple_of,
        count=count,
        remainder=remainder
    )

NOTE: How when the object is printed, it is of format: Count(input_number=100, multiple_of=10, count=10, remainder=0) for example.
Is there a Pythonic / best practice way to represent ordinary classes in the same way?
I then wanted to incorporate the typing features of python3.6+ and found I couldn't do that with namedtuple from collections, so I edited the Count class to the following:
from typing import NamedTuple

class Count(NamedTuple):
    input_number: int
    multiple_of: int
    count: int
    remainder: int

I wasn't quite happy with needing two functions so I started new with:
class GetCount():
    '''
    >>> GetCount(100, 10)
    GetCount(input_number=100, multiple_of=10, count=10, remainder=0)
    >>> GetCount(5, 6)
    GetCount(input_number=5, multiple_of=6, count=0, remainder=5)
    >>> GetCount(999, 90)
    GetCount(input_number=999, multiple_of=90, count=11, remainder=9)
    '''

    def __init__(self, input_number: int, multiple_of: int):
        self.input_number: int = input_number
        self.multiple_of: int = multiple_of
        self.count: int = input_number // multiple_of
        self.remainder: int = input_number % multiple_of

What is the best way to get the output in the way I expect (please see doctests for expected output).
Answer: A solution to the problem is the following:
class GetCount():
    '''
    >>> GetCount(100, 10)
    GetCount(input_number=100, multiple_of=10, count=10, remainder=0)
    >>> GetCount(5, 6)
    GetCount(input_number=5, multiple_of=6, count=0, remainder=5)
    >>> GetCount(999, 90)
    GetCount(input_number=999, multiple_of=90, count=11, remainder=9)
    '''

    def __init__(self, input_number: int, multiple_of: int):
        self.input_number: int = input_number
        self.multiple_of: int = multiple_of
        self.count: int = input_number // multiple_of
        self.remainder: int = input_number % multiple_of

    def __repr__(self):
        return f"{self.__class__.__name__}({', '.join([f'{k}={v}' for k, v in self.__dict__.items()])})"

You can see that the provided tests pass by running the below:
import doctest
doctest.testmod(verbose=True)


Degree of min distance function between two algebraic curves

Question: Suppose I have two algebraic curves $C_1$ and $C_2$ in the plane.

I would like to find the minimum distance between the two curves.
If the two curves have degrees $n_1$ and $n_2$, what is (generically)
the degree of the equation one of whose roots identifies that minimum distance?
Above, $n_1=3, n_2=2$:
$$ C_1 \;:\; y=x^3 $$
$$ C_2 \;:\; (x+\tfrac{5}{4})^2 + (y-\tfrac{3}{4})^2 = \tfrac{1}{2} $$
Comment: How do you define degree here?
Comment: Sounds like something that Bernd Sturmfels can give a pertinent answer to.
Comment: @Kaster: I meant the highest combined exponent of $x$ times $y$, e.g., $x^2 y^3$ is degree $5$.
Answer: I am not sure I answer exactly the question as posted; so, forgive me if what I write is out of topic.
If you have two curves defined by $y_1(x)$ and $y_2(x)$, the square of the distance between the two curves is given $$\Phi(x_1,x_2)=\big(x_1-x_2\big)^2+\big(y_1(x_1)-y_2(x_2)\big)^2$$ and you want to minimize this function with respect to $x_1$ and $x_2$.
The problem can be difficult with multi-valued functions (as in the case the the circle you gave). This can lead to very complex equations and, more than likely, only numerical methods will be able to do the job.


pm2 Multiple God Daemons and node process Spawning

Question: I Have node apps unning using pm2.And it is spawning multiple pm2 daemon instead of one which is eating up all the memory.
When I run ps aux | grep pm2 Command I see multiple God daemons for the pm2 process instead of one.  I have a total of 10 pm2 processes for which there should be only one God Daemon. I have installed pm2 globally and it is running by user appuser. Can anyone tell me how can I fix this?
<code>appuser    930  0.0  0.2 573196 10532 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/dj.json
appuser    931  0.0  0.2 572900  9688 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/dj-ui.json
appuser    938  0.0  0.2 572648  9640 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/custom-dj-ui.json
appuser    939  0.0  0.2 573084  9672 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/qa-custom-dj.json
appuser    947  0.0  0.2 572692 10436 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/preview-custom-dj.json
appuser    960  0.0  0.2 573100 10564 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/dev-custom-api.json
appuser    963  0.0  0.2 573408 10100 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/qa-custom-api.json
appuser    967  0.0  0.2 572824  9848 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/preview-custom-dj.json
appuser    968  0.0  0.2 573352 10212 ?        Sl   Aug17   0:00 node /opt/node/bin/pm2 start /opt/pm2-config/preview-custom-api.json
appuser   1890  0.0  0.4 682036 19636 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1893  0.0  0.4 681716 18728 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1907  0.0  0.5 682092 20104 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1916  0.0  0.5 681808 21412 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1917  0.0  0.5 682064 19856 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1918  0.0  0.4 681800 19200 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1923  0.0  0.4 682088 19288 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1931  0.0  0.4 682308 19404 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)
appuser   1941  0.0  0.4 681712 19196 ?        Ssl  Aug17   0:01 PM2 v4.4.0: God Daemon (/naught-home/.pm2)```

</code>
Comment: Why do you use pm2? You could just start your app from systemd directly.
Comment: We manage the node service with pm2, and we manage pm2 via a init.d service file which is located at /etc/init.d/service-file.
Answer: We fixed the above issue by removing the update-rc.d entries for pm2 services which were causing the extra node and pm2 process to start.
Also to start the services at reboot, we added the start script in cronjob.


iOS signal generation pattern not expected

Question: I would like to generate the tone with wave pattern as below ( last mid point should be at the bottom tough as previous set.)

When after chaining the frequency from 44.44Hz to 45.89 Hz, it becomes

Even I have  changed the buffer length from 1024 to 960 , it stills shows that the buffer length is still at 1024 . Hence, it causes the problem that some of the remaining tails displays the mid-point tail instead of bottom .
The below is my code
<code>OSStatus RenderTone(
                    void *inRefCon,
                    AudioUnitRenderActionFlags  *ioActionFlags,
                    const AudioTimeStamp        *inTimeStamp,
                    UInt32                      inBusNumber,
                    UInt32                      inNumberFrames,
                    AudioBufferList             *ioData)

{
    // Fixed amplitude is good enough for our purposes
    const double amplitude =  2.7171;

    // Get the tone parameters out of the view controller
    ToneGeneratorViewController *viewController =
    (ToneGeneratorViewController *)inRefCon;
    double theta = viewController->theta; //992 f0r 44.44 , 959 for 45.89
    double theta_increment = viewController->sampleRate / viewController->frequency;
    int increment = ceil(theta_increment);
    NSLog(@"increment= %i" , increment);
    const int channel = 0;
    Float32 *buffer = (Float32 *)ioData->mBuffers[channel].mData;
    int squareIndex = 0;

for (UInt32 frame = 0; frame < 401; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 401; frame < 419; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 419; frame < 468; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 468; frame < 487; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 487; frame < 536; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 536; frame < 555; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 555; frame < 604; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 604; frame < 622; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 622; frame < 671; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 671; frame < 690; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 690; frame < 739; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 739; frame < 757; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 757; frame < 806; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 806; frame < 825; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 825; frame < 874; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 874; frame < 892; frame++)
{
    buffer[frame] =  -amplitude;
}
for (UInt32 frame = 892; frame < 941; frame++)
{
    buffer[frame] =  amplitude;
}
for (UInt32 frame = 941; frame < increment; frame++)
{
    buffer[frame] =  -amplitude;
}

squareIndex += 1.0;
if(squareIndex >= theta_increment) squareIndex-=theta_increment;
viewController->theta = theta;

void ToneInterruptionListener(void *inClientData, UInt32 inInterruptionState)
{
    ToneGeneratorViewController *viewController =
    (ToneGeneratorViewController *)inClientData;

    [viewController stop];
}

@implementation ToneGeneratorViewController

@synthesize frequencySlider;
@synthesize playButton;
@synthesize frequencyLabel;

- (IBAction)sliderChanged:(UISlider *)slider
{
    frequency = 45.9;
    frequencyLabel.text = [NSString stringWithFormat:@"%4.1f Hz", frequency];
}

- (void)createToneUnit
{
    // Configure the search parameters to find the default playback output unit
    // (called the kAudioUnitSubType_RemoteIO on iOS but
    // kAudioUnitSubType_DefaultOutput on Mac OS X)
    AudioComponentDescription defaultOutputDescription;
    defaultOutputDescription.componentType = kAudioUnitType_Output;
    defaultOutputDescription.componentSubType = kAudioUnitSubType_RemoteIO;
    defaultOutputDescription.componentManufacturer = kAudioUnitManufacturer_Apple;
    defaultOutputDescription.componentFlags = 0;
    defaultOutputDescription.componentFlagsMask = 0;

    // Get the default playback output unit
    AudioComponent defaultOutput = AudioComponentFindNext(NULL, &defaultOutputDescription);
    NSAssert(defaultOutput, @"Can't find default output");

    // Create a new unit based on this that we'll use for output
    OSErr err = AudioComponentInstanceNew(defaultOutput, &toneUnit);
    NSAssert1(toneUnit, @"Error creating unit: %ld", err);

    // Set our tone rendering function on the unit
    AURenderCallbackStruct input;
    input.inputProc = RenderTone;
    input.inputProcRefCon = self;
    err = AudioUnitSetProperty(toneUnit,
                               kAudioUnitProperty_SetRenderCallback,
                               kAudioUnitScope_Input,
                               0,
                               &input,
                               sizeof(input));
    NSAssert1(err == noErr, @"Error setting callback: %ld", err);

    // Set the format to 32 bit, single channel, floating point, linear PCM
    const int four_bytes_per_float = 4;
    const int eight_bits_per_byte = 8;
    AudioStreamBasicDescription streamFormat;
    streamFormat.mSampleRate = sampleRate;
    streamFormat.mFormatID = kAudioFormatLinearPCM;
    streamFormat.mFormatFlags =
    kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
    streamFormat.mBytesPerPacket = four_bytes_per_float;
    streamFormat.mFramesPerPacket = 1;
    streamFormat.mBytesPerFrame = four_bytes_per_float;
    streamFormat.mChannelsPerFrame = 1;
    streamFormat.mBitsPerChannel = four_bytes_per_float * eight_bits_per_byte;
    err = AudioUnitSetProperty (toneUnit,
                                kAudioUnitProperty_StreamFormat,
                                kAudioUnitScope_Input,
                                0,
                                &streamFormat,
                                sizeof(AudioStreamBasicDescription));
    NSAssert1(err == noErr, @"Error setting stream format: %ld", err);
}

- (IBAction)togglePlay:(UIButton *)selectedButton
{
    if (toneUnit)
    {
        AudioOutputUnitStop(toneUnit);
        AudioUnitUninitialize(toneUnit);
        AudioComponentInstanceDispose(toneUnit);
        toneUnit = nil;

        [selectedButton setTitle:NSLocalizedString(@"Play", nil) forState:0];
    }
    else
    {
        [self createToneUnit];

        // Stop changing parameters on the unit
        OSErr err = AudioUnitInitialize(toneUnit);
        NSAssert1(err == noErr, @"Error initializing unit: %ld", err);

        // Start playback
        err = AudioOutputUnitStart(toneUnit);
        NSAssert1(err == noErr, @"Error starting unit: %ld", err);

        [selectedButton setTitle:NSLocalizedString(@"Stop", nil) forState:0];
    }
}

- (void)stop
{
    if (toneUnit)
    {
        [self togglePlay:playButton];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self sliderChanged:frequencySlider];
    sampleRate = 44100;

    OSStatus result = AudioSessionInitialize(NULL, NULL, ToneInterruptionListener, self);
    if (result == kAudioSessionNoError)
    {
        UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
        AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
    }
    AudioSessionSetActive(true);
}

- (void)viewDidUnload {
    self.frequencyLabel = nil;
    self.playButton = nil;
    self.frequencySlider = nil;

    AudioSessionSetActive(false);
}
</code>
Comment: When you say you have "changed the buffer length from 1024 to 960", is there code to do this somewhere? Or do you actually mean you're now putting 960 values into the buffer because your increment variable now calculates to 960?
Comment: It is because 960 is the approximate value of number of samples taken per hour but it seems showing the default samples taken is 1024 , which confuses me
Comment: And I am not sure where to change the default samples taken changed  from 1024 to 960
Comment: You can't tell Core Audio exactly how many samples to take. (You can give it a preferred value but it may change this e.g. to a power of 2). Core Audio tells you how many samples per channel it wants when it calls RenderTone. That's what the inNumberFrames parameter is.
Comment: So how am i supposed to generate My custom tone with slightly higher frequency? i just the tail to be removed such that frequenxy meets my requirement
Answer: When Core Audio calls your RenderTone callback it wants you to provide a particular number of audio frames per buffer. The 'inNumberFrames' parameter tells you what this number is.
(Core Audio does allow some adjustment of the hardware buffer size but this value may be altered to suit Core Audio e.g. by being rounded up to the next power of 2.)
So you can't adjust the callback buffer size to exactly fit one cycle of a waveform you want to generate: Instead you must keep track of where you currently are in the waveform so you can generate as much or as little of it as required, and then continue where you left off in the next callback.
In your example, if inNumberFrames is 1024 then in the first callback you would supply a complete 960 sample cycle AND an additional 64 samples from the next cycle. In the second callback you would provide the remaining 896 samples of your second cycle and 128 samples from the start of your third cycle, and so on.
Comment: It is given that the LCM of 1024 and 960 is 15360. It turns that we have to fill in 16 buffers of 960 and copy to 15 buffers in 1024 default buffer frame. What should I consider to modify the for loop besides making use of modulus ?
Comment: Yes it turns out that 16 cycles of your waveform fit in 15 buffers of 1024 samples. But you can forget about the buffers and just keep track of where in your waveform you are. E.g. you could add a property to your ToneGeneratorViewController that remembers which sample of the waveform (not the buffer) is next, and increment this (modulo 960) as you generate samples.
Comment: inNumberFrames tells you how many samples to produce in the callback, but the value of each sample depends on where in your waveform you have reached, not on where in the CoreAudio buffer you happen to be.
Comment: So i don't understand how the remaining inNUmberFrames (64,128) .... after putting 960 samples to be brought down to the next for loop cycle until it meets 16 times (960X16 = 1024X15) if the end condition of for loop is fixed to be inNumberFrames instead
Comment: It looks like you started from [this example](http://www.cocoawithlove.com/2010/10/ios-tone-generator-introduction-to.html) but then went wrong. Look at the example again: It uses 'frames' for "how far through the buffer am I?" but uses 'theta' for "how far through my waveform am I?". The loop fills the buffer of size inNumberFrames, but _inside_ the loop 'theta' decides what value goes in the buffer. You have started using 'frame' to decide what value goes into the buffer, which is a mistake.
Comment: So what is the way out to handle the remaining buffer samples to be brought down into next cycle for filling in new samples for new waveform?
Comment: If it's a repeating waveform, you just loop back to the beginning of that waveform if you need more samples to fill the buffer (with inNumberFrames).  Also remember where you left off in the waveform after each buffer so you can start there+1 for the next buffer.


Specifying random slope in a nested model

Question: I am super confused on mixed models now. Can anyone explain me what does the following imply:
mod <- lmer(yield ~ year + (1|country/region/state), data = temp)

What I understand is that in the above model I am modelling yield as a function of time trend while controlling for the effect of location i.e. state is nested within region and regions are nested within country.
Now I want to include year as a random slope such that the year time trend varies at only one level i.e. state. How do I specify such a model. Is it:
mod <- lmer(yield ~ year + (1 + year|country/region/state), data = temp) OR
mod <- lmer(yield ~ year + (1|country/region/state) +(1+year|state), data = temp) OR
mod <- lmer(yield ~ year + (1|country) + (1|country:region) + (year|country:region:state), data = temp)

Answer: Yes, you are correct in your interpretation of the initial model.
Your first model with random slopes will fit random slopes for all 3 factors, so that isn't what you want.
I would use the 2nd random slope model to fit individual slopes for year for each level of state.
The 3rd model is interesting. On the face of it, it looks like it should be equivalent to the 2nd one, but I suspect that this will be dependent on the way the data are encoded to represent nesting (explicit vs implicit).
Comment: Okay. Thank you. The way I have encoded that data is there is explicit nesting i.e. state has ids that goes from 1 to 20. 1 to 5 states fall under region X1, 6 to 10 states fall under region X2 and so on. Same in case of how regions are encoded


Ajustar query sql de acordo com disciplina disponível

Question: Possuo esta query, funcionando de boa, mas acontece que funciona apenas se tiver dados para as duas disciplinas PORTUGUES e MATEMATICA, como posso fazer para que, sem prejudicar o resultado, independente de haver apenas uma ou as duas disciplinas eu possa obter os resultados, segue abaixo apenas a parte da query que acho necessária, se preciso coloco o resto.
-- Campos a selecionar.
SELECT
AVG(IFNULL(pqas.fraction, 0)) * 10 AS MediaPT,
AVG(IFNULL(mqas.fraction, 0)) * 10 AS MediaMT,
gg.finalgrade AS NotaGeral,
u.firstname AS Aluno,
u.username AS Usuario,
u.lastname AS siem,
--  u.id, -- removido
u.department AS Turma,
u.institution AS Escola,
pqc.name AS catp,
mqc.name AS catm

FROM mdl_user u

INNER JOIN mdl_grade_grades gg ON gg.userid = u.id
INNER JOIN mdl_grade_items gi ON gi.`id` = gg.`itemid`
INNER JOIN mdl_question_attempt_steps pqas ON u.id = pqas.userid
INNER JOIN mdl_question_attempts pqa ON pqa.id = pqas.questionattemptid
INNER JOIN mdl_question pq ON pq.id = pqa.questionid
INNER JOIN mdl_quiz_slots pqs ON pqs.questionid = pqa.questionid AND pqs.slot = pqa.slot
INNER JOIN mdl_quiz pquiz ON pquiz.id = pqs.quizid
INNER JOIN mdl_question_categories pqc ON pqc.id = pq.category
INNER JOIN mdl_question_attempt_steps mqas ON u.id = mqas.userid
INNER JOIN mdl_question_attempts mqa ON mqa.id = mqas.questionattemptid
INNER JOIN mdl_question mq ON mq.id = mqa.questionid
INNER JOIN mdl_quiz_slots mqs ON mqs.questionid = mqa.questionid AND mqs.slot = mqa.slot
INNER JOIN mdl_quiz mquiz ON mquiz.id = mqs.quizid
INNER JOIN mdl_question_categories mqc ON mqc.id = mq.category

-- Parte do WHERE para filtrar apenas PORTUGUES nas tabelas p.
WHERE SUBSTR(pqc.name, 8) = "PORTUGUES"

-- Parte do WHERE para filtrar apenas matemática nas tabelas m.
AND SUBSTR(mqc.name, 8) = "MATEMATICA"

-- Final da query.
GROUP BY turma, u.id
ORDER BY turma ASC, `Aluno` ASC

Comment: Miguel, adicione os JOINS da `pqc` e `mqc` para a pergunta ficar correta...
Comment: Dei uma ordenada no código, e corrigi o `WHERE` (o que eu tinha errado também na resposta) rs
Comment: @rbz adicionado
Answer: Como fazer
Você pode usar a cláusula OR:
SELECT
    AVG(IFNULL(pqas.fraction, 0)) * 10 AS MediaPT,
    AVG(IFNULL(mqas.fraction, 0)) * 10 AS MediaMT,
    gg.finalgrade AS NotaGeral,
    u.firstname AS Aluno,
    u.username AS Usuario,
    u.lastname AS siem,
--  u.id, -- removido
    u.department AS Turma,
    u.institution AS Escola,
    pqc.name AS catp,
    mqc.name AS catm
FROM mdl_user u

WHERE SUBSTR(pqc.name, 8) = "PORTUGUES"
   OR SUBSTR(mqc.name, 8) = "MATEMATICA"

GROUP BY turma, u.id
ORDER BY turma ASC, `Aluno` ASC

Explicando
Linha:
WHERE SUBSTR(pqc.name, 8) = "PORTUGUES"
       OR SUBSTR(mqc.name, 8) = "MATEMATICA"

A função OR fará com que a query traga os resultados de:
SUBSTR(pqc.name, 8) = "PORTUGUES" OU (OR) SUBSTR(mqc.name, 8) = "MATEMATICA"
Comment: alterei a resposta porque estava sem `where` (não fazia sentido)
Comment: @rLinhares Opa, nem tinha reparado! ✌
Answer: resposta alterada após comentários
Utilizando a validação via OR (já que os campos de controle são de tabelas diferentes), adicione também uma validação na consulta do campo; caso exista (português ou matemática), calcule a média.
Esta validação é necessária para que sejam exibidas as duas médias (caso existam) ou apenas uma:
SELECT
    CASE WHEN (SUBSTR(pqc.name, 8) = 'PORTUGUES') THEN (AVG(IFNULL(pqas.fraction, 0)) * 10) ELSE NULL END AS MediaPT,
    CASE WHEN (SUBSTR(mqc.name, 8) = 'MATEMATICA') THEN (AVG(IFNULL(mqas.fraction, 0)) * 10) ELSE NULL END AS MediaMT,
    gg.finalgrade AS NotaGeral,
    u.firstname AS Aluno,
    u.username AS Usuario,
    u.lastname AS siem,
--  u.id, -- removido
    u.department AS Turma,
    u.institution AS Escola,
    pqc.name AS catp,
    mqc.name AS catm

FROM mdl_user u
-- join demais tabelas

WHERE SUBSTR(pqc.name, 8) = 'PORTUGUES'
   OR SUBSTR(mqc.name, 8) = 'MATEMATICA'

GROUP BY turma, u.id
ORDER BY turma ASC, `Aluno` ASC

Comment: Cara, não funciona porque são diferentes: `pqc` e `mqc`. Pelo que entendi, são tabelas diferentes que estão em `-- joins necessários ...`, `-- Parte do WHERE para filtrar apenas PORTUGUES nas tabelas p.` e  `-- Parte do WHERE para filtrar apenas matemática nas tabelas m.`
Comment: dessa vez eu que não reparei =p vou apagar minha resposta
Comment: @MiguelSilva entendi o ponto, veja se a alteração atende.
Comment: @MiguelSilva o ideal é manter o foco da pergunta; como o problema da pergunta já foi solucionado, é aconselhável deixar a pergunta respondida (para que alguém que busque a solução do problema original, encontre) e criar uma nova pergunta com a outra dúvida.
Comment: normals ;) ....
Comment: poizé, estava pensando nisso, são tabelas que não existem na consulta; acho que a pergunta está errada.
Comment: @rLinhares dessa forma não vou ter problemas no resultado da nota de português e matematica quando tiver as duas disciplinas?
Comment: @rLinhares as tabelas existem sim, estão em ´joins necessários´ já havia pensado no OR, mas não serve
Comment: @rLinhares vou testando
Comment: @rLinhares funcionou perfeitamente, muito obrigado
Comment: Agora surgiu um problema, quando há mais de uma turma, ele não filtra mesmo usando condição no where para me trazer apensa determinada turma
Comment: ok, marquei como resolvida novamente


Remix.run popup toast message on HTTP error status

Question: Wondering what the recommended approach is to fire a popup toast message (keeping the rest of UI intact) when the server returns an error response from an ActionFunction? I realise I can use a CatchBoundary, but that will replace the component, so do i just need to embed the component within the catch boundary and add a toast component? Feels clunky. Is there any way I can simply get the response status in my main component, something similar to useCatch()?
Answer: You can return data from your action and useActionData to get it.
export function action() {
  if (someError) {
    return json({error: 'oops'})
  }
}
export default function() {
  const data = useActionData()
  return (
    {data?.error ? <Toast message={date.error} /> : null }
  )
}

Comment: Ah missed this in the docs. Thank you!


Como mudar o nome do processo de um programa em C\C++ (Lib Windows)

Question: Estou criando um programa de utilitário para o windows mais não consigo mudar o nome que aparece no gerenciador de tarefas, já tentei SetConsoleTitle("atwconnect"); mas mudou só o nome da janela mas não o nome do processo do gerenciador de tarefas.
Alguém sabe como mudar o nome do processo e adicionar uma descrição do programa no processo também ?
Comment: Se estiver a usar visual studio, acho que a solução passa por criar um ficheiro .rc (resource). Por exemplo, https://stackoverflow.com/questions/1022449/how-to-change-an-executables-properties-windows
Comment: Existe algum tutorial de como escrever um arquivo .rc ?
Answer: muda o argv[0] onde fica o nome do processo, ex: argv[0] << "nome";
Comment: Apesar do baixo nível técnico é uma tentativa de resposta. O que cabe a negativação e não a exclusão.


How to show documents that doesn't have an specific key

Question: I need to obtain all the documents in a collection that doesn't have an specific key called "_content_Type".
I was attempting to compare with null or "" but it doesn't work.
db.fs.files.find({"_contentType":""}).count()

0

Answer: you can use $exists operator:
{ _contentType: { $exists: false } }


How to properly check the menu for emptiness in twig?

Question: I use Simplify Menu to display the necessary menu markup. How do I make sure that the menu is not empty (there are items there) and if there are menu items, they are enabled?
{% set items = simplify_menu('main') %}

    {% for menu_item in items.menu_tree %}

      {{ menu_item.text }}

{% endfor %}

In my work, I use the Twig tweak module, but I can't do a check with it either:
{% if drupal_menu('main') is empty %}
{% endif %}

Answer: This is tricky as you would expect {% if drupal_menu('main') is empty %} to work for checking if the menu exists or not. In reality, you'll want to use the render filter for twig. So that would become:
{% if drupal_menu('main') | render %}

I tested this code in my theme's page.html.twig file and it works. e.g.
{% if drupal_menu('main') | render %}
  {{ 'Main menu is not empty'|t }}
{% else %}
  {{ 'Main menu is empty'|t }}
{% endif %}

There is a very long winded issue here with regard to this:
[meta] Themes improperly check renderable arrays when determining visibility
There are also some related issues for this.

2447049: Add a render filter to twig
Checking for empty fields in Twig templates is complicated
Comment: https://www.drupal.org/project/twig_capture is related.


is fourth to fifth in parallel motion permittable in satb?

Question:
I am currently working out some SATB composition and I am wondering a bit about the alto-tenor part. There is fourth to fifth in parallel motion in the first measure.  Is this permitted in strict SATB? Will it be considered consecutive fifths if the G in the first chord is moved up one octave?
Answer: It's not really parallel motion as the interval changes. It is similar motion. However it's also moving by non-contrary motion into a perfect interval which is usually avoided in strict counterpoint. Between outer voices, moving by similar motion to a perfect interval (like an octave or fifth) can make is sound like one voice dropped out; it's usually avoided. Between inner voices, the effect is not so marked.


Symbol to Break Steps to Solve Equation Apart in the Same Line?

Question: Is there a symbol for solving an equation that breaks each step? Usually this is done as a new line, like the following:
4x + 2 = 5
    4x = 3
     x = 3/4

I'm looking for a universal symbol that could change the above to look like this:
4x + 2 = 5 [SYMBOL] 4x = 3 [SYMBOL] x = 3/4

I've asked several math teachers throughout the years in school and none knew the answer.
Comment: How about: $\iff$
Comment: Would a ; (semicolon) be correct? I know "equations" (lines) in programming languages end in semicolons.
Comment: No. You need to use something that makes clear the connection of one statement to the next, and a semicolon doesn't.
Answer: There is no such symbol in general, though in some cases $\iff$ or $\text{iff}$ (meaning if and only if) are technically correct. In general, however, it's preferable to use words:

$4x+2=5$, so $4x=5-2=3$, and therefore $x=\frac34$.

In general you should think of a mathematical argument as a piece of expository prose, and you should use enough linking expressions to make the flow of the argument clear.


TLS Termination using kubernetes Ingress

Question: I'm working on putting TLS/SSL in front of my wordpress site in kubernetes.
I have an Ingress in front.
Without any TLS config I can access the site ok. When I add TLS config I get timeouts on accessing the site.
Ingress.yaml:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: helloworld-rules
spec:
  tls:
  - hosts:
    - mysite.com
    secretName: tls-secret
  rules:
  - host: mysite.com
    http:
      paths:
      - path: /
        backend:
          serviceName: mysite
          servicePort: 80

ingress-controller.yaml:
apiVersion: v1
kind: Service
metadata:
  name: nginx-ingress
  labels:
    app: nginx-ingress
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 80
  selector:
    app: nginx-ingress
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-ingress
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx-ingress
    spec:
      containers:
      - name: nginx-ingress
        image: gcr.io/google_containers/nginx-ingress-controller:0.9.0-beta.10
        imagePullPolicy: Always
        readinessProbe:
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
        livenessProbe:
          httpGet:
            path: /healthz
            port: 10254
            scheme: HTTP
          initialDelaySeconds: 10
          timeoutSeconds: 1
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        ports:
        - containerPort: 80
          hostPort: 80
        args:
        - /nginx-ingress-controller
        - --default-backend-service=$(POD_NAMESPACE)/echoheaders-default
        - --configmap=$(POD_NAMESPACE)/nginx-load-balancer-conf

Answer: Turns out Load balancer needs to specify port 443
apiVersion: v1
kind: Service
metadata:
  name: nginx-ingress
  labels:
    app: nginx-ingress
spec:
  type: LoadBalancer
  ports:
  - name: http
    port: 80
    targetPort: 80
  - name: https
    port: 443
    targetPort: 443
  selector:
    app: nginx-ingress

This thread was also helpful in completing the set up.
https://github.com/kubernetes/ingress/issues/672
Comment: Hopefully this gets resolved soon, it seems a bit arbitrary.


Run software when USB is connected

Question: I am looking for a way to run software that is stored on a windows machine when a usb device is connected. Similar to how an antivirus program would scan it to make sure it is safe before allowing access. Is there an api or other way that you can do that? Thanks in advance for any help!
Answer: I hope this link will help you: Detecting Media Insertion or Removal

Run software when USB is connected


Are classic electronic instruments doomed to exist only virtually?

Question: I saw a Farfisa combo organ at a guitar store two months ago and was blasted by its low price. I plugged it into an amp and was in great awe, up until I heard the first note. It was like meeting your childhood hero when both of you are older, and your childhood hero is now old, grey-haired, wispy in voice and soft in hand and handshake. I did not buy the organ. If I want a Farfisa sound, I can just synthesize it; it's just a chorus-y sawtooth. I can get a Yamaha Reface YC. I can download a VST.
The thrust of the above is: for specific hardware electronic and electric instruments, can there be a future? Vintage instruments won't last forever. No individual physical instrument will last forever. Mozart's pianoforte, though preserved, probably isn't playable anymore. But new pianos, and even pianofortes, are still being produced. But Farfisa has been bought out by Bontempi, and nobody knows who Bontempi is anymore. How many Yamaha GX-1's are still in existence; is it even ten? Did anyone in Yamaha even keep the production spec? Could they even make another, if some fresa slipped Yamaha a million dollar bribe to recreate the thing?
Are all Farfisas, Magnus chord organs, Echo-Recs, and the like destined to only be reproduced digitally, not manufactured?
Comment: 'Fraid so. As you state, something like a Farfisa, or even a venerable DX7, was very limited in what range of sounds they could produce, and with technology now being able to emulate all those sounds plus thousands more, probably for the same or less money than it would take to re-create a Farfisa, why would anyone bother?
Comment: Korg announced a limited run reissue of the ARP 2600 synthesizer in January. Every single unit was pre-sold within 72 hours, and a rep from a major online retailer said they have a waiting list over 100 orders long, which is just the list for that one retailer. Recently Moog did quite well with their model D reissue. Sequential is selling the prophet 6 and the OB-6 fairly well, which are 100% analog updates of the prophet 5 and original Oberheim synths. Many classic instruments still sell in the physical analog world.
Comment: I've still got a Rhodes Chroma, reportedly now worth 12 grand… if any one can manage to fix it for long enough to get the programmes reloaded :\  BTW, the GX1 was never meant to sell. Yamaha do that with experimental high-end proof of concept pieces. They give them away to famous people to build hype for an upcoming consumer version.
Comment: I gave my [production] DX7 away eventually. The first DX7 I ever had didn't have midi [mid 83] ;-) I'm still waiting for a VSTi Chroma… any takers??
Answer: In order for an instrument to be manufactured on a commercial basis, there needs to be a market for it. The reason those electronic instruments are no longer produced is that technology has advanced and created a more profitable method of creating the sound of the music we love to hear. Some of the old instruments are still in pretty good repair and can still make that music, but as age takes its toll and parts become less available, the new technology will likely replace the old technology. I have a friend who has a Hammond B3, but when he plays a gig, he gets his B3 sound on his digital keyboard. That Hammond is just to much to haul around and set up. It seems that most folks view the situation the same way and there is little or no demand for the old technology anymore.
Comment: Especially true about hauling. I used to work with a Hammond C3 organist back in the '70s, and lugging that, a tone cab and a Leslie cab up and down stairs meant gym membership never ever came to mind.
Comment: @Tim- It helps us appreciate the new technology, especially when we age.


Por que os controles instanciados não são exibidos na UI?

Question: Tenho esse aplicativo de login. Ele não está iniciando os componentes corretamente. Gostaria de saber como iniciá-los.
O código é o mesmo que está no livro JavaFX da casa do código, no exemplo de login.
package loginapp;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javax.swing.JOptionPane;

/**
 *
 * @author sergi
 */
public class LoginApp extends Application {

    private AnchorPane pane;
    private TextField txtLogin;
    private PasswordField txtSenha;
    private Button btEntrar;
    private Button btSair;
    private static Stage stage;

    public static Stage getStage() {
        return stage;
    }

    private void initComponents() {
        pane = new AnchorPane();

        txtLogin = new TextField();

        txtSenha = new PasswordField();

        btEntrar = new Button("Entrar");

        btSair = new Button("Sair");

    }

    private void initLayout() {
        pane.setPrefSize(600, 200);
        pane.setStyle("-fx-background-color: blue;");

        txtLogin.setPromptText("Digite aqui o seu Login: ");
        txtLogin.setLayoutX((pane.getPrefWidth() - txtLogin.getLayoutX()) / 2);
        txtLogin.setLayoutY(50);

        txtSenha.setPromptText("Dgite aqui a sua senha");
        txtSenha.setLayoutX((pane.getPrefWidth() - txtSenha.getLayoutX()) / 2);
        txtSenha.setLayoutY(100);

        btEntrar.setLayoutX((pane.getPrefWidth() - btEntrar.getLayoutX()) / 2);
        btEntrar.setLayoutY(150);

        btSair.setLayoutX((pane.getPrefWidth() - btSair.getLayoutX()) / 2);
        btSair.setLayoutY(200);

    }

    private void initListeners() {
        btSair.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

                fecharAplicacao();
            }
        });

        btEntrar.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {

                if (txtLogin.getText().equals("admin") && txtSenha.getText().equals("casadocodigo")) {
                    //TODO Abrir tela vitrine
                } else {
                    JOptionPane.showMessageDialog(null, "Login e//ou senha invalidos", "Erro", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }

    private void fecharAplicacao() {

        System.exit(0);
    }

    @Override
    public void start(Stage stage) throws Exception {
        initComponents();
        initListeners();
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        //Remove a opçao de maximizar a tela
        stage.setResizable(false);

        //Dá um titulo para a tela
        stage.setTitle("Login - GolFX");
        stage.show();
        initLayout();
        LoginApp.stage = stage;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

O código não apresenta erros de compilação, mas não executa os componentes (txtLogin, txtSenha entre outros). Entretanto o estilo é carregado.
Answer: Carregados eles são. Acredito que a sua dúvida esteja relacionada aos elementos não aparecerem no AnchorPane. Se for isso, o motivo é que você está somente inicializando os objetos, porém em momento algum os adiciona ao painel.
Pode alterar o método initLayout para, além de definir as propriedades, também inseri-los no painel. Por exemplo:
private void initLayout(){

    /* ... código que você tem até o momento aqui... */

    // Inserindo os elementos após definir as propriedades.
    pane.getChildren().add(txtLogin);
    pane.getChildren().add(txtSenha);
    pane.getChildren().add(btEntrar);
    pane.getChildren().add(btSair);
}

Resultado:
Comment: Era isso mesmo. Obrigado! :D


AutoClick somente em class dentro de class

Question: Gostaria de realizar um autoclick sequenciado em apenas um link por por vez e somente na class="mobile" que tiver uma class="check-handler". Agradeço a quem me ajudar pois já tentei vários scripts mas até agora nada.
(A)

(B)

(C)

if ($('.mobile #container .check-handler').is(':visible'))
    setTimeout(function(){$('.mobile #container .check-handler').click();},5000);

Comment: Poderia explicar melhor?
Comment: Na página existe vários blocos mas eu preciso de um autoclick somente nos blocos igual a opção "B". Meu pensamento é: Seria possível criar um código que funcionasse o autoclick somente se a class=x estivesse abaixo da class=y?
Answer: Consegui a resposta através de outro site de Javascript.
$(document).ready(

function() {

setTimeout(
function () {

$('#container:not(.clicked.mobile) .check-handler').click();

}, 3000);});


Rails, Has many through relation within seller and buyer

Question: I am trying to build has_many :through relation within seller and buyer upon products.
product.rb
class Product < ActiveRecord::Base
  resourcify
  include Authority::Abilities
  self.authorizer_name = 'ProductAuthorizer'

  belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id', required: false

  has_many :purchasements
  has_many :buyers, :class_name => 'User', through: :purchasements

  has_many :comments, as: :commentable, dependent: :destroy
end

purchasement.rb
class Purchasement < ApplicationRecord
  belongs_to :buyer
  belongs_to :purchase
end

user.rb
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
  rolify
  include Authority::UserAbilities

  has_many :sales, :class_name => 'Product', :foreign_key => 'sale_id'

  has_many :purchasements
  has_many :purchases, :class_name => 'Product', through: :purchasements
end

migration for product
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :title
      t.text :content
      t.integer :price

      t.belongs_to :seller, index: true

      t.integer :purchase_count, default: 0, null: false

      t.timestamps null: false
    end
  end
end

migration for purchasement
class CreatePurchasements < ActiveRecord::Migration[5.0]
  def change
    create_table :purchasements do |t|
      t.belongs_to :buyer, index: true #상품 입장에서의 구매자들
      t.belongs_to :purchase, index: true #구매자 입장에서의 상품들

      t.timestamps
    end
  end
end

products_controller.rb
def create
  @product = Product.new(product_params)
  @product.seller = current_user
  authorize_action_for @product
  #remote true 가 적용된 폼에는 token 이 포함되지 않는다. 따로 포함하라고 말해줘야함.

  if @product.save
    redirect_to @product, notice: '상품 업로드 완료'
  else
    Rails.logger.info(@product.errors.inspect)
    flash[:error] = 'fjeislafsa'
    render :new
  end
end

def download
  if points_check(@product)
    @product.purchase_count += 1
    @product.buyers << current_user
    #current_user.purchases << @product
    @product.save
    redirect_to @product.file.expiring_url(10)
  else
    redirect_to payments_path
  end
end

The problem is when user tries to download(purchase) product.
@product.buyers does not work and gives this error 'NameError: uninitialized constant Purchasement::Buyer
'
My goal is to make product have only one seller(user), and have multiple buyers(user). On the other side, user can have many sales(product) and purchases(product) at the same time.
I get confused somewhere and can't find where to fix.
Thanks ahead.
extra errors
Started GET "/products/download/1" for 127.0.0.1 at 2017-03-26 18:22:10 +0900
Processing by Shop::ProductsController#download as HTML
  Parameters: {"id"=>"1"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Product Load (0.1ms)  SELECT  "products".* FROM "products" WHERE        "products"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  BEGIN
  SQL (0.2ms)  UPDATE "users" SET "point" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["point", 9948], ["updated_at", 2017-03-26 09:22:10 UTC], ["id", 1]]
   (1.1ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
Completed 500 Internal Server Error in 64ms (ActiveRecord: 8.9ms)

ActiveModel::UnknownAttributeError (unknown attribute 'product_id' for Purchasement.):

app/controllers/shop/products_controller.rb:67:in `download'
  Rendering /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendering /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
  Rendered /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (3.9ms)
  Rendering /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
  Rendered /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.9ms)
  Rendering /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms)
  Rendered /Users/mac/.rvm/gems/ruby-2.3.0/gems/actionpack-5.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (53.5ms)

Answer: class Purchasement < ApplicationRecord
  belongs_to :buyer
  belongs_to :purchase
end

Given the above declaration, Rails attempts to associate buyer association with a Buyer class and purchase association with a Purchase class, both of which don't exist.
You should specify the model class names here as well:
class Purchasement < ApplicationRecord
  belongs_to :buyer, class_name: 'User'
  belongs_to :purchase, class_name: 'Product'
end

Comment: how about for migration file of Purchasements ? should I change this too ?
Comment: unknown attribute 'product_id' for Purchasement. I get this error now ...
Comment: Unless you are want to add a foreign key (in which case you will have to specify `foreign_key: {to_table: :users}`) migration does not need to be changed.