Save a yaml file to a generator object to a dictionary python

Question: I am having a lot of issues saving a YAML file to a python dictionary. I will display two routes I take below, both being suboptimal.
Yaml file:
modules:
    module_1: True
    module_2: True
    module_3: False
scenarios:
    constant:
        start_date: "2018-09-30"
        end_date: "2019-09-30"
    adverse:
        start_date: "2019-09-30"
        end_date: "2022-09-30"

Route 1: Saving YAML file directly to a dictionary without specifying a loader which is now depreciated
import yaml
filepath = "C:\\user\\path\\file.yaml"
_dict = yaml.load(open(filepath))
print(type(_dict))
>>> <class 'dict'>

error message: Calling yaml.load() without loader=... is depreciated, as it is unsafe

Route 2: Loading in as a generator (which is not subscriptable)
import yaml
filepath = "C:\\user\\path\\file.yaml"
document = open(filepath, "r")
dictionary = yaml.safe_load_all(document)

print(type(dictionary)
>>> <generator object>

print(dictionary["modules"]["module_1"]
>>> generator object is not subscriptable

Is there a way I can import my yaml file into a dictionary safely? I wish to use the dictionary in my python project instead of creating global variables, etc.
Example:
if _dict["modules"]["module_1"]:
    # Do something

Comment: Try using `safe_load` instead of `safe_load_all`?
Comment: Adeom has provided the answer
Answer: Only calling without loader was depracted. You can always pass SafeLoader to the load function.
import yaml

with open(filepath, 'r') as stream:
    dictionary = yaml.load(stream, Loader=yaml.SafeLoader)

This should return your dictionary.
edit:
And as for yaml.safe_load_all, you only need to call generator.__next__() to obtain the dictionary.
import yaml
filepath = "C:\\user\\path\\file.yaml"
document = open(filepath, "r")
generator = yaml.safe_load_all(document)
dictionary = generator.__next__()

I would recomend the first option for your use.


drush omega-guard and missing or unreadable gemfiles

Question: My machine is running Archlinux and and I am new in drush and omega theme.
I have installed drush and then run bundle install to install the dependencies of my subtheme.
When I run drush omega-guard, I get some errors which says the file to import not found or unreadable, while I have installed those gems too.
<code>[timmy@MyPC drupal-7.31]$ drush omega-guard
Which theme do you want to run Guard for?
 [0]  :  Cancel
 [1]  :  First (Subtheme of Omega) - My first theme.
 [2]  :  Ohm (Subtheme of Omega) - Omega based demonstration theme. Serves as a best-practice reference for the Omega documentation. Ohm
         will be constantly updated as best practice evolves so shouldnt be used in production.
 [3]  :  Omega - A powerful HTML5 base theme framework utilizing tools like Sass, Compass, Grunt, Bower, Ruby Version Manager, Bundler and
         more.
1
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
/home/timmy/.gem/ruby/2.1.0/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/timmy in PATH, mode 040777
    error sass/first.no-query.scss (Line 3 of sass/first.styles.scss: File to import not found or unreadable: breakpoint.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
    error sass/first.normalize.scss (Line 8: File to import not found or unreadable: toolkit/border-box.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
    error sass/first.styles.scss (Line 3: File to import not found or unreadable: breakpoint.
Load paths:
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  Compass::SpriteImporter
  /srv/http/drupal-7.31/sites/all/themes/first/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-core-1.0.1/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/susy-2.1.3/sass
  /usr/lib/ruby/gems/2.1.0/gems/compass-normalize-1.5/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/compass-rgbapng-0.2.1/lib/stylesheets
  /usr/lib/ruby/gems/2.1.0/gems/toolkit-2.6.0/stylesheets
  Sass::Globbing::Importer)
Compilation failed in 3 files.

07:11:22 - INFO - Guard::Compass is waiting to compile your stylesheets.
07:11:22 - INFO - LiveReload is waiting for a browser to connect.
07:11:22 - INFO - Guard is now watching at '/srv/http/drupal-7.31/sites/all/themes/first'
[1] guard(main)> help
</code>
Answer: Found the answer.
here is the solution:
https://www.drupal.org/node/2323235#comment-9069731


Quotient of Jacobson ring is Jacobson as in Eisenbud

Question: I wanted to prove the following:

Let $R$ be a Jacobson ring, $\mathfrak{p}<R$ a (prime) ideal. Then $R/\mathfrak{p}$ is Jacobson.

The statement has been taken from Eisenbud's Commutative Algebra with a View Towards Algebraic Geometry, p. 132 in the proof of lemma 4.20.
I want to prove it with what I have available there, hence:

A ring $R$ is Jacobson if $$\mathfrak{p}=\bigcap_{\substack{\mathfrak{m}\in\max(R)\\ \mathfrak{p}\subseteq\mathfrak{m}}}\mathfrak{m}\quad\forall \mathfrak{p}\in \operatorname{prime}(R)$$ where $\max(R)$ is the collection of maximal ideals and $\operatorname{prime}(R)$ is the collection of prime ideals in $R$.

We have to show that $\mathfrak{q}\in\operatorname{prime}(R/\mathfrak{p})$ implies $\mathfrak{q}=\bigcap_{\mathfrak{m}\in\max(R/\mathfrak{p}), \mathfrak{q}\subseteq \mathfrak{m}}\mathfrak{m}$. Let $\mathfrak{r}:=\bigcap_{\mathfrak{m}\in\max(R),\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}\pi(\mathfrak{m})$. In what follows I denote by $\pi:R\to R/\mathfrak{p}$ the canonical projection. I used the following claim:

Let $R$ be a ring, $\mathfrak{p}<R$ an ideal (not necessarily prime), $\mathfrak{m}$ a maximal ideal containing $\mathfrak{p}$, then $\pi(\mathfrak{m})$ is a maximal ideal and $\pi$ yields a bijection between maximal ideals containing $\mathfrak{p}$ in $R$ and ideals in $R/\mathfrak{p}$.

$$\begin{align*}\pi^{-1}(\mathfrak{r})=&\bigcap_{\substack{\mathfrak{m}\in\max(R)\\\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}}\pi^{-1}(\pi(\mathfrak{m}))\\ =&\bigcap_{\substack{\mathfrak{m}\in\max(R)\\\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}}\mathfrak{m}\qquad\text{(as of the 1-1 correspondence)}\\
=&\pi^{-1}(\mathfrak{q})\qquad\text{(as $\pi^{-1}(\mathfrak{q})< R$ is prime and $R$ is Jacobson)}\end{align*}$$
Because $\pi(\mathfrak{m})$ is an ideal for every $\mathfrak{m}\in\max(R)$ such that $\mathfrak{p}\subseteq\mathfrak{m}$ by the 1-1 correspondence, so is $\mathfrak{r}$ and as of the 1-1 correspondence between maximal ideals containing $\mathfrak{q}$ and maximal ideals containing $\pi^{-1}(\mathfrak{q})$, $\mathfrak{r}=\bigcap_{\mathfrak{m}\in\max(R/\mathfrak{p}),\mathfrak{q}\subseteq\mathfrak{m}}\mathfrak{m}$.
Thus the 1-1 correspondence implies $\mathfrak{r}=\mathfrak{q}$.
Question: does this make sense? Is this correct reasoning? Thank you!
Answer: What you have written doesn't quite make sense (though these may just be typos): if $\mathfrak{r}:=\bigcap_{\mathfrak{m}\in\max(R),\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}\mathfrak{m}$, then
$\pi^{-1}(\mathfrak{r})$ is not $\bigcap_{\substack{\mathfrak{m}\in\max(R)\\\pi^{-1}(\mathfrak{q})\subseteq\mathfrak{m}}}\pi^{-1}(\pi(\mathfrak{m}))$. Also, note that for any maximal ideal $\mathfrak{m}$ of $R$, $\pi^{-1}(\pi(\mathfrak{m})) = \mathfrak{m}$ always holds. As an alternative way to view the Jacobson condition, consider the following:
$\DeclareMathOperator{nil}{nil}
\DeclareMathOperator{rad}{rad}$
Proposition: Let $\nil(R)$ be the nilradical of $R$ (i.e. intersection of all primes), $\rad(R)$ the Jacobson radical of $R$ (i.e. intersection of all maximal ideals). The following are equivalent:
i) $R$ is Jacobson
ii) $\nil(R/I) = \rad(R/I)$ for every ideal $I$
iii) $\nil(R/p) = \rad(R/p)$ for every prime $p$
The implications (i) $\implies$ (ii) and (iii) $\implies$ (i) follow immediately from the correspondence of primes and maximal ideals in the quotient (try proving this carefully!). Once this characterization is shown though, the property of being Jacobson is seen to pass to any quotient, since any quotient of $R/p$ is still a quotient of $R$.
Comment: Thank you. $\mathfrak{r}$ should indeed be the intersection of the images. I will check your proposed statement. I wanted to do it in the "self-contained" way mentioned above though.
Answer: there is some nice reference on this topic you may want to have a look:
https://en.wikibooks.org/wiki/Commutative_Algebra/Jacobson_rings_and_Jacobson_spaces
For a solution in the "self-contained" way as you want:
Let $p$ be a prime in $R/I$, and it can be pulled back to the unique prime $P$ in $R$. Denote $\pi$ the canonical projection from $R$ to $R/I$. We also assume that
\begin{equation}
P = \cap M_{\alpha} \text{ ,where $M_{\alpha}$ is maximal.}
\end{equation}
Then we have the following:
\begin{equation}
p=\pi(\pi^{-1}(p))
=\pi(P)=\pi(\cap M_{\alpha})=\cap \pi (M_{\alpha})
\end{equation}
It's worth noticing that the last equality doesn't hold in general.
In this case, the nontrivial direction holds since
\begin{equation}
\forall y \in\pi(\cap M_{\alpha}),\forall \alpha, (y+ I)\subset M_{\alpha}+I
\end{equation}
This leads to $y=x_{\alpha}+i_{\alpha}$ ,where $x_{\alpha} \in M_{\alpha}$ and $i_{\alpha} \in I$
So $ \forall \alpha , y\in M_{\alpha} $
Comment: The trivial part is $\pi(\cap\mathfrak{m}_i)\subseteq \cap\pi(\mathfrak{m}_i)$. If $y+I\in$ R.H.S. then $y=x_i+j_i, x_i\in \mathfrak{m}_i,j_i\in I$. This does not imply in general, that $y+I\in $L.H.S.
Comment: I don't think there is some big idea behind so I prefer to post the little trick in detail.
Comment: Also, the reference gives another nice characterization of Jacobson rings.


BigQuery: Retrieve rows that are unique across two columns, otherwise row with largest third column

Question: I have a BigQuery table, my_table, that looks like the following:
+---------+---------+-------+------------------+----------+--------+-----+--------+
| poll_id | user_id | count |    timestamp     | timezone | answer | age | gender |
+---------+---------+-------+------------------+----------+--------+-----+--------+
|       1 |       1 |     5 | 2019-08-06 11:00 |        1 | no     |  25 | male   |
|       1 |       1 |    10 | 2019-08-06 10:00 |        1 | no     |  25 | male   |
|       1 |       1 |    10 | 2019-08-06 10:30 |        1 | yes    |  25 | male   |
|       1 |       2 |    10 | 2019-08-06 11:00 |        1 | no     |  35 | male   |
|       1 |       2 |    20 | 2019-08-06 11:00 |        1 | no     |  35 | male   |
|       1 |       2 |    35 | 2019-08-06 11:00 |        1 | NULL   |  35 | male   |
|       2 |       1 |    10 | 2019-08-06 10:35 |        1 | no     |  25 | male   |
|       3 |       1 |    10 | 2019-08-06 10:35 |        1 | NULL   |  25 | male   |
+---------+---------+-------+------------------+----------+--------+-----+--------+

I want to retrieve rows that fulfill the following requirements:

If the row has a unique combination of poll_id and user_id, include the row if it has a non-NULL value in answer
If the row does not have a unique combination of poll_id and user_id:

Include the row with the largest count that is not NULL in the answer column

If there are two rows with the same count (and non-NULL answer), include the row with the largest timestamp

I also want to be able to limit the search to a specific date and timezone, for example a date of 2019-08-06 and a timezone of 1, and I don't want to retrieve the rows with a value of NULL in user_id.
So far, I've tried the following standard SQL statement:
  SELECT
    t1.poll_id,
    t1.user_id,
    t1.count,
    t1.timestamp,
    t1.timezone,
    t1.answer,
    t1.age,
    t1.gender,
  FROM
    `my_table` t1
  LEFT JOIN
    `my_table` t2
  ON
    t1.poll_id = t2.poll_id
    AND t1.user_id = t2.user_id
    AND t1.count < t2.count
    AND t2.answer IS NOT NULL
    AND DATE(t2.timestamp, "+1:00") = "2019-08-06"
  WHERE
    t1.user_id IS NOT NULL
    AND t1.answer IS NOT NULL
    AND DATE(t1.timestamp, "+1:00") = "2019-08-06"
    AND t1.timezone = 1
    AND t2.count IS NULL

The expected result for the shown table is:
+---------+---------+-------+------------------+----------+--------+-----+--------+
| poll_id | user_id | count |    timestamp     | timezone | answer | age | gender |
+---------+---------+-------+------------------+----------+--------+-----+--------+
|       1 |       1 |    10 | 2019-08-06 10:30 |        1 | yes    |  25 | male   | // count = 10 and largest timestamp
|       1 |       2 |    20 | 2019-08-06 11:00 |        1 | no     |  35 | male   | // count = 20 (the 35 row had NULL in 'answer')
|       2 |       1 |    10 | 2019-08-06 10:35 |        1 | no     |  25 | male   | // unique 'poll_id', 'user_id' combination
+---------+---------+-------+------------------+----------+--------+-----+--------+

However, it seems there are two problems:

If there is more than one row with the same (largest) count value, all those rows are retrieved. This means both row 2 and 3 are retrieved in this example.
If there are exactly two rows for a poll_id, user_id combination, neither is retrieved, even if they have different count values.

That is at least how it seems. I'm having a hard time tracking the problem and, of course, figuring out the correct query.
Any help would be appreciated.
Answer: For this type of query, row_number() is usually appropriate.  I think this fits what you have described:
select t.*
from (select t.*,
             row_number() over (partition by poll_id, user_id order by count desc, timestamp desc) as seqnum
      from my_table t
      where answer is not nll
     ) t
where seqnum = 1;

Answer: Below is for BigQuery Standard SQL
#standardSQL
SELECT * EXCEPT(pos)
FROM (
  SELECT *,
    ROW_NUMBER() OVER(PARTITION BY poll_id, user_id ORDER BY count DESC, timestamp DESC) AS pos
  FROM `project.dataset.table`
  WHERE NOT answer IS NULL
  AND NOT user_id IS NULL
  AND timezone = 1
  AND SUBSTR(timestamp, 1, 10) = '2019-08-06'
)
WHERE pos = 1

If to apply to sample data from your question - result is
Row poll_id user_id count   timestamp           timezone    answer  age gender
1   1       1       10      2019-08-06 10:30    1           yes     25  male
2   1       2       20      2019-08-06 11:00    1           no      35  male
3   2       1       10      2019-08-06 10:35    1           no      25  male


Simple Sturm-Liouville Problem $(Lx)(t)=-x''(t)$

Question: Given the SL operator $L=-\frac{\mathrm{d}^2}{\mathrm{d}x^2}$ and the boundary conditions
$f'(0)=0,\ f'(1)+f(1)=0$
I want to compute eigenvalues and eigenvectors.
Since we have $f''+zf=0$ the solution is given by
$f=c_1\sin(\sqrt{z}x)+c_2\cos(\sqrt{z}x)$
The first boundary condition $f'(0)=0$ gives $c_1=0$ and the second one
$c_2\left ( \cos(\sqrt{z})-\sin(\sqrt{z})\sqrt{z}\right )=0$ so we need
$z=\mathrm{cotan}^2(\sqrt{z})$
I am not sure how to go from here.
Answer: That is all that there is to this problem. Perhaps you should add some remark why you exclude negative $z$ resp. how they are still included in the formula.
Then you can try to find quantitative properties of the eigenvalues, for large $z$ these will be close to the poles $\sqrt{z}\approx k\pi$ of the co-tangent. Then with $\sqrt{z}=k\pi+u_1$
$$
(k\pi+u_1)=\cot(k\pi+u_1)=\cot(u_1)
$$
has the approximate solution
$$
u_1\approx\tan(u_1)=\frac1{k\pi+u_1}\approx\frac1{k\pi}-\frac{u_1}{k^2\pi^2}
$$
so that
$$
u_1\approx\frac{k\pi}{1+k^2\pi^2}.
$$
Numerical computation confirms that formula
<code> k     x0=k*pi       x1=x0+x0/(1+x0^2)   numerical sol.

 1   3.14159265359     3.43061813581     3.42561845948
 2   6.28318530718     6.43840840331     6.43729817917
 3   9.42477796077     9.52970005277     9.52933440536
 4  12.5663706144     12.6454473268     12.6452872239
 5  15.7079632679     15.7713682744     15.7712848748
 6  18.8495559215     18.9024586756     18.9024099569
 7  21.9911485751     22.0365275822     22.0364967279
 8  25.1327412287     25.1724670728     25.1724463266
 9  28.2743338823     28.3096574619     28.3096428545
10  31.4159265359     31.4477253056     31.4477146375
11  34.5575191895     34.5864322411     34.5864242153
12  37.6991118431     37.725619016      37.7256128278
13  40.8407044967     40.8651752015     40.8651703305
14  43.9822971503     44.0050218233     44.0050179208
15  47.1238898038     47.1451009112     47.1450977368
16  50.2654824574     50.2853689545     50.2853663378
17  53.407075111      53.4257926597     53.4257904774
18  56.5486677646     56.5663461188     56.5663442798
19  59.6902604182     59.7070088694     59.7070073053
20  62.8318530718     62.8477645357     62.8477631945
21  65.9734457254     65.9885998573     65.9885986985
22  69.115038379      69.1295039819     69.1295029739
23  72.2566310326     72.2704679426     72.2704670603
24  75.3982236862     75.4114842655     75.4114834888
</code>
Comment: For the positivity of the operator I showed that $\langle Lx,x\rangle \ge 0$ by integrating by parts.


Why the NIO code is faster than that of Java IO?

Question: I have lots of quests about Java NIO. I have read many articles where the discussion was digged deeper about it. But I really don't know in which aspects the NIO is quicker than IO.
Also I have observed that downloading a 100MB file with Java NIO code is at least 10 times faster than downloading with Java IO code.
Now my question regarding the fact is:
Suppose I am  downloading a file is 1KB. In this case, will NIO code still be ten times faster for a 1KB file?
Comment: Why don't you make some tests and find out yourself?
Answer: Generally speaking, NIO is faster than classic Java IO because it reduces the amount of in-memory copying.  However, a ten-fold improvement in speed is implausible, even for large files.  And when we are talking about downloading files (rather than reading / writing them to disk), the performance is likely to be dominated by the bandwidth and end-to-end latency to the machine you are loading from.
Finally, you are likely to find that the relative speedup of NIO for small files will be even less ... because of the overheads of establishing network connections, sending requests, processing headers and so on.
Comment: Thanks for your answer. Once again, can you be a little bit more specific in this line: "Finally, you are likely to find that the relative speedup of NIO for small files will be even less". Does it mean that 1kb file may take longer time?  P.S: I am not native english. Some phrases may confuse me.
Comment: No.  I'm referring to the relative speedup / speed improvement.  So a 100Kb file might copy 50% faster with NIO compared to classic IO, but a 1Kb file might copy 5% faster with NIO compared to classic IO.


Equation of plane passing through 3 points

Question: Given three points $a, b, c\in \mathbb R^3$, how do we find the equation of the plane passing through these three points?
Original Question : Let $p : \mathbb{R} \to \mathbb{R}^3$ be a twice differentiable parametric curve, which is nowhere straight. For arbitrary h find the equation of the plane that goes through the three points $p(t)$, $p(t+h)$, $p(t−h)$. Then find the equation of the limit plane that one obtains from letting $h\to 0$. Verify that the tangent and normal unit vectors at $p(t)$ lie on that plane.
I just want to know how to form the equation of the plane using the three coordinates provided. (Please no complete answer to the above question.)
Comment: @RobertLewis is the answer $$r=a+(b-a)t+(c-a)s$$?
Comment: Nice question, +1.  I added the "differential geometry" tag.
Comment: @RobertLewis Sorry that I made another changes to the question and took away the tag. The first version is just too misleading, the OP does not want ppl to solve that DG question....
Comment: @FaiqRaees Have you tried searching for "equation of plane passing through 3 points"?  Are you looking for an implicit equation? A parameterization?
Comment: @KyleMiller please look at the previous edited version of the question
Answer: The parametric equation of the plane passing through the three points $p(t)$, $p(t+h)$, $p(t−h)$ is
$$Q_{t,h}(r,s):=p(t)+\frac{p(t+h)-p(t)}{h}\cdot r+\frac{p(t-h)-p(t)}{-h}\cdot s$$
Comment: Can you please look at the previously edited version of the question? And respond in regards to that?
Comment: @Faiq Raees I have re-edited the question, otherwise it is hard to understand what' s going on.
Comment: Can you please tell why divide by h? Because I have learnt that if a,b,c are the vector points then the plane passing through them have the equation $$r=a+(b-a)s+(c-a)t$$
Comment: Because $r$ and $s$ are free parameters. Note that $Q_{t,h}(r,s):=p(t)+({p(t+h)-p(t)})\cdot r+({p(t-h)-p(t)})\cdot s$ is another parametric equation of the same plane.
Comment: Can you answer one last question? Is dividing by h essential to solve this question? Is it done to calculate the limit plane? On that note, can you clearing what a limit plane is?
Comment: @FaiqRaees It is done to calculate the limit plane. Do you know the term "osculanting"? See https://en.wikipedia.org/wiki/Osculating_plane
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/66320/discussion-between-faiq-raees-and-robert-z).
Answer: First, assume that the 3 points are not co-linear. The normal to the plane is then nontrivial:
$\mathbf n = (\mathbf b - \mathbf a) \times (\mathbf c - \mathbf a)$.
Let $\mathbf r$ be a point on the plane. The equation of the plane is:
$$
(\mathbf r - \mathbf a)\cdot \mathbf n = 0,
$$
or explicitly:
$$
(\mathbf r - \mathbf a)\cdot \big( \mathbf (\mathbf b - \mathbf a) \times (\mathbf c - \mathbf a) \big)= 0.
$$
Intuition: $(\mathbf r - \mathbf a)$ is a vector parallel to the plane, thus its dot product with the plane's normal has to vanish.
Comment: I did not see the original question, so my answer is to the general question


Is this the right way i should be coding my game to reset the score once the player dies?

Question: Score does not reach 0 once the player dies.
I tried all different kinds of methods and changing values but nothing seemed to work.
{
    //when the player's box collider collides with another box collider
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            //scene moves to a game over screen
            SceneManager.LoadScene("Player Death");
            //Reset score everytime player dies
            void resetScore()
            {
                PlayerPrefs.SetInt ("Score", 0);
            }
        }
    }
    // Start is called before the first frame update
    void Start()
    { }

    // Update is called once per frame
    void Update()
    {

    }
}

It was just building the score up from where it left off and didnt do as i programmed.
Comment: I would be calling PlayerPrefs.SetInt ("Score", 0); directly after the LoadScene().
Answer: Have you tried to reset the score right when the player dies? I assume you reset it on game start. Try doing it right after the player dies, or use it in a constructor when creating a new game/player. It isn´t clear how you implemented it, it would help if you post more pieces of code.
[EDIT]
Firstly, you are declaring the ResetScore Method, but you don´t call it to execute. So you need to declare it outside the "OnTriggerEnter" method, and then call it inside the method like this :
ResetScore();

Secondly, Why don´t you try to use property instead of SetInt?
public int Score { get; set;}

Then you can change it like this :
if (other.gameObject.tag == "Player")
    {
        Player.Score = 0;
        //scene moves to a game over screen
        SceneManager.LoadScene("Player Death");
        //Reset score everytime player dies
    }

Answer: You are declaring a new method resetScore() when a player dies, but you're never calling it.
What you should do is declare the method outside of OnTriggerEvent() and call it when a player dies:
//when the player's box collider collides with another box collider
private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "Player")
    {
        //scene moves to a game over screen
        SceneManager.LoadScene("Player Death");
        //Reset score everytime player dies
        resetScore();
    }
}
// Start is called before the first frame update
void Start()
{ }

// Update is called once per frame
void Update()
{

}

void resetScore()
{
    PlayerPrefs.SetInt("Score", 0);
}


Padrão de organização de projeto WEB (HTML, CSS, PHP)

Question: Eu não sei exatamente como organizar o meu projeto, eu estou fazendo da seguinte forma:
/produtos/
  cabecalho.php
  index.php
  rodape.php

dentro do cabeçalho e do rodapé tem um
if(verificacao != 1){sai da pagina}

e o meu index define a variável $verificacao = 1; para que as páginas só possam ser exibidas a partir do index.php
Eu sei que isso é uma gambiarra, mas foi uma forma que eu encontrei de organizar meu código e eu gostaria de saber se existe algum padrão de projeto, algum documentação para isso, uma orientação, algo assim.
Obs: Criar produtos.php e colocar tudo junto é inviável por que o código fica uma bagunça imensa (mesmo tendo um arquivo separado para o CSS e o JS).
Comment: Ok, qual é exatamente o problema que você pretende resolver? Organização de pastas ou bloquear alguns arquivos de serem acessados diretamente?
Comment: A resposta para isso será baseado em opinião, como previsto na [help] (se não viu, recomendo acessá-la e fazer o [tour]). Não existe regras sobre como você irá organizar o seu projeto. Somente você, como responsável, que pode determinar com base naquilo que facilita a sua vida.
Comment: Eu gostaria de uma ajuda na parte de organização.
Comment: Realmente eu sou quem decide, porém, eu gostaria de um auxilio, de alguem mais experiente que ja bateu nessa tecla e encontrou alguma luz que o ajudou kk.
Comment: Exemplos de organização, de seus próprios projetos ou de algum no qual você se baseia. A minha ideia aqui não é copiar/imitar, mas sim a de analisar e criar um "estilo" próprio a partir de coisas que funcionam e são realmente viáveis.
Comment: Se quer um rumo, busque por HTML boilerplate e estude tudo, mas tudo mesmo, dele.
Answer: Primeiro, não tem uma forma 100% certa de padronizar um projeto, o que tem por aí são alguns padrões preestabelecidos pela comunidade, que diz ser o melhor ou o a mais aceito, até aparecer alguma falha 'nesse padrão' (seja de segurança, usabilidade, performance, etc.).
O que eu sugiro, no entanto, é aprender os pontos fundamentais da linguagem em si que você escolheu usar como ferramenta de trabalho ou por hobby mesmo. Em seguida, aprender algum padrão desses já usados, como por exemplo o padrão MVC (Model-View-Controller), que, para mim, é muito complicado para um iniciante aprendê-lo.
Veja bem: até o Mozilla Firefox, em seu site de desenvolvimento, diz que não há um padrão.
O Facebook, por meio do seu Framework React JS, diz a mesma coisa.
Se você pegar 100 projetos de 100 empresas diferentes, verás que, numa probabilidade de quase 100% delas, os projetos serem diferentes, e, em alguns, não estarem em nenhum desses padrões preestabelecidos.
Novamente, para concluir, corroboro dizendo que o mais importante é aprender os fundamentos, isto é, aprender o que a sua linguagem de programação faz, suas principais características, etc, então, depois que tiver, ao menos, um certo domínio da mesma, escolher um padrão desse.  Pode ser até o MVC, mas com o advento da programação funcional, como por exemplo, em React Js (front-end), seria legal aprender as duas formas.
Além disso, veja a diferença entre programação monolítica, que, em resumo, é colocar tudo em um único lugar e programação baseada em serviços ou em micro-serviços, que as partes do seu projeto são colocadas em lugares diferentes. Atualmente, esse último está sendo bastante aceito.

Quando você disse: "o código fica uma bagunça imensa", você, provavelmente, referiu-se à programação monolítica (mesmo sem saber), embora na programação baseada em serviços, também haja bagunça.

No momento em que você aprender realmente os fundamentos da programação web, qualquer coisa que você colocar pra aprender, aprenderá facilmente, até mesmo qualquer padrão desse.
Então, comece com uma estrutura básica mesmo (pode ser a monolítica), você mesmo pode criar; entenda como se importa os arquivos, caminhos relativos, absolutos, por exemplo:
a diferença include, include_once, require, require_once, etc., em php.
root:
    - index.php (caso seja php)
    - assets (onde irão os arquivos css, javascripts, fontes)
    - class (pode colocar algumas classes php)

Eu, particularmente, não aconselho usar um padrão desse (MVC, etc.) no início, porque você não vai absorver muita coisa, podendo até atrapalhar a aprendizagem no início.
REFERÊNCIA:

https://pt.wikipedia.org/wiki/MVC
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript
https://pt-br.reactjs.org/docs/getting-started.html
Comment: Ja havia tentado o padrão MVC, mas é muito complicado ainda kk, eu sabia que existia algum outro padrão de projeto, mas não sabia que se chamava monolítica, você ja me deu um norte bem bacana, muito obrigado pela sua resposta, eu vou pesquisar sobre o conteúdo que você me indicou.
Answer: Alguns gostam de impor um padrão, mais você não precisa segui-los, tão pouco deve acreditar na frase "não reinvente a roda".
A vantagem de seguir o padrão é que você saberá resolver um problema de forma mais rápida e pratica, além de poder contar com a ajuda de outros desenvolvedores, sem que seja necessário mostrar o seu código, pois você estará de acordo com a documentação da linguagem, do framework ou mesmo do CMS, então poderá entender e usar os exemplos que existirem lá (na documentação), além disso, se você estiver fazendo um projeto para um cliente, seguir o padrão, facilitará para o próximo desenvolvedor modificar o código, embora alguns sabotem para o cliente retornar a quem "resolve". Você não falou se esta fazendo no código puro ou em um framework, mais no php puro, você pode fazer assim:
/Assets

   - css
   - img
   - js
   - vendor

/Int ou config

 - config.php
 - db.php
 - functions.php
 - route.php

// Aqui você coloca todos os arquivos de configuração

/Public

- index.php
- .htaccess
- manifest.json (opcional)
- sw.js (opcional)
- favicon.ico

/View
   - /layout
      - header
         - head.php
      - footer
         - footer.php
      - page.php // layout da pagina

  - /page(s)
    // suas paginas aqui

Basicamente é isso, porem, é mais fácil você usar o laravel se estiver sem tempo, pois, ele já tem ali tudo configurado.

os nomes dos arquivos não precisão ser em inglês, desconfie de quem diga isso.

no caso do route.php, você pode criar uma pasta ao invés de um arquivo, por exemplo
/router

api.php
rotas.php

eu prefiro substituir /header e /footer por /global e colocar tudo lá, mais você quem decide.

no caso da pasta Public, quando for passar para o servidor, pode colocar os arquivos na raiz do projeto, ela não é necessária.

/assets
/config
/router (opcional)
/view
index.php
.htaccess
manifest.json (opcional)
sw.js (opcional)
favicon.ico

você pode colocar todas as paginas na pasta view/pages, inclusive a home, e usar o arquivo index.php, apenas para carregar bibliotecas, como é feito no laravel.
Comment: Muito obrigado pela sua resposta cara, era exatamente isso que eu queria, um norte para eu poder me basear e organizar meu projeto.
Comment: de nada, precisando volte a postar : )


Solve integral $\iiint_Ax^pdxdydz$ on $A=\{(x,y,z):x^2+y^2+z^2<x^{\frac{1}{3}}\}$

Question: We have following integral to count:
$$
\iiint_Ax^pdxdydz
$$
where $p$ is constant real number and $A=\{(x,y,z):x^2+y^2+z^2<x^{\frac{1}{3}}\}$
I tried spherical substitution and cylindrical.
Comment: I guess $x \geq 0$. Isn't it ?.
Answer: By setting $x=w^3$, the triple integral turns into
$$3\iiint_{w^6+y^2+z^2<w}w^{3p+2}\,dw\,dy\,dz \tag{1}$$
that equals:
$$ 3 \int_{0}^{1}\iint_{y^2+z^2<w-w^6}w^{3p+2}\,dy\,dz   \,dw\tag{2}$$
or:
$$ 3\pi \int_{0}^{1}w^{3p+2}(w-w^6)\,dw = \color{red}{\frac{5\pi}{(p+3)(3p+4)}}.\tag{3}$$
Comment: How did you move from (2) to (3)?
Comment: @SekstusEmpiryk: $$\iint_{y^2+z^2<w-w^6}w^{3p+2}\,dy\,dz$$ is $w^{3p+2}$ times the area of a circle with squared radius $w-w^6$.
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\int_{0}^{\infty}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}
x^{p}\bracks{x^{2} + y^{2} + z^{2} < x^{1/3}}\dd y\,\dd z\,\dd x
\\[5mm] = &\
\int_{0}^{\infty}x^{p}\int_{0}^{2\pi}\int_{0}^{\infty}
\bracks{x^{2} + \rho^{2} < x^{1/3}}\rho\,\dd\rho\,\dd\phi\,\dd x
\\[5mm] = &\
\pi\int_{0}^{\infty}x^{p}\int_{0}^{\infty}
\bracks{\rho < x^{1/3} - x^{2}}\,\dd\rho\,\dd x =
\pi\int_{0}^{\infty}x^{p}\bracks{x^{1/3} - x^{2} > 0}
\int_{0}^{x^{1/3}\ -\ x^{2}}\,\dd\rho\,\dd x
\\[5mm] = &\
\pi\int_{0}^{\infty}\pars{x^{p + 1/3} - x^{p + 2}}
\bracks{x < 1}\,\dd x =
\bbx{\ds{{5\pi \over \pars{3p + 4}\pars{p + 3}}\,,\qquad
\Re\pars{p} > -\,{4 \over 3}}}
\end{align}


How is a secondary dominant used for modulation?

Question: In the Reddit FAQ question How are 7th Chords Used?, the following explanation appears:
Dominant 7th chords are also useful in modulation as secondary dominants - the addition of the seventh will create a much stronger pull to the tonic chord you are aiming for
What does this mean? What would be an example in C major modulating to G major or E minor?
See also What is a secondary dominant chord?
Answer: We're in the key of C. Then comes a secondary dominant chord to get us to A minor.That chord will be E, or E dominant 7. The reason it works well is resolution. Notes from one chord moving as little as possible to the next. The A minor has A, C and E. The secondary dominant (in this case, although it is the dominant of Am) has E, G#, B and D. The E note stays constant, the G#, being a leading tone, pushes a semitone up to the A. B has a semitone to get to C, and D could be thought to move a tone each way to arrive at C or E.
Your specific in C, going to G, would involve the dominant of G, D7. To modulate to E minor, the secondary dominant will be B7 : B stays, D# up a semione to E, F# up a semitone to G, and A (the b7) goes a tone either way to G or B.
Interesting that the major 3 and the minor (b) 7 of the secondary dominants form a tritone, which tends to give an unstable feel to the chord.
Comment: Thank you Tim for writing an answer. For some reason the site didn't send me a notification until yesterday :-/
Answer: A dominant chord is a major chord built on the fifth degree of a scale. It has a strong tendency to resolve to (go to) the tonic chord fifth below. For example in C major, G major is the dominant chord and it "pulls" towards the tonic C chord. In G7 chord, this tendency is even stronger.
A secondary dominant is the dominant of a chord other than the tonic chord. Due to its strong tendency to resolve to a fifth below, it is often used to modulate to different keys.
For example, D7 is the dominant of the G chord so it can be used to modulate to G major (or minor for that matter) from more or less any other key. Similarly a B7 chord can be used to modulate to E minor.
Comment: Or, less jarringly, A7 helps modulate to D. A7 has two notes (E,G) in common with C, along with one sharpened note (C# as opposed to C).
Comment: Thank you cyco130 for writing an answer. For some reason the site didn't send me a notification until yesterday :-/
Answer: If you wish to establish a new tonal centre, a good method is to precede it with its dominant chord.  Strengthen it even further by preceding the dominant seventh with ITS dominant.  This is referred to as a string of secondary dominants.
Example.  In C major.
C, Am7, Dm7, G. Probably no modulation.  The next chord is likely to be C.
C, Am7, D7, G.  Maybe a modulation.  G is preceded by its dominant 7th chord.  The music could proceed with G being treated as tonic.
C, A7, D7, G.  More chance again of it being a modulation, rather than 'just visiting'.
In all cases, what happens next is more important than the chords leading up to the G chord.   OK, we've got there.  But are we just passing through, are we pitching a tent, are we building a house.. ?   Is a passing visit a 'Modulation'?  Maybe.  It's only a word.  Between 'just passing through' and 'settling down for a long stay' are many degrees.
Comment: Thank you Laurence for writing an answer. For some reason the site didn't send me a notification until yesterday :-/


There are 8 events that can be scheduled in a week, then find total number of ways that these 8 events are scheduled on exactly 6 days…[CONT]

Question:
There are 8 events that can be scheduled in a week, then find total number of ways that these 8 events are scheduled on exactly 6 days of a week. (Assume arrangement of multiple events on any particular day as immaterial)

I have been struggling with this question for quite some time now. Here is what I managed to do
The events can be distributed in the following ways
$$1+1+1+1+1+3=8$$
And
$$1+1+1+1+2+2=8$$
Now one of the expressions that apparently gets the answer is
$$\left [ \frac{8!}{3!5!} + \frac{8!}{4! (2!)^2 2!} \right]7!$$
Now the expression inside the bracket seems familiar, basically they are trying to distribute the events on various days, but I could still use an explanation for that. I also have no idea why they multiplied by $7!$
Answer: There are two cases.
i) One of the days has $3$ events and each of the remaining $5$ days has an event each.
ii) Two of the days have $2$ events each and rest $4$ days have an event each.
We first make $6$ unordered groups of events. We will assign them to days later.
Number of ways for $i)$ is $ \displaystyle {8 \choose 3} = \frac{8!}{5! \cdot 3!}$.
Number of ways for $ii)$ is $ \ \displaystyle  \frac{1}{2}{8 \choose 2}{6 \choose 2} = \frac{8!}{2^3 \cdot 4!}$
Above, we divide by $2$ as we are making unordered groups at this point.
Now we add $(i)$ and $(ii)$ and order them by multiplying by $7!$ as there are $7$ groups ($6$ with events and one group with no event). If this is not intuitive, we can see it this way - we order $6$ groups with events in $6!$ ways. But we also have $7$ ways to choose the day with no event.
That leads to the answer -
$ \displaystyle \left[ \frac{8!}{5! \cdot 3!} + \frac{8!}{2^3 \cdot 4!} \right] \cdot 7!$
Comment: The ${6 \choose 2}$ counts the number of ways to choose $2$ events among the remaining $6$ that are available. The division by $2$ ensures that these selections remain unordered and prevents double counting. If you didn't divide by $2$ you would be assuming the selection $\{E_1,E_4\},\{E_5,E_7\}$ is distinct from $\{E_5,E_7\},\{E_1,E_4\}$.
Comment: I didn't understand the arrangements for case 2. Why is $\binom 62$ there. Also the division by 2 isn't clear either
Comment: @Aditya - I hope Matthew Pilling's comment clarifies.
Comment: very elegant answer
Comment: @MatthewPilling then what is $\binom 82$ about? Is it for selecting 2 events on the same day then and then $\binom 62$ was for selecting two more events that occur on the same day?
Comment: Also that $7!$ part, can it be written is $7P6$ ie. Selecting 6 days out of 7 and permuting them across various events rather than permuting events among days?
Comment: @Aditya yes we choose two groups of $2$ events from total of $8$ events using ${8 \choose 2} {6 \choose 2}$ but as they are ordered we divide by $2$ to make them unordered
Comment: Also yes we can write $7!$ part the way you mentioned too.
Comment: I don't get how they are ordered. Isn't combination by definition unordered? Am I using the wrong definition here? Also why do we need to separately select events?
Comment: There are just a lot of conditions to keep track of here :(
Comment: @Aditya yes combinations are unordered - when we select $2$ out of $8$ events, say $(e1, e2)$, they are unordered within. In other words we are not counting $(e1, e2)$ and $(e2, e1)$ separately. But when we do ${8 \choose 2} {6 \choose 2}$ to create two groups of two events each, the groups are ordered. ${8 \choose 2} {6 \choose 2}$ will count both $(e1, e2), (e3, e4)$ and $(e3, e4), (e1, e2)$. But we are only interested in counting one of them as when we multiply by $7!$ to order groups, we will count the other one anyway.
Comment: Ok I thought it was giving an ordered pair of $(e_1,e_2)$. So it is to remove the ordering of events on the two **separate** days which have 2 events in them, but not within the day itself
Comment: @Aditya yes that is correct.
Comment: Also I saw this formula for distributing. Suppose we have $12n$ functions, then no, of distributions is $\frac{12n!}{\frac{(2n)!(2n)!(2n)!(3n)!(3n)!}{2!3!}} * 5!$ for dividing these objects in groups of $2n,2n,2n,3n,3n$. Is this formula correct, and if so, why isn't the ans matching?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128048/discussion-between-math-lover-and-aditya).
Answer: Let me give you another approach
Question is obviously disctinct balls into distinct bins , so the exponential generating functions is useful tool for it.
Firstly , lets select which day will not be used ,  we can do it by $C(7,1)=7$ ways.
Now , we have $6$ days and all of them must have at least one event.
Then , the generating function for each day is $$\bigg(x + \frac{x^2}{2!} + \frac{x^3}{3!}\bigg)$$
Then , what we are looking for is that $$\bigg(x + \frac{x^2}{2!} + \frac{x^3}{3!}\bigg)^6 , \bigg[\frac{x^8}{8!} \bigg]$$ or find the coefficient of $x^8$ and multiply it by $8!$ such that https://www.wolframalpha.com/input/?i=expanded+form+of+%28x+%2B+x%5E2+%2F2+%2B+x%5E3+%2F+6%29%5E6
We see that the coefficient of $x^8$ is $\frac{19}{4}$ , then $$\frac{19}{4} \times 8! = 191,520$$
Moreover , we have $C(7,1)=7$ ,so the result is $$C(7,1) \times \frac{19}{4} \times 8! = 1,340,640 $$ which is equal to @Mathlover 's answer
MY ADDITION = If the arrangements of the multiple events on any particular day does matter , then we would think the events as identical objects and the question would turn out to be stars and bars question.
We should select fistly that which day will be omited by $C(7,1)=7$ ways. Then , the $8$ events can be dispersed to $6$ different days by $C(2+6-1,2)=21$ ways where all days has at least one events. (Notice that we thought the events as identical objects).
After that , we should multiply by $8!$ to arrange our events. Notice that when we multpily with $8!$ ,we actually determine that which identical event  is which events .For example , let $$*|*|**|*|**|*$$ be one of the distribution and the leftmost objects in the same gap is the first scheluded event. So , the $8!$ will determine that which star is which event.
As a result , $$7 \times 21 \times 8! =5,927,040$$


Guitar tablature: same fret indication connected by arc, no label

Question: I'm trying to learn "Hard Time Killin' Floor Blues", by Skip James, and I am stumped on the circled notation in the picture. It doesn't look like a pull off or hammer on to me, because the fret number is the same in the arc notation.
Comment: Hope you don't mind, I touched up your image a bit.
Answer: The 3^3 is called a tie, it simply means you play the first note, hold it and let it ring into the next note, where you simultaneously play the open E string.
BTW your tab diagram seems to be missing two strings, maybe its's a low resolution copy?
Answer: This is called a "tie".

a curved line connecting the heads of two notes of the same pitch, indicating that they are to be played as a single note with a duration equal to the sum of the individual notes' values. (SOURCE)

The tie is required to make clear that the note should be held through the articulation of the next rhythmic moment.


Clicar em ID gerado Dinamicamente

Question: Boa noite!
Tenho um botão de remover que é gerado via Jquery.
Gostaria de saber como clicar neste botão via Javascript puro.
Já tentei diversar formas as o botão não é  visto no código fonte, apenas quando inspeciono.

$("span").html("
Remover
");
#BtnRemove {

  padding: 10px;
  color: #fff;
  background: red;

}

Comment: Bom, primeiro, você não tem um botão e sim uma ``. Agora, o que você quer dizer em clicar no botão com JavaScript puro e por que essa restrição uma vez que você já está utilizando JQuery?
Comment: @LeandroAngelo Uma div (ou qualquer outro elemento) pode se tornar um botão também quando vc formata para funcionar como um botão. No caso pode não ser um botão em si, mas apenas tem a função de ser um botão :D
Comment: @dvd Isso eu sei, mas é aparência ou role, mas nesse continua sendo uma . E nenhum behavior pro evento de click foi apresentando, e talvez a restrição de JavaScript pode ser porque o AP
está tentando fazer o bind quando o elemento ainda não existe na DOM e acha que por conta JQuery. (especulando)
Comment: @Oclácio, esse botão é gerado como? tens controle sobre esse código? vai haver mais que um botão igual na página?
Comment: Não há outros botões com esse ID, ele é único na página.
Comment: Quando dou um document.getElementById("BtnRemove"); o console me retorna NULL, retorna nulo quando é gerado dinamicamente. Quando coloco ele manualmente o console me retorna Object. É isso que quero entender Por que o console retorna NULL quando o ID é gerado dinamicamente e como posso localizar esse ID e Clicar Nele.
Answer: Minha resposta é baseada no caso de se inserir APENAS 1 botão com a id #BtnRemove, conforme informado na pergunta:

Tenho um botão de remover que é gerado via Jquery[...]

Se estiver inserindo vários desses botões, já está incorreto pois estás duplicando ids, pois um id deve ser único na página. Se for este o caso, é preciso fazer de outra forma utilizando class em vez de id.

Você pode usar document.querySelector("body").addEventListener("click"... verificando se o target do evento possui a id do botão:
document.querySelector("body").addEventListener("click", function(e){
   if(e.target.id == 'BtnRemove'){
      // ação ao clicar no botão
   }
});

A variável e (você pode usar qualquer nome para essa variável) retorna o evento chamado. A propriedade target retorna o elemento alvo do evento (no caso, o elemento clicado) e .id o atributo id do elemento.
Verificando no if se a id é a do elemento quem questão (botão "Remover"), você pode executar a ação que deseja.
Exemplo ilustrativo:

document.querySelector("body").addEventListener("click", function(e){
   if(e.target.id == 'BtnRemove'){
      console.log("botão clicado");
   }
});
$("span").html("
Remover
");
#BtnRemove {
  padding: 10px;
  color: #fff;
  background: red;
}

Comment: Eu só trocaria o nome da function :P
Comment: IDs têm de ser únicas. Quando crias uma função que gera IDs duplicadas estás a gerar HTML errado e JavaScript errado.
Comment: Se sabes que está errado sugiro não dares soluções que criem código errado (o que acontece se alguém carregar 2 vezes em `` e que indiques na resposta a problemática de IDs duplicadas.
Comment: Eu percebo, e acabaste por ilustrar, sem aviso, como se faz código que gera HTML errado e problemas de código difíceis de perceber a quem estiver a aprender. E acho isso errado, e que devia ser corrigido. Como a resposta não é minha comento para te ajudar a ver o erro e melhorares a resposta.
Comment: @Sergio Veja se melhorou agora, amigo.
Comment: @dvd sim, bem melhor. Ainda acho que deves avisar sobre os problemas de IDs duplicados, pois o teu código (agora com delegação do evento) vai funcionar se houver IDs duplicados, e não devia permitir isso.
Comment: @Sergio Obg! Vou inserir isto na resposta.
Answer: O problema está porque não tem um botão no seu código:
$("span").html("
Remover
");

a maneira correta seria assim:
$("span").html("
<button type='button' onclick='alert(1)'>Remover</button>
");

veja o exemplo em um run code.

$("document").ready(function(){

  $("#btn").html("<button type='button' onclick='alert(1)'>button</button>");
});

Para você clicar nele via javascript puro basta:
var meu_botao = document.getElementsByTagId("btn");
meu_botao[i].click();

aonde meu_botao pega o botao da pagina pelo id dele, e meu_botao[0].click(); realiza o click
Answer: Possivelmente o elemento que você está buscando ainda não foi carregado no DOM,
Para solucionar isso você pode carregar seus scripts no final da pagina, aqui você encontra uma breve explicação:
Onde devo colocar um código JavaScript em um documento HTML?

#BtnRemove {
  padding: 10px;
  color: #fff;
  background: red;
  cursor: pointer;
}

Clicar em ID gerado Dinamicamente


libphp5.so is missing, dependency problems

Question: after some updates my Debian server (running Apache 2.2) seems to miss the libphp5.so. Starting Apache leads to the error message
sudo service apache2 restart
apache2: Syntax error on line 244 of /etc/apache2/apache2.conf: Syntax error on line 1 of /etc/apache2/mods-enabled/php5.load:
Cannot load /usr/lib/apache2/modules/libphp5.so into server: /usr/lib/apache2/modules/libphp5.so: cannot open shared object file: No such file or directory
Action 'configtest' failed.
The Apache error log may have more information.
 failed!

Trying to reinstall libapache5 however lead to
 sudo apt-get install libapache2-mod-php5
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 libapache2-mod-php5 : Depends: apache2-api-20120211
                       Depends: apache2 (>= 2.4)
 udev : Depends: libudev1 (= 215-5+b1) but 215-6 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

and apt-get -f install couldn't solve the problem. It wants to install the package udev but ends up with an error
insserv: script apache: service apache2 already provided!
Errors were encountered while processing:
 /var/cache/apt/archives/udev_215-6_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

I don't know what to do. How can I get my Apache running again?

Edit
dpkg -C
The following packages are only half configured, probably due to problems
configuring them the first time.  The configuration should be retried using
dpkg --configure <package> or the configure menu option in dselect:
 dictionaries-common  Common utilities for spelling dictionary tools
 dovecot-core         secure POP3/IMAP server - core files

Answer:
Check if this sharedlib is really missing (there is some case if its load fails with this error even if the file is on your system), with an ls -ldL /usr/lib/apache2/modules/libphp5.so. Probably yes, it is missing, so we go further on this branch.
Your packages seem a little bit problematic. With a dpkg -C you can check if there are some damaged packages on your system. If yes, you had to solve this problem first.
Try an apt-get --reinstall install libapache2-mod-php5. The key is the --reinstall flag, without it nothing happened even if your system is in an undamaged state.
Here you can find my other answer, which can provide useful commands to you, although the original question was different: he wanted to fix a failed upgrade, you want to fix your apache php5 module. But the problem is essentially the same: both of you want to fix the inconsistent state of a debian/ubuntu system.

Extension reacting comment: then you should have a clear dpkg -C output (no damaged packages). Next what I can see is that you have probably some type of inconsistence between your package versions and between your actual debian(ubuntu) repository. First check if you have installed all of the latest updates: apt-get update, apt-get dist-upgrade.
If works, you are ready. If not, then some tricky solution is probably needed. In your place I removed some problematic packages (dpkg --purge for induvidual packages, or apt-get --purge remove to remove packages with all of their dependencies), and then tried to reinstall them. If nothing works, I removed the whole apache2 & php thing.
But beware: removing packages by purging deletes their configuration in /etc as well. Make a backup from your whole /etc (or at least from /etc/apache2) before that!
P.s. It is not impossible, that your actual debian mirror isn't really okay. What is in your /etc/apt/sources.list?
Comment: Thank you, I was able to configure some packages that were listed by dpkg -C. However, I can't reconfigure two of them and nearly everything I do with apt-get gives me the error "libapache2-mod-php5 : Depends: apache2-api-20120211   Depends: apache2 (>= 2.4)
 udev : Depends: libudev1 (= 215-5+b1) but 215-6 is to be installed"


import android.bluetooth.BluetoothDevice in a module

Question: I am trying to break parts of my app out into a reusable module.
Now, a class in my module that is trying to import android.bluetooth.BluetoothDevice cannot resolve the symbol.
Here is my gradle script for the module:
apply plugin: 'java'

dependencies {

    compile 'com.android.support:appcompat-v7:22.2.0'
    compile files('libs/Android_Platform_Adapter.jar')

    compile files('libs/wisepadapi-android-2.7.0.jar')
    compile files('libs/emvswipeapi-android-2.12.3.jar')
}

This is the first module I've worked on.  I'm sure it's something easy.  Thanks!
Answer: Here is the mismatch. You are trying to import import android.bluetooth.BluetoothDevice inside a strictly java module (apply plugin: 'java').
You should create android library module. Create a new Phone & Tablet module as described here.
Comment: Will that still build as a jar?


Availability test dashboard

Question: I have some endpoints in Azure that I need to test for availability and present in some kind of health check dashboard. I have set up some availability tests in an Application Insights instance but I am struggling to represent this in some kind of a dashboard.
So far I have looked at Kusto queries and I can pin chart result to an Azure shared dashboard but it is quite limited and not suitable for representation of health checks. It would be the best if solution was in Azure, I am aware that there are commercial solutions for this.
As I haven't built something like this before, any advice is welcome.
I ended up with creating some workbooks, queried availability results and visualized it with tiles that I pin to a dashboard. Now I have to figure out dashboard sharing.
Comment: Limited in what way? What are your requirements?
Comment: if your web app runs in multi instances(if you specify the scale rules), for Health check, if an instance fails to respond to the ping, the system determines it is unhealthy and removes it from the load balancer rotation. This increases your application's average availability and resiliency.

Availability-test in Application Insights does not do such thing, it just checks the health.
Comment: @Zare  AFAIK, Since the availability test has two parameters in common, we can form a graph between time and availability. The remaining parameters change with resources.
Comment: @PeterBons availability test results seamed limited for presentation but a colleague helped me set up visualizations with tiles and I created some workbooks which are now pinned to a dashboard.
Comment: How do you add 1 single Availability Test to the Dashboard? With Availability Test Summary widget you get ALL of your Standard Tests aggregated on the widget. What if I want to have a single one?
Answer: If your web application runs in several instances, the system will do a health check and remove any instances that don't respond to pings from the load balancer rotation if they are deemed unhealthy. The average availability and resilience of your application are improved as a result. Application Insights' availability test doesn't carry out such actions; it merely examines the system's health.

Enabled the availability test with the URL for every respective domain, like the image shown below.

I accessed every URL to trace the availability of the app.

The images below show the results of availability test logs.

While moving the chart Since the availability test has two parameters in common, we can form a graph between time and availability or size. The remaining parameters change with resources.
Comment: Thanks for the tip @Sampath but we really need just the result of those tests to see that apps are alive and ready, I know there are more advanced features such as you mentioned.

Availability test dashboard


Assume that the probability for an angle $\phi$ is $P(\phi) = \lambda\phi^2$. The game pays $\$1000$ times the angle. What is $\lambda$?

Question: Wheel of fortune: Assume that the probability for an angle $\phi$ is $P(\phi) = \lambda\phi^2$. The game pays $\$1000$ times the angle.
a) What is $\lambda$?
b) Find the expectation and the variance of the game.
Comments: I've been thinking of this question for days. Other than an idea that there being $360$ degrees may be part of the solution, I don't know where to start.
I interpreted $\lambda$ as follows:
$P(φ) = \lambda\phi^2 = 1 \Rightarrow \lambda =\frac{1}{\phi^2} $
At this point answers are nice, however explanations will be crucial. I really want to know how a and b work, and if my ideas were in the right direction.
Comment: Also, how are you defining $\varphi$? $\in (-\pi,\pi)$? $(0,2\pi)$?
Comment: Hint:  The probability of landing *anywhere* on the wheel is : $\mathsf P(2\pi)=1$ is it not?
Answer: Hint: There must be
$$
\int_0^{2\pi}\lambda\varphi^2\,d\varphi=\lambda\frac13(2\pi)^3=1,
$$
hence $\lambda=\frac{3}{8\pi^3}$. If we have density, the rest are calculations.
Comment: You must mean lambda=3/(8pi^3)
Comment: @AspiringMathematician Thank you! Corrected. There was `{}` instead of `()` in the value of the integral, hence the error.
Answer: You've almost got (1) down.  What you want is to use $\mathsf P(2\pi)=1$ to determine the parameter, $\lambda$. (Note: this is assuming $\mathsf P$ is the cumulative probability function.)
For (2) you'll want to use
$\begin{align}
\mathsf E(1000\varphi) &= \int_0^{2\pi} 1000\phi\mathsf P(\operatorname d \phi)
& \text{where }\mathsf P(\operatorname d \phi)=\frac{\operatorname d \mathsf P(\phi)}{\operatorname d \phi}\operatorname d \phi
\\ & = 1000\int_0^{2\pi} \phi \times(2\lambda\phi)\operatorname d \phi
\\[2ex]
\mathsf {Var}(1000\varphi) & = \left(\int_0^{2\pi} 10^6\phi^2\mathsf P(\operatorname d\phi)  \right)-\mathsf E(1000\varphi)^2
\\ & =2\times10^6\left(\int_0^{2\pi} \lambda \phi^3\operatorname d \phi\right)-\mathsf E(1000\varphi)^2
\end{align}$


Exponential sum identity

Question: How do I show that $$\sum_{|j| \leq J} (J-|j|) e(j \alpha) = \left| \sum_{j=1}^J e(j \alpha) \right|^2,$$
where $e(n)=e^{2 \pi i n}$ and $\alpha \not \in \mathbb{Z}$?
Thank you very much in advance!
Answer: $$\left \vert \sum_{j=1}^J e^{2\pi i j \alpha}\right \vert^2 = \left(\sum_{j=1}^J e^{2\pi i j \alpha}\right) \left(\sum_{k=1}^J e^{-2\pi i k \alpha}\right) = \sum_{j,k=1}^{J} e^{2 \pi i (j-k) \alpha} = \sum_{k=1}^J \sum_{m=1-k}^{J-k} e^{2 \pi i m \alpha} = \sum_{\vert m \vert < J} \sum_{k=1}^{J-\vert m \vert} e^{2 \pi i m \alpha} = \sum_{\vert m \vert < J} (J - \vert m \vert) e^{2 \pi i m \alpha}$$

Exponential sum identity


Using the Bayes Theorem?

Question:
A certain town has two taxi companies, the Green Taxi Co (cars coloured green) and the Blue
  Taxi Co (cars coloured blue). 10% of taxis are the Green and 90% are the Blue. There was an
  accident on a dark evening, and the witness claimed a Green cab was involved. On future testing, they discovered that under the conditions of that evening, there was an 80% chance of correct identification of the cab colour (regardless of colour) and 20% chance of erring in colour identification. (assume neither company is more accident prone than the other)
a. Before actually hearing the testimony of this witness, what is the probability that the
  witness will claim that it was a Blue Cab involved in the accident that night?
b. If we now have the testimony of the witness, who declares that the cab was Green, what
  is the probability that it actually was Green?

I used a probability tree to solve this question but apparently, it was actually related to Bayes theorem. How I did (a) was use the probability tree and got $P(Witness~claims~Blue) = (0.9)(0.8)+(0.1)(0.2)=0.74$.
For (b), $P(Actually~green) = (0.1)(0.8)+(0.1)(0.2)=0.10$.
However, the answer for (b) was $\frac{.08}{.26}$ and I was supposed to use the Bayes Theorem. Can someone please explain why the Bayes is to be used instead of a sum of probabilities?
Answer: Because Bayes Theorem combines prior information with collected data to create a posterior probability.  think about what you know (the prior probability of the cab being green = 10%) combined with 'collected' information, (that the witness identified the car as being green).  Use Bayes Theorem:
$P(B|A) = \frac{P(A|B)P(B)}{P(A)}$
You started the problem with a certain belief that the cab would be green (10%, since 10% of all cabs are green).  You have new information.  how should that affect your belief that it's 10 % likely that the cab is green?
Comment: Keep in mind that what you're trying to find out isn't $P(Actually Green)$ but rather $P(Actually Green|Witness claims Green)$
Comment: But then can't I just use the conditional probability instead of Bayes? I am slightly confused about which one to use sometimes.
Comment: I'm not sure what you're asking.  You needed to use Bayes because you were looking for a conditional probability in part (b).  Bayes gives you the conditional $P(Actually Green|Witness Claims Green)$.
Answer: Given the events:

$T_b$: witness think it's blue
$T_g$: witness think it's green
$I_b$: is blue
$I_g$: is green

So we have:

$P(I_g) = 0.1$
$P(I_b) = 0.9$
$P(I_g|T_g) = P(I_b|T_b) = 0.8$
$P(I_g|T_b) = P(I_b|T_g) = 0.2$

In (a), you wanted $P(T_b)$, so you used $P(T_b) = P(T_b|I_b)P(I_b) + P(T_b|I_g)P(I_g)$
In (b), you wanted $P(I_g|T_g)$, so you use $P(I_g|T_g) = P(I_g)P(T_g|I_g)/P(T_g)$, where $P(T_g) = 1-P(T_b)$ (the answer you got on (a))
Note the difference between the two problems, in the second you wanted a conditional probability, so that's why you used Bayes Theorem.
Comment: I can't really grasp the difference between conditional probability and Bayes Theorem. I looked it up many times but I can't seem to understand.
Comment: The conditional probabilities the wrong way round (see answer below)
Comment: @Ray I don't even recall answering this as it was more than a decade ago. Anyway, I've change edited the question to make it a community wiki, fell free to edit it and improve it.
Answer: Came across this when preparing a class. The accepted answer above has the conditional probabilities the wrong way round. If it is blue we identify it correctly 80% of the time etc. So we should have:
\begin{equation}
P(T_g|I_g)=P(T_b|I_b)=0.8
\end{equation}
and
\begin{equation}
P(T_b|I_g)=P(T_g|I_b)=0.2
\end{equation}
For (b) then we have:
\begin{equation}
P(T_g) =P(T_g|I_b)P(I_b) = P(T_g|I_g)P(I_g) = (0.2)(0.9) + (0.8)(0.1) = 0.26
\end{equation}
\begin{equation}
P(I_g|T_g)=\frac{P(T_g|I_g)P(I_g)}{P(T_g)} = \frac{(0.8)(0.1)}{0.26} = \frac{0.08}{0.26}
\end{equation}

Using the Bayes Theorem?


Como evitar a propagação do método toggleClass no evento de click

Question: No código abaixo eu tenho dois toggleClass(são no total 12) que estão funcionando corretamente, porem eu preciso que seja expandido somente 1, ou seja, se eu expandir o primeiro e depois o segundo, imediatamente o primeiro deve reprimir-se. No momento, não acontece isso. Execute o código abaixo e clique nos "+":

// when DOM is ready
$(document).ready(function() {

 mapItems = $("div.map").find("div img.mapItem");

 var tempItem;

 for(var i = 0; i < mapItems.length; i++){

  tempItem = mapItems[i];

  $(tempItem).click(function($e){

   //Evita o scroll mudar com o click
      $e.preventDefault();
   $e.stopPropagation();

      //Obtendo valor do data-desc
      var desc = $("#" + $(this).attr('id') + "-desc").attr("data-desc");
   var modals = $("#" + $(this).attr('id') + "-desc").attr("data-modals");
   titulodata = $("#" + $(this).attr('id') + "-desc").attr("data-titulocarrossel");
   desccarrossel = $("#" + $(this).attr('id') + "-desc").attr("data-desccarrossel");
      //Adcionando descrição
   $("#" + $(this).attr('id') + "-desc").html('
'+desc+'
');

      //Criando a função toggle para a utilização da class modal-celebration(balão)
      $("#" + $(this).attr('id') + "-desc").toggleClass("modal-celebration " + modals);

      //Obtendo o boolean
      var isVisible = $("#" + $(this).attr('id') + "-desc").is( ":visible" );
      var isHidden = $("#" + $(this).attr('id') + "-desc").is( ":hidden" );

   //Verificando estado
   if (isVisible) {
    $(".borda").delay(700).fadeIn(500);
    $("#selectLocation").stop().fadeOut(500);
    $("#galleryContainer").stop().fadeOut(200, onHideGalleryComplete);

   }else{
    $(".borda").delay(700).fadeOut(500);
    $("#galleryContainer").stop().fadeOut(200);
    $("#selectLocation").stop().fadeIn(500);
   }

   //rotacionando
    $(this).toggleClass("down");

  });

  $(tempItem).click(function(){

   TituloEmprendimento = '
' + titulodata +'

'+ desccarrossel +'
';

  });
 };

})

function onHideGalleryComplete(){
 loadXMLEntries();
}
body{
  margin: 0;
  padding: 0;
  background-color:#fff;
 }

 /*** main layout ***/

 .main{
  display:block;
  position:relative;

  width: 810px;
  height: 1160px;

  overflow:hidden;
 }

 .preloader{
  display:block;
  position:absolute;

  width: 810px;
  height: 1160px;
  top: 0;
  left: 0;

  background-color:#000;
 }
 .preloaderImg{
  display:block;
  position:absolute;

  width: 100px;
  height: 44px;
  top: 40%;
  left: 50%;
  margin-left: -50px;
  margin-top: -55px;
 }

 @font-face {
     font-family: 'Century_Gothic';
     src: url('../font/Century_Gothic.ttf') format('truetype');
 }

 @font-face {
     font-family: 'Century_Gothic_BOLD';
     src: url('../font/Century_Gothic_BOLD.ttf') format('truetype');
 }

 @font-face {
   font-family: 'Helvetica';
   src: url('../font/Helvetica.ttf') format('truetype');
 }

 .lote p{
  font-family: 'Helvetica', Arial!important;
 }

 h3 {
     font-size: 24px;
     font-family: 'Century_Gothic', sans-serif!important;
     color: #fff!important;
 }

 .map{
  display:block;
  width: 810px;
  height: 760px;

  background-image:url(../img/map-bg2.jpg);

 }

 .logo{
     position: absolute;
     width: 100%;
     text-align: center;
     margin: 68px auto;

 }

 .logo h1{
     width: 730px;
     margin: -13px auto;
     font-size: 55px;
     font-weight: bold;
 }

 .tagline{
  display:none;
  position:absolute;

  width: 354px;
  height: 41px;
  margin-left: -183px;
  left: 50%;
  top: 130px;
 }

 .galleryBox{
  background: url(../img/bg-galeria.jpg);
  position:absolute;
  display:none;
  left: 0%;
  top: 760px;

  width: 810px;
  height: 300px;

  padding:0;
  margin:0;
 }

 .galleryName{
  display: block;
  position: absolute;
  width: 689px;
  left: 37px;
  text-align: left;
  top: -3px;
 }

 .selectLocation{
     position: absolute;
     display: none;
     left: 0%;
     top: 760px;
     width: 810px;
     height: 300px;
     padding: 0;
     margin: 0;
 }

 .footer{
  background-image:url(../img/footer-bg.png);
  display:none;
  position:absolute;
  width: 810px;
  height: 100px;
  top: 1060px;
     background-repeat: no-repeat;
 }

 .celebration{
     position: absolute;
     width: 160px;
     height: 97px;
     left: 84%;
     top: -17px;
 }

 .instagramFollow{
     position: absolute;
     width: 162px;
     height: 95px;
     left: 36px;
     top: 14px;
 }

 /*** gallery stuff ***/

 #galleryContainer {
  position:relative;
  left:0px;
  top:0px;
  width:100%;
  height:100%;
 }

 #galleryTopContainer {
  width: 728px;
  margin: 0 auto;
  height: 300px;
  overflow: hidden;
 }

 .galleryPictureList {
  position:relative;
  left:0px;
  width:0px;
 }

 .galleryPictureItem {
     display: inline-block;
     zoom: 1;
 }

 .galleryBoxPicture{
      margin-top: 102px;
      width: 240px;
      margin-left: 4px;
      height: 177px;

 }
 .galleryBoxDescription{
  font-family:Arial, Helvetica, sans-serif;
  font-size: 12px;
  position:absolute;
  bottom: 0px;
  display:none;
  width: 44px;
  height: 50px;
  margin-left: 30px;
  margin-bottom: 10px;
  background-color:rgba(0,0,0,0.6);
  color:#DDD;
  padding:5px;
 }

 .galleryArrowBtn {
  position:absolute;
  width:66px;
  height: 100%;
  background-repeat:no-repeat;
 }

 .galleryArrowBtn:hover {
  background-position:-66px 0px;
 }

 .galleryArrowLeft {
  visibility:hidden;
  left: 41px;
     top: 102px;
  background-image:url(../img/arrowLeft.png);
 }

 .galleryArrowRight {
  visibility:hidden;
  left: 724px;
     top: 102px;
  background-image:url(../img/arrowRight.png);
 }

 /*** other ***/

 .mapItem{
  display:block;
  position:absolute;
  cursor: pointer;
  cursor: hand;
  background-repeat:no-repeat;
  background-position: 0 0;
 }

 .mapLabel{
  display:block;
  position:absolute;
  background-repeat:no-repeat;
  background-position: 0 0;
  width: 250px;
  height: 100px;
 }
 .mapDesc{
  display:block;
  position:absolute;
  background-repeat:no-repeat;
  background-position: 0 0;
  width: 256px;
     height: 106px;
 }

 /*** PORTICO ***/

 #z-in-portico-build{
     z-index: 1!important;
  position: relative;
  right: 433px;
        top: -99px;
  width: 1px;
 }

 #portico-build{
  z-index: 1!important;
  left: 495px;
  top: 180px;

 }

 #portico-build-desc{
  display:none;
  background-image:url(../img/descriptions/descri.png);
  left: 483px;
  top: 55px;
 }

 #portico-build-img{
  right: -447px;
  top: 181px;
  position: relative;
  z-index: -2;
 }

 /*** CASA ***/

 #z-in-casa-build{
        z-index: 0!important;
  position: relative;
  right: 98px;
  top: 8px;
  width: 1px;
 }

 #casa-build{
  z-index: 1!important;
  left: 547px;
     top: 31px;

 }

 #casa-build-desc{
  display:none;
  background-image:url(../img/descriptions/descri.png);
  left: 533px;
     top: -97px;
 }

 #casa-build-img{
  right: -496px;
     top: 32px;
  position: relative;
  z-index: -2;
 }

  /*** STREET ***/

 #z-in-street-park-build{
        z-index: 0!important;
  position: relative;
  right: 344px;
        top: -59px;
  width: 1px;
 }

 #street-park-build{
  z-index: 1!important;
     left: 557px;
     top: 142px;

 }

 #street-park-build-desc{
  display:none;
  background-image:url(../img/descriptions/descri.png);
  left: 533px;
     top: 8px;
 }

 #street-park-build-img{
    right: -509px;
    top: 150px;
    position: relative;
    z-index: -2;
 }

 /*** POR GERAL***/

 #z-in-portico-geral-build{
  z-index: 0!important;
  position: relative;
  right: 280px;
  top: 141px;
  width: 1px;
 }

 #portico-geral-build{
  z-index: 1!important;
  left: 547px;
     top: 31px;

 }

 #portico-geral-build-desc{
  display:none;
  background-image:url(../img/descriptions/descri.png);
  left: 533px;
     top: -97px;
 }

 #portico-geral-build-img{
  right: -496px;
     top: 32px;
  position: relative;
  z-index: -2;
 }

/* ----------------------------------------*/

 .redes{
  width: 387px;
     float: left;
     color: #fff;
 }

 .redes ul{ width: 200px; }

 .redes ul li{
  width: 25px;
     float: left;
     margin-left: 16px;
     margin-top: 21px;
 }

 .lote{
  width: 645px;
  float: left;
  color: #fff;
  font-size: 7px;
  text-align: left;
  position: relative;
  top: -8px;
 }

   p.p-top{
    font-size: 15px;
    margin: 0 0 10px;
    color: #fff;
    float: right;
    position: relative;
    left: -43px;
    top: 192px;
    width: 280px;
    text-align: right;
   }

   p.p-bot{
 font-size: 15px;
    margin: 0 0 10px;
    color: #fff;
    float: right;
    position: relative;
    left: 238px;
    top: 209px;
    width: 280px;
    text-align: right;
   }

   p {
     font-family: 'Century_Gothic',
     sans-serif; color: #fff;
    }

   .redes p {font-family: 'Century_Gothic_BOLD', sans-serif;   }

 .rotate{
     -moz-transition: all 2s linear;
     -webkit-transition: all 2s linear;
     transition: all 0.5s linear;
 }

 .rotate.down{
     -moz-transform:rotate(225deg);
     -webkit-transform:rotate(225deg);
     transform:rotate(225deg);
 }

 @-webkit-keyframes overlayfx {
    0% { -webkit-transform: scale(.8); opacity: 0; }
    100%   { -webkit-transform: scale(1.1); opacity: 1;  z-index: 1; }
 }
 @-moz-keyframes  overlayfx {
    0% { -moz-transform: scale(.8); opacity: 0; }
    100%   { -moz-transform: scale(1.1); opacity: 1;  z-index: 1;  }
 }
 @keyframes overlayfx {
    0% { transform: scale(.8); opacity: 0; }
    100%   { transform: scale(1.1); opacity: 1;  z-index: 1;  }
 }

 .modal-celebration {
   display: block!important;
   width: 158px;
   height: 158px;
   position: absolute;
   top: 0;
   left: 0;
   bottom: 0;
   opacity: 0;
   -webkit-transform: scale(.8);
   -webkit-animation: overlayfx 0.3s linear 0.1s 1 forwards;
   -moz-transform: scale(.8);
   -moz-animation: overlayfx 0.3s linear 0.1s 1 forwards;
   transform: scale(.8);
   animation: overlayfx 0.3s linear 0.1s 1 forwards;

 }

p.descs.portico-build {
    font-weight: bold;
    color: #2B467D;
    position: relative;
    top: 72px;
    left: -49px;
    text-align: center;
    width: 156px;
    font-size: 15px;
}

p.descs.street-park-build {
    font-weight: bold;
    color: #2B467D;
    position: relative;
    top: 68px;
    left: -32px;
    text-align: center;
    width: 148px;
    font-size: 15px;
}

Comment: Se é "um de cada vez" então está como esperado. Mas talvez o que você quer é que quando um estiver ativo/aberto o outro deve está desativado/fechado. Se é o caso você deveria esclarecer.
Comment: Eu farei e postarei o link aqui nos comentários. Me dê um minutinho, por favor.
Comment: aqui está o link de exemplo: http://jsfiddle.net/72jjj1ne/
Comment: Isso! Sabe como resolver?
Comment: Puxa, tem tantas formas de resolver pois isso é tão trivial. O mais estranho é que se você fez isso tudo deveria ser fácil também pra resolver isso. O que eu faria era isolar isto em métodos/funções especializadas. Haveria uma função tal como *aplicarEventos(elmentos, callback)*. Então o 2º parâmetro seria um função como *exibir(elemento)* que ativa/mostra o elemento clicado e fecha todos os outros elementos abertos anteriormente. Isso não só funciona com 2 eleentos como também com inúmeros, exatamente como em um componente do tipo *accordion*.
Comment: Entende a ideia? Eu quase não posto mais aqui pois isso está uma bagunça, o pessoal sai negativando as respostas de uma forma estranha (há uns maria-vai-com-as-outras).
Comment: @felipsmartins, eu também estava percebendo isso, há algum tempo, mas depois aprendi que na verdade aqui é organizado a ponto de você precisar brilhar na resposta para poder ser positivado. Ajuda awe , mano!
Comment: @felipsmartins, ta dando certo?
Comment: Descobri por que é negativado, brother, você não desenvolve sua resposta a partir da pergunta, mas cria algo alternativo, as vezes complexo, que requer mais trabalho, pois há pouca explicação. MAS MUITO OBRIGADO! APRENDI MUITO. Você é um ótimo desenvolvedor javascript, pensa e faz. Parabéns.
Answer: Segue uma solução para fazer oque você pretende.

$(document).ready(function() {

  var $descritions = $('div[id*="z-in-"] .mapDesc');
  var $buttons = $('div[id*="z-in-"] a');
  var $rotates = $('img.rotate');
  var toggleClasses = 'modal-celebration portico-build';

  $buttons.on('click', function($e) {

    //Evita o scroll mudar com o click
    $e.preventDefault();
    $e.stopPropagation();

    var $self = $(this);
    var $prev = $self.prev();
    var $current = $prev.is('.modal-celebration.portico-build');

    //Obtendo valor do data-desc
    var desc = $prev.data("desc");
    var modals = $prev.data("modals");
    var titulodata = $prev.data("titulocarrossel");
    var desccarrossel = $prev.data("desccarrossel");

    //Adcionando descrição
    $prev.html('
' + desc + '
');

    //Criando a função toggle para a utilização da class modal-celebration(balão)
    $prev.toggleClass("modal-celebration " + modals);

    //Verificando estado
    if ($current) {
        $(".borda").delay(700).fadeIn(500);
        $("#selectLocation").stop().fadeOut(500);
        $("#galleryContainer").stop().fadeOut(200, onHideGalleryComplete);

      } else {
        $(".borda").delay(700).fadeOut(500);
        $("#galleryContainer").stop().fadeOut(200);
        $("#selectLocation").stop().fadeIn(500);
      }

    $descritions.removeClass(toggleClasses);
    $rotates.removeClass("down");

    if (!$current) {
      $index = $self.index($buttons);
      $descritions.eq($index).addClass(toggleClasses);
      $self.find('img.rotate').addClass('down');
    }

  });

})

function onHideGalleryComplete() {
  loadXMLEntries();
}
.main,.preloader{width:810px;height:1160px}body{margin:0;padding:0;background-color:#fff}.main{display:block;position:relative;overflow:hidden}.preloader,.preloaderImg{position:absolute;display:block}.preloader{top:0;left:0;background-color:#000}.preloaderImg{width:100px;height:44px;top:40%;left:50%;margin-left:-50px;margin-top:-55px}@font-face{font-family:Century_Gothic;src:url(../font/Century_Gothic.ttf) format('truetype')}@font-face{font-family:Century_Gothic_BOLD;src:url(../font/Century_Gothic_BOLD.ttf) format('truetype')}@font-face{font-family:Helvetica;src:url(../font/Helvetica.ttf) format('truetype')}.lote p{font-family:Helvetica,Arial!important}h3{font-size:24px;font-family:Century_Gothic,sans-serif!important;color:#fff!important}.map{display:block;width:810px;height:760px;background-image:url(../img/map-bg2.jpg)}.galleryBox,.tagline{display:none;position:absolute}.logo{position:absolute;width:100%;text-align:center;margin:68px auto}.logo h1{width:730px;margin:-13px auto;font-size:55px;font-weight:700}.tagline{width:354px;height:41px;margin-left:-183px;left:50%;top:130px}.galleryBox,.selectLocation{height:300px;padding:0;margin:0}.galleryBox{background:url(../img/bg-galeria.jpg);left:0;top:760px;width:810px}.footer,.galleryArrowBtn{background-repeat:no-repeat}.galleryName{display:block;position:absolute;width:689px;left:37px;text-align:left;top:-3px}.footer,.selectLocation{display:none;width:810px;position:absolute}.selectLocation{left:0;top:760px}.footer{background-image:url(../img/footer-bg.png);height:100px;top:1060px}.celebration{position:absolute;width:160px;height:97px;left:84%;top:-17px}.instagramFollow{position:absolute;width:162px;height:95px;left:36px;top:14px}#galleryContainer{position:relative;left:0;top:0;width:100%;height:100%}#galleryTopContainer{width:728px;margin:0 auto;height:300px;overflow:hidden}.galleryPictureList{position:relative;left:0;width:0}.galleryPictureItem{display:inline-block;zoom:1}.galleryBoxPicture{margin-top:102px;width:240px;margin-left:4px;height:177px}.galleryBoxDescription{font-family:Arial,Helvetica,sans-serif;font-size:12px;position:absolute;bottom:0;display:none;width:44px;height:50px;margin-left:30px;margin-bottom:10px;background-color:rgba(0,0,0,.6);color:#DDD;padding:5px}.galleryArrowBtn{position:absolute;width:66px;height:100%}.galleryArrowBtn:hover{background-position:-66px 0}.mapDesc,.mapItem,.mapLabel{display:block;position:absolute;background-repeat:no-repeat;background-position:0 0}.galleryArrowLeft{visibility:hidden;left:41px;top:102px;background-image:url(../img/arrowLeft.png)}.galleryArrowRight{visibility:hidden;left:724px;top:102px;background-image:url(../img/arrowRight.png)}.mapItem{cursor:pointer;cursor:hand}.mapLabel{width:250px;height:100px}.mapDesc{width:256px;height:106px}#casa-build-desc,#portico-build-desc,#portico-geral-build-desc,#street-park-build-desc{display:none;background-image:url(../img/descriptions/descri.png)}#z-in-portico-build{z-index:1!important;position:relative;right:433px;top:-99px;width:1px}#portico-build{z-index:1!important;left:495px;top:180px}#portico-build-desc{left:483px;top:55px}#portico-build-img{right:-447px;top:181px;position:relative;z-index:-2}#z-in-casa-build{z-index:0!important;position:relative;right:98px;top:8px;width:1px}#casa-build,#portico-geral-build{z-index:1!important;left:547px;top:31px}#casa-build-desc,#portico-geral-build-desc{left:533px;top:-97px}#casa-build-img,#portico-geral-build-img{right:-496px;top:32px;position:relative;z-index:-2}#z-in-street-park-build{z-index:0!important;position:relative;right:344px;top:-59px;width:1px}#street-park-build{z-index:1!important;left:557px;top:142px}#street-park-build-desc{left:533px;top:8px}#street-park-build-img{right:-509px;top:150px;position:relative;z-index:-2}#z-in-portico-geral-build{z-index:0!important;position:relative;right:280px;top:141px;width:1px}.redes{width:387px;float:left;color:#fff}.redes ul{width:200px}.redes ul li{width:25px;float:left;margin-left:16px;margin-top:21px}.lote{width:645px;float:left;color:#fff;font-size:7px;text-align:left;position:relative;top:-8px}p.p-bot,p.p-top{font-size:15px;margin:0 0 10px;float:right;position:relative;width:280px;text-align:right;color:#fff}p.p-top{left:-43px;top:192px}p.p-bot{left:238px;top:209px}p{font-family:Century_Gothic,sans-serif;color:#fff}.redes p{font-family:Century_Gothic_BOLD,sans-serif}.rotate{-moz-transition:all 2s linear;-webkit-transition:all 2s linear;transition:all .5s linear}.rotate.down{-moz-transform:rotate(225deg);-webkit-transform:rotate(225deg);transform:rotate(225deg)}@-webkit-keyframes overlayfx{0%{-webkit-transform:scale(.8);opacity:0}100%{-webkit-transform:scale(1.1);opacity:1;z-index:1}}@-moz-keyframes overlayfx{0%{-moz-transform:scale(.8);opacity:0}100%{-moz-transform:scale(1.1);opacity:1;z-index:1}}@keyframes overlayfx{0%{transform:scale(.8);opacity:0}100%{transform:scale(1.1);opacity:1;z-index:1}}.modal-celebration{display:block!important;width:158px;height:158px;position:absolute;top:0;left:0;bottom:0;opacity:0;-webkit-transform:scale(.8);-webkit-animation:overlayfx .3s linear .1s 1 forwards;-moz-transform:scale(.8);-moz-animation:overlayfx .3s linear .1s 1 forwards;transform:scale(.8);animation:overlayfx .3s linear .1s 1 forwards}p.descs.portico-build,p.descs.street-park-build{font-weight:700;color:#2B467D;position:relative;text-align:center;font-size:15px}p.descs.portico-build{top:72px;left:-49px;width:156px}p.descs.street-park-build{top:68px;left:-32px;width:148px}

Uma dica todas as vezes em que você usar um mesmo seletor da jQuery de forma repetida, guarde o resultado da seleção em uma variável pois assim você evita que a jQuery fique varrendo o DOM em busca do elemento demasiadas vezes.
Comment: Seu código não resolve meu problema, uma vez que citei que trabalho com 12 locais e você setou somente 2. Não há uma forma que funcione para quantos forem necessários?
Comment: Cara se você aumentar a quantidade de locais continua funcionando eu não fiz nada com id fixo exatamente por isso
Comment: O que isso significa: `var toggleClasses = 'modal-celebration portico-build';` Fiquei em dúvida.
Comment: Eu coloquei o seletor em uma variável para evitar de escrever multiplas vezes.
Answer: O método not(), ajudou-me a resolver o problema junto do método removeClass() que passam os seletores que necessito.
$(".mapDesc").not("#" + $(this).attr('id') + "-desc").removeClass("modal-celebration");

Comment: lollipop, não era mais simples, armazenar o item ativo na interação anterior, então você remove a class del?.


Problemas ao instalar jdk7 ou 8 no MAC OS 10.6.8 - Snow Leopard

Question: Sou iniciante em java, e tenho um MACBook com MAC OS X 10.6.8 mais conhecido como Snow Leopard.
Estou tentando instalar o jdk e o Netbeans no mesmo e não consigo.
Ele me diz que preciso da versão 10.7 do MAC OS.
Já tentei todas as versões de jdk 8 e 7, sem sucesso.
Alguém pode me ajudar ?
Answer: Faça o download do jdk7-7uX-macosx-x64.dmg na parte de downloads do site da Oracle.
Use o Pacifist para abrir e instalar o JDK 7 Update X.pkg que está no arquivo que você baixou.
Resposta original no SOEN: How to install java jdk 7 on Snow Leopard


Como funciona a sincronização em Java?

Question: Qual é a vantagem de ter duas threads, que rodam ao mesmo tempo mas que uma espera a outra ser concluída para ser executada? Quando se utiliza a palavra chave SYNCHRONIZED em uma aplicação JAVA com THREADS, fica estabelecido que uma thread só pode ser executada após o final da outra. Neste caso, qual a vantagem de se utilizar a thread em lugar de uma aplicação mono-tarefa?
Comment: https://pt.stackoverflow.com/questions/95233/o-que-%c3%a9-uma-thread-como-ela-funciona, creio que essa pergunta possui a resposta que tu deseja
Answer: De fato se isto acontecer não deveria usar desta forma.
As pessoas tem a crença de que colocando novas threads tudo fica rápido, mas frequentemente fica mais lento. Veja É sempre garantido que uma aplicação com múltiplas threads rode mais rápido que usando uma única thread?.
Se a thread ficar travada esperando outra na maior parte do tempo então só haverá perda de tempo, nunca ganho. Se esta espera é eventual pode ainda ter algum ganho, ainda que não seja tão grande, por isso tem que pensar bem se vale a pena a complexidade de fazer isto, até porque ambiente multithread é mais difícil de programar e muita coisa pode dar errada.
Só há este problema se pelo menos duas threads competem pelo mesmo recurso durante o processamento. Sem threads neste cenário a competição não existirá mas a velocidade seria limitada. Quando você coloca outra thread pode diminuir bem o tempo para finalizar enquanto elas não estão competindo pelo recurso e a espera só acontece em alguns momentos, se acontecer de fato. Em muitos casos o travamento de uma thread é muito curto então a espera não é longa. Não quer dizer que isto é bom, mas se é eventual não é um grande problema.
Onde se espera competição real em muitos casos não vale a pena usar este tipo de estratégia. Existem estruturas de dados que não precisam de sincronização e permitem melhor competição. Claro que elas possuem outras desvantagens, então não pode ser usado em qualquer caso. E a maioria das situações a solução é ter um processamento serializado mesmo.
Pensa em um banco de dados. Muitos funcionam assim, ele trava o registro que está trabalhando porque é improvável que outra operação esteja acessando o mesmo dado, mas se isto acontecer então haverá uma espera e isso não é bom, mas é melhor que essa operação acessar o dado que já está sendo acessando. Alguns bancos de dados usam um sistema chamado MVCC em que tudo o que for alterado é copiado então o acesso não cria problemas.
Se os acessos serão só de leitura a sincronização não é necessária.
Answer: Não entendo como duplicada porque a pergunta é mais especifica do que "o que é thread", bom a resposta é relativamente simples, essa situação que você apresentou o maior motivo é que "se paga pelo processamento mais lento"
Suponhamos
Uma execução em thread onde a primeira contem um código que demora em média 1 segundo para ser executado e na segunda thread contem um código que demora 3 segundos, caso fosse executado os processos de forma sequencial a demora seria de um total de 4 segundo, mas executando em paralelo a execução mais rápida paga o preço da mais lenta sendo assim os valores não se somam e apenas o mais lento é levado em consideração.
Obviamente existe uma perda de performance na quebra em threads deveria ser observado caso a caso a necessidade, mas basicamente a logica é essa, a de pagar apenas pelo processamento mais lento.

Como funciona a sincronização em Java?


Least Square Estimation of Linear Regression

Question: I have a linear regression model:
$$y = \beta_0 + \beta_1x + \epsilon$$ with $\epsilon$ as a random noise.
The least squares estimation is given by:
$$S(\beta_0, \beta_1) = \sum^n_{i=1} (y_i - \beta_0 - \beta_1x_i)^2$$
By setting partial derivatives with respect to $\beta_0$ and $\beta_1$, I obtained:
$$\hat \beta_1 = \frac{\sum x_iy_i - \frac{\sum x_i \sum y_i}{n}}{\sum x_i^2 - \frac{(\sum x_i)^2}{n}} (1)$$
The final result for $\hat \beta_1$ is:
$$\hat \beta_1 = \frac{\sum(x_i - \bar x)(y_i - \bar y)}{\sum (x_i - \bar x)^2} (2)$$
with $\bar x = \frac{\sum x_i}{n}$ and $\bar y = \frac{\sum y_i}{n}$
I am stuck at getting from (1) to (2), which is the final result. How should I proceed for this case?
Comment: Any further questions? I don´t know since you haven´t ginve any reply yet.
Comment: @callculus42 hi, sorry I was busy with other lectures. I just read your solution and I understood it clearly now. Thank you so much!
Comment: It pleases me. You´re welcome.
Answer: Some transformations are necessary. For instance the numerator:
$$\sum x_iy_i - \frac{\sum x_i \sum y_i}n$$
$$=n\left(\frac1n\sum x_iy_i - \frac{\sum x_i \sum y_i}{n\cdot n}\right)$$
$$=n\left(\frac1n\sum x_iy_i - \overline x\cdot \overline y\right)$$
$$=n\left(\frac1n\sum x_iy_i\underbrace{+\overline x\cdot \overline y-\overline x\cdot \overline y}_{=0} - \overline x\cdot \overline y\right)$$
$$=n\left(\frac1n\sum x_iy_i-\overline x\cdot \overline y-\overline x\cdot \overline y+ \overline x\cdot \overline y\right)$$
$$=n\left(\frac1n\sum x_iy_i- \overline y \cdot \frac1n\sum x_i-\overline x\cdot \frac1n\sum y_i- \overline x\cdot \overline y\right)$$
$$=\sum x_iy_i- \overline y \sum x_i-\overline x\cdot \sum y_i+ n\cdot \overline x\cdot \overline y$$
$$=\sum x_iy_i- \overline y \cdot\sum x_i-\overline x\cdot \sum y_i+ \sum \overline x\cdot \overline y$$
$$=\sum \left(x_iy_i- \overline y \cdot x_i-\overline x\cdot  y_i+ \overline x\cdot \overline y\right)$$
Since $(a-b)(c-d)=ac-bc-da+bd$ we get
$$=\sum \left(x_i-\overline x)(y_i-\overline y\right)$$
For the denominator see here the transformations.


Display floating point number in decimal form in Python?

Question: Let's say I have the following float point number in Python
>>>a = 10 ** -10
>>>print a
1e-10

How can I display .0000000001 instead of 1e-10?
Comment: You presumably know that 1e-10 is not exactly representable in a `float`.
Answer: >>> a = "%0.10f" % (10 ** -10)
>>> a
'0.0000000001'

Comment: I think your 9 is meant to be a 10 otherwise they only get 9 0's
Comment: @Mike I don't think so. `0.0100000000` is not the same than `0.0100000000`.
Comment: @Twitchykid Yes! But him got a point. That is just a exemple. ;)
Comment: Is there a way to remove trailing zeros? For example if I do `"%0.10f" % (10 ** -2)` it will print `0.0100000000`.
Answer: Maybe a bit more readable:
a = float("1e-10")
format(a, ".10f")

Output
'0.0000000001'
Answer: Or using format
>>> a = 10 ** -10
>>> '{a:0.10f}'.format(a=a)


How fast is decryption by a YubiKey?

Question: Do YubiKeys decrypt GPG or SSH/SFTP data directly within themselves? If so, would that cause a bottleneck? Do YubiKeys have accelerated AES hardware that does most of the heavy lifting of decryption?
Also, YubiKeys aren't needed when encrypting to another person's key, correct?
Comment: Yubikeys do not encrypt data, they supply keys https://www.linuxjournal.com/magazine/yubikey-one-time-password-authentication
Answer: The YubiKey only does public key cryptography, not symmetric cryptography.
In each of those cases, the YubiKey is used to encrypt (or decrypt) a symmetric key, which is then used by a symmetric cipher such as AES. The YubiKey is not involved at all, after this key is made available. Symmetric cryptography is performed by the device (computer, phone, etc).

How fast is decryption by a YubiKey?


Show only objects with the latest date

Question: How can I show objects having the latest post date? I.e. if 1 was posted yesterday, and 2 -- today, then show only 2 but if they both were posted yesterday and all the others before that, then show 1 and 2.
Is it possible with Views?
Comment: or, in other words, show only first group of display if using grouping criteria on post date.
Answer: Since there's logic involved (check records based on this date, if there are no results, check the previous date) I would do this with a custom module making use of Entity Field Queries.

Show only objects with the latest date


In OLS, why does the error term equal $\mathbf{y} - \hat{\mathbf{y}}$?

Question: In OLS, why does the error term equal $\mathbf{y} - \hat{\mathbf{y}}$? I would have assumed that
$$
\begin{aligned}
\mathbf{y} - \hat{\mathbf{y}} &= \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon} - \mathbf{X}\boldsymbol{\hat{\beta}}
\\
 &= \mathbf{X}(\boldsymbol{\beta} - \boldsymbol{\hat{\beta}}) + \boldsymbol{\varepsilon}
\end{aligned}
$$
The only thing I can think of is that we assume $\boldsymbol{\beta} = \hat{\boldsymbol{\beta}}$, and that all the error is captured by $\boldsymbol{\varepsilon}$. I can't find this assumption in a textbook, though.
Comment: What your derivation shows is that *if* your estimator $\hat\beta$ were to be exactly equal to the true parameter $\beta$ (whether that is the case is unknown in practice as we do statistics precisely because we do not know $\beta$), then residuals $\hat\epsilon$ and errors $\epsilon$ would be identical.
Comment: That makes sense. Thanks.
Answer: The residual (you don't mean "error") is by how much your estimate misses the observed value.
You observe $y$.
You estimate $\hat y$.
You missed by $y-\hat y$.
The "error" term is unobserved but estimated by the residuals.
Comment: I see. So $\hat{\varepsilon}$ is the _residual_, which is an estimate of the error $\varepsilon$. We simply define it to be $y - \hat{y}$? I was a little surprised, because I expected us to disambiguate between the error in the estimate of $\beta$ and the unavoidable error implicit in $\varepsilon$. But $\hat{\varepsilon}$ captures both.


Error creating virtual device using android studio on Mac

Question: I have this error after creating new android virtual device on mac using android studio :
Name: Nexus_4_API_21

CPU/ABI: Google APIs Intel Atom (x86)

Path: /Users/Nicolas/.android/avd/Nexus_4_API_21.avd

Error: Unknown target 'Google Inc.:Google APIs:21' in
  /Users/Nicolas/.android/avd/Nexus_4_API_21.ini

I checked the path on error and it is in the folder.
Answer: You must have selected a faulty or incomplete (without Google APIs) System Image when creating the AVD. Delete this one and create a new one. When selecting the system image make sure you do not the the following message (in red) on the right side of the system image list where you select one.


Penalising input datapoints to a logistic regression

Question: I am fitting a logistic regression model using 4 indepdendent features. These features are counts of signal features present in a time series dataset. For example, number of peaks, number of troughs, etc. We have approximately 100,000 samples, however these have been measured from signals of differing length (between 10 and 60 minutes). The most 'truly' representative data are from those samples acquired for 60 minutes, however many of the samples are from observations less than 20 minutes. Converting these signal feature counts to the frequency domain (e.g. 10 peaks per hour) results in an overestimation of certain features from the shorter signal duration samples because we know, for example, that 100 peaks per hour does not occur. The frequency of features within these signals are non-steady and change significantly throughout recording. Only once a recording duration of >40 minutes are the signal features most reliable.
Therefore, the question is: is there a way to 'penalise' the datapoints that are from shorter signal lengths (e.g. <30 minutes) in the model training process?
Comment: I am not sure whether you are confused by your scaling. eg would 15 peaks/10 minutes be more meaningful? A tennis ball can be served at 263 km/h.  That doesn't mean any tennis ball has ever travelled 263 kilometres from a serve.
Answer: There are several things that you could do:

You could include measurement length as a feature in your model and interactions of this feature with other features. In such a case, the model would estimate parameters to "correct" for different length. This has the positive side of having explicit estimate of the effect of measurement length. By this, you could verify if the assumption that something changes with more measurements.
Alternatively, you could include the inverse of measurement length as a sample weights in your model (e.g. weights parameter in R's glm, or sample_weight parameter of the fit method for logistic regression in Python's scikit-learn). This would force the model to pay more importance to longer measurements and less to shorter, proportionally to the length. This is a pretty standard approach. One problem with this solution is that you would need to decide how would like to penalize for measurement length: should the weight be proportional to the inverse of the length or maybe it should be some non-linear transformation..?
Finally, you could just ignore the rows with not enough measurements from the analysis. It's not elegant, but if they are unreliable, this could be the simplest solution to consider. Nonetheless, it might be an interesting exercise to compare results of the models with and without those observations to verify how much impact do they have and what is the nature of their impact.