No resource found that matches the given name: attr 'actionBarStyle'

Question: I am trying to change the android action bar style. The minimum API support for the app is 8. So as using android:actionBarStyle attribute in the style xml file in the values folder gives the minimum required API 11 error, I have commented it out and moved it to a separate style xml file in v11 folder.
However, when using the actionBarStyle attribute only for android 2.1 and higher as mentioned in the android documentation, it gives me the No resource found error. Below is the style code:

I have tried changing the style parent theme from DeviceDefualt to Holo.Light.DarkActionBar, AppCompat.Light.DarkActionBar, etc. but the error still remains.
Comment: Have you added the appcompat-v7 library project to your application?
Comment: Do I have to add that extra library manually? My minimum api version is 8? Is there any equivalent library for v8?
Answer: If you want to use the standard Action Bar on Android devices v7 appcompat library, which backports the Action Bar to any API 7+ device when you use ActionBarActivity. (Note, the Android documentation you found reference this same library, hence the 'When using the Support Library' comments throughout that document)
To add it to your project, you can follow the directions for adding a library with resources for whatever IDE you use.
Once you have the appcompat library added, you may consider using a tool like the Android Action Bar Style Generator which automatically builds the correct styles/resources needed to fully style your action bar (make sure to change the 'Style Compatibility' drop down to 'AppCompat').
Comment: ahh.. the 'When using the Support Library' comment was misleading to me. Now understood. Yes, I had checked that generator. Thanks.


Why are there mathematicians that do not use computers?

Question: I was watching a video on Andrew Wiles and his proof of Fermat's Last Theorem and I quite liked the video, especially the complexity of the proof only to prove a simple concept which can be understood by most people.
I also liked the graphics they used to illustrate elliptic curves and modular forms.
But then Andrew Wiles said that he never uses a computer, he only uses pen and paper and I also heard of other mathematicians that don't use computers.
Do they not use computers because there are problems only a mathematicians can solve or are there other motives? Wouldn't the proof have taken him less time if he used a computer to assist him?
Comment: You can't delegate the thinking to a computer. If your work involves mostly thinking and little computing, you can use a computer mostly for emails, there simply isn't much where a computer _could_ help.
Comment: I recently heard something along these lines: "Mathematics asks 'what?' and 'why?', while computer science asks 'how?'" I use computers a lot in my mathematical work, but that is because many of my mathematical questions either a) have to do with computation, or b) can be helped to some extent by having an unbiased source confirm that I'm not doing something stupid. (One example of b would be using Monte Carlo sanity checks for complex integration proofs.) It's easy to see why someone working on sufficiently non-constructible mathematics, e.g. the continuum hypothesis, would have no use for b.
Comment: There are areas of mathematics where the use of computers is not so useful. The emphasis is not on numerical computations or modelling of large systems, for example. And the theorem provers we have are not developed enough to be useful in all areas.
Comment: @DanielFischer: ... and for typing up your papers. ;)
Comment: I vote not to close.
Comment: @KonformistLiberal It is not obvious. It is in fact reasonable to assume that you can reduce a problem of Fermat type to verifying properties of certain explicit curves, and these properties could in principle be verified with the assistant of explicit computations.
Comment: @Rasmus Isn't that what assistants/students (or even secretaries) are for?
Comment: @user2357 I'm not quite sure what the difference is between computation and a computer-based AI solving a problem. The latter is still computation, but with a (I guess only implied) more sophisticated algorithm.
Comment: I know this is a more general question but for Fermat's Last Theorem, you should prove it for all numbers, so computers obviously can't do it.
Comment: It's been interesting to observe how computers have been playing an important role in the twin primes polymath project.
Comment: We can also discuss this question with respect to the future of computing, i.e. quantum computers and the impact that more powerful computers can have on mathematics and whether more mathematicians will start using them. Currently it seems like the main use of computers in mathematics is computation but with more advanced artificial intelligence computers can probably prove conjectures etc. but this discussion is off topic as it should probably be discussed on on a computing site or physics site.
Comment: @DanielRust may be I should have said calculations instead of computation. I am not sure exactly what they are used for right now and what their mathematical limitations are.
Comment: Maybe related question: [How to properly use technology for back-of-the-envelope calculations?](http://math.stackexchange.com/questions/762665/how-to-properly-use-technology-for-back-of-the-envelope-calculations)
Comment: I think they somehow consider the computer as a rival to their mind, fearing it might blunt their minds.
Answer: I work in software and I have an amateur interest in mathematics, and from what I can tell many theoretical mathematicians don't have much use for computers because of the domains they work in. In order for a mathematician to utilize a computer, the problem must either be something that requires a lot of computation or is already formalized enough for a proof assistant or theorem prover to attack.
If you need one closed form solution to an easy differential equation, just using the stuff you learned in calculus is easier than figuring out how to use software that does integration for you, much as you wouldn't turn to a calculator to multiply six times nine. Computers can be useful for areas of mathematics where you need to come up with lots of closed form solutions (computer algebra systems) numerical integration or integral transforms, or running other intensive computing tasks in other domains like computing the class number (or other properties) for a large number of number fields.
Many of these problems are tedious and not particularly interesting to theorists, even if they're quite useful for applied math; Further, solving the problem often requires writing software to do it, given theorists often work in unexplored areas. For theorists, you often want to prove a statement of some sort, and that requires a proof assistant of some sort; While they can be useful, the foundations for most graduate level mathematics aren't formalized in first order logic, and where they are they're usually inaccessibly unwieldy compared to more informal reasoning.
Further complicating the picture is the traditional method of formalizing mathematics is built on the foundation of set theory in first order logic, which is often incompatible (or at least unwieldy) with metamathimatical reasoning about categories, nonstandard models, and other foundational issues. So if mathematicians who worked in this field tried to use computers, they'd spend more time writing software and formalizing existing math than doing new work.
As an example, very little of Wiles proof has been formalized in a form that can be verified by mechanized reasoning, because most of the branches of mathematics that it rests on have yet to be formalized. This may change in coming decades, as theorem provers and proof assistants get more advanced, but for the time being computers are useful for the most mature, formalized areas of mathematics that is largely the domain of physics and applied math.


Why is $T(n)=2T\left(\frac{n}{2}\right) + n\log(n)$ time complexity is $Θ\big( n\log^2(n) \big) $?

Question: I was doing some homework and worked out a closed form for $T(n) = 2T\left(\frac{n}{2}\right) + n\log(n)$ and got:
$T(n)=n+n\left(\log(n)+\log\left(\frac{n}{2}\right)+\log\left(\frac{n}{4}\right)+\log\left(\frac{n}{8}\right)+\cdots+ 1\right)$
as closed form.
I was able to prove that $T(n)$ is in big O of $n\log^2(n)$ by:
$T(n) < n + n\log(n)\leq a\log^2(n)$ for some constant $a\geq 1$
But I don't know how $T(n)$ is in big omega of $n\log^2(n)$ since I have to go the other way and cannot see how:
$T(n)\geq a\log^2(n)$
in order to prove that $T(n)$ is in big omega of $n\log^2(n)$ and therefore in big theta of $n\log^2(n)$.
Am I missing something here?
Comment: Note that $\log(n/2^k) = \log(n) - k$. So, the sum you have is $ \sum_{k = 0}^{\log n} \log(n) - k.$ This works out to $\log^2(n)/2 + O(\log n)$ (using $\sum_{i = 0}^m i = m^2/2 + O(m)$).
Comment: But how does that prove big omega?
Comment: Notice that the above is an equality. So, the sum is $S = \log^2(n)/2 + O(\log n) = \frac{\log^2(n)}2 (1 + o(1)),$ which is a quantity that is $\Omega(\log^2(n))$. (More concretely, $ \frac{S}{\log^2 n} = \frac{1}{2} + o(1),$ so $\liminf \frac{S}{\log^2(n)} > 0,$ ergo $S = \Omega(\log^2 n).$)
Answer: Let $k = \lfloor \frac12 \log n\rfloor$, which is $\Omega(\log n)$. Then if we just take the first $k+1$ terms of the sum, that is
$$
    \log n + \log \frac n2 + \log \frac n4 + \dots + \log \frac n{2^k},
$$
we already get something that's $\Omega(\log^2 n)$.
That's because $\frac{n}{2^k} \ge \sqrt n$, so $\log \frac{n}{2^k} \ge \log \sqrt{n} = \frac12 \log n$, which is $\Omega(\log n)$ - and that's the smallest term. Summing $\Omega(\log n)$ terms, on which we have an $\Omega(\log n)$ lower bound, we get $\Omega(\log^2 n)$.
Answer: $$ \bbox[7px,border:2px solid red] {\text{MASTER THEOREM}}: $$
$$T(n)=aT(n/b)+f(n).$$
$$\bbox[1px,border:1px solid green] {a\ge 1,b>1,f(n)=Θ\big( n^k\cdot \log^p(n)\big)}$$
$$\text{CASE 1}:$$
$$ \text{if } \log_b(a)>k\text{ then: }\quad \bbox[0.2px,border:0.8px solid black] {T(n)=Θ\big( n^{\log_b(a)}\big)}   $$

$$\text{CASE 2}:$$
$$\text{if } \log_b(a)=k:\begin{cases}
\text{if $p>-1:\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^k\cdot \log^{p+1}(n)\big)}$} \\
\text{if $p=-1:\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^k\cdot \log\big( \log(n)\big)\big)}
$ }\\
\text{if $p<-1:\quad \bbox[1px,border:1.5px solid black] {T(n)=Θ\big( n^k\big)}$ }\\
\end{cases} $$

$$\text{CASE 3}:$$
$$\text{if $\log_b(a)<k:\begin{cases}
\text{if $p\ge 0:\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^k\cdot\log^p(n)\big)}
$} \\
\text{if $p<0:\quad \bbox[0.5px,border:0.2px solid black] {T(n)=\mathcal O \big( n^k\big)}
$}
\end{cases}$}$$

$$\text{So, let }a=b=2,f(n)=Θ\big( n^1\cdot \log^1(n)\big) \Rightarrow k=p=1,$$
$$\log_2(2)=1=k\text{ we are in case 2, where $p=1>-1$ hence,}$$
$$T(n)=Θ\big( n^k\cdot \log^{p+1}(n)\big)=\bbox[3px,border:2px solid green] {Θ\big( n\cdot \log^{2}(n)\big)}. $$
Comment: I am not allowed to use master theorem to answer this question and had to do it in another way.


Alternative to field group module

Question: The field group module is currently not ready for Drupal 9. I would like to implement the same functionality for my forms. What other alternative module can I use that is compatible with Drupal 9, PHP 7.4, and MySQL 8?
Comment: As Kevin said, the [Field Group](https://www.drupal.org/project/field_group) module is definitely D9 ready.
Comment: What does this have to do with webforms?
Comment: I'm voting to close this question because it's asking for recommendations or suggestions on hosting, tools, modules, themes, distributions, books, tutorials, documentation, or other off-site resources.
Answer: Field Group does work with Drupal 9. There is no alternative.

Alternative to field group module


Theme the View/Edit Tabs

Question: I would like to be able to theme the view/edit tabs.
That is, I'd like to add a class to the
.
Any help with this would be much appreciated.
Cheers in advance.
Answer: If you want to create tabs use this module: http://drupal.org/project/tabs
else you can modify the tab wrapper in your page.tpl.php and then costumize your tabs with the api functions, to see more read:
http://api.drupal.org/api/drupal/includes--menu.inc/function/theme_menu_local_task

Theme the View/Edit Tabs


parametrical representations of polygons

Question: Could you please explain, how one gets this Parametric representation of a solid trapezoid ? I mean the procedure and not the answer. I have some linear geometry (as polygons), and I need to represent them in the parametric form. I have no idea how to get the parametric form of the rectangle or triangle and how to build the complex geometries (like trapezoid). May be some hints or where can I find it in the literature?
Here are the examples of my geometries.
Example Geometry 1
Example Geometry 2
Comment: Possibly helpful: https://math.stackexchange.com/questions/315828/transformation-between-square-and-a-polygon
Comment: Welcome to stackexchange. In order for us to help you we need much more context. Please [edit] the question to show us a few particular polygons you care about, and why, so we can see how you are representing them. You seem to want a map from the unit square to your polygon. There is probably no easy way to do that in general.. Are you looking for an algorithm?
Comment: I have taken the liberty to modify your title in order to attract more attention for future readers. Furthermore, I have added tag "polygons".
Comment: It is unclear if you want to parameterize the outlines or the whole area. Maybe better to tell us why you need that. Sounds like an XY question.
Comment: I need to parametrize the outlines, as I need to find the coordinates of the surface points. So the coordinates of the outlines in a parametric form
Answer: Here are two different parametrization methods for a convex quadrilateral $ABCD$, a trapezoid being a particular case.
First method : ("bilinear interpolation", using barycentric principles)
a) on the two opposite sides $AB$ and $DC$, using a first parameter $0 \leq u \leq 1$, define $M:=(1-u)A+uB \in [AB]$ and $P:=(1-u)D+uC \in [DC].$
b) on the two other opposite sides $BC$ and $AD$, using a second parameter $0 \leq v \leq 1$, define $N:=(1-v)B+vC \in [BC]$ and $Q:=(1-v)A+vD \in [AD].$
The point at the intersection of line segments $[MP]$ and $[NQ]$ is defined in a unique way by coordinate pair $(u,v)$ ; in a reciprocal manner,  every point interior to the quadrilateral has such a representation.

Fig. 1 : the case $u=1/2$ ($M$ and $P$ are the midpoints of their line segments), and $v=1/3$.
This mapping method is called bilinear interpolation.
Grouping operations a) and b) above, one obtains the coordinates of the intersection point as
$$\begin{cases}x& = &\color{red}{(1-v)}(\color{blue}{(1-u)}x_A+\color{blue}{u}x_B)+ \color{red}{v}(\color{blue}{(1-u)}x_D+\color{blue}{u}x_C) \\
y& = &\color{red}{(1-v)}(\color{blue}{(1-u)}y_A+\color{blue}{u}y_B)+ \color{red}{v}(\color{blue}{(1-u)}y_D+\color{blue}{u}y_C)\end{cases}$$
or, in a simplified form :
$$\begin{cases}x& = &a+bu+cv+duv \\ y &= &e+fu+gv+huv\end{cases}\tag{1}$$
for certain fixed coefficients $a,b,...h$.
References :

The long answer by NominalAnimal to this SE question : Quadrilateral Interpolation
A previous answer of mine https://math.stackexchange.com/q/1792460 showing that the method can be extended to a non planar case.
What is the inverse of this transformation from a rectangle to a quadrilateral?
for an application to color interpolation : https://en.wikipedia.org/wiki/Bilinear_interpolation

Remark : this transformation is not amenable to a projective transform (see below) because for exemple lines $AB$, $CD$ and $NQ$ do not intersect into a single point.

2nd method : (projective transformation)
Convex quadrilateral $ABCD$ could as well be considered as the image by a projective transformation of a reference square $[0,1] \times [0,1]$ with natural coordinates $(u,v)$ that will be "mapped" onto the quadrilateral. In this case, we have to find the matrix entries of the corresponding homography.
If for example, we want to "map" the reference square with current point $(u,v) \in [0,1] \times [0,1]$, to the quadrilateral given on the figure below, we will use the projective transformation :
$$x=\dfrac{au+bv+c}{gu+hv+1}, \ \ \ y=\dfrac{du+ev+f}{gu+hv+1}\tag{2}$$
with fixed coeffients that we store in a so-called homography matrix :
$$H=\begin{pmatrix}a&b&c\\d&e&f\\g&h&1\end{pmatrix}=\begin{pmatrix}7&5&1\\2&4&2\\1&1&1\end{pmatrix}$$
(please note the common denominator). Check for example that the image of vertex $(0,0)$ on the square is vertex $(1,2)$ on the quadrilateral.
The entries of matrix $H$ are obtained through 8 equations expressing that the image of $(0,0)$ is $(x_A,y_A)$ (known quantities), the image of $(0,1)$ is $(x_B,y_B)$, etc.
Being able to go the other way (knowing (x,y), find $(u,v)$, is essential. We need for that inverse formulas that are readily obtained : they belong to the same family of projective transformations with coefficients the entries of $H^{-1}$...

Fig. 2 : Points $(u,v)$ are related to their images $(x,y)$ by a green line segment.
Appendix : Matlab program that has generated Fig. 2 :

<code>i=complex(0,1);
R=[7,5,1,2,4,2];
a=R(1);b=R(2);c=R(3);d=R(4);e=R(5);f=R(6);
Z=@(x,y)((a*x+b*y+c)./(x+y+1)+i*(d*x+e*y+f)./(x+y+1));
plot(Z([1,1,0,0,1],[0,1,1,0,0]),'b');axis equal
plot([1,1,0,0,1],[0,1,1,0,0],'r')
plot([1+0i,Z(1,0)],'g')
</code>
Comment: @Ekaterina Deriabina Any comment to my answer ?


Find the value of $h$ so that the vector $(2,4,3)$ is the image through $T$ of the vector $(-2/3,4/3,-1)$

Question: Let $T: \mathbb{R}^3\to \mathbb{R}^3$ be the linear transformation that reflects any vector about the $xz$-plane then multiplies its length by $h>0$. Find the value of $h$ so that the vector $(2,4,3)$ is the image through $T$ of the vector $\left(-\cfrac{2}{3},\cfrac{4}{3},-1\right)$
Can anyone help me in understanding this question. Thank you
Answer: Surely there is no such $h>0$ since you know that $T$ does the following:
$$ \left(
\begin{array}{c}
x\\
y\\
z\\
\end{array}
\right)\mapsto h\left(
\begin{array}{c}
x\\
-y\\
z\\
\end{array}
\right) $$ So we'd need a $h$ to satisfy:
$$ \left(
\begin{array}{c}
2\\
4\\
3\\
\end{array}
\right)\mapsto h\left(
\begin{array}{c}
2\\
-4\\
3\\
\end{array}
\right) $$ but we are told that the vector $(2,3,4)$ is mapped to $(-2/3,4/3,-1)$ by $T$, so:
$$ h\left(
\begin{array}{c}
2\\
-4\\
3\\
\end{array}\right)=\left(
\begin{array}{c}
-\frac{2}{3}\\
\frac{4}{3}\\
-1\\
\end{array}\right) $$
but then what positive $h$ would satisfy $2h=-2/3$ etc.


Get Counts according to Last Date in SQL Server

Question: I have this data in a table:
+-------------+-------+----------------+
| id   | Added | Removed | Date        |
+-------------+-------+----------------+
|  1   |  yes  |  yes    | 06-19-2016 |
|  2   |  yes  |  yes    | 06-19-2016 |
|  3   |  yes  | false   | 06-19-2016 |
|  4   |  false|  yes    | 09-19-2016 |
|  5   |  yes  |  yes    | 09-19-2016 |
|  6   |  false|  false  | 10-19-2016 |
|  7   |  false|  yes    | 10-19-2016 |
|  8   |  yes  |  false  | 10-19-2016 |
|  9   |  false|  yes    | 11-19-2016 |
+-------------+-------+-----------------+

I know total added and removed record for date wise is like
  Date        TotalRecordAdded TotalRecordRemoved
06-19-2016          3                 2
09-19-2016          1                 2
10-19-2016          1                 1
11-19-2016          0                 1

What is the SQL Server query for getting this result?
Comment: You can do this quite easily by using (sum case when Added = 'yes'...) in your select clause. Also, I'd store the values as 0/1 instead of strings.
Comment: Please show us what you have tried so far, and tell us where you're stuck - we'll be glad to help, but we're not just writing the whole code for you....
Answer: You can do it with conditional aggregation using CASE EXPRESSION :
SELECT t.date,
       COUNT(CASE WHEN t.added = 'yes' THEN 1 END) as TotalRecordAdded,
       COUNT(CASE WHEN t.removed = 'yes' THEN 1 END) as TotalRecordRemoved
FROM YourTable t
GROUP BY t.date


Como remover parênteses de valores num array?

Question: Tenho um array e preciso remover todos os parênteses de todos os valores desse array. Segue o array:
$array = array(
    "chave1" => "(valor1)",
    "chave2" => "(valor2)",
    "chave3" => "(valor3)"
);

Preciso que fique assim:
$array = array(
    "chave1" => "valor1",
    "chave2" => "valor2",
    "chave3" => "valor3"
);

Como posso fazer isso usando o php?
Answer: Pode usar array_map(), para aplicar uma função anônima em cada item do array. A substituição fica por conta do str_replace() que procura por ( e ) e trocar por nada. Um novo array é gerado:
$array = array(
        "chave1" => "(valor1)",
        "chave2" => "(valor2)",
        "chave3" => "(valor3)"
);

$novo = array_map(function($item){return str_replace(array('(', ')'), array('', ''), $item);}, $array);

echo "
";
print_r($n);

Outra opção é usar array_walk() ele faz quase a mesma coisa que array_map() porém não gera um novo array, como o argumento é passado por referência a alteração é feita no próprio elemento.
array_walk($array, function(&$item){ $item = str_replace(array('(', ')'), array('', ''), $item);});

echo "
";
print_r($array);

Comment: Uma dúvida, em desempenho, o `array_map` supera uma estrutura de repetição? +1, ótima solução.
Comment: @lvcs não fiz nenhum teste de desempenho, o que posso dizer que `array_map()`/`array_walk()` podem ser mais práticos em algumas situações, evitando o `for`/`foreach`.
Comment: @Ivcs todas as funções nativas (escritas em C) são superiores em desempenho que qualquer estrutura criada com PHP puro.
Comment: @rray sim com certeza é mais prático :)
Comment: Funcionou direitinho!
Comment: uma dica seriá vc sempre optar por métodos próprios do PHP, como no caso de array_map(), pois ele estão otimizados para trabalhar da melhor forma com a linguagem.
Answer: Você pode alterar facilmente utilizando a função array_walk em conjunto com uma boa expressão regular.

array_walk - Apply a user supplied function to every member of an array

Como o manual diz, array_walk percorre todos os elementos de um array aplicando a cada um deles uma função fornecida como parâmetro.
Para remover os parênteses, utilizarei uma expressão regular. A ER em questão, é simples \(([^()]+)\). Traduzindo, significa "tudo que estiver dentro de parênteses que não sejam parenteses".
Conforme já informado, é necessário fornecer uma função para array_walk. Nesse caso, será criada uma função como callback. A função é a seguinte:
$callback = function(&$value , $key) {
    preg_match('/\(([^()]+)\)/' , $value , $matches);

    $value = $matches[1];
};

Aplicando o seu array com o callback.
array_walk($array , $callback);

Obterá o seguinte resultado:
array(3) { ["chave1"]=> string(6) "valor1" ["chave2"]=> string(6) "valor2" ["chave3"]=> string(6) "valor3" }

Comment: Boa solução, ainda mais usando regex :)
Comment: @DiChrist, muito obrigado. Com a regex, você vai pegar somente o que existe entre parênteses. Caso houver valores externos, eles serão ignorados.
Answer: Pode tentar assim:
foreach($array as $key => $value):
    $array[$key] = str_replace('(', '', $value);
    $array[$key] = str_replace(')', '', $array[$key]);
endforeach;

Basicamente percorri todos elementos do array e troquei ( e ) por nada.
Comment: Funcionou aqui mano!
Answer: Você pode percorrer o array com um loop foreach, usar str_replace para tirar os parênteses e escrever os itens sem os parênteses em um novo array:
$parentheses = array('(', ')');
$newArray = [];
foreach ($array as $value) {
  $value = str_replace($parentheses, '', $value);
  $newArray[] = $value;
}

Comment: Outra forma de resolver o problema apontando é alterar o valor por referência, basta adicionar um `&` antes da variável ex:  `foreach ($array as &$value)`
Comment: -1 pois não vai funcionar, `$value` é uma variável local da estrutura de repetição, quando você sai da estrutura de repetição e quando você percorre outro elemento do array ela deixa de existir, então é como que você não tivesse feito nada nessa estrutura de repetição, o correto seria usar `$array[$key]`, quando mudar eu retiro o -1.
Comment: Você está certo. Alterei a resposta para escrever um array novo, assim não fica duplicada, pois a sua resposta já faz o você comentou ;)


Radius of convergence using ratio test complex

Question: I have tried to compute the radius of convergence for the following series: $$\sum\limits_{n=0}^{\infty}ni^nz^n$$
but I keep getting $zi$ as the limit when I take the ratio.
What is the correct method for this problem?
Comment: So then notice that $|zi| = |z| < 1$ if and only if.....
Comment: You need to look at the absolute value of the quotients.
Comment: iff it converges, okay got it, thanks a bunch
Answer: Use the Cauchy Hadamard formula:
$$\frac1R=\lim\sup_{n\to\infty}\sqrt[n]{|ni^n|}=\lim\sup_{n\to\infty}\sqrt[n]n\,|i|=1\implies R=1$$


Find a singular value decomposition of the matrix

Question:
Fina a singular value decomposition for
  $$A=\begin{bmatrix} -2 & 2 \\ -1 & 1 \\ 2 & -2\end{bmatrix}.$$
  Find a (full svd)singular value decomposition for the matrix $A$.

My working thus far not sure how to determine u2 and u3 . A little confused on the whole process. ANy workings step by step that can assit would be appreciated.
$$A^TA=\begin{pmatrix} 9 & -9 \\ -9 & 9  \end{pmatrix}$$
For the eigenvalue $\lambda=18$ I found a normalized eigenvector of $\frac{1}{\sqrt 2}\begin{pmatrix} -1 \\ 1 \end{pmatrix}$. For $\lambda=0$ I found an eigenvector of $\frac{1}{\sqrt 2}\begin{pmatrix} 1 \\ 1 \end{pmatrix}$ and so $$V=\frac{1}{\sqrt{2}}\begin{pmatrix} -1 & 1 \\ 1 & 1  \end{pmatrix}.$$ $\Sigma$ is the $3\times 2$ matrix whose diagonal is composed of the singular values $$\Sigma=\begin{pmatrix} \sqrt{18} & 0 \\ 0 & 0 \\ 0&0  \end{pmatrix}.$$
 $$U1=\begin{pmatrix}\frac{2}{3} \frac{1}{3} \frac{-2}{3}\end{pmatrix}.$$
Comment: If your computations are correct, then any choice of $u_2$ and $u_3$ that makes $\{u_1, u_2, u_3\}$ into an orthonormal basis will suffice, since $u_2$ and $u_3$ disappear when you multiply by $\Sigma$.
Comment: Yes your steps are correct .. bravo, what is your question now ?
Answer: If $A$ is a matrix and $A \in \mathbb{R}^{ m \times n}$ then it has an SVD. i.e
$$A_{m \times n} = U_{m \times m} \Sigma_{m \times n} V_{n \times n}^{T}  \tag{1}$$
now if the rank of $A$ is $r$ then the reduced or truncated SVD is given by an SVD like the following
$$ A_{m \times n} = U_{m \times r} \Sigma_{r \times r} V_{r \times n}^{T} \tag{2} $$
that means your reduced SVD is
$$ A_{m \times n} = \begin{bmatrix} \frac{2}{3} \\ \frac{1}{3} \\  \frac{-2}{3} \end{bmatrix} \begin{bmatrix} \sqrt{18} \end{bmatrix} \begin{bmatrix} \frac{-1}{\sqrt{2}}  & \frac{1}{\sqrt{2}}\end{bmatrix} \tag{3}$$
checking this in Python
<code>import numpy as np

A1 = np.matrix([[-2, 2], [-1, 1], [2,-2]])

a1 = np.matrix([[2/3] , [1/3] ,[-2/3] ])
a2 = np.matrix([np.sqrt(18)])
a3 = np.matrix([-1/np.sqrt(2),1/np.sqrt(2)])

A2 = a1*a2*a3

error = np.linalg.norm(A1-A2)
error
Out[13]: 9.42055475210265e-16
</code>
Comment: @Liz There is no $u_2,u_3$ in this answer; it's a reduced SVD of a rank 1 matrix, so only one of each type of singular vector is required
Comment: Thanks RHowe. For u2 and u3 in part a) are you able to demonstrate how that comes about,
Answer: Your $A$ is rank $1$, as you can see by inspection. Thus the shape of $U,\Sigma,V^T$ in the reduced SVD are $3 \times 1,1 \times 1$ and $1 \times 2$ respectively. So you were actually done before computing the eigenvector with eigenvalue $0$.
If you want a full SVD, then you need shapes of $3 \times 3,3 \times 2$ and $2 \times 2$. To assemble this, you need to compute a unit eigenvector of $A$ with eigenvalue zero (which will be any unit vector orthogonal to $v_1$). This will be your $v_2$, which completes the set of right singular vectors. Then you need to get vectors $u_2,u_3$ that $\{ u_1,u_2,u_3 \}$ is an orthonormal system; this completes the set of left singular vectors.
Comment: Sorry Ian are you able to explain by workings still not getting it.
Comment: @Liz Do you want a full SVD or a reduced SVD? If you want a reduced SVD then you are already essentially done. $\Sigma=\begin{bmatrix} \sqrt{18} \end{bmatrix},V^T=\begin{bmatrix} -1/\sqrt{2} & 1/\sqrt{2} \end{bmatrix}$. To get $U$, multiply out $AV$ and normalize the columns (of which there is just one in this case).
Comment: @Liz But if you want a full SVD then you have some more calculations to do.


If $z$ is inversely proportional to $x$ and $z=5$ when $x=7$, find the value of $x$ when $z=70$

Question: If $z$ is inversely proportional to $x$ and $z=5$ when $x=7$, find the value of $x$ when $z=70$.
Comment: This is a "do my homework" question
Comment: what do you mean?
Comment: It means that all we see is your question, with no context, no attempt to answer it, and no manners. This is a site for improving one's mathematical abilities, not for doing other people's homework. By all means, yes, ask for help if you're stuck, but let us know what you think and what you've done. That way, we can help you to answer similar questions yourself in future.
Comment: im trying to understand what people are doing as well not just blindly copying....
Comment: How are we supposed to know that if all you do is show us the question?
Comment: ok ok i'll say what i've already done next time  and some step i had already done but im not that sure so im afraid to post
Answer: When two numbers are inversely proportional it is defined as:
$$a =\frac{k}{b}$$
Where $a$ is inversely proportional to $b$, and $k$ is a constant.
Therefore, in this problem:
$$z =\frac{k}{x}$$
When $z = 5$, $x=7$, so we can use this to find $k$:
$$5 =\frac{k}{7},\ k = 35$$
So our equation now becomes:
$$z = \frac{35}{x}$$
When $z = 70$, we have to find the value of $x$:
$$70 = \frac{35}{x},\ x = \frac{1}{2}$$
Comment: @linwei if you are content with the answer, feel free to upvote/check so other users know it has been answered.


How to compute the distance between a leaf and the root node in a tree structure

Question: I'm trying to create a tree structure. But I don't know how to use recursive methods.
I'm loading an array that contains info and children.
What I would like to know is, how far down is a node from the root?
For exmaple:

element with id 1 is 0 steps from the root
element with id 12 is 1 steps from the root
element with id 122 is 2 steps from the root
element with id 13 is 1 steps from the root

const data = [
    {id: 1, title: 'foo', children: [
        {id: 11, parentId: 1, title: 'bar',},
        {id: 12, parentId: 1, title: 'baz', children: [
            {id: 121, parentId: 12, title: 'qux'},
            {id: 122, parentId: 12, title: 'quz'}
        ]},
        {id: 13, parentId: 1, title: 'corge'}
    ]}
];

Comment: What do you mean by "tree component"?
Comment: Are you trying to find the depth of a specific `id`, or find the depth of every `id` at once?
Answer: You can write a recursive method for that:

const data = [
  {id: 1, title: 'foo', children: [
    {id: 11, parentId: 1, title: 'bar'},
    {id: 12, parentId: 1, title: 'baz', children: [
      {id: 121, parentId: 12, title: 'qux'},
      {id: 122, parentId: 12, title: 'quz'}
    ]},
    {id: 13, parentId: 1, title: 'corge'}
  ]}
];

function findDistance(data, id) {
  for(const elem of data){
    if(elem.id === id) return 0
    if(!elem.children) continue
    const value = findDistance(elem.children, id)
    if(!Number.isNaN(value)) return value + 1
  }
  //Not found, return NaN
  return NaN
}

console.log(findDistance(data, 1))   //0
console.log(findDistance(data, 12))  //1
console.log(findDistance(data, 122)) //2
console.log(findDistance(data, 13))  //1
console.log(findDistance(data, 0))   //Not found, NaN


couldn't display pdf file in my iframe in .net web application?

Question: I have to display a pdf file in an iframe control in .net web application.But when I run the application it could not load the pdf file in an iframe control. I don't know the reason for this...
This is my code...
aspx code :

C# Code :
protected void Button1_Click(object sender, EventArgs e)
{
    frmWord.Attributes.Add("src", Server.MapPath(@"~/iplt20.pdf"));
}

my pdf file is physically located in my project folder like below:
D:\vs-2010projects\rti_chk\rti_chk\iplt20.pdf

I have tried in ie,firefox,chrome also...
If firefox, inside iframe control it says "The address wasn't understood Firefox doesn't know how to open this address, because the protocol (d) isn't associated with any program."
Please guide me to get out of this issue...
Answer: User cannot drectly access local paths on server.
instead of d:\path_to_file you should produce something like http://youdomain.com/path-to_file
so
protected void Button1_Click(object sender, EventArgs e)
{
    var fullPath = ResolveUrl(filePath); // this could work instead of string concat
    //var fullPath = String.Format("{0}/{1}",serverpath,filepath);
    frmWord.Attributes.Add("src", fullPath);
}


Find is not a method Mongoose Error

Question: I'm working with a todoList app using express, node, mongodb, and I keep getting "find is not a method of" in this case my variable is todoItem. I created the schema and have data inside the db. When I run my app a collection is created in mongodb with "todos" name. then I can see the documents inside "todos" But still keep getting the error. Any help appreciated!
todoItem.find({}, function(err, todoItem) {
         ^

TypeError: todoItem.find is not a function
    at Object.<anonymous> (/home/george/Desktop/work/todo-nodejs/app.js:40:10)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:598:3

my app.js
var express = require("express");
var app = express();
var bodyParse = require("body-parser");
var mongoose = require("mongoose");

//mongodb connection
mongoose.connect("mongodb://localhost/todo");

//view engine for ejs file
app.set("view engine", "ejs");

//bodyparser for extracting data form ejs pages
app.use(bodyParse.urlencoded({extended: true}));

//mogoose schema
var todoSchema = new mongoose.Schema({
    name: String
});

var todo = mongoose.model("Todo", todoSchema);

//adding a new todoItem to db
var todoItem = new todo({
    name: "Wash car and change oil!"
});

//saving todoItem to mongodb
// todoItem.save(function(err, todoItem) {
//     if(err) {
//         console.log(err);
//     }
//     else {
//         console.log("saving: "+todoItem);
//     }
// });

//retrieving todoItem from mongodb
todoItem.find({}, function(err, todoItem) {
    if(err) {
        console.log("something went wrong");
    }
    else {
        console.log("find data: "+todoItem);
    }
});

/*var todoList = [
    "print documents for driving test",
    "send resume to prospect employers",
    "buy food for the pigs and shower"
]*/

//======Express routes Here!============//

//default route
app.get("/", function(req, res) {
    res.render("index.ejs", {todoList: todoList});
});

//add new todo item to list
app.post("/newtodo", function(req, res) {
    console.log(req.body.todoitem);
    var item = req.body.todoitem;
    todoList.push(item);
    res.redirect("/");
});

//catch all other routes
app.get("*", function(req, res) {
    res.send("all others /*");
});

//express server
app.listen(3000, function() {
    console.log("Server started port 3000");
});

Answer: Try todo.find(), because your model is stored into todo variable. todoItem is an instance of this model.
Comment: @miatech it's because `todo` is a model, and `todoItem` is a document. You do a `find()` on a model, and you `save()` a document. It doesn't make sense to `find()` a document.

Find is not a method Mongoose Error


Alternative admin-side content browsing - module?

Question: Does anyone know of, or is working on a Drupal 7 module which would provide alternative, hierarchical content browser on the admin side?
While the filter in the Find Content section is a great aid for unrelated pages, I'd really love to be able to browse through taxonomy-bound PAGES (rather than terms), just like I browse through folders and files in Windows Explorer or Mac's Finder.
What bites me most is that in default Drupal installation, the taxonomies are too much separated (in terms of managing and reviewing the content) from the actual pages. And the pages bound to vocabulary terms are browsable as unrelated ones.
I would be curious to see if anyone found a solution for that.
Regards,
Artur
Answer: I'm not sure if I understand what you're looking for in the admin pages, but I do know that Views is a great tool to build custom admin pages, especially when combined with Views Bulk Operations.
Comment: Imagine you have 200 pages, all bound to a taxonomy tree. What I want is to be able to view those pages in hierarchical style: by expanding/collapsing the parent nodes - just as much as hierarchical is the taxonomy tree. Is that more illustrative? :)


Remover a ação do botão físico do OptionsMenu

Question: Temos uma aplicação em que estamos removendo a ação  do OptionsMenu do botão físico e inserindo na Toolbar.
Gostaria de saber se é possível anular a ação do botão físico do Menu?
Gostaria que o Menu fosse exibido apenas na Toolbar e não mais no botão físico.
Answer: Consegui solucionar meu problema sobreescrevendo o seguinte método: onMenuOpened :
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    return false;

}

Este método é invocado apenas quando clico no botão físico!


How do I free 2D array allocated with malloc?

Question: How do I free this array? Is this enough? Would it be enough to write only free(arr)? Do I need to free **arr? If yes, how can I do that?
Thanks in advance!
#include <stdio.h>
#include<stdlib.h>
#define N 5
int main(void)
{
    int **arr = malloc(N*sizeof(int*));

    for(int i=0;i<N;i++)
    {
        arr[i] = malloc(N*sizeof(int));
    }
    for(int i=0;i<N;i++)
        free(arr[i]);
    free(**arr);

    return 0;
}

Comment: You don't need to free the array in this case because the allocations are not repeated and the OS will free the memory after the execution ends. For more information, see [c - What REALLY happens when you don't free after malloc? - Stack Overflow](https://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc)
Comment: If you have to free memory (long-running process that might conceivably starve), then the rule is "Free whatever you malloc".
Comment: Does this answer your question? [How to free 2d array in C?](https://stackoverflow.com/questions/5666214/how-to-free-2d-array-in-c)
Answer: You don't need to free **arr because **arr is an int.
Instead of that, you should free the allocated pointer arr.
The line
    free(**arr);

should be
    free(arr);

Comment: thank you so much!! and what about the loop arr[i]? i need to run it or just write free(arr)?
Comment: @danielevanenko The loop is required if you want to manually free everything you allocated. Practically no `free()` here are required because the memory used will be freed by the OS after exiting of the process.
Answer: **arr in this case is equivalent to arr[0][0], which is actually an integer, and free function expects a pointer to memory. So free(**arr) would be "freeing" an integer pretending to be a pointer in memory, and that would cause your program to crash.
What you need to do is free a pointer to array of 5 pointers, and this pointer is simply arr. So you need to free(arr).
Answer: if you want to declare two-dimensional array instead of the array of pointers (and I think that is your idea)
int foo(size_t x, size_t y)
{
    int (*arr)[x][y];

    arr = malloc(sizeof(*arr));

    (*arr)[4][2] = 5;

    free(arr);

}

You can index it as any other array and you need only one free


Disabling Recursion in DNS on Windows 2008 R2 Server Core

Question: I have a W2K8R2 Server Core install with the DNS role. I want to disable recursion on this server as it exists only to respond to DNS requests for which it is authoritative.
I have run the "dnscmd /config /norecursion 1" command and dnscmd /info shows fNoRecursion with a value of 1, that is, do not do recursion. My forwarders list is also empty, although I don't think that even matters if I'm not doing recursion. I have cleared the cache and stopped and restarted the DNS service.
However, if I connect to this server from a remote machine the server is doing recursive lookups for me. I can connect to it and ask it to resolve www.cnn.com and it will do so. Any ideas?
Answer: Have you tried deleting root hints?
Comment: Sadly this strikes me as wrong as effectively the server is trying to do lookups but is unable since it has no root hints, vs. not trying to do them in the first place. But the net effect is the same.
Comment: Create a . zone then.
Comment: That did it. I even tried setting IsSlave first and it still did resolution. It wasn't until I deleted the root hints file (%systemroot%\system32\dns\cache.dns) that it no longer did resolution.


django get_queryset() with conditional filter()

Question: I have a custom model manager on model such as:
class MyCustomManager(models.Manager):
   def doFoo(self, user, s_format):
        qs =  super().get_queryset().filter(created_by=user)
        return qs

which is returning data based on the user passed as the argument. However, how would I go about adding more AND conditions to the above query based on if conditions? Something like this:
class MyCustomManager(models.Manager):
       def doFoo(self, user, s_format):
            qs =  super().get_queryset().filter(created_by=user)
            if <condition 1>:
                qs.filter(mode='A')
            elif <condition 2>:
                qs.filter(mode='B')
            return qs

If I do the above, even if <condition 2> is true, it's not generating created_by=1 AND mode='B' SQL
I'm basically trying to do the equivalent of the following but split by conditions
qs =  super().get_queryset().filter(created_by=user, mode='A')

Answer: You need to reassign qs in your conditions
class MyCustomManager(models.Manager):
       def doFoo(self, user, s_format):
            qs =  super().get_queryset().filter(created_by=user)
            if <condition 1>:
                qs = qs.filter(mode='A')
            elif <condition 2>:
                qs = qs.filter(mode='B')
            return qs

Answer: .filter(…) [Django-doc] returns a new queryset, it does not alter qs itself, you thus should assign the result to qs again, or in this case return the queryset constructed by .filter(…):
class MyCustomManager(models.Manager):
    def doFoo(self, user, s_format):
        qs = super().get_queryset().filter(created_by=user)
        if <condition 1>:
            return qs.filter(mode='A')
        elif <condition 2>:
            return qs.filter(mode='B')
        return qs


Automate configuration change on Outlook 2007

Question: I am migrating a bunch of mailboxes to google apps. Each user owns several mailboxes each serving different domains (john has email@example.com, firstname.lastname@example.com, and so on...)
Currently, those accounts are hosted on (edit:NOT an exchange server) an old SMTP/POP server we want to replace, and I need to edit their outlook 2007 configuration to change the pop, smtp and password parameters.
The hard way to do it is to connect to each outlook session and edit the parameters manually. I want to avoid that. Because that represents over 700 accounts spread between 40 users... :'(
How can I automate this configuration change ? In the active directory ? Using a PRF file ?
note: I'm a linux sysadmin with very little knowledge of windows's black magic.
Comment: I have to agree with Massimo - things like this that sound small can end up being a surprising amount of work. Testing and automating this is something that should have been solved before agreeing to make the switch. Having said that, it might be worth speaking to google and checking their support forums as I doubt you're the first customer to need this kind of help.
Answer: If your users are using Outlook as an Exchange client, which really is how they should be using it if they have an Exchange server, then moving to POP3/SMTP requires a complete reconfiguration of Outlook; they will also be in for some really nasty surprise if they are used to sharing calendars and do some of the other many things that Exchange supports.
Anyway, I'm not here to question your choices... but moving Outlook from being an Exchange client to plain POP3/SMTP automatically for all your users is definitely not trivial. Something can probably be achieved using .PRF files, but this is neither trivial, too.
Comment: it's probably more work trying to script the prf changes (on a per user basis, per account basis) than it is to do manually.  Pity they couldn't have gone to a hosted exchange.
Comment: Saying it's non trivial is definitely not an answer.... I'm not touching the main exchange account, only the additional onces that don't have shared calendar and such. There will be no side effect, this is already taken care of. Anyway, I already know it's non trivial (I did my research before posting to serverfault), but I'm still looking fr a way to automate it. How can I generate a prf or a reg key for each user that avoid having to change the parameters manually ?
Comment: So what do you exactly want to accomplish? Add a POP3/SMTP account? Modify an existing one? Create a new Outlook profile? You should provide more details.
Comment: "Currently, those accounts are hosted on the local exchange 2003 small business server, and I need to edit their outlook 2007 configuration to change the pop, smtp and password parameters." In other words: I just need to edit the settings in the "accounts" section of outlook.
Comment: Yes, but how many accounts do your users already have? What is the standard configuration for a user? An Exchange account + 1 (2,3...) PO3/SMTP ones? Do they use a single default profile or more than one?
Answer: You are asking too much from Outlook.  No there isn't an easy way of doing that.  Not to mention even if you could easily modify the Outlook config file to point to another server, (POP3 and Exchange both act completely different in regards to Outlook.  Cached Exchange mode doesn't use a PST all of the time, sometimes it is an OST instead, and POP3 always uses PST.)
Let's just say that you could do it, wouldn't you have to edit each user's config file, not saving you from having to touch each machine.
From a 10,000 foot view, I'm going to say you are making a mistake. All of your user's mailboxes are stored on one nice neat little box that can easily be backed up.  Once you migrate all of them over to google, you depend on each user to back up their own mail contacts etc.
Comment: Actually, there is an error in my initial question. I thought the accounts where stored in exchange, but there are just basic smtp/pop accounts stored in a third party server we want to get rid of. So it's just a configuration change of pop server, smtp server, password. If modification is impossible, is there a way to automate the creation of new accounts ?


fibre channel debian problem

Question: I have a QLogic Fibre Channel card installed in a Debian box (Lenny), and after some tiffs with the firmware, I managed to get the operating system to recognize the card (DKMS driver, and the "firmware-qlogic" package for firmware).
However, for some reason, no block devices are being created for the two SAN volumes being exposed to the unit.  They show up when I 'cat /proc/scsi/scsi' but there's no /dev/sdX block device that I can see and further, I have to run the rescan-scsi-bus.sh shell script every time I need to get the /dev/sgX devices back.
How can I get the system to recognize those fibre-channel volumes persistently?
EDIT: Found out that the dual devices being seen are part of the Multipath I/O system we use with our SAN array.  Does multipath i/o need to be set up prior to the volumes being recognized as block devices?
Answer: Make sure that the devices you see are actually the exposed LUNs and not just the storage subsystem controllers.
Try reading from the sgX device directly. If you're reading from a real disk, you'll see:
# sg_read if=/dev/sg0 bs=512 count=1M mmap=1 time=2
time from second (SCSI) command to end was 3.851212 secs, 139.39 MB/sec
1048576+0 records in, SCSI commands issued: 8192

But a read from an access LUN ought to fail:
# sg_read if=/dev/sg4 bs=512 count=1M mmap=1 time=2
reading: SCSI status: Check Condition
 Fixed format, current;  Sense key: Illegal Request
 Additional sense: Logical block address out of range
  Field replaceable unit code: 5
plus...: Driver_status=0x08 [DRIVER_SENSE, SUGGEST_OK]
sg_read: failed, skip=0
Some error occurred,  remaining block count=1048576
0+0 records in

Can we see the output of lsscsi -g?
If we only see the controllers, I expect something like:
[0:0:0:31]   disk    IBM      Universal Xport  0916  -
[1:0:0:31]   disk    IBM      Universal Xport  0916  -

But if the disks are there as well, you should see something like:
[0:0:0:0]    disk    IBM      1814      FAStT  0916  /dev/sda
[0:0:0:1]    disk    IBM      1814      FAStT  0916  /dev/sdb
[0:0:0:2]    disk    IBM      1814      FAStT  0916  /dev/sdd
[0:0:0:31]   disk    IBM      Universal Xport  0916  -
[1:0:0:0]    disk    IBM      1814      FAStT  0916  /dev/sdc
[1:0:0:1]    disk    IBM      1814      FAStT  0916  /dev/sde
[1:0:0:2]    disk    IBM      1814      FAStT  0916  /dev/sdf
[1:0:0:31]   disk    IBM      Universal Xport  0916  -

You don't need multipath setup before you can see the block devices, but you should set it up before you use them.
Once multipath is setup, you should see something like:
3600a0b8000266f7e000026314950d851 dm-0 IBM,1814      FAStT
[size=100G][features=1 queue_if_no_path][hwhandler=1 rdac]
\_ round-robin 0 [prio=6][active]
 \_ 1:0:0:2 sdf 8:80  [active][ready]
\_ round-robin 0 [prio=1][enabled]
 \_ 0:0:0:2 sdd 8:48  [active][ghost]

Comment: Wow, thanks man for the rocking answer.  I see the storage controllers but not any storage units themselves.  Any idea why I'm not seeing any LUNs if they're configured properly on the controller?
Comment: Uhhh.... they're not configured properly? :) I'd double-check that you have the controller exposing the LUNs to the right WWPNs.
Comment: Wow, big time moron moment on my part.  The LUNs weren't exposed properly. Once that was fixed, everything started working like a charm. Thanks for your help man.

fibre channel debian problem


JACK JackRouter (and then?)

Question: I'm using Jack 1.9.10.  I want to record system sound into Ableton, and don't want to plug a cable from line out to line in.
I start PortAudio, I turn on JACK Audio Connection Kit, it is already started.
(It's all set up for portaudio default default default.)

Ok, but now what?
In Ableton, I don't see any sound coming in via the 1/2 channels,
From the Docs:

"You can route the output of ASIO applications into the inputs of
  other ASIO applications (like a VST host application), and then
  connect the audio output of that application to your system output (or
  a combination of both)."

Ok, so system's capture_1, capture_2 is going into Ableton's 1 and 2, but I kind of want system's playback_1 and playback_2 to go into Ableton's 1 and 2?
That's not happening.
Ok I'm stuck.  Anyone got to this point and worked out the final step?
Answer: I run the following command in the execute script after startup part of QJackCtl
<code>pacmd load-module module-jack-source channels=2; pacmd load-module module-jack-sink channels=2;
pacmd set-default-sink "jack_out" && pacmd set-default-source "jack_in"
</code>

what it does is set up a jack source and sink and route your system audio through these
I end up with this

JACK JackRouter (and then?)


ASP.NET, PHP, SQL Server, MySQL hosting provider for developer?

Question: I am looking to find a web hosting provider that provides ASP.NET and PHP hosting. The purpose is pretty much just a programming playground for me to develop in and possible show some of my work.
As I use ASP.NET and PHP I am looking for a provider that provides hosting for both of these technologies as well as access to MS SQL Server and MySQL.
Of course I am on a budget so I really can't afford to pay more than $20/month. I had looked at M6.net however in scanning for reviews I found a good deal of negative feedback. I currently use DownTownHost.com and have a good experience with them, however they do not support ASP.NET.
I do not require email hosting though I know most packages include it anyway. Thanks for any suggestions.
Some features that are important to me:
<code>* ASP.NET 4 hosting
* ASP.NET MVC support
* PHP
* MySQL
* SQL Server
* URL Rewrite support
* multiple sites under one account
</code>
Comment: Shopping Questions are Off-Topic on any of the [se] sites. See [Q&A is hard, lets go Shopping](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping) and the [FAQ] for more details.
Answer: Take a look at 1and1.com
Answer: I'd recommend a VPS if you want to just play. A VPS is a virtual server that you can configure to any needs you want and when you want to play with something else just wipe it and install another distribution. I use linode (referral link) and recommend them. Linode also has great documentation for managing and setting up your VPS here.
Answer: I would just setup a VM on your PC which has the software that you need, or even on your main PC.


grep: matching on literal "+"

Question: I need to find occurrences of "(+)" in my sql scripts, (i.e., Oracle outer join expressions). Realizing that "+", "(", and ")" are all special regex characters, I tried:

grep "\(\+\)" *

Now this does return occurrences of "(+)", but other lines as well. (Seemingly anything with open and close parens on the same line.) Recalling that parens are only special for extended grep, I tried:

grep "(\+)" *
grep "(\\+)" *

Both of these returned only lines that contain "()". So assuming that "+" can't be escaped, I tried an old trick:

grep "([+])" *

That works. I cross-checked the result with a non-regex tool.
Question: Can someone explain what exactly is going on with the "+" character? Is there a less kludgy way to match on "(+)"?
(I am using the cygwin grep command.)
EDIT: Thanks for the solutions. -- And now I see that, per the GNU grep manual that Bruno referenced, "\+" when used in a basic expression gives "+" its extended meaning, and therefore matches one-or-more "("s followed by a ")". And in my files that's always "()".
Answer: GNU grep (which is included in Cygwin) supports two syntaxes for regular expressions: basic and extended. grep uses basic regular expressions and egrep or grep -E uses extended regular expressions. The basic difference, from the grep manual, is the following:

In basic regular expressions the metacharacters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

Since you want the ordinary meaning of the characters ( + ), either of the following two forms should work for your purpose:
grep "(+)" *       # Basic
egrep "\(\+\)" *   # Extended

Comment: I just discovered that your second example works, not the first. Hmm. Is cygwin grep busted??
Comment: What is the output of grep --version? For me, it works for "grep (GNU grep) 2.5.1".
Comment: Hmm, same here: grep (GNU grep) 2.5.1
Comment: And the following does not work? echo -e "(+)\n()\n+" | grep "(+)"
Comment: Ah, that is working! (I didn't realize you dropped the \ in front of +) So duh, "+" is also an extended regex. I was stubbornly thinking is was a basic. THANKS.
Answer: You probably need to add some backslashes because the shell is swallowing them.
ETA: Actually, I just tried on my Cygwin and grep "(+)" seems to work just fine for what you want.
Comment: I just tried grep -E "\(\+\)" *, and that works. So it's does not seem to be a shell issue. Could cygwin non-extended regex be broken??
Comment: Too bad only one answer can be accepted. Bruno walked me through it, but you were correct as well. I had forgotten that "+" is also only special for extended regex.
Comment: No, those characters should be fine inside a double-quoted string.

grep: matching on literal "+"


Out of memory exception when using Geospatial queries in Spring Data ArangoDB

Question: i'm using spring-boot 2.0.0 and arangodb-spring-data 2.0.3, i was following geospatial queries tutorial in here with my own data structure.
@Data
@NoArgsConstructor
@Document(value = "hospital")
public class Hospital {
    @Id
    private String id;
    private String name;
    private String phone;
    private String address;
    @GeoIndexed
    private double[] location;

    public Hospital(String name, String phone, String address, double[] location) {
        super();
        this.name = name;
        this.phone = phone;
        this.address = address;
        this.location = location;
    }
}

@Repository
public interface HospitalRepository extends ArangoRepository<Hospital> {
    GeoResults<Hospital> findByLocationWithin(Point location, Distance distance);
}

@Test
public void geoSpatialTest() throws IOException {
    populateDb();
    Point point = new Point(-7.2895286, 112.7731704);
    Distance distance = new Distance(2, Metrics.KILOMETERS);
    GeoResults<Hospital> results = repository.findByLocationWithin(point, distance);
    results.getContent().forEach(System.out::println);
}

it'll throw out of memory exception only if i call findByLocationWithin() method.
com.arangodb.ArangoDBException: Response: 500, Error: 3 - AQL: out of memory (exception location: /var/lib/otherjenkins/workspace/RELEASE__BuildPackages/arangod/MMFiles/MMFilesGeoIndex.cpp:151) (while executing) (exception location: /var/lib/otherjenkins/workspace/RELEASE__BuildPackages/arangod/RestHandler/RestCursorHandler.cpp:135)

what i want to do is to get nearby hospital with distance less than X Km. I can achieve this by using this query in ArangoDB.
FOR hospital IN WITHIN(hospital, -7.2895286, 112.7731704, 2000)
RETURN hospital

Is arangodb-spring-data somehow broken? Do i need to make custom @Query for this?
Comment: Please provide the exact version of ArangoDB and storage engine in use.
Answer: You have to switch the values for Point to do the same in your Java application as in your AQL query.
Point point = new Point(112.7731704, -7.2895286);

ArangoDB Spring data assumes that the first parameter of Point is longitude and the second latitude.
The Error AQL: out of memory occurs because of a check within the ArangoDB geo-index which checks that longitude is between -180 and 180 and latitude is between -90 and 90. The error message is very misleading but there is already a PR on github to fix this.
Comment: this solved my problem :D but it is a bit confusing since i need to use
`double[] location = {latitude, longitude}`
to store the data, and use
`new Point(longitude, latitude)`
for geospatial query.


Create custom form and store form data into database

Question: I am start working with Drupal just some days ago. I am really a amateur in Drupal . I just want to know how can I create a form in Drupal with textbox or check-boxes and store the value of the form in the database.
Like a registration form script in PHP.
Comment: The easiest would be to create a new node-type with fields matching the data you want to capture. Drupal will generate the form and deal with the DB.
Comment: Can you explain in brief.That may be help ful for me.Because I am really amateur in Drupal.Thanks for your reply.
Comment: Check https://www.drupal.org/documentation/modules/field-ui
Comment: See Webform module and https://www.drupal.org/project/examples for two ways about this.
Answer: Creating the module structure
The first step in creating the module is to create a folder for the module. You should put this in "sites/all/modules/{name of your module}." Keep in mind that whenever I say "{name of your module}," you should insert the name of your module. For example, we will use the module directory "sites/all/modules/form_example."
Now, create two empty text files called "{name of your module}.module" and "{name of your module}.info."
These two files are required by your module. The .info file contains information about what your module does, while the .module file contains the actual code including hooks. Hooks are functions with special names that will be called by Drupal when actions occur. For example "form_example_menu()" is called when menu information is gathered. In many examples, you will see names such as "hook_menu()" or "my_theme_menu()" and in these cases "my_theme" and "hook" should be replaced by the name of your module or theme.
Build the basic module files
Here is what we will put into the form_example.info file. This tells Drupal and users about your module.
core = "7.x"
description = "An example module used to learn module development and forms creation."
name = "Form Example Module"

There are more options that you can put in the .info file, but the ones above should be added.
Here is the start of our form_example.module file. This will create a very basic form that only has one field, a submit button.
<?php
function form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
?>

Note: Do not include the last "?>" part of the PHP code and leave a trailing blank line at the end of the file. This is the Drupal standard.
The module right now contains one function that will create a form. It is important to note that the function takes the inputs $form, and a reference &$form_state. This function will be called when Drupal tries to build the form "form_example_form."
The process for creating a form is mainly two steps. The first is to build an associative array $form that contains all the fields. The second step is to return that $form variable.
To add a field, you set the variable $form[{name of your field}] = array(); Each field can then have a number of attributes, such as "#type" and "#value." Most of these attributes are named with a proceeding "#" sign.
The field we added above is a submit button with the text "Click Here!" on the button. Note that t() will output text and is a Drupal function that plays nice with translation.
Now that we have a form, we need to add two more function: form_example_form_validate, and form_example_form_submit. These two functions are hook functions that will be called when Drupal validates the form and when it submits the form (assuming it validated).
form_example.module:
<?php
function form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

You will note that these three functions take the same variables. $form is the original form information and can be seen as the original structure of the form. $form_state holds all of the submitted values as well as other information, some of which you can add yourself. These two functions need to named similar to the other form, but with "validate" and "submit" at the end.
We want to see the form!!! We will add a menu link to this form.
form.example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

Now enable your module and try to access the link. You will probably need to clear the cache.
Add more functionality to the form.
Now we will add one more field to the form.
form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    ),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
}
function

form_example_form_submit($form, &$form_state) {
}
?>

Here we have added a new textfield and made it required. We have also set the maximum length. You'll see if you try to submit the form, that Drupal will automatically produce an error for the user if they don't fill in the required fields. We will add some more validation in the next step.
Add validation
form_example.module

<?php
function form_example_menu() {
  $items = array();

$items['examples/form-example'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Example Form', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('form_example_form'), //put the name of the form here
    'access callback' => TRUE
  );
  return

$items;
}
function

form_example_form($form, &$form_state) {

 $form['price'] = array(
    '#type' => 'textfield', //you can find a list of available types in the form api
    '#title' => 'What is Your Price?',
    '#size' => 10,
    '#maxlength' => 10,
    '#required' => TRUE, //make this field required
  );

$form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),
    ),
  );

  return $form;
}
function

form_example_form_validate($form, &$form_state) {
  if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }
}
function

form_example_form_submit($form, &$form_state) {
}
?>

You will now see that the form will not submit unless price is a positive number. We do this by checking the value of price, in $form_state['values'][{name of your field}]. There are similar variables for all of your fields.
We then set an error with form_set_error. Adding this error will alert Drupal that the form did not pass validation.
What to do when your form is submitted?
From this point, you will want to either save the form data, send an email, or display some information. That is beyond the scope of this How To at this point.
I have built some module "tools" or "calculators" using the above method and included the calculation steps in the submit function. You can set the variable "$form_state['rebuild'] = TRUE;" in the submit function so that Drupal does not clear the form. You can therefore edit the $form_state to change a "markup" field type to have your output.
This can also be done with AJAX so that the form displays the calculated values without a page load. That gets a little more complicated and may be added as a separate How To.
Conclusions
Hopefully this is helpful for people interested in writing a module, or adding a form to a module.
Reference: How to Make a Simple Module with a Form and Menu Link
Comment: I created the module successfully.It is showing on the specific path link I given in function.But can you tell me how can I add the module to a specific block in my pages?
Comment: adding a module to specific block, this doesn't happen it think.
Comment: While it's very nice of you to spend this much time writing up an answer to the question, I have to ask, is this _helpful_? You're suggesting that he does everything from scratch, and I don't think there's any need. Why not just create a content type? That would provide nice integration with blocks, views, the menu system, access and everything else. But with this approach, @SubhajyotiDe has to do _everything_ on his own. I can't help but feel he's being tricked into doing a great deal of work for no particular reason. I really hope I'm wrong.
Comment: yes this can be done easily by creating a content type, blocks, views, the menu system, access etc with existing features of drupal. But doing custom'ly not wrong, but its alternate way, might be learning..!
Comment: Old post, but I'll add that this is useful for me. I am creating a configuration screen for a module, and the data is not a good fit for a content type and all of that. I created a custom table, and this post helped me get my data into and out of it. There are lots of use cases, and if these facilities exist in Drupal you can assume they're there for a reason.


Evaluating $\lim_{x\to - \infty} \sum_{k=1}^{1000} \frac{x^k}{k! }$

Question: $$\lim_{x\to - \infty} \sum_{k=1}^{1000} \frac{x^k}{k! }$$ is
A)$-\infty$
B) $\infty$
C)$0$
D)$1/e$
I tried $\sum_{k=1}^{1000} \frac{x^k}{k! } \lt e^x$ Taking limit i got the answer to be less than zero. However the answer given is B. Any ideas. Thanks.
Comment: Check your inequality again. It doesn't hold for every value of $x$. You just have a polynomial.
Answer: It's an even-degree polynomial. The largest power of $x$ eventually dominates, and $x^{1000} \to +\infty$ as $x \to \pm \infty$.
Comment: Let $P(x) = x^n + \sum_{k=0}^{n-1} a_kx^k$ be a polynomial. Let $x>A=\max\{1,\max_{k} |a_k|\}$. Then $$ \frac{P(x)}{x^n} = 1 + \sum_{k=0}^{n-1} \frac{a_k}{x^{n-k}}.  $$ Since every power in the sum is negative, it can be made as close to zero as we like by taking $|x|$ large enough. Hence it can be made less in modulus than $1/2$, say, so we have the bound $|P(x)-x^n| < \frac{1}{2}|x|^n$. This means that $P(x)$ and $x^n$ have the same sign for $|x|$ sufficiently large, and also $|P(x)| > \frac{1}{2}|x|^n$, so $|P(x)|$ diverges. Hence it diverges in the same direction as $x^n$.
Comment: Thanks for your answer. But $x^{999}$ tends to $-\infty$ as $x$ tends to $-\infty$. In other words we cannot subtract or add infinity. Can you please explain why other powers of $x$ donot dominate the sum. Thanks.
Comment: or considering the limit of the last two terms:
$\lim_\limits{x\to+\infty} \left(\frac{x^{1000}}{1000!}-\frac{x^{999}}{999!}\right)=\lim_\limits{x\to+\infty} \frac{x^{999}}{1000!}\left(x-1000\right)=+\infty,$ since $x>1000.$


display checkmark on UITextField righthand side

Question: I am trying to display checkmark on UITextField righthandside on tapGesture.
Could you please help me to achieve this.
Comment: possible duplicate of [UITextField Validation visual feedback](http://stackoverflow.com/questions/1906799/uitextfield-validation-visual-feedback)
Comment: Thanks, By this i am able to achieve.
Comment: I have a UITextField also for customCell for UITableView. On TapGesture of UITextField, I need to display checkmark on right side of UITableViewCell. I am able to achieve this, when I am setting textfield property enabled=NO. But I have to keep enable property ON.
Comment: You must include what you've tried in your question body. http://stackoverflow.com/help/how-to-ask
Answer: Check below link for what you exactly looking for
http://dhawaldawar.wordpress.com/2014/06/11/uitextfield-validation-ios/
I have created inherited class of UITextField for validating input effectively, you just need to give regex string in sequence for validation on a particular field and other things like show error on right side and showing popup with a message that we provided at the time of assigning regex will handle by class itself.
I'm damm sure it will save your lot of work...


concatenation of two unicode srings?

Question: #!/usr/bin/python
# -*- coding: utf-8 -*-

import re
separators = [u"।", u",", u"."]
dat=open(r"C:\Users\User\Desktop\text4.txt",'r').read()
text=dat.decode("utf-8")
wros=text.split()
out=""
import string
space=" "
counter=0;
for word in wros:
        out=u" ".join(word)

writ=open("C:\\Users\\User\\Desktop\\text5.txt",'w')
writ.write(out.encode('utf-8'))
writ.close()

text4.txt contains भारत का इतिहास काफी समृद्ध एवं विस्तृत है।
text5.txt outputs as ह ै ।
desired output is भारत का इतिहास काफी समृद्ध एवं विस्तृत है।
please tell me what i am doing is wrong ? HElp required ! thanks in advance
Comment: every time you assign `out = u" ".join(word)` you're losing the previous value assigned to `out`. You might want to use a list and `append` instead (but it's not clear what exactly you're trying to do since the `join` statement in your case adds a space between each character of each word which is not your desired output).
Comment: Your problem is in the for loop... you keep discarding the string in `out` each time it loops. The loop also adds spaces between each character of the words. It looks like you want output that is the same as input... can you tell us what the conversion should do.
Comment: you don't need `for` - you need only `out = u" ".join(wros)`
Comment: @tdelaney i need the for loop to edit few words . so as to get different result .
Comment: if you need `for` loop then show it in code. Now you don't need this `for`
Comment: @furas i need the for loop in order to iter between different words of wros
Comment: @furas what part of code? for loop is in the code.
Comment: I would create list `out = []` and in for-loop I would append words to the list `out.append(word)` and afters for-loop I would concatenate list into one string `result = u" ".join(out)`
Comment: In `for-loop` you have only `out=u" ".join(word)` which you can do without `for-loop`. So show what else you do in `for-loop` - why do you need this for-loop`.
Comment: @sirfz if i used a list and then used     list.append(word) i cannot encode it again. can i?
Comment: In your example, the input and output strings are identical. From the example, you shouldn't have done anything at all. I could post an answer adding spaces between all letters in the words (that appears to be what you code is trying to do), but that wouldn't match your desired output.
Comment: You could join the list and encode that `u" ".join(wros).encode('utf-8')`.
Comment: As an aside, considering moving to python 3.x if you can. Its unicode support works better.
Comment: @furas let it be anything what i do in for loop... but at the end i need to concat after operating on each word i need to add space between previous sets of word and then new word.
Comment: @tdelaney i am encoding it after when i am writing back to the file as
Comment: writ.write(out.encode('utf-8'))
Comment: @tdelaney there is word i  am looping with not in wros
Answer: I don't know what you have to do with word but I would do it this way:
text = open('text4.txt').read()

text = text.decode("utf-8")

# split one string into list of (old) words
words = text.split()

# list for new words
out = []

# modify words
for word in words:
    # here - do something with `word`
    out.append(word)

# concatenate all new words to one string
result = u' '.join(out)

result = result.encode('utf-8')

writ = open('text5.txt', 'w')
writ.write(result)
writ.close()

Comment: thanks man so much thanks .. i was confused where to put that result = u' '.join(out)
Answer: Here's a template:
# no need for coding:utf8 unless *source code* has non-ASCII.

import io # Contains modern version of open compatible with Python 3.

# Use with and file is automatically closed when block is exited.
with io.open(r'c:\users\user\desktop\text4.txt',encoding='utf8') as dat:
    text = dat.read()

words = text.split()

#edit words

text = u' '.join(words)

with io.open(r'c:\users\user\desktop\text5.txt','w',encoding='utf8') as writ:
    writ.write(text)

concatenation of two unicode srings?


If $X$ is locally compact Hausdorff, then $X$ is regular.

Question: The following are from Munkres' book on topology:

Theorem 29.2. Let $X$ be a Hausdorff space. Then $X$ is locally compact if and only if given $x$ in $X$, and given a neighborhood $U$ of $x$, there is a neighborhood $V$ of $x$ such that $\overline{V}$ is compact and $\overline{V} \subseteq U$.
Lemma 31.1 a. Let $X$ be a topological space. Let one-point sets in $X$ be closed. $X$ is regular if and only if given a point $x$ of $X$ and a neighborhood $U$ of x, there is a neighborhood $V$ of $x$ such that $\overline{V}\subseteq U$.

Doesn't the $(\implies)$ part of theorem 29.2 and the $(\impliedby)$ part of lemma 31.1 a together prove that locally compact Hausdorff spaces are regular? I'm a little bit suspicious because this seems an easy solution, I might be missing something.
Comment: Why do I need to show that compact Hausdorff spaces are regular?
Comment: You're right: I didn't read carefully enough and was using a slightly different characterization of local compactness. It's fine as is.
Answer: In fact, X is completely regular: Let X be locally compact Hausdorff. Then, there exists a compact Hausdorff space Y containing X as a subspace. Now since Y is normal, Y is completely regular, which implies that X is completely regular, because it is a subspace of a completely regular space.


Optimal permutation for differential storage

Question: This is a practical problem I encountered recently. I'm convinced that it has been solved before, however I don't know where to start looking as I'm unfamiliar with all the terminology involved. Hope someone can point me in the right direction :)
Suppose you have n files of various sizes. You can use a computer program to obtain a diff-file, which contains the difference between two files. Depending on the similarity of file oA and oB, this diff dAB could be very small. The size of a diff is not affected by file order; dAB is the same size as dBA. However, the diffs are monodirectional: To reconstruct oA you would need oB and dBA, as dAB would be of no use.
You want to find the optimal permutation of diffs, such that by starting from just one of the original files, you can recreate all the other files. The size of all possible diff files are already known. For example, given files oA, oB, oC, oD and oE, the optimal permutation could be dAB, dAC, dBD, dCE.
Comment: A [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) should do the trick.
Answer: You can approach this as a minimal spanning tree problem. Create a complete graph with the vertices corresponding to your files. Label each edge with the size of the diff file between the two files; as you point out these diffs are the same regardless of direction. You can then use Kruskal's algorithm to find a minimal weight spanning tree.
To actually pick which files you want to keep, start with the smallest file you have, say A. For each of A's edges in the minimal weight spanning tree, pick the diff file which transitions A to the file corresponding to the next vertex. Then from each of these vertices, take each diff file moving outward.
So for your example, your spanning tree would look like:
A -- B -- D
|
C -- E


What is the best setup for high gain and low noise for my amp and effects?

Question: I have a JVM 410H - Using mainly the OD1 channel with Gain at 3 0'clock.
I have two noise gates, an ISP Decimator and a Boss NS-2.
I have these pedals:

ISP Decimator
Boss NS-2
Boss Chorus
Phaser
Delay
Compressor Sustainer

What would be the best setup to avoid noise?
Comment: You asked this question previously - "[Cannot get rid of pedal / amp noise (Hiss)](http://music.stackexchange.com/q/12157/821)".
Comment: My question was mainly targeted at the best order in which to put my pedals, both at the amp front and the effects loop.
Answer: Well, the general advice to avoid noise is to use as few pedals as possible, as each one raises the noise floor.
A noise gate will act as a gain reducer until you send a signal over its threshold, so having a noise gate first is a good idea. (It does affect sustain and various other factors, but they are outside the scope of the question)
The rest of your setup is usually determined by how you want your guitar to sound. Putting a compressor early sounds very different to putting it late in the chain.
For certain high gain distorted sounds, I find on stage I commonly start with a compressor, then distortion, modulation effects then delay - but if I get uncontrollable feedback due to strange acoustics, I may add a noise gate in front of the compressor (odd, but sometimes it is a quick and dirty fix)
If you are wanting to use all those pedals, you should also start looking at signal switchers. I'm guessing you won't run a phaser and a chorus together, so a signal switcher lets you avoid running your signal path through an effect which isn't being used (as you still get noise from an inactive effect)
Also, the decision on whether you run effects pre-amp or on the FX send is not generally done for noise reduction reasons- it gives an entirely different sound, so usually you choose what sound you want.
Comment: My question was mainly targeted at the best order in which to put my pedals, both at the amp front and the effects loop
Answer: Noise comes from a lot of places, not just your effects. The best idea is to think your guitar, cables, effects and amplifier are a chain, and remember that a chain is only as strong as its weakest link.

The guitar's wiring can pick up hum from all sorts of electrical equipment, especially if it's an older guitar with single-coil pickups. A good repairman can put foil or conducting paint inside the guitar's cavity to help reduce induced noise. Old/noisy single-coils can be replaced with variations on humbuckers that still sound like single-coils. You can use active pickups, or add a little buffer/boost inside the guitar to increase the signal being sent over the cable. This can reduce the effect of capacitance too, keeping your signal very clean and fidelity intact.
Cheap cables can pick up noise; You don't have to purchase the most expensive cables out there, but don't buy cheap ones either. I've used George L's cables for years and find them to be very quiet. Their thinnest ones can pick up handling noise if you move them, at least the old ones I have will, but the thicker ones are very quiet. Use the minimum cable length necessary. A coiled cord isn't going to reduce noise; 20-feet of coiled cord is still 20-feet long, even when its not stretched out. I have good 20-foot cords but use 10-foot cords when possible.
9-volt battery-powered effects can add noise to your chain. Make sure your batteries are always at full-strength or use a high-quality power-supply.
Better quality effects will generally be quieter and cleaner than less expensive ones. I have pedals from over 20 years ago that, in a chain, were noisy. Adding a buffer and small preamp in front helped reduce the noise. The newer effects I have are all very clean; The manufacturers have learned a few things about reducing noise over the years, plus they can get cleaner-sounding chips for the pedals now.
Amplifiers can hiss and hum. They can pick up noise from nearby radio stations. (Yeah, the scene in Spinal Tap where the guitar amp picks up the control-tower can happen.) Run your input stage at the minimal setting needed to get the sound you want. The more amplification in the preamp stage, the more hiss you'll hear. Pump up the signal going into the amp to reduce that noise.

I'd run the compressor first in the chain. As the output drops as a string vibrates, the compressor will begin increasing the amplification to hold the volume. It can amplify any noise from the guitar, and introduce hiss all on its own.
Comment: My question was mainly targeted at the best order in which to put my pedals, both at the amp front and the effects loop
Comment: That may be. It's important to think of all the components in the setup as they all affect the noise. I have two compressors, from the same era, both are considered "classic" pedals, and both can add a lot of hiss. Turning up their gain is the problem. They're cheap little designs and good for simple use but not studio quality. If you are using massive amounts of gain or overdrive, which is gain too, you will get noise. A noise gate can only do so much before it starts getting in the way. I'd try a boost inside the guitar to push a hotter signal down the wire.
Answer: Time based pedals (chorus, delay, phaser etc.) are not supposed to make noise. Your problem probably comes from your sustainer, guitar, cable or amp. Using NS2 with Send and Return with compression sustainer may solve your problem. But if it's from the amp or guitar, you'll have to reduce the gain or change your equipment.
Answer: You don't need both the NS-2 and the Decimator, pick one. I like the NS-2 for high gain stuff. The ISP Decimator is not really a true gate so I might just ditch it. Your chain should be something like: NS-2 > compressor > chorus/phaser > delay. This is into the front of the amp. Loops are too finicky for my tastes, but you could go NS-2 to amp input, then phaser/chorus/delay in the loop.


Ansible: Chocolatey - remove_dependencies abandoned?

Question: I am using ansible to remove python on a windows VM (hence chocolatey) that I have.
I get this error when I set remove_dependencies to yes.
"changed": false, "msg": "Unsupported parameters for (win_chocolatey module: remove_dependencies. Supported parameters include: proxy_username, timeout, source, name, soure_password, ignore_dependencies, source_username, architecture, ignore_checksums, allow_multiple, validte_certs, proxy_password, allow_prerelease, skip_scripts, allow_empty_checksums, proxy_url, state, packge_params, pinned, force, install_args, execution_timeout, params"}

On ansible's website under their chocolatey documentation, remove_dependencies is still listed. I did not find anything about it being deprecated. (https://docs.ansible.com/ansible/latest/collections/chocolatey/chocolatey/win_chocolatey_module.html). Is there an update I may have missed? Can anyone fill me in on what is going on?
Answer: I found a solution to this problem. Not sure if it is the right one but it works. If you set force: yes then it forces the uninstall


How do I extract estimates and standard errors as a measure of linear increment from an lm model in R?

Question: Let's say I have data:*
data = data.frame(xdata = 1:10, ydata = 6:15)

I look at the data
data

  xdata ydata
1      1     6
2      2     7
3      3     8
4      4     9
5      5    10
6      6    11
7      7    12
8      8    13
9      9    14
10    10    15

Now I want to include a third column to the data which should be an increment/estimate and a fourth column we should be standard errors. To do this, I estimate the increment for each row of the data by fitting a linear model and taking the slope/estimate and also the associated standard error. So I fit model_1:
model_1 = lm(ydata~xdata,data = data)
out = summary(model_1)
out

It gives me:
Call:
lm(formula = ydata ~ xdata, data = data)

Residuals:
       Min         1Q     Median         3Q        Max
-5.661e-16 -1.157e-16  4.273e-17  2.153e-16  4.167e-16

Coefficients:
             Estimate Std. Error   t value Pr(>|t|)
(Intercept) 5.000e+00  2.458e-16 2.035e+16   <2e-16 ***
xdata       1.000e+00  3.961e-17 2.525e+16   <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.598e-16 on 8 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 6.374e+32 on 1 and 8 DF,  p-value: < 2.2e-16

To extract the estimate, I can simply do:
out$coefficients[2,1]

To extract the standard error, I can simply do:
out$coefficients[2,2]

but my interest is to have an output that shows estimates and standard errors for each row so that I end up with 10 estimates and 10 standard errors. Is there a way to do this?
Many thanks!
Answer: Basically, your lm model is of the formula y = Intercept + x*coefficient.
So, you can calculate the estimate based on the output of the summary(lm(...
So, if you take the following example:
set.seed(123)
vector1 = rnorm(100, mean = 4)
vector2 = rnorm(100, mean = 1)
dat = data.frame(vector1,vector2)
model_dat = lm(vector2 ~ vector1, data = dat)
Model = summary(model_dat)

And now, you can calculate the estimate:
dat$estimate = dat$vector1 * Model$coefficients[2,1] + Model$coefficients[1,1]

And then for the standard error, you can use predict.lm with the function se.fit = TRUE:
dat$SE = predict.lm(model_dat, se.fit = TRUE, level = 0.95)$se.fit

So, you get the following dataset:
> head(dat)
   vector1    vector2  estimate         SE
1 3.439524 0.28959344 0.9266060 0.11942447
2 3.769823 1.25688371 0.9092747 0.10294104
3 5.558708 0.75330812 0.8154090 0.18452625
4 4.070508 0.65245740 0.8934973 0.09709476
5 4.129288 0.04838143 0.8904130 0.09716038
6 5.715065 0.95497228 0.8072047 0.19893259

You can compare the result of this by first, checking the plotting obtained using stat_smooth:
library(ggplot2)
ggplot(dat, aes(x = vector1, y = vector2)) + geom_point() + stat_smooth(method = "lm", se = TRUE)

And you get this plot:

And if now, you use estimate and SE columns from your dat:
ggplot(dat, aes(x = vector1, y = vector2)) + geom_point() +
  geom_line(aes(x = vector1, y = estimate), color = "red")+
  geom_line(aes(x = vector1, y = estimate+SE)) +
  geom_line(aes(x = vector1, y = estimate-SE))

You get almost the same plot:

Hope that it answers your question
Comment: @JoeN another option might be `broom::augment(model_dat)`.
Comment: How come using comments to appreciate helpful response provided is prohibited here? How are you supposed to thank someone who took time to provide a response to your query?


Convert a String representation of byte[] back to an byte[]

Question: I have a String variable say string that I converted into byte[] and then I encoded the same using Base64 in as byte[] say encodedByteArr. Using the below code:
String string = "Test";
byte[] encodedByteArr= null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(check);
encodedByteArr= Base64.encodeBase64(bos.toByteArray());
oos.flush();
oos.close();
bos.close();
System.out.println("Encoded value is:- "+encodedByteArr);

Output is:

Encoded value is:- [B@5fd0d5ae

Now, I receive the same encoded value in another method as a String, which means:
String string = "[B@5fd0d5ae";

And it is nothing but a String representation of byte[] which I generated in above code.
Now my task is to actually decode the value and get back the original text back, that is "Test".
And for that, I want the String representation of byte[] back to a an byte[] without losing its integrity.
Comment: See https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array
Comment: You have actually solved your problem already (I think).  The problem is that you are printing the array the wrong way ... and the output makes you *think* you have done it incorrectly.
Comment: You'll never decode anything out of `[B@5fd0d5ae`. You'll need a more meaningful encoding than the default `toString()`.
Answer: All Java arrays print like that.  It's the way they work.  If you want to print the contents of the array, you have to use a static method from java.util.Arrays.
System.out.println("Encoded value is:- "+Arrays.toString(encodedByteArr));

It's kind of dumb, but that's the way it works.
Answer:
Now my task is to actually decode the value and get back the original text back

It sounds like you have a Base64-encoded string that you want to decode to yield the original string?
In Java 8, you can do
import java.util.Base64;
byte[] decoded = Base64.getDecoder().decode(string);
String original = new String(decoded);

A full "round trip" would look like:
String original = "Hello";
byte[] encodedBytes = Base64.getEncoder().encode(original.getBytes());
String encodedString = new String(encodedBytes);
System.out.println(encodedString);  // "SGVsbG8="

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println(decodedString);  // "Hello"

Answer: System.out.println("decoded raw byte: ");
for (byte singleByte:encodedByteArr) {
    System.out.print((char)singleByte);
}

Will return the string representation of byte to the output.
(not so efficient)


How do I automatically return a 404 when a GET path doesn't exist?

Question: I am using NodeJS, Express and Handlebars (template engine) to build a web application. Currently I'm trying to automatically redirect users whenever they enter an URL that does not exist (or whenever they might not have access to it).
The following returns the index page:
router.get('/', (req, res) => {
    res.render('index/index');
});

But how do I make something like this:
router.get('/:ThisCouldBeAnything', (req, res) => {
    res.render('errors/404');
});

The following example is from Github:
Say that I enter this URL:
https://github.com/thispagedoesnotexist
It automatically returns a 404. How do I implement this in my application?
Thanks in advance.
Answer: Use a middleware just after all route handlers to catch non existing routes:
app.get('/some/route', function (req, res) {
    ...
});

app.post('/some/other/route', function (req, res) {
    ...
});

...

// middleware to catch non-existing routes
app.use( function(req, res, next) {

    // you can do what ever you want here
    // for example rendering a page with '404 Not Found'
    res.status(404)
    res.render('error', { error: 'Not Found'});

});

Comment: another approach is to use `http-errors`, as described on [MDN](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website)
Comment: Thank you for the fast reply. I'll be using your middleware function!
Comment: I believe I can't do that yet because I'm new here.
Comment: I did, but It states:

Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
Comment: Just to add that you should put this also after the routes to properly work. Thanks.
Answer: After all your other routes you can add:
app.get('*', (req, res) => {
  res.render('errors/404');
});

Alternately, you can use a middleware function after all your other middleware and routes.
app.use((req, res) => {
  res.render('errors/404');
});

So you might end up with something that looks like:
//body-parser, cookie-parser, and other middleware etc up here

//routes
app.get('/route1', (req, res) => {
  res.render('route1');
});

app.get('/route2', (req, res) => {
  res.render('route2');
});

//404 handling as absolute last thing
//You can use middleware
app.use((req, res) => {
  res.render('errors/404');
});

//Or a catch-all route
app.get('*', (req, res) => {
  res.render('errors/404');
});

Comment: Sorry, YouneL. I wasn't trying to steal your answer. I must have been editing my post while you were writing yours.
Comment: Also, it looks like I posted my middleware suggestion edit a few minutes before you wrote your answer. But my more fleshed out example was posted after your answer.
Comment: No your first post was about using asterisk which is not gonna work because it match all routes
Comment: Yes, that's right. My edit where I added the middleware suggestion though, was before your answer.
Answer: I see that you have express tagged.  All you have to do is include a default handler that includes
res.status(404).render('404template')

For example
app.get('*', (req, res,next) => {
     res.status(404).render('error.ejs')
});

Comment: This doesn't work with the forward slash '/', shouldn't it be a "*" like the reply above?