O que é que o operador ">" faz no meio de uma expressão aritmética em C++?

Question: Encontrei esta linha de código em um solução proposta para um certo problema.
excedente = a % 10 + b % 10 + excedente > 9;

A minha questão é, que função é que o > 9 faz nesta linha me específico?
Answer: Esse é o operador relacional de "maior que", igual o que tem na matemática, então ele compara o operando que está à esquerda com o operando que está à direita e resulta em um valor booleano, ou seja, ou o resultado será falso ou verdadeiro, não pode ser outra coisa, portanto a variável excedente é do tipo bool e terá o valor false ou o valor true.
Note que a expressão da esquerda é toda operação matemática a % 10 + b % 10 + excedente, já que a precedência deste operador é menor do que os demais operadores usados, e tem associatividade da esquerda para a direita, então podemos ler assim:
excedente = ((a % 10 + b % 10 + excedente) > 9);

Coloquei no GitHub para referência futura.
E claro, ele quer saber se aquele cálculo da esquerda é maior que 9.
Comment: Nunca tinha visto um exemplo deste tipo. Obrigado !
Comment: Extremamente comum.
Comment: Eu ainda estou aprendendo C++. Toda ajuda é essencial.


Guidelines for men singing "women's" songs (and vice versa)

Question: In the classical repertoire, there are some works where gender "roles" seem to be fluid, but others where they are not.
For instance, Schubert's Winterreise is performed by both men and women. However, even when there are implied "characters," the tendency is inconsistent: as an example, Schubert's Die schöne Müllerin is almost always sung by men, while Mahler's Lieder eines fahrenden Gesellen is split almost equally between men's and women's voices in performance.
Are there any general guidelines that govern when a piece can be "transposed" between men's and women's voices?
Comment: Some vocal music were written for specific people. It would be presumptuous of you to sing a piece composed for a woman.
Comment: So be presumptious.  Even easier these days, now choice of gender identity is a thing!
Answer: Good Question. It prompted me to search and find this interesting read.

Although I enjoy and have studied a wide spectrum of music, my preferred specialty for several years has been Baroque vocal music.  Over the last generation or two, singers, directors, and audiences gradually have shown an increased interest in the vocal works written for castrati.  Because the era of castrati is long gone, a frequent solution has been to cast such roles with women.  These efforts continue to be met with relative success or failure depending upon the quality of the voices and the training of the singers.Not surprisingly, the casual listener conveniently equates high voices with female and low voices with male.  If, for example, a male sings with a high tessitura, whether naturally or with falsetto, some listeners fail to analyze what they hear beyond their simple conclusion.  I recall during one of my lectures, a music professor and Julliard graduate exclaimed, "Why, he sounds just like a woman!"  One irritated response was, "No, he does not!"  I suggest that there are two major factors in one's ability to discern male voices from female voices other than tessitura: musical experience and innate musical sensitivity.

As far as classical theory, there are no specific rules that dictate when and where a male or female should or should not sing a specific part, as long as s/he can "hit the notes." The full read of the article I linked goes more in depth on the differences of timbre. This is the crux of the issue for determining whether to use male or female, child or adult, voices.
What sound are you trying to achieve? What mood are you conveying? Finally, this is art, baby! Some of us males just drop the octave when we're performing a female vocal or singing "Habanera" in the shower...


How do I update the sitemap in D7?

Question: I want to exclude some pages from the sitemap.
I go to these pages/nodes, edit them, then go to the XML sitemap tab and set it to 'Exclude'.
I then save and clear cache.
But when I look at my sitemap.xml file nothing is changed - the page URLs are still present.
How do I remove them?
Answer: The XML Sitemap module doesn't rebuild sitemaps on every node save/load; also, it's not cached like other artifacts in Drupal.
The module tracks XML Sitemap links and they are added/removed upon cron runs. So you'll need to run cron to rebuild your sitemap files.
You can also follow some of the steps in the Setting up your site map (7.x) documentation:

Under "Inclusion" change "Excluded" to become "Included"
To add pages linked from menus to the sitemap, visit the edit page for each menu whose items should be included (this would usually
  include the Main menu). Open the XML sitemap fieldset, and similarly
  change "Excluded" to "Included". Hit Save.
Once that is all complete, go to Configurations --> Search and Metadata --> XML Sitemap
Click on the Rebuild Links tab in the upper right
Click on "Rebuild sitemap" even if the message says that you do not need to.
Now you're taken back to the config page which shows you the link to your xmlsitemap which you can click and confirm that pages have
  been added

How do I update the sitemap in D7?


For a given point $a=4$ and $\epsilon=0.01$ find a $\delta$ such that all x satisfying $0<|x-a|<\delta$ , the inequality

Question:
For a given point $a=4$ and $\epsilon=0.01$ find a $\delta$ such that
  all x satisfying $0<|x-a|<\delta$ , the inequality
  $0<|f(x)-L|<\epsilon$ holds where $f(x)=sqrt(x+1)$ is real valued
  function and $L=5.$

I tried to solve it as following
<code>kill(all)\$
load(solve_rat_ineq);
g(x):=sqrt(x+1);
a:4; eps:0.01;  l:5;
j(t):=t;
solve_rat_ineq(t<eps);
solve_rat_ineq(t>-eps);
cond1:t^2>0 and t^2 < (1/100)^2;
cond2:subst(sqrt(1+x),t,cond1);
cond3:x>-1 and x<1/10000 -1;
delta=min(abs(float(-1-a)),abs(float(-9999/10000 -a)))
</code>
am getting answer $\delta=4.9999$ which I think is wrong.
Can anyone tell me my mistake ? I think I have done something wrong in going from cond1 to cond2 (because I had to square 't'). Is there any other good method to solve it ?
Answer: I think it should read $L =\sqrt{5}$. In this case we have
$|f(x)-L|= |\frac{(\sqrt{x+1}-L)(\sqrt{x+1}+L)}{\sqrt{x+1}+L}|= \frac{|x-4|}{\sqrt{x+1}+L} \le \frac{|x-1|}{L} \le |x-1|=|x-a|$.
Can you proceed ?


javascript hover over TR to show image on hover only shows after hover

Question: I'm trying to make a price table that shows the area that will be worked on during that service with an image. So far I've managed to show the image that relates to the service that is hovered on. Only the image doesn't show until not hovering the text any more. But it is supposed to show immediately when being hovered.
It has been a while since I worked on a website and I'm getting a little rusty.
Html  (short version):

                        Onderlichaam
                        Prijs
                        Pakketprijs ( 6 + 2 gratis )

                        Bikini (buiten slip)
                        € 60
                        € 360

                        Bikini klein
                        € 70
                        € 420

                        Bikini groot (volledig)
                        € 90
                        € 540

                        Bilnaad
                        € 120
                        € 720

                        Onderbenen
                        € 125
                        € 750

                        Knieën
                        € 50
                        € 300

                        Bovenbenen
                        € 130
                        € 780

                        Zone bovenbenen
                        € 65
                        € 390

                        Volledige benen
                        € 260
                        € 1560

                        Voeten
                        € 40
                        € 240

                        Tenen
                        € 25
                        € 150

script

Does anyone see why it behaves like this?
Also, I have several of these tables that have their own image container that should behave in the same way. So any advice to help me make it more efficient would be a very good learning opportunity.
Thanks in advance!
Comment: `.toggle()` switches the element between being shown (if it is currently hidden), and being hidden (if it is currently shown.) I doubt that you want to do those two things alternatingly there, that makes little sense.
Comment: I misunderstood the functionality of toggle(). Thank you for explaining it. I left toggle out of the script and it works the way I want it to now.
Answer: .toggle hide the element, you can add the handlerout function inside the hover, to go back to the main image on mouseleave.
 $(function() {
    $(".tr-hover").hover(function(){
        $( "#vrouw-onderlichaam" ).attr("src", $(this).data("img"))
    },function(){
        $( "#vrouw-onderlichaam" ).attr("src", "./laserontharing-img/vrouw/onderlichaam/volledig.png")
    });
  });

Comment: Not sure if I want this flow yet but this could be useful for future projects. Thanks for this insight!


Reciprocal sum of triangular numbers is 1.

Question: n∈N
Triangular numbers set is $$\{1,3,6,10,15,21,28,36,45,55,\dots,\frac{n(n+1)}2,\dots\}$$
n≥3
I solved the equation   $$\frac 1{x_1} +\frac1{x_2} +\cdots+\frac1{x_n} =1$$      for triangular numbers:
$$\begin{align}n&=3,(3,3,3)\\
n&=4,(3,3,6,6)\\
n&=5,(3,6,6,6,6)\\
n&=6,(6,6,6,6,6,6)\\
n&=7,(3,6,10,10,10,10,10)      \text{ and } \\   &\quad(3,3,15,15,15,15,15)\\
n&=8,(3,6,6,15,15,15,15,15)\\
n&=9,(6,6,6,6,15,15,15,15,15)\\
n&=10,(10,10,10,10,10,10,10,10,10,10)\end{align}$$
Question is,
how can I find the solution of the equation for triangular numbers for other $n$?
Comment: Absolutely unreadable. Please use MathJax: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Interestingly $$\sum_{n=2}^\infty\frac{2}{n(n+1)}=1.$$ So there are no solutions with unique triangular numbers other than the trivial case of $1=1.$
Comment: I'm unsure what you're trying to *find*. Is it, given an integer $n$, find $n$ (not unique) elements of $T_n$ such that their reciprocals sum to $n$? Or sum to $1$?
Comment: I'm not understanding what people are finding confusing about this problem. The only thing I can think of is that the problem doesn't make clear if the OP is trying to find all solutions for each $n,$ or if one solution for each $n$ ($\neq2$) is enough.
Answer: Not an answer, just expanding on my ideas in comments.
Let $x_i=\frac{m_i(m_i+1)}{2}.$ Then $\frac{1}{x_i}=\frac{2}{m_i(m_i+1)}=\frac2{m_i}-\frac2{m_i+1}.$ Then your equation can be written as: $$\sum_{i=1}^{n} \frac{1}{m_i}=\frac 12+\sum_i \frac1{m_i+1}$$
If the largest $m_i$ has $m_i+1=p^k>2$ for some prime $p,$ then the number of $i$ with $m_i=p^k-1$ must be a multiple of $p.$ This is because the right side will still have $p^k$ as a factor in the denominator if not, and it can't be a factor on the left side.
If the largest $m_i$ has $m_i=p^k>2$ then the number of $m_i=p^k$ must be congruent to the number of $m_i=p^k-1$ modulo $p.$
So when the largest $x_i=10,m_i=4$ then the number of $10$s must be congruent to the number of $6$s modulo $2,$ and the number of $10$s must be a multiple of $5.$
If $m_i=5,x_i=15$ is the largest, the number of $15$s must be congruent to the number of $10$s modulo $5.$ We have $a$ $10s$ and $5b+a$ $15?$s, you get the sum of those is:
$$a\left(\frac1{10}+\frac1{15}\right)+\frac{5b}{15}=\frac a6+\frac b3.$$
When $a+2b\leq 6,$ you get solutions: $((6-a-2b)\times 6,a\times 10,(a+5b)\times 15).$ This gives an answer for $n=6-a-2b+a+a+5b=6+a+3b.$
When $6-a-2b>2,$ we can replace any pairs of sixes with a $3.$
So when $a=2,b=1,$ we get another solution for $n=10,$ $x_*(3,2\times 10,7\times 15)$ or $m_*=(2,2\times 4,7\times 5).$
When the largest $m_i=6, x_i=21$ then there must be a multiple of $7$ of them. Then you get $\frac{7b}{21}=\frac b3.$ You can $\frac13$ and $\frac23$ in quite a few ways with the smaller $m_i.$
$m_i=7$ is interesting because $m_i$ and $m_i+1$ are prime powers, so if the largest $x_i=28,$ then the number of $28$s must be even and congruent to the number of $21$s modulo $7.$ If there are $a$ $21$s] and $a+7b$ $28$s, then $a+b$ must be even, the partial sum $\frac{a}{12}+\frac{b}{4}=\frac{a+3b}{12}=\frac{b+\frac{a+b}2}6$ and thus we can make thirds and sixths out of the smaller $m_i.$
But this approach will really only work for small $m_i.$ Prime powers became rarer when $m$ increases. When $m_i=14,$ neither $m_i$ nor $m_i+1$ is a prime power. You might still be able to do something with that, but it gets more complicated.

Solutions for all $n>2:$
If $T(k)=\frac{k(k+1)}2,$ we have: $$\sum_{k=2}^{m-1}\frac1{T(k)}=1-\frac{2}{m},$$ we can add $m+1$ copies of $\frac1{T(m)}$ to get a total of $1,$ yielding a solution $(T(2),T(3),\dots,T(m-1),(m+1)\times T(m))$ for $n=2m-1.$ That gives a solution for all odd $n.$
For $n=11,$ this becomes $(3,6,10,15,7\times 21).$
We can get a solution for $n=2m$ by first solving for $2m-1,$ then replacing the $3$ with two $6$s.
So we can find a solution for all $n>2.$
Since $\sum_{m=2}^{\infty}\frac{1}{T(m)}=1,$ there is no $n>2$ for which there no repeating values. For $n$ odd, we see there is a solution with only one repeated value. For $n=2m$ even, our solution has potentially two repeated. values, $T(3)$ and $T(m).$
There are cases when $n=T(k)$ is even where we have a solution with only one value, such as $(6,6,6,6,6,6)$ and $(10\times 10).$ But are those the only even cases where all but one value occurs only once?
Comment: Thanks Thomas. Your answers will shed light on my work.


How do I solve simultaneous congruence modulo equations

Question: How do I find one value of $x$ in these equations?
$$
\begin{cases}
x \equiv 3 \pmod{5}\\
x \equiv 4 \pmod{7}
\end{cases}
$$
Comment: Goggle the "Chinese Remainder Theorem".
Comment: There are two approaches the general (Chinese Remainder Theorem and the associated algorithms) and the particular, which is well-suited to small moduli like the $5$ and $7$ of your problem.
Answer: First ascertain that the moduli are coprime, guaranteeing a solution by the CRT.
Then solve one equation first (doesn't matter which):
$x \equiv 4 \pmod 7$
$x = 7k + 4$
Substitute this into second equation.
$7k + 4 \equiv 3 \pmod 5$
$7k \equiv -1 \pmod 5$
$k \equiv (-1)(7^{-1}) \pmod 5$
$7^{-1}$ is not a reciprocal. It is the modular multiplicative inverse of $7$. You can find it using the Extended Euclidean Algorithm, but for small moduli, it's much easier to just test a few values. In this case, the inverse is $3$ because $(7)(3) = 21 \equiv 1 \pmod 5$.
So $k \equiv (-1)(3) \pmod 5 \equiv 2 \pmod 5$
$k = 5t + 2$.
Substitute that back into the solution of the original equation:
$x = 7k + 4 = 7(5t+2) + 4 = 35t + 18$
which is the required solution. If you want to express it more compactly, you can write:
$x \equiv 18 \pmod{35}$
In your answer, you've found a particular solution, but not the general one. $18, 53, 88,...$etc. all solve the system. Your question stated that you only need to find one value, in which case your solution is fine. But if you need a complete solution set, this answer may be helpful. Of course, once you've found a single solution, you don't have to go through this process. CRT guarantees the uniqueness of the solution modulo the product of the other two moduli, i.e. $\pmod{35}$ in this case. So if you've already found $53$ to be a solution you know that every solution will be equivalent to this modulo $35$.
So $x \equiv 53 \pmod{35} \implies x \equiv 18 \pmod {35}$ since $53 - 35 = 18$. This way you can immediately generalise your particular solution.
Answer: If you are still looking for a way to find solutions to your problem, you might want to consider this.
The "method" is based on introducing parameter variables so that the original variables can be expressed as parameter variables. If such an expression exist, then enumerating integer values for the parameter variables would then yield integer solutions to the original variables. The "method" might work for any arbitrary linear system of equations where the domain of each variable is from the set of Integers.
I hope you find this useful. – john
A solution to your problem using the "method":
Answer: I reckon I've worked it out, so I'll just answer my own question.
Firstly, make sure the GCD of your mods are equal to one. ie in this example:
<code> gcd(5,7) = 1
</code>
Then solve the question in 2 parts since there are 2 simultaneous equations.
<code>x = _______ + ________
</code>
where the first underlined bit is for mod5 and the second part is for mod7
Then, you add a 7 to the first section of your solution, as 7(mod7) is 0 and will cancel that section out. You do the same for the second section but with a 5, as 5(mod5) is also 0. (sorry I'm not very good at explaining.)
so you get:
<code> x = 7 * ______ + 5 * _______
</code>
working with the first section, you get:
<code> 7 = (2 mod 5) but we need it in terms of (3 mod 5)
</code>
so by inspection, we find that:
     7*4=28 which is (3 mod 5)
we can now update the solution to
<code> x = 7*4 + 5* _____
</code>
Doing the same thing again to the second section of the solution, we get:
<code> x = 7*4 + 5*5 = 53
</code>
Answer: Given x ≡ a (mod m) and x ≡ b (mod n), if there is a solution at all, there are infinitely many of them, all congruent modulo lcm(m,n).
(If m and n are coprime, a solution must exist per the Chinese Remainder Theorem; if they're not coprime, a solution only exists if a ≡ b mod gcd(m,n)).
The first step is to find any solution to Bézout's Identity: a pair of integer values u and v such that um+vn = gcd(m,n). In this case, you're looking for solutions to 5u + 7v = 1.
In general you can get solutions to this sort of problem using an extension of Newton's method, but for small values like this it's not hard to find some by inspection. The first one that occurs to me is u=3, v=-2, since 5(3)+7(-2) = 15-14 = 1.
Any valid solution for u and v will give you one of the infinitely-many solutions to the original problem  when you plug them into the expression (bum + avn)/gcd(m,n). That is, multiply each remainder by the other divisor and its Bézout coefficient, add the products together, and divide by the GCD of the moduli (which is 1 in this case).
For your problem that expands to 4(3)5 + 3(-2)7 = 60 - 42 = 18.  And sure enough, 18 ≡ 5 (mod 3) and 7 (mod 4).
Another solution I can see for u and v is u=-4 v=3, since 7(3)+5(-4) = 21 - 20 = 1; that yields 4(-4)5 + 3(3)7 = -80 + 63 = -17, which is of course congruent to 18 modulo lcm(5,7) = 35.


chi-square distribution with $v = 7$ degrees of freedom Ti-89?

Question: I need to figure out the Probability that $Y > 23$ for a chi-square distribution with degrees of freedom $= 7$.
The book says to do this with some applet. I don't know what it's talking about.
Can I do this on my Ti-89 (preferable) or on some website somewhere?
EDIT/UPDATE:
I found a program on my ti-89 for chi-square distribution. However it asks me for lower and upper bound and degrees of freedom. I put in $7$ for degrees of freedom but i'm not sure how to translate probability $Y > 23$ into an upper and lower bound?
I put in lower $= 0$, upper $= 23$, degrees of freedom $= 7$ and I said to auto-scale and I got $.998295$. Is that the right probability?
Comment: [This](http://education.ti.com/calculators/downloads/US/Software/Detail?id=189) could have just been found using a search engine. Voting to close.
Comment: I'm confused as to how this answers my question. I don't see anywhere that it says this program can preform the calculation I need.
Comment: And I did google my question. This did not come up.
Comment: and i believe I have this on my calculator already because I can get to the screen that is shown, and I cannot figure out how to use it to solve my problem.
Comment: But you did read that app's manual, yes?
Comment: nope. I didn't see it. Thought that was a link to download the program. I found the program and am reading the manual but still don't get how to use the program. I'll edit my question.
Comment: A hint: on these calculators, $-10^{99}$ and $10^{99}$ are stand-ins for $-\infty$ and $\infty$.
Comment: Ive seen the calculator give me artifacts a bunch of times, they always have more 99s than this did. If it was tyring to give me an artifact meaning 1 it would have said .9999998 or 1.000001 . I'm thinking that .998295 is the actual value. is there a table with these numbers in them?
Comment: The expected value of the chi-square is 7, so $Y > 23$ is an improbable event. You probably want $1-.998295 = .001705$.
Answer: There's an online calculator here. Plugging $\chi^2 = 23$ and $df=7$, we get $.0017$. Your calculator calculated the probability that $0 \leq \chi^2 \leq 23$, which is $1-.0017 = .9983$.
As I commented above, you could tell that you needed to take $1-p$ instead of $p$ since $\chi^2 > 23$ is an unlikely event, given that the expectation is $7$ and the standard deviation is $\sqrt{14} \approx 4$ (Chebyshev and even Markov would give you that $p < 1/2$).
Comment: Good think you need more than just one vote to close or I would never have gotten this excellent answer. Thanks!


Terminology: Is DTW considered to be machine learning or signal processing?

Question: The DTW Wikipedia article puts this method in the category "Machine learning algorithms". On the other hand, the famous paper "Dynamic Programming Algorithm Optimization for
Spoken Word Recognition" was published in IEEE Transactions on Acoustics, Speech, and Signal Processing, indicating that DTW might have been considered a signal processing algorithm by the authors.
Admittedly, the term machine learning might not have been as common in 1978 as it is today but I still wonder the following: Is DTW considered to be a machine learning algorithm or a signal processing algorithm?
Comment: Thanks for your reply but I was asking about DTW, not PCA.
Comment: Some teach PCA as a ML tool
Comment: You can anything a machine learning algorithm
Answer: I don't think there is an accepted answer to this question. (Which would be ironic if you were to accept an answer in this thread.) Signal processers and machine learners will both use DTW in their work and consider it "theirs".
There are 170 hits on CrossValidated and 83 results on SignalProcessing, but of course the two sites have very different traffic, and DTW is probably more important to signal processing "as a whole" than to statistics "as a whole".


Modules imported twice. Possible bug in Python interpreter

Question: I've made a rather contrived import scheme in a project of mine and I think I might have discovered a bug in the Python interpreter that causes modules to be imported twice.
Here's how my test project is set up:

/

Launcher.bat — Project is run from here. It launches 'main/__init__.py` using the Python 3.2 executable
main/__init__.py — The __main__ script, the one launched by 'Launcher.bat'
main/foo.py — Contains an empty class
external/__init__.py — A script external to the 'main' project scripts, used to demonstrate the problem

./Launcher.bat
@echo off
C:\Python32\python.exe main\__init__.py
pause

./main/__init__.py
from foo import Foo
print("In 'main', Foo has id:", id(Foo))

# Add the directory from which 'Launcher.bat' was run,
# which is not the same as the './main' directory
# in which this script is located
import sys
sys.path.insert(1, '.')

# This script will try to import class Foo, but in doing so
# will casue the interpreter to import this './main/__init__.py'
# script a second time.
__import__('external')

./main/foo.py
class Foo:
    pass

./external/__init__.py
from main.foo import Foo
print("In 'external', Foo has id:", id(Foo))

All of this will print the 'Main script was imported' message twice. If the external script imports any other scripts, those too will be imported twice. I've only tested this on Python 3.2. Is this a bug, or did I make a mistake?
Output of the program is:

In 'main', Foo has id: 12955136
  In 'main', Foo has id: 12955136
  In 'external', Foo has id: 12957456
  Press any key to continue . . .
Comment: It always make me laugh the statements: my code works, python has a bug :D
Comment: @fabrizioM Then again, you can't really say that you'd expect Python to import the same module twice. I now know why it happens, but I still don't think it should happen.
Answer: I don't think it's a bug. You should ask on the python-dev list for a more authoritative answer. You are executing once (when you run the script) and importing once (from external) so the line gets printed twice. It's not importing twice.
However, this is a horrible setup. There are a lot of style violations here. Granted that some are for demonstration purposes only, it's still quite messy.

You shouldn't use a package __init__.py file as a file which should be run. The main entry point should be a script that imports the package.
You shouldn't have an imported module importing the module which imported it. Like you external is doing to main.
Comment: @Paul Manta: There is one import of "main", and one _execution_ of main. This explains why you have two versions of Foo being defined. When you execute a script, it does not get imported and cached. To test the theory, create a blank main/__main__.py, and change your launcher script to execute "python -m main".
Comment: I know it's a horrible setup, I called it contrived myself. :) It's for demonstration purposes, I tried to do this in as few files as possible. And the module is, in fact, imported twice. If you compare the `id()` of `class Foo` from `main` and the on from `external`, you'll see that they are different.
Comment: The `id`s of classes are orthogonal to the question of imports. You can define a `Foo` class in a module, import another module `x` and have an `x.Foo`. Both will have different `id`s. That's your situation.
Comment: @axw Thanks, I didn't know that. But please check out my updated post, does what you said still apply?
Comment: @PaulManta: Yes. Try adding a `import sys; print('main' in sys.modules)` at the top of external/__init__.py. The "from main.foo import Foo" implicitly imports main/__init__.py since it's not in sys.modules already.
Comment: @awk I see. :) But when `foo.py` is imported, is it not added to sys.modules? I don't understand why Foo has different `id()` values in the two scripts. Doesn't `id()` (in CPython) give you the address in memory of the data itself? — or is it the address of the handle you have to the data?
Answer: The first print is misleading: Since you're not importing, but executing the file at the first time (__name__ == '__main__' holds true), the main modules just gets imported once. Move the start point into a secondary file, or check for __name__ == '__main__'.
By the way, circular import are a bad idea. You should resolve the circular import (by moving foo to a dedicated library). Alternatively, you can make your modules reentrant (i.e. check for the current directory being in sys.path before adding it).
Comment: @PaulManta Huh? The definition of foo doesn't matter. `__init__.py` always gets executed first when importing from somewhere, no matter with what syntax. `from a import b` is only syntactic sugar for `import a; b = a.b; del a`.
Comment: @PaulManta You seem to be on the wrong track. This has nothing to do with `from a import b`, which is syntactic sugar as I wrote above. If you replace it with the longer statement, you still get the same result. [Here is the object graph created by your script.](http://phihag.de/2011/so/so-pymodules.svg) (modules only, file names just for reference).
Comment: So whether or not the module was imported before is determined by the module name, not by the file path of the script?
Comment: @PaulManta Precisely. Since some modules don't have filenames, that wouldn't be possible anyways.
Comment: It's not the result of a circular import. I initially discovered this by having a third file, `./main/foo.py`, which both `./main/\__init__.py` and `./external/\__init__.py` imported. I noticed that the classes defined  inside `foo.py` had different `id()` values between the scripts in `main` and the ones in  `external ` (which means the script was imported twice). (But you are right, at a first glace this does look like a circular import problem, I'll fix this.)
Comment: @Paul Manta I'm looking forward to an updated question that does not contain a circular import, and does not fiddle around with import internals (i.e. only the `import` statement)
Comment: @PaulManta Oops, I overlooked another thing: You're *executing* a `main/__init__.py`. Therefore, the module just gets loaded once; the first print is misleading. Updated the answer.
Comment: I still don't understand why the `id()` of `Foo` is different between scripts. In CPython it represents the address in memory of the "object". What is an "object"? Is it the data itself, or the handle you have to the data?
Comment: @PaulManta The problem has nothing to do with `id`. There are two instances of the module foo, each with its own class object Foo. I suggest you add `print('foo gets imported, __name__: ' + __name__)` to `foo.py`. That should clear it up.
Comment: @PaulManta An object is an abstract entity (probably what you mean with "the data itself"). CPython chose to implement that by returning the memory address, because it assigns a unique block of memory to each object.
Comment: @philag Thanks. I see the `from ... import` syntax causes the that `print` you gave me to be executed twice (the `import ...` syntax does not). I expected the module to stay in memory for as long as at least one object it contains is referred to by another module.
Comment: Okay, thanks for helping me. I'll pick yours as an answer, because of the comments.
Comment: @Paul Manta For me, an object is a portion of the RAM memory whose bits are structured in a manner that represents data according to some conventions. A Python object holds bits that conventionally represent a type and bits that conventionally represent a value, said 'its' type and 'its' value. The identity of an object isn't hold in its structure, it is the location where it is lying in the memory. That's my idea. I never understood why the Python doc defines _"Objects are Python's abstraction for data_". For me, objects are not abstract they are concrete representations of abstract notions.
Comment: @eyquem Well, that holds true for cpython, but does not apply for jython and IronPython.
Comment: @phihag I would like to know more about the implementations of Jython and IronPython. Aren't there objects in these two languages ?


CSV export hidden series in Highcharts

Question: I have a chart with 2 series, one of which I should not be visible. However, that data should be present in the CSV export. Setting,
<code>showInLegend: false,
visible: false
</code>
hides that series in the chart, however it also does not export in the CSV. How can I disable a series to be displayed, but enable its export?
Fiddle: http://jsfiddle.net/absessive/cqjvD/1109/
Answer: THe plugin that you are using is checking if series is visible - if you remove that check, then hidden series will be included in exported CSV.
Example: http://jsfiddle.net/cqjvD/1111/
Changed line in the plugin:
<code>      if (series.options.includeInCSVExport !== false) { // #55
</code>

CSV export hidden series in Highcharts


How did we derive the least square estimator using OLS?

Question:

How does multiplying a matrix with its transpose equal "minimizing" it?
When calculating the partial derivative, where does the X' come from?
Why setting the value of third equation to 0 is legal here and why did the X' changed again to W' in the third equation?
Answer: $\bullet$ Multiplying a matrix with its transpose doesn't "minimise" it. Here, we seek $\bf a$ such that sum of squares of residuals i.e. $\boldsymbol\epsilon^\top\boldsymbol\epsilon$ gets minimised.
$\bullet$ That is plausibly a typo.
$\bullet  $ The derivative has to be equated to zero in order to meet the first order condition: remember we are seeking to minimise the residual sum of squares.
Comment: Please check what it means to [minimise a function](https://mathinsight.org/minimization_maximization_refresher).
Comment: Thanks for the response. What do you mean by the word minimise? To make it close to zero?


clicar em link e abrir conteudo em div como um _blank

Question: Eu preciso criar em link e fazer com que o conteúdo do arquivo chamado seja exibido dentro de uma div de acordo com os $_GET[] informados.
Este comando eu já entendi como deve ser feito.
Entretanto, eu preciso que esta div seja aberta como se fosse um _blank.
ela não ficaria fixa em alguma parte da tela e também não ficaria preenchida com display: none e seria exibido habilitanda display ao clicar.
O conteúdo seria buscado no momento em que a DIV fosse aberta como acontece com as divs que são abertas no facebook.
Agradeço a quem puder ajudar.

function carregar(pagina){
    $("#conteudo").load(pagina);
}

Arquivo 1
Arquivo 2

eu colei o código,mas ele não aparece aqui. não sei como fazer esta configuração.
Comment: Como acontece com as divs que são abertas no facebook.
Comment: coloque o que vc ja tem, parte do codigo
Comment: inserido o codigo
Comment: Pode usar modal do bootstrap.
Comment: Fala Leonardo. Eu vi sobre o bootstrap e realmente ele é uma excelente ferramenta. Resolve o problema de abrir modal. Mas reparei que quando é aberta ela já fico com o conteúdo preenchido e faz um efeito como display: none e block. Fazer desta forma é tranquilo. Mas preciso que ao ser aberta a div seja carregada buscando o  conteúdo naquele momento, como ocorre com as divs no facebook. De qualquer forma agradeço sua ajuda.
Answer: você cria uma página para receber esses dados, envia o id pela url, ja que é um get, e nessa página você faz um select dos dados baseado nesse id, pelo que eu entendi é isso que vc quer <a href="pagina_dados.php?&id=<?php echo $row['id'];> ">


Chance of spotting an incorrect value by random checks in a string

Question: To check that you are communicating securely with your friend, many chat applications allow you to verify the encryption key. If you meet in person and see on their screen that they use encryption key "dbdcc", and your device also reports using that encryption key, then you know that the two devices are not being intercepted.
A typical key size is 256 bits and is often displayed in hexadecimal encoding, i.e. 64 characters to compare. Since people am lazy, I would like to find the minimum number of random characters to compare for security (such as two blocks of 6 characters). An attacker would not be able to brute force 256 bits, but they could do 64 bits. But let's keep the example small, and use the "dbdcc" string from above. Imagine an attacker can brute force only three characters of that five-character string, and only the values a through d can be used in each position.
The attacker could choose to brute force the key until the 1st, 3rd, and 5th characters match, for example yielding "dadac" as key. Depending on which characters we compare, we find that the keys do not match:
<code>1 2*
1 3
1 4*
1 5
2 3*
2 4*
2 5*
3 4*
3 5
4 5*
</code>
* In these cases, the attack would be detected, since it includes either 2 or 4, which the attacker did not attack.
So in the example, we have a $\frac{7}{10}$ chance of detecting the attack, assuming all characters that the attacker did not attack are indeed incorrect. In reality, the odds are 1 in 4 for each overlapping character, so even if we check both positions 2 and 4, there is a 1 in 16 chance of a successful attack.
The number 10 (combinations, "5 choose 2") is a formula I was able to find:
$\frac{n!}{(n-c)!×c!} = \frac{5!}{(5-2)!×2!} = 10$
But I can't figure out how to compute the 7. How do I calculate the odds that the attacker chooses an identical set, or the converse: that the defender chooses an overlapping set? The only way I can think of solving this is by doing it manually as done for the example above, which I could easily script in Python to be able to do it for arbitrary parameters, but surely there is a better way.
One way to get to 7 would be the number of possible sets checked by the attacker (10) minus the number of characters the attacker attacks (3), but that does not hold up in the case where the attacker attacks only 2 (then there is only one case where you do not detect the attack: if the attacker attacks the exact two characters you check), since that would give $10-2=8$ but in reality we have a $\frac{9}{10}$ chance and not an $\frac{8}{10}$ chance.
How could one calculate these odds without simulating all possible choices and checking for how many choices the two chosen sets overlap? Note that we'll need to account for the chance that one or more positions are correct, even if they were not part of the attacker's chosen set, so it needs to be broken down by number of items in the sets' overlap.
Answer: In your specific example, you get the number $3$ as $3$-choose-$2$ a.k.a. ${3\choose 2} = {3! \over 2! 1!} = 3$ because that's how many size-$2$ subsets (pairs) of positions which fit entirely within the size-$3$ subset of hacked positions (positions $\{1,3,5\}$).  Such pairs are guaranteed to match.
More generally...
If I understand you correctly, you have a string of $n$ characters, each character being from an alphabet $\Sigma$ of size $s.$  The attacker has a string of $n$ characters of which $m < n$ are guaranteed exact matches and the remaining $n-m$ characters has a $1/s$ chance each of matching.  Then you're comparing some $c < n$ of the characters, and you want the probability of find all $c$ matching, a.k.a. a successful attack.  (In your example, $n=5, \Sigma = \{a,b,c,d\}, s =4, m=3, c=2$.)
First, is my interpretation correct?
Among the $c$ characters being compared, some $d \le c$ of them are among the $m$ guaranteed matches, and the remaining $c-d$ of them would match with probability $1/s^{c-d}$.  The number of ways to pick such a combo is ${m \choose d} {n-m \choose c-d}$ where the ${a \choose b} = {a! \over b! (a-b)!}$ is the $a$-choose-$b$ formula you found.  So you sum over all $d$ and get:
$$\mathit{Prob}(\text{successful attack}) = {1 \over {n \choose c}} \sum_d {m \choose d} {n-m \choose c-d} {1 \over s^{c-d}}$$
You need to be careful of the range of $d$ in the summation: AFAICT, you need $0 \le d \le m, 0 \le d \le c,$ and $0 \le c-d \le n-m$.
Comment: I think your interpretation is correct. I'm short on time right now so I'll implement it in python later to test if it works, but insofar as I can follow the second part ("Among the..."), it looks like this will be the answer!
Comment: Just be careful with the range of $d$ in the summation.  Good luck!  :)
Comment: Thanks again antkam, I finally got around to writing an implementation and the results look good! This is the code, in case you are interested: https://pastebin.com/m44uzt8m Might also be good to check if I understood your answer correctly :)


Applying Ito's Lemma and integrating, show $\int_{t_i}^{t_{i+1}} W_sdW_s = \frac{1}{2}(W_{t_{i+1}}^2 - W_{t_i}^2 - {\Delta}t)$

Question: I need to show
$$\int_{t_i}^{t_{i+1}} W_sdW_s = \frac{1}{2}\left(W_{t_{i+1}}^2 - W_{t_i}^2 - {\Delta}t \right)$$
And then apply the result to show
$$\int_{t_i}^{t_{i+1}} \left [\int_{t_i}^{s}dW_u \right]dW_s = \frac{1}{2}\left({\Delta}W_{i}^2 - {\Delta}t \right)$$
Could someone please advise how I can approach this? I don't know how to do it.
Thanks
Comment: Rather than posting a bare problem statement, it's required to give some context for a Question.  The tags and mention (only in title) of Ito's Lemma suggest this is an exercise from a book or course on stochastic processes, so perhaps you could briefly edit the Question to explicitly state the book or class where you encountered it.  Such context may prove valuable to future Readers.
Answer: Per Ito's Lemma
$$d(W_s^2)=2W_sdW_s+2ds
$$
or
$$W_sdW_s= \frac12(d(W_s^2) -ds)$$
Then, integrate to obtain
$$\int_{t_i}^{t_{i+1}} W_sdW_s
=\frac12(W^2_{t_{i+1}}-W^2_{t_{i}}-\Delta t)
$$


Difficulty to understand SQLite exists and its subquery

Question: Assume there is one table called Temp, its schema and data are listed blow
Table Temp :
A         B
----      ----

1         1        # Row 1
1         5        # Row 2
2         2        # Row 3

SQLite Query :
1) DELETE FROM Temp WHERE EXISTS (SELECT 1 FROM Temp AS IL2 WHERE Temp.A = IL2.A AND Temp.B = 1 AND IL2.B = 5)
2) DELETE FROM Temp WHERE EXISTS (SELECT 1 FROM Temp AS IL2 WHERE Temp.A = IL2.A AND Temp.B = 5 AND IL2.B = 1)

Question 1)
What is the meaning of "Temp.A = IL2.A"?
IL2 is alias of Temp, it compares to itself? I get lost here.
Question 2)
Query 1 and 2 deletes Row 1 and 2 by experiment, respectively.
It seems to me that the return value of the sub-query "(SELECT 1 FROM Temp AS IL2 WHERE Temp.A = IL2.A AND Temp.B = 5 AND IL2.B = 1)" is controlled by the value of "IL2.B". I thought this sub-query return both Row 2 and Row 3.
Answer: The delete statements look for a record with the same A, but the other B (1 vs. 5) in the same table. In order to do this a table alias (IL2) is needed to be able to distinguish between the one record and the other. The queries are a little obfuscated, though. Some criteria is hidden in the subquery where it not really belongs. Better would be:
delete from temp
where b = 1
and exists (select 1 from temp as il2 where il2.a = temp.a and il2.b = 5);

delete from temp
where b = 5
and exists (select 1 from temp as il2 where il2.a = temp.a and il2.b = 1);

A side remark: The second statement will not find (and hence delete) anything of course, because all b1 for which a b5 exists are already deleted then. In order to circumvent this and delete both records, i.e. both the b1 and b5, combine the two statements:
delete from temp
where b in (1,5)
and exists
(
  select *
  from temp other
  where other.b in (1,5)
    and other.a =  temp.a
    and other.b <> temp.b
);

Comment: Thank you very much for your re-factor Sql query.
Answer: WHERE EXISTS means that all Rows will be deleted, where the Subquery (SELECT 1 FROM Temp AS IL2 WHERE Temp.A = IL2.A AND Temp.B = 1 AND IL2.B = 5) gets more than 0 results.
So look at the subquery. Basically it selects all values from temp a second time.

DELETE FROM Temp -> First time (referenced as Temp)
SELECT 1 FROM temo AS IL2 -> Second time (referenced as IL2)

Now the subquery has its own where clause, in which both tables (Temp and IL2) are compared:

In Temp and IL2, A has to be equal
in Temp, B has to 1
in IL2, B has to be 5

There are only 2 rows, where those clauses are true (and therefore returned): Row 1 and Row 2.
Comment: Thank you. I have the same idea as you for sub-query (Row 1 and Row 2 will return), but the experiment showed that only Row 1 is return for "(SELECT 1 FROM Temp AS IL2 WHERE Temp.A = IL2.A AND Temp.B = 1 AND IL2.B = 5)", which I do understand.
Comment: @Zhongkun Ma: The first statement returns row #1, because its B is 1 and there exists a record with the same A and with B = 5 in the table. The second statement returns row #2, because its B is 5 and there exists a record with the same A and with B = 1 in the table (provided, you didn't run the first statement already and deleted that record). It shouldn't be confusing you that the same table is queried twice. Maybe it helps to imagine there really *is* another table named IL2 with exactly the same data.
Comment: @ThorstenKettner: I think I get it, but one thing to confirm. "(select 1 from Temp)" indicates the result is selected from Temp table and "Temp.B = 1" indicates the select result's B field in Table Temp  has to be 1. Am I correct?
Comment: @Zhongkun Ma: I've written an additional answer to explain the whole process step by step.
Comment: @ThorstenKettner: I would like to thank you from my heart. This is super clear for me.
Answer: Here is another answer explaining step by step what happens in the query. Let's take query #2:
DELETE FROM Temp
WHERE EXISTS
(
  SELECT 1
  FROM Temp AS IL2
  WHERE Temp.A = IL2.A
    AND Temp.B = 5
    AND IL2.B = 1
);

This statement is supposed to find records in table Temp and delete them. So let's start with the first record and see if it matches the criteria given in the where clause:
row #1: A=1, B=1
We are looking for existence in the same table, which we call IL2 (just as if it were a different table). So whenever we refer to the just-read record which we may want to delete or not, we use the qualifier Temp, and we read the table IL2 record for record in order to compare them with the Temp record. So let's look if we find a match:

A | B |  Temp.A = IL2.A?               | Temp.B = 5?       | IL2.B = 1?
--+---+--------------------------------+-------------------+------------
1 | 1 |  Yes, both records have A=1.   | No, Temp.B is 1.  | Yes.
1 | 5 |  Yes, both records have A=1.   | No, Temp.B is 1.  | No, it's 5.
2 | 2 |  No, Temp.A is 1, IL2.A is 2.  | No, Temp.B is 1.  | No, it's 2.

As you see, Temp.B = 5? is always false (and would always be true, ich we looked at the second record row #2 instead), because although the criteria is in the EXISTS subquery, it really refers to the record that stands trial. This is why I recommended to move this criterion outside the EXISTS clause for readability. This query is 100% equivalent, but easier to read:
DELETE FROM Temp
WHERE B = 5
AND EXISTS
(
  SELECT 1
  FROM Temp AS IL2
  WHERE IL2.A = Temp.A
    AND IL2.B = 1
);

Let's now look at this query instead. Again we read the first row from Temp. B is 1, so WHERE B = 5 is not matched. The criteria is not met, the record will not get deleted.
Next record (row #2). B = 5. Okay, so let's look into the exists clause and check again record for record:

A | B |  Temp.A = IL2.A?               | IL2.B = 1?
--+---+--------------------------------+------------
1 | 1 |  Yes, both records have A=1.   | Yes.
1 | 5 |  Yes, both records have A=1.   | No, it's 5.
2 | 2 |  No, Temp.A is 1, IL2.A is 2.  | No, it's 2.

Aha. The first record matches, so the EXISTS criteria is met. (The DBMS has to find at least one match. Once it found a match, it doesn't have to read the remaining records. So we could have stopped, after having found row #1 as a match.) All criteria is TRUE; the investigated Temp record (row #2) will get deleted.
Now to the last record. B is 2, so WHERE B = 5 is not matched. The criteria is not met, the record will not get deleted.
I hope this clarifies how EXISTS works. (As to the "selected" data: it doesn't matter what you select in EXISTS; these three all work the same: where exists (select 1 from ...), where exists (select * from ...), where exists (select 'yes, there exists a row' from ...).)


Linux heartbeat: which one becomes master?

Question: Suppose I confiugred 2 machines to be active/passive with the linux heartbeat and pacemaker, then I create a resource group in node1, commit it. If I am correct the configuration will be propagated to node2. The resource group is going to monitor one of the service in the machine.
My question is, because the 2 nodes are running identical service, which one is becoming the active node firstly? Or the linux heartbeat will decide that(the two has equal possibility)?
Comment: As an aside, you can force a standby or takeover with /usr/lib/heartbeat/hb_standby all (or hb_takeover all)
Answer: With Pacemaker you don't have 'an active node' and 'a passive node'. All cluster nodes (there may be more than 2) can run services equally and the rules in the CIB database tell CRM (Pacemaker's resources manager) what node can run what services.
If you configured the service to run as a single instance that can run on both nodes with no constraints, then you cannot tell which node will run it.  If you have two such services then you may end with one running on one node and the other on the other node. For the first service node1 will be active and for the second – node2.
You define actual preference by declaring some constants. Example: 'run service 1 on a node where service 2' is running or 'always prefer node 1 for both services'.
Usually you have a service which defines 'a logical master' – it can be an IP address or DRBD volume in the primary state – then all other services depend on this and you choose the 'master' by setting preferences for the primary service.
See the Pacemaker documentation for details on setting the constraints.
Heartbeat itself, when used with Pacemaker, doesn't make any decisions on master/slave states or on what resources are running.
Comment: actually I want to setup an active node and a passive node backup for the active node. Do you have any reference for me to start? I want a simple enough configuation to start and add more complex ones :)
Comment: This is still too generic to give a simple answer. Everything depends on the services you want to run, the storage they use, etc. You just need to read the documentation: http://www.clusterlabs.org/doc/en-US/Pacemaker/1.1/html/Pacemaker_Explained/ It is quite complicated at first, but when you get it 'just works' (with some magic inside)


Api Localização com Zona

Question: Tenho uma base de endereços(logradouro, cidade, estado, CEP, bairro) e precisaria completar o endereço com a Zona (Leste, Norte, Sul, Oeste, Centro).
Pensei que a forma mais fácil de fazer seria por API, esse site é perfeito para ilustrar: http://thiagorodrigo.com.br/cep-sao-paulo-lista-de-cep-por-bairro-e-cidade-da-grande-sao-paulo/, mas não achei API, alguém conhece alguma?
PS.: Se for só São Paulo já atende a maioria dos meus endereços.
Answer: Exportei id e CEP de toda minha base de dados para um Excel, peguei as faixas de CEP por zona nesse site: http://rainydays.com.br/faixas-de-cep-de-sao-paulo e coloquei no mesmo Excel. Separando pelas colunas Zona, Inicio e Fim
Fiz um PROCV procurando os CEPs da minha base na Tabela de faixa de CEP me retornando a Zona. Agora eu tinha id e Zona, com isso montei um UPDATE e executei no Banco de Dados.

Api Localização com Zona


convert of the object (image) to another object (Byte) in three layers(3-tier)

Question: Conversions can be done in the first layer ( UI ) ?
Comment: Conversion *can* take place anywhere. The question is wheter it *should*, and that entirely depends on what your application is doing, and how. You will need to provide some more information to get any useful answers.
Comment: possible duplicate of [Convert string to image in 3-tier](http://stackoverflow.com/questions/4447438/convert-string-to-image-in-3-tier)
Comment: never to convertion in the UI that is bad practice
Comment: @CoffeeCode :  Why? Where the conversion is done
Comment: @ Fredrik Mörk : Each layer can be converted? Even ِDAL(DataAccessLayer).
Comment: do the convertion on the model level. convetions must be done in the backend not frontend
Answer: For these kind of operations I personally create a Utils class/namespace under project namespace (myProjectNamespace.Utils). A ststic class with public static members for conversions, formatting, calculations...
Put this class in BLL (Business Logic Layer) most of the time but sometimes you need different Utils for different layers.
Comment: BLL is not for validation. It's a good place for putting Logic. Most of the time `Utils` best place is there in compare to `UI` or `DAL`
Answer: Assuming an image is an input - inputs usually come into a system through:

The frontend interface / UI.
A backend interface (service).
An API call.

If the input is specific to - say the UI - then that would suggest it was a UI specific thing and should sit there.
The same rule / principle applies for the other input 'channels'.
if the API being called is in the BL then that's where it might sit.
Where Yousefvand is coming from (and which I agree with) is that if more than one component is using it then it's probably be a good candidate for putting in some osrt of reusable library.
So...

Conversions can be done in the first layer ( UI ) ?

Yes if the what you're converting is specific to the UI / UI technology being used; otherwise you could but probably shouldn't - in this case you'd probably be better implementing your converter in a utility.


Configuring SQL Report Server to work with Team Foundation Server using Internet URLs

Question: Currently we have SQL 2012 with Reporting Services, Team Foundation Server 2012 and SharePoint Server 2013 on our single Windows Server 2012 machine. We are a small company and we have some developers who work from home. We do not have VPN nor domain controllers yet.
We wanted to expose our TFS Agile reports through Sharepoint using Windows authentication.
We created a subdomain, configured Sharepoint Alternate Access Mapping and now our devs are able to open our project web site (created automatically by TFS) from the Internet after they enter their Windows credentials.
The only problem is that our TFS Agile Dashboard on Sharepoint fails to render reports. The Web browser shows a standard error page because it is trying to access our internal URL for report server.
So we went to the report server config and added our external subdomain for both Report Web Service and Report Manager. Now we are able to access them both from external computers through Internet Explorer.
The problem is that we cannot access report server when we configure TFS Reporting settings.
TFS correctly pulls new public URLs for both Web service and Report Manager. Everything works fine if we select the public URL for Report Manager and hit OK, so TFS is able to access the Report Manager without any issues. But when we pick the public URL for Web service and hit OK, TFS asks for credentials (we tried to enter the server Admin credentials to be sure) and then fails with a message:
<code>The server you specified was not found or cannot reached.
The specified configuration is invalid. Update the fields as indicated for each tab.
</code>
Essentially, /Reports folder is working and can be assigned on TFS, but only /ReportServer fails.
Also, we are not able to access any of our reports nor Sharepoint sites on the server itself when entering our public URL - it asks for credentials three times and then dies. I guess, maybe that's because of some IE settings on the server, because from our other computers we are able to open all these web sites on IE right after we enter our credentials one time.
What's wrong with TFS and Reports Web Service? How do I connect them both?
Answer: After long long search, I found this one:
http://support.microsoft.com/kb/926642
It seems, Microsoft has deliberately blocked loopback authentications. That's why I cannot configure my TFS and Sharepoint URLs as needed - they just fail to authenticate.


iOS JSON parsing returns null

Question: I am parsing a JSON that looks like this:
    [
  {
  "Country of Build":"Belgium",
  "Shipbuilder":" Boelwerf",
  "Hull #":" 1487",
  "Ship Name":" Methania",
  "Shipowner":" Distrigas",
  "Operator":" Exmar",
  "Delivery":"Oct-78",
  "Flag":" Belgium",
  "Class":" LR",
  "Power Plant":" Steam",
  "HP":" 45,000",
  "Speed": 19.0,
  "Cargo System":" GT NO 85",
  "# of Tanks": 5,
  "Capacity ":" 131,235",
  "Price":
  },
  {
  "Country of Build":"China",
  "Shipbuilder":" Cosco Dalian",
  "Hull #":"  ",
  "Ship Name":"  ",
  "Shipowner":" CNOOC Energy",
  "Operator":"  ",
  "Delivery":" 1Q15",
  "Flag":"  ",
  "Class":" AB/CC",
  "Power Plant":" DFDE",
  "HP":"  ",
  "Speed":  ,
  "Cargo System":" GT NO 96",
  "# of Tanks": 4,
  "Capacity ":" 28,000",
  "Price":81
  }, ---8000 more lines--- }]

I have a custom object in which I want to parse the objects into, which looks like this:
.h
@interface LNGVessel : NSObject

@property NSString *countryOfBuild;
@property NSString *shipBuilder;
@property NSString *hull;
@property NSString *shipName;
@property NSString *shipOwner;
@property NSString *shipOperator;
@property NSString *delivery;
@property NSString *flag;
@property NSString *shipClass;
@property NSString *powerPlant;
@property NSString *hp;
@property NSString *speed;
@property NSString *cargoSystem;
@property NSString *numOfTanks;
@property NSString *capacity;
@property NSString *price;

-(id)initWithDict:(NSDictionary*)dictionary;

@end

and a .m like this
-(id)initWithDict:(NSDictionary *)dictionary{
self = [super init];
if(self)
{
    self.countryOfBuild = [dictionary objectForKey:@"Country of Build"];
    self.shipBuilder = [dictionary objectForKey:@"Shipbuilder"];
    self.hull = [dictionary objectForKey:@"Hull #"];
    self.shipName = [dictionary objectForKey:@"Ship Name"];
    self.shipOwner = [dictionary objectForKey:@"Shipowner"];
    self.shipOperator = [dictionary objectForKey:@"Operator"];
    self.delivery = [dictionary objectForKey:@"Delivery"];
    self.flag = [dictionary objectForKey:@"Flag"];
    self.shipClass = [dictionary objectForKey:@"Class"];
    self.powerPlant = [dictionary objectForKey:@"Power Plant"];
    self.hp = [dictionary objectForKey:@"HP"];
    self.speed = [dictionary objectForKey:@"Speed"];
    self.cargoSystem = [dictionary objectForKey:@"Cargo System"];
    self.numOfTanks = [dictionary objectForKey:@"# of Tanks"];
    self.capacity = [dictionary objectForKey:@"Capacity"];
    self.price = [dictionary objectForKey:@"Price"];

}
return self;
}

Now, I have a local .json file with about 8000 lines, 450-ish objects.
I parse them to an array in a UIMutableArray category, which looks like this:
//.h
 @interface NSMutableArray (LNGVessels)
+(NSMutableArray*)allVessels;

@end

//.m

    @implementation NSMutableArray (LNGVessels)

+(NSMutableArray*)allVessels{
    NSMutableArray *array;

    NSString* pathToFile = [[NSBundle mainBundle] pathForResource:@"Vessels" ofType: @"json"];

    NSData *data = [[NSData alloc]initWithContentsOfFile:pathToFile];

    id JSONArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    NSEnumerator *enumerator = [JSONArray objectEnumerator];
    NSDictionary* item;
    while (item = (NSDictionary*)[enumerator nextObject]) {

        LNGVessel *vessel = [[LNGVessel alloc]initWithDict:item];
        [array addObject:vessel];
    }
    return array;
}
@end

The problem? this doesn't work, it always returns null. I have logged the NSData object, which returned all the json contents (in hex)
I thought that it might be the JSON's fault, so I checked http://jsonlint.com/ and pasted the whole thing. I got an error on
Parse error on line 18:
...      "Price":     },    {        "Co
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

which suggests I need to fix that. But still, I would assume that my code would just insert nil for that argument.
Oh, and I realised that JSONSerilaziation got an error parameter. That logs
 Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (Invalid value around character 376.) UserInfo=0x170463380 {NSDebugDescription=Invalid value around character 376.}

Answer: As you already noticed, your JSON data is invalid. In that case
id JSONArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

just returns nil. (It does not omit or skip invalid entries.)
And you also forgot to alloc+init the NSMutableArray *array.
Answer: i would do it like this:
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
for (NSDictionary *dict in array) {
    LNGVessel *vessel = [[LNGVessel alloc]initWithDict:dict];
    ....
}

Comment: I did, but some other SO question I came by suggested using fast enumeration like such, so I assumed it was better.
Answer: Your JSON should be
{
...
"Price":null
...
}

According to Apple documentation:

JSONObjectWithData:options:error:
error If an error occurs, upon return contains an NSError object that
  describes the problem.
Return Value A Foundation object from the JSON data in data, or nil if
  an error occurs.

Setting error parameter to nil might not be helpful at times like this.
Comment: I pasted the source into EXCEL, exported it as CSV, parsed CSV to JSON, somewhere along the way, null's got inserted instead of nothings. Code works now, JSON was the sinner.
Comment: Its the json docs fault? Is there any tool to mass insert nil objects to empty arguements, doing so to possibly 8000 lines would be a pain.
Comment: I guess it'd be better you make sure that's the problem, first test your code with smaller and totally valid JSON object, if it is ok then sharpen your regex skills :) you can look for invalid patterns and replace them with regex as you know.

iOS JSON parsing returns null


Getting a mach-o plug-in bundle's path from within a dylib

Question: I'm trying to get the executable path of a plug-in bundle which is loaded by another process, when running a dylib module.
When running a non-plug-in bundle e.g. a regular application, it's easy enough to call
<code>[[NSBundle mainBundle] executablePath]</code>. However, with a plug-in bundle this returns the path for the hosting app, not of the plug-in bundle.
In that case, the following tricky code can be used to get the executable's path:
<code>#include <dlfcn.h>

const char* getExecutableFile()
{
    Dl_info exeInfo;
    dladdr((void*) getExecutableFile, &exeInfo);
    return exeInfo.dli_fname;
}
</code>
This returns the correct bundle executable's path, except when calling this function from within a function exported by a dylib, which returns the dylib's path.
Is there any way to get the bundle executable's path consistently even from within a call to a function in a different module?
Answer: You can do that if you use the dyld APIs directly. In fact, it's pretty easy. The following code dumps all the images, with their offsets (and ASLR value).
<code>#include <mach-o/dyld.h>

// List all mach-o images in a process
uint32_t i;
uint32_t ic = _dyld_image_count();
printf ("Got %d images\n",ic); for (i = 0; i < ic; i++)
{
    printf ("%d: %p\t%s\t(slide: %p)\n", i,
            _dyld_get_image_header(i),
           _dyld_get_image_name(i),
            _dyld_get_image_slide(i));

}
</code>
So naturally, you can strstr() your bundle name in the char * returned by dyld_get_image_name(), and you'll get the full path of it.
Reference: "Mac OS X and iOS Internals" (Wiley, 2012), pg 123.
Comment: Not sure if this helps or not, but the NS- classes are typically wrappers for CF- backends, all of which are open source, E.g. http://opensource.apple.com/source/CF/CF-550.13/CFBundle.c
Comment: That's cool! I'm actually just reading this book :) But I don't think it answers what I'm looking for. I'm looking for a general replacement for the -executablePath of NSBundle, but which will return the correct path also when called from within a plug-in bundle or from a function in a dylib called by plug-in bundle.
Comment: Apple's executable path of the NSBundle is their API, which is actually built on top of this. The method presented above shows you how you enumerate all paths of all Mach-O objects (executables, libraries and bundles alike). You can easily refactor this into your own function (in fact passing in [NSBundle exeutablePath] to look for it in the image list), but won't be able, I believe, to find anything exported by NSBundle.
Comment: I'm not looking for a replacement method within NSBundle, just for similar functionality (which will return the correct path also when called from within a plug-in bundle or from a function in a dylib called by plug-in bundle). The method should not know in advance what the plug-in bundle name is - that's the whole point of calling the method.
Comment: The open source code shows that CFBundleGetMainBundle relies on the process path to return its result, which is the evident behavior, and no good for the dylib from within a plug-in bundle case.


How to add a permission : reorder Taxonomy terms

Question: I need some roles to be able to edit and add terms of specific vocabularies, but not to reorder them. How can I add the permission reorder foo vocabulary terms, reorder bar vocabulary terms... with a module or programmatically ?
AFAIK edit terms permissions immediately give you the permissions to reorder terms also.
I already tried these modules below but none implements such permission.
Vocabulary Permissions Per Role

Allows adding to/editing terms of/removing terms from vocabularies per
role... adding terms to a vocabulary but not to another, reordering/editing terms of a vocabulary but not another's, etc.

Says so, but reordering /editing come together.
Taxonomy access fix

adds 1 permission per vocabulary: "add terms in X"
changes the way vocabulary specific permissions are handled
changes the Taxonomy admin pages' access checks
alters the vocabularies overview table to show only what you have access to edit or delete

The module does what native Taxonomy lacks: more specific Taxonomy
permissions (and checking them correctly).

Thank you.
Answer: You need to implement hook_form_alter  and remove the Sort alphabetically button based on the role.
Edit: Something like this (tested)
function mymod_form_alter(&$form, &$form_state, $form_id) {
  if (in_array('userrole', $user->roles) && ($form_id == 'taxonomy_overview_terms') {
    unset($form['actions']['reset_alphabetical']);
    drupal_add_css(drupal_get_path('module','mymod').'/css/mymod.css');
  }
}

and in css/mymod.css, do
.handle,.tabledrag-toggle-weight {display:none;}

This hides the Reset to alphabetical button, drag handles, and Show row weights link.
Comment: Thank you. What about the drag and drop UI to reorder almost anything in Drupal including taxonomy terms ? And its alter ego "show row weight" ?
Comment: You can also use hook_form_alter for that.
Comment: @Kojo I updated my answer.
Comment: @Kojo Edits should not change an answer's code in a radical way. If you have better code, write your own answer.
Comment: Thanks Kartagis, for this turn around. By the way, anybody with Firebug or similar could reorder the terms anyway. I posted another solution which really _gives or not_ a permission to reorder vocabulary terms
Answer: After digging a bit more into permission implementation, this is how I solved this issue, in combination with Taxonomy access fix.
/**
 * Implements hook_permission();
 */
function MYMODULE_permission() {
  return array(
    'reorder_taxonomy_terms' => array(
      'title' => t('Reorder taxonomy terms'),
      'description' => t('Allows users to reorder taxonomy terms.'),
    ),
  );
}

/**
 * Implements hook_js_alter().
 */
function MYMODULE_js_alter(&$javascript) {
  if (!user_access('reorder_taxonomy_terms')) {
    unset($javascript['misc/tabledrag.js']);
  }
}

/**
 * Implements hook_form_FORM_ID_alter();
 */
function MYMODULE_form_taxonomy_overview_terms_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (!user_access('reorder_taxonomy_terms')) {
    foreach($form as $k=>$v){
      if(substr($k, 0, 3) == 'tid'){
        unset($form[$k]['weight']);
      }
    }
    unset($form['actions']['reset_alphabetical']);
    drupal_add_css(drupal_get_path('module','vts_taxonomy_permissions').'/MYMODULE.css');

  }
}

/**
 * Implements hook_FORM_ID_alter();
 */
function MYMODULE_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
  global $user;
  if (!user_access('reorder_taxonomy_terms')){
    unset($form['relations']['weight']);
  }
}

In MYMODULE.css
/* Hide reorder help text */
#block-system-help {
  display: none;
}


Should I play a B♭ or a B♭♭

Question: There's a passage I encountered in a piece I was practicing, the key signature was E♭ Major, which contains 3 flats: E♭, B♭, and A♭.

The passage looked like this:

In that passage, there is a B♭. So should it be a normal B♭ or a B♭♭
Any hints would be appreciated. :)
Answer: Is there a B♮ in the previous measure? I'd guess there is, and the flat is just a courtesy to remind you of the return to normal key signature.
By definition, courtesy accidentals are not mandated by notation rules and the score is unambiguous without them (they're there because somebody thought it would make it easier to read). Sometimes they're printed inside () brackets to avoid just this kind of head-scratching—good practice IMO.
Answer: B♭. For B there would need to be an actual double flat symbol ().
It's impossible to tell for sure as the example doesn't contain preceding music, but it's probably either a courtesy accidental, or there was some other accidental (perhaps B♮) earlier in that measure.
Comment: There was a B natural before that measure, thanks
Answer: There is another 'B' in another octave later in the bar. With no 'accidental'. That says to me that the one on the middle line was probably B♮ in the previous bar (the other wasn't there at all).
So, it's probably a courtesy accidental, there to remind the reader that the barline has actually done its job of cancelling the prior natural on B. It really ought to have brackets round - (♭)  which then makes it very obvious.
It certainly would not be B♭♭, as the accidental before any note makes it clear what that note should be. If the composer or printer wanted B♭♭  it would have been written exactly as that.

Should I play a B♭ or a B♭♭


Convert Caffe CNN to Feature Extractor

Question: I have to use a CNN model to extract features from images. I am using a trained model called Caffenet.
On Caffe, it is very easy to extract features after running the image through the CNN model. For example, if I want features extracted by the "conv5" layer, I simply call the method:
features = net.blobs['conv5'].data[0, : , : , :]

However, the tricky part is I need to use a 3rd party conversion tool to convert the model so that it can run on my mobile device. After converting the model, I cannot access the output of layers inside the model. I only get the final output, which in this case are classifications, and they are not what I need.
To get the model directly output features from the "conv5" layer, which is the final convolutional layer, I went inside the deploy.prototxt file and deleted all layers after the "conv5" layer, so "conv5" effectively became the final output layer. However, after doing so, the feature values I get are completely different from the feature values I had gotten before I changed the prototxt file.
My suspicion is that even though I changed the architecture by deleting layers in deploy.prototxt, I cannot change the weights inside the caffenet.caffemodel file. I am not sure why this would be a problem since the weights for layers after "conv5" would just not be used. I am not sure why this would change the output of "conv5".
How I can change a trained model to directly output features from the final convolutional layer?
Comment: it is difficult to answer such question since it is not clear what "conversion" your model is undergoing when you port it to mobile. Generally speaking, removing top layers from `deploy.prototxt` should not affect the feature values of preceding layers. So, your `conv5` features should remain the same. The usual suspect in this case is the input transformation: does your ported model subtract mean and scale the pixel in the **exact** same way as your original model? Do you get **exactly** the same class predictions (probabilities) using the ported mobile model?
Comment: look at [this answer](https://stackoverflow.com/q/38312250/1714410), and [this one](https://stackoverflow.com/a/40480511/1714410),
Comment: BTW, do you have `BathNorm` layers in your model?
Answer: One reason may be that some layers after the "conv5" layer will update or change the top blob of conv5. These layers include relu layers or batch_norm layers since these layers usually use in-place operations. So you'd better check the deploy prototxt and keep batch_norm and relu layers after conv5  unchanged.
Comment: I kept the relu layer and now it's outputting correctly!

Convert Caffe CNN to Feature Extractor


Inflation Index

Question: The inflation index of a country $A$ in $1995$ relative to $1990$ was $5$. Meaning that the ratio of dollars spent during $1990$ for goods compared to dollars spent for same goods is $1:5$. In country $B$ the inflation index is $9$ for the same period. In country $C$ the inflation index is $1$3. A pair of shoe cost $ \$72$ more in $1995$ than in $1990$ in all three countries. What was the ration between the price of pair of shoe in country $A,B,C$ in $1995$.
I cant get the concept of inflation index.
Comment: in the first line, "relative to 1990" is it?
Comment: It means that if something cost one dollar in each country in 1990, then in 1995, it cost five dollars in $A$, nine in $B$, and 13 in $C$.
Comment: Yes sorry for the typo its edited
Comment: the answer is 30:27:26
Answer: Let the cost of the shoe be x , y , z in country A, B , C respectively in 1990.      In 1995, they became  5x, 9y, 13z   due to inflation(that's what the index meant). Now, the difference is 4x, 8y, 12z which is all the same 72$ .   From this, x=18 ; y= 9 ; z=6 ;     5x=90; 9y = 81; 13z= 78    ;   ans- 90:81:78 = 30:27:26

Inflation Index


Confusion of the decidability of $(N,s)$

Question: In some context the PA has only the successor operator $'s'$, but in logic we always refer the structure of PA is $(\mathbb{N},0,1,s,+,\times)$. I believed the theory of the two sturctures are equivalent because I believed that $ '+'$and $  '\times'$ are definable in $(\mathbb{N},s)$. Then I concluded that the theory of $(\mathbb{N},s)$ is not decidable.
But now I'm not quite sure about this, in addition, what is the decidability of the theory of $(\mathbb{N},+)$? Thanks for your help.
Comment: @Chao: Yes, PA axioms are complete for the $(\mathbb{N},s,+)$ fragment. To see this it is enough (because Pressburger arithmetic is complete) to check that the fragment of any PA-model satisfies the sentences in some axiomatization of Pressburger arithmetic (see for example http://en.wikipedia.org/wiki/Presburger_arithmetic )
Comment: Decidable and decidable.
Comment: @AndréNicolas So $'+'$ and $'\times'$ are not definable in $(N,s)$? Are PA axioms for $(N,s)$ complete?
Comment: Am uncertain about Peano axioms, But the set of sentences that only involve $+$ and are **true** in $\mathbb{N}$ is recursive.
Answer: Here's a straightforward way to show that $+$ is not definable relative to $\text{Th}(\mathbb{N},s)$.

$0$ is definable in $\text{Th}(\mathbb{N},s)$, so $\text{Th}(\mathbb{N},s)$ and $\text{Th}(\mathbb{N},s,0)$ have the same definable sets (i.e. any formula in the language $\{s,0\}$ is equivalent to one in the language $\{s\}$ by replacing any occurrence of $0$ with its definition). In particular, it suffices to show that $+$ is not definable in $\text{Th}(\mathbb{N},s,0)$.
$\text{Th}(\mathbb{N},s,0)$ has quantifier elimination. Showing this is not too hard.
Now we want to examine all the formulas in three variables ($x$, $y$, $z$) and check that none of them picks out the graph of $+$ (i.e is the formula $x+y=z$). Well, any formula in three variables is equivalent to a boolean combination of atomic formulas. Since the only relation around is $=$, any atomic formula looks like $s^n(a) = s^m(b)$, where $a$ and $b$ are one of $x$, $y$, $z$, or $0$. So any such formula expresses that some variable has a particular value, or that some pair of variables differ in value by some fixed amount. It only takes a bit of thinking to convince yourself that no boolean combination of these can define $+$.

You said in a comment that you only know two ways of showing that something is not definable: decidability arguments and automorphism arguments. It's true that these are the main tricks, but there's a third, more basic way - actually characterizing all the definable sets. This is exactly what quantifier elimination helps us do.
Comment: Nice proof, +1 of course!
Answer: The theory of the successor function, and the theory of addition, are both decidable. For details about the theory of addition, please see Presburger Arithmetic.
Multiplication is not definable in Presburger arithmetic.
Comment: Thank you, the only question left is what about the definability of '+' in $(N,s)$?
Comment: Addition is not definable from successor. I would have to think for a while to recall/reconstruct the proof. Definability is a very narrow notion in first-order logic. Note that the answers are completely different in second-order logic.
Comment: How do show that addition is not definable by successor if the theories of them are both decidable?
Comment: Thanks, in fact I only know two methods to prove a relation is not dedinable: by a decibability arguement, or construct a automorphism which does not preserve the relation. Neither works for this case.
Answer: Let me address one way (using some powerful machinery, but well-known) to show that addition is not definable in $(\mathbb{N}, s)$. We will see that $(\mathbb{N}, s)$ and $(\mathbb{N}, +)$ have different decidability behaviour with respect the monadic second order language, this is enough.
As others have pointed out it is known that the first-order theory of  $(\mathbb{N}, s)$ is decidable, and the same is true for  $(\mathbb{N}, +)$. On the other hand, it is also a famous result of Buchi the fact that the monadic second order theory of $(\mathbb{N}, s)$ is also decidable (it is worth noticing here that Rabin generalized this result to the full binary tree). On the other hand, it is not difficult to check that multiplication $\cdot$ is definable in the monadic second order theory of $(\mathbb{N}, +)$; as a hint I suggest to first show that the binary divisibility relation "$a | b$" is definable. Thus, from the undecidability of the first-order theory of  $(\mathbb{N}, +, \cdot)$ it follows that it is also undecidable the monadic second order theory of $(\mathbb{N}, +)$.
Comment: Thanks I admit that I have never heard 'monadic second order logic' before, I can't find its definition on wiki, but I'm quite interested. Can you give some reference on this subject?
Comment: @Chen: Take a look at http://en.wikipedia.org/wiki/Second-order_logic , and then you can read the following "old" survey by Gurevich http://projecteuclid.org/euclid.pl/1235417279


Show block on nodes and only for node author

Question: I am building a simple classifieds style site. Instead of using straight email, I was thinking about creating a simple "make offer" node type. Create a few basic fields (reference to classified listing, message, will buy for X price, would trade, etc...).
Then create a view block and put the nid in to limit those "offer" nodes to only the node being viewed. However, I would like to do two things.
1) Limit the block to only be viewable to administrators and the node author themselves, other users should not be able to see the other offers.
2) Make it so going to /node/{nid} that is an offer content type is hidden from view so users can't just bypass the block and hit the nid of the offer node.
Any help on how to implement this? I am trying to do it with no added modules.
EDIT: The access to the block should be as follows:
Administrators: Should see all "offer" nodes in the block regardless of who they are from.
Listing Author: Should see all "offer" nodes in block.
Offer Author: Should only see "offer" nodes they have submitted to "listing" nodes. They shouldn't see any other "offer" nodes from any other user.
Answer:
In views, add a relationship on "Content: Author", then add a filter "User: Current" and configure it so it uses the relationship you added and has "Is the logged in user" = "Yes".
Install the Rabbit Hole module and its node sub module and configure it (on the edit page for the offer content type) to give a 404 error for those nodes. Then configure the rabbit hole permissions so that admins can bypass rabbit hole if you need that ability. I would recommend adding this module as opposed to writing some custom code to do this.
Comment: @Brandon: writing *Fantastic* is ... *Fantastic*, but are you aware of what's written in [Someone Answers](http://drupal.stackexchange.com/help/someone-answers) ? Moreover, the edited version of your question makes it a cameleon question (= solution to the  problem, changes the problem) ... it makes this answer at least look incomplete. Instead you should have posted a followup question (with a link to this one if you want). And the edit you added looks to me like you're mixing block visibility (I think) with block content (not sure what it actually is). Just trying to "help" a bit, ok?
Comment: Fantastic! Thank you so much. Rabbit Hole was exactly what I was looking for.
Comment: Yeah it's a really poorly named module in terms of making it easy for people to find via google.
Comment: Yeah, it should be something relateable like "Custom Node Views" or "Block Node Paths"...or something like that.
Comment: rooby, I am still having a bit of trouble with this. I have updated the original post with the access requirements and I have the exported view here: http://pastebin.com/w7yMNF9S

Is there something I am missing? Any help would be greatly appreciated. Thank you.


Local minimum and maximum of the function

Question: Can anyone help me to solve the following question?
maximize and minimize the function $(10-x)(10-\sqrt{9^2-x^2})$ over $x\in[0,10]$
This is a high school question, so is there any simple trick help solve it? Thanks!
Comment: Is taking the derivative allowed?
Comment: @joriki: I don't even see a reasonable calculus approach, at least using hand computations (which I've put some effort into), although assuming I typed things correctly, WolframAlpha says all extrema are quadratic irrationals. Maybe someone can do something with the following observation. Consider the circle $x^2 + y^2 = 81$ inside the square with sides $x = \pm 10$ and $y = \pm 10$. The question asks for the extrema of the product of a point's distances from the upper side and the right side of the square as the point traces through 1st quadrant portion of the circle.
Comment: You could write $u=x^2$, $x=\sqrt u$ to get $(10-\sqrt u)(10-\sqrt {81-u})$, which simplifies the derivative somewhat, but then you have to treat $x=0$ separately. You could then use the symmetry by writing $u=81/2+s$ to get $(10-\sqrt{81/2+s})(10-\sqrt{81/2-s})$, which allows you to guess the maximum at $s=0$, corresponding to $x=\sqrt{81/2}$, but I don't see how you could get the two minima without actually differentiating the function. By the way, assuming we're talking about a real-valued function, this function is ill-defined for $x>9$.
Comment: How do we talk about the maximum or minimum of a function when it can have values in both the reals and the complex numbers?
Comment: @Dave: Starting from the form $(10-\sqrt{81/2+s})(10-\sqrt{81/2-s})$, you can take the derivative, multiply through with $2\sqrt{81/2+s}\sqrt{81/2-s}$, multiply out, take the two remaining square roots to one side, square, take the remaining root to one side and square again. The result is a biquadratic equation for $s$ with the solutions $s=0$ and $s=\pm5\sqrt{62}$, so the minima are at $x=\sqrt{81/2\pm5\sqrt{62}}$, which W|A simplifies to $5\pm\sqrt{31/2}$. Not a well-chosen question for high-school students if you ask me... :-)
Comment: @André: Yes, but it was a high-school question, not a contest question :-) Contest kids are almost by definition not the measure of what is "very easy".
Comment: @Zhuqing Yu: It turned out to be very easy, no calculus, no trig, only machinery available in middle high school in North America, presumably much earlier elsewhere.
Comment: @joriki: Maybe mildly tricky, but very elementary, no tools needed, calculations easy.
Comment: @André: Well done for elementary, no calculus, no trig, only high-school machinery -- but "very easy"? If I offered you a bet on the fraction of high school students who are able to find this solution, at what fraction would you accept even odds? :-)
Comment: @Joriki: A contest kid could do it.  I chose the style of write-up to highlight symmetric functions.  Will test on our Olympiad Math Circle group.
Comment: I deleted my answer because as pointed out by Gerry Myerson the method explained in it fails in general, although not in this case, where the local maximum is reached at $x=\frac{9}{2}\sqrt{2}$. If $w+h$ is a constant and both $w$ and $h$  are positive, then the max of $wh$ does occur for $w=h$. @Gerry Myerson: Thanks!
Comment: @Americo, just another example of a beautiful theory shot down by an ugly fact.
Comment: @Gerry: You're right!
Answer: We give a short argument for both maximum and minimum.
To bring out the symmetry, let $y=\sqrt{81-x^2}$.
We study the behaviour of $(10-x)(10-y)$, that is, of
$$xy-10(x+y)+100.\qquad\qquad\text{(Expression $1$)}$$
We will find the maximum and minimum values of Expression $1$, given that
$x^2+y^2=81$ and $x \ge 0$, $y \ge 0$.
Let $w=x+y$ and $xy=v$.
We are interested in the behaviour of
$$v-10w+100. \qquad\qquad\text{(Expression $2$)}$$
But since $(x+y)^2-2xy=x^2+y^2$, we have $w^2-2v=81$.
So we are interested in the behaviour of
$$\frac{w^2-81}{2} -10w +100, \quad\text{that is, of}$$
$$\frac{1}{2}\left(w^2-20w+119\right).  $$
Complete the square.  We get
$$\frac{1}{2}\left((w-10)^2+19\right).\qquad\qquad\text{(Expression $3$)}$$
Now it's over. There is a local minimum at $w=10$.
The minimum value is $19/2$.
The maximum is reached where $w$, that is, $x+y$, reaches a maximum subject to $x^2+y^2=81$.  Since $(x+y)^2+(x-y)^2=2(x^2+y^2)=162$, the maximum value of $(x+y)^2$, and hence of $x+y$, occurs where $x=y$.
We can if we wish find the values of $x$ at which the minimum is reached.  We need to solve the system $x+y=10$, $x^2+y^2=81$. That gives $2xy=10^2-81=19$, so $(x-y)^2=81-19=62$, and therefore $x-y =\pm \sqrt{62}$, and now we can find $x$ and $y$.
Note on Symmetry:  All the way through, we have preserved symmetry between $x$ and $y$. We introduced symmetry in the initial setup, and every step involved only symmetric functions of $x$ and $y$.  Symmetry allowed the easy identification of $x+y$ as a key parameter.
The formal algebraic symmetry comes, in this case, from the underlying geometry. For the problem posed by the OP is fundamentally geometric. It has to do with the interaction between a circle and a rectangular hyperbola.
Comment: Good point! This looks much easier.
Answer: I think a "precalculus"-typed solution is bound to be tedious, but you may try the following approach.

Note that the function is non-real on the interval (9,10], so the function domain should be first corrected to [0,9].
Put $x=9\sin\theta$ and transform the objective function to $(10-9\sin\theta)(10-9\cos\theta)$ with $0\le\theta\le 90^\circ$.
So, up to a multiple, the objective function is of the form $(t-\sin\theta)(t-\cos\theta)$, where $t=\frac{10}{9}$ and $0\le\theta\le 90^\circ$.
Put $\theta= 45^\circ+\phi$. Then, up to a suitable multiple, the objective function takes the form of $(u-\cos\phi-\sin\phi)(u-\cos\phi+\sin\phi)$, where $u=\frac{10\sqrt{2}}{9}$ and $-45^\circ\le\phi\le 45^\circ$.
The function is equal to $(u-\cos\phi)^2-\sin^2\phi = 2\cos^2\phi-2u\cos\phi+(u^2-1)$, which is quadratic in $\cos\phi$. Now you can try to find its maximum and minimum with $\cos\phi\in[\frac{1}{\sqrt{2}}, 1]$.
Edit: Having $\cos\phi$, we may compute $x = 9\sin(\phi+45^\circ)=(9/\sqrt{2})(\cos\phi\pm\sqrt{1-\cos^2\phi})$.
Comment: Thanks, probably I should try to use trigonometric function
Comment: Nice solution. This is actually slightly suggested by how the function is written ($81$ as $9^2$), so perhaps this is how they intended it to be solved.
Answer: Let $f(x)=(10-x)\cdot (10-\sqrt{81-x^{2}})$. First solve for $f'(x) =0$. Then find $f''(x)$. If $f''(x) < 0$, then you have a maximum and if $f''(x) > 0$, then you have a minimum.
Please see:

http://en.wikipedia.org/wiki/Second_derivative_test
http://en.wikipedia.org/wiki/First_derivative_test
Comment: In any case, you don't need the second derivative. On a closed interval, the max/min will occur at endpoints or critical points.
Comment: The question got categorized as an algebra question and mentioned "high school", so are derivatives allowed for an answer?
Comment: @Doug: Well, other users can see other ways of doing it. WHile looking at this question, I didn't really see the tag.
Answer: Perhaps this is a graphing question. Some high school teachers allow the use of calculators to get numerical approximations for certain problems. I can't see how else this problem is possible without calculus.
Comment: I agree with the graphical interpretation. The maximum and minimum corresponds to the maximum/minimum area of the rectangle
Answer: Generally, one can note the following:
There are single, double and triple roots.
For a simple root of the graph intersects the x-axis Example x1=0
With a double root touch it and  indicating an extreme point. Example x1=0,x2=0
Tripple a root point is a saddle point Example x1=0,x2=0,x3=0.
if your equatiion:
$f(x)=(10-x)\cdot (10-\sqrt{81-x^{2}})$
$f(x)=0$
$(10-x)=0 $
if $ x=10$
$(10-\sqrt{81-x^{2}})=0$
$10 = \sqrt{81-x^{2}}$ | ^2
$100 = 81-x^{2}$
$-19 = x^{2}$
$\sqrt{-19}=x$ ERROR ! you will get complex roots... not useable for Maxima and Minima
root = 10
derivation of $f(x) = y$ is
$y' = - \frac{(-10 + x) x)}{ \sqrt{81 - x^2}} + \sqrt{81 - x^2} -10$
To get the extrema you had to $y'=0$
Xe = root(s) of $y'=0$
and put the roots (Xe) if any there in $y''(Xe)$
$y''(Xe) < 0 $ it's a Maximum
$y''(Xe) > 0 $ it's a Minimum
$y''(Xe) = 0 $ Xe is not an extrema
Comment: The derivative is wrong, and some of the rest is hard to follow. It's not apparent what you're deducing from what (i.e. what the "if"s refer to) and what your variable names mean (x1, x2, x3). Also, there are roots of any multiplicitly, not just single, double and triple ones.
Comment: i've corrected the derivation Xe is the variable name for the extrema (Min/Max). @jorki yes there are three roots but for maxima and minima of an curve you take onle the non complex parts for example $\sqrt{-9}$  is a complex result 3i (i is an imaginary number (don't know the right english word))
Comment: Sorry for everyone. I should narrow x to [0,9].


PrintTo for a pointer in Google Test

Question: I can specify how to display the content of an object if a test has failed. To do it, I define the function PrintTo for the class. The result is as desired (the string MyObject as object):
x.cpp:17: Failure
Value of: foo1
Expected: has foo <MyObject as object>
  Actual: <MyObject as object> (of type Foo)

Unfortunately, I can't find how to do the same for a pointer to the object. Instead of the custom string MyObject as pointer I get the default output:
x.cpp:22: Failure
Value of: pfoo1
Expected: has foo 0x8058330
  Actual: 0x8058320 (of type Foo*)

As a workaround I can dereference the pointers, but I'd like to know if there is a direct solution, which is to overload PrintTo on a pointer.
#include <gmock/gmock.h>

struct Foo { };

void PrintTo(const Foo& value, ::std::ostream* os) {
  *os << "<MyObject as object>";
}

void PrintTo(const Foo* value, ::std::ostream* os) {
  *os << "<MyObject as pointer>";
}

MATCHER_P(HasFoo, expected, "") { return false; }

TEST(Foo, Object) {
  Foo foo1, foo2;
  ASSERT_THAT(foo1, HasFoo(foo2));
}

TEST(Foo, Pointer) {
  Foo *pfoo1 = new Foo(), *pfoo2 = new Foo();
  ASSERT_THAT(pfoo1, HasFoo(pfoo2));
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

Comment: Have you tried overloading as `void PrintTo(Foo* value, ::std::ostream* os)`? The `const` could make all the difference here.
Comment: Or maybe `PrintTo(Foo *const value, ::std::ostream *os)`?
Answer: As suggested by @AndyG and @olaf-dietsche, the leading const should be removed. These work:
Foo* value
Foo* const value
And these does not:
const Foo* value
const Foo* const value
const Foo*& value

PrintTo for a pointer in Google Test


Possible to run Express/React/Node application on Heroku w/ remote connection to Microsoft SQL Server?

Question: I'm running it fine locally in Node.js using Sequelize/Tedious. This is a test application so database security not required. If not supported on Heroku, any other services that do? Thanks.
Answer: I got it working!! I suspected something was up with my Create-React-App/Express.js boilerplate so I re-created from scratch and then brought over all of my React components. This time I also made sure I had the latest version of Create-React-App too - I was running a much older version. Seems like the older version wasn't playing well with the newer node packages (express, sequelize, tedious, etc.). All is well now.


global name 'ssl' is not defined error while executing aws s3 cp command

Question: Am trying to upload a file to the AWS S3 using the AWS CLI command.
I am using a system with RedHat 4 operating system.
Python version is 2.7.9
OpenSSL version is 0.9.8v 19 Apr 2012.
I have installed the AWS CLI and when I executed the below command I got an error regarding the ssl

[test-user@redhat4 ~]$ aws s3 cp /export/home/test_dir/test_file.txt s3://test-bucket/ --region us-west-2
upload failed: test_file.txt to s3://test-bucket/test_file.txt global name 'ssl' is not defined

Does I have to configure anything regarding the Openssl. Could anyone please help me to resolve this issue as am blocked with this issue for the last few days.
Comment: you can try something like `pip install pyopenssl ndg-httpsclient pyasn1`
Comment: OpenSSL 0.9.8 is probably too old to interop with a modern server. It can be done, but you have to weaken the server's configuration, and Amazon is likely not doing it. That means your option is update OpenSSL to version 1.0.2 or 1.1.0.
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. Also see [Where do I post questions about Dev Ops?](http://meta.stackexchange.com/q/134306)
Comment: At 1st glance, it looks like an error in some _Python_ code. The _ssl_ module failed to import (for some reason? - _\_ssl.so_ could not load _libssl.so_ and/or _libcrypto.so_) but that error got somehow swallowed, and when the _ssl_ module was used it triggered the error. Or of course _ssl_ might refer to something totally different, which would invalidate what I stated before.
Answer: I've solved this problem by installing Python again with SSL support.
I did it on old CentOS 5.1 server - but it will be the same for any other Linux distro. Also, you need Python 2.7.12 at least.
The example is for installing it in opt folder - you can change it. Thanks to sergey for the answer.
# install openssl-devel
yum -y install openssl-devel

# re-install python
cd /opt/Python-2.7.13
./configure --with-ssl  ### this line is the key

make

make install

# re-install AWS
cd /opt

/usr/local/bin/python2.7 awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws

# you can make sure that python was installed with ssl support
# by running this command without error or messages.
python2.7 -c "import ssl"

Answer: I had a similiar error when running aws-okta:
name 'ssl' is not defined
exit status 255

In my case the problem was that my python version and awscli versions were incompatible (see Python version support matrix).
Upgrading my awscli resolved the issue for me.


remove item from python path

Question: I have added a path to the system pythonpath on linux and now i've broken it. How may I remove it ?
[EDIT]
Finally i solved it removing the script that added that path + installing something to rebuild the path.
Answer: not directly programming related but....
'print' your pythonpath to a file, edit the file and export that as your new pythonpath
[edit]
I stand corrected, see Banang answer below
[/edit]
Answer: I don't think there is a concept of Windows-like environment variables in Linux; they are defined in various scripts (e.g. <code>.bashrc</code>). You can edit those in any text editor.
What exactly did you to do "break" your PYTHONPATH?
Comment: I'm sorry, this is just not true: you may not set them in the control panel, but that doesn't mean they aren't environment variables.
Comment: @Andrew Aylett: but am I right that there are no win32-ey magic variables floating around? I.e., that all variables in the shell are defined in a script somewhere?
Comment: A process (even in Windows) gets its environment from its parent process.  Windows has a GUI to let you set what environment is defined by the session; I've not come across an equivalent for Linux (but it would be fairly easy to write).  In general, yes, environment variables will be in shell scripts, but there's no reason why that has to be the case.

remove item from python path