Real locus of a cone or a double cone

Question: If we take the algebraic set of $X^2+Y^2-Z^2=0$, $V(X^2+Y^2-Z^2)$, why do we obtain a single cone, rather than the real locus of $X^2+Y^2-Z^2$ being a double cone? This seems absolutely wrong, since $(-z)^2=z^2$ obviously. Is there something more going on here?
Cones
Comment: I think the locus **is** a double cone. Who says it isn't?
Comment: @bubba Good to hear, see attached picture for James Milnes text excerpt.
Comment: @Timothy I take it you took that excerpt from http://www.jmilne.org/math/CourseNotes/AG.pdf. Indeed I could find no condition in the surrounding context which would reduce this to a single cone. But also note that the *text* does *not* explicitly say that it's a *single* cone. For some people, cones are double cones by default unless stated otherwise. The *figure* is obviously that of a single cone, though, so taken together this looks not merely confusing but plain wrong to me.
Comment: @MvG Thanks!   -T
Answer: I'm answering to get this out of the unanswered queue.
$X^2+Y^2-Z^2=0$ without any further restrictions does describe a double cone.
People who just call it "cone" might be lazy, and might have established a convention where "cone" without qualification means "double cone".
People who call it a "single cone", or depict it as such, are in my opinion just wrong.

Real locus of a cone or a double cone


Firebase Function using Auth getUserByEmail

Question: I'm trying to create a simple Firebase function using Firebase Auth that returns a user's uid if I send it a valid email address. No matter what I change I always get the same error:
Error fetching user data: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type function ([Function (anonymous)])
To call it I use: ...email@example.com
I have tried wyn%40wyn.com as well. The user does exist.

I'm obviously doing something wrong. But what?
   export const checkemail = functions
    .region("deleted")
    .https.onRequest(async (request, response) =>{
      const email = String(request.query.email);
      await admin.auth().getUserByEmail(email)
          .then((userRecord)=> {
            const data = userRecord.toJSON;
            response.send(data);
          })
          .catch(function(error) {
            response.send("Error fetching user data: "+ error);
          });
    });

Answer: toJSON is a method. Therefore it needs brackets: const data = userRecord.toJSON()


The closure/interior of a open/closed half space

Question: Let $X$ be a real topological vector space.
A subset $S$ of $X$ is called an open half-space if there is a continuous linear  functional $f:X\longrightarrow \mathbb{R}$ such that $S=\{x\in X: f(x)>a\}$ for some $a$. S is a closed half-space if there is a continuous linear functiona $f:X\longrightarrow \mathbb{R}$ such that $S=\{x\in X: f(x)\geq a\}$ for some $a$.
I want to show that: The closure of an open half-space is a closed half-space and the interior of a closed half-space is an open half-space.
I am trying to use the following result:  Let $X$ be a TVS and let $A$ be a convex subset of $X$. Then, if $a\in int A$ and $b\in cl A$, then $[a,b)=\{tb+(1-t)a, 0\leq t<1\}\subset int A$. But am having problems with inequalities.
Answer: I am assuming that $f \neq 0$.
Let $C = \{ x | f(x) \ge a \}$ and $U = \{ x | f(x) > a \}$.
We have $U \subset C$, $C$ is closed and $U$ is open.
Let $x_0$ be such that $f(x_0) > a$.
Suppose $F$ is closed and $U \subset F$.
Suppose $f(x_1) = a$ and let $y_n = {1 \over n} x_0 + (1-{1 \over n} ) x_1$, note that $y_n \in U$ for all $n$ and $y_n \to x_1$. Since $F$ is closed we see that $x_1 \in F$ and hence $C \subset F$ and so $C = \overline{U}$.
Now suppose $V$ is open, $V \subset C$ and pick $v \in V$. Since $V$ is open, we must have $v-t x_0 \in V$ for some $t>0$ and so $f(v-tx_0) \ge a$ from which we get $f(v) > (1+t) a \ge a$. In particular, $v \in U$ and so $C^\circ = U$.
Answer: Let me try to answer one part of your question, with the hope that the other is similar. Try to prove that the interior of a closed half-space is an open half-space.
So let $S=\{x\in X: f(x)\ge a\}$ be a closed half space and $V$ be its interior.
If $f$ is a constant function then $S=X=V=\{x\in X: f(x)>a-1\}$, we are done (and $a=0$ but nevermind).
Assume that $f$ is not constant. Then $T=\{x\in X: f(x)>a\}$ is a non-empty open half-space. Clearly
$T\subseteq V$. Suppose $x\in V\setminus T$. Then $f(x)=a$. Take a symmetric
neighborhood $U$ of $0$ such that $x+U\subseteq V$. Take $z\in U$ such that $f(z)>0$. Then $x+z\in V$ but $f(x+z)=a+f(z)>a$, a contradiction. Hence $T=V$.


PHP _GET string query not working with htaccess modrewrite

Question: I am trying to get variables from a query string with the _GET superglobal.  The way I have my project setup now is by using a driver file to access files within my website.  Each included file as a security check that is set by the main index file therefore you cannot directly access nested files.  As an example of my setup, here is how I've configured it.
localhost/index.php
    define('SECURE_CHECK', true);
    include(admin/site.php);

and the included file would only work by being included
admin/site.php
    defined('CHECK_SECURE_ENVOI') or die("Please return to the main page.");

In one of my admin files, I tried creating a clean way to retrieve pages based on URI requests and reinforce this with my .htaccess.
if (fnmatch("*dashboard/", $_SERVER['REQUEST_URI'])) {
    include(DIR_ADMIN_VIEWS . 'dashboard.php');
} else if (fnmatch("*add-post/", $_SERVER['REQUEST_URI'])) {
    include(DIR_ADMIN_VIEWS . 'add-posts.php');
} else if (fnmatch("*edit-post/", $_SERVER['REQUEST_URI'])) {
    include(DIR_ADMIN_VIEWS . 'edit-post.php');
} else if (fnmatch("*view-posts/", $_SERVER['REQUEST_URI'])) {
    include(DIR_ADMIN_VIEWS . 'view-posts.php');
} else {
    include(DIR_ADMIN_VIEWS . 'dashboard.php');
}

Any my .htaccess looks like:
<IfModule mod_rewrite.c>

Options -MultiViews
Options +FollowSymlinks
RewriteEngine on

RewriteCond %{REQUEST_URI} !^/?(resources)/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^(.*) index.php [PT,L] <--- was my original before this issue
RewriteRule ^(.*)$ index.php?edit=$1 [NC,QSA]

</IfModule>

The above code makes so that I can use the url of localhost/admin/add-post/ instead of localhost/core/admin/views/add-posts.php. It also helps reinforce the security in a way that you can't access a page without properly navigating to it.  The problem is now I can't seem to get values through a query string.
I tried following a few guides like this one, but I haven't had success;
Here
My goal is to be able to use a link like localhost/admin/edit-post/?edit=value
Or localhost/admin/edit-post/edit/value and get the value with something like an isset check below:
if(isset(_GET['edit'])) {
$value = isset(_GET['edit'];
//do something
}

I think the problem I have might be related to my admin redirect pages through my if/else, but I am not sure.  Any help would be greatly appreciated.  Thanks.
Comment: So, this issue was with my if/else statement.  The line `} else if (fnmatch("*edit-post/", $_SERVER['REQUEST_URI'])) {` didn't account for anything coming after it.  Adding a * allowed the page parameters to be captured.

As for why it wasn't loading, the page was actually loading the dashboard because it defaulted to the bottom statement when it didn't meet any other conditions.  PHP Web, you were absolutely right in that it all should have worked.  Thanks for the help, the bottom line is attention to detail!
Comment: Can you take the url and split it by '/' and take the last record which will be your value ? I think this will work .
Comment: Could you elaborate or provide an example?  I am not following what you are trying to say.
Comment: Hello Will , when you are passing the value through URL in the format "localhost/admin/edit-post/edit/value" , get the current URL first , then split the string by '/' and take the last record . It will give you the value .
Comment: Sorry, I misunderstood.  The problem is that the page associated to /edit-post/ doesn't load.  So, I could get the value by splitting the URL by this way, but I need to page to continue loading so that I can perform actions with the value.

If I navigate to localhost/admin/edit-post/ then the page loads, if I navigate to localhost/admin/edit-post/edit/value/ the page is blank.  Ulitmately, there is something wrong with htaccess or with the if/then process in my admin file.
Comment: Please re-check with the htaccess , that's why its not loading . By the way , have you put the debug mode on ? What error it is showing ?
Comment: Another method is to keep the URL to "localhost/admin/edit-post/" and pass the value through session or cookies .
Comment: I have debugging on and I am not getting any errors (and the system log isn't showing anything either).  I think it might be an htaccess issue.  I'll try passing through a session and let you know how that goes.
Comment: What is the purpose of `RewriteRule ^(.*)$ index.php?edit=$1 [NC,QSA]`? That would get you the URL path in `edit`, but why are you trying to explicitly pass this as a parameter in the first place? `$_SERVER` gives you access to that value anyway.
Answer: The issue I was faced with was my if/else statement.  As PHP Web stated, the htaccess and query should have all worked properly but because I wasn't allowing the if/else statement to detect anything past the folder (*edit-post/), the query string was never processed.
else if (fnmatch("*edit-post/", $_SERVER['REQUEST_URI']))

By adding a wildcard (*edit-post/*), this allowed everything to process properly.


Openstack Single Physical Network

Question: I am trying to deploy openstack grizzly on a 12 node cluster. I want to use the xen hypervisor. I currently have xenserver installed, and I have 3 virtual machines running Ubuntu 12.04 to use for the control, compute, and network nodes.
Is it at all possible to combine the VM and Management Network into one physical network? I only have one router, so I need to use only one network. I got my setup pretty much working using this guide. But now, I only have access to a single physical network.
Is there a way to have VM and Management traffic on the same network? Security is not a concern at the moment.
Thanks!
Comment: You only have one router?  Your router doesn't support vlans?  Running a compute node inside a virtual machine is probably not a good idea.
Comment: Yes. I should have been more clear. All physical machines are plugged into an  unmanaged switch, which is plugged into a router. The switch does not support vlans. As far as I can tell, running every node in a xen vm is the only way to use xen as the hypervisor.
Answer: Yes, you can use a single physical network, and the best way to do so is to use VLANs to create multiple logical networks on top of your sole physical network. But since you say your switch lacks VLAN support, I recommend you investigate GRE instead. I'm guessing your switch doesn't support VXLAN either, but if it did, that would probably outperform GRE.

Openstack Single Physical Network


How to prove $\sqrt{18}$ is irrational without using proof by contradiction?

Question: I want to know how to prove $\sqrt{18}$ is irrational using method other than proof by contradiction. I have always been taught to prove irrationality using proof by contradiction. So when I was asked this in my exam I was really surprised. Can anyone think of other methods to prove this? Please help. Thank you.
Comment: One finds on wikipedia (https://en.wikipedia.org/wiki/Square_root_of_2#Constructive_proof) a constructive proof of the irrationality of $\sqrt{2}$.
Comment: It is 2 sqrt 3. This is twice an irrational number (if you know that) . You could also use prime decomposition: rational numbers have prime decompositions too.
Comment: @Alephnull 2 sqrt 3 < sqrt 18
Comment: The best way to prove these constructively is to form the continued fraction. Showing that the continued fraction does not terminate is sufficient. Do it for $\sqrt 2$, it's a lot quicker!
Comment: @ahamed 3 sqrt 2.
Comment: @user259242 That's a good idea, but how can we, without contradiction, define the concept of _valuation_, such that we may claim the valuation of $2a^2$ is odd while that of $b^2$ is even? We define it using "_any finite set of natural numbers has a maximum_", which is usually proved by contradiction.
Comment: @ScottBurns but how can one prove that a continued fraction does not terminate? It might terminate after 2 million terms and what then? :q  For $sqrt{2}$ it might be easy to observe that we end up with what we've started, but it might not be so easy for other numbers.
Comment: see the accepted answer for https://math.stackexchange.com/questions/1310014/what-is-the-most-rigorous-proof-of-the-irrationality-of-the-square-root-of-3 It covers the proof for all non-perfect squares and uses contrapositive instead of contradiction.
Answer: $\sqrt{18}=3\sqrt{2}$ and $\sqrt{2}\notin \mathbb{Q}$ (for proofs of this last point not using contradiction, see wikipedia for example).
Comment: Yes but the standard proof of $\sqrt 2 \notin \mathbb{Q}$ uses contradiction.
Comment: This does not use contradiction. In fact, one can show that for any two integers $a$ and $b$,  $\left| \sqrt{2} - \frac{a}{b}\right| \geq \frac{1}{3b^2}$, *without using the law of the excluded middle*.
Comment: I am asking for methods that does not use contradiction.
Comment: @user259242 Right !
Comment: @mathguy I do not use contradiction but only rest on a result which standardly (but not necessarily, see wikipedia) uses it. I bet that this was awaited in your exam
Answer: Interesting question.
There's a short proof using the rational root theorem. (Credit - Wikipedia)
The theorem essentially say that if $q(x)$ is a monic polynomial (https://en.wikipedia.org/wiki/Monic_polynomial), then any rational root of the aforementioned polynomial must be an integer or an irrational number.
Conveniently, take the polynomial: $q(x)=x^2-18$
According to the theorem, it follows that $\sqrt{18}$ is either an integer or an irrational number. Because it is not an integer (for 18 is not a perfect square, i.e. 18 is not the square of an integer), it is irrational.
Comment: You are saying: If $\sqrt{18}$ is rational then it is an integer. So, assume it is rational. Then it is an integer, which is a contradiction since $18$ is not a perfect square. Thus, $\sqrt{18}$ is irrational. This is a proof by contradiction, no?
Comment: @user259242 `So, assume it is rational. Then it is an integer` No, this line of argument said no such. Rather, it said "*is either an integer or an irrational number*", while noting that the former is trivially false, which left $\sqrt{18}$ having to be irrational. There is no proof by contradiction that I can see there.
Comment: @dxiv Its subtle, but it is in fact a proof by contradiction. Without appealing to the law of the excluded middle, all one can conclude from this proof is that $\sqrt{18}$ is *not rational*. But then we need LEM to get $\sqrt{18}$ is irrational.
Comment: @user259242: Are you prepared to claim that $\sqrt{18}$ may not be a number? Because irrational is defined as any number that is not rational.
Comment: @LutzL The point of contention relates to the logical difference between proving that a proposition is false, and proving that the negation of that same proposition is true. See Example 2.1 of https://arxiv.org/pdf/1110.5456v1.pdf
Comment: @user259242 Irrationals are *defined* as numbers which are not rational. But if you truly mean to push this into a discussion about Brouwer's intuitionism then I'll just leave it at that.
Answer: I suppose you could grind out the continued fraction for $\sqrt{18}$ and show or observe that it's with non-zero period .
Comment: Good (+1) added "with non-zero period" (otherwise it does not prove :)
Answer: In general, if $x$ is a positive integer, and $\sqrt[q]{x}$ is not an integer, then it will be irrational.  You can argue this without using proof by contradiction as follows.
Order the prime numbers as $p_1 = 2, p_2 = 3, p_3 = 5,...$  By the fundamental theorem of arithmetic, every positive rational number $x$ can be identified uniquely with a sequence $(n_1,n_2,n_3,...)$ of integers such that $n_i = 0$ for all but finitely many $i$.  Specifically $(n_1,n_2,n_3,...)$ is such that
$$x = 2^{n_1} 3^{n_2} 5^{n_3} \cdots$$
which is a finite product.  For example, $(-1,-1,-1,0,0,...)$ corresponds to the rational number $\frac{1}{30}$.

If $x,y$ are positive rational numbers, $(n_1, n_2, ...)$ is the sequence corresponding to $x$, and $(m_1, m_2, ...)$ is the sequence corresponding to $y$, then $(n_1+m_1,n_2+m_2,...)$ is the sequence corresponding to $xy$.

In particular, $y^2$ corresponds to the sequence $(2m_1,2m_2,...)$.

A positive rational number is an integer if and only if all the terms in its sequence are nonnegative.

Every positive integer is uniquely expressible as a product of primes, so its sequence, which uniquely identifies it, will consist of nonnegative terms.
From these two facts, we see that the only integers which are squares of rational numbers are those for which the correspondence sequence consists of nonnegative even terms, in which case their square roots are also integers.
Comment: The fundamental theorem of arithmetic is a very strong result, and I'm afraid you have to prove it by contradiction somewhere...


How to set a value of a known cell in IE7?

Question: I have a report that has some headers on the top of the table(columns) but also some headers on the left of the table (rows). Those headers are variable, never fixed. The whole entire table is built through DOM Scripting based on an Ajax response that returns me the top headers, the left headers, and the qty at a particular intersection.
I already have an algorithm that knows how populate the cells in that table based on the column header and the row header.
In Firefox, Chrome, and Safari the following works:
document.getElementById("myTable").rows[row].cells[column].firstChild.nodeValue = item.qty.toString();

The problem is in IE7 (what the client uses). IE 7 does not let me access a particular cell by using the [index] notation.Basically, its blowing up at ".cells[column]" .  Do you guys know the equivalent of the statement above in IE7?
Also do you know of a jQuery way to fill a known cell once I have the row and the column coordinates?
Thanks,
-Dario
Comment: http://stackoverflow.com/questions/376081/how-to-get-a-table-cell-value-using-jquery/376095#376095
Comment: jquery is ok but you can use xpath too http://js-xpath.sourceforge.net/
Comment: can you show more of your js/markup?
Comment: Thanks a lot everybody,

I tried your jQuery approaches and they worked.

Additionally, what I thought it did not work in IE7. It does work in IE 7 but I have found that IE7 wants you to create the table with a **thead** tag and a **tbody** tag as well.

Once I included the thead and tobdy tags. The following also worked in IE7:
document.getElementById("myTable").rows[row].cells[column].firstChild.nodeValue = item.qty.toString();

Sorry if I wasted your time but your answers were also a solution to the problem.
Answer: jQuery("#myTable tbody tr:eq(" + row + ") td:eq(" + column + ")").html("foo");

jQuery selector #id
jQuery selector element
jQuery selector eq()
jQuery html()
Comment: Some text explaining would be appreciated.
Comment: `#myTable tbody` won't count the rows in thead
Answer: row and column will start from 0. Use the above codes.
Answer: Non-jquery way:
document.getElementById("myTable").getElementsByTagName('tbody')[0].getElementsByTagName('tr')[row].getElementsByTagName('td')[column].innerHTML = item.qty.toString();

Answer: $("#myTable tr:eq(" + row + ") td:eq(" + column + ")").html(item.qty.toString());

However you should be aware of nested tables. Especially if you have another table inside the table with the myTable id. If so let me know, i might rewrite the line for you.
Also you should be aware that I was using jQuery here. To add jQuery to your page you should add the following to the page, preferably in the  element:

This if you want to make use of the jQuery file hosted by google, but of course you can download it and host it yourself if you wish so.
Answer: Try this:
$("#myTable tr:eq(" + row + ") td:eq(" + columnh + ")").html(item.qty.toString());

Comment: `#myTable tr` will count the rows in thead


Event Listener on dynamically created elements only working for first result

Question: I have my event listener working on my dynamically created HTML, but the problem I'm having is that it is only always listening to the first result.
For Example, The value 'this.id' are different;

IMAGE (hidden value = '3')
IMAGE (hidden value = '6')
IMAGE (hidden value = '8')

However no matter the image I click, value 3 is always selected. How can I solve this problem?
HTML

JavaScript (dynamically creating HTML)
var html =
'<form action="test.php" method="get" id="myForm">' +
  '<input type="hidden" name="mID" value"' + this.id + '"/>' +
  '<input type="image" id="send" src="this.image" name ="send"  alt="submit"/>' +
'</form>';
$('div#test').append(html);

AJAX
$("#test").on('click', '#send', function(e) {
e.preventDefault();

            $.get( $("#myForm").attr("action"),
                    $("#myForm :input").serializeArray(),
                    function(data) {
                      console.log(data);
                        });

            $("#myForm").submit( function() {
               return false;
            });

});
Comment: man id is unique for element try class
Comment: Use delegated handler to handle the submt event also...
Comment: ID of an element must be unique so use class instead of ID... `$("#myForm")` will select only the first element with the ID `myForm`
Answer: The problem is your use of static ID for element which are added multiple times. ID of an element must be unique in a document, the ID selector will fetch only the first element with the given ID. So in your case when you say #myForm it will always return the first myForm in the page.
Instead you can use class selector, and you can lookup the form to which the clicked send element belongs using closest() like
var html =
  '<form action="test.php" method="get" class="myForm">' +
  '<input type="hidden" name="mID" value="' + this.id + '"/>' +
  '<input type="image" class="send" src="this.image" name ="send"  alt="submit"/>' +
  '</form>';
$('div#test').append(html);

$("#test").on('click', '.send', function(e) {
  e.preventDefault();

  var $form = $(this).closest('form');

  $.get($form.attr("action"), $form.find(":input").serializeArray(), function(data) {
    console.log(data);
  });
});
$("#test").on('submit', '.myForm', function(e) {
  return false;
});

Comment: Hi @Arun thanks for your reply. I tried you code suggestion but it didn't work :( with your code the page just goes straight to the php page (test.php), almost like the JavaScript isn't there.
Comment: Actually my bad.. IT WORKED!! I had an error in my code which I fixed.. Thanks a lot @Arun.


$x^4+y^4+z^4=\frac{m}{n}$, find $m+n$.

Question: $x^4+y^4+z^4$=$m\over n$
x, y, z are all real numbers,
satisfying $xy+yz+zx=1$ and $5\left(x+\frac{1}{x}\right)=12\left(y+\frac{1}{y}\right)=13\left(z+\frac{1}{z}\right)$
m, n are positive integers and their greatest common divisor is 1. Calculate m+n.
My thinkings so far are as follows:

to operate such that we can arrange 5,12,13 into some kind of pythagorean triplets.
to do whole square of x+1/x or x^2 + 1/x^2 such that
the third term is a constant and can be moved to other side.
Comment: Hi, please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to write maths.
Comment: "5*(x+1/x)=12*(y+1/y)=13*(z+1/z)": What does this mean?  Does this mean that $$5 \times \frac{x+1}{x} = 12 \times \frac{y+1}{y} = 13 \times \frac{z+1}{z}~?$$  Alternatively, do you instead intend that $$5 \times \left[x + \frac{1}{x}\right] = 12 \times \left[y + \frac{1}{y}\right] = 13 \times \left[z + \frac{1}{z}\right] ~?$$
Comment: See [this](https://math.stackexchange.com/help/notation) for a MathJax tutorial.
Comment: @user2661923 Good question - I took the latter version. It has a nice solution.
Comment: @DietrichBurde I was wondering how you knew the OP's (i.e. original poster's) intent.  Did you by any chance place your fingertips on your monitor at the same time that the OP placed his fingertips on his monitor?  Are you from the planet Vulcan?
Comment: @user2661923 intended the second one. updated now. sorry for the trouble . Learning MathJax
Answer: Taking resultants of the polynomials given by
$$
f=5\left(x+\frac{1}{x}\right)-12\left(y+\frac{1}{y}\right),g=5\left(x+\frac{1}{x}\right)-13\left(z+\frac{1}{z}\right), h=xy+yz+zx-1,
$$
set to zero, i.e., with
\begin{align*}
0 & = 5x^2y - 12xy^2 - 12x + 5y,\\
0 & = 5x^2z - 13xz^2 - 13x + 5z,\\
0 & = xy + xz + yz - 1
\end{align*}
we obtain the linear equation $13z=12y+25x$, and then by substituting $z$ and taking resultants again,
$$
(x,y,z)=\left(\frac{1}{5},\frac{2}{3},1\right),\; \left(-\frac{1}{5},-\frac{2}{3},-1\right).
$$
Hence we have
$$
x^4+y^4+z^4=\frac{60706}{50625}.
$$
So we have $(m,n)=(60706,50625)$, so that
$$
m+n=111331.
$$
Note: Over the complex numbers we obtain two additional solutions, namely
$$
(x,y,z)=(i,-i,i),(-i,i,-i).
$$
But then $x^4+y^4+z^4=3$, so that $m+n=4$.
Comment: Yes, now it has $x$. But why "then" in "and then"?
Comment: Thanks  for the quick response, Can you  be bit more explicit. can't follow how you arrived at the first linear equation itself.
Comment: The first line is not clear. What are the resultants? The equation has no $x$ in it and too few $=$ signs. It is not clear how the  second line relates to the first.
Comment: @markvs Thank you, I have edited.
Comment: $f,g$ are not polynomials. The equation $13z=...$ still does not contain $x$.
Comment: The equation 13z=... still does not contain $x$ and too few $=$.
Answer: Notice if $(x,y,z)$ satisfies the two conditions, so does $(-x,-y,-z)$. Furthermore, it is clear $x,y,z$ have the same sign. Since $(x,y,z)$ and $(-x,-y,-z)$ gives the same $\frac{m}{n}$, we only need to consider the case $x,y,z > 0$.
Take three numbers $\alpha,\beta,\gamma \in (0,\frac{\pi}{2})$ such that
$$x = \tan\alpha, y = \tan\beta, z = \tan\gamma$$
Recall the three angle summation formula for tangent, we have
$$\begin{align}\tan(\alpha+\beta+\gamma)
&= \frac{\tan\alpha + \tan\beta + \tan\gamma - \tan\alpha\tan\beta\tan\gamma}{1 - \tan\alpha\tan\beta - \tan\beta\tan\gamma - \tan\gamma\tan\alpha}\\
&= \frac{x+y+z - xyz}{1 -xy - yz -zx}\\&= \infty\end{align}$$
This implies $\alpha + \beta + \gamma = (N + \frac12)\pi$ for some integer $N$.
Since $\alpha + \beta + \gamma \in (0,\frac32\pi)$, this forces $N = 0$ and
hence $\alpha + \beta + \gamma = \frac{\pi}{2}$.
Notice
$$\frac{2}{x+\frac1x} = \sin(2\alpha),\quad
\frac{2}{y+\frac1y} = \sin(2\beta)\quad\text{ and }\quad
\frac{2}{z+\frac1z} = \sin(2\gamma)$$
the condition
$$5\left(x+\frac1x\right) = 12\left(y  + \frac1y\right) = 13\left(z + \frac1z\right)$$
is equivalent to
$$\sin(2\alpha) : \sin(2\beta) : \sin(2\gamma) = 5 : 12 : 13 \tag{*1}$$
Since $5^2 + 12^2 = 13^2$, we find
$$\sin^2(2\alpha) + \sin^2(2\beta) = \sin^2(2\gamma)\tag{*2}$$
With a little bit of algebra, one can verify when $\alpha + \beta + \gamma = \frac{\pi}{2}$, one has the "cosine rule":
$$\cos(2\gamma) = \frac{\sin^2(2\alpha) + \sin^2(2\beta) - \sin^2(2\gamma)}{2\sin(2\alpha)\sin(2\beta)}$$
$(*2)$ tell us  $\cos(2\gamma) = 0 \implies \gamma = \frac{\pi}{4} \implies z = \tan\gamma = 1$. Plug this into $(*1)$, we get
$$
\begin{cases}
\sin(2\alpha) = \frac{5}{13}\\
\sin(2\beta)  = \frac{12}{13}
\end{cases}
\quad\implies\quad
\begin{cases}
\cos(2\alpha) = \frac{12}{13}\\
\cos(2\beta)  = \frac{5}{13}
\end{cases}
$$
This leads to
$$\begin{align}
x &= \tan \alpha = \sqrt{\frac{1-\cos(2\alpha)}{1 + \cos(2\alpha)}}
= \sqrt{\frac{1-\frac{12}{13}}{1+\frac{12}{13}}} = \frac15\\
y &= \tan \beta = \sqrt{\frac{1-\cos(2\beta)}{1 + \cos(2\beta)}}
= \sqrt{\frac{1-\frac{5}{13}}{1+\frac{5}{13}}} = \frac23\\
\end{align}
$$
As a result
$$\frac{m}{n} = x^4 + y^4 + z^4 = \frac1{5^4} + \frac{2^4}{3^4} + 1^4 = \frac{60706}{50625}$$
This leads to $m + n = 60706 + 50625 = 111331$.

$x^4+y^4+z^4=\frac{m}{n}$, find $m+n$.


VSCode C# Intellisense not displaying correct autocompletions

Question: i'm using VSCode for a quick and Lite programming, but Intellisense does not work giving autocompletion out of the box, instead it only shows options of word that are frequently used or common snippets in code.
Comment: sometimes you need to type more than 2 characters, type the full prefix and see if it shows
Comment: do you have correct extensions installed?
Comment: yes i have correct extensions installed
Comment: no, when the extensions run on top appear the class and method that i am typping in
Answer: My bad, kinda. The C# extension can fail to initialize due to low performance, the Intellisense is magically fixed when you restart the Omnisharp server


Display pip values in Nouislider as number range

Question: I have created a nouislider with this code:

and my pip values appear as,

but I want it to appear this way:

Please how can I achieve this? Can I input an HTML value in the pip value or do I have to use jquery?
Answer: The pips option accepts a format parameter. You can pass a to function there to format each value as described in the question.


How can I mock a service?

Question: i have this code:
/**
 * Defines a wrapper target around a paragraph bundle's target field.
 *
 * @FeedsTarget(
 *   id = "feeds_para_mapper_temp_target",
 *   field_types = {
 *     "entity_reference_revisions",
 *   },
 *   arguments = {
 *     "@entity.manager",
 *     "@entity_field.manager"
 *   }
 * )
 */
class TempTarget extends FieldTargetBase implements, ConfigurableTargetInterface,
{
  protected $entity_type_manager;
  protected $field_manager;
  public function __construct(array $conf, $id, array $def, EntityTypeManagerInterface $en_man, EntityFieldManagerInterface $f_man)
  {
    parent::__construct($conf, $id, $def);
    $this->entity_type_manager = $en_man;
    $this->field_manager = $f_man;
  }
  // Here is where i need the instance, and it's weird because it gets called
  // without instantiating this class:
  public function defaultConfiguration(){
    // This function create a form configuration and return it:
    $definition = $this->targetDefinition;
    $field = $definition->getFieldDefinition();
    $instance = $this->createTargetInstance($field,$this->feedType)
  }
  // Calls this plugin manager to get instance of another plugin
  public function createTargetInstance(FieldConfigInterface $field, FeedTypeInterface $feed_type){
    // This is where the test is failing:
    $manager = \Drupal::service('plugin.manager.feeds.target');
  }
}

what it does it calls a plugin manager in order to create instance definition,
whenever it gets tested i see this error:
\Drupal::$container is not initialized yet.

which i know is caused by calling to the service
i have tried this in the test file:
$container = new ContainerBuilder();
$manager = $this->prophesize('Drupal\feeds\Plugin\Type\FeedsPluginManager');
$container->set('plugin.manager.feeds.target', $manager);
\Drupal::setContainer($container);

Not working.
i tried as the answer suggested in the comment bellow to add implement ContainerInjectionInterface not working, and with ContainerFactoryPluginInterface as this article suggested, not working too, in both implementations the create() method is never get called
i tried to add this to he annotation:
 *   arguments = {
 *     "@entity.manager",
 *     "@entity_field.manager",
 *     "@plugin.manager.feeds.target"
 *   }

with this constructor:
public function __construct(array $$conf, $id, array $def, EntityTypeManagerInterface $en_m, EntityFieldManagerInterface $f_m, FeedsPluginManager $p_m)
  {
    $stop = null;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entity_type_manager = $en_m;
    $this->field_manager = $f_m;
    $this->plugin_manager = $p_m;
  }

and it's working only if this class is instantiated, and as i said it's not when the defaultCongiguration() get called, i can go without the plugin manager at this stage but i really prefer if i can have it in this function.
Update:
The reason why implementing either ContainerInjectionInterface or ContainerFactoryPluginInterface didn't work is because i added my dependencies in the arguments, annotation and in the create() method too.
Comment: Possible duplicate of ["Drupal calls should be avoided in classes, use dependency injection instead"](https://drupal.stackexchange.com/questions/207151/drupal-calls-should-be-avoided-in-classes-use-dependency-injection-instead)
Comment: I don't see the entire class but shouldn't that be passed in instead of called statically?
Comment: no the test is failing with this exception `Drupal\Core\DependencyInjection\ContainerNotInitializedException`: i think a plugin manager is some kind of service: https://www.drupal.org/docs/8/api/plugin-api/creating-your-own-plugin-manager
Comment: I was confused why this was a duplicate at first, but to explain, I think that leymannx is suggesting you can work around your question by by injecting FeedsPluginManager into the static method. Then it can be mocked without creating a container. I see how this could be a duplicate given that.
Comment: it is not duplicate, and i already tried it and not working there is something worked for me but only if the constructor got called, but wait you said injecting into static method, is there such thing ??
Comment: i've updated my question, any help is really appreciated
Answer: This is probably a unit test (not mentioned in the OP). If so, the intention should be to test the methods of the TempTarget class, which means, that the first thing needed would be to instantiate an instance of that class, e.g.
/**
 * Instantiates and returns a TempTarget object.
 */
protected function getTempTargetInstance()
{
  $id = $this->generateId();
  $def = $this->generateDef();
  // This is where you mock the constructor dependencies/services.
  // You probably will need to create a mock like this:
  //   $this->getMockBuilder('Drupal\Core\Entity\EntityTypeManager')
  //     ->disableOriginalConstructor()
  //     ->getMock();
  $this->entityTypeManager = $this->getEntityTypeManagerMock();
  $this->entityFieldManager = $this->getEntityFieldManagerMock();

  // You can now call the constructor.
  $tempTarget = new TempTarget($id, $def, $this->entityTypeManager, $this->entityFieldManager);
  return $tempTarget;
}

At this point, your object should be instantiated and you can call methods on it to assert the assumptions you want to be testing. For example:
public function testDefaultConfigurationMethod()
{
  $tempTarget = $this->getTempTargetInstance();
  $formConfiguration = $tempTarget->defaultConfiguration();
  // Test different assertions given the $formConfiguration object.
}

However, at the time you call defaultConfiguration() you know that you need a container available that holds an entry for plugin.manager.feeds.target, so, you have to have that prepared in advance. The right place for that would be your setUp() method in your class, for example:
/**
 * {@inheritdoc}
 */
public function setUp() {
  parent::setUp();

  // Provide a mock service container, for the services our module uses.
  $container = new ContainerBuilder();
  $container->set('plugin.manager.feeds.target', $this->getFeedsTargetPluginManagerMock());
  \Drupal::setContainer($container);
  ...
  // Further setting-up of your testing class.
}

with getFeedsTargetPluginManagerMock() looking something like this:
/**
 * Creates and returns a mock for the feeds
 */
protected function getFeedsTargetPluginManagerMock() {
  $feedsTargetPluginManager = $this
    ->getMockBuilder('Drupal\feeds\Plugin\Type\FeedsPluginManager')
    ->disableOriginalConstructor()
    ->getMock();
  ...
  // Further mocking of the objects methods if needed.
  ...
  return $feedsTargetPluginManager;
}

Good luck!
Comment: Sure thing, did you manage to make it work in the end?
Comment: Yes the test is working now, i had to change few things in the main code
Comment: Good to know, would be very helpful for others landing here if you could update your question with the final details.

How can I mock a service?


Eigenvalues of Hecke operators are algebraic integers

Question: I want to show that if a normalised modular form of level $1$, say $f$, is a simultaneous eigenform of the Hecke operators $T(n)$ for all $n$, then the corresponding eigenvalues are all algebraic integers. My approach goes like this:
Let $M_k(SL_2(\mathbb{Z}))$ be the space of modular forms of level $1$ and weight $k$. Let $M_k(SL_2(\mathbb{Z}))_{\mathbb{Z}}$ be the subset of those modular forms all of whose Fourier coefficients are integers. Then, one can check that the action of $T(n)$ descends to an action on $M_k(SL_2(\mathbb{Z}))_{\mathbb{Z}}$. Hence, if we can find a $\mathbb{Z}$-basis for $M_k(SL_2(\mathbb{Z}))_{\mathbb{Z}}$ which is also a $\mathbb{C}$-basis for $M_k(SL_2(\mathbb{Z}))$, then, the matrix of the action of $T(n)$ will have integer entries, and so, the eigenvalues will be algebraic integers. So, I only need to find such a basis.
I feel that some combinations of $E_4$ and $E_6$ (the normalised Weierstrass forms) should work, but I haven't been able to work out the details.
Comment: @Mathmo123 I found what I was looking for. Actually, I was referring to something on the lines of Serre's 'A Course in Arithmetic', Page 105, Section 5.6.2 on Integrality Properties.
Answer: You are correct. For a given $k\geqslant 12$ a basis for $M_k$ is given by $E_4^aE_6^b$ with $4a+6b=k$.


What is the distribution of $Z(X+Y)+XY$?

Question: Given that
$$
X \sim \mathcal{N}(0,1) \\
Y \sim \mathcal{N}(0,1) \\
Z \sim \mathcal{N}(\mu,1)
$$
are independent, what is the PDF of
$$
Z(X+Y)+XY
$$
I tried to transform this expression to
$$
\frac{1}{4}{\left( {X + Y + 2Z} \right)^2} - {Z^2} - \frac{1}{4}{\left( {X - Y} \right)^2},
$$
in which case it is the sum of a chi-squared distribution and two non-central chi-squared distributions.
However, $X + Y + 2Z$ is not independent of $Z$ (from Bernstein's theorem). Therefore, $Z\left(X + Y\right) + XY$ is not a sum of independent chi-squared distributions.
If $X + Y + 2Z$ is independent of $Z$, I can obtain the generalized chi-square CDF and PDF using MATLAB.
By the way, from Bernstein's theorem, we have that $X+Y$ and $X-Y$ are independent, thus
$$
XY = \frac{{{{\left( {X + Y} \right)}^2}}}{4} - \frac{{{{\left( {X - Y} \right)}^2}}}{4}
$$
is a weighted sum of two independent ${\chi ^2}\left( 1 \right)$ random variables.
Comment: You're on the right track, because $12(xy+yz+zx)=4(x+y+z)^2-3(x-y)^2-(x+y-2z)^2,$ *etc.*
Comment: @whuber Thank you so much for your help!
Comment: Are $x,y,z$ independent?
Comment: @mhdadk Sorry I missed that in the introduction. They are independent.
Comment: I'd start by finding the distribution of $XY.$ Google it.
Comment: @BruceET Thanks for the headsup. $XY$ can be expressed as a weighted sum of two independent chi2 random variables. That's why I tried to solve this problem by writing it as a sum of squares.
Comment: @whuber Dear Dr. Huber, I have one more question. In the case where the variance of $Z$ is not 1, let's say $\sigma^2$, do we have a general solution to transform $XY+YZ+XZ$ to a sum of independent (which complies with the requirement of Bernstein's theorem) chi-squared distributions?
Comment: Yes: the method described in my answer applies directly.  One way to carry it out is to write $Z=\sigma Z_0$ where $\operatorname{Var}(Z_0)=1.$
Answer: This is a special case of a real symmetric quadratic form $\mathbf{x^\prime \mathbb{Q} x},$ where
$$z(x+y) + yz = xy+yz+xz= \frac{1}{2}\pmatrix{x,&y,&z}\pmatrix{0&1&1\\1&0&1\\1&1&0}\pmatrix{x\\y\\z}.$$
We find its eigenvalues $\lambda$ by solving its characteristic equation
$$p_{\mathbb Q}(\lambda) = \det\left(\mathbb{Q} - \lambda\mathbb{I}_3\right) = -\lambda^3+3\lambda+2=(\lambda-2)(\lambda+1)^2.$$
The eigenspace for $\lambda=2$ is (therefore) the kernel of
$$\mathbb{Q}-2\mathbb{I}_3 = \pmatrix{-2&1&1\\1&-2&1\\1&1&-2}$$
which evidently is generated by $(1,1,1)^\prime.$  Similarly, by inspection, we can find a basis for the two-dimensional eigenspace for $\lambda=-1.$  To match the original form I selected the first basis element to be $(1,-1,0)$ (corresponding to the linear combination $x-y,$ whose square will contribute the $xy$ term) and then chose an orthogonal vector $(1,1,-2).$  Thus, it must be the case that $xy+yz+zx$ can be written as a linear combination of the squares of $x+y+z,$ $x-y,$ and $x+y-z,$ respectively.  It's now easy algebra to obtain
$$xy+yz+zx= \frac{1}{12}\left(4(x+y+z)^2-3(x-y)^2-(x+y-2z)^2\right).$$
When $(X,Y,Z)$ is standard Normal, the three squared expressions are uncorrelated (by construction) and have variances $1^2+1^2+1^2=3,$ $1^2+(-1)^2=2,$ and $1^2+1^2+(-2)^2=6,$ respectively.  So, letting $U=(X+Y+Z)/\sqrt{3},$ $V=(X-Y)/\sqrt{2},$ and $W=(X+Y-2Z)/\sqrt{6},$ we have shown $(U,V,W)$ is standard Normal--all have unit variances and are uncorrelated--and that
$$XY + YZ + XZ = \frac{1}{12}\left(12 U^2 - 6 V^2 - 6 W^2\right) = U^2 - \frac{1}{2}\left(V^2  + W^2\right).$$
Finally, let the expectation of $(X,Y,Z)$ be $(\kappa,\lambda,\mu).$ By linearity, the expectation of $(U,V,W)$ is
$$E[(U,V,W)] = \left(\frac{\kappa+\lambda+\mu}{\sqrt{3}},
\frac{\kappa-\lambda}{\sqrt{2}},
\frac{\kappa+\lambda-2\mu}{\sqrt{6}}\right)$$
By definition, $U^2$ has a $\chi^2_1((\kappa+\lambda+\mu)^2/3)$ distribution and, because $V$ and $W$ are independent, $V^2+W^2$ has a $\chi^2_2((\kappa-\lambda)^2/2 + (\kappa+\lambda-2\mu)^2)/6)$ distribution.  Moreover, $U^2$ is independent of $V^2+W^2$ because $(U,V,W)$ are independent. Thus,

The distribution of $XY+YZ+ZX$ is that of a  $\chi^2_1((\kappa+\lambda+\mu)^2/3)$ distribution minus one-half of a $\chi^2_2((\kappa-\lambda)^2/2 + (\kappa+\lambda-2\mu)^2)/6)$ distribution.

(I haven't simplified the expressions for the noncentrality parameters in order to display their derivation.)
Arbitrary symmetric quadratic forms in Normal variables are analyzed in the same way, with comparable results: their distributions are those of linear combinations of (possibly) non-central chi-squared variables.
When the form is positive-definite, all coefficients will be positive (and vice versa).

As a check, we can generate random values in both ways.  Using R, we sample from the form in the most straightforward way:
n <- 1e4
mu <- c(1,-1,3)    # Mean of (X,Y,Z) -- vary at will
set.seed(17)
xyz <- matrix(rnorm(3*n), 3)
q <- xyz[1,]*xyz[2,] + xyz[2,]*xyz[3,] + xyz[3,]*xyz[1,]

The chi-squared equivalent is also simple:
ncp1 <- (mu[1] + mu[2] + mu[3])^2/3
ncp2 <- (mu[1] - mu[2])^2/2 + (mu[1] + mu[2] - 2*mu[3])^2/6
c1 <- rchisq(n, 1, ncp=ncp1)
c2 <- rchisq(n, 2, ncp=ncp2)
q. <- c1 - c2/2

A probability plot compares the distributions:
plot(sort(q), sort(q.), asp=1,
     main="Theory v. Simulation",
     pch=19, col="#00000020", xlab="XY + YZ + ZX", ylab="")
mtext(bquote({chi[1]^2}(.(signif(ncp1, 2))) - {chi[2]^2}(.(signif(ncp2, 2)))/2),
     side=2, line=2)
abline(c(0,1), lwd=2, col="Red")

Because the points come close to the reference line (of equal values), we see the two samples agree to within expected random deviation:
Comment: Beautiful resolution!
Comment: Seems like there is a missing $\mu$?
Comment: @BigBend You're right: I didn't see that $Z$ is supposed to have mean $\mu.$ It's not a real complication, though: now $U=(X+Y+Z)/\sqrt{3}$ has a mean of $\mu/\sqrt{3}$ and $W$ has a mean of $-2/\sqrt{6},$ so $U^2$ has a $\chi^2(1,\mu^2/3)$ distribution and $V^2+W^2$ has a $\chi^2(2,2/3)$ distribution.  This kind of result is general: nonzero means introduce non-zero centrality parameters into the $\chi^2$ components.  I will edit this post.


Stanford Engineering Everywhere CS106B Library

Question: I  am currently a C# programmer and have been interested in learning more about C++ and data structures.  I found the CS106B class offered free online through the Stanford Engineering Everywhere program which seems like it would be a good fit.
I've tried to install the library files they use for the class and keep getting a message that I have to have visual studio 2005 installed for the setup file to run.  I don't have 2005, but I've tried the express editions of both vc++ 2008 and vc++2005.  Is there any way around this that I can get the proper files installed?
The zip file containing the libraries came with two files, an exe and an msi.
Comment: Could you be more specific about these library files? Are they *.sln files, *.vcproj, *.lib?
Answer: Just got it to work by using some information I found here: http://www.functionx.com/visualc/libraries/staticlib.htm
I'm using Visual C++ 2008 Express. Here's how I did it:

Download the PC Starter Code ZIP file for Assignment 1 from the
current semester's CS106B class website.
http://www.stanford.edu/class/cs106b/ In that file you'll find a
folder named "StanfordCPPLib". In that folder, you'll need the
StanfordCPPLib.lib and the *.h files you want to include.
In Visual Studio, create a new project (File -> New -> Project). Select a Win32
Console Application, choose a name, and click Next.
When the Application Wizard pops up, click Next (not Finish). In the
Application Settings, check the box marked "Empty Project". Click
Finish.
In the Solution Explorer, right click on the Source folder and
create a new .cpp file. (Add -> New Item -> Code -> C++ File)
Find your new project's folder in Windows Explorer. In that folder,
you should be able to find your new .cpp file you just created.
Paste the StanfordCPPLib.lib and your needed *.h files you
downloaded earlier into the same folder that contains your new .cpp file.
Finally, you need to add the library to our new project. In Visual Studio, using
the main menu, click Project -> Add Existing Item. The dialog should
default to your project's folder where you just pasted
StanfordCPPLib.lib. Select StanfordCPPLib.lib and click Add.

You should now be able to add an #include "example.h" for whatever .h files you copied into your project folder.
Note: Since you'll be using a newer version of Stanford's custom library, there may be some small differences between the original handouts and the new library. For instance, when using #include "simpio.h", the handouts list a function called GetLine(). In the new library, that function is capitalized differently: getLine(). Make sure you check the header files for correct syntax/usage.
Answer: Thanks to Dani, with his help, I succeed in installing the library on vs2008(both express and professinal are OK) on win7. With Dani's help,
I have finished the first three assignments in cs106X(winter2010) - life, ADT, boggle - so far.
I'm just a undergraduate in China, thanks so much to the great education of stanford and power of internet.
http://abloggingattempt.blogspot.com/2010/05/stanford-cs106-lib-and-vs2008-express.html
the following are copied mainly from Dani's blog.
Stanford CS106 Lib and VS2008 Express
The CS106B is a great CS Stanford course available online (iTunes e.g.) in video and for free. All assignments and the course itself use an in-house developed library (not sure if it has a name, cslib, cs106 lib, dunno) available in all of the assignment zips as well as installable with the Xcode/VS2005 wizard installs. The problem - the VS custom wizard will install on VS2005 only (could be that a newer version exists but I couldn't find one). So how to port the VS wizard to VS2008 Express(professional)?
- I got the 2005 custom wizard setup, PCLibs-VS2005-ADT-Installer.zip and used a small tool , the LessMSIerables(Universal Extractor also works well) in order to extract the contents of the msi file. The msi contains four folders with all the stuff needed to create a new custom wizard. So, the tool extracted the following:
SourceDir
|- Includes Folder
|- Library Folder
|- Project Folder
|- Wizard Folder

Now some copying:

The CS106CPPInc folder inside the 'Includes Folder' goes to
C:\Program Files\Microsoft Visual Studio 9.0\VC\include (as a subfolder!)
'Library Folder'\CS106CPPLib.lib goes to
C:\Program Files\Microsoft Visual Studio 9.0\VC\lib
'Wizard Folder\AppWiz\CS106 Assignment Wizard' to
C:\Program Files\Microsoft Visual Studio 9.0\VC\VCWizards\AppWiz
(meaning CS106... should appear as a sub-folder of AppWiz)
The three files in 'Project Folder' will go into
C:\Program Files\Microsoft Visual Studio 9.0\VC\Express\VCProjects\Stanford. One of those three files, the CS106 Assignment Wizard.vsz, needs to be edited (a text file) and its second line should become:

Wizard=VsWizard.VsWizardEngine.9.0
Answer: Was having the same problem. I found both the .h and the .c files online.
You can find them here:
http://www.ime.usp.br/~pf/Roberts/C-library/standard/cslib/
Answer: I suggest to go to the CS106B page directly:
http://www.stanford.edu/class/cs106b/
And grab newest assignments. They are compatible with VS 2008.
The assignment material from SEE is outdated (VS 2005). The assignments are not discussed in the video, so you won't miss anything by doing that.
Just download from the CS106B page and open in VS 2008, that will work!
Answer: Reading through handout 5P makes it seem like the installer will expect the file structure VS2005 will create - especially this sentence: "Run (and quit) Visual Studio (you can go ahead and register your copy if it asks you). It is important that you have done this at least once before proceeding to the next step."
Try creating a folder structure like: (under "My Documents") "Visual Studio 2005\Projects" and see if setup.exe will work.
Comment: Thanks!  I'll try this when I get home tonight and let you know.
Comment: Didn't work, I'm getting the same message.  Anything else you can think of?
Comment: I tried this with VS 2003 and VS 2008, and it refused to install. I can't think of what else to suggest, other than sending Ms Zelenski an email through the "contact us" link.
Answer: I am using visual studio express, and all I did was to just unzip the files it works fine..  here I have done the CS106B assignment with also the full zip'd up files of that assignment as well, all I did was to uncompress the assignment from the cs106b website and open up the sln (solution) file within visual studio express.
Answer: There is no c++ library available for cs106b in unix system. I hope they publish the library in source.


Arredondar bordas tabela CSS3

Question: Bom dia pessoal, estou tentando arredondar as bordas de uma tabela que estou utilizando, mas não consigo alterar nem pelo arquivo css e nem pela tag style dentro do próprio elemento.
Alguém saberia dizer qual o problema do meu código?
index.html
<!DOCTYPE html>

<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Pain Free</title>
    <meta name="description" content="Site voltado para manipular doencas de pacientes que utiizando o app do pain free">
    <meta name="Laura" content="">
    <link rel="stylesheet" href="./css/listar_pacientes.css">
    <link rel="stylesheet" href="./css/menu.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

   <?php include ("class/menu.php"); ?>

Lista de Pacientes

              <input name="consulta" id="txt_consulta" placeholder="Pesquisar" type="text" class="form-control">

                 **
**

                        Nome
                        Último Acesso
                        Ações

                        Maria
                        12/04/2019

                         <a href="editPatient.php?codigo=<?php echo $dado["id"] ?>" id="editPatient">
                         <a href="javascript: if(confirm('Tem certeza que deseja deletar o paciente <?php echo $dado["patient_name"]; ?>?'))
                         location.href='deletar.php?codigo=<?php echo $dado["id"] ?>'" id="deletePatient">

                      <?php }?>

listar_pacientes.css
@-webkit-viewport { width: device-width; }
@-moz-viewport { width: device-width; }
@-ms-viewport { width: device-width; }
@-o-viewport { width: device-width; }
@viewport { width: device-width; }

body
{
    margin: 0px;
    text-align: center;
}

/* ==================== LISTA DE PACIENTES ============================ */
#list_patient
{
    width: 45em;
    margin: 0 auto;
}

#border-table
{
    border-radius: 10px;
}

.table
{
   /* padding-right: 5em; */
    font-weight: bold;
    border-radius: 10px;
}

.table tr td
{
    margin-left: 3em;
    background-color: #f5f5f5;
    text-align: center;
}

#title_list_patient
{
    margin-right: 1em;
    color: #346789;
}

Comment: Suas tabelas não possuem bordas definidas, tente definir algo como o exemplo:

#example1 {
  border: 2px solid red;
  border-radius: 25px;
}
Comment: Possível duplicata de [border-radius na tabela não funciona CSS](https://pt.stackoverflow.com/questions/59602/border-radius-na-tabela-n%c3%a3o-funciona-css)
Answer: As bordas da tabela não aceitam border-radius, mas o background aceita. Logo, você pode arredondar as bordas inferiores da tabela, já que as td's possuem uma cor de fundo. Basta colocar no seu CSS as propriedades que alteram a borda do primeiro e último td da última linha da tabela, que seriam:
.table tr:last-child td:last-child{
    border-bottom-right-radius: 20px;
}

.table tr:last-child td:first-child{
    border-bottom-left-radius: 20px;
}

Veja:

@-webkit-viewport { width: device-width; }
@-moz-viewport { width: device-width; }
@-ms-viewport { width: device-width; }
@-o-viewport { width: device-width; }
@viewport { width: device-width; }

body
{
    margin: 0px;
    text-align: center;
}

/* ==================== LISTA DE PACIENTES ============================ */
#list_patient
{
    width: 45em;
    margin: 0 auto;
}

#border-table
{
    border-radius: 10px;
}

.table
{
   /* padding-right: 5em; */
    font-weight: bold;
    border-radius: 10px;
}

.table tr:last-child td:last-child{
    border-bottom-right-radius: 20px;
}

.table tr:last-child td:first-child{
    border-bottom-left-radius: 20px;
}

.table tr td
{
    margin-left: 3em;
    background-color: #f5f5f5;
    text-align: center;
}

#title_list_patient
{
    margin-right: 1em;
    color: #346789;
}

Lista de Pacientes

     <input name="consulta" id="txt_consulta" placeholder="Pesquisar" type="text" class="form-control">

               Nome
               Último Acesso
               Ações

               Maria
               12/04/2019

                <a href="editPatient.php?codigo=<?php echo $dado["id"] ?>" id="editPatient">
                <a href="javascript: if(confirm('Tem certeza que deseja deletar o paciente <?php echo $dado["patient_name"]; ?>?'))
                location.href='deletar.php?codigo=<?php echo $dado["id"] ?>'" id="deletePatient">

               Maria
               12/04/2019

                <a href="editPatient.php?codigo=<?php echo $dado["id"] ?>" id="editPatient">
                <a href="javascript: if(confirm('Tem certeza que deseja deletar o paciente <?php echo $dado["patient_name"]; ?>?'))
                location.href='deletar.php?codigo=<?php echo $dado["id"] ?>'" id="deletePatient">

Arredondar bordas tabela CSS3


Can a HP P2000 G3 SAN with SAS controller direct connect to a Dell PowerEdge Server with a Dell brand HBA

Question: I am building a home rig and have recently acquired an HP P2000 G3 SAN with SAS controllers. I appreciate these are supposed to connect into a DL380 G7 or G8 with the HP branded SAS interface card (sc08e) but I have a Dell PowerEdge R710 server. I'm wondering, if I purchased a dell SAS card like a Perc H200e, would I be able to directly connect the SAN in a similar way?
Answer: Technically this question is off-topic if this is for home lab use - check out the allowed topics.
The question here is essentially whether the HP array will work with a Dell SAS HBA, or if an HP SAS HBA will work in a Dell server. Either one should work, but there's no guarantee. HP's rebranded LSI 9200-8e and Dell's rebranded 9207-8e both use the same LSI SAS 2008 chipset, so I would fully expect things to "work", though an HP card's firmware might not play nicely with Dell's system monitoring. Probably best to use the Dell 6Gbps SAS HBA or a generic LSI 9207-8e, as I doubt the HP array would have any mechanism to "disallow" non-approved HBAs from connecting.
Comment: That is excellent, many thanks. I appreciate it falls slightly off-topic and I apologise but as it involves enterprise level hardware I thought there may be some value for people who might have a similar situation in a business scenario.
Comment: Yeah, TBH these kinds of questions are usually 2 words away from being on topic by the letter of the law... e.g. "I am building a testing/learning lab rig". The site isn't strictly limited to production boxes, though that's certainly where the priority and focus are.


Finding coordinates of best fit rectangle

Question: Input:  A,B,a,b - where A and B my width and height of the grid, and a,b - width and height of rectangle that i want to fit in. Then i'm given N - number of rectangles,that already fitted in grid. In the next N lines i am given coordinates of opposite diagonal verteces of each rectangle,for example for first rectangle,input will be (x0,y0) (x1,y1) and so on. These rectangles can overlap. And i need to find coordinates of opposite diagonal verteces of initial rectangle, such that it can be fit in the grid(we need to print maximal height)
Example:
9 5 2 4
2
1 1 3 4
1 1 6 2

Output will be: 6 0 8 5 Picture of input
Can you please give me some hints? It seems that i need to use dynamic programming here
Comment: Can you explain one input-output case elaborately? Your diagram is kind of useless without any markers.
Comment: The width `a` is fixed (`=2`) and the height `b` should be maximal `>=4`, right?
Comment: @HEKTO yes, but in boundaries of grid
Comment: Interesting question, but I think - you could improve its phrasing... AFAIU your grid means that all rectangles corners are integers, and the new rectangle shouldn't intersect with all the existing ones. Also your picture should be inside of your question
Answer: If to assume that all coordinates are integers, then you could consider all the possible rectangles with width a and height >=b, inscribed inside the boundary rectangle with width A and height B - it's easy to see that their number is O(AB^2). You will need to check the intersection of each such rectangle with your N predefined rectangles. There are data structures like Quadtree, which will allow you to do a single intersection test in O(logN) time.
In more general case you can use the Plane Sweep approach, and it will be much faster. I'll describe it briefly here.
At first you need to sort all the X-coordinates you have - including coordinates of the boundary rectangle (you call it grid). Each element of this sorted array S should store the X-coordinate value itself together with the rectangle number it belongs to, and a flag, marking left or right side of this rectangle.
Now imagine a "sliding" rectangle T with width a and height B, located in extreme left position inside the boundary rectangle - its left side will have the S[0].x coordinate. You can find all the rectangles, intersecting with the rectangle T looking into the array S only - let's call this set of rectangles an active set. You need to find out if you have an empty space with height >=b in the intersection of T with the active set. Remember the maximal rectangle with width a and maximal height >=b (if it exists).
Shift the sliding rectangle T to the right until its left side reaches the S[1].x coordinate. Again, you can use the array S to find the active set, intersecting with the T, and perform the same local analysis as before. If you can find an empty space inside the sliding rectangle, compare it with already found one and remember the best result.
Continue this process until the sliding rectangle T reaches the right side of the boundary rectangle. Number of shifts here is O(N), and the time complexity of this algorithm depends on how effectively you can find an empty space at each step. Many approaches are possible here - a simplest one will be based on sorting of Y-coordinates. Also you can represent the active set of rectangles using some data structure. I'm leaving this part to you.


Using Categories in Objective C

Question: I have a file called ViewMessages.m which is becoming quite verbose. I'd like to refactor and put part of my methods into a separate file. It seems that Categories are the right way to go, so I've created a Category on ViewMessages called DataEngineViewMessages
It created 2 files, DataEngineViewMessages.h and DataEngineViewMessages.m
My Question: Do I need to #import "DataEngineViewMessage.h" in my original ViewMessage.h or .m in order to access my new methods?
Comment: If you're accessing the methods from the category in the original class (instead of the opposite, which is normal), then I'd say you don't have a good design.
Answer: Not into the .h file. The category header should import ViewMessages.h, and if required the category header should be imported into ViewMessages.m. This prevents any kind of circularity.
Usually you want to differentiate between category methods that should be public (defined in a header perhaps like ViewMessages+DataEngine.h) and category methods that are for internal use (defined in a header perhaps like ViewMessages+Private.h). The former shouldn't be included by ViewMessages and the latter should (again, in the .m file).
Comment: what exactly does "if required" mean? If I write methods in DataEngine.m that I want to use in ViewMessages.m?
Comment: Yes, exactly. Usually those methods would be private, but not always.
Comment: In the case that the methods are private, I can simply declare my methods in dataengine.h, write them in dataengine.m, and then import dataengine.h in viewmessages.m to use them? As a side question, will @properties defined in viewmessage.h be accessible in dataengine.m? Thanks
Comment: Yes, and yes. Because dataengine.h imports viewmessages.h
Comment: I just tried implementing the above design, however I'm unable to access the properties of ViewMessage.h in DataEngine.m even though I'm #import "ViewMessage.h" in DataEngine.h
Comment: do I have to create an instance of ViewMessage every time I want to access one of the properties of ViewMessage.h?
Comment: You need to access them through `self.` (you don't create a new instance, the category methods are called on an instance)
Answer: Any code that calls the methods will raise a compiler warning if the compiler can't see the method definition. They may also raise an error if the compiler can't figure out exactly what to do about the return type and you're expecting it to be an atomic C type.
In terms of keeping the external interface untouched, you can probably just add a #import for your category methods at the bottom of the main class's header file.

Using Categories in Objective C


O que é a linguagem de programação Ballerina?

Question:

Ballerina is an open-source programming language for the cloud that makes it easier to use, combine, and create network services.

Seguindo a mesma lógica de outras perguntas aqui com a finalidade de entender melhor alguma ferramenta/linguagem pouco conhecida no mercado, pergunto o que é a linguagem Ballerina?
Em sua descrição traz "linguagem para nuvem que facilita o uso, a combinação e a criação de serviços de rede", o que isso significa? Que outras características dessa linguagem podem fazê-la competitiva com as linguagens mais usuais?
Trecho de exemplo da linguagem retirado da documentação oficial:
import ballerina/http;

service /hello on new http:Listener(9090) {
    resource function get sayHello() returns string {
        return "Hello Ballerina!";
    }
}

Comment: Vamos ver se alguem consegue explicar "que problema ela resolve". Aguardemos as respostas...
Comment: E se possível, os problemas que ela gera.....
Answer:
Nota: Sou engenheiro da equipe responsável pelo compilador da linguagem Ballerina.

Qual problema ela resolve?
Ballerina visa facilitar a criação de serviços de rede seguros e com bom desempenho. É uma linguagem de propósito geral, assim como muitas outras, mas além disso, há recursos que foram adicionados (e outros que foram removidos) para facilitar o trabalho com a rede.
Em primeiro lugar, a linguagem possui suporte à representação gráfica do código, gerando diagramas de sequência automaticamente. Um dos objetivos finais é garantir que qualquer programa escrito em Ballerina possa ser visualizado através deste diagrama.
Alguns recursos da linguagem:

Tem um sistema de tipo estrutural (semântico), o que significa que os nomes dos tipos não importam, apenas a forma do tipo é considerada. Isso a torna mais semelhante às linguagens dinamicamente tipadas, enquanto fornece a segurança e o suporte de ferramentas de linguagens estaticamente tipadas.
É null safe.
Tem um modelo de threading leve, onde pode-se escrever código de maneira simples e fazer com que seja executado em paralelo.
Podemos gerar artefatos de implantação de Docker e Kubernetes com uma configuração simples.
Tem um sistema de gerenciamento de configuração embutido.

Uma lista mais elaborada dos recursos pode ser encontrada nesta apresentação.

Na documentação é possível ver a maioria dos recursos disponíveis da linguagem. Especificamente na seção Working Over the Network há vários exemplos de serviços HTTP, como esse:
import ballerina/http;

type Student record {
    string Name;
    int[] Grades;
};

service / on new http:Listener(9090) {

    // This resource method serve http GET requests to path /hello/[XXXXX] and the value XXXXX will be bound to a parameter `name`
    resource function get hello/[string name]() returns string {
        return string `Hello ${name.toUpperAscii()}`;
    }

    // /queryPramToJson?name=Jane&id=443948333
    resource function get queryPramToJson(string name, string id) returns json {
        return {user_name: name, id};
    }

    // Query params, the hard way
    // localhost:9090/queryParamObject?name=Jane
    resource function get queryParamObject(http:Request req) returns json {
        map<string[]> qParams = req.getQueryParams();
        string[]? name = qParams["name"];
        if name == () {
            return "No query param found with name=name";
        }
        else {
            return "Hello " + name[0];
        }
    }

    // `val` extracted from http header.
    resource function get header(@http:Header string? val) returns json {
        return {value: val};
    }

    // Ballerina natively support JSON
    // This resource is serving http POST requests as we want to pass data as http payload
    resource function post jsonEcho(@http:Payload json j) returns json => j;

    // Json structure similar to { "Name": "Miranda", "Grades": [65, 99, 88] } will be mapped to `Student` type.
    resource function post bumpGrades(@http:Payload Student student) returns json {
        string name = student.Name;
        int[] newGrades = student.Grades.map((i) => int:min(i + 10, 100));
        int sum = 0;
        foreach var i in newGrades {
            sum += i;
        }
        int avg = sum / newGrades.length();

        return {Name: name, Grades: newGrades, Average: avg};
    }

    // XML is natively supported.
    resource function post extractCity(@http:Payload xml store) returns xml {
        // Extract a descendent element from a xml value.
        xml city = store/**/<city>;
        return city;
    }
}

Comment: What is the relationship of the language with Java? Could you give concrete examples about the network services you mentioned?
Comment: At the moment, Ballerina is a JVM language. We have a small team working on a native compiler, but it will take a couple of years for it to be production ready.
Comment: @Woss I updated the answer with an example and a pointer to more sample code.


Flask WTF Selectfield choices not being displayed properly while fetching from mysql

Question: so I am trying to populate Flask form's SelectField from a mysql database. This is the relevant code:
app = flask.Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/vshdb?'
app.config['SECRET_KEY'] = 'mysecret'
db = SQLAlchemy(app)
admin = Admin(app)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'vshdb'

mysql = MySQL(app)

#Creating a connection cursor

#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/vshdb'

class history(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    vendorName = db.Column(db.String(100))
    vendorCompany = db.Column(db.String(100))
    sopVer = db.Column(db.Numeric)
    sopName = db.Column(db.String(100))
    entryDate = db.Column(db.Date)

class vendorForm(FlaskForm):
    vendorCompany = SelectField('vendorCompany', choices=[], validators=[DataRequired()])
    vendorName = SelectField('vendorName', choices=[], validators=[DataRequired()])
    sopName = SelectField('sopName', choices=[], validators=[DataRequired()])
    sopVer = StringField('sopVer', validators=[DataRequired()])

@app.route('/test')
def test():
    form = vendorForm()
    cursor = mysql.connection.cursor()
    cursor.execute("SELECT DISTINCT vendorCompany from history")
    vendCompChoices = cursor.fetchall()
    print(vendCompChoices)
    form.vendorCompany.choices = [(vC, vC) for vC in vendCompChoices]

    return render_template('FlaskForm.html', form=form)

And this is my test html template:
<!doctype html>

       <form method="POST">
           {{ form.csrf_token }}
           {{ form.vendorCompany }}
           <input type="submit" value="Go">
        </form>

I am able to get unique values in the Selectfield, but they are not being displayed properly. This is how they are coming:

The values are correct, but the formatting isn't
This is the outcome of print(vendCompChoices):
(('',), ('ABC',), ('qw',), ('qfadas',), ('eqwe',), ('asdas',), ('wqeq',))

Please help
Answer: First import QuerySelectField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
Then define a function with query:
def vendor_name_choices():
    return history.query.with_entities(history.vendorCompany).all()

Then modify your form
class vendorForm(FlaskForm):
    vendorCompany = SelectField('vendorCompany', validators=[DataRequired()], query_factory=vendor_name_choices)
    ...

After some update, this is what I did, and it works except the distinct values part:
def vendor_name_choices():
    return history.query

class vendorForm(FlaskForm):
    vendorCompany = QuerySelectField('vendorCompany', query_factory=vendor_name_choices, validators=[DataRequired()], get_label='vendorCompany')

Comment: Its giving me following error:
```
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'sqlalchemy.util._collections.result' is not mapped
```
Comment: I don't have your code to test, but using current_app.app_context, can't you popultate choices=[]?
Comment: I couldn't find anything using current_app.app_context to populate the choices
Comment: I could make it work, but except the distinct part, can you help me with that please? I have updated your answer above
Comment: @RaghavChamadiya what do you mean by distinct?
Comment: So, if "ABC" is present 2 times in the column, it should appear only once in the Select Field
Comment: Just filter it out, it's beyond flask-wtf


Find the dimension of the kernel

Question: Consider the map $T$ from the vector space of polynomials of degree at most $5$ over the reals to $\mathbb{R}\times \mathbb{R}$, given by sending a polynomial $P$ to the pair $(P(3),P′(3))$, where $P′$ is the derivative of $P$. How to find the dimension of the kernel.
Answer: If we call the domain vector space $V$, this has dimension $6$ (it has a basis $\{1, x, \ldots, x^5\}$).
If you show $T$ is surjective then the theorem that says $\dim(V) = \dim(\ker(T)) + \dim(\operatorname{Im}(T))$ implies that the dimension of the kernel must be $4$.
Or directly:
Any polynomial $p$ in the kernel must be of the form $p(x) = a(x)(x-3)^2$:
Write $p(x) = a(x)(x-3)^2 + b(x)$ by Euclidean division, where $a(x)$ and $b(x)$ are polynomials with $\deg(b(x)) < \deg((x-3)^2) = 2$.
We must have $p(3) = 0$ so $b(3) =0$ and $p'(3) = 0$ forces $b'(3) = 0$.
($p'(x) = a'(x)(x-3)^2 + 2a(x)(x-3) + b'(x)$ and the first two terms vanish at $3$). And as $b(x)$ is linear, these two facts force $b(x) = 0$)
As the degree of $a$ can be at most $3$, a basis for the kernel of $T$ is
$\{(x-3)^2, x(x-3)^2, x^2(x-3)^2, x^3(x-3)^2\}$.

Find the dimension of the kernel


Probability of correctly declaring number as prime

Question: It is known that a way to check whether a number $n$ is prime, is to check for divisors of $n$ from $2$ to $\lfloor\sqrt{n}\rfloor$. If we find any divisor, then $n$ is not prime. If we don't, then we don't need to check for divisors bigger than $\sqrt{n}$ (and $n$ is prime).
An "approximation" of this method would be to check for divisors the same way but from $2$ to $log_2n$. If we find any divisor we declare that $n$ is not prime. If we don't find any divisor we declare that $n$ is prime. Of course this method will not always give the correct results. My question is:
If the second algorithm declares a number to be prime, what is the probability that this number is actually prime?
Comment: For large numbers, lets say , $100$ - digit numbers many composites will be declared as prime. Which is the magnitude you are interested in ?
Comment: I upvoted this question in particular because it enlights that even massive trial division does not make the primality test of a huge number necessarily feasible. Even ruling out prime factors to $10^{50}$ would only increase the probability that we have a prime by factor $205$, hence a number of , lets say, $10\ 000$ digits would still have a very small chance to be prime. This is why finding huge primes is so difficult.
Comment: @Peter Large numbers is the magnitude I am interested in. Let $n$ be a random positive integer.(So it is almost always very large)
Answer: For very large numbers we can estimate the probability as follows :
Let $N$ be the given number , then $M:=\frac{\ln(N)}{\ln(2)}$ is the limit of trial division.
Denote $$P:=\prod{\frac{p}{p-1}}$$ where $p$ runs over the primes upto $M$, if $M$ itself is very large, we can approximate this as $$P\approx \frac{e^{-\gamma}}{\ln(M)}$$ where $\gamma$ is the Euler-Mascheroni-constant.
Then, the probability that we have a prime, if no factor is found, is roughly $$\frac{P}{\ln(N)}$$
For numbers $N\approx 10^{99}$ , we get about $4.6$%
Comment: Does this assume that the event that a number's least prime factor is greater than $\log_2 n$ is independent from the number being prime? If that fact is in any way correlated with a number being prime, the probability may not work out so cleanly, would it? How does one know the events are not correlated? (I am definitely not saying that this is incorrect, I am just curious if that is already part of the calculation).
Comment: @InterstellarProbe If $N$ is so large that the product of the primes upto the limit of the trial division is much smaller , then this probability will be near to the true probability. The probability for a "random" number to be prime is about $\frac{1}{\ln(N)}$ , and with the theorem of Bayes we can easily derive the probability given in my answer.
Comment: For $10^{99}$ , the product is in fact bigger than $N$, but still the dependecies between the small prime factors should not be too dramatic. I think, my approximation still works well.
Comment: Interesting. I never got too in depth with number theory, but it is very cool that works :). I'll have to think more on it.
Comment: Also note that in the case, there is a factor in the trial division range, the number is not prime (if $N$ is sufficiently large). Hence only the case that no factor is found is relevant.
Answer: Suppose $n$ is a random positive integer from $1$ to $N$.  By the Prime Number Theorem, the probability that it is prime is on the order of $1/\log N$.  On the other hand, for each
prime $p < \log N$ the probability that it is not divisible by $p$ is $1 - 1/p$, so the probability that it has no prime factors $< \log N$ is on the order of
$$ \prod_{p \le \log N} (1 - 1/p) \approx \exp \left( - \sum_{k=2}^{\log N} 1/(k \log k) \right) \approx \exp(- \log\log\log N) = \frac{1}{\log \log N}$$
Thus the probability that a number that passes the test is prime is on the order of
$$ \frac{\log \log N}{\log N} $$
Comment: In your answer you say "for each prime $p<log N$" but the question was about testing for divisors until $log_2 n$. I know that $log_2n=O(logn)$ but why does that mean that your checking for prime factors until $log N$ gives the same result to my question as testing for prime factors until $log_2 N$?
Answer: The probability that $n$ is not divisible by $p$ is : $1-\frac{1}{p}$, then
The probability that $n$ is prime is :
$$\prod_{\substack{\log_2(n) < p \leq \sqrt{n} \\ \text{p prime}}} \left( 1 - \frac{1}{p} \right)$$
Consider Mertens 3rd theoreme as $n \to +\infty$:
$$\prod_{\substack{p \leq n \\ \text{p prime}}} \left(1-\frac{1}{p}\right) \sim \frac{e^{-\gamma}}{\log(n)}$$
Then :
$$\prod_{\substack{\log_2(n) < p \leq \sqrt{n} \\ \text{p prime}}} \left( 1 - \frac{1}{p} \right) \sim \dfrac{2 \log(\log_2(n))}{\log(n)}$$


Change JFileChooser to a Microsoft look and feel?

Question: Is there any better option than JFileChooser. I would like to have the windows look in my application and Java JFileChooser. Is there a way to customize the JFileChooser or to change the look. I know about look and feel but will that work for my purposes. The JFileChooser works but it has the old 80s look to it and that is not what I want and neither do the users of the program.
Question: Can you turn the JFileChooser into a Microsoft Look and Feel?
Code:
package TestMenu;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FileChooserDemo extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;
    static private final String newline = "\n";
    JButton openButton;
    JButton saveButton;
    JTextArea log;
    JFileChooser fc;

    public FileChooserDemo() {
        super(new BorderLayout());

        log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);

        fc = new JFileChooser();

        openButton = new JButton("Open a File...");
        openButton.addActionListener(this);

        saveButton = new JButton("Save a File...");
        saveButton.addActionListener(this);

        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);

        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(FileChooserDemo.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                log.append("Opening: " + file.getName() + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
        } else if (e.getSource() == saveButton) {
            int returnVal = fc.showSaveDialog(FileChooserDemo.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                log.append("Saving: " + file.getName() + "." + newline);
            } else {
                log.append("Save command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
        }
    }

    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = FileChooserDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("FileChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new FileChooserDemo());

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        createAndShowGUI();
     }
}

Answer: Of cause, if you are on a Microsoft Plattform then try in your JFrame class
try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedLookAndFeelException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

Comment: UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); With this you can set the Look and Feel of your current Plattform to your Java Appication.
Comment: is the MainFrame.class.getName... is that the name of my class that I put this code in. It works and that is what I did so I was just wondering.
Comment: You should have a class which extends JFrame and where you call add(FileChooserDemo()) to the contentPane, and there you place the above code.
Comment: I do that. But MainFrame.class.getName().log... etc is that the name of my class because I tried it with MainFrame class and it told me to create a class called MainFrame. So i figured that was incorrect. Then by accident I changed it to the name of a class that is in the same package and it gave no errors. Then I realized that it probably was supposed to be the class that I am working in so I put it as that, and there were no errors.
Comment: Vice Versa can you make it look like a Mac on a Windows machine.
Comment: Sorry, this is not possible, because of copyright "problems", if you want to have the same look and feel on every plattform just use ´CrossPlatformLookAndFeel´, this is the "Java Look and Feel", it is also called ´Metal´.
Comment: If your on a mac what is the string?


Problem distinguishing certain P4 and P5

Question: When I was doing ear training, I found it's very difficult for me to distinguish some P4 and P5 intervals (harmonically), mostly around C3 or lower. For instance, if a perfect fifth, C3 and G3 are played simultaneously, it sounds more like C4 and G3 to me, which I think would be a perfect fourth. It seems difficult for me to hear the fundamental tone of C3, however I'm more sensitive to its overtones.
For higher notes this won't be a problem. Nor if it's a melodic interval (i.e. notes are played one by one).
What might have gone wrong with me? I use the "Complete Ear Trainer" app by the way.
Answer: I don't think anything has gone wrong with you.  Perfect 5th and 4ths both have an open, pure sound to them.  Try isolating and distinguishing between the notes being played.  Maybe pick the top note as that would be easier to catch.  Then sing down to the bottom note.  It should be easy to recognize going down a 4th (if it's C4 to G3).  Also, the perfect 5th sounds a bit more stable and full than the forth.  With practice you will be able to differentiate between the fundamentals and the overtones.
Answer: As already mentioned, P4 and P5 are inversions of each other. as in C>G=P5, G>C=P4. So they will sound similar in isolation. Intervals are named from the lower to the higher note, so you need to try to determine which is which, and concentrate on the lower.
Listen to the intro of 'Chasing Cars', that's the P5 interval. Listen to 'Auld Lang Sine' beginning, it's P4.
They're both 'firm' and hard sounding intervals - used by piano tuners, which doesn't help you, but does them! The lower the notes, the more muddy the sound, so hearing each separate rather than both simultaneously will help.It also may be that the speakers/headphones you use don't produce a clear enough sound at the bottom.
Answer: Invert a Perfect 4th (put the bottom note on top) and you get a Perfect 5th.  And vice versa.   Sounds like you're having trouble perceiving which octave each note is in.  Do you have the same trouble when listening to a real instrument like a piano, or just with this 'app'?  Computer sounds and computer speakers can confuse the issue.
Answer: I think the advice they give you above is good. But in any case, I just wanted to ask whether you sing the notes or not. If you don't you will find that singing the notes helps a great deal. Singing helps you internalize the interval so later you won't have to do it bc you will hear it right away but at the beginning it will help. It took me a while to distinguish P4 and P5 from one another too.


UITableView Cell Button mixed up

Question: I have a problem, setting a button to a UITableviewCell.
After viewDidLoad, the button is on the right place. But when I am scrolling down, the button is anyplace else.
Here is my code, I hope you can help me.
Thanks In Advance.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

if (indexPath.section == 0 && indexPath.row == 0 && _isAddImageViewLoad == NO) {
    // Add Image Button
    UIButton *addImage = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage* image = [UIImage imageNamed:@"AddImage@2x"];
    addImage.frame = CGRectMake(110.0f, 10.0f, 110.0f, 110.0f);
    [addImage setImage:image forState:UIControlStateNormal];

    [cell.contentView addSubview:addImage];
    _isAddImageViewLoad = YES;
} else {
    NSDictionary *dictionary = [_items objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"data"];
    NSString *cellValue = [array objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;
}

return cell;

}
Comment: Could you perhaps give some more information and make it a bit more clear what the problem is?
Answer: It is because you are reusing the cells, and the button is getting placed when it shouldn't an easy solution in your else section. Write addImage.hidden = YES; and in your if statement put addImage.hidden = NO;
Answer: Look at this line of code:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

This line of code means the UITableViewCells are not created every time. They are re-used as you scroll up and down. Using the code you have above, the UIButton will be created in the correct spot, but then as the cells are re-used, it will create the button in random spots.
One quick way to solve the problem, change the above line of code to simply
UITableViewCell *cell;

Comment: Then he isn't reusing cells and the scrolling performance will suffer
Comment: Instead of not reusing cell its better to use two seperate identifier for one with button and and other with not
Comment: That is an option too, but not reusing cells, definitely not an option
Answer: Just a couple things.  If you use "AddImage" it will use the "AddImage@2x" automatically if it's a retina display. I don't think that will solve your issue but it could be causing weirdness.
When a table view cell is scrolled off the view it is "recycled" in a sense. It appears like you are using a bool to exclude the original cell from being loaded again with a button. You may want to use a header to hold your button if you always want it at the "top".  You may also want to verify that the button is being removed when the cell is reused. if its not it will show up in the next row that reuses that cell.
On a side note... Buttons don't usually work very well in table view cells because they handle touches in very different ways.  It's quite a bit of modification to get them to feel natural but that's another matter.
Hope that helps!
Comment: Thank you very much. For my issue it was the best, to set a button to the header.
Comment: Glad I could help!  Interestingly enough I had an interview question recently and it was "How do you get a UIButton to work correctly in a UITableViewCell."  It was quite the question to work through :)
Answer: The problem is because of cell reuse. You need to put some code in the else clause to delete the button if it exits. One way to do this, would be to give your button a tag, like:
addImage.tag = 10;

Then in your else clause:
}else{
    if (cell viewWithTag:10) [[cell viewWithTag: 10] removeFromSuperview];
    ...

Answer: The problem is because of the dequeue for the cells.  The first time the tableview creates the cells, all the cells run through the
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

code.  But when the section 0 row 0 is moved off the screen, that cell is pushed into the cell reusable queue.
Now when your tableview needs to display section 0 row 0, it will get a cell from the reuse queue.  you will not get the same cell as the first time.  So now you might have 2 cells with the button.
What you should do is have different CellIdentifier for section 0 row 0 , and all other sections and rows.  Also create the button when creating the cell. So after the first time the tableView creates the cell, you will not be creating the the button everything.

UITableView Cell Button mixed up


Statistical tests

Question: Can someone please explain the difference between difference test and correlation test?
I am confused because e.g. if a mean of one group (males) is significantly different from the other (females), isn't there a correlation between this mean and its group at the same time?
Answer: The word correlate is sometimes used informally as you use it, but in statistics it has a more formal definition.
If you measured height and weight in a bunch of kids of different ages, you'd find that on average the taller kids are also heavier. You could say then that height and weight are correlated.
If you measured height in men and women, you'd find that on average the men are taller. But a statistician wouldn't usually say that height correlates with gender. The concept is correct, but the term correlate is rarely used like that.
Comment: I find it helpful to try to draw the distinction between *association* (i.e.  knowing something about *X* tells you something about *Y*), and *correlation* which is an quantified measure of such association. Of course, different measures of correlation have different assumptions and properties built in.

Statistical tests