Equality simplification -- have I done it correctly?

Question: I previously posted this equality and got some nice feedback. This is my final equality to prove Legendre's, Brocard's, Andrica's, and Oppermann's Conjectures. The first equality was to determine if there would be any surprises with this one:
$$
\left(\left(\frac{1}{2} (((k+1) \bmod 2)+k+1-2)\right)^2+\frac{1}{2} (((k+1) \bmod 2)+k+1-2) (2-((k+1) \bmod 2))\right)
 - \left(\left(\frac{1}{2} ((k \bmod 2)+k-2)\right)^2+\frac{1}{2} ((k \bmod 2)+k-2) (2-(k \bmod 2))\right)
  - ((k+1) \bmod 2) = \frac{1}{2} (((k+1) \bmod 2)+k+1-2),
$$
which I was able to simplify to:
$$
(((k+1) \bmod 2)+2) ((k+1) \bmod 2)+4 (k \bmod 2)=(k \bmod 2)^2+3,
$$
which Mathematica reduces to: $c_1\in \mathbb{Z}\land k=c_1,$ same as the previous equality. So, no surprises. I just need some eyes on this to double-check my results. Do you see any problems?
Edit Since $(k \bmod 2)^2$ is 0 or 1, we can remove the exponent without loss of information. Then we subtract from both sides to leave:
$$
(((k+1) \bmod 2)+2) ((k+1) \bmod 2)+3 (k \bmod 2)=3,
$$
which reduces to: $c_1\in \mathbb{Z}\land k=c_1.$
Answer: That's a fascinating expression, $(k+1)\mod2$.  It's 1 if k is even, or 0 if k is odd.  And $k \mod 2$ is its mirror image, 1 if k is odd, or 0 if it's even.
Let $e=(k+1) \mod 2$ and $o=k \mod 2$.  Then you can separate the equalities into two discrete cases, one where e=1 and o=0, and the other where e=0 and o=1.  This easily verifies the simplified equality.
$$(e+2)(e) + 4o = o^2+3$$
$$(1+2)(1) + 4*0 = 0^2+3$$
$$3 = 3$$
and
$$(e+2)(e) + 4o = o^2+3$$
$$(0+2)(0) + 4*1 = 1^2+3$$
$$0 + 4 = 1 + 3$$
$$4 = 4$$
So, for a double-check, you could apply this to the original formula for each case.  I see free-standing k's in the original formula, so they'll have to cancel if this is to work out.  But I'm not quite ready to tackle that yet.


When using Zen and Zen grids, where do I put SASS variables?

Question: I am trying to use Zen Grids with the Zen ver. 5 starter theme.
The Zen starter theme comes with a lot of .scss files (in the sass/ subdirectory).  I am trying to use Zen Grids to set up a simple layout.  I've read up on Sass and think I understand the concept, and I've Compass installed and working.
I've read everything on the Zen Grids website. On the front page of that website, below the promising headline: "Using Zen Grids is easy!", there is a nice introduction to Sass and Zen Grids followed by: "And here's the complete Sass code:".
The example is strightforward enough.  What I am not able to figure out is where (as in "in what file") you put the statements used in the example.
(My setup is a Zen sub-theme created from the Zen STARTERKIT, straight out of the box.)
Answer: In the Zen theme structure there are several main style files: pages.scss, nodes.scss, blocks.scss, forms.scss. Depend on which part of website that you want to make styles. You have to choose the correct files for changing. In order to use the sample code in the Zen Grids . You can go to pages.scss and make changes here . Make sure that your website will generate the same HTML markup structure like the sample by creating new pages.tpl.php.
Answer: If you use the Zen STARTERKIT ver. 5, Sass configuration variables and Sass mix-ins similar to those you link to on the Zen Grids website is already in place in the file named responsive-sidebars.scss.
So to create a responsive design by means of Zen Grids, you don't add these anywhere, as they're already in place. But if you want to change them to other values, you do so by simply editing responsive-sidebars.scss in your starterkit sub-theme.
Note that most of the selectors used in the example on the Zen Grids website (e.g. .aside1) will not do anything in Zen (unless you also change the corresponding template file).  You can see from responsive-sidebars.scss what selectors to use (e.g. .region-sidebar-first).


XAML string format in multibinding w/converter

Question: I am implementing this TextBlock and the stringformat is not appearing, only the value of the binding property. Can you tell me what I'm doing wrong?
XAML CODE
<TextBlock>
     <TextBlock.Text>
       <MultiBinding Converter="{StaticResource ResourceKey=myConverter}">
         <Binding Path="loc.country" StringFormat="Country: {0}"/>
         <Binding Path="loc.area" StringFormat="Area: {0}"/>
       </MultiBinding>
     </TextBlock.Text>
 </TextBlock>

Converter
public class MyMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[1] == null)
            return values[0];

        return values[1];
    }

    public object[] ConvertBack(object values, Type[] targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

Best regards,
Comment: Check the **Output Window** for binding errors.
Comment: No binding errors Mike.
Answer: See the Remarks section on the StringFormat page on MSDN:

...
When you use a MultiBinding, the StringFormat property applies
  only when it is set on the MultiBinding. The value of StringFormat
  that is set on any child Binding objects is ignored. ...

The reason is that StringFormat is only applied when the target property of the binding is actually of type string, which is not the case in a MultiBinding

So you either set the StringFormat of the MultiBinding (and don't set its Converter), or you do the formatting in your converter.
Comment: thanks for your answer. In my case, I want to show one or another...And if is the first is Country and the second it's an area. What would you recommend? (this happens in another places as well, but of simplicity purposes I didn't put it here)
Comment: You can always return a formatted string from the converter.
Comment: Done. I've done what you suggested. My thanks to you.


Play bar 7 of Mikrokosmos piece "In Dorian Mode"

Question: I'm learning piece 32 "In Dorian Mode" of Bartok's Mikrokosmos, and I am puzzled by something at bar 7.  Left and right hand staves are both written in the treble clef, and the last note of bar 7 is the same G for both hands

The piano does not allow to play this G twice simultaneously.  How am I supposed to play this?
Answer: No need to play it twice.  Both voices just happen to use the same note at that point.  You can choose which hand you wish to use.  Or you could play the G using a finger from both hands at the same time, if that helped musically, but the result would pretty much be the same, so no real need to do that.


Prove whether the linear equations are solvable or not?

Question: I am beginner to linear algebra. I am confused for finding the solution for following question.
There are set of linear equation(m equations and n unknown) represented in the form of matrices.
matrix(m x n) * vector(n) = Vector(m).
Now how would i prove that the solution exist for the set of linear equation for the following cases:
1) if m > n
2) if m = n
3) else m < n
Q: Now consider the matrix(mxn) as input of function(which if vector(n)) and producing the output vector(m). So i want to know in which of the above three conditions the functions can be onto, one-to-one or both and why?
Answer: The function corresponding to an $m \times n$ matrix is onto if and only if the matrix has rank $m$.  It is one-to-one if and only if it has rank $n$.  The rank is at most $m$ and at most $n$, so in case (1) it can never be onto, and in case (3) it can never be one-to-one.  Only in case (2) is it possible for the function to be both one-to-one and onto.


If $|f(z)|=1$ , $f$ is holomorphic then $f$ is constant

Question: Let $G\subset \mathbb{C}$ be a region, $f$ a holomorphic function.
Then it does hold that:

If $f(G) \subset \mathbb{R} \Rightarrow  f$ is constant
If $|f(z)|=1$ for all $z \in G$, then $f$ is constant.

Proof of 1:
$f$ is holomorphic, so it holds that $$u_x=v_y; u_y=-v_x$$ where $f(z) = u(x,y)+iv(x,y)$, then $u_x=0$ and $u_y=0$ so $u,v$ both must be constant
Proof of 2:
$$|f(z)|= 1 \Rightarrow u^2+v^2=1 $$
taking the partial derivatives:
$$2uu_x+2vv_x=0 , 2uu_y+2vv_y= 0$$
putting inside the Cauchy-Riemann equations:
$$uu_x-vu_y=(u^2u_x^2-2uvu_xu_y+v^2u_y^2)=0; uu_y+vu_x=(u^2u_y^2+2uvu_xu_y+v^2v_y^2)=0$$
so either $u=v = 0$ or $u_x=u_y=0$
so $$\Leftrightarrow (u^2+v^2)(u_x^2+u_y^2)=0.$$
If everything was done correctly so far, wouldn't
switching $1$ with a constant $M$ give a proof for Liouville's theorem?
Comment: Liouville's theorem only requires a bounded norm, not constant, so your proof doesn't prove Liouville's theorem.
Comment: The Liouville's theorem that I know of is about entire functions, and you can't really hope for it to be true for functions of bounded domain. Also, partial derivative of $1$ is $0$.
Answer: Both claims follow at once from the fact that a non-constant holomorphic function is an open map: Apparently, the image of $f$ is not open in $\mathbb C$.


Gal$(X^2-X-1) ⊆ S_2$ and Gal$(X^9-X) ⊆ S_9$

Question: The question I'm trying to answer reads:

Describe the embeddings Gal$(f) \subset S_2$ and Gal$(f) \subset S_9$ for $f = X^2 - X - 1$ and $f = X^9-X ∈ _3[X]$

but I don't know how to interpret it. Does it mean Gal$(X^2 -X-1) \subset S_2$ and Gal$(X^9-X) \subset S_9$ or also, in addition, Gal$(X^2 -X-1) \subset S_9$ and Gal$(X^9 -X) \subset S_2$? I'm completely new to Galois theory, and might lack some relevant knowledge about finite fields..
Comment: Looks like whoever asked you this question wants you to realize the Galois group of a polynomial as permutations of the roots. The quadratic has two roots, hence its Galois group is (or at least can be viewed as) a subgroup of $S_2$. The other polynomial has nine roots, so its Galois group can be seen as a subgroup of $S_9$.
Comment: Hint: Both polynomials split over $\Bbb{F}_9$.
Comment: @JosvanNieuwman note that $\mathbb{Z}/p\mathbb{Z}$ is a field only when $p$ is prime. The field $F_9$ of $9$ elements can be described, for example, as the splitting field of $g = X^9-X \in F_3[X]$. The existence of splitting field can be proved from the existence of algebraic closures: pick an algebraic closure and adjoint the roots of $g$ there to $F_3$. This gives a field $K$. Since $\alpha \mapsto \alpha^9$ is a field morphism in characteristic $3$, one can actually see that any $x \in K$ satisfies $x^9 = x$ and so $K$ consists exactly of the roots of $g$, having thus $9$ elements.
Comment: So if I were to identify the zeros in $_9 (= \mathbb{Z}/9\mathbb{Z}??)$ of both polynomials, say, $z_1, z_2$ for the first one, then I could just map the permutation $z_1 \leftrightarrow z_2$ to the cycle $(z_1 \,\, z_2) ∈ S_2$, right?
Answer: As Jyrki points out in the comments, if $f \in k[X]$ is a nonconstant separable polynomial with (distinct) roots $\alpha_1, \dots, \alpha_n \in \overline{k}$, the extension $k(\alpha_1,\dots, \alpha_n)/k$ is Galois and a morphism
$$
\sigma : k(\alpha_1,\dots, \alpha_n)/k \to
k(\alpha_1,\dots, \alpha_n)
/k
$$
is determined by $\sigma(\alpha_i)$ for each $i$. Note that field morphisms are injective so $\sigma(\alpha_i) \neq \sigma(\alpha_j)$ when $i\neq j$. This defines a permutation on $\{1,\dots, n\}$ via
$$
\tau_\sigma(i) = j \iff \sigma(\alpha_i) = \alpha_j
$$
and the function $\sigma \in Gal(f) \mapsto \tau_\sigma \in S_n$ is a group morphism. Moreover, it is injective: if $\tau_\sigma = 1$, then $\sigma(\alpha_i) = \alpha_i$ for all $i$ and thus $\sigma = id$.
Hence $Gal(f) \hookrightarrow S_{\deg f}$ for any $f \in k[X]$ (separable and non-constant) via the aforementioned assignment.
Comment: Note that if $f = x^2 - x -1$ then $f' = 2x-1$ whose only root in $F_3$ is $2$. But $2^2 - 2 -1 = 1 \neq 0$, so $f$ and $f'$ do not share roots: hence $f$ is separable.
Comment: As for your calculation, note that $5 = 2$ mod $3$. Also $\sqrt{2}$ should mean a root of $g = X^2-2$ in an algebraic closure of $F_3$.  Since $g$ is irreducible in $F_3[X]$ (because it has degree $2$ and so roots in $F_3$), such a root $\beta$ has minimal polynomial $g$ over $F_3$, and thus $[F_3(\beta) : F_3] = 2$ which means that $F_3(\beta) = F_9$ (you can check that $\beta \in F_9$ since $\beta^9 = \beta$ and both fields have the same amount of elements).
Comment: Hence an $F_3$-basis of this field could be $\{1,\beta\}$ and so its elements are of the forma $a+b\beta$ with $a,b \in F_3$.
Comment: (also, $1/2$ here is just $2$ as $4 = 1$ mod $3$)
Comment: What I still don't understand is this: to determine whether $X^2 -X -1$ is separable, we must determine whether it has repeated roots. Using the quadratic formula, we find that its roots are $\frac{1}{2} ± \frac{1}{2}\sqrt{5}$. Does that mean its splitting field is $\mathbb{F}_3(\sqrt{5})$? Does that expression even make sense? What would that field even look like?
Comment: Great! I now think I understand the case of $f$ completely! And learned a lot from this. My suspicion is now that, as $X^9-X$ has the same splitting field, they will have the same Galois groups and we can use _the exact same embedding_ in $S_9$ as in $S_2$ (The one where id $↦ (1)$ and $(a+b\sqrt{2} ↦ a-b\sqrt{2}) ↦ (12)$)! We don't need the rest of $S_9$! However, doesn't that contradict the fact that $X^9-X$ is separable (Its derivative is $9X^8 - 1 = 0 - 1 = -1$, which has no roots)? Shouldn't it have 9 distinct roots?
Comment: The polynomial $g$ has $9$ distinct roots and so its Galois group is a subgroup of $S_9$, but it may as well be very small. Actually, one can show that $\mathsf{Gal}(F_{3^j}/F_3) \simeq Z_j$.  We know the automorpshisms are permutations of the $9$ distinct roots, but not every permutation is admissible: in fact, we have shown that there are only two valid such morphisms.
Comment: (I meant $\mathbb{Z}_j$, can't edit the comment now. For a proof: show that its Galois group is cyclic with generator the Frobenius map $\alpha \mapsto \alpha^3$.)


$\operatorname{Aut}(G\times H)$ is isomorphic to the direct product $\operatorname{Aut}(G)\times\operatorname{Aut}(H)$.

Question: Suppose $G$ and $H$ are finite groups of relatively prime orders. Prove that $\operatorname{Aut}(G\times H)$ is isomorphic to the direct product $\operatorname{Aut}(G)\times\operatorname{Aut}(H)$.
My attempt: I can imagine that given some automorphism of $G\times H$, $\phi(g,h)\rightarrow(g_2,h_2)$ where $g,g_2\in G$ and $h,h_2\in H$, we can create two automorphisms for $G$ and $H$ where $\tilde{\phi}(g)=g_2$ and $\hat{\phi}(h)=h_2$. Basically we can "build" an automorphism of $G\times H$ out of any two automorphisms of $G$ and $H$, and hence $\operatorname{Aut}(G\times H)$ will be all possible combinations of automorphisms of $G$ and $H$.
I know this is a very imprecise method, but I'm looking for a step in the right direction.
Any help appreciated!
Comment: Is the converse of statement true @Jess
Answer: You're on the right track. Your argument about "building an automorphism" shows that $\operatorname{Aut} G \times \operatorname{Aut} H$ is contained in $\operatorname{Aut} (G\times H)$.
Note that your argument does not make use of the assumption that $G$ and $H$ have relatively prime orders. Thus it shows that $\operatorname{Aut} G \times \operatorname{Aut} H$ is always contained in $\operatorname{Aut} (G\times H)$, regardless of the group orders.
What's missing is an argument that $\operatorname{Aut} (G\times H)$ doesn't have anything in it besides the things coming from $\operatorname{Aut} G\times\operatorname{Aut} H$. This is the part of the claim that depends on the assumption that $G$ and $H$ have relatively prime orders. Indeed, without this assumption, it's not true: for example if $G$ and $H$ are both cyclic of prime order $p$, then $\operatorname{Aut} (G\times H)$ is actually $GL(2,\mathbb{F}_p)$, which is significantly bigger than $\operatorname{Aut} G \times \operatorname{Aut} H = \mathbb{F}_p^\times \times\mathbb{F}_p^\times$. This is because there exist automorphisms that "mix up" $G$ and $H$. For example if $G=H=(\mathbb{F}_p,+)$, then there is an automorphism that fixes $(1,0)$ (so $G\times\{0\}$ stays inside $G\times\{0\}$), but sends $(0,1)$ to $(1,1)$ (so $\{0\}\times H$ is moved by the automorphism to somewhere else).
G. Sassatelli's hint is aimed at showing how you can rule out the possibility that $G\times H$ has any automorphisms that "mix up" the $G$ part (which is $G\times\{\text{identity in $H$}\}$) and the $H$ part (i.e. $\{\text{identity in $G$}\}\times H$). Use the fact that $G,H$ have prime orders.
(In case the phrase "characteristic subgroup" is new to you, it means a subgroup that is not moved to somewhere else by any automorphism.)
Answer: Hint: The thing that makes your idea work is that, since $\operatorname{gcd}(\lvert G\rvert,\lvert H\rvert)=1$, the subgroups $G\times\{e_H\}$ and $\{e_G\}\times H$ are characteristic subgroups of $G\times H$.


Possible alternate proof of uniqueness of power series?

Question: I want to show that if $\sum_{k=0}^\infty a_kx^k = 0$ on $[0,1]$, then $a_k=0 \forall k\in\mathbb{N}$. I'm aware of the standard proof, but wanted to try another argument.
We know that a polynomial of degree $k$ has at most k roots, so the polynomial $\sum_{k=0}^N a_kx^k$ has at most $N$ roots. Now if we let $N\rightarrow \infty$ we know that we can have at most "$\aleph_0$ roots", but for the function to be identically zero we must have uncountably many roots.
I know that this argument is rubbish, but is there a way (by transfinite induction/Baire Category or something else) to make this idea rigorous?
Comment: Does this imply $f^{n}(0) = 0, \forall n \ge 1\implies a_k = 0, \forall k \ge 1$ ?
Comment: I don't understand what "this idea" you want to make rigorous is.
Comment: @AndrésE.Caicedo he's saying intuitively, a nonzero power series should have at most countably many roots, so if $f$ is zero on $[0,1]$, then all the coefficients should be zero.
Comment: @D_S But they want this as a corollary of the result about polynomials, so does the "idea" amount to "let $N \to\infty $", or is there actually something else?
Comment: You could use the [identity theorem](https://en.wikipedia.org/wiki/Identity_theorem), which is a bit like a generalization of this fact about polynomials.
Comment: @Jair isn't that the standard proof? The question wants a different approach.
Comment: What standard proof are you aware of?
Answer: I think that the closest way to prove the claim following your idea is putting the problem in the complex plane, so you can use Rouché's theorem: basically, you approximate the behavior of $f$ in a small neighbourhood of $0$ by the first non-vanishing Taylor polynomial of $f$.
Suppose that for some $n\ge0$ we have that $a_n\neq0$. Get the smallest integer $n$ such that $a_n\neq0$. Then: $$\exists r>0,\forall |z|=r, |f(z)-a_n z^n|<|a_n|r^n.$$ Then, by Rouché's theorem, $f$ has exactly $n$ zeros in the disk $D_r$, contradicting the fact that $f$ is equal to zero in $[0,1]$.


Proof of Simple graph using vertex degrees

Question:
I think that this graph exists because the Handshaking Lemma says that the sum of the vertex degrees must be an even number. The sum of the vertices is, $1 + 2+3+4+4 = 14$ .  I know that a simple graph is a graph with no loops or multiple edges. I am confused on why this graph does not exist.
Comment: If a graph exists, it's degree sequence follows the handshaking lemma. That doesn't necessarily mean that if a degree sequence follows the handshaking lemma, the graph must exist.
Answer: You have 5 vertices, and two of them have degree 4, which means that both of them are connected to every other vertex, meaning that every vertex must have a degree of at least 2. So, you cannot have one with degree 1.


Calcular Custo Médio de uma posição de ações

Question: Olá, estou tentando criar uma query que calcula para todas as datas o custo médio da ação. A formula é descrita abaixo.
The Average Cost Price formula in T0 is: ((Accumulated Position T-1 * Av Cost Px T-1) + Qtty T0* Price T0)/ (Accumulated Position T-1+ Qtty T0)
Se o record é de venda, eu apenas subtraio a quantidade da posição aumulada e mantenho o custo médio
To perdido em como fazer isso, subquery não funciona para a mesma query, e não sei como pegar o valor de um record da mesma query. Qqr luz será bem vinda!
Exemplo
Na tabela abaixo tenho a negociação do ativo Yum. No primeiro dia, comprei 9 mil quantidades ao preço de 88.97. Então o custo médio é 88.97.
No segundo dia, comprei 3 mil quantidades a 89.81. Agora tenho 12 mil quantidades a um preço médio de 89.18. O calculo foi:
((preço Dia 0 * Quantidade Dia 0) + ((Av Cost Price Dia -1)*(Quantidade Acumulada Dia -1)) / (Qtd Acumulada Dia 0)
Todos os dias que tenho compra, faço esse cálculo. Se tenho uma venda, simplesmente uso o preço médio da última compra.
Para calcular a quantidade acumulada usei uma subquery.
╔═══════════╦════════╦══════════╦══════════╦════════════════╦═══════╦═══════════════╦═════════════╗
║   Date    ║ Ticker ║ buy_sell ║  Qtdade  ║ SumOfNotional  ║ Preço ║ Qtd Acumulada ║ Preço Médio ║
╠═══════════╬════════╬══════════╬══════════╬════════════════╬═══════╬═══════════════╬═════════════╣
║ 28-May-20 ║ YUM    ║ B        ║ 9,000    ║ 800,760.00     ║ 88.97 ║ 9,000         ║ 88.97       ║
║ 29-May-20 ║ YUM    ║ B        ║ 3,000    ║ 269,430.00     ║ 89.81 ║ 12,000        ║ 89.18       ║
║ 01-Jun-20 ║ YUM    ║ B        ║ 6,000    ║ 545,095.50     ║ 90.85 ║ 18,000        ║ 89.74       ║
║ 04-Jun-20 ║ YUM    ║ B        ║ 3,000    ║ 282,318.76     ║ 94.11 ║ 21,000        ║ 90.36       ║
║ 08-Jun-20 ║ YUM    ║ S        ║ (3,000)  ║ (287,970.00)   ║ 95.99 ║ 18,000        ║ 90.36       ║
║ 10-Jun-20 ║ YUM    ║ S        ║ (3,000)  ║ (284,558.70)   ║ 94.85 ║ 15,000        ║ 90.36       ║
║ 16-Jun-20 ║ YUM    ║ S        ║ (7,000)  ║ (654,720.91)   ║ 93.53 ║ 8,000         ║ 90.36       ║
║ 18-Jun-20 ║ YUM    ║ B        ║ 2,000    ║ 179,560.00     ║ 89.78 ║ 10,000        ║ 90.25       ║
║ 19-Jun-20 ║ YUM    ║ B        ║ 7,000    ║ 622,670.00     ║ 88.95 ║ 12,000        ║ 89.54       ║
║ 19-Jun-20 ║ YUM    ║ S        ║ (5,000)  ║ (457,820.00)   ║ 91.56 ║ 12,000        ║ 89.54       ║
║ 22-Jun-20 ║ YUM    ║ B        ║ 12,000   ║ 1,055,360.00   ║ 87.95 ║ 24,000        ║ 88.74       ║
║ 24-Jun-20 ║ YUM    ║ B        ║ 21,000   ║ 1,821,280.00   ║ 86.73 ║ 45,000        ║ 87.80       ║
║ 26-Jun-20 ║ YUM    ║ S        ║ (45,000) ║ (3,808,740.00) ║ 84.64 ║ -             ║ 87.80       ║
╚═══════════╩════════╩══════════╩══════════╩════════════════╩═══════╩═══════════════╩═════════════╝

SELECT db_TradeHistory.Date, db_TradeHistory.Ticker, db_TradeHistory.buy_sell, Sum(db_TradeHistory.Quantity) AS SumOfQuantity, Sum(db_TradeHistory.Notional) AS SumOfNotional, [SumOfNotional]/[SumOfQuantity] AS Preço, (SELECT Sum(Dupe.[Quantity]) AS SumOfQuantity
FROM db_TradeHistory AS Dupe
WHERE (((Dupe.Date)<=[db_TradeHistory].[Date]) AND ((Dupe.Ticker)=[db_TradeHistory].[Ticker]))
ORDER BY Sum(Dupe.[Quantity]) DESC) AS [Qtd Acumulada]
FROM db_TradeHistory
GROUP BY db_TradeHistory.Date, db_TradeHistory.Ticker, db_TradeHistory.buy_sell
HAVING (((db_TradeHistory.Ticker)="YUM"));

eu não sou expert em SQL e uso o Access pela interace e pois uso apenas para contole dessas posições, mas estou travado nesse problema, não sei se é possível fazer isso com SQL ou se tenho que tentar outra solução.
Comment: Isto responde à sua pergunta? [Exibir a Média em uma consulta SQL](https://pt.stackoverflow.com/questions/100270/exibir-a-m%c3%a9dia-em-uma-consulta-sql)
Comment: T0 é a posição inicial (tempo 0) ? T-1 a posição anterior ? Me parece difícil fazer isto no sql do ms-acess. Edite a pergunta para identar a sql e publique o modelo , um exemplo numérico ajudaria.
Comment: Oi Motta, isso. T0 é a posição do dia, e T-1 do dia anterior. obrigado pelas dicas, eu adicionei mais informações e o exemplo numérico do projeot. Por favor me avisa se é o suficiente. Abs!
Comment: Acho que ms-acess dificulta soluções do tipo totais acumulativos (running totals) e valores precedentes (lead & lag), o resto seria aplicar esta variante da média ponderada. Talvez seja mais fácil no Excel. https://www.techrepublic.com/article/how-do-i-generate-a-running-total-in-an-access-query/   https://techcommunity.microsoft.com/t5/access/available-lead-and-lag-function-in-ms-access/m-p/1401504
Answer: Creio que com meu problema possa ajudar em algo:
Tenho um problema parecido, mas construi de modo diferente pois não achei matéria específica.
Depois de ter homologado a tabela de inclusão de dados segui com virtual tables no SLQLITE até encontrar um problema que já estou  a muito tempo remexendo nele.  Primeiramente deve-se ter em conta que tudo que se refere  a ações enfim ativos de investimento é aplicado média ponderada e nao média simples, aí que esbarra no problema em que se temos uma tabela de compra e venda em uma só temos que limitar o stop para médias a
cada lote vendido e zerado, sendo assim deve haver novamente um reset e começar tudo de novo se for
recomprar um mesmo ativo por exemplo. Segue alguns trechos que elaborei ate chegar a isso:
tabela fonte:
  id       INTEGER PRIMARY KEY AUTOINCREMENT,
  idNC            INTEGER,
  data_pregao     DATE, '+
  num_nc          VARCHAR(12),
  C_V             VARCHAR(1),
  tipo            VARCHAR(12),
  ticker          VARCHAR(14),
  qde             FLOAT,
  saldo_qde       FLOAT,
  tot_item        FLOAT,
  tot_custos      FLOAT ,
  tot_opers_liq   FLOAT,         //calculado
  custo_item      FLOAT,         //calculado
  val_item_bru    FLOAT,         //calculado
  val_un_medio    FLOAT,         //vazio
  valor_total     FLOAT,         //vazio
  arquivado       DATE;

Determinar e Postar calculo da valor medio ponderado da unidade:
UPDATE tbtempor AS A SET val_un_medio = (SELECT
        (SUM(round(B.val_item_bru,2)) / SUM(round(B.qde,2)))
        FROM tbtempor AS B '+
        WHERE   B.C_V = "C" AND B.cod_ativo = A.cod_ativo
        GROUP BY cod_ativo);

Com esta tabela fonte em mãos e com os cálculos auxiliares prontos
sigo  para a tab teporária para a carteira atual:
CREATE  TABLE tbcarteira  AS
SELECT A.id,
A.data,
A.C_V,
A.tipo,
A.ticker,
SUM(A.qde) - '+         //ABATIMENTOS AQUI
                COALESCE((SELECT SUM(B.qde)
                FROM tbtempor AS B '+
                WHERE B.ticker = A.ticker   AND   B.C_V = "V"
                AND DATE(arquivado) IS  NULL),0)  AS qde,
A.val_item_bru,
A.val_un_medio,
A.valor_total,
A.arquivado
FROM tbtempor AS A
WHERE A.C_V = "C" AND DATE(A.arquivado) IS  NULL
GROUP BY ticker ;

Obs Não normalizei ticker ainda ate eu encontra uma solução.
coloquei um trigger para quando zerar alguma venda marcar onde. Mas nao consegui prosseguir
porque ele enxerga a tabela toda por GROUP BY e nao consigo marcar uma venda.
Enfim, mais um módulo em que demonstro as negociações e detalhes delas.
Ate aqui tudo bem mas como delimitar quando um lote vendido para iniciar outro??
Eu deveria dar uma resposta em vez de uma pergunta mas talvez este modelo de para tirar algum proveito.
Penso ate em migrar para esta forma por acúmulo de resultados mas nao sei se vale o esforço.
Comment: Olá Cafi. Visando unir a ideia da média acumulada mais a minha ideia de abranger um carteira toda, pergunto: Este exemplo é só uma parte do projeto? Ou Voce sempre utiliza desta forma, inserindo o ativo para pesquisa? Estou tentando adaptar o modelo de media acumulada para montar a tb toda e chegar a um resultado satisfatório. Mesmo que voce esteja utilizando outra ferramenta encorajo a não desistir. Unirei esforços.


notifyDataSetChanged() with PagerAdapter in Android

Question: I put the view pager in list view as row and want to update content of view pager when I scroll the list view . I have tried with  =
<code> @Override
        public int getCount() {

            // return PAGE_NUM;
            Log.e("intCount8888: "," = " +intCount );
            notifyDataSetChanged();
            return intCount;

        }
</code>
and I have calling the notifyDataSetChange on list Adapter also in getView()
<code>  @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        Holder holder = null;
        if (row == null)
        {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new Holder();
            holder.txt_Descid = (TextView) row.findViewById(R.id.textDescid);
            holder.txtTitle = (TextView) row.findViewById(R.id.txt_Desc);
            holder.txtInitialLetter = (TextView) row.findViewById(R.id.txt_InitialLetter);
            holder.txtRemark = (TextView) row.findViewById(R.id.textRemark);

            holder.imgBtn_Rework = (ImageView) row.findViewById(R.id.imgButtonRework);
            holder.imgBtn_FollowUp = (ImageView) row.findViewById(R.id.imgButtonFoloowUp);
            holder.imgBtn_RateEquipMent = (ImageView) row.findViewById(R.id.imgButtonRateEquipment);
            holder.imgBtn_Camera = (ImageView) row.findViewById(R.id.imgButtonCamera);
            holder.imgBtn_Audio = (ImageView) row.findViewById(R.id.imgButtonAudio);
            holder.imgBtn_FollowInspector = (ImageView) row.findViewById(R.id.imgButtonFollowInspector);

            holder.viewPager = (ViewPager) row.findViewById(R.id.Image_ViewPagers);

            holder.viewPager.setPageMargin(-50);
            holder.viewPager.setHorizontalFadingEdgeEnabled(true);
            holder.viewPager.setFadingEdgeLength(20);
            holder.viewPager.setClipToPadding(false);
            holder.viewPager.setPadding(-5, 0, 0, 0);
            MyPagerAdapter adapter = new MyPagerAdapter(getContext());

            holder.viewPager.setAdapter(adapter);
            holder.viewPager.setCurrentItem(0);
            adapter.notifyDataSetChanged();
            //holder.viewPager.getAdapter().notifyDataSetChanged();

            row.setTag(holder);
        } else {
            holder = (Holder) row.getTag();
        }

        All_Post all_Post = data.get(position);

        holder.txt_Descid.setText(Integer.toString(all_Post.getID()));
        String strTextDescId = holder.txt_Descid.getText().toString().trim();
        Log.e("strTextDescId ", " = " + strTextDescId);
        getActivityId(strTextDescId);
        getActivityObjectId_Count();

        holder.txtTitle.setText(all_Post.getName());
        String strTxtTitle = holder.txtTitle.getText().toString().trim();
        Log.e("strTxtTitle ", " = " + strTxtTitle);

        holder.txtInitialLetter.setText(all_Post.getInitName());
        holder.txtRemark.setText(all_Post.getStrDesc());

        holder.imgBtn_Rework.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("Button click ", "event is fire");

            }
        });
</code>
But getting error
<code>08-07 05:56:27.806    4475-4475/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.StackOverflowError
            at java.lang.IntegralToString.convertInt(IntegralToString.java:209)
            at java.lang.IntegralToString.appendInt(IntegralToString.java:173)
            at java.lang.StringBuilder.append(StringBuilder.java:139)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:553)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPosts_Page.java:554)
            at android.support.v4.view.ViewPager.dataSetChanged(ViewPager.java:882)
            at android.support.v4.view.ViewPager$PagerObserver.onChanged(ViewPager.java:2905)
            at android.database.DataSetObservable.notifyChanged(DataSetObservable.java:37)
            at android.support.v4.view.PagerAdapter.notifyDataSetChanged(PagerAdapter.java:276)
            at com.example.tazeen.classnkk.AllPosts_Page$MyPagerAdapter.getCount(AllPost
</code>
Answer: Notifydatasetchange() is used to tell adapter to update its list, when the data has changed. You do not call it in getView() or in getCount(). You have to call notifyDataSetChanged(), if you have added or removed any list item from the list View.
getView() method will inflate the view when you scroll the lisview. And getCount() method just returns the number of list items that ListView contains.
Comment: Thanks to reply , can you please explain me or suggest me how to do .  .
Comment: On phone so its hard to, but i can try. Whatever your using for data in adapter it must be a List of something, list of strings for instance. GetCount just needs to return the list.size() or the array.length. getView inflated that particular element in the list. So you grab it like theList.get(position). So if its like a string it be simple, if its a list of containers with bunch of data than peal out each piece and attach it in the getView(). But no need for notifydatasetchange unless you removed an item or added an item to the list of items.
Comment: Comment back if you dont get it. When i get to a pc ill throw down some code. Good luck


Which edition of SQL Server 2008 should I install on dev machine?

Question: Which edition of SQL Server 2008 should I install for development purposes?
I'm presuming the developer edition, but...
What I do is (SQL Server 2005 until now):

Develop databases to plonk onto our web server (that runs SQL Server Express)
Manage and extend these database using the SSMS (SQL Server Management Studio)
Develop SQL Server databases as a backend to MS Access apps

OTHER, SECONDARY QUESTIONS:
Can I have SQL Server 2005 and SQL Server 2008 installed on the same dev machine?
The reason for the question is that we are in the process of updating the webserver from a virtual server to a cloud server (Host:  www.orcsweb.com).  And, as all our databases are quite simple, have installed SQL Server Express 2008, so that future upgrades are less abrupt.
Would you expect any disruption in really simple databases by going from SQL Server 2005 to SQL Server 2008?
Answer: 1). Install Developer Edition (with the caveat, that it has all the Enterprise features, so you might use these and then find they're not there in Standard Edition...)
2) Yes. Both can be installed but one will need to be a named instance.
3). No. I'd be surprised if there were any problems going from 2005 to 2008.
Comment: Just don't ever try to go **back** from a 2008 database to a 2005 server - that's just plain not supported by Microsoft....


Why are high notes easier to sing in tune?

Question: I'm not sure that this is a universal phenomenon but even if it's not - what could be the reason that for many people it's easier to hit a stable pitch in their higher register?
Edit:
To be clear, in my personal case I am speaking about the higher part f my chest voice (below the bridge) vs the lower one, as measured by a pitch tracker. The former is much more in tune and stable.
Comment: Not even sure this is a fact..!
Comment: Perhaps the disconnect here is that "in tune" and "stable pitch" are not at all the same thing.
Comment: I would say the opposite is true. Are you speaking from personal experience, or did you read it somewhere?
Comment: "...but even if it's not..." that's your signal to change the question to "Are high pitches easier to sing?" and also look for some research on the topic.
Comment: If it *is* true, this could be about the fact that it's easier to assess intonation in the middle of our *hearing* register. If you play two notes, one after the other, a fifth apart, and detune one of them slightly, someone who could easily detect the detuning, and say whether the fifth was too narrow or too wide, might find it harder several octaves below or above middle C.
Answer: Interesting hypothesis.   Not, I think, a general rule.   But if some people find higher notes easier to stabilise, perhaps it's because they take a little more effort and are therefore sung with more conviction.
Answer: To answer the in tune part: there are some nice sound samples towards in the sample* section of the Wikipedia article Beat. Check for yourself, but the higher the frequency the faster the perceived amplitude change.
Answer: Definitely don't think it's a universal rule, but was certainly true for me. In my case it came down to the clear vs muddy vs flat vs sharp effect.
New singers often mistake tonality for pitch. So they may hear a singer sing with a muddy tone, and then mistakenly sing flat when trying to match pitch because they interpret the note as being sung low. Typically, higher notes will have a clearer tone, and can be less ambiguous.


Decreasing sequence in a normed space

Question: Consider by $p\geq 1$ the set $l^p=\{(x_n):x_n\in\mathbb{R},\,\,\sum |x_n|^p<\infty\}$. If defined  by $x\in l^1$ $$||x||_p=\left(\sum_{n=1}^{\infty} |x_n|^p\right)^{1/p}$$ How to prove that the sequence $(||x||_p)_{p\geq 1}$ is decreasing?
Answer: Suppose $x\in \ell^p$ with $\|x\|_p = 1$, $q > p$. Then we have $|x_n| \le 1$ for all $n$, that is $|x_n|^q \le |x_n|^p$, hence
$$ \|x\|_q^q = \sum_{n=1}^\infty |x_n|^q \le \sum_{n=1}^\infty |x_n|^p = 1 $$
This gives $\|x\|_q \le 1$.
If $x \in \ell^p$ is arbitrary, let $x' = x/\|x\|_p$. We have $\|x'\|_p = 1$, by the above $\|x'\|_q = \|x/\|x\|_p\|_q \le 1$, therefore $\|x\|_q \le \|x\|_p$. So $p\mapsto \|x\|_p$ is decreasing.
Comment: martini why if $\|x\|_p = 1$ then  $|x_n| \le 1$ for all $n$?
Comment: As $|x_n| = (|x_n|^p)^{1/p}\le (\sum_{k=1}^\infty |x_k|^p)^{1/p} = \|x\|_p$.
Comment: Ok. Thanks martini.

Decreasing sequence in a normed space


Django, upload two files on one page

Question: model.py:
class InJPG(models.Model):

    file_path = models.FileField(upload_to="media",unique=True)

views.py
from model import InJPG

def get_name(request):
    file1=InJPG(request.POST or None)
    file2=InJPG(request.POST or None)
    if file1.is_valid():
        file1.save()
    if file2.is_valid():
        file2.save()

    return render(request,'files.html',{'file1':file1,'file2':file2})

files.html
 ...

{% block page %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{file1}}
        <button type="submit">upload file1</button>
    </form>

    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{file2}}
        <button type="submit">upload file2</button>
    </form>
{% endblock %}

I have web page, where I can upload two files file1 and file2
problem:
I can load one file at once only, page is refreshing when I am uploading first file.
I want to Load both files using one button. or two load buttons without refreshing second form.
I am using two forms because i want to separate webpage and use there card classes
Comment: You can't use two different forms on a single page and expect both of them to work while submitting one of them. You either have to combine the forms into one or do some js and ajax calls to separate the submission since django template will pass the data and refreshes the page on the first submit.
Answer: That is because the files have to be passed to the same form as two separate inputs.
Try this:
{% block page %}

<form method="post" enctype="multipart/form-data" required="True">
    {% csrf_token %}
    <input type="file" name="file1">
    <input type="file" name="file2">
  <button type="submit">Submit both files</button>
</form>

 {% endblock %}

Comment: that will be another two inputs, having attribute type="text". e.g.
Comment: got it, so one form for one page then. so what should I do ,when I want to add field file_name? normally i can use form from views.py and add in my models char field, but in this `<input type=file` i dont see any option to show filename
Comment: I have one more question if I can ask, i am using one form but with my code , because i am using models.py/  when i am loading those two files when i am printing their names, it seems that both files are same. I am uloading file 1 and file 2 , but as result i am receiving two times file 2.  why? thanks
Comment: I suggest you to open a new question where you show your code.

Django, upload two files on one page


How do I find a (7, 3) parity check code generator matrix?

Question: Our teacher didn't mention what polynomial we're to use, or anything else much. All he said was to read about it online, which I did and apparently I need some polynomial of degree four to find the matrix. How do you find this polynomial and why doesn't any polynomial work? Also, what do you do after you have the polynomial, like how do you choose what message to encode and such? Thanks for your help.
Answer: You're not giving us much to go on, but maybe the matrix $$A=\pmatrix{1&0&0&1&1&0&1\cr0&1&0&1&0&1&1\cr0&0&1&0&1&1&1\cr}$$ is the matrix you are looking for. If you want to encode a message, first you turn that message into a bunch of length 3 bitstrings (by any method you like), then you multiply each bitstring, $v$, by the matrix $A$, giving you a length 7 bitstring that you send out as the encoded message. Maybe you want to search for "Hamming code" for a fuller explanation.
Comment: Well, I don't know how you go from polynomial to matrix, but I know that $G$ is no good. The 5th column's the same as the 1st; the 6th is the same as the 2nd; you're wasting those two bits. Probably this happens because you chose a reducible polynomial.
Comment: Thanks for your answer. Would the explanation for how you came about constructing the matrix also be there?
Comment: I don't know. Why don't you try?
Comment: I 'll do that now. :) Thanks again.
Comment: I came up with another matrix using $p(x) =1+x+x^3+x^4$   $$G=\pmatrix{1&0&0&1&1&0&1\cr0&1&0&1&0&1&1\cr0&0&1&1&0&0&0\cr}$$ Would this also be correct? I'm confused about the polynomials one chooses and I didn't find any literature that I could understand addressing this problem.


Qual problema com as minhas saídas da tabela verdade?

Question: Estou treinando como extrair uma tabela verdade, a partir de um enunciado em português, o qual peguei o seguinte exercício:

A figura acima representa o cruzamento das ruas A e B. Neste cruzamento queremos instalar um sistema automático para os semáforos com as seguintes características:

1) Quando houver carros transitando somente na Rua B, o semáforo 2 deverá permanecer verde para que estas viaturas possam trafegar livremente.
2) Quando houver carros transitando somente na Rua A, o semáforo 1 deverá permanecer verde pelo mesmo motivo.
3) Quando houver carros transitando nas Ruas A e B, deveremos abrir o semáforo para a Rua A, pois é preferencial.

Após isto indo para as respostas o autor me diz o seguinte:

A situação 0 (A = 0 e B = 0) representa a ausência de veículos em ambas as ruas. Se não temos carros, tanto faz qual sinal permanece aberto. Vamos adotar, por exemplo, que o verde do sinal 2 permaneça acesso. Neste caso, preenchemos a tabela verdade da seguinte maneira:

Logo o resultado da tabela verdade do autor é o seguinte:

Em seguida após a aplicação do mapa k, segundo autor o circuito lógico é o seguinte:

Segue agora o que EU FIZ:
PS: O restante da saída é idêntica ao do autor!

Mapa K para as saídas:

Qual a minha dificuldade?

1) Fiz o inverso do autor em relação as primeiras saídas (A=0 e B=0), por conta da afirmação do mesmo descrita acima. Então qual é o problema que está ocorrendo com a minha tabela verdade?
2) Seguindo princípio da pergunta (1), porque o meu mapa K está tendo problemas?
3) Qual o modo correto de analisar esta situação?
Answer: 1)No seu caso, você arbitrou que caso não haja carros passando em nenhuma das ruas, o sinal da rua 1 fica verde, e o da rua 2 vermelho.
Isso não é nenhum problema. Qualquer combinação de valores para a tabela verdade é válida.
2) Se entendi bem, você não conseguiu obter a expressão para Sv2 e Svm1. Neste caso, e com a convenção que você escolheu utilizar, o agrupamento (Na sua imagem, o retângulo azul) que você deve fazer contem um só elemento.
Não se é obrigado a fazer agrupamentos com mais de um elemento.
Em ambos os casos você irá agrupar só o caso em que A=0 e B=1, retornando a expressão:
Sv2 = Svm1 = A'B
3)Nestes casos, em que para alguns casos o valor final pode ser qualquer um, costuma-se marcar com um X, chamado de termo "Don't Care" [0] (do inglês, "não importa"). Assim, ao montar a tabela verdade, você pode agrupá-los ou não conforme for mais vantajoso e gerar a expressão mais curta.
No seu caso, isso permitiria você economizar um agrupamento na expressão de Sv1 e Svm2, que ficaria apenas: Sv1=A
Na segunda e terceira expressão, isso permitira agrupar a linha superior, gerando a expressão:
Sv2 = Svm1 = A'
Fazendo isso, você economizaria algumas portas lógicas e diminuiria o tamanho do circuito. Concluímos com os agrupamentos que a convenção utilizada pelo autor é a mais vantajosa, e por isso o circuito dele ficou tão compacto. Pelo que você contou, ele apenas não narrou como chegou a essa escolha.

Edit: Melhorando alguns pontos conforme pedido no comentário:
Qualquer agrupamento que você fizer deve agrupar uma quantidade de elementos igual uma potência de 2, isto é, 1,2,4,8, etc...
Agrupar uma quantidade de elementos maior sempre vai resultar em uma expressão menor. Você já fez isso em seu exercício, na tabela de Sv1, você agrupou uma linha e uma coluna. Você poderia ter, erroneamente, agrupado apenas a linha e o outro elemento independente, de forma que a expressão resultante seria:
Sv1=A+B'A', isto é, uma expressão maior.
Com isto definido, se em algum dos casos não faz diferença o valor da saída ser 0 ou 1, como quando não há carros na rua, é bom escolher o melhor valor para simplificar a expressão ao máximo.
No exemplo que você citou:
[...]só tinha achado um x e somente um bit 1 do lado dele[...]
Nesse caso, o X está representando que tanto faz o valor ali ser "0" ou "1". Isto é, para o problema em questão, não faz diferença a saída nessa situação. Seria útil para nós que fosse "1", visto que desta forma, poderíamos agrupar dois elementos ao invés de um só, então agrupamos o 1 com o X, pois foi vantajoso para reduzir o tamanho da expressão. Resumindo: Quando for fazer os agrupamentos, as lacunas com X podem ser usadas para agrupamento, mas não precisam ser inclusas necessariamente. Inclua-as nos seus agrupamentos conforme for vantajoso.
Sobre comparar com múltiplas saídas: Como todas as saídas dependem das mesmas entradas, comumente elas são escritas em uma mesma tabela, como colunas extras, como a imagem que você postou mostra. Elas podem ser interpretadas como múltiplas tabelas verdade escritas de forma mais compacta. Para comparar a saída, cada expressão encontrada por você vai preencher uma coluna da tabela verdade. Se os valores de uma dada coluna conferem, isso significa que aquela saída (neste caso uma luz verde/vermelha) irá reagir corretamente.
[0] - https://en.wikipedia.org/wiki/Don%27t-care_term
Comment: Ôpa! Editei a resposta contendo os esclarecimentos que você pediu.
Comment: 1) Eu vi em outros exemplos este "Dont care", onde no mapa k só tinha achado um x e somente um bit 1 do lado dele, o autor juntou os dois e fez uma expressão. Poderia fornecer mais detalhes sobre o mesmo? 2) eu gostaria de testar a expressão encontrada por ele, geralmente eu pego a expressão final monto a tabela verdade da mesma e comparo com a original, porém neste exemplo como eu faço isto? Pois são diversas saídas


How do I extract a substring between two characters using split()?

Question: I'm having trouble taking out a substring located between the third occurrence of "." and the first occurrence of ":" in a line containing the word "foo". It would be helpful if someone could explain what numbers should go in the brackets and why.
    for line in myfile:
        if "foo" in line:
            substring=line.split('.')[].split(':')[]
            print(substring)

My Google searches have led me mainly to people suggesting Regex but I would rather not use that to be honest as I am a newbie at Python - I would prefer not to complicate things. I'd like to use split(). But I'm not sure what numbers to put in the brackets and every website I read just confuses me more and more.
I appreciate any help! Thanks
Comment: The easiest for you to figure this out is to try by yourself, on an example of the data I think :) First look at what `line.split('.')` looks like, then select the element you want to keep in there, and keep chaining all the functions, while taking a look at every step to make sure you understand what's going on
Comment: Can you guarantee that the first occurrence of ':' is after (at least) 3 occurrences of '.'?
Comment: yes, it always is
Answer: Given your numbers, you could try something like this:
for line in myfile:
    if "foo" in line:
        substring = line.split(".", 3)[3].split(":")[0]
        print(substring)

line = "a.b.c.d.e.f:foo"
s = line.split('.', 3)[3]
# "d.e.f:foo"
s.split(':')[0]
# d.e.f

This uses the maxsplit paramter of split(sep=None, maxsplit=-1) which can limit the number of splits.
Comment: This only works if there are exactly 3 periods. For example, if the line is 'a.b.c.d.e.f:foo' the output would be 'd' whereas it should be 'd.e.f'. From the question "...substring located between the third occurrence of "." and the first occurrence of ":"" Perhaps *'.'.join(s.split('.')[3:]).split(':')[0]* would be better
Comment: @Pingu
Amended my answer to use the maxsplit param.


Getting mentions and DMs through twitter stream API 1.1? (Using twython)

Question: I'm using twython (twitter API library for python) to connect to the streaming API, but I seem to only get the public twitter stream possibly filtered by words. Isn't there a way to get a real-time stream of the authenticated user timeline or @mentions?
I've been looping through delayed calls to the REST API to get those mentions but twitter doesn't like me to make so many requests.
Twython documentation isn't helping me much about it, neither is the official twitter doc.
If there's another python library that can work better than twython for streaming (for Twitter API v1.1). I'd appreciate the suggestion... Thanks.
Answer: In the beginning of my research I thought python-twitter is the twitter library for Python. But finally, it seems as if the Python Twitter Tools are more popular and support also twitter streaming.
It's a bit tricky, the streaming API and the REST api are not equal for direct messages. This small example script demonstrates how you can use the user stream to get direct messages:
import twitter # if this module does not
               # contain OAuth or stream,
               # check if sixohsix' twitter
               # module is used!
auth = twitter.OAuth(
    consumer_key='...',
    consumer_secret='...',
    token='...',
    token_secret='...'
)

stream = twitter.stream.TwitterStream(auth=auth, domain='userstream.twitter.com')

for msg in stream.user():
    if 'direct_message' in msg:
        print msg['direct_message']['text']

This script will print all new messages - not the ones already received before starting the script.
Answer: There is no way to stream direct messages.
However, there is a way to stream a users timeline. Check out the documentation on Twitter here: https://dev.twitter.com/docs/streaming-apis/streams/user
from twython import TwythonStreamer

class MyStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            print data['text'].encode('utf-8')
        # Want to disconnect after the first result?
        # self.disconnect()

    def on_error(self, status_code, data):
        print status_code, data

# Requires Authentication as of Twitter API v1.1
stream = MyStreamer(APP_KEY, APP_SECRET,
                    OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

stream.user()

Until a new version of requests (https://github.com/kennethreitz/requests) is released, however, tweets from your followers will be one post behind. This should be fixed relatively soon though! :)
Comment: This seems to be wrong. Direct message streaming is mentioned here: https://dev.twitter.com/docs/streaming-apis/streams/user#Direct_messages
Comment: Oh, I'm sorry; I never saw that documentation.
Comment: Update or delete your answer to reflect DM streaming.


TweenSequence Ignores TweenSequence Items

Question: Hi I want to continuously Fade an Image in and out in my Flutter App.
For That I use a TweenSequence:
<code>AnimationController animationController;
  Animation<double> opacityAnimation;
  double opacity = 0.5;

  @override
  void initState() {
    super.initState();
    animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 3));
    opacityAnimation = TweenSequence(
      [
        TweenSequenceItem<double>(
            tween: Tween<double>(begin: 0.5, end: 1.0).chain(
              CurveTween(curve: Curves.bounceIn),
            ),
            weight: 50),
         TweenSequenceItem<double>(
             tween: Tween<double>(begin: 1.0, end: 0.5).chain(
               CurveTween(curve: Curves.bounceIn),
             ),
             weight: 50),
      ],
    ).animate(animationController);
    animationController.addListener(
      () {
        setState(() {
          opacity = animationController.value;
          print(opacity);
        });
      },
    );
    animationController.repeat();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Stack(
        children: [
          Image.asset("assets/images/buildup_0.png"),
          Opacity(
            child: Image.asset("assets/images/Logo_K.png"),
            opacity: opacity,
          ),
        ],
      ),
    );
  }
}
</code>
However, the animation just ignores the Tweens i gave it and animates between 0 and 1, jumps back to 0 and repeats. I can see that in my console due to due to the print statement. Am I missing something obvious here?
Answer: I just found the solution: Instead of setting opacity to animationController.value I needed to set it to opacityAnimation.value


Safari on iPhone 3g fixed position of a button

Question: I have the following jsfiddle setup:
http://jsfiddle.net/zZDqH/
Currently it is just a button that is fixed in position at bottom:0px, you can scroll up and down the page and the button remains at the bottom of the page.
When tested in Safari on an iPhone 3G (v4.2.1) the buttons position does not remain at the bottom of the page, so when you scroll the button moves position.
Any advice on how to get this working would be appreciated.
Thanks
Answer: Position fixed is not supported in older versions of ios.
It's answered here CSS "position: fixed;" on iPad/iPhone?.


Ajuda com a função query_post WordPress

Question: Eu estou tentando fazer uns posts personalizados no meu tema WordPress, porém estou com um problema.
Eu quero pegar sete Postagens na página principal, minha index. Porém a primeira postagem eu vou estilizar de forma diferente das outras seis.
Eu estou repetindo o query_posts(). Na primeira eu coloquei assim:
Eu estou usando isso para pegar a primeira postagem.
query_posts('posts_per_page=1')
if (have_posts()) : while (have_posts() ) : the_post();
E para as demais eu estou repetindo o código com um parametro diferente.
query_posts('posts_per_page=5')
if (have_posts()) : while (have_posts() ) : the_post();
O problema é que a primeira postagem está se repetindo nos dois blocos. Eu queria saber se tem algum parâmetro que eu possa usar no segundo bloco para dar um "salto" começar a pegar as postagens a partir do 2.
Answer: Galera achei a solução!
É só passar o seguinte parametro na função query_posts():
query_posts('showposts=4&offset=1');
Answer: Não é recomendável utilizar a função query_posts. Veja o que é dito na documentação do WordPress:

Nota-se que utilizar este método pode extender o carregamento da página, uma vez que a consulta principal é chamada mais de uma vez. Em alguns cenários pode ser pior, chegando a dobrar o número de processos executados desnecessariamente. Embora simples de ser executada, a função também é propensa a acarretar problemas futuros.

A sugestão é usar a classe WP_Query ou a função get_posts. Exemplo de utilização da classe WP_Query:
<?php

    // WP_Query arguments
    $args = array(
    );

    // The Query
    $the_query = new WP_Query( $args );

    // The Loop
    if ( $the_query->have_posts() ) {
        echo '
';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            echo '
' . get_the_title() . '
';
        }
        echo '
';
    } else {
        echo '
Nenhum post encontrado
'
    }
    /* Restore original Post Data */
    wp_reset_postdata();

Ajuda com a função query_post WordPress


Difference between Array.apply(null, Array(x) ) and Array(x)

Question: What exactly is the difference between:
Array(3)
// and
Array.apply(null, Array(3) )

The first returns [undefined x 3] while the second returns [undefined, undefined, undefined]. The second is chainable through Array.prototype.functions such as .map, but the first isn't. Why?
Comment: Related: http://stackoverflow.com/questions/22949976/why-does-array-applynull-args-act-inconsistently-when-dealing-with-sparse-a
Comment: `Array.apply(null, Array(9))` is *not* `new Array(9)`. It is spreading an `Array(9)` into `Array()` as nine parameters.  Even if it works it is pretty much the wrong way.  For example you can `new Array(1e7)` but not `Array.apply(null, Array(1e7))`.
Answer: There is a difference, a quite significant one.
The Array constructor either accepts one single number, giving the lenght of the array, and an array with "empty" indices is created, or more correctly the length is set but the array doesn't really contain anything
Array(3); // creates [], with a length of 3

When calling the array constructor with a number as the only argument, you create an array that is empty, and that can't be iterated with the usual Array methods.
Or... the Array constructor accepts several arguments, whereas an array is created where each argument is a value in the array
Array(1,2,3); // creates an array [1,2,3] etc.

When you call this
Array.apply(null, Array(3) )

It get's a little more interesting.
apply accepts the this value as the first argument, and as it's not useful here, it's set to null
The interesting part is the second argument, where an empty array is being passed in.
As apply accepts an array it would be like calling
Array(undefined, undefined, undefined);

and that creates an array with three indices that's not empty, but have the value actually set to undefined, which is why it can be iterated over.
TL;DR
The main difference is that Array(3) creates an array with three indices that are empty. In fact, they don't really exist, the array just have a length of 3.
Passing in such an array with empty indices to the Array constructor using apply is the same as doing Array(undefined, undefined, undefined);, which creates an array with three undefined indices, and undefined is in fact a value, so it's not empty like in the first example.
Array methods like map() can only iterate over actual values, not empty indices.
Answer: The .map() API does not iterate over completely uninitialized array elements. When you make a new array with the new Array(n) constructor, you get an array with the .length you asked for but with non-existent elements that will be skipped by methods like .map().
The expression Array.apply(null, Array(9)) explicitly populates the newly-created array instance with undefined, but that's good enough. The trick is whether or not the in operator will report that the array contains an element at the given index. That is:
var a = new Array(9);
alert(2 in a); // alerts "false"

That's because there really is no element at position 2 in the array. But:
var a = Array.apply(null, Array(9));
alert(2 in a); // alerts "true"

The outer call to the Array constructor will have explicitly populated the elements.
Comment: http://es5.github.io/#x18.104.22.168 `Function.prototype.apply` also doesn't really care if `argArray` is a true _Array_ as long as it is a readable _Object_, `Array.apply(null, {length: "2.5"}); // [undefined, undefined]`
Comment: @mb_s88 consider `0 in Array(9); // false`
Comment: Thanks for the answer, I wasn't really sure that what was 'in' each slot wasn't the same as the value undefined, since indexing into any given position returns undefined.
Comment: @mb_s88 answer extended a little bit
Answer: This is an artifact of how apply works. When you do:
new Array(9)

an empty array is created with a length of 9. map does not visit non–existent members, so does nothing at all. However, apply turns the array into a list using CreateListFromArrayLike so it turns the formerly empty array into a parameter list like:
[undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined];

that is passed to Array to create an array with 9 members, all with a value of undefined. So now map will visit them all.
BTW, ECMAScript 2015 has Array.prototype.fill for this (also see MDN) so you can do:
Array(9).fill(0);

Comment: The question is if performance-wise you're better off using Array.apply(null,length) or Array(length).fill()
Comment: @Jony-Y—not an important one. I'd use whichever suited my situation best, micro-optimisations should be the last consideration. :-)
Answer: Because the first array would not have ordered properties arr[0] === undefined and the second does. Array functions like forEach and map will iterate from 0 to the array's length - 1 and the lack of order to the properties of the first is an issue. The second version produces an array with the correct ordering, i.e.
arr = Array.apply(null, Array(3));
arr[0] === undefined //true
arr[1] === undefined //true
//etc.

The first version as you noticed doesn't. Also, adding new to the first version would not make it work.
Answer: In the first case you have one operation

Array(3)

Its creates an array with three empty slots. Not an array with the three undefined values but exactly - empty.
At the second case

Array.apply(null, Array(3) )

we can spread it to the three operations:

first: Array(3) - you get an array with 3 empty slots;
second: Array(3) spreads by Function.prototype.apply() function to 3 parameters that it passes to Array() function. At this stage 3 empty slots in given array transformes by apply() to 3 undefined values (it looks like if apply() sees an empty slot it automaticaly turns it to undefined in any sparsed array).
third: we get an Array(undefined, undefined, undefined). And that will do to us an array with 3 undefined (not empty) values.

Because now you have 3 undefined but not empty slots, you can use them with map() function.
Note that not only Function.prototype.apply() have such behavior of decomposing arrays by such way. You can also do this in ECMAScript 6 by "..." - spread operator.
Array(...new Array(3));

This will also returns an array with 3 undefined and respectively can be mapped slots.
Here i giving more detailed explanation.
https://stackoverflow.com/a/56814230/11715665


How to read individual lines of a text from the isolated storage?

Question: (EDITED)
My codes doesn't read the text file. Apparent;y, when I want to read the file, they gave me a "File Not Found!" message box which it is in the if else loop, indicating that the code in the if loop doesn't work.
        private void OnSaveFile()
        {
            if (!string.IsNullOrEmpty(this.FileName))
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(FileName))
                        store.DeleteFile(FileName);

                    using (var fileStream = store.OpenFile(FileName, FileMode.Create, FileAccess.Write))
                    {
                        using (var writer = new StreamWriter(fileStream))
                        {

                            writer.WriteLine(FileName);
                            writer.WriteLine(FileText1);
                            writer.WriteLine(FileText2);

                        }
                    }
                }
            }
        }

        private void OnReadSelected()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(FileName))
                {
                    using (var fileStream = store.OpenFile(FileName, FileMode.Open, FileAccess.Read))
                    {
                        using (var reader = new StreamReader(fileStream))
                        {
                            FileName = reader.ReadLine();
                            FileText1 = reader.ReadLine();
                            FileText2 = reader.ReadLine();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("File not found!");
                }
            }
        }

CreateTextPage:
 private void Button_Click(object sender, RoutedEventArgs e)
        {
            AddFileModel model = this.LayoutRoot.DataContext as AddFileModel;
            model.SaveFile.Execute(null);
            model.FileName = string.Empty;

            model.FileText1 = string.Empty;
            model.FileText2 = string.Empty;

            MessageBox.Show("File saved successfully");

            NavigationService.Navigate(new Uri("/CompleteQuestionPage.xaml", UriKind.Relative));

        }

ReadFilePage:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        AddFileModel model = this.LayoutRoot.DataContext as AddFileModel;
        model.ReadSelectedFiles.Execute(null);

    }

Comment: Sorry, I really can't keep on with this. I'm trying to get breakfast for the kids and do 101 other things at the same time (otherwise I'd have taken this to chat a long time ago). I strongly suggest you read http://tinyurl.com/so-hints and rewrite your question so that it's *absolutely clear* what you're seeing... which isn't the case at the moment.
Comment: The code you've posted wouldn't even compile - `reader` will be out of scope for the second `ReadLine` call, due to not using braces on the inner `using` statement. Please post the *actual* code which is failing.
Comment: @Jon Skeet - Sorry, I don't get what you mean. However, i am indeed getting errors for the reader. They said reader does not exist in the current context. And I was told by someone if i align reader.ReadLine(); like this, it will allow the text to be shown on diffeerent text box instead of a string of text on 1 text box.
Comment: @Jon Skeet-Thanks, I've finally know what I'm missing. Still, I can't read the file as it is still giving me the FileNot Found messagebox.
Comment: But that shows that the code you gave before *isn't* the code you had when you first got the exception. Is this now *really* the code you've got? If you step through with a debugger, presumably an exception is thrown - what *exactly* are the details of that exception?
Comment: @Jon Skeet- they said the store value is null. Btw, this set of codes are in a class file. I'm using data binding method to save and get the text.
Comment: What do you mean by "they said the store value is null" - who? Where? If that was an exception message, when I said "what exactly" I meant "cut and paste them".
Comment: @Jon Skeet-             `using (var store = IsolatedStorageFile.GetUserStoreForApplication())` has a null value under the OnReadSelected.
Comment: Sorry, you're still not being very clear. You've shown a line of code - do you mean that the value of `store` is null? *After* executing that line?
Comment: @Jon Skeet- i debugged that line, is it correct?
Comment: What *exactly* do you mean by "I debugged that line"? Please try hard to be clearer - I'm having to ask for a clarification of just about everything you say.
Comment: @Jon Skeet- I'm really sorry, i dun really know much about c# programming and the features on the visual studio. I think it meant that I've been saving null values. That's why the store has nothing inside it. Is it because of the way I data bind the controls?
Comment: No, if the value of `store` is null, that has nothing to do with the value inside the file - it's before you even *get* to the file. It seems very unlikely that `GetUserStoreForApplication` would return null though.
Comment: @Jon Skeet- If you dun mind, may i post the XAML, the codes behind that calls this method, and the complete class file itself? I dunno where the problem might be.
Comment: The XAML is completely irrelevant to that line of code. If `store` really is `null`, something very odd is going on.
Comment: @Jon Skeet- it could be the way I data bind was wrong? i named my control which i want to input a text as textFileName, with the Text Binding to FileName, Mode=TwoWay. And the textblock on the different page is named titleText, with the Text Binding as FileName too, Mode=Twoway. And I've added the complete class file to the question, and the 2 codes that calls the method.
Comment: Nothing in the line of code assigning a value to `store` uses any data binding. *If* the value of `store` is null, there's something else going on. But you still haven't explained what you meant by "I debugged that line".
Comment: @Jon Skeet- I debugged the line `using (var store = IsolatedStorageFile.GetUserStoreForApplication())` which is under the `public void OnReadSelected()`. Do check my edited question, i hope it might help in your assistance.
Comment: Sorry, you still haven't said what you *mean* by the phrase "I debugged the line" - you've said that value of `store` is null, do you mean *after* you've executed the line. I'm afraid I don't think I can help you, as we're clearly not communicating properly...
Comment: @Jon Skeet- i'm sorry. That error shows when i'm about to execute that line. Please tell me if this clear your doubts. I really need your help, and i'm sorry i wasn't co-operating well.
Comment: Which error? *Please* try to read your comments from the point of view of someone who can't see over your shoulder. If you mean the message box, how could that show *before* you even execute the first line of the method which is going to show it?
Comment: @Jon Skeet -mind if i post a screen shot? I really dunno how to explain it. And you are right, it is weird that the MessageBox will be executed if the codes before it should not work. So i tried to debug another line and i've got an error with that.
Comment: Is this the problem you were having as when you asked me? You really need to clarify the problem as it's almost impossible to understand what's going on like last time.  IIRC, you got this code from somewhere else (and you're using MVVM). I think this might be tripping you up a bit because you don't know exactly what's happening when you have someone else's code. Try recreating the problem in a new project. Read and write from the Isolated Storage and once you have that, you can move that code into your main project.
Comment: @keyboardP -true, and once again i really appreciate the helps and answers i get, even some have taught me of how wrong and how bad i was.
Comment: @lala -Helping's no problem, we all have to learn sometime :) It's just quite difficult to help when the problem isn't all that clear
Answer: In your OnSaveFile method, it looks like you're saving the data to a file called "myfile.txt". In OnReadSelected you're opening a file using the 'Filename' property. What is 'Filename' set to? Because if it is not set to "myfile.txt", then that's probably why you're seeing 'File not found'.
Try changing
using (var fileStream = store.OpenFile("myfile.txt", FileMode.Create, FileAccess.Write))

to
using (var fileStream = store.OpenFile(Filename, FileMode.Create, FileAccess.Write))

Also, change
using (var reader = new StreamReader(fileStream))

FileName = reader.ReadLine();
FileText1 = reader.ReadLine();
FileText2 = reader.ReadLine();

to
using (var reader = new StreamReader(fileStream))
{
   FileName = reader.ReadLine();
   FileText1 = reader.ReadLine();
   FileText2 = reader.ReadLine();
}

to get your code to compile.
UPDATE:
Okay, right now in your button click handler you're doing this:
model.SaveFile.Execute(null);
model.FileName = string.Empty;

You're setting the value of 'Filename' to be an empty string; later on, you're called OnReadSelected again, which uses the value in 'Filename'. Since it's been set to an empty string, I think that's why you're seeing 'File Not Found'. What happens if you remove the line
model.FileName = string.Empty;

? Do you still get 'File Not Found'?
Comment: @E.Z.-btw, i've an error where they say reader does not exist in the context. And thanks for pointing that out
Comment: @lala - see Jon Skeet's comment above - you're missing a set of braces around the code following "using (var reader = new StreamReader(fileStream))". That's why you're seeing 'reader does not exist'.
Comment: -I'm still getting the "File not Found!" Message Box.
Comment: How are you calling your methods? I just tried calling 'OnSaveFile' and then 'OnReadSelected' and it worked just fine.
Comment: -Would you mind if i send you the app and check for me? I swear, it is really messy. This is jsut a small portion of the codes. And I really dunnno who to turn to at this point of time.
Comment: I mean I'm serious. If you want, i can paste the whole codes here if it helps. I'm using a data binding format to get the text from the controls. The Save and Read codes are in a class file.
Comment: @lala I updated my answer - see if that change fixes your problem.
Comment: You've solved the problem @_@ I've always thought that that line of code will clear the inputted text as it is a good habit to clear off what the user has typed previously after he/she leaves the page. Thank you so much! And to the others that tried to help as well @_@
Comment: ok, that isn't the answer. The codes are just getting the words inside the textbox, and it isn't reading it from the saved file. That's why if i delete that line of code, it will just retrieve the text from the uncleared textbox after being used.
Comment: I think the original problem has changed enough that it might be a good idea to open up a new question with the current code and the current problem you're having.


How to set up the matrix in data generation in R?

Question: I am trying to generate two continuous predictors and one continuous outcome from mvrnorm. Now, I am trying to set up both standardized slopes at 0.3.
This is my R code.
n.tr=10
mu = c(3, 3, 3)
Sigma = cbind(c(0.91,0,0.3),
              c(0 0.91,0.3),
              c(0.3,0.3,0.91)
dat =  as.data.frame(mvrnorm(n=n.tr, mu=mu, Sigma=Sigma,
                     empirical=TRUE))
colnames(dat) = c('z', 'w','y')

I want both of the standardized slopes to be 0.3, and 0 correlation between z and w. I also want the variance of y to be 1, so the residual variance of y is 0.91. If i want the diagonal of the matrix to be residual variance, how can I set up the matrix?
Comment: Could you please explain what you mean by "set up" and also indicate what your statistical question might be?
Answer: If X, W are independent, then the covariance between two predictors is related to the regression slope by:
$\beta_{Y|X} = \text{Cov}(X,Y)/\sqrt{\text{Var}(X)}$
So your Sigma matrix should be modified. If $\text{Var}(X)$ is set to 1 instead of 0.91 you will have the correct regression coefficient from the covariance matrix.
You have correctly constrained the conditional variance of $Y$ to be 0.91. If you want the total variance of $Y$ additionally to be 1 you can apply the law of total variance:
$$ \text{Var}(Y) = E(\text{Var}(Y|X)) + \text{Var}(E(Y|X))$$
The first term is recognizable as the conditional variance, i.e. 0.91, the second term reduces to $$\text{Var}(E(Y|X)) = \beta_1^2 \text{Var}(X) + \beta_2^2 \text{Var}(W)$$
So if we control this parameter first, assuming $\beta_1 = \beta_2 = 0.3$ then one choice of the regressor variance is 0.5 for both $X$ and $W$. Then the constrained solution for the covariance of X,Y and W,Y would be set to $0.3/2=0.15 $ to meet the requirements you laid out.
> x <- rnorm(1e6, 0, sqrt(0.5))
> w <- rnorm(1e6, 0, sqrt(0.5))
> y <- rnorm(1e6, 0, sqrt(0.91))
> y <- y + 0.3*x + 0.3*w
> var(y)
[1] 0.9998229
> lm(y ~ x+w)

Call:
lm(formula = y ~ x + w)

Coefficients:
(Intercept)            x            w
  -0.001749     0.299974     0.301086

> var(lm(y ~ x+w)$residual)
[1] 0.9094854

> round(var(cbind(y,x,w)), 2)
     y    x    w
y 1.00 0.15 0.15
x 0.15 0.50 0.00
w 0.15 0.00 0.50

Comment: Thanks! can you be more specific about how to set up the matrix?  so according to your comments, the matrix should be like (0.5,0,0.6) (0,0.5,0.6) (0.6,0.6,1)?
Comment: @April the approach (easier than mvrnorm) and the actual covarince mat is below.
Comment: it works! thank you so much!!
Answer: Here are some tips:

Always set the random seed to make it fully reproducible.  Later, you'll be able to figure out what you did.
I would create the matrix using rbind(), instead of cbind(), so that it's easier to see the matrix you are creating.
Likewise, I add decimal places and spaces so that the values are aligned.  That makes for a better gestalt, and it's easier to see what you have at a glance.
(You seem to be missing a comma and a closing parenthesis.)
It's easier to make everything standard normal (i.e., variances equal to 1, and off-diagonal elements correlations), and rescale afterwards to whatever means and SDs you want.
It's easiest to use mvrnorm() to generate the matrix of X variables, and then generate the Y data using a regression type specification.  Again, it's just easier to see that what you have written matches what you have in mind.

With those suggestions, here is how I might adapt your code:
set.seed(1)
n.tr  = 10
mu    = c(0, 0)
Sigma = rbind(c(1,0),
              c(0,1) )
X     = mvrnorm(n=n.tr, mu=mu, Sigma=Sigma, empirical=TRUE)
z     = X[,1]
w     = X[,2]
y     = 3 + .3*z + .3*w + rnorm(n.tr, mean=0, sd=sqrt(.91))
dat   = data.frame(z=z, w=w, y=y)

Comment: if the betas are set to be 0.3, the estimated betas in lm() should be 0.3 as well, right?
Comment: @April, yes, that's what you're hoping for. Due to sampling error, they won't be exact, but in the long run, the sampling distribution of estimated betas should be centered on that.
Comment: Helpful answer. The empirical argument is logical, and if true, mu and Sigma specify the empirical not population mean and covariance matrix. This I think means that the variates will have a mean and covariance matrix similar to the mu and Sigma arguments entered into mvrnorm. For your example you selected empirical to have more determinism / control to provide to your regression equation? Rephrased, when to opt for the empirical setting in mvrnorm?
Comment: @SingleMalt, excellent point. I just copied that part over without thinking about it, which was perhaps a poor choice. I never use `empirical=TRUE`.
Comment: Possibly (a guess) selecting for "empiricism" is computationally slower, although this would not be an issue with the above sample size. Using empirical=TRUE presumably could be useful for exposition purposes (like here) as in a sense it reduces the level of randomness from the programmers perspective since they know (input) mu and Sigma.
Comment: @gung-ReinstateMonica, that makes sense. i used your code and run the model y~z+w in lm(), the residual variance is no where near 0.91. should the residual variance be close to 0.91?
Comment: TBH, I haven't run it, @April. But it should vary due to sampling variation.
Comment: @gung-ReinstateMonica, thanks! but how can i make sure that these codes are doing what i want them to do?
Comment: I'm not sure I follow your question, @April. You look at them & you (should) understand how R code works (if you're going to use R). Data are supposed to be random--that's the nature of the business we're in.


Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in@babel/helper-compilation-targets/package.json

Question: Recently, I got unexpected problem when deploying my Ruby on Rails app
to Heroku:
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main resolved in node_modules/@babel/helper-compilation-targets/package.json

To be honest, I do not have any idea because I did not touch any javascript code at all, does anyone encounter this error and resolved it?
Here is the full logs:
https://gist.github.com/johnvmo/b3340f541cf32cb0c15ecbffc1aca6f9
I am very appreciated if someone can help.
Comment: I reslove it using the second answer in this [link](https://stackoverflow.com/questions/62246824/error-err-package-path-not-exported-no-exports-main-resolved-in-app-node-m) ```I had the similar problem. npm install @babel/helper-compilation-targets --save-dev
solved this situation```
Answer: Ran into the same error and found this:

Solution
This is a regression in Node.js. If you hit this issue from search engines, please choose one of the following solutions

update @babel deps to v7.8.7
use Node < 13.9
wait until nodejs/node#32107 is fixed! (Probably in the next Node.js patch release).

https://github.com/babel/babel/issues/11216
Comment: update babel deps to v7.8.7 => it will very complicated, for example I am using plugin uppy/dashboard that is using preact v8 and preact v8 currently uses  @babel 7.0
Answer: I have simple solution just downgrade Nodejs version to v10 LTS or 11. For example in my Raisl app, my Dockerfile look like this:
FROM ruby:2.7.1

ARG DEBIAN_FRONTEND=noninteractive
ENV RAILS_ENV=production
ENV RAILS_SERVE_STATIC_FILES=true
ENV RAILS_LOG_TO_STDOUT=true
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - && \
    curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
    echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
    apt-get update && \
    apt-get install -qq -y nodejs yarn vim
#RUN apt-get update -yqq && apt-get install -yqq --no-install-recommends nodejs
COPY Gemfile* /usr/src/app/
WORKDIR /usr/src/app
RUN bundle config --global frozen 1
RUN bundle config set without 'development test'
RUN bundle install
#RUN yarn install --prod
COPY . /usr/src/app/
# RUN bundle exec rake assets:precompile

CMD ["bin/rails", "s", "-b", "0.0.0.0"]

Answer: Based on @DoubleMalt answer, I downgraded Node to v13.8.0, it worked. It's an old project.
However, for the current Nuxt project, it hits an error:
ExperimentalWarning: Package name self resolution is an experimental feature. This feature could change at any time

but the project runs fine so far.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question.


404 when Serving Static Files Owned By Another User From /opt

Question: OS = Debian 11
I have edited default nginx (version 1.18.0, installed from Debian repository) config as below:
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
            try_files $uri $uri/ =404;
    }

    location /torrent/ {
            autoindex on;
            alias /opt/docker/qbittorrent/downloads;
    }
}

to serve my downloaded files with qbittorent docker container on HTTP protocol. However, I get a 404 Not Found error when I visit either /torrent/ or /torrent/some_folder/some_name.some_extension.
If important, these have rw-r--r-- permission and are owned by docker_qbit:docker though the web server is installed by a sudoer.
Comment: I think I may be able to answer this but I need to understand the requirements a little better.
You mean for the files to have permission `rw-r--r--` or "644" with the Owner being "docker_qbit" and the Group being "docker"?
I may be wrong, but if this is correct then I think the solution would be to add "nginx" user to the "docker" Group.
Comment: @Cnasp Yes, all are correct.
Comment: Did you check the permission of `/opt/docker/qbittorrent/downloads`, `/opt/docker/qbittorrent`, `/opt/docker`, `/opt` and `/`?
Comment: @PothiKalimuthu Except the last one (i.e., root `/`) which I don't know what its permission is, they are all 755; however, the last but two are owned by `root:root`.
Answer: What is happening is that the NGINX user doesn't have permission to traverse the directory you have specified in your alias.
Your requirements indicate we cannot change the permissions on the target directory.
The only solution I see would be to add the main nginx (www-data) user to the docker group. That way the webserver should be able to access the specified directory without changing its permission.
If the default nginx user on Debian 11 is www-data.
Assuming that to be the case, the command to do this would look like this:
usermod -a -G docker www-data

That command will modify the user "www-data" by adding them to group "docker".
To be sure what user is running nginx you could look at the output of this command:
ps -eo user,comm | grep nginx

Once complete you can reload nginx and see if the content is now available.
systemctl reload nginx

Comment: Yeah! Thanks. It shows that the final problem is the omitted trailing `/` after the address in the `alias` command. Solved, thanks.
Comment: Thanks. The outputs of the last command are `root    nginx` and `www-data    nginx`. But the first command run with a *sudo*er says that `usermod: user 'nginx' does not exist`
Comment: So your "nginx" user is actually "www-data". I will update my answer for this.
Comment: Changed nginx user to match your system user. I hope this gets you going. Let me know! =)
Comment: Unfortunately, nothing changed with adding this user to the group.
Comment: Is there anything in `/var/log/nginx/error.log that may be useful?
Answer: Thanks to all. The problem was omitted trailing / after the address in the alias directive.


Use Nagios to monitor toner levels of local USB printers

Question: I have a bunch of computers with local USB attached printers.
I'd like to be able to monitor things like paper jams and toner levels with Nagios but all I've been able to find involves using SNMP.
How can I use Nagios to monitor local USB printers?
Comment: On what platform are the USB printers connected?
Comment: If it's Windows I could see using check_wmic and a WMI query, if the data is available there.
Comment: @SvenW It's Windows XP.
Answer: A PowerShell script like this should do the trick.  This can be called via Nagios and will return an exit code of 0 and "OK: All printers are normal" or an exit code of 2 and information about the printer(s) that have a problem.
<code>#Initialize variables
$nagiosStatus = "0"
$nagiosDescription = ""
$detectedErrorStateDescriptions = New-Object string[] 12

#Assign error state descriptions - see http://msdn.microsoft.com/en-us/library/windows/desktop/aa394363(v=vs.85).aspx
$detectedErrorStateDescriptions[0] = "Unknown"
$detectedErrorStateDescriptions[1] = "Other"
$detectedErrorStateDescriptions[2] = "No Error"
$detectedErrorStateDescriptions[3] = "Low Paper"
$detectedErrorStateDescriptions[4] = "No Paper"
$detectedErrorStateDescriptions[5] = "Low Toner"
$detectedErrorStateDescriptions[6] = "No Toner"
$detectedErrorStateDescriptions[7] = "Door Open"
$detectedErrorStateDescriptions[8] = "Jammed"
$detectedErrorStateDescriptions[9] = "Offline"
$detectedErrorStateDescriptions[10] = "Service Requested"
$detectedErrorStateDescriptions[11] = "Output Bin Full"

#Check the status of each printer on the system
ForEach ( $printer in ( Get-WmiObject win32_printer ) ) {
    If ( ( $printer.DetectedErrorState -ne "0" ) -and ( $printer.DetectedErrorState -ne "2" ) ) {
        $nagiosStatus = "2"
        If ($nagiosDescription -ne "") {
            $nagiosDescription = $nagiosDescription + ", "
        }
        $nagiosDescription = $nagiosDescription + $printer.Name + ":" + $detectedErrorStateDescriptions[$printer.DetectedErrorState]
    }
}

#Output the status
If ( $nagiosStatus -eq "2" ) {
    Write-Host "CRITICAL: " $nagiosDescription
}
Else {
    Write-Host "OK: All printers are normal"
}

exit $nagiosStatus
</code>
I do not have a Nagios installation available to me for testing at the moment, but this is modified from another PowerShell script that I used to use with Nagios.
See http://msdn.microsoft.com/en-us/library/windows/desktop/aa394363(v=vs.85).aspx for further information about possible information you can get from the win32_printer WMI object.
Comment: Thats a nifty script +1
Comment: Tested with Nagios, works as is.