Are the roots of unity the only algebraic subgroups of the multiplicative group?

Question: $\newcommand{\G}{\mathbb{G}}$
Let $k$ a field (or maybe more generally an arbitrary ring with connected spectrum), $\G_m$ the multiplicative group over $k$. Are the $\mu_n = \{x^n = 1\}$ the only $k$-subgroup schemes of $\G_m$? What is the best way to see this? I have difficulty mostly in the algebraically closed field case.
My incomplete thoughts:
Working first on $\overline{k}$ an algebraically closed field, a proper closed subgroup-scheme $H$ of $\G_m$ must be affine of dimension zero, hence its $\overline{k}$-points are a finite discrete subgroup of $\overline{k}^\times$ and must coincide with $\mu_n$ for some $n$ (WLOG relatively prime to $p$, the characteristic).
How do I know there aren't any choices for nonreduced structure to put on these sets of points other than the ones which define $\mu_{np^k}$?
Edit: I suppose by homogeneity that the nonreduced structure on each point must be identical to that on the identity, so we reduce to classifying subgroups of $\G_m$ supported on the origin. Perhaps this can be approached ring-theoretically?
How do you descend the case above to $k_s$, so that Galois descent gives the case of an arbitrary field? The proof above doesn't seem to translate so well, as we could have to worry about $H$ being supported on points which aren't $k_s$-rational. But $k_s \to \overline{k}$ is a universal homeomorphism, so maybe one can sidestep the issue somehow?
I don't know how one would formally patch this result to arbitrary rings or schemes, but it seems intuitively true since the classification is uniform and discrete (so it doesn't seem like a subgroup could vary in families except to be constant.)
Comment: I'm just wondering whether the Frobenius kernels would qualify. They have been used heavily in the representation theory of characteristic $p$ algebraic groups. Largely as substitutes for Lie algebras. I have become rather rusty with this, but the idea is (IIRC) to take the scheme theoretic kernel of the Frobenius automorphism. Of course, the resulting group scheme won't have any non-trivial rational point over any field, but the structure sheaf is different. If you think of an algebraic group scheme over a field $k$ as a functor from commutative $k$-algebras to groups, you see extra points.
Comment: (cont'd) After all, when you look at a $k$-algebra with nilpotent elements, you get non-trivial points mapped to the identity by the Frobenius. Somewhat analogous to the Lie group - Lie algebra situation, where you get a quick idea of the Lie algebra of a Lie group of matrices by checking out which matrices of the form $I+\epsilon A$ (with $\epsilon^2=0$) satisfy the defining equations of the Lie group.
Comment: In your case of the multiplicative group scheme (as opposed to, say $SL_n(k)$) you would then also see the groups $\mu_n$ thickened by a Frobenius kernel.
Comment: @Jyrki As Alex confirmed in a comment below, the relative Frobenius for the multiplicative group is the $p$-th power map, so has kernel $\mu_p$, so this doesn't seem to introduce any new possibilities.
Comment: LOL, a fair point C.D. :-) What the Frobenius kernels bring to us is then surely covered in the scheme theoretic version of $\mu_n$. It, too, has those extra points when the functor is applied to a $k$-algebra with nilpotent elements. Sorry about creating some confusion.
Comment: What you've written can't be literally true -- what do you mean by subgroup scheme? Do you at least want to assume that it's flat and finite presentation over the base?
Comment: If you assume that $H\subseteq \mathbb{G}_{m,S}$ is flat and of finite presentation over $S$ then it's true.
Comment: C.D. I don't know if you get pinged for edits, but I just wanted to let you know I added an example of why flatness is important.
Comment: Yes, I saw it! Thanks for the clarification and reorganization -- it seems evident now that without flatness of course one should have to worry about fibers jumping.
Answer: Case of fields
Let me begin by confirming your suspicion over a field.

Claim (field case): Let $k$ be a field, and $H\subsetneq \mathbf{G}_{m,k}$. Then, $H$ is isomorphic to $\mu_{n,k}$ for some $n\in\mathbf{Z}_{\geqslant 1}$.

As the later answer uses more heavily the theory of multiplicative group schemes, let me sketch a proof of this using more the theory of finite group schemes.
Proof: If $k$ has characteristic $0$ then this is trivial. Indeed, in this case $H$ is etale by [Pink, Theorem 13.2]. Then, by [Pink, Theorem 12.2] we know that it suffices to show that $H(\overline{k})$ agrees with $\mu_N(\overline{k})$ as $\mathrm{Gal}(\overline{k}/k)$-modules for some $N$. But, as $H(\overline{k})$ is a $\mathrm{Gal}(\overline{k}/k)$-submodule of $\overline{k}^\times$ this is clear.
So, we may assume that $\mathrm{char}(k)=p>0$. As we have the connected-etale sequence
$$1\to H^\circ\to H\to \pi_0(H)\to 1,$$
(see [Milne, Proposition 5.58]), where $H^\circ$ is connected and $\pi_0(H)$ is etale, it suffices to show that $H^\circ=\mu_{p^r,k}$ for some $r$ and that $\pi_0(H)=\mu_{N,k}$ for some $p\nmid N$. Indeed, in this case, the connected-etale sequence necessarily splits by a simple computation (e.g. see [Milne, Corollary 15.40]), and as $H$ is commutative the claim will follow.
So, let us first assume that $H$ is etale. Then, the argument works exactly as in the characteristic $0$ case noting that the finite $\mathrm{Gal}(k^\mathrm{sep}/k)$-submodules of $(k^\mathrm{sep})^\times$ are of the form $\mu_N(k^\mathrm{sep})$ for some $p\nmid N$.
So, let us assume that $H$ is connected. Note then that the relative Frobenius map $F_H$ on $H$ is nilpotent (e.g. see [Pink, Proposition 15.6]), say $F_H^\ell=0$. Since $H\subseteq \mathbf{G}_{m,k}$ we see that this implies that $H\subseteq \ker(F_{\mathbf{G}_{m,k}}^\ell)=\mu_{p^\ell,k}$. But, we then see that $H\subseteq \mu_{p^\ell,k}$ gives us (by Cartier duality) a surjection $\underline{\mathbf{Z}/p^\ell\mathbf{Z}}_k\cong \mu_{p^\ell,k}^\vee\twoheadrightarrow H^\vee$. It's easy to see then that this implies that $H^\vee \cong \underline{\mathbf{Z}/p^r\mathbf{Z}}_k$ for some $r$, and so $H\cong H^{\vee\vee}\cong \mu_{p^r,k}$. $\blacksquare$

Issue with claim over arbitrary base
Unfortunately, the claim as stated is false over arbitrary base. In fact, we can write down a very simple example.
Let $R$ be a DVR with uniformizer $\pi$ (e.g. $R=\mathbf{Z}_p$ and $\pi=p$, or $R=\mathbf{C}[\![t]\!]$ and $\pi=t$) and consider
$$H:=V(\pi x^r-\pi)\subseteq \mathbf{G}_{m,R}=\mathrm{Spec}(R[x^{\pm 1}]).$$
Then, it's easy to see that
$$H_{R[\pi^{-1}]}\cong \mu_{r,R[\pi^{-1}]},\qquad H_{R/\pi R}\cong \mathbf{G}_{m,R/\pi R}.$$
In particular, $H\subseteq \mathbf{G}_{m,R}$, but $H$ is not isomorphic to $\mu_{n,R}$ for some $n$.
This group $H$ may look artificial, but it is in fact not. For example, let us consider the action
$$\mathbf{G}_{m,R}\times\mathrm{GL}_{2,R}\to\mathrm{GL}_{2,R},\qquad \left(x,\begin{pmatrix}a & b\\ c & d\end{pmatrix}\right)\mapsto \begin{pmatrix}x^r & 0\\ 0 & 1\end{pmatrix}\begin{pmatrix}a & b\\ c & d\end{pmatrix}\begin{pmatrix}x^r & 0\\ 0 & 1\end{pmatrix}^{-1}.$$
Then,
$$H=\mathrm{Cent}\left(\mathbf{G}_{m,R},\left(\begin{smallmatrix}1 & \pi\\ 0 & 1\end{smallmatrix}\right)\right).$$
Fix a base scheme $S$ and $H\subsetneq\mathbf{G}_{m,S}$. By the field case discussed above, for every point $s$ of $S$ the subgroup $H_s\subseteq \mathbf{G}_{m,k(s)}$ is $\mu_{n_s,k(s)}$ for some $n_s\in\mathbf{Z}_{\geqslant 0}$ (where we take the convention that $\mu_{0,k(s)}:=\mathbf{G}_{m,k(s)}$). The issue is that there's no guarantee, as we saw in the above example, that the function
$$n\colon |S|\to\mathbf{Z}_{\geqslant 0},\qquad s\mapsto n_s,$$
is constant.
Challenge question: For $R$ as above, can you describe which functions $n\colon |\mathrm{Spec}(R)|\to \mathbf{Z}_{\geqslant 0}$ are actually realized by some $H\subsetneq \mathbf{G}_{m,R}$? Can you describe matrix realizations of the groups you construct?

The case of general base
To remedy the issue that $n_s$ is constant, one should imagine that we need $H\to S$ to have 'continuously varying fibers'. If you've been in the game long enough, you know that is code for 'flat'. Fore sxample, our example above is not flat as the map $R[x^{\pm 1}]/(\pi x^r-\pi)$ has $\pi$-torsion.
To state the result correctly, let us fix a base scheme $S$ and recall that a group $S$-scheme $H\to S$ is fppf if it is flat and locally of finite presentation. For simplicity let us assume that $S$ is locally Noetherian.${}^{\color{red}{(1)}}$

Claim (general base): If $H\subsetneq \mathbf{G}_{m,S}$ is an fppf group $S$-scheme, then $H$ is isomorphic to $\mu_{n,S}$ for some $n$.

Proof: Let us observe that as $H$ is fppf over $S$ that [Conrad, Corollary B.3.3] implies that $H\to S$ is of multiplicative type as in Definition B.1.1 of loc. cit. But, if $\xi\colon \text{Spec}(\Omega)\to S$ is a geometric point, then by[SGA 3, Exposé X, Théorème 7.1] there is an anti-equivalence of categories between group $S$-schemes of multiplicative type and discrete $\pi_1^\text{SGA3}(S,\xi)$-modules${}^{\color{red}{(2)}}$ finitely generated as an abelian group given by
$$H\mapsto X(H,\xi):= \text{Hom}_\Omega(H_\xi, \mathbf{G}_{m,\xi}).$$
In particular, from our closed embedding of group $S$-schemes $H\hookrightarrow \mathbf{G}_{m,S}$ we get a closed embedding of group $\Omega$-schemes $H_\xi\hookrightarrow\mathbf{G}_{m,\xi}$ which induces a surjection $X(\mathbf{G}_{m,S},\xi)\to X(H,\xi)$ which is evidently $\pi_1^\text{SGA3}(S,\xi)$-equivariant. But, $X(\mathbf{G}_{m,S},\xi)$ is isomorphic to $\mathbf{Z}$ with the trivial $\pi_1^\text{SGA3}(S,\xi)$-action. Thus, the surjection $X(\mathbf{G}_{m,S},\xi)\to X(H,\xi)$, which can't be an isomorphism as we assumed that $H\to \mathbf{G}_{m,S}$ was not an isomorphism, identifies $X(H,\xi)$ as $\mathbf{Z}/n\mathbf{Z}$ with the trivial $\pi_1^\text{SGA3}(S,\xi)$-action for some $n$. But, it's easy to compute that this is precisely $X(\mu_{n,S},\xi)$, and so the claim follows. $\blacksquare$
$\color{red}{(1)}$: That said, it should almost certainly be ok for locally topologically Noetherian $S$, and probably in general by a `descent to the Noetherian case' type argument. For instance, if $S$ is quasi-compact and quasi-separated then one quickly reduces to the Noetherian case by combining Tag 01ZA and Tag 01ZM.
$\color{red}{(2)}$: The topological group $\pi_1^\text{SGA3}(S,\xi)$ is an enlargement of the etale fundamental group $\pi_1^\text{et}(S,\xi)$ first studied in [SGA3, Exposé X, §6]. This group has its category of discrete sets with continuous action classifies the category $\mathbf{ULoc}(S_\text{et})$ -- the category of 'disjoint unions of' sheaves of sets on $S_\text{et}$ locally constant for the etale topology -- this is contrast to $\pi_1^\text{et}(S,\xi)$ whose category of discrete sets with continuoussets classifies $\mathbf{ULCC}(S_\text{et})$ -- the category of 'disjoint unions of' sheaves of sets on $S_\text{et}$ which are locally constant for the etale topology with finite fibers. The two groups actually coincide when $S$ is normal. You can also understand this as the maximal pro-discrete quotient of the pro-etale fundamental group from [BS].
References:
[BS] Bhatt, B. and Scholze, P., 2013. The pro-'etale topology for schemes. arXiv preprint arXiv:1309.1198.
[Conrad]Conrad, B., 2014. Reductive group schemes. Autour des schémas en groupes, 1(93-444), p.23.
[Milne] Milne, J.S., 2017. Algebraic groups: the theory of group schemes of finite type over a field (Vol. 170). Cambridge University Press.
[Pink] https://people.math.ethz.ch/~pink/ftp/FGS/CompleteNotes.pdf
[SGA3] M. Demazure, A. Grothendieck, Sch´emas en groupes I, II, III, Lecture Notes in Math 151, 152, 153, Springer-Verlag, New York (1970).
Comment: What does "finite" mean in the phrase "finite discrete $\pi_1$-modules" if $\mathbb{Z}$ is an example? Finitely generated?
Comment: I'm not going to try to follow this argument over a base scheme more complicated than $\text{Spec}$ of a field; in that case I'm familiar with the classification of group schemes of multiplicative type in terms of Galois actions but I don't know why an fppf subgroup scheme of $\mathbb{G}_m$ must have multiplicative type (in particular I don't know how to rule out the possibility of non-reduced behavior as the OP and Jyrki have been speculating about, especially in the positive characteristic case). Do the results you're quoting simplify enough in this case to give a direct proof?
Comment: @QiaochuYuan I'm not sure what you mean. Open subgroup schemes are not really a thing. For example, over a field any homomorphism of linear algebraic groups $G\to H$ with trivial kernel is a closed immersion (e.g. see Prop 1.1.1 of this: http://math.stanford.edu/~conrad/papers/luminysga3.pdf) -- results like this hold over more general bases.
Comment: @QiaochuYuan By the way, it's true that every homomorphism of linear algebaric groups over a field has closed image. This is, in the case of a monomorphism, a priori weaker than saying it's a closed immersion, but it's a general fact I thought you might want to know.
Comment: @QiaochuYuan I don't know if it's more your style, but I have included a proof now that is more specific to fields.
Comment: @QiaochuYuan Yes, fixed. Thanks!
Comment: @QiaochuYuan I am unfortunately not sure I understand Jyrki's idea -- the relative Frobenius map for the multiplicative group has kernel $\mu_p$, right? Anyways, another way to think about multiplicative groups are those that are geometrically 'diagonalizable' (i.e. isomorphic to $\mathrm{Spec}(k[M])$ for some finitely generated abelian group $M$ with the obvious group scheme structure). So, it suffices to show that a subgroup of a diagonalizable group is diagonalizable. That said, you can phrase diagonalizable groups as being those whose global sections are generated by group-like elements
Comment: using this it's easy/elementary to show the claim. For example, see Theorem 4.4 (c) of Chapter XIV here: https://www.jmilne.org/math/CourseNotes/AGS.pdf Let me know if that clears things up.
Comment: Okay, it looks like I'm missing something very basic. It looks like for Milne (affine) subgroup schemes are closed by definition? That makes things very straightforward as you say, but then why is there a concept of open subgroup scheme? Actually I guess I have no idea what a "subscheme" is, generally. Gun to my head I'd define a "subgroup scheme" as a morphism $f : G \to H$ of group schemes which is injective on functors of points; is such a thing necessarily a closed affine subgroup scheme if $H$ is an affine group scheme?
Comment: Thanks Alex, that's helpful.


Get most sold product for each country from NORTHWIND database

Question: Good day guys, I've been struggling with this for the past day and I just can't seem to figure it out.
My task is to derive the most sold product for each country from the popular open source database called NORTHWIND: https://northwinddatabase.codeplex.com
I was able to get to this stage, here is my code in SQL Server:
--Get most sold product for each country
WITH TotalProductsSold AS
(
    SELECT od.ProductID, SUM(od.Quantity) AS TotalSold
        FROM [Order Details] AS od
        GROUP BY od.ProductID
)
SELECT MAX(TotalProductsSold.TotalSold) AS MostSoldQuantity, s.Country --,p.ProductName
    FROM Products AS p
    INNER JOIN TotalProductsSold
    ON TotalProductsSold.ProductID = p.ProductID
    INNER JOIN Suppliers AS s
    ON s.SupplierID = p.SupplierID
    GROUP BY s.Country
    ORDER BY MostSoldQuantity DESC

This gives me the following result:

That's all good but I wish to find out the product name for the MostSoldQuantity.
Thank you very much !
P.S I put a comment --p.ProductName where I thought it would work but it didnt and if someone could explain me why does GROUP BY not automatically allow me to derive the product name for the row that would be great
Comment: I assume you know your proposed answer doesn't work, as you deleted it.  The important *reason* is that the `MAX(productID)` has nothing at all to do with the `MAX(TotalSold)`, they're calculated independently.  (You create the data set, you create groups inside the data set, within in each group you get the highest TotalSold and separately you get the highest value of ProductID.  There is no SQL expression for *"get the productID that is associated with the result of `MAX(TotalSold)` as calculated in another expression in the SELECT list`"*).
Comment: Yeah I realized as soon as I check the productIDs do not match to the most sold quantity
Comment: I am looking at your answer now, thank you for your time :)
Answer: First, start with the count of products sold, per country, not just per product.  Then rank them and pick only anything at RANK = 1.
Something like...
WITH
    ProductQuantityByCountry AS
(
    SELECT
       s.CountryID,
       p.ProductID,
       SUM(od.Quantity)   AS Quantity
    FROM
        [Order Details]   AS od
    INNER JOIN
        Products          AS p
            ON  p.ProductID = od.ProductID
    INNER JOIN
        Suppliers         AS s
            ON  s.SupplierID = p.SupplierID
    GROUP BY
       s.CountryID,
       p.ProductID
),
    RankedProductQuantityByCountry
AS
(
    SELECT
        RANK() OVER (PARTITION BY CountryID ORDER BY Quantity DESC)  AS countryRank,
        *
    FROM
        ProductQuantityByCountry
)
SELECT
    *
FROM
    RankedProductQuantityByCountry
WHERE
    countryRank = 1

Note, one country may supply identical quantity of different producs, and so two products could both have rank = 1.  Look into ROW_NUMER() and/or DENSE_RANK() for other but similar behaviours to RANK().
EDIT:
A simple though exercise to cover why SQL doesn't let you put Product.Name in your final query is to ask a question.
What should SQL do in this case?
SELECT
    MAX(TotalProductsSold.TotalSold) AS MostSoldQuantity,
    MIN(TotalProductsSold.TotalSold) AS LeastSoldQuantity,
    s.Country,
    p.ProductName
FROM
    blahblahblah
GROUP BY
    s.Country
ORDER BY
    MostSoldQuantity DESC

The presence of a MIN and a MAX makes things ambiguous.
You may be clear that you want to perform an operation by country and that operation to be to pick the product with the highest sales volume from that country.  But it's not actually explicit, and small changes to the query could have very confusing consequences to any inferred behaviour.  Instead SQL's declarative syntax provides a very clear / explicit / deterministic description of the problem to be solved.
If an expression isn't mentioned in the GROUP BY clause, you can't SELECT it, without aggregating it.  This is so that there is no ambiguity as to what is meant or what the SQL engine is supposed to do.
By requiring you to stipulate get the total sales per country per product at one level of the query, you can then cleanly state and then pick the highest ranked per country at another level of the query.
This can feel like you end up with queries that are longer than "should" be necessary.  But it also results in queries that are completely un-ambiguous, both for compiling the query down to an execution plan, and for other coders who will read your code in the future.
Comment: Thank you very much ! I got it to work and I used your ideas. I am still a beginner in SQL and I didn't know about the ranking functions and I was thinking there's gotta be an easier solution without going beyond GROUP BY and aggregate functions but so far your answer is the only one that solves my problem and not in a bad way imo.

Thanks man ! :)
Comment: You an (if I recall correctly) do `RANK() OVER (PARTITION BY CountryID ORDER BY SUM(Quantity) DESC) AS CountryRank` in the first CTE to shorten it, I just separated it to make it clearer for you.


how to get previous step values in next step in drupal multi step form?

Question: How to get previous step values in drupal in the next step in a multiform. I want to display the values other than drupal_set_message(). I want to use these previous values in other function in the next step.
function form_example_wizard_previous_submit($form, &$form_state) {
  $current_step = &$form_state['step'];
  $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];
  if ($current_step > 1) {
    $current_step--;
    $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
  }
  $form_state['rebuild'] = TRUE;
}

function form_example_wizard_next_submit($form, &$form_state) {

  $current_step = &$form_state['step'];

  $form_state['step_information'][$current_step]['stored_values'] = $form_state['values'];

  if ($current_step < count($form_state['step_information'])) {
    $current_step++;
    if (!empty($form_state['step_information'][$current_step]['stored_values'])) {
      $form_state['values'] = $form_state['step_information'][$current_step]['stored_values'];
    }
    else {
      $form_state['values'] = array();
    }

    // Force rebuild with next step.
    $form_state['rebuild'] = TRUE;
    return;
  }
}

function form_example_wizard_personal_info($form, &$form_state) {
   $form = array();
  $form['pagenumber']= array(
      '#title' =>t('Page Number'),
      '#type' => 'textfield',
      '#required' => TRUE
      );
  $form['wordscount']= array(
      '#title' =>t('Words count'),
      '#type' => 'textfield',
      '#required' => TRUE
      );
  $form['calcvalue'] = array('#type' => 'hidden',
  '#value'=>'test' );
  return $form;
}

function form_example_wizard_location_info($form, &$form_state) {
  $form = array();
  $form['quoteprice'] = array(
    '#type' => 'textfield',
    '#title' => t('Editing Your Document Will Cost'),
    '#value'=>$quoteval,
    '#required' => TRUE,
  );
  return $form;
}

Comment: I need to pass hidden filed value in next step.
Answer: There are so many ways to send data from one from to other.

You can use session
You can also pass value in url

Example of pass by value
function register_form_submit($form, &$form_state){
$name = $form_state['values']['name'];
$age = $form_state['values']['age'];

$data = array(
    'query' => array(
         'name' => $name,
         'age' => $age,
        )
    );

$form_state['redirect'] = array('/success', $data);
}

here is a link you can refer for send data
https://www.drupal.org/node/2064545
Comment: I am using this $form_state['rebuild']
Comment: Here is a example you can refer http://davidsonj.com/blog/how-create-multi-step-form-drupal-7
Comment: please check my code on above.. and help me.
Answer: You need to set $form_state['storage'] for this. Checkout the linked blog.
Comment: I am not getting how to apply $form_state['storage'] here
Comment: Instead of setting the step info in `$form_state['step_information']` use `$form_state['storage']`.


How do you compute with decimal numbers on a computer?

Question: I came across something this morning which made me think...
If you store a variable in Python, and I assume most languages, as x = 0.1, and then you display this value to 30 decimal places you get: '0.100000000000000005551115123126'
I read an article online which explained that the number is stored in binary on the computer and the discrepancy is due to base conversion.
My question is how do physicists and nano-scientists get around this problem when they do computation?
I always thought that if I input data into my calculator using scientific-notation it will give me a reliable accurate result but now I am wondering if this is really the case?
There must be a simple solution?
Thanks.
Comment: "My question is how do physicists and nano-scientists get around this problem when they do computation?" - it's not a problem at all for those domains. Decimal isn't special. Physics doesn't need decimal.
Comment: I know it doesn't need decimal but I think computers do and hence computations involving these numbers will introduce some level of error? That was my thinking.  From reading the replies it seems that the level of error is there but not significant given that there is an error bar anyway in measurements.  That is what I took from reading the contributions.
Answer: Well, as a physicist I say these decimals are redundant in most cases.. it really doesn't matter what's on the 16th decimal place. The precision of measurements doesn't reach that level (not even in QED). Take a look at here, the highest precision measurements are around 10^13 - 10^14.
Applying to this to your example:
With 14 decimal places
0.100000000000000005551115123126 becomes 0.100000000000000, which doesn't introduce any errors at all.
Answer: There is the decimal class in python that can help you deals with this problem.
But personally, when I work with money transactions, I don't want to have extra cents like 1€99000012. I convert amounts to cents. So I just have to manipulate and store integers.
Answer: As always, it depends on the context (sorry for all the "normally" and "usually" words below). Also depends on definition of "scientific". Below is en example of "physical", not "purely mathematical" modeling.
Normally, using computer for scientific / engineering calculations:

you have reality
you have an analytical mathematical model of the reality
to solve the analytical model, usually you have to use some numerical approximation (e.g. finite element method, some numerical scheme for time integration, ...)
you solve 3. using floating point arithmetics

Now, in the "model chain":

you loose accuracy from 1) reality to 2) analytical mathematical model

most theories does some assumptions (neglecting relativity theory and using classical Newtonian mechanics, neglecting effect of gravity, neglecting ...)
you don't know exactly all the boundary and initial conditions
you don't know exactly all the material properties
you don't know ... and have to do some assumption

you loose accuracy from 2) analytical to 3) numerical model

from definition. Analytical solution is accurate, but usually practically unachievable.
in the limit case of infinite computational resources, the numerical methods usually converges to the analytical solution, which is somehow limited by the limited floating point accuracy, but usually the resources are limiting.

you loose some accuracy using floating point arithmetics

in some cases it influences the numerical solution
there are approaches using exact numbers, but they are (usually much) more computationally expensive

You have a lot of trade-offs in the "model chain" (between accuracy, computational costs, amount and quality of input data, ...).
From "practical" point of view, floating point arithmetics is not fully negligible, but usually is one of the least problems in the "model chain".
Comment: Thank you Jan.  I don't have a practical problem to solve.  I just stumbled across the issue when I was reading about floating point numbers in Python and it struck me that there would be computing ramifications. I'll have a look at 'floating point arithmetic'.
Comment: By floating point arithmetics, I mean these artifacts like `0.1+0.2!=0.3`, `(0.1+0.2)+0.3!=0.1+(0.2+0.3)` (important in parallel computing, where numbers are summed in random order), printing actually stored value for `0.1` etc. Definitely good to know (although not everybody need it)


Batting average greater than on-base percentage

Question: While watching a New York Mets game early this season, before one plate appearance the broadcast graphics displayed that catcher John Buck had a batting average (AVG) of .400 and an on-base percentage (OBP) of .396. Several games later I saw a similar phenomenon for Buck, whose OBP was again several points lower than his AVG. (In other words, the stats presented were very likely to be actual and not an on-screen typo.)
How is this possible? By my understanding, the two are calculated as follows:
AVG = (hits) / (at-bats)

and
OBP = (times reaching first base) / (plate appearances)

It would seem to me that the conditions by which a plate appearance does not count as an at-bat would always result in the batter reaching first.
What could have happened to cause Buck's on-base percentage to drop below his average?
Answer: Sacrifice Flies
It can happen because Sacrifice Flies are in the denominator of the on-base percentage
OBP=(H+BB+HBP)/(AB+BB+HBP+SF),

but not in the batting average
AVG=H/AB.

For small numbers of at-bats, it is possible (though unlikely) for a player's on-base percentage to be lower than his batting average (H/AB). This happens when a player has almost no walks or times hit by pitch, with a higher number of sacrifice flies (e.g. if a player has 2 hits in 6 at-bats plus a sacrifice fly, his batting average would be .333, but his on-base percentage would be .286). The player who experienced this phenomenon with the most number of at-bats over a full season was Ernie Bowman. In 1963, with over 125 at-bats, Bowman had a batting average of .184 and an on-base percentage of .181.

Source
Comment: That makes perfect sense; a sac fly shouldn't count against you for batting average, but since you didn't actually get on-base, it wouldn't count favorably towards OBP.


How do I create customer/order relationship with entities?

Question: I am fairly new to Drupal 7 and especially new to the entity concept.
I need to create a site which records customer data (name, address etc) as well as other objects/entities such as orders, which are related to the customer with a parent/child relationship. I don't know how to do this in Drupal 6 and definitely not in Drupal 7. I know you can create a node reference as a field, but that is not what I want.
I'm pretty sure this has to do with entities, as entities are paralleled to objects, and what I really need is an object to own another object. I am presently listening through tutorials about Entities, but can someone point me in the correct direction to see what exactly I should be looking for (and to perhaps clarify the Entity concept to me).
Answer: You should look at Drupal Commerce, a suite of modules that sets up e-commerce in Drupal.  You will have a much easier time adapting Drupal Commerce to fit your needs than you will writing a store from scratch in Drupal.
Comment: Thats the issue: I'm not creating a store, just a backend for administrators to store customer and user data. No one will be buying anything from this site. Would you still suggest commerce, or is there a simpler implementation for this? (also, it would like to learn more about the entity api anyways...)
Comment: Yes, you should still look at Commerce.  Commerce makes extensive use of the new features of Drupal 7, including entities.  It is also completely modular; if you don't need payment, simply don't enable the payment module.  You can also use the default permissions to shut off access to everything except to administrators.


Field Type: Text vs. Long text

Question: What are the differences between 'Text' and 'Long text' in Drupal 7?
If it is simply database character length, is it better to be cautious and default to using Long text in situations where the domain of possible entered values is not precisely known?
Answer: The differences are laid out in text.module.

text fields are stored as varchar with a maxlength of 255 characters, and their default widget is a simple text input.
long text fields are stored as longtext, with a maximum length of 4 GiB (maximum characters depending on the encoding), and their default widget is a textarea
text with summary fields are like long text fields, except that text processing is enabled by default. That is, summary text can be included along with the main text, and the content will be processed through input filters. The default widget is a "textarea with summary"

Generally, long text and text with summary fields are used for, well, long text— anything longer than a few words or a few dozen characters: body text, lengthy embedding code, data tables, and so on. Ordinary text is better suited to short snippets of text: a personal name, a company tagline, a favorite color.
I think it would be rare that your data would be suitable to either type. If you're storing a biography for a user profile, for example, you would have a clear idea as to whether it is expected to be a narrative of several paragraphs or simply a short personal motto.
Answer: There are three more types of text that a text field can be set for:

Text plain (stored as varchar)

Text plain long (stored as longtext)

Use these for the most secure outward facing fields. Plain text provides a secure, generic text format that can be used by all roles, including an anonymous user. It has no html formatting tags whatsoever (no bold, no italic, ...)

List (Text)

List text is for key|label lists, as described in Drupal 7 documentation.

Field Type: Text vs. Long text


XPath Expression for getting default namespace

Question: I am looking for an XPath Expression to get the default namespace of a node.
My XML document might look like this.
<aaa>
    <bbb xmlns="ns1" xmlns:ggg="ns2" attribute="value" attribute2="value2">
        <ccc />
    </bbb>
    <bbb xmlns="ns4" xmlns:ggg="ns5" attribute="value" attribute2="value2">
        <ddd />
    </bbb>
</aaa>

I want to get ns1. I've tried it with the following expressions but none of it worked (I'm programming in Java 1.7 (so it is XPath 1.0) and tested with the online XPath visualizer on http://chris.photobooks.com/xml/default.htm).
/aaa/*[name()='bbb' and position()=1]/attribute::*

This expression only selects the attribute- and the attribute2-nodes.
/aaa/*[name()='bbb' and position()=1]/namespace::*

This expression does not select anything.
I would be grateful if someone has a hint for me.
Answer: Your expression
/aaa/*[name()='bbb' and position()=1]/namespace::*

is correct and returns three namespace nodes. The problem might be in the way you are processing these nodes after they are returned. The expression should work in both XPath 1.0 and XPath 2.0, though I haven't checked it with the XPath engine built in to the JDK.
(Incidentally the notion that because you are using JDK 1.7 therefore you are using XPath 1.0 is a complete non sequitur, since there are several XPath 2.0 engines available for Java users).
To return only the namespace URI corresponding to the default namespace, use
/aaa/*[name()='bbb' and position()=1]/namespace::*[name()='']

Or indeed, since this query already assumes that the bbb element is in the default namespace, use
namespace-uri(/aaa/*[name()='bbb' and position()=1])

Comment: Thanks for the answer. I'm glad I did not make a mistake. It really was the build in XPath engine. Now I'm using saxon library and everything works fine.
Answer: This page explains the namespace-uri function in xpath.
It looks like you want something like this:
namespace-uri(/aaa/*[name()='bbb' and position()=1])

If the namespace isn't specified, you will get an empty string as the result.
EDIT: I reread your question and am not sure my answer is what you are looking for. The namespace-uri function is used to find the uri for nodes like <ns1:bbb>. It would return the uri for ns1. I'm not sure there is a way to use x-path to look at namespace definitions other than when they are actually used.
Comment: Hi, you did understand me right. That is a good solution, although like my query it does not work unter build in XPath engine. A change to saxon library worked fine. Thanks!


Calculate the length of curve

Question: The curve is the intersection of:
$$4x=(y+z)^2$$
$$4x^2+3y^2=3z^2$$
And the interval of curve length is from $O(0,0,0)$ to $M(x,y,z)$
The answer is $\sqrt2 z$

My substitution is $u=y+z$ and $v=z-y$, then I put them into these two equations generating the relation of $u$ and $v$. However when I go down the track, trying to write the $dL$ to get the length, I found that the integral is complex to resolve. Did I go wrong or something else?
Answer: By inspection, one branch of the solution is $x=0$ and $y=-z$.  This is simply a line with with slope $-1$ in the $yz$-plane and, of course, the segment from the origin to a point $(0,-z,z)$ along this line has length $\sqrt{2}\,z$.
There is, however, another branch along which the problem could be harder.  The two branches are shown in the figure below.  My solution is for the diagonal line.
Comment: Thank you! And this is really a tricky skill. I search the wolfram for the $4x=(y+z)^2$ and it show **solution** is $x=0, y=-z$. I feel pretty strange what does the solution means here? I suppose x be any positive number.
Comment: @Sacheo You're welcome, though I wouldn't be so fast to accept this answer - I think it's missing something and someone else may spot it..  You can always upvote without accepting.

Calculate the length of curve


Fan basis for $\mathbb{C}^2$

Question:
Find a fan basis for the linear maps of $\mathbb{C}^2$ represented by the matrices: a)$\begin{bmatrix}1&1\\1&1\end{bmatrix}$

Solution.(a) Clearly, the vector $\begin{bmatrix}1\\-1\end{bmatrix}$ is an eigenvector corresponding to the eigenvalue 0. Let $V_1$ be the space generated by this vector. Then $\{V_1,\mathbb{C}^2\}$ is a fan for the given linear map.
Solution´s Manual for Lang´s Linear Algebra, Rami Shakarchi.
Fan basis definition: By a fan basis we shall mean a basis $\{v_1,...v_n\}$ of V such that $\{v_1,...,v_i\}$ is a basis for $V_i$.Linear Algebra, Serge Lang.
Questions:
1) I may be misunderstanding the defintions I am studying. Since $\begin{bmatrix}1\\-1\end{bmatrix}$ generates a subspace of $\mathbb{C}^2$, then $\{V_1\mathbb{C}^2\}$ is a fan basis. Can I pick an arbitrary subspace? Why does the subspace needs to be generated by a basis that is an eigenvector?
2) If I multiply $\begin{bmatrix}1\\-1\end{bmatrix}$ by a negative scalar, it proves that $\begin{bmatrix}1\\-1\end{bmatrix}$ does not generate a subspace. Is this true?
Answer:
1) I may be misunderstanding the defintions I am studying. Since $\begin{bmatrix}1\\-1\end{bmatrix}$ generates a subspace of $\mathbb{C}^2$, then $\{V_1\mathbb{C}^2\}$ is a fan basis. Can I pick an arbitrary subspace? Why does the subspace needs to be generated by a basis that is an eigenvector?

You're missing a key part of the definition of a fan basis.
Let $~f:V\longrightarrow V~$ be a linear map, $\dim V =n$.
Definition: A basis $( v_1, \ldots, v_n)$ of $V$ such that for all $j=1, \ldots,n$ the space $\text{span}(v_1,\ldots,v_j)$ is $f$-invariant is called a fan basis of $V$ with respect to $f$. See: A matrix-free way to find a fan basis of $V$? for where I clipped that text from.
From this definition, it would appear that you're missing a vector, namely $$v_2=\left[
\begin{array}{c}
1\\
1
\end{array}
\right].$$
You should check that this is, in fact, an eigenvector with eigenvalue 2, and this should allow you to construct a fan basis for $\Bbb{C}^2,$ in agreement with the definition Leo has provided in the link.

2) If I multiply $\begin{bmatrix}1\\-1\end{bmatrix}$ by a negative scalar, it proves that $\begin{bmatrix}1\\-1\end{bmatrix}$ does not generate a subspace. Is this true?

No this is not true. Every vector generates a subspace via the "span" operation. In particular
$$\text{span}\left(\left[
\begin{array}{c}
1\\
-1
\end{array}
\right]\right)=\left\{ \alpha \left[
\begin{array}{c}
1\\
-1
\end{array}
\right], \text{ where } \alpha \in \Bbb{C}\right\}=V_1.$$
You should verify that this is a subspace, and that for any negative scalar, say for example $-1,$ that $$-1\left[
\begin{array}{c}
1\\
-1
\end{array}
\right]=\left[
\begin{array}{c}
-1\\
1
\end{array}
\right]\in \text{span}\left(\left[
\begin{array}{c}
1\\
-1
\end{array}
\right]\right).$$
Comment: The author has never referred that a fan basis needs to be $A$-invariant. The only occasion I used the  $A$-invariant was to prove that the inverse of $A$ has a fan basis .
Comment: I have been searching for fan basis definitions and unfortunately, I am not finding in the definition the fact the basis must be A-invariant.
Comment: Could you provide me other sources?

Fan basis for $\mathbb{C}^2$


Every element of a subgroup $N$ normalizes $N$

Question: Let $N$ be a subgroup of a group $G$. By definition, an element $g\in G$ is said to normalize $N$ if $gNg^{-1}=N$. I am trying to show every element of $N$ normalizes $N$.
In other words, I want to show for all $n\in N$, $nNn^{-1}=N$.
My attempt:
Fix $n\in N$ and let $x\in nNn^{-1}$. Then $x=nhn^{-1}$ for some $h\in N$. Since $N$ is a group, $x\in N$. So $nNn^{-1}\subset N$.
I am having a trouble showing the other inclusion. Let $y\in N$. I want to show that $y\in nNn^{-1}$ in order to show $N\subset nNn^{-1}$. Can someone help me figure this out?
Answer: We can say even more: for every $n\in N$, we have $N=nN=Nn$ if $N$ is a subgroup and $n\in N$.
To prove $N\subseteq nN$, just consider $x=n(n^{-1}x)$ for $x\in N$.
We can use the same reasoning directly for $N\subseteq nNn^{-1}$: write $x\in N$ as $n(n^{-1}xn)n^{-1}$.
Answer: Hint
$$y=n(n^{-1}yn)n^{-1}\\
n^{-1}yn \in N$$


DukeScript: Android start an intent

Question: We would like to know if it is possible to get the context of Duksecript Android presenter so we can call external elements?
    Intent intent = new Intent(Intent.ACTION_MAIN, null);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.bluetoothSettings");
    intent.setComponent(cn);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity( intent);

or
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(path);
    intent.setType("application/pdf");
    startActivity(intent);

would this be possible short of changing the presenter to suit our needs?
Thanks in advance.
Comment: Can Anybody Help??
Answer: public class AndroidMain extends Activity{
public AndroidMain() {
}
private static Context mContext;
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mContext = this.getApplicationContext();
    GlobalVariables.setmContext(getAppContext());//set context to global variable Global Variable
    try {
        // delegate to original activity
        startActivity(new Intent(getApplicationContext(), Class.forName("com.dukescript.presenters.Android")));
    }
catch (ClassNotFoundException ex) {
        throw new IllegalStateException(ex);
    }
    finish();

}

private static Context context;
public static void main(String... args) throws Exception {
    DataModel.onPageLoad();
}

public static Context getAppContext(){
   return mContext;
}
}

The Manifest is Exactly the same as the Above answer only calling my AndroidMain Activity.
To Call the Intent
Intent intentOpenBluetoothSettings = new Intent();
intentOpenBluetoothSettings.setAction(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
intentOpenBluetoothSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getmContext().startActivity(intentOpenBluetoothSettings);

This Works Perfect for calling any other intent you might need, Thanks again @monacotoni for the push in the right direction.
Answer: Sorry for the late answer. You don't need to change the presenter. By default DukeScript provides you an activity which handles everything behind the scene automatically. But you can also create a decorating activity that has access to all Android services. E.g.:
public class AndroidMain extends Activity {
    public AndroidMain() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // obtain information you need
        //
        SharedPreferences prefs = getApplicationContext().getSharedPreferences("karel.prefs", 0);
        new AndroidStorage(prefs);

        try {
            // delegate to original activity
            startActivity(new Intent(getApplicationContext(), Class.forName("com.dukescript.presenters.Android")));
        } catch (ClassNotFoundException ex) {
            throw new IllegalStateException(ex);
        }
        finish();
     }
   }
}

You'll also need to register this Activity in your AndroidManifest.xml, e.g. like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cz.xelfi.karel"
    android:versionCode="1"
    android:versionName="1.0-SNAPSHOT" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="karel"
        android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
        <activity android:name="cz.xelfi.karel.AndroidMain"
                  android:configChanges="orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.dukescript.presenters.Android"
                  android:configChanges="orientation|screenSize"
                  android:exported="false"
                >
        </activity>

        <meta-data android:name="loadPage" android:value="file:///android_asset/pages/index.html" />
        <meta-data android:name="loadClass" android:value="cz.xelfi.karel.AndroidMain" />
        <meta-data android:name="invoke" android:value="main" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

https://dukescript.com/best/practices/2015/11/20/AndroidBoot.html
Comment: Hi Tony... Thanks for the Help, I did not -1 it I will try this as soon as we work on the project again as we are working on something else at the moment but will return to this asap.
Comment: Great, let me know when you need help.
Comment: Hi There. Just a Follow Up. I have manged to get this Right and wanted to Thank you for the Help. Just Adding our example as it might help someone else who is still struggling with this.

DukeScript: Android start an intent


How to fill dynamically a json file

Question: im using this block of code to send some data from a Pi to the cloud (needs to be in a json format). However i would also like to save the data in a created json file. Everything concerning the sending to the cloud works as i can send the values one by one but in the json file i have some problems. As anyone can see with my commands:
with open('json_body.json', 'w') as json_file:
           json.dump(data, json_file)

i create a json file but only the latest "data" value is being saved. Does anyone know how can i save all of them ? do i have to use an array or a list to save them first?
Any suggestions are helpful. Thank you in advance!
while True:
       acc = ReadChannel(acc_channel)
     # Print out results
       print("--------------------------------------------")
       print("Acc : " , acc , ",Acc in volts", ConvertVolts(acc,2))
       data = {}
       data['acceleration'] = acc
       json_body = json.dumps(data)
       print("Sending message: ", json_body)
       counter = counter + 1
       print(counter)
       with open('json_body.json', 'w') as json_file:
           json.dump(data, json_file)
       await device_client.send_message(json_body)
     # Wait before repeating loop
       time.sleep(delay)
   await device_client.disconnect()

Comment: Are you asking how to *append* to a file instead of just *writing* to one?
Answer: There is no need to do file write operation in every iteration you can try writing all data at once after the loop end.

temporary_json = []

while True:
    acc = ReadChannel(acc_channel)
    # Print out results
    print("--------------------------------------------")
    print("Acc : ", acc, ",Acc in volts", ConvertVolts(acc, 2))
    data = {}
    data["acceleration"] = acc
    json_body = json.dumps(data)
    print("Sending message: ", json_body)
    counter = counter + 1
    print(counter)
    temporary_json.append(json.dumps(data))
    await device_client.send_message(json_body)
    # Wait before repeating loop
    time.sleep(delay)

with open("json_body.json", "w") as json_file:
    proper_json = ",".join(temporary_json)  # making a valid json out of temporary json
    json.dump(proper_json, json_file)

awaitdevice_client.disconnect()
Comment: Thank you for the answer i managed to create a json file with all the values. However with your example the output in the final json file looks like this:                                                                        ["{\"acceleration\": 1023}","{\"acceleration\": 0}",....]                                                                                But the form I should create for the cloud looks like this: [
  {
    "acceleration": 1023
  },

  {
    "acceleration": 0
  }
]                     Do you have any idea how to create such form? all my tries failed.
Comment: one is a dictionary and the other one is JSON that why they look different.
Comment: do you know if it is possible to fill a dictionary dinamically like we did in the json file?
Comment: it's not clear what you want. You should probably ask a new question for getting a better answer.

How to fill dynamically a json file


Confused about CMake versions, need CMake 3.5 but CMake's site can only find CMake 3.27

Question: I am told that I need to use CMake version 3.5 but I can only find 3.27, on CMake's GitHub the newest version is 3.27, on their website the newest version is 3.26. I can find release notes on CMake 3.5 but no code for it. Does being on a windows machine affect this?
I know that this may be a trivial question for some but I don't understand this.
Comment: @CraigEstey so if i am understanding this correctly the version numbers count up like 3.7, 3.8, 3.9, 3.10, 3.11, . . . 3.20, 3.21, . . . 3.27 not like 3.07, 3.08, 3.09, etc.
Comment: Why do you want an older version? Because you're on a system that has an older version and you want documentation for it? Do you have `git` on your system? Have you done `git clone` so you can do other commands like `git log`? Then, you could do `git checkout` on the correct revision for 3.5 Also, I'm not familiar with CMake's use of version numbers. But, with the minor version bump, it may just be bug fixes, so 3.26 is just fine for 3.5
Comment: "I can only find verson 3.27". The officially current release version is 3.26; 3.27 is currently in the release candidate state. If you go to "older releases" available releases seem to go back until version 2.4.8 though: https://github.com/Kitware/CMake/releases?page=21 (and even older ones, if you look at the ones on `cmake.org` linked on the download page...
Comment: How are the "alternatives" for counting mentioned in your previous comment different though? The convention for version number comparisons is you take a look at the numbers before the first period, then the ones between the first and second period, and so on until you find the first place where the numbers are different. At that point the version with the smaller number is the older version. E.g. `2.3.4` is older than `3.3.4`, `2.3.4` is older than `2.99.4`, `2.3.4` is older than `2.3.1111115`
Answer:
Older Releases

Host
Link

kitware
https://cmake.org/files

github
https://github.com/Kitware/CMake/releases

src: https://cmake.org/download
So for CMake 3.5 => https://cmake.org/files/v3.5/
Answer: If you're looking at a CMake project's cmake_minimum_required call and it says cmake_minimum_required(VERSION 3.5), that means you should be able to use version equal to or greater than 3.5.
That being said, if you want to install past versions of CMake, the downloads page is pretty clear about where you can get them. The "Alternative Binary Releases" section points to https://apt.kitware.com/, https://snapcraft.io/cmake, and https://pypi.org/project/cmake/. The "Older Releases" section points to https://cmake.org/files and https://github.com/Kitware/CMake/releases.


Regex to find text between expressions, where the end of one match might be the start of the next

Question: I'd like to match the text between each line starting "2 capacitors", "1 op-amp", etc. in the following data using Python 3.5:
#Sat Dec 16 09:10:37 2017
#
#2 capacitors:
#  0 c1 10 uF GND n1
#  1 c2 47 pF nm nout
#1 op-amp:
#  0 o1 lt1124 '+'=nin '-'=nm 'out'=nout a0=15M gbw=14.6 MHz
#       un=2.7 nV/sqrt(Hz) uc=2.3 Hz in=300 fA/sqrt(Hz) ic=100 Hz
#       umax=12 V imax=20 mA sr=4.5 V/us delay=18.9 ns
#       pole at 200 kHz (real)        pole at 200 kHz (real)        zero at 800 kHz (real)        zero at 800 kHz (real)        zero at 9.4 MHz (real)
#2 resistors:
#  0 r1 430 Ohm n1 nm
#  1 r2 43 kOhm nm nout
#4 nodes:
#  0 n1
#  1 nm
#  2 nout
#  3 nin
#Logarithmic frequency scale from 1 Hz to 100 kHz in 100 steps.

I'd like to extract:
match 1: (2, capacitors, #  0 c1 10 uF GND n1#  1 c2 47 pF nm nout)
match 2: (1, op-amp, #  0 o1 lt1124 '+'=nin '-'=nm 'out'=nout a0=15M gbw=14.6 MHz#  un=2.7 nV/sqrt(Hz) uc=2.3 Hz in=300 fA/sqrt(Hz) ic=100 Hz.......)
match 3: (2, resistors, #  0 r1 430 Ohm n1 nm#  1 r2 43 kOhm nm nout)
match 4: (4, nodes, #  0 n1#  1 nm#  2 nout#  3 nin)
Whether or not the third group retains newlines is not important to me. Currently, I match by searching for the text between the first match and the first line that is not whitespace:
^\#(\d+) (op\-amps|op\-amp|capacitors|capacitor|resistors|resistor|nodes|node):$([\d\D]*?)^#\S

regexr example
(The MULTILINE flag must be enabled. The [\d\D] trick is to match all characters including newlines on different platforms.)
The problem is that the 1 op-amp and 4 nodes segments don't match because they form part of the previous match: for example, the #1 op-amp line. How can I get all of the possible matches?
Answer: Optimized solution:
import re

with open('yourfile.txt') as f:
    pat = r'^#(\d+) (op-amps?|capacitors?|resistors?|nodes?):([\s\S]+?)(?=\n#\S+ )'
    result = re.findall(pat, f.read(), re.M)
    for m in result:
        print(m)

The output:
('2', 'capacitors', '\n#  0 c1 10 uF GND n1 \n#  1 c2 47 pF nm nout ')
('1', 'op-amp', "\n#  0 o1 lt1124 '+'=nin '-'=nm 'out'=nout a0=15M gbw=14.6 MHz \n#       un=2.7 nV/sqrt(Hz) uc=2.3 Hz in=300 fA/sqrt(Hz) ic=100 Hz \n#       umax=12 V imax=20 mA sr=4.5 V/us delay=18.9 ns \n#       pole at 200 kHz (real)        pole at 200 kHz (real)        zero at 800 kHz (real)        zero at 800 kHz (real)        zero at 9.4 MHz (real) ")
('2', 'resistors', '\n#  0 r1 430 Ohm n1 nm\n#  1 r2 43 kOhm nm nout')
('4', 'nodes', '\n#  0 n1\n#  1 nm\n#  2 nout\n#  3 nin')

Details:

<word>s?- matches zero or one s ending char of <word>
[\s\S]+? - matches any character sequence [\s\S] between one and unlimited times, as few times as possible, expanding as needed (lazy)
(?=\n#\S+ ) - lookahead positive assertion, ensures that the needed sequence of matches is followed by \n#\S+ (separate line starting with # and non-whitespace char sequence \S+)
Comment: Perfect! Thanks a lot for the solution and explanation.


In Futsal, can a goalkeeper score with a drop kick (i.e. released from hands)?

Question: The question is about Futsal.
Consider the following situation:

The goalkeeper holds the ball in his hands after the opposing team's attack. The ball has not left the field so it is not a goal clearance.
The goalkeeper releases the ball and then kicks it.
The ball hits the post of opposing team's goal and goes in, touching neither the field nor any player.

Will it count?
What if we change the first statement (1.) to be a goal clearance instead.
Will it still count, or will it be an indirect free kick since the goalkeeper needs to throw the ball?
Answer: Ball in Play
Yes - The goalkeeper may score a goal with his feet from directly inside the goalkeeper's penalty area when holding a ball in play.

Law 10 The Method of Scoring
  ...
  A goal is disallowed if the goalkeeper of the attacking team throws or hits the
  ball intentionally with his hand or arm from inside his own penalty area and
  is the last player to touch or play the ball. (Page 37)

Goal Clearance
No - A goal may not be scored directly from a goal clearance.

Law 16 The Goal Clearance
  ...
  A goal may not be scored directly from a goal clearance. (Page 57)

Infringements and sanctions

If the goalkeeper takes the goal clearance with his foot, the referees will issue
  a warning and order him to take it with his hand, but the four-second count
  continues from where it was stopped once the goalkeeper is ready to retake it. (Page 152)
If the ball is not thrown directly out of the penalty area from a goal clearance:
  • the clearance is retaken, but the four-second count is not reset and
  continues once the goalkeeper is ready to retake it. (Page 57)
If the goal clearance is not taken within four seconds:
  • an indirect free kick is awarded to the opposing team, to be taken from the
  penalty area line at the place nearest to where the infringement occurred. (Page 58)

FIFA - FUTSAL Laws of the Game 2014/15
Answer: Also during general play, the goalkeeper is allowed to drop kick the ball and score directly on the opposing net. If the keeper has saved the ball during play and drop kicks it they can score and it counts. If it goes out and it's a restart then the keeper can only release it from their hands so no they can't directly score from that.


No bootable Device with two RAID1

Question: I have an DELL Poweredge R310. Configured are two RAID1 with 1TB each. My bootable device is on BAY 2 and 3. If I add the other RAID 1 in Bay 0 & 1 it can't find the bootable Device. How can I change the Boot Order of the Raid Controller so it will try to boot from the second RAID on BAY 2 & 3 ?
Raid Controller: SAS6IR with LSI Corp Config Utility for DELL SAS 6 v.6.22.03.00
I know that the server is not the newest one, but I really can't find any Information about my problem.
Answer: It should be possible via DELL utilities, from controller boot firmware (usually accessible via pressing F12 at some point of booting) or IPMI.
Also you can just use LSI tool named megacli. It will work with any LSI controller. You can download it here. As you can see, the tool is universal for all SATAIII/SAS controllers. You will need "MegaCLI 5.5 P2". They have rpm package included. For deb-based os you can use alien or other tools, but in fact it is statically linked binary, so you can just extract it and run binary.
First of all, list all your logical drives:
megacli -LDInfo -Lall -Aall

For every configured virtual drive you will get output.
Adapter 0 -- Virtual Drive Information:
Virtual Drive: 0 (Target Id: 0)
Name                :
RAID Level          : Primary-1, Secondary-0, RAID Level Qualifier-0
Size                : 278.875 GB
Mirror Data         : 278.875 GB
State               : Optimal
Strip Size          : 64 KB
Number Of Drives    : 2
Span Depth          : 1
Default Cache Policy: WriteBack, ReadAdaptive, Cached, Write Cache OK if Bad BBU
Current Cache Policy: WriteBack, ReadAdaptive, Cached, Write Cache OK if Bad BBU
Default Access Policy: Read/Write
Current Access Policy: Read/Write
Disk Cache Policy   : Disk's Default
Encryption Type     : None
Is VD Cached: Yes
Cache Cade Type : Read Only

Then you just select needed drive as bootdrive. For drive 0 (L0) from adapter 0 (a0) that will be
megacli -AdpBootDrive -Set -L0 -a0

Of course than means you need to boot server one way or another. If you don't have OS on it, or it is not bootable, just create bootable flash with some linux on it.
Answer: The SAS 6/iR controller is old enough that connection order matters - the controller can only boot from the drives with the lowest ID (slot number), regardless of what you do with the boot settings. If you swap the drives currently marked PD 2 and PD 3 into slots 0 and 1, you should be able to boot and see the new drives as expected.
This is also mentioned on page 50 of the manual:
http://www.dell.com/support/home/us/en/19/product-support/product/dell-sas-6ir-intgtd-and-adptr/manuals

No bootable Device with two RAID1


Network Security Device/Software

Question: We currently run Symantec Antivirus Corporate 10.2. The software is really easy to manage on a network but the actual virus detection isn't bad but the malware detection is crap.
We recently were infected with a email bot that got us put on some block lists. This has been resolved.
I cannot have that happen again. I would like to find a program as easy to manage as symantec that I can install on all the user's workstations as well as the servers. We run a windows 2003 domain. We have a couple 2008 test servers in the environment. Most of the workstations are xp though I am using windows 7 and symantect is not compatible with this OS... So we need a solution that would cover all those operating systems. If it could be installed on macs too that would be a bonus though not necessary at all.
This software must detect:
Viruses AND Malware
I am looking for something that combines the features in anti-malware programs like  malwarebytes or spybot with an antivirus program like symantec or AVG.
Alternatively if there is a piece of hardware that is a firewall, router, and packet inspection for virus/spam that would be the most ideal solution. I then could supplement with a piece of software that could pickup what the hardware misses.
Thank you for your suggestions.
UPDATE: I am in talks with AVG for their AVG Internet Security Business Edition.
Have others used this program? How did they find the admin panel for it?
Any suggestions for removing Symantec to install AVG?
UPDATE2: I am waiting to get AVG approved for our servers. Any input that is against this decision? Any horror stories?
Comment: Why can your desktops send mail directly to the internet?  If they can't, why didn't your mail server notice the deluge of email and do something?
Comment: The desktop was using a non standard port to send. Some of these malware use custom stacks to send mail out over already open ports.
Comment: All the custom stacks in the world don't help if you don't allow port 25 (587, etc) out from your desktops to the outside.  At that point they're sending through servers they have control of, and _those_ machines can get blacklisted.
Answer: We have been using Symantec Endpoint Protection 11. Release 5 (11.0.2002) Some minor glitches but much better detect rate on some of teh spyware and malware.  Easy to manage but a bit of a learning curve from SAV CE 10.X  Overall it has been pretty smooth for our 100 users in five separate offices.  You can likley get an upgrade from SAV CE
We cannot deploy the firewall easily but that would also help stop some malware.
I know some users have had issues and earlier releases had some challenges.  Release 5 seems to have addressed those issues.
Version 12 is the Small Business Edition designed for 100 users or less  Endpoint Data Sheet
Comment: Interface is different and client management is different.  Setup was pretty easy and there is a migration tool.  The weakaest link for us is still users that downlaod the stuff directly.  You can lso control applications if you have a standard build. We don't and it changes almost daily so hard to manage that.
Comment: Version 12 is the Small Business Edition.  Designed for under 100 users and some features of the Version 11 product not available. However, it is basically teh same product.  They also preconfiure some policies and some alerts. I will edit my earlier reply with a helpful link to a PDF
Comment: Interesting. I am very hesitant to go back to symantec. What is different in 11? What additional learning was required? Is the interface and security center that different?
Comment: Yah I cant control these freaks. They visit malicious sites and get viruses its a nightmare... management does not want me to filter the web because they need it for research. I need a really good program that can detect these threats. AVG seems really good I feel.
Comment: I think you will find SEP 11 much better than SAV. It has a smaller footprint than SAV and some of the advanced features give better protection.  Management is very granular.  Filtering can be doone with something like Websense.  Lets then go where they want but will block infected sites and has great reporting.  Not inexpensive but well worth the price
Comment: What about 12? I am finding others online saying 11 is better than 12... Thoughts?
Answer: Started to use this software from ESET which has good network management interface and also the scanner isnt very CPU intensive which i have seen issues
http://www.eset.co.uk/
They are also planning on releasing versions of the software for some linux distributions and Mac's i played about with a beta version of it under ubuntu for a while and was impressed with it.
Comment: Thanks Paul. I checked them out too and I am familiar with Symantec and AVG so I would rather not get into a whole new company. I am really looking for people who have info on AVG Internet Security Business Edition.
Answer: Ended up going with AVG. It is spectacular and great value. I prefer it over Symantec and ESET
Update as per comment Request: We ended up going with AVG Business Internet Security 9. I really enjoyed the admin console. It was fast and painless to install. Deployment was equally as simple. For the exchange server you need to install the Email Edition. We licensed 25 copies and it comes with 25 mailboxes for the Anti-Spam portion. I had an issue the other day and my reseller and AVG were able to resolve it in under 1 hour. Excellent Service so far!
I would go into pricing but that is more easily found on AVGs website.
The 25 Licenses can be applied to servers or workstations. We run it on 20 workstations and 5 servers.
Comment: If you're comfortable with it, could you share what sort of per-user/per-server pricing AVG provided?  How many clients/server total?
Answer: Symantec AV Corp is discontinued, but the follow-up product, Symantec Endpoint Protection has both AV & AM...
-Josh

Network Security Device/Software


aggregate rows into tensorflow variable

Question: I have a tf.Variable tensor that should work as a result aggregator.
The idea is that I will execute an operation on the graph with batches of data and the results should be appended as new rows to my result Variable.
Because at the beginning the variable should be empty, I initialize it like this:
result_tensor = tf.Variable(0, expected_shape=[0, 5], dtype=tf.float32)

Then, what I do is concatenate the new rows along the axis 0 (as new rows):
total_output = tf.concat([result_tensor, operation], 0)

Finally, I reassign the variable:
assign_op = tf.assign(result_tensor, total_output, validate_shape=False)

However, when all of this is run, I get the following error:
ValueError: Shape must be rank 0 but is rank 2 for 'concat_1' (op: 'ConcatV2') with input shapes: [], [?,25088], [].

Can you guys help me to find the obvious thing that I'm doing wrong?
Thanks!
Answer: You're creating result_tensor by feeding a 0. Which means your result_tensor is a scalar value and not a row as you expect. The expected_shape property doesn't fix that.
Instead, you should declare result_tensor to be tf.zeros([1, 25088]) as 25088 seems to be the size of the rows you want to append. Then, once you have all your results, just remove the first row by slicing.
Note: The tf.Variable class is not meant to store results but to add trainable values to your graph. In all my experiments with Tensorflow, I never had to use it. Not even once. The tf.layers module usually contains all I need.
Comment: Where should I store the results then? Keeping in mind that later I'll need to do operations on them.
Comment: I showed you in my answer how you could do it. You need to do operations on them. Sure. But you don't need to update the values inside when training your graph, do you ?

aggregate rows into tensorflow variable


Autopublish content from drupal to wordpress

Question: My question is that i am having a drupal blog and wordpress on different different domains. I am looking for a module so that whenever i publish some content in drupal it should also published in wordpress.
Answer: This is more of a Wordpress question, but on drupal side you could expose the new content with a feed or JSON View and after that use some WP module to import the data.
Edit
And here's something that you can use on WP side to autopost from a feed: https://wordpress.org/plugins/wp-rss-multi-importer/


How to set the focus to a non Java application in embeded in Java application on Windows

Question: I use the code to make a C# application embeded in Java application. But I can't set the focus on C# application.
hwnd = OS.FindWindow(null, new TCHAR(0, title, true));

int oldStyle = OS.GetWindowLong(hwnd, OS.GWL_STYLE);
OS.SetWindowLong(hwnd, OS.GWL_STYLE, oldStyle & ~OS.WS_BORDER);

OS.SetParent(hwnd, composite.handle);
OS.SendMessage(hwnd, OS.WM_SYSCOMMAND, OS.SC_MAXIMIZE, 0);

OS.SetForegroundWindow(PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell().handle);

Comment: I viewed this post, but alt+tab just useful for seperate application.
https://stackoverflow.com/questions/4782231/using-java-to-set-the-focus-to-a-non-java-application-in-windows
Comment: CWDOW maybe work, but it depends on third party exe.
Comment: Finally, it works by using OS.SetForegroundWindow(hwnd);
When an application embeded in another application, I can't use OS.FindWindow(null, new TCHAR(0, title, true)); to get hwnd. Maybe there is no title now. If I store the hwnd get before, it works.
Answer: To set focus to a Windows application I use the following method:
Required Imports:
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;

The method:
/**
 * Sets focus to a running windows application Windows Application. If the
 * handle of the desired application is not found then nothing happens.

 *
 * Example Usage 1:
 *
 *      setFocusToWindowsApp("Untitled - Notepad");
 *
 * Example Usage 2:
 *
 *      setFocusToWindowsApp("Untitled - Notepad", 1);

 *
 * @param applicationTitle (String) The title contained upon the application's
 * Window Title Bar.

 *
 * @param windowState (Optional - Integer - Default is 0) By default when the
 * desired application window is set to show to the forefront on screen it is
 * displayed in its Normal window state (not maximized or minimized). If a value
 * of 1 is supplied then the windows is brought to the forefront in its Maximized
 * state. If 2 is supplied then the window is set to is Minimized state.

 *
 *      0   Normal (default)
 *      1   Maximized
 *      2   Minimized

 *
 * A value supplied that is less that 0 or greater than 2 is automatically changed
 * to 0 (Normal State).
 */
public void setFocusToWindowsApp(String applicationTitle, int... windowState) {
    int state = User32.SW_SHOWNORMAL; //default window state (Normal)
    if (windowState.length > 0) {
        state = windowState[0];
        switch(state) {
            default:
            case 0:
                state = User32.SW_SHOWNORMAL;
                break;
            case 1:
                state = User32.SW_SHOWMAXIMIZED;
                break;
            case 2:
                state = User32.SW_SHOWMINIMIZED;
                break;
        }
    }

    User32 user32 = User32.INSTANCE;
    WinDef.HWND hWnd = user32.FindWindow(null, applicationTitle);
    if (user32.IsWindowVisible(hWnd)) {
        user32.ShowWindow(hWnd, state); //.SW_SHOW);
        user32.SetForegroundWindow(hWnd);
        user32.SetFocus(hWnd);
    }
}

This method will also expand the application window should it have been minimized onto the task bar as well as set focus upon it unless of course the integer value of 2 is supplied to the optional windowState parameter which tells the method to gain focus on the application but in its minimized state. If the application is not minimized then it minimizes it.


Difficulty with rewriting DNF's

Question:
Is the following formula in DNF?
$$((P \land Q) \land ( \neg R \land \neg S)) \lor ((r \lor s) \land (\neg p \lor \neg q))$$

I think it is not a DNF, because in the second part there are OR's inside an AND. Is this correct?
How should I rewrite this to a proper DNF?
Answer: You must simply expand it performing the AND's in the second part (following the same rule as if AND were a multiplication and OR an addition), so obtaining:
$$(p\land q\land \neg r\land\neg s)\lor(\neg p\land s)\lor(\neg p\land r)\lor(\neg q\land s)\lor(\neg q\land r)$$
Comment: Distributivity: the AND operation distributes over the OR operation. Notice that in boolean algebra there is one more distributivity rule, whereby the OR operation distributes over the AND operation. In this last case you cannot use the suggestion I told you where AND is though of as multiplication and OR as addition.
Comment: Thank you.How is this rule formally called?
Comment: Well explained. Thank you!
Comment: you're welcome. If it can be of any help, yesterday I solved a minimization problem that had as solution just your DFN (probably asked by one of your colleagues): https://math.stackexchange.com/a/2423199/309917
Comment: Yep, very well could be one of my colleagues :P. That post was usefull thanks.

Difficulty with rewriting DNF's


How to get/set value of MAX_ZONEORDER in user space?

Question: Is there any way to change MAX_ZONEORDER from user space without compiling kernel? How to get available nodes and pages on each node ?
Answer: You can get the value of max zoneorder in userspace using cat /proc/pagetypeinfo, but you cannot set max zoneorder value in userspace.
Value is set while memory subsystem ups, for setting value use kernel menuconfig.
default value is 11.


Array change input like if A change to B for example

Question: Question: so i have a form with arrays that sends data to excel but i need the time that they put in the form to be : and not . is there a way i can check the array like
if $time = 00.00 change to 00:00 like that, can I do that ?
if not is there a way to lock the format of the input form so it only accepts 00:00 and if they put 00.00 they will get something that says its wrong ?
Edit:
i have a list but if they doesent use it
<input list="start" name="start[]" value="" class="listbox" />
<datalist id="start">
<option value="08:00"/>
<option value="08:30"/>
</datalist>

Answer: You can use an HTML5 pattern to confirm the input meets your requirements.
pattern="^\d+:\d+$"

This requires the field has numbers to start with, a colon, and then ends with numbers. You also should have a validation server side incase someone bypasses the check, or is using an older browser.
if(!preg_match('/^\d+:\d+$/', $_POST['field'])) {
      echo 'Invalid input';
}

Regex demo: https://regex101.com/r/xp8IzI/1
Another client side option would be using a select in place of the datalist and input, that won't allow them to enter altering times though.
<select name="start[]" class="listbox">
     <option value="08:00">08:00</option>
     <option value="08:30">08:30</option>
</select>


o(h) term in birth-death process

Question: This is from the note

I have two questions.

Since $o(h)$ represents the probability of 2 birth and 1 death, 3 birth and 2 death, etc, why it still says $P(|X(t+h)-X(t)|>1)=o(h)$? shouldn't it be $P(|X(t+h)-X(t)|=1)=o(h)$?
how to get the equation 13 from equation 12?
Comment: To get (13) from (12), the idea is that for small $h$, $h^2\ll h$. In other words, as $h\to 0$, $h^2$ is negligibly small compared to $h$ (and similarly for $h^3$, $h^4$, etc.).
Answer: First of all, what does $o(h)$ (it is a class of functions, called Landau or Big- O notation) actually mean? Generally it means for a function $f\in o(g)$ that we have
$$
{\displaystyle \lim _{x\to a}\left|{\frac {f(x)}{g(x)}}\right|=0}
$$ As an example, take a differentiable function $f$, then we have for $h\to0$ the following
$$
f(x+h)=f(x)+hf'(x)+o(h)
$$
this means, that the approximation error goes faster than linear to $0$.
Your $2$nd question was already answered by @Math1000, for completeness:
Since we investigate the behavior of $h$ close to $0$, we indeed have
$$
h^2\ll h \text{ respectively for }n\geq2: h^n\ll h
$$
so for $h\to0$, all higher powers $h^n$ are of neglectable magnitude compared to $h$ and therefore we get
$$
(\lambda_ih)(1-h(\lambda_i+\mu_i)+\ldots)+o(h)=\lambda_ih+o(h)
$$
Your $1$st question:
The expression
$$
P(|X(t+h)-X(t)|>1|X(t)=i)=o(h)
$$
means, that for sufficient small h  ($\to 0$), the probability that there occurs  a jump in each direction larger of magnitude larger than $1$ is converging to $0$ faster than linear and for very small $h$ neglectable.
The bottom line is, that a Birth-Death process only jumps by $\pm1$ into the next state.

o(h) term in birth-death process


StarTeam - checkout file of a specific revision using stcmd

Question: Is it possible to checkout file of a specific revision using stcmd?
I want to checkout all (or some) history of a specific file.
Answer: Is it possible to checkout file of a specific revision using stcmd?

You can checkout a specific revision using the label as follows
"C:\Program Files\Borland\StarTeam Cross-Platform Client 2005 R2\stcmd" co -p "user:pwd@host:port/MyProject/view_r1/" -is -eol on  -o  -rp "D:\LocalDir" -cfgl  "LABELNAME"

The history of a particular file in that label is gotten by
stcmd hist -p "user:pwd@host:port/MyProject/view_r1/" -cfgl "labelName" -is -rp "D:\LocalDir" FILENAME

Answer: stcmd.exe co has a -vn flag that allows you to specify a version number.  This is the version number, not the DotNotation, so 1.15 would be version 16.  This command:
stcmd.exe co -vn 1 -fp . -p "user:password@server:port/ProjectName/ViewName/FolderPath" file.ext

would get you the 1.0 of file.ext in the current directory.  If you want to get the full history, you can parse the output of stcmd hist and figure out the current revision number, or you can just run the above stcmd co command with increasing version numbers from 1 until the result says "file.ext: skipped" instead of "file.ext: checked out" (the current version of stcmd does not error if the version number is too large to be valid).  Remember to either delete the local file between calls or add the -o flag to overwrite it.  I'd recommend deleting it - there have been issues with stcmd co and overwriting.
Note this will only get you the versions of the file on the current branch back to the 1.0 - you won't get any versions of the file from other branches.  So if the current version is 220.127.116.11, you would be able to get 188.8.131.52, 184.108.40.206, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0, but not 22.214.171.124.


script apenas em uma div

Question:

com .html
sem .html

to usando esse codido do adfly pra por .html nos links do meu site, são mais de 300 então não to afim de fazer manualmente.
Funcionou muito bem, porem ele esta atrapalhando outros links que não precisam dele.
Queria saber se tem como fazer funcionar apenas em uma div?
Comment: Não estou com tempo para responder agora, mas 1 pergunta: a tua página tem conteúdo dinamico ou o HTML é o mesmo desde que a página carrega. `adfy_id` é declarado algures?
Comment: HTML, não apenas na função
Answer: Adicione um atributo de 'id' (com um nome, claro) para sua div e use o método document.getElementById para capturar ela. Portanto, você não terá a propriedade links no seu elemento e terá que usar HTMLElement.prototype.getElementsByTagName para pegar os hyperlinks da div em uma array.
Se possível, poderia explicar o porquê de usar o evento onmousemove para atualizar os hyperlinks? Isso pode causar lentidões...

window['onmousemove'] = (function adfy() {

    /* Href file extension */
    var fileFormat = '.html';

    var div = document.getElementById("id"),
        links = div.getElementsByTagName("a");

    /* Iterate through the links */
    for (var i = 0, a; a = links[i]; i++) {
        if (a['href'].match(".html") || a['href'].match("javascript:") || a['href'].match("#")) {
            a.href = a['href'];
        } else a.href = a['href'] + fileFormat;
    }

});

  com .html
  sem .html

Answer: Adicione aos links que quer que tenha .html uma class, neste caso adicionei .addHtml. Assim a function só irá funcionar nesses elementos.
com .html
sem .html

script apenas em uma div


SQL Laundry List

Question: I had someone ask me for a comprehensive list of configuration options for an x64 SQL Server install. besides just SQL config options, they were also looking for info on OS settings (server 2003 in particular).
i know where we could get bits and pieces of the information, but does any provide a comprehensive type list?
Answer: http://technet.microsoft.com/en-us/default.aspx
Look for your version of SQL in there.
Comment: that's close, but it really is just an index of all the bits and pieces and doesn't seem to include OS configuration options. i've poked around there previously and will continue to do so, maybe i will be able to find two ror three useful links instead of the hundred it seems i need to browse.
Answer: The only OS related item that I have encountered is with SQL 2005 Enterprise Edition and that is setting the server group policy to lock pages in memory for the SQL Server service account.
Comment: Are you sure about that? http://support.microsoft.com/kb/918483
Comment: In Aug 2007 when researching the message "A significant part of sql server process memory has been paged out. This may result in a performance degradation." that was in our the sql (error) log, KB918483 indicated that granting 'lock pages in memory' to the SQL service account would correct this condition for SQL 2005 Enterprise Edition (and it did).

BTW, our OS is Windows 2003 R2 Enterprise x64 and we run SQL 2005  EE (64-bit).
Comment: you dont need that option for x64

SQL Laundry List


Downloading a file with MailChimp

Question: I've got a simple embedded MailChimp form (email addresss + submit button) on my site. For now, clicking on submit allows users to subscribe to my MailChimp list.
What I want is that when the user subscribes, he/she automatically receives an email containing a link to some PDF file. And that's it, I won't send anything else to this user.
So I guess this is not done using campaigns, because campaigns are emails sent from the admin to subscribers at specified times. By contrast, I want the user to receive the email containing the file immediately and only once.
How to do that?
Answer: You are right, you can't do that with email campaign. But you can do it uising the "welcome email".

When a new user subscribe to your list a "welcome email" can automatically be sent to him.
You can personalize the content of that email and it's the right place for you to put your html link to the pdf file that the user can download.

Downloading a file with MailChimp


How to compute differential forms multiplied by functions

Question: I'm learning differential forms (via the excellent book 'A Visual Introduction to Differential Forms and Calculus on Manifolds' by J. P. Fortney).
One operation I'm not 100% I understand how to parse is the notion of multiplying a form, say a 2-form, by a function e.g as in Question 3.31 in the book:

I get that that by using the definition in the book as a starting point, namely that the value of the two form dz^dx(u, v) itself can be computed essentially as a determinant (of the relevant projected components of the two input vectors), I get a real number representing the oriented volume of the projected parallelogram on the Z-X plane.
However, once I add in the 'xyz' bit infront, how do I treat this object? are those x, y, z components referring to the point 'p' at which I'm working with the cotangent space? e.g. so the whole thing is a function of the point i'm tangent at (plus the two vectors given to the two form as input, comprising in this case essentially a constant vector field)?
Comment: The multiplication is pointwise. You evaluate the form on some tangent vectors at a point to get a number, then evaluate the function at that same point to get a number, then multiply these numbers.
Answer: Same thing as Qiaochu said I'm just adding a bit of details for completeness.
If $\omega$ is a differential form on your manifold $M$, then at any point $p \in M$, it is essentially a map:
\begin{equation}
\omega|_p : T_p M \times \dots \times T_p M \to \mathbb{R}
\end{equation}
Given a function $f : M \to \mathbb{R}$, then the form $f \omega$ is defined pointwise:
\begin{equation}
(f\omega)|_p = f(p)\cdot\omega|_p
\end{equation}
where $\cdot$ just denotes usual multiplication in $\mathbb{R}$ (since $\omega|_p$ outputs a real number).
Comment: Got it, yes that's what I surmised. Thank you for clarifying!


Why is /storage/sdcard0/Music returned as the Qt standard music path, but /mnt/sdcard/Music is the path that works to show and play my mp3s?

Question: QStandardPaths::standardLocations(QStandardPaths::MusicLocation) returns /storage/sdcard0/Music/ on my Android devices (both older 4.1.2 and latest 5.1.1), but my mp3s are actually all located in /mnt/sdcard/Music/
I can easily fix this by simply replacing /storage/sdcard0/ with /mnt/sdcard/, but I don't think that is very future proof or correct.
Is /mnt/sdcard/ the correct path to use (I have tried all other variants I can come up with and none work with QML MediaPlayer) and why is Qt standard paths returning /storage/sdcard0/ which is clearly not working on any device I own?
Answer: Those paths are actually the same path. The /mnt folder has references to locations on the device.
Since /mnt is an Android standard now, using that would be your best bet.
Comment: Interesting then that the /mnt/sdcard/ path works with QML MediaPlayer, but /storage/sdcard0/ does not.
Comment: It is possible that the QML MediaPlayer has some sort of permissions issue, like it's trying to access /storage directly then getting the sdcard0 folder. I don't know what the exact implementation is though.


Counterexample for countable subadditivity of outer/exterior measure

Question: Is it possible to define an order-preserving map $\mu: \mathcal{P}\left(\mathbb{R}^d\right)\to [0,+\infty]$ such that $\mu(\emptyset)=0$ and that there exist countable mutually disjoint non-empty sets $\{E_n: n\in\mathbb{N}\}$ with $ E_i \cap E_j=\emptyset$ for $i\neq j$, satisfying $\mu\left(\cup_n E_n\right)>\sum_n \mu(E_n)$, where the infinite sum converges?
Since countable subadditivity is included as part of the definition of an outer/exterior measure, I'm just curious if the opposite could be true. I've never seen one such counterexample anywhere. Hence the question.
Answer: Consider $\mu(A)=\begin{cases}
0 \text{ if }0,1\notin A,\\
1 \text{ if }|A\cap\{0,1\}|=1,\\
3 \text{ if } 0,1\in A.
\end{cases}$


Cleanest way to generate stars in EJS

Question: Using ejs in Node.JS (templating) what's the cleanest and most efficient (in terms of typing) way to generate this kind of html for stars?
stars look like:

 reviews

I'm trying to avoid using some disgusting syntax like this:

 reviews

                            <% for (i = 0; i < 5; i++) { %>
                                    <% if (i < (star_rating - 0.5)) { %>

                                    <% } else { %>

                                    <% } %>
                            <% } %>

Answer: Nothing much you can do about the for loop, but the code inside it can be reduced by 4 lines using ternary/conditional operator:

 reviews

        <% for (var i = 0; i < 5; i++) { %>
            <span class="glyphicon glyphicon-star<%= (i < star_rating - 0.5)? '' : '-empty'%>">
        <% } %>

Cleanest way to generate stars in EJS


Expected count of event based on different probabilities per independent day

Question: This is very basic, but I just want certainty that what I'm doing isn't stupid.
Say I have a set of data which gives me a probability of an event A happening each day for a week.
For example:
day 1: 0.1
day 2: 0.15
day 3: 0.05
day 4: 0.1
day 5: 0.1
day 6: 0.05
day 7: 0.05

Now, what I want is the number of event A we expect to have happened after these 7 days.
What I would do, considering this binomial distribution, is:
E = 0.1 + 0.15 + 0.05 + 0.1 + 0.1 + 0.05 + 0.05 = 0.6

Hence, we expect 0.6 event A to happen during that week.
Is this correct?
As an aside, I'll then want to apply a Poisson process on this to obtain the probability of the event A happening within the next year, that is P(t < 1y) = 1 - exp(-0.6/7 * 365)
Answer: Hmmm, so, I decided to test it out in python:
import numpy as np
rows = [(1, 0.1), (2, 0.15), (3, 0.05), (4, 0.1), (5, 0.1), (6, 0.05), (7, 0.05)]

scenario = 0
n=50000
elts, probs = np.array(rows).T
m = len(elts)
scenario = [elts[np.random.rand(m) < probs].astype(int) for _ in range(n)]

print(np.mean([len(i) for i in scenario]))

This gives me when I run it 10 times:
0.60118
0.59308
0.60536
0.59812
0.6013
0.59246
0.6025
0.6027
0.60146
0.59656
0.59716

Hence it should confirm empirically that what I believed was indeed correct.
Answer: You are right.
The expected value of A event in a week is:
$$ E[X] = 1 \cdot 0.1 + 1 \cdot 0.15 + 1 \cdot 0.05 + 1 \cdot 0.1 + 1 \cdot 0.1 +1 \cdot 0.05 + 1 \cdot 0.05 = 0.6 $$
And when k is the number of A events happen, the Poisson distirbution probability is:
$$ p( k ; \lambda) = e^{-\lambda} \frac{\lambda^k}{k!} $$
$$ \text{where } \lambda = \frac{events}{time}*period$$
Then, the probability of the event A happening in next 365/7 weeks is equal to 1 minus the probability of the event A not happening at all:
$$ 1- P(k=0; \lambda) = 1 - e^{-0.6 * 365/7} \frac{\lambda^0}{0!} $$
which is almost 1.


JSP para desenvolvedores .NET

Question: Sou desenvolvedor .NET que precisa entender um bug que ocorre numa aplicação JSP. (Não preciso compilar ou corrigir, só entender como o mesmo está usando o banco de dados e etc.)
Já tenho o Eclipse, solução carregada, tenho os fontes e etc. Mas preciso de um quick start na arquitetura. Ainda estou com dificuldades básicas do tipo essa página está sendo populada como?
Existe algum tipo de tutorial rápido para desenvolvedores de JSP para desenvolvedores .NET?
Tenho perguntas do tipo :

JSP está mais para ASP, ASP.NET ou ASP.NET MVC?
Tipo quais as diferenças entre ASP.NET e JSP, em que são similares e
etc.
Existe codebehind?
Use-se controllers tipo no ASP.NET MVC?
Uma URL http://meusite/teste.do, onde encontro o arquivo jsp?
Comment: A princípio, não existe. Uma resposta explicando isso caberia melhor.
Answer:
JSP está mais para ASP, ASP.NET ou ASP.NET MVC?

A princípio, para as três, embora não seja exatamente correto estabelecer este tipo de paralelo. JSP é uma tecnologia de processamento de HTML, assim como a notação ASP, ASPX ou Razor. As três tecnologias da Microsoft usam, respectivamente, ASP Clássico e linguagens dentro do .NET para processar o conteúdo de marcação. JSP faz o mesmo com Java.

Tipo quais as diferenças entre ASP.NET e JSP, em que são similares e etc.

Há mais similaridades que diferenças. Ambas processam uma página com marcações de forma a obter um resultado dinâmico, normalmente em HTML.
Há algumas respostas sobre isso aqui.

Existe codebehind?

JSP não é orientado a eventos. Aqui tem-se uma confusão com o ASP.NET Web Forms, que é uma stack de frameworks. JSP é apenas um framework, especializado na substituição de um documento anotado com a notação característica por conteúdo processado pelo Java.

Use-se controllers tipo no ASP.NET MVC?

Assim como na resposta anterior, o ASP.NET MVC é uma arquitetura, uma stack de frameworks. Uma comparação mais equivalente seria JSP vs. Razor, ou JSP vs. ASPX.
Contudo, o Java possui seus próprios frameworks MVC que podem ser usados juntamente com o JSP, como o Spring MVC e o Play! Framework.

Uma URL http://meusite/teste.do, onde encontro o arquivo jsp?

Depende do framework. Se for um framework MVC, por exemplo, normalmente estes arquivos ficam em um diretório Views.
Comment: É comum quando nos envolvemos com outras tecnologias, ter o hábito, que pode ser ruim, de fazer relações com o que já conhecemos. Por isso nesse sentido sua resposta é de grande ajuda para que eu não faça as relações erradas. Obrigado. Já ajuda no entendimento do que tenho pela frente.

JSP para desenvolvedores .NET


Need some Guide with a Android SELinux Build Error

Question: im currently trying to compile Android 9 with an Quectel EC25 LTE on the RockPi 4.
But currently i'm stuck at the SELinux implementation.
The EC25 RIL Guide tells me to modify/add the following Files to the src tree.

($Android_src)/system/core/rootdir/ueventd.rc

#quectel port
/dev/ttyUSB* 0660 radio radio
/dev/cdc-wdm* 0660 radio radio
/dev/qcqmi* 0660 radio radio
/dev/cdc-acm* 0660 radio radio

($Android_src)/external/sepolicy/file_contexts

/dev/ttyUSB[0-9]* u:object_r:tty_device:s0
/dev/ttyACM[0-9]* u:object_r:tty_device:s0
/system/bin/rild u:object_r:rild_exec:s0
/system/socket/rild u:object_r:rild_socket:s0
/system/socket/rild-debug u:object_r:rild_debug_socket:s0
/system/bin/pppd u:object_r:pppd_exec:s0
/dev/ppp u:object_r:ppp_device:s0

($Android_src)/external/sepolicy/rild.te

allow rild default_prop:property_service set;
allow rild device:chr_file { read write ioctl open getattr };
allow rild kernel:system module_request;
allow rild net_radio_prop:property_service set;
allow rild ppp_device:chr_file { read write ioctl open };
allow rild ppp_exec:file { read execute open execute_no_trans };
allow rild radio_prop:property_service set;
allow rild self:capability { net_admin setuid };
allow rild shell_exec:file { read execute open execute_no_trans };
allow rild sysfs_wake_lock:file { open read write };
allow rild system_file:file execute_no_trans;
allow rild system_prop:property_service set;

after running make i get the following Error:
FAILED: out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy
/bin/bash -c "(ASAN_OPTIONS=detect_leaks=0 out/host/linux-x86/bin/checkpolicy -M -c             30 -o out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.tmp out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.recovery.conf ) && (out/host/linux-x86/bin/sepolicy-analyze out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.tmp permissive > out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.permissivedomains ) && (if [ \"userdebug\" = \"user\" -a -s out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.permissivedomains ]; then          echo \"==========\" 1>&2;               echo \"ERROR: permissive domains not allowed in user builds\" 1>&2;             echo \"List of invalid domains:\" 1>&2;               cat out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.permissivedomains 1>&2;           exit 1;                 fi ) && (mv out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.tmp out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy )"
libsepol.report_failure: neverallow on line 532 of system/sepolicy/public/domain.te (or line 10484 of policy.conf) violated by allow rild default_prop:property_service { set };
libsepol.report_failure: neverallow on line 418 of system/sepolicy/public/domain.te (or line 10370 of policy.conf) violated by allow rild device:chr_file { read write open };
libsepol.check_assertions: 2 neverallow failures occurred
Error while expanding policy
out/host/linux-x86/bin/checkpolicy:  loading policy configuration from out/target/product/rk3399/obj/ETC/sepolicy.recovery_intermediates/sepolicy.recovery.conf
[  4% 449/10291] build out/target/product/rk3399/obj/ETC/sepolicy_neverallows_intermediates/sepolicy_neverallows
FAILED: out/target/product/rk3399/obj/ETC/sepolicy_neverallows_intermediates/sepolicy_neverallows
/bin/bash -c "(rm -f out/target/product/rk3399/obj/ETC/sepolicy_neverallows_intermediates/sepolicy_neverallows ) && (ASAN_OPTIONS=detect_leaks=0 out/host/linux-x86/bin/checkpolicy -M -c               30 -o out/target/product/rk3399/obj/ETC/sepolicy_neverallows_intermediates/sepolicy_neverallows out/target/product/rk3399/obj/ETC/sepolicy_neverallows_intermediates/policy.conf )"
libsepol.report_failure: neverallow on line 532 of system/sepolicy/public/domain.te (or line 10425 of policy.conf) violated by allow rild default_prop:property_service { set };
libsepol.report_failure: neverallow on line 418 of system/sepolicy/public/domain.te (or line 10311 of policy.conf) violated by allow rild device:chr_file { read write open };
libsepol.check_assertions: 2 neverallow failures occurred
Error while expanding policy
out/host/linux-x86/bin/checkpolicy:  loading policy configuration from out/target/product/rk3399/obj/ETC/sepolicy_neverallows_intermediates/policy.conf
[  4% 450/10291] //bionic/libc:libc_bionic_ndk clang++ bionic/bionic_systrace.cpp [arm]
ninja: build stopped: subcommand failed.
10:24:06 ninja failed with: exit status 1

i'm not familiar with Android/SELinux but i googled about the error and found "neverallow" directives to be set without any luck.
Help would be appreciated,
rgds
Comment: Does this help? https://stackoverflow.com/questions/58210696/build-aosp-custom-rom/58211402#58211402
Comment: after adding "-rild" to the lines:

system/sepolicy/public/domain.te :418
neverallow { domain -rild } device:chr_file { open read write };

system/sepolicy/public/domain.te :523
neverallow { domain -init -vendor_init -rild } default_prop:property_service set;

i receive following error:

system/sepolicy/public/domain.te:418:ERROR 'unknown type rild' at token ';' on line 10295:
neverallow { domain -rild } device:chr_file { open read write };
Comment: Ok, that's strange. The existing source in system/sepolicy has other mentions of rild, right? Does it have "type rild, domain;" somewhere?
Comment: i checked folder "system/sepolicy/*" for files containing "type rild, domain;"
system/sepolicy/vendor/rild.te
system/sepolicy/prebuilts/api/26.0/public/rild.te
system/sepolicy/prebuilts/api/27.0/public/rild.te

thats all in /system/sepolicy/*
Comment: this problem is resolved ?? i am also facing same issue.
Comment: I have this same issue. Do you have a specific fix?
Answer: Your allow rules are too generic for Android.
The neverallow rules are quite well documented. Look  at system/sepolicy/public/domain.te:532 and system/sepolicy/public/domain.te:418 from your error message:
# Require that domains explicitly label unknown properties, and do not allow
# anyone but init to modify unknown properties.
neverallow { domain -init -vendor_init } default_prop:property_service set;

# Don't allow raw read/write/open access to generic devices.
# Rather force a relabel to a more specific type.
neverallow domain device:chr_file { open read write };

You need to find out which properties rild has to set and then add a more specific allow rule. Check if existing property_contexts files already assign a type to the properties rild needs or create them yourself.
The same needs to be done for the devices rild wants to access.
Note: There are macros at system/sepolicy/public/te_macros which would make your rild.te more readable. Example: replace allow rild default_prop:property_service set with set_prop(rild, default_prop).