The probability of independent events.

Question:
Suppose that there is a 1 in 50 chance of injury on a single skydiving attempt.
(a) (3 points) If we assume that the outcomes of different jumps are independent, what is the probability
that a skydiver is injured if she jumps twice?

The solution of this question was that 1-(the probability that she is not injured).
But I think it is not reasonable.
Let P(A)=the probability that she is not injured during two jumps.
1-P(A) contains the probability of (injured, safe), (injured, injured), (safe, injured). However, in general, if she gets injured at first jump, then she can't jump anymore. So, I think (injured, safe) case is impossible.
Answer: The complement event of "the skydiver is injured" is "the skydiver is safe in both jumps." The skydiver has a chance of $1/50$ to be injured in an individual jump, so the chance that the skydiver is safe in an individual jump is
$$1 -\frac{1}{50} = \frac{49}{50}. $$
Since the two jumps are independent, the probability that she is safe in both jumps is:
$$\biggl(\frac{49}{50}\biggr)^2 = \frac{2401}{2500}. $$
Thus, the probability that the skydiver is injured in either jump is
$$1 - \frac{2401}{2500} = \frac{99}{2500} = 3.96\,\%. $$
Comment: The only way to know for sure that is indeed the complement is to realize that the event is a union of injury on the first try and the second try. Just something to keep in mind, as I've been told going the route of the complement can often lead to mistakes with ambiguous language.
Comment: I suggest you check out part (b) of this question whenever you get the chance.
Answer: To answer your question more directly, if she's injured the first jump then the desired condition is already satisfied, and it doesn't matter whether she jumps again or not. (And if she jumps again, it doesn't matter if she's injured or safe the second time.)
So if you wish, you can consider there to be $3$ events instead of $4$:

With prob $p = 1/50$ she is injured the first jump.  (The desired condition is satisfied, and it doesn't matter whether she jumps again or not.  This combines your (injured, injured) and (injured, safe) scenarios into one.  Note that I am making a mathematical point.  I am not talking about typical human behavior at all.)
With prob $(1-p)p$ she is safe the first time and injured the second time.
With orb $(1-p)^2$ she is safe both times.

You can find your desired prob either as $1 - (1-p)^2$ (as in the answer by @L.F.) or as $p + (1-p)p$.  They both equal $2p - p^2$.
Comment: @sqrtpapi2001 The "desired" condition, i.e. the event for which we want to calculate the probability, is "she gets injured (in at least one jump)".  If she is injured the first jump, then the condition is met, regardless of whether she is injured again at second jump or not.
Comment: This logic is very alien to me: "The desired condition is satisfied, and it doesn't matter whether she jumps again or not." Could you provide explanation further? Namely, how were you supposed to extract this reasoning from the mere wording of the question?
Answer:
However, in general, if she gets injured at first jump, then she can't jump anymore. So, I think (injured, safe) case is impossible.

If that were the case, then the events would not be independent.
You are asked to find the probability while assuming that the events are independent.
Therefore you should not consider injury to prevent (or otherwise influence) the second jump.   If you like, think of it as having sufficient time between jumps for recovery or whatever.
Comment: Oh thank you . I didn't consider the meaning of "independent". :-D
Answer: The event the skydiver is injured consists of the realized outcomes either that she is injured on her first attempt, or her second attempt, or both her first and second attempt. You should have already figured this part out by thinking about the structure of the sample space.
The union of two events $A_1$ and $A_2$ is logically equivalent to this phrase: "$A_1$ or $A_2$ or both $A_1$ and $A_2$ overall." The event of injury $A$ is therefore equivalent to the union of the event of injury on the first try, $A_1$, and on the second try, $A_2$.
Knowing now that $P(A)=P(A_1 \cup A_2)$, by the Additive Law of Probability we have it that $P(A_1 \cup A_2) = P(A_1) + P(A_2) - P(A_1 \cap A_2)$. Because $A_1$ and $A_2$ are said to be independent, we can calculate $P(A_1 \cap A_2)=P(A_1)P(A_2)$. We arrive at the final answer making the necessary substitutions: $P(A)=2p-p^2$.
Comment: In Mathematical Statistics with Applications, 7th Edition, this question is presented in the section on the additive law of probability.

The probability of independent events.


Matlab - Single Layer Perceptron - output?

Question: I'm trying to train single layer perceptron. I don't understand one thing. How to calculate output for vector input x?
For example let say we have this data to use for training:
L1 = [1.5 2.4; -0.3 3; 2 3; 2 2.5];
L2 = [2.5 1.4; -1.3 2; 3 3.1; 1.2 2.5];

weight init, step:
step = 0.1
w = [1 1];

Then L = [L1; L2];
Then we have this formula to calculate mean sum square
sum_all - I mean sigma symbol which means sum all elements.
E = 1/N * sum_all(d(j) - o(j))^2

j - is index of vector inside L matrix.
Then new weight equation:
w(new) = w + step/N * sum_all(d(j) - o(j) * o(j) * (1 - o(j)) * x(j))

Then we have this logical function (pseudo code as it may look clearer):
d(j) = 1 if x(j) belongs to L1
d(j) = 0 if x(j) belongs to L2

And I don't understand how I have to get o(j) or in other words output. I didn't find anywhere where it would say how you get it. It kind of not clear for me.
Should I do something like this?
if w * x(j)' > 0 then o(j) = 1
elseif w * x(j)' <= then o(j) = 0

But then if I run my algorithm, it stops training after one epoch and of course does not train it at all (as actual output won't differ from desired output in a first epoch at all).
If I try something like this:
o(j) = w * x(j)', then numbers go so high that matlab stop recognizing it as number and it goes into infinite loop..
So how I should get actual output x(j) - o(j) using single layer perceptron and backpropagation algorithm?..
Answer: "I don't understand one thing. How to calculate output for vector input x?"
If by single layer perceptron you mean the input layer plus the output layer:

Then for each input to the output node, take the values applied to the inputs and multiply them by their cosponsoring weight values. Then sum these weighted inputs. This sum of weighted inputs is then passed into the activation function you are using (linear summation, sigmoidal, gaussian etc) to produce the output o for those inputs.
"If I try something like this:
o(j) = w * x(j)', then numbers go so high that matlab stop recognizing it as number and it goes into infinite loop."
As far as I recall if left unguarded back propagation can push the weight values to become larger and larger. A possible solution is to cap them at a certain value.
Answer: Based on your update pseudo code it looks like you're using a sigmoid output. In this case given an input $x$ your output should be
$$
 \sigma(x) = \frac{1}{1 + e^{-(w^T x + b)}}.
$$
It is worth noting that if you assume a log-loss function (which is what you should use for classification) your setup is just binary logistic regression. In this case your update should be
$$
w_\text{new} = w_\text{old} + \eta \sum_{j}[d(j) - \sigma(x(j))] x(j),
$$
where $\eta$ is the learning rate. If on the other hand you're using a squared loss (which it seems like you are, but is normally not the right choice for classification) the update will look like
$$
w_\text{new} = w_\text{old} + \eta\sum_{j}[d(j) - \sigma(x(j))][1 - \sigma(x(j))]\sigma(x(j))x(j).
$$
The reason your weights are diverging is probably due to forgetting the parenthesis when translating the above, you have
w(new) = w + step/N * sum_all(d(j) - o(j) * o(j) * (1 - o(j)) * x(j))

which should be
w(new) = w + step/N * sum_all((d(j) - o(j)) * o(j) * (1 - o(j)) * x(j))

All that being said the above isn't really the standard perceptron algorithm. Normally the output for a perceptron is given by
$$
f(x) = \mathbb{I}\{w^T x > 0\},
$$
where $\mathbb{I}$ is the indicator function. In this case you can learn the parameters using subgradient descent which results in an update of the form
$$
w_\text{new} = \left\{\begin{array}{l l} w_\text{old} + \eta [d(j) - f(x(j))] x(j) &:\; d(j) \neq f(x(j)) \\ w_\text{old} &:\; \text{otherwise.} \end{array}\right.
$$
Comment: Thnanks. Output equation was what I was looking for.


Realizando uma consulta linq C#

Question: Tenho um controller onde faço um Select para obter uma lista, porém o mesmo retorna vazio.
public IEnumerable<Check> GetUserByNumberOfregistration(int numberOfregistrationUser)
{
    CheckContext contextObj = new CheckContext();

    var result = contextObj.hour
        .Where(x => x.NumberOfregistrationUser == numberOfregistrationUser)
        .Select(p => new Check()
        {
            Id = p.Id,
            ArrivalTime = p.ArrivalTime,
            DepartureTime = p.DepartureTime,
            NumberOfregistrationUser = p.NumberOfregistrationUser
        });

    return result;
}

Comment: Complicado saber o porque disso só com esse código.
Comment: '((System.Data.Entity.Infrastructure.DbQuery)result).Sql' threw an exception of type 'System.NotSupportedException'
Comment: @Gvr Conseguiu resolver já?
Answer: Isso está acontecendo porque seu result é do tipo dbquery. Você tem que executar a query após o Where ou o Select utilizando o método ToList() para retornar uma coleção, ou o método FirstOrDefault() para retornar apenas um objeto.
Para seu caso, ficaria assim:
public IEnumerable<Check> GetUserByNumberOfregistration(int numberOfregistrationUser)
{
    CheckContext contextObj = new CheckContext();
    var result = contextObj.hour
                           .Where(x => x.NumberOfregistrationUser == numberOfregistrationUser)
                           .Select(p => new Check() { Id = p.Id, ArrivalTime = p.ArrivalTime, DepartureTime = p.DepartureTime, NumberOfregistrationUser = p.NumberOfregistrationUser })
                           .ToList();
    return result;
}

Realizando uma consulta linq C#


Irrational numbers on the number line

Question:
We can construct a right triangle with its each leg as 1 unit,then the hypotenuse would be √2 units,and then we can point √2 on the number line.
But √2 has a non-terminating and non-recurring decimal representation.We always approximate the value of √2 up to certain decimal places.
What is the need for approximation,as we already know the correct lenght of √2 on the number line.
So my question is -
√2 can be plotted on the number line, and we know its exact length
So how √2 has a non-terminating decimal and non-recurring decimal representation,It must have have a fixed value ,as hypotenuse of the triangle has a fixed value.
Comment: `It must have have a fixed value (terminating decimal)` A fixed value does not mean a terminating decimal. As a side note, "*values*" do not depend on the representation, for example $1/3$ has a non-terminating representation in base $10\,$ vs. the very simple representation $0.1$ in base $3\,$, yet it's the same *value*. Back to the point, and since you phrased it in terms of construction, you can certainly construct a circle with the compass. Would you argue that the ratio of the circumference to the radius is not a "*fixed value*" because $\pi$ is not rational?
Comment: My reading of it is "We can geometrically construct the length $\sqrt{2}$ on the number line with a straighedge and compass.  But, as it's irrational, we shouldn't be able to point to it on the number line.  How is this apparent contradiction resolved?"
Comment: You seem to be confusing the property of being finite (*there exists a real number larger than it in magnitude*) with the property of having a terminating or repeating decimal representation.  These two things have absolutely nothing to do with one another.  Yes, $\sqrt{2}$ is indeed finite (*it's magnitude is smaller than $2$ for easy example*).  Why having a non-terminating and non-repeating decimal representation happens goes to the definition and properties of irrational numbers.  If it did have a terminating or repeating decimal rep it would be rational.
Comment: And the question is ????
Comment: Your question seems to be based on a belief that an exact location on the number line must correspond to a finite or repeating decimal, not to an infinite non-repeating decimal. An equivalent way to express that belief would be that all points on the number line correspond to rational numbers. That belief may be intuitively plausible, and indeed it was held rather widely in ancient Greece. That's why the irrationality of $\sqrt2$ was originally regarded as surprising. But since then, we've learned that that belief, despite its plausibility, is false.
Comment: We *can* plot square roots exactly on a number line using a compass, at least in theory (in the real world things like atoms and trying to get the legs to be the exact length and for all lines to be straight and so forth really mess us the exactness aspect)
Answer:
By using a compass and a ruler we can construct a right triangle with its each leg as 1 unit

Ruler and compass are not concerned with "units", but just with straight lines and circles.

then the hypotenuse would be √2 units,and then we can point √2 on the number line.

Yes, but - per the previous point - leave out the units for now. You can construct an arbitrary isosceles right triangle, then yes, you can mark the length of its hypotenuse on the line definining one of the legs.

As √2 has non-terminating and non-recurring decimal representation, we should not be able to point it on the number line.

Why? So far, it's all been a geometric ruler-and-compass construction, which defined a few points.
Now, take the leg where the length of the hypotenuse was marked, and choose one (arbitrary) point of it to be the "unit".

If you choose that point to be the endpoint of the leg, then that would be $1$ (rational) and the point marking the length of the hypotenuse would be $\sqrt{2}$ (irrational).
If however you choose the unit point to be the one marking the length of the hypotenuse, then that would be $1$ (rational) and the leg would be $1 / \sqrt{2}$ (irrational).

Why would choosing the unit after the fact affect the legitimity of the construction itself? Of course, it doesn't. All that rationality tells is whether the ratio of two lengths can be expressed as the ratio of two integer numbers or not. It doesn't make either length less "measurable" than the other.
Comment: @Shobhit Thank you for the so convincing critique. P.S. And the downvote.
Comment: @VasanthBhaskara Idea is that the construction is plotting a *point*, not a number. You only associate a number with the point *after* you define the unit, which is independent of the construction. The above is a direct answer to this (now deleted) part of the question: "*we should not be able to point it on the number line*".
Comment: Not convincing.
Comment: You did not give an answer to my question
Comment: You know very well what the OP is asking, the way u r answering it. It dosen't help the cause
Comment: @dxiv what do you mean by "Ruler and compass are not concerned with "units"."  If it is a meter scale for example, the length being measured will be in centimeters right ? then how is it not concerned?

Also please help me in understanding the following point:-
" If you choose that point to be the endpoint of the leg, then that would be 1 (rational) and the point marking the length of the hypotenuse would be sqrt (2) (irrational). "  ---> wouldn't the length be sqrt(2)-1 instead of just sqrt(2).  In your case we should mark the endpoint as 0 right ? to measure the value of sqrt (2)
Comment: @Fin27 In classical geometry, [ruler-and-compass constructions](https://en.wikipedia.org/wiki/Straightedge_and_compass_construction) use a straightedge with no markings i.e. no "units" to speak of. You can measure the same lengths using different units, and you'll get different numeric values, some rational, some irrational. The one thing that holds regardless of the choice of units is that the ratio of the hypotenuse to the legs is always $\sqrt{2}\,$, an irrational.
Answer: The question as to whether every number is a rational number is ancient and philosophically interesting - and the constructibility of the hypotenuse of an isosceles right-angled triangle in the Euclidean plane is a paradigmatic example, which shows that in Euclidean geometry there are more numbers than rationals.
The idea that the circumference of a circle has a length or that a circle has an area likewise leads to a demonstration that there are useful numbers which cannot be constructed exactly using Euclidean methods.
The understanding of the number line as consisting of the "Real Numbers" is a mathematical development which has facilitated studies in continuity and calculus. The Real Numbers are uncountable, as shown by Cantor. However it is also easy to prove (since we have only a finite alphabet) that the nameable numbers are countable. Why the difference? Well it seems important to know in advance the existence of any number we may construct (methods of construction not now confined to Euclidean methods).
Of course we cannot in practice construct any number exactly as a physical artefact - a point drawn in ink or pencil on a line has a size, a piece of wood or metal does not have a precisely flat end. The numbers form a model of reality (just as also our native geometry is not precisely Euclidean, so Euclidean geometry is a very good model for some purposes).
Then idea that only certain kinds of numbers "really count" has been present in the background of mathematics for a long time. But the broad modern understanding is that how we define our numbers depends on what we want to use them for. The rational numbers are still very important, and solving equations in integers or rationals is at the heart of things like Fermat's last theorem. There are mathematical tasks for which the rationals are unsuitable (geometry and calculus being examples) and for these we use extended number systems suitable to the purpose. It took years and considerable mathematical skill to get those number systems properly defined.

One answer to your amended question, by the way, is that decimal expansion is only one way of naming a number. It is a big step, in fact, to suggest that only things which can be named in a certain way using a decimal expansion deserve to be called numbers.
Answer: You can approximate the square root of $2$ to arbitrary precision using a sufficiently precise straightedge and compass.  (Also note, the precision can be attained by using larger materials rather than more exacting tiny measurements.)
This is not the same as achieving the exact value of the square root of $2$.
For practical purposes such as constructing a building, what's necessary is that your construction be precise enough to satisfy aesthetic qualities and architectural integrity, i.e., the walls of your building should meet at the corners and the building should stay up.  Construction foremen have no professional interest in the exact decimal value of the square root of $2$, but they might be interested in more exact means of constructing a "perfect" right angle (for instance, using electronic equipment rather than the Egyptian method with rope—although that was itself pretty good).
For the puristic (read: abstract, theoretical) sake of math itself, irrational numbers are interesting.
Remember that although geometry gives an excellent model of the real world and the relationships of shapes, lines, distances, angles, it is just a model.  In the real world, there are no lines without width; there are no precise 90 degree angles; etc.

Addendum: It's worth considering the fact that it's just as impossible to make a piece of wood whose length is an absolutely perfect double of the length of another piece of wood.  In order to apply the abstraction of mathematics to the real world, it is necessary to have some concept of the scale at which you are dealing.  The tool of "significant figures" is very useful in bridging the gap from abstraction to actuality.  Not all decimal digits are important.

The fact remains that if multiplication is defined as a method of manipulating decimal numbers so as to get another decimal number, there is no decimal number which can be finitely expressed (terminating decimal) that can be multiplied by itself and result in exactly $2$.
If you define multiplication geometrically in some manner involving a unit length and construction of additional lengths via similar triangles, you can construct a length which is exactly between 1 and 2 multiplicatively.  This is not a decimal expression of a number, though.
Comment: @Shobhit, convincing of what?  What did you think I'm trying to convince you of?
Comment: @Shobhit I'm sorry that I "dosen't help the cause" (whatever "cause" you are referring to; I've really no idea).  Perhaps you can post an answer yourself, showing how this question can better be addressed in your opinion.  Or do you just come on this site to make snide remarks and semi-grammatical critiques?
Comment: If i knew how to answer, i would have. Also, ur attitude, tells many things about u. Cheers.
Comment: Attitude certainly does tell a lot about a person.  However if you refuse to articulate yourself, and refuse to suggest a means of explaining things *better,* you rather forfeit your right to criticize.
Comment: @VasanthBhaskara, I'm not sure how you mean math to be "inaccurate."  The hypotenuse *is* exactly $\sqrt 2$.  What's the difficulty?  Of course, that's "triangle" as in the mathematical (geometric) abstraction, not "triangle" meaning "a physical object in the approximate shape of a triangle."  (Thanks for the tip re Shobhit.)
Comment: @VasanthBhaskara, perhaps this will help: *There are other types of exactness besides a terminating decimal number.*  Just because a number can't be represented with a terminating decimal, doesn't mean that number is inexact.
Comment: @Wildcard , I saw this comment on one of the similar question being asked on this platform :- "we can't accurately plot irrational number on a number line"....  This would be a wrong statement to make, right ?... Since you showed that with the help of abstract concept of geometry we can accurately measure the length, but the thing is we cant just name it as a terminating decimal number
Comment: Not convincing.
Comment: You know very well what the OP is asking, the way u r answering it. It dosen't help the cause
Comment: Shobhit is a grammar Nazi and he's just bluffing,leave him,Wildcard.
But Wildcard, How can math be so inaccurate
In the right triangle with each of its legs as 1,according to pythagoras the hypotenuse must be exactly √2.How can math go wrong.Math is all about accuracy,right!
Comment: So if hypotenuse is exactly √2 ,then we must know the exact value of √2
we just approximate it.
Its decimal representation is non terminating and non repeating,
if you approximate the value of √2  to a certain extent(up to 1000 decimals),
I will approximate it still more(say abou 10000 decimals)
Some one else would find √2  upto 100000 decimals.
Then We are changing its value.
Each one is using different value.
Comment: @VasanthBhaskara, the length itself *is* an exact length (in geometry).  Why do you need to assign it a number?  What are you trying to solve?  If math is just for the sake of math, then you don't have a purpose for it and you'll just go in circles.  This isn't even limited to geometry; you can get the same trouble in English.  The name of a thing is only used to communicate the *idea* of the thing.  The thing is *actual*; the name only exists to communicate that idea.  The name may be misunderstood.  That doesn't mean the thing itself is confused.
Comment: "My bedroom" refers to a specific location, with space, matter (walls, etc.), energy, and time.  If you think "bedroom" is another word for "basket," then you will misunderstand the object I'm referring to, but that has nothing to do with the actual physical space and location of my bedroom.  Similarly, "the length of the hypotenuse of a right triangle with legs of $1$ unit each" refers to an exact length.  You can also name that length "$\sqrt 2$."  Why do you need to name it with a decimal number?  The length is the same; it just can't be *named* with a *terminating* decimal.
Comment: @Fin27 yes, I think that's an inaccurate statement.  But, if you accept some of the nonsensical bits of modern mathematics like Cauchy sequences and uncomputable numbers then you could indeed get a "number" that "can't be plotted."  It's more of an article of faith that you're actually talking about a number at all at that point, though.  I limit all consideration of numbers to *computable* numbers, which I consider are the only "real" Reals.

Irrational numbers on the number line


JDK error while i run react-native-doctor but i already upgrade jdk version

Question: So i have error while i run react-native-doctor
✖ JDK
   - Version found: 1.8.0_352
   - Version supported: >= 8
 ✓ Android Studio - Required for building and installing your app on Android
 ✓ Android SDK - Required for building and installing your app on Android
 ✓ ANDROID_HOME

can anyone solve that problem?
Comment: you need to change your JDK from 1.8 to 8 or higher, I refer to using JDK 11.
Answer: Try to install it with brew
brew tap homebrew/cask-versions
brew install --cask zulu11

Then check in terminal
java -version
openjdk version "11.0.13" 2021-10-19
OpenJDK Runtime Environment Temurin-11.0.13+8 (build 11.0.13+8)
OpenJDK 64-Bit Server VM Temurin-11.0.13+8 (build 11.0.13+8, mixed mode)


Hide header and footer on first page, but show on others EDITED

Question: So, I have a simple website with dynamically generated menu in the header and footer sections (different style for both, for footer more like a page map). I include header and footer blocks with php. So, I have a problem: I need the header and footer blocks to be seen only on other pages, not the first one- Home- page, because of different styling. I tried to do : if (content == "home") { echo .header, .footer { display: hidden;"}; but it doesn't work when I first load the page! Maybe you guys have some ideas? Thank you in advance!
Here is my code:
<?php
$languages = array("eng","lat", "ru");
$sections = array("home", "about", "cafe", "catering", "gallery", "contact");
$sectionTitles = array("eng" =>array("ABOUT US", "CAFE MENU"), "lat"=>array("PAR MUMS", "ĒDIENKARTE"), "ru" =>array("ru1","ru2",));
$lang = "eng";
$section = "home";

$content = explode("/", $_SERVER['REQUEST_URI']);

if (!empty($content[2]) && (in_array($content[2], $languages))) { $lang = $content[2];}
if (!empty($content[3]) && (in_array($content[3], $sections))) { $section = $content[3];}
$sectionTitles = $sectionTitles[$lang];

require_once ("header.php");
require_once ("$lang/$section.php");
require_once ("footer.php");
?>

Header file:

Some header info+menu. Not visible on first page

Content file:

Content different for every page.

Footer file:

Footer info+page map. Not visible on first page.

Comment: hi please check the link http://stackoverflow.com/questions/3952590/php-how-to-find-application-root .. will be helpful for you
Answer: Assuming the locationon your homepage is index.php
$homepage = "/index.php";
$currentpage = $_SERVER['REQUEST_URI'];
if(!$homepage==$currentpage) {
    require_once ("header.php");
}
require_once ("$lang/$section.php");
if(!$homepage==$currentpage) {
     require_once ("footer.php");
}

This checks if the requested page is the homepage, if not, it will require the header and footer. Otherwise only the section is loaded.
UPDATE:
If you want to hide the divs without rewriting your header and footer, check the current URL with javascript and hide the divs if the current URL is the same as that of your homepage:
var pathname = window.location.pathname;
if (pathname == 'http://www.InsertYourHomepageURL.com'){
    $('.header , .footer').hide();
}

Comment: The problem is: I need to include those files, but I need divs with class .header and .footer to be hidden. I have all the head block in header.php file!
Comment: I guess I can make different header and footer files for home page and for others. Thank you!
Comment: @Kristine Does your homepage always have the same URL i.e. no variables in the URL? I could write a jquery variant that hides classes `header` and `footer` when this URL is active.
Answer: Change the require part of your code to;
if ("$lang/$section.php" === "$lang/home.php") {
    require_once ("$lang/$section.php");
}else{
    require_once ("header.php");
    require_once ("$lang/$section.php");
    require_once ("footer.php");
}

Answer: So, I did this and it works:
if ("$lang/$section.php" === "$lang/home.php") {
    require_once ("headerHome.php");
    require_once ("$lang/$section.php");
    require_once ("footerHome.php");
}else{
    require_once ("header.php");
    require_once ("$lang/$section.php");
    require_once ("footer.php");
}


Pass an object with JS throw new Error in node

Question: I want to throw an error in my node application as follows.
throw new Error({ status: 400, error: 'Email already exists' });

this give me the following output.
Error: [object Object]

I can't access the properties of this error object. What am I doing wrong here?
Comment: That's not how you should handle http errors in nodeJs. The error message should only conatin the message associated not the status! http://expressjs.com/en/guide/error-handling.html
Answer: The constructor for an Error object expects a string, not an object (which is why your scheme doesn't work).
You are free to add your own custom properties to the Error object after you create it.
let err = new Error('Email already exists');
err.status = 400;
err.whateverElse = someValue;
throw err;

The standard properties on an error object are (for some reason I don't know) not enumerable so they don't show up in some contexts (even though they are there). Any new properties you add with plain assignment like above, will be enumerable.
FYI, you do this in multiple places, you can also subclass the Error object and give your subclass a constructor that takes whatever arguments you want to give it.  That constructor can then call super(msg) and then add its own properties to the error object from the constructor arguments.
The [object Object] is your message is because you are attempting to convert your error object to a string and the default string representation of the object is [object Object].  That will happen if you trying to use your error object in a string such as:
console.log('Error: ' + err);

Instead, you should pass the whole object to console.log() like this:
console.log('Error:', err);

And, the console.log() gets the whole object and can display its properties.

You can also make your own error subclass that then takes whatever constructor arguments you want.  So, if you want to pass an object to your custom error object, you can do that like this:
class MyError extends Error {
    constructor(data) {
       super(data.message);
       this.status = data.status;
    }
}

throw new MyError({ status: 400, message: 'Email already exists' });

Comment: I'm trying to access error.status but its undefined. How would i access it? @jfriend00
Comment: @O'DaneBrissett - You would have to show your actual code for us to know where things have gone wrong.  Please write your own question and show your specific implementation of this.
Comment: Note: this will not work with TypeScript (at least as intended). One needs to extend the class
Comment: Fantastic! so much easier than trying to create a custom error type
Comment: Added custom MyError class as an option.
Answer: you could try with the cause propoty of :

TS has inaccurate value type about it at present, this is being discussed on the official to revolve it.

try {
     throw new Error('Email already exists', {
       cause: { status: 400 }
     });
   } catch(e) {
     console.log(e); // Error('Email already exists')
     console.log(e.cause) // { status: 400 }
   }

or throw the Error instance with the custom property
try {
     const error = new Error('Email already exists');
     error.status = 400;
     throw error;
   } catch(e) {
     console.log(e); // Error('Email already exists')
     console.log(e.status) // 400
}

Answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
The Error object takes a string parameter as the first parameter.
JSON.stringify the object if you are looking to print it out to the console.
throw new Error(JSON.stringify({ status: 400, error: 'Email already exists' }));

You will get something like this:
Uncaught Error: {"status":400,"error":"Email already exists"}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Comment: This would require the user of this error object to then parse the JSON.  There's no reason to stringify it (see my answer for how else to do it).
Comment: I have no clue why this has so many upvotes. It literally does not make sense to stringify the json to a string: There's almost no cases where you'd want to echo out json than simply just writing out something like `Error status: ${status}, Returned: ${error}`...he likely wants to reuse these errors later on, which the other answer would be a much better answer.
Comment: Even though I have used `Error` as a base class for my use case, the answer might be relevant if you do not want to extend it but want to send some raw data to the client for further processing such as localisation purposes.


Preenchendo index de resultados inexistentes de um select com 0

Question: Eu faço um select no banco de dados do qual me retorna um array de dados. Com isso, faço o seguinte foreach no mesmo:
foreach ($resultado4 as $key => $value7) {
    $array6[$value7['carteira'].'flores'] = $value7['floresqtd'];
    $array6[$value7['carteira'].'isa'] = $value7['isaqtd'];
    $array6[$value7['carteira'].'uni'] = $value7['uniqtd'];
    $array8[$value7['carteira'].'flores'] = $value7['floresvalor'];
    $array8[$value7['carteira'].'isa'] = $value7['isavalor'];
    $array8[$value7['carteira'].'uni'] = $value7['univalor'];
}

Algumas vezes, acontece de um dos indexes do select vir com nenhum resultado, no caso o index Z, não existir. Quando acontecesse isso, queria colocar os valor desse index inexistente como 0, assim criando ele e atribuindo o valor 0, pois preciso dele para realizar algumas contas que não entra na questão. Até agora não consegui formular nenhuma lógica para realizar o mesmo.
Answer: Olá, você pode verificar se o index esta setado antes de atribuir o valor usando a função isset junto com operadores ternários. Nesse link aqui tem mais informações.
// php <= 5.6
foreach ($resultado4 as $key => $value7) {
    $array6[$value7['carteira'].'flores'] = isset($value7['floresqtd']) ? $value7['floresqtd'] : 0;
    $array6[$value7['carteira'].'isa'] = isset($value7['isaqtd']) ? $value7['isaqtd'] : 0;
    $array6[$value7['carteira'].'uni'] = isset($value7['uniqtd']) ? $value7['uniqtd'] : 0;
    $array8[$value7['carteira'].'flores'] = isset($value7['floresvalor']) ? $value7['floresvalor'] : 0.0;
    $array8[$value7['carteira'].'isa'] = isset($value7['isavalor']) ? $value7['isavalor'] : 0;
    $array8[$value7['carteira'].'uni'] = isset($value7['univalor']) ? $value7['univalor'] : 0;
}

// php >= 7.x
foreach ($resultado4 as $key => $value7) {
    $array6[$value7['carteira'].'flores'] = $value7['floresqtd'] ?? 0;
    $array6[$value7['carteira'].'isa'] = $value7['isaqtd'] ?? 0;
    $array6[$value7['carteira'].'uni'] = $value7['uniqtd'] ?? 0;
    $array8[$value7['carteira'].'flores'] = $value7['floresvalor'] ?? 0;
    $array8[$value7['carteira'].'isa'] = $value7['isavalor'] ?? 0;
    $array8[$value7['carteira'].'uni'] = $value7['univalor'] ?? 0;
}

Outra opção também seria alterar a query para pegar o valor da coluna se não for null caso contrário pega um valor definido por você no caso 0. Por exemplo:
SELECT id,
   IF(valor IS NOT NULL, valor, 0)
FROM tabela


Can any cricket player play for any other team without nationality of this country?

Question: I saw many cricketers which play for another country instead of his own country.But  is it necessary to get nationality of this country for playing international cricket  for this country?
Comment: I'm confused by your question. There aren't that many cricketers that don't play for their country of birth and if they don't, they will always meet some eligibility requirement. Eoin Morgan is a good example and one that has played for both Ireland and England. Mark Chapman, who has played for both Hong Kong and New Zealand, holds dual citizenship for those countries.
Comment: Could you please edit your question to include some examples of what you're referring to?
Answer: Cricketers who play for other countries are most likely born and raised in that country. For example, Hashim Amla is an Indian by origin, but was raised in South Africa and gained nationality of South Africa. Thus, he is in the national team. If any player does not have a nationality of the country they wish to play for, then they most probably aren't able to.


How to hide a field in a comment in hook_comment_view programatically?

Question: My comments have a field called 'Extra'. I'm trying to hide it when the user who's viewing the comment wrote it. This is my custom module:
function mymodule_comment_view($comment) {
  global $user;
  if ($comment->uid == $user->uid){
    unset ($comment->field_extra);
  }
}

Why isn't this working and what's the correct way to achieve my goal?
Answer: hook_comment_view(), along with most of the other entity view hooks, are typically used to add properties onto the entity object.
If you read the source for comment_build_comment(), $comment->content[] has already been built up by the time the view hook gets invoked.  So, messing with the field directly has no effect at this point.
You want to implement a template_process_comment() in your theme, or you can implement a module (which technically makes it an instance of hook_preprocess_comment().
Implement this, and then dpm($variables) inside it.  Figure out what you don't want, and then unset() it.  If the variable is printed directly from the comments template, this is is directly in $variables.  If it is in the content section, then unset the proper key in $variables['content'], which is a render tree.
Comment: @berliner I filled out my explanation a bit.  I had to do some field-level shenanigans on a project a few weeks ago, and ran into some of the same issues.
Comment: Shouldn't it be possible then to do `$comment->content['field_extra']['#access'] = FALSE`? That's the way I would do it in a `hook_node_view()`.
Comment: So then it should be possible to do `$comment->field_extra = '';` as it is done in [user_comment_view](https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_comment_view/7)?
Comment: @berliner Adding your own property, yes, but I am not sure if altering a true field this way is really safe. Mainly I am not sure how field caching comes into play.  Also, an empty field is also normally the empty array.
Comment: ok, then your's is the way to go I guess. Thanks for explaining
Comment: @berliner: I tried `$comment->field_extra['#access'] = FALSE` and that didn't work, but I forgot the `content`. I tried it again with your version and **it works**! I'll mark your answer after you've updated it. Thanks!
Answer: Looking at the same kind of functionality in the user.module function user_comment_view() I would expect your code to work.
If your function is really called hook_comment_view then it won't work though. Either this is just a typo, or rename your function to MYMODULE_comment_view where MYMODULE is the name of your custom module.
Edit: After a little discussion with MPD it turns out, that this actually works:
$comment->content['field_extra']['#access'] = FALSE;

Respect to MPD for explanations and an inside for why that could work and especially for why the other solution doesn't work!
This is the phrase from MPD that lead to the solution:

If you read the source for comment_build_comment(), $comment->content[] has already been built up by the time the view hook gets invoked. So, messing with the field directly has no effect at this point.

Which means, that the field output has already been built and stored in $comment->content, which implies that this follows the same rules as in hook_node_view(). So accessing $comment->content[FIELD_NAME] should work.
Comment: Indeed, instead of "hook", I'm using "mymodule". I changed this in my question.
Comment: ah, ok, I was just looking at http://drupal.stackexchange.com/questions/102730/how-to-get-uid-from-a-node-on-which-is-commented and figured from there that this was a typo ;) Then I'm baffled too about why it doesn't work. Can you add any information to the comment? Will it be displayed?


Is $S=\left\{ \left( \frac{1}{n}, \frac{1}{m} \right) \mid m,n \in \mathbb{N}\right\} \subset \mathbb{R^2} $ open or closed?

Question: consider the following set:
$$
S=\left\{ \left( \frac{1}{n}, \frac{1}{m} \right) \mid m,n \in \mathbb{N}\right\} \subset \mathbb{R^2}
$$
Showing Open:
considering the complement of S, one can write it as the Cartesian product of the union of open intervals as follows:
$$
\bigcup\limits_{n=1}^{\infty} F_{n}$$
$$\bigcup\limits_{m=1}^{\infty} G_{m}$$
Where we define F and G as follows:
$$
F_{n}=\big( \frac{1}{n+1},\frac{1}{n} \big) \\
G_{m}=\big( \frac{1}{m+1},\frac{1}{m} \big)
$$
The union of an arbitrary collection of open sets is open, therefore both unions defined above are open. Taking the cartesian product we get the complement of S. Since cartesian products preserve openness, we conclude the complement of S is normal, therefore, S is closed
HOWEVER, S does not contain its accumulation points (0,1),(0,0),(1,0), therefore it cannot be closed. I'm confused
Comment: Then it is nor open nor closed. It is not open because there are points which have no open nhood in $S$, for example $(1,1)$. It is not closed since it does not contain some of its limit points, as $(0,0)$.
Comment: Is $S$ a set of points or intervals?
Comment: Points, it is a subset of R^2. Fixed
Comment: Thank you, that makes complete sense, though I am slightly confused as to where my proof logic above fails regarding my construction of the product. May you please look into it and see where perhaps theres an error in my understanding of the theory
Comment: Ok. But first, I don't understand what you are doing. You assert $\mathbb{R}^2\setminus S=F\times G$ with $F=\bigcup_{n\in\mathbb{N}}F_n$ and $G=\bigcup_{n\in\mathbb{N}} G_n$?
Answer: The set $$\bigcup\limits_{n=1}^{\infty} F_{n} \times \bigcup\limits_{m=1}^{\infty} G_{m}$$ is not your complement, it only contains the points in the first quadrant.
Your complement is actually
$$\left(\bigcup_{n=0}^\infty F_n \times \mathbb{R}\right) \cup \left(\mathbb{R}\times \bigcup_{m=0}^\infty G_m\right) \bigcup ( (- \infty , 0] \times \mathbb R ) \bigcup ([0, \infty ) \times (- \infty , 0])\bigcup (1, \infty) \times \mathbb R \bigcup  \mathbb R \times(1, \infty)$$
P.S. Your answer would be correct if your set was a subset of $$( 0 , 1] \times (0, 1]$$, and the set is indeed closed in this space. If you also set $F_0, G_0$ as Julian suggested, then the set is closed in $(0, \infty)^2$.
Comment: Every point of the form $\left( \frac{1}{n} , 0\right) $ or $\left( 0 ,\frac{1}{n}\right)$ for a fixed $n$ is a limit point. Since $a_m=\left(\frac{1}{n},\frac{1}{m}\right)$ (resp. $a_m=\left(\frac{1}{m},\frac{1}{n}\right)$) converges to it.
Comment: This was the best answer I could have hoped for. Thank you. One more question, if I may, would it also be correct to conclude no elements in the set S are cluster points. In general for not closed sets this is not true, but is such true for this set
Comment: $(1,1)$ is not a cluster point. Did you mean $(0,0)$?
Comment: This still isn't quite correct.  The easiest way I see to correct it is to first define $F_0=G_0 = (1,\infty)$ and then replace $$\bigcup_{n=1}^\infty F_n \times \bigcup_{m=1}^\infty G_m$$ with $$\left(\bigcup_{n=0}^\infty F_n \times \mathbb{R}\right) \cup \left(\mathbb{R}\times \bigcup_{m=0}^\infty G_m\right).$$
Comment: @JulianVillaquirá yes I immediately changed it when i realized my dumb error. Anyway is such a statement true? thank you
Comment: @JulianVillaquirá TY, fixed (I think). I had $F_0, G_0$ in the back of my mind but missed that the OP started at 1.
Comment: The $F_0, G_0$ was only half of the fix I was talking about.  To reiterate the point with an example, note that $\left(\frac{1}{2}, \frac{1}{\pi}\right) \in \mathbb{R}^2 \setminus S.$  Is $\left(\frac{1}{2}, \frac{1}{\pi}\right)$ in your proposed set?
Comment: @BrianMoehring ty, need more coffee before posting :)


How to change the default window font in Windows Server 2016

Question: The Tahoma font that was used for many versions of Windows worked very well.  It used to be a snap to change the fonts used.
Setting up my first Server 2016 for a customer today, my eyes hurt from trying to read the default font "Segoe UI".  It seems Microsoft has once again excelled at "new and frustrating ways to do familiar tasks" to the extent that I can't even find where to fix this setting.  After 30 minutes wasted I gave up.
Thanks in advance for the help!
Answer: Found the solution: I was able to copy some keys from an older system that has screen fonts set to Tahoma.  This should probably work for Windows 10 also, but I haven't tested.
Copy/paste the following into a .reg file, then import it into the registry.
<code>[HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics]
"CaptionFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,00,\
  00,00,00,01,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"IconFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\
  00,00,01,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"MenuFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,00,\
  00,00,01,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"MessageFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,\
  00,00,00,01,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"SmCaptionFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,bc,02,00,\
  00,00,00,00,01,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
"StatusFont"=hex:f5,ff,ff,ff,00,00,00,00,00,00,00,00,00,00,00,00,90,01,00,00,\
  00,00,00,01,00,00,00,00,54,00,61,00,68,00,6f,00,6d,00,61,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
</code>


My for loop isn't responding right

Question: I am searching an array. Trying to find a the entry that is 746.
It is the last one in the array and my for loop is always returning a 0 for x. I am not that new to for loops, but I am about to scream here.
It also seems to take anything I give it and say found.
Is there an obvious problem with the for loop?
int search;
printf("what is your search: ");
gets_s(buf);
search = atoi(buf);

for(int x = 0; x < 8; x++) {
    if(search = id[x]) {
        printf("FOUND! %i", x);
        break;
    }
}

Comment: you have to use the equality operator `==`.
Comment: you are all correct. It is sometimes those little things that kick me around. I will mark correct in 5 mins, stackoverflow won't let it happen until then.
Answer: You are using = instead of ==. Change
if (search = id[x])

to
if (search == id[x])

Answer: Change to:
if (search == id[x])
{
      printf("FOUND! %i", x);
      break;
}

= is the assignment operator. So (search = id[x]) is true if id[x] is non-zero.
Whereas, == is the equality operator, which checks if two expressions are equal.
Answer: In C and similar languages (Java, C# etc.), = is not a equality test, it is assignment (i.e. setting a value). To test equality, you need to use ==.
Thus update your code to if (search == id[x]) if you want to check if search is equal to id[x]. Otherwise it returns the assignment value (i.e. id[x]). which is considered "true" in C if it non-zero.
Answer: you were doing search=id[x],
initially x is 0 ,
at that point search gets the value of id[0].
if it is a non-zero value, the expression in if condition evaluates to TRUE and it will execute the body of if()
and hence it was getting terminated with wrong result
for (int x = 0; x < 8; x++)
{

    if (search == id[x])    //here is the change
    {
        printf("FOUND! %i", x);
        break;
    }
}

Answer: in your if condition instead of comparison
search == id[x]

you have done assignment as
search = id[x]

in c language if u do an assignment in an if condition assignment happens and than value of search variable in your case is passed to if condition.
In C language since a positive integer value greater than 0 is considered as true therefore your if condition satisfies and you are getting 0 as positions of your searched item every-time.

My for loop isn't responding right


How to Add tab space to multilple line at the same time in any text editor

Question: If you select a text you can add multiple tab spaces to the all lines simultaneously.
Answer: For that you must select the n lines of the code and press the key tab. If you want
remove the tab spaces should select the text and press shift+tab.
I was programming in my job and I accidentally discovered this in the IDE eclipse. I test the same process
in the Sublime Text and  Geany and it works too.
Y suposse and pressume that works for the most of text editor
Answer: I can confirm the answer from kelgwiin for sublime text.
Depending on your platform you could also do the following in sublime text:
Linux: Hold shift and the right mouse button, then move the mouse up or down to make a column selection.
Windows + OS X: Simply hold down the mousewheel and move your mouse up and and down to select the columns.
Hope this helps!
Answer: On Geany you can create by using Alt+Shift+Mouse (Windows) or Ctrl-Shift-Mouse (*x) a multiline cursor or an rectange selection, where you can work on many lines at the same time. This is only working for lines 'in row' so you cannot choose line 9 and lines 12-16 and lines 23-44 to be edited at the same time.
Comment: Thanks for your comment but the command is `ctrl+shift+mouse`.
Comment: Sorry. It's differing between Windows and *X for §reasons.
Comment: Oks. Dont worry about that. Anyway thanks for your answer. And my SI is Linus Mint and too Windows 7.


SDRUM verse-chorus switch causes JamMan to restart loop

Question: I use the SDRUM and JamMan Solo XT in tandem with my electric guitar to accompany a live electric fiddle performance. The SDRUM and JamMan are linked with a jamsync TRS cable. I begin by starting the JamMan, which flashes red until the SDRUM is started. I then play chords on the JamMan for 32 bars while backing the fiddle. When it's time to continue playback, I stomp the JamMan and play fills. If the fiddler stops playing, I take a solo.
Unfortunately, I encounter an intermittent issue where the JamMan loop unexpectedly goes back to the beginning from the middle, especially when I stomp the SDRUM to switch from chorus to verse or vice versa. I've tried two different JamMan pedals, but the problem persists.
I'm wondering if anyone else has experienced this issue and if there are any solutions or workarounds available.
Answer: The SDRUM sends a MIDI start message to the JamSync'ed JamMan when the SDRUM foot button is pressed. The user is supposed to record a loop for the verse and a loop for the chorus and press the next loop or previous loop switch on the Digitech FS3X switch attached to the JamMan Solo XT at the same time as the SDRUM foot button.  Stupid, but there you go. No hope of a firmware upgrade as the SDRUM is a discontinued product.


Draft Pick Trading in NHL

Question: When trading picks (1st round, etc...) Do you essentially give up your spot, or do you give an extra pick to the other team?
For example, the Leafs won the draft lottery so they get to pick first. If they traded a first round pick to another team, say the Rangers.
Do the Rangers now get to bypass every other team and get the very first pick? Or do they just get an extra pick once their turn comes?
Answer: Let's look at some trades executed from the 2015 NHL Draft: https://www.nhl.com/news/trades-completed-during-2015-nhl-draft-weekend/c-772519
Here's one (paraphrased for brevity):

Colorado traded a 2nd-round pick (31st overall) in the 2015 NHL Draft
  to San Jose for a 2nd-round pick in 2015 (39th overall), a 2nd-round
  pick in 2016 and a 6th-round pick in 2017.

Because Colorado traded the 31st pick for San Jose's 39th pick, Colorado now picks with the 39th pick and San Jose now picks with the 31st pick. In addition, Colorado gets a 2nd round pick from San Jose in 2016, and a 6th round pick from San Jose in 2017 (as compensation to "even out" the trade).

Do you essentially give up your spot, or do you give an extra pick to the other team? If [the Maple Leafs] traded a first round pick to another team, say the Rangers. Do the Rangers now get to bypass every other team and get the very first pick? Or do they just get an extra pick once their turn comes?

If the trade is straight up (eg, Maple Leafs' 1st overall pick for Rangers' 78th overall pick, the Rangers' first pick of this draft -- which is very unlikely without adequate compensation to even out the trade), then the Rangers chooses with the very first overall pick and the Maple Leafs chooses with the 78th overall pick.
If the trade involves a player (eg, Maple Leafs' 1st overall pick for Rangers' "best" player), then the Rangers chooses with the very first overall pick and the Maple Leafs obtain the player from the Rangers to play for them.
In essence, in these cases, the Maple Leafs "give up" their spot to the Rangers. There is no "extra pick."
Comment: Correct. The Rangers don't "have 2" per se, but acquire one from the Maple Leafs.
Comment: Incorrect that the Rangers would choose twice at 78th as "there is no 'extra pick.'". I have already stated: "the Rangers chooses with the very first overall pick and the Maple Leafs chooses with the 78th overall pick" in the scenario of trading pick for pick. In the "Maple Leafs trade a 1st round pick for a Rangers player" scenario, "the Rangers chooses with the very first overall pick and the Maple Leafs obtain the player from the Rangers to play for them" and the Rangers remain choosing at 78th as that pick was not involved in the trade. There is no picking twice at 78th in any scenario.
Comment: Say the Maple Leafs trade a 1st round pick for a Rangers player. Does that mean the Maple Leafs no longer have a 1st round pick and Rangers have 2?
Comment: In this case, Rangers get to go 1st and then 78th for their second pick, or simply 78th with 2 picks, correct?

Draft Pick Trading in NHL


Espresso testing on Webview within ViewPager

Question: I have an Android Application that uses ViewPager and each Fragment in the view pager has its own WebView. I am able to write test case to check navigation on the ViewPager. But how can I test whether the div in the webview which is first child of the view pager asserts the provided string?
onWebView().withElement(findElement(Locator.ID, "desgination")).
                check(webMatches(getText(), containsString("Doctor")));

This one throws

android.support.test.espresso.AmbiguousViewMatcherException: 'WebView
  with JS enabled' matches multiple views in the hierarchy. Problem
  views are marked with '****MATCHES****' below.
Answer: Change your code to
onWebView(Matchers.allOf(isDisplayed(), isJavascriptEnabled()))
    .withElement(findElement(Locator.ID, "desgination"))
    .check(webMatches(getText(), containsString("Doctor")));

The isDisplayed() method is needed to automatic select the one that is currently on your screen.
Answer: In my case I had several fragments with nested WebViews. I was using add/show/hide with the fragmentManager. This meant that isDisplayed() returned multiple matches. In the end I assigned a unique contentDescription to each webview:
webView.setContentDescription("webView[0]");

and located the specific webView with Espresso with:
onWebView(withContentDescription("webView[0]"))
    .withElement(findElement(Locator.ID, "submit"))
    .perform(webClick());

Edit: After reading a bit more about the contentDescription it became clear that this is a misuse of the member variable which is intended for accessibility. docs


How does one know whether a straight, sixth, seventh, diminished, or augmented chord needs to be played?

Question: I'm sure this fairly stupid question comes up periodically.
Still, here's the verse from "Puttin' on the Ritz":
F        Abdim7   Gm7     C7
Have you seen the well to do?
F      Abdim7    Gm7 C7
Up and down Park Avenue?
Ab      Bdim7  Bbm7    Eb7
On that famous thoroughfare?
Ab         Bdim7 Bbm7   Eb7
With their noses in the air?
C    C#dim7   Dm7     G7
High hats and arrowed collars
C     C#dim7    Dm7     G7
White spats and fifteen dollars
Am             D7
Spending every dime
G7              C7    Caug
For a wonderful time!
There are sevenths, diminished chords, and augmented chords. The song is played in F, which means (for instance) that C# is not even part of the scale, and yet the music seems to call for a diminished C# 7 - how? why?
I mean, yes, try them all out and see which one sounds best, I get that.
But is there a general rule of some sort?
Comment: As for a validation of the more chromatic chords, try https://en.wikipedia.org/wiki/Passing_chord, https://www.secretsofsongwriting.com/2012/06/25/working-diminished-chords-into-your-progressions/, https://www.hearandplay.com/main/3-simple-ways-to-use-diminished-seventh-chords, and https://music.stackexchange.com/q/29301/45266. There are tons of resources on passing chromatic chords, so feel free to find other sources too!
Comment: Are you sure that the last chord is a Caug? or is it leading back to F? If this is the end of the song It could be rather a C maj7 ... any way  - if yes, it has no function (or just to color the lyrics
Answer: It is a little difficult to answer your question without knowing your understanding of theory. C'est la vie. I will do my best.
The first progression is fairly common: F, A♭ dim7, G min7, C7. F is the tonic (I) chord, the G min7 is the II chord, and the C7 is the dominant (V) chord. The function of a dominant chord is to lead you back to tonic. In jazz, the II chord is a chord that leads you to the dominant chord to provide harmonic interest preceding the V chord. In this progression, there is a Ab dim7 before the II. This occurred frequently in earlier jazz to add chromaticism to the progression. Non technically, it sounds bluesy.
The second progression is a transposition of the first.
In regard to seventh chords, jazz almost always uses seventh chords or other added note chords. Most chords with a '7' are constructed with a minor seventh above the root of the chord. The only exception is a FULLY diminished seventh chord, which has a diminished seventh (enharmonic with a major sixth) above the root. If there is a major seventh above the root, the chord symbol will indicate that (G maj7 or [less frequently with minor chords] A min maj7).
In the third progression, C, C♯ dim7, D min7, G7, the C♯ dim7 chord, being a half step below the D min, is leading you to the D min7 chord, and is a substitute for a dominant chord of the D min (very common in baroque music as well).
You might get a clearer answer by (if you have not done these things already) studying a general music theory book, studying jazz theory specifically, and playing many jazz tunes. Aebersold play alongs are great sources for jazz tunes. Bon chance!
Comment: This is, in fact, a pretty clear answer, thank you. Unless I'm much mistaken, the "extra" chords lead to the "principle" chords, making the ear long for resolution.
Answer:
... and yet the music seems to call for a diminished C# 7 - how? why?

I can answer to you how and why:
Actually we have here only one progression in which the diminished chord is easily fitting:
It is the famous I-VI-II-V. (first in F, then in Ab and in C.
Depending of the melody VI and II can be minor or major chords. As major chords they are secondary dominants. In  some tunes they can be both used.
Now the diminished chords are just substitutions for the VI and secondary dim. seventh of the predominant VIIdim7/IIm.
e.g. in C major key:
a,c,e,g respectively a,c#,e,g can be replaced by eb,gb,a,c or c#,e,g,bb

How does one know ...

a) by knowing the theory and functions as explained above
b) by listening and analyzing what you here
c) and if there is no fixed progression or version that you will play along then it's up to you and you can decide whether you will bring more colors in your accompaniment
try it out!
Comment: There is no general rule. You can accompany an entire song only by the root and the fifth of the key tonic, or only with the tonic and the dominant chord. But this will sound like medieval or like folk music, or bag-pipe. The pattern I-vi-ii-V is very popular in Jazz and Pop  and will fit to many songs but not to all. e.g. if the tune is on the root tone or the fifth it is quite useful ... but **no, there us no rule!**
Comment: "Now the diminished chords are just substitutions for the VI and secondary dim. seventh of the predominant VIIdim7/IIm." Please elucidate that. Using simple English words.
Comment: the VIIdim7 is the diminished seventh chord you are asking for. The IIm is the second degree (in your example the minor chords following the dim. chords. The slash / between the roman numbers means that the chord in front of the slash is a "secondary" chord leading to the chord following the slash). In my example the VIm is Am and this VIm can be replaced by the dim7 of the augmented tonic (c#dim7) or the dim7 of A. You can transpose this progressions to the keys of your song.
Comment: My question was, and is, is there a general rule? You're just listing chords.
Comment: I wish I could give you 20 plus-ones.


jQuery how to find hyperlink by href attribute

Question: Am trying to find hyperlink by href attribute i tried  but no success with it not sure what am doing wrong
here is the html

jQuery('a[href*="15628"]').prop("onclick", "window.location.href='https://stackoverflow.com/?page_id=15628';console.log('no ajax');return false;");
jQuery('a[href="https://stackoverflow.com/?page_id=15628"]').prop("onclick", "window.location.href='https://stackoverflow.com/?page_id=15628';console.log('no ajax');return false;");

jQuery('ul#menu-main_menu').find('a[href*="15628"]').prop("onclick", "window.location.href='https://stackoverflow.com/?page_id=15628';console.log('no ajax');return false;");

        Home

        FAQs

  FAQs

Comment: You are selecting it correctly, but aren't binding the click event properly. Change `.prop(` to `.on(`
Answer: You've misidentified the problem.
jQuery('a[href*="15628"]')  is finding the element just fine (I haven't checked the others).
However, the value you assign to the onclick property must be a function and you are assigning a string.
You should use the on() method to assign event handlers when you are using jQuery though.
Answer: You can do this several ways, but your binding of the event is incorrect.  See these examples from your code and one I added.

console.log(jQuery('a[href*="15628"]').length);
console.log(jQuery('a[href="https://stackoverflow.com/?page_id=15628"]').length);
jQuery('a[href="https://stackoverflow.com/"]').on("click", function(event) {
  event.preventDefault();
  event.stopPropagation();
  console.log('home link');
  //  window.location.href = 'https://stackoverflow.com/?page_id=15628';

  return false;
});
jQuery('a[href*="15628"]').on("click", function(event) {
  event.preventDefault();
  event.stopPropagation();
  console.log('no ajax1', $(this).attr('href'));
  //  window.location.href = 'https://stackoverflow.com/?page_id=15628';

  return false;
});
jQuery('a[href="https://stackoverflow.com/?page_id=15628"]').on("click", function(event) {
  console.log('no ajax0', $(this).attr('href'));
  event.preventDefault();
  event.stopPropagation();
  //  window.location.href = 'https://stackoverflow.com/?page_id=15628';
  return false;
});

jQuery('ul#menu-main_menu').find('a[href*="15628"]').on("click", function(event) {
  event.preventDefault();
  event.stopPropagation();
  console.log('no ajax2', $(this).attr('href'));

  //  window.location.href = 'https://stackoverflow.com/?page_id=15628';

  return false;
});
jQuery('ul#menu-main_menu').on("click", 'a[href*="15628"]', function(event) {
  event.preventDefault();
  event.stopPropagation();
  console.log('no ajax3', $(this).attr('href'));

  //  window.location.href = 'https://stackoverflow.com/?page_id=15628';

  return false;
});

    Home

        FAQs

FAQs
Comment: thanks ya i got the point i should have used click()  it worked now . thanks for putting so much example it will help someone for sure :)


How to model percentage dependent variable using logistic regression in spss

Question: I have some aggregated data.
<code>Indep.   Dep.    N
1.3      78%     23
1.2      67%     20
</code>
Indep var the average score of people in a particular region. Dep. var is the percent says 'yes' in that region. N is the count of subject the dep. is based on.
I have read people suggesting logistic regression to model dependent percent or proportion data, i.e., When Dependent Variables Are Not Fit for Linear Models, Now What?, I am confused as to how to do it in spss, and doesn't logistic reg requie the dep var to be binary?
Answer: The usual approach for modelling this type of data structure is to use a fractional logistic regression. The canonical paper is this one by Papke and Wooldridge. Further details can be found here and here. Sadly, it does not seem that there is an appropriate model in SPSS, but maybe others can help more here. (The model is, for example, available in R: see here.)
Comment: Papke and Wooldridge's 1996 paper has been deservedly influential among economists in particular, but the main idea was explicit in mainstream statistical literature long before. See Wedderburn, R. W. M. 1974. Quasi-Likelihood Functions, Generalized Linear Models, and the Gauss-Newton Method. _Biometrika_ 61: 439–447. http://doi.org/10.2307/2334725 Incidentally, the idea that continuous proportions are best thought of on logit scale also long predates the use for binary responses of logits as a link function (as we might now say) by Joseph Berkson and others.
Comment: I defer to your superior knowledge! I should have mentioned that I am an economist...
Comment: That's why we have this site, to pool different personal resources, yours too.
Comment: Thanks. Before delving into more advanced methods, I would like to apply the simpler approach as described in Papke and Wooldridge's paper. Does it mean if I have no 0 or 1 in my dep var (which is the case), I can transform the % into log-odds, and simply run the linear regression model?
Comment: You could do that, but the model implied cannot plausibly match your generating process. For example, as the mean proportion approaches 0 or 1, so also the variance must approach 0; hence errors are heteroscedastic. Any good statistical software makes a better approach easily computable, and better solutions have been known for decades, so a fudged approach can't be defended convincingly.
Comment: Thanks Nick, what might be a convincingly better approaches? I have tried beta regression, grouped logistic regression, fractional response regression, and GLM with logit link function. Are these appropriate approaches?
Comment: @user2728808  Can you comment on my problem?https://stats.stackexchange.com/questions/296227/modeling-votes-on-discrete-outcomes-with-mlogit


jQuery: Is it possible to assign a DOM element to a variable for later use?

Question: I'm working on a project that is using jQuery, which I'm much more familiar with Mootools.
I'll start with my code first.
var customNamespace = {
    status: 'closed',
    popup: $('#popup'),

    showPopup: function() {
        // ...
    }
}

$(document).ready(function(){
    console.log($('#popup'));
    console.log(customNamespace.popup);
    console.log($(customNamespace.popup));

    $('#popup').fadeIn('slow');
    (customNamespace.popup).fadeIn('slow');
    $(customNamespace.popup).fadeIn('slow');
});

My goal is to not have jQuery traverse the DOM everytime I want to do something with the #popup div, so I wanted to save it to a variable to use it throughout my script.
When the page loads, the console prints out the object 3 times as I would expect, so I assumed that for each method, the fadeIn would just work. But it doesn't, only
$('#popup').fadeIn('slow');

Actually fades in the div.
Even if I remove my namespace hash, and just save the object to a global variable, and do a
var globalVariable = $('#popup');
.
.
.
globalVariable.fadeIn('slow');

Also does not work as I thought it would. Can jQuery do what I am trying to do?
Answer: You want to be careful that the DOM is actually loaded before you run your selector and assign it to the variable, but otherwise you can store a reference to a DOM element in a variable with no problems.
var globalVariable;

$(document).ready(function(){
    globalVariable = $('#popup');
    console.log($('#popup'));
    console.log(globalVariable);

    $('#popup').fadeIn('slow');
    globalVariable.fadeIn('slow');
});

Comment: Thank you. I spent all morning forgetting that the DOM wasn't even loaded while trying to access its elements. It was driving me crazy as I thought the code should have worked as is.
Answer: Where are you assigning your global variables?
If it is outside the document.ready declaration, then you may well be assigning it something that has not been loaded.
Try this:
$(document).ready(function(){
    var customNamespace = {
        status: 'closed',
        popup: $('#popup'),

        showPopup: function() {
            // ...
        }
    }
    console.log($('#popup'));
    console.log(customNamespace.popup);
    console.log($(customNamespace.popup));

    $('#popup').fadeIn('slow');
    (customNamespace.popup).fadeIn('slow');
    $(customNamespace.popup).fadeIn('slow');
});

What happens when you try to output .length? :
console.log($('#popup').length);
console.log(customNamespace.popup.length);
console.log($(customNamespace.popup.length));

Answer: Sure, that works. It's actually a good thing to do improve performance.
Answer: Everything you get back from $() will always be an object. Your problem is that when customNamespace is assigned, and the code is executed, the DOM element #popup does not yet exist, and as such, you'll end up with a zero-length object in that example.
To check whether you've found an object in jQuery, you don't check the result for null, you check its length.
To be sure that the DOM nodes exist when your code is executed, defer it to DOMReady:
$(document).ready(function() {
   ...
});

Answer: Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes like fx.:
$('selector').attr('alt', 'data being stored');

// later the data can be retrieved using:
$('selector').attr('alt');
HTML attributes is not meant to store data like that and the "alt" as a parameter name does not really make sense. The right alternative in most cases is using the data method in jQuery. It allows you to associate data with an element on the page.
$('selector').data('paramtername', 'data being stored');

// then later getting the data with
$('selector').data('paramtername');
This approach allows you to store data with meaningful names and it is more flexible as you can store as much data as you want on any element on the page. For more information about data() and removeData(), see here jQuery internals One classical use of this is saving the default value of a input field because you want to clear it on focus.
        <form id="testform">
 <input type="text" class="clear" value="Always cleared" />
 <input type="text" class="clear once" value="Cleared only once" />
 <input type="text" value="Normal text" />
</form>

$(function() {
 //Go through every input field with clear class using each function
 //(NB! "clear once" is two classes clear and once)
 $('#testform input.clear').each(function(){
   //use the data function to save the data
   $(this).data( "txt", $.trim($(this).val()) );
 }).focus(function(){
   // On focus test for default saved value and if not the same clear it
   if ( $.trim($(this).val()) === $(this).data("txt") ) {
     $(this).val("");
   }
 }).blur(function(){
   // Use blur event to reset default value in field that have class clear
   // but ignore if class once is present
   if ( $.trim($(this).val()) === "" && !$(this).hasClass("once") ) {
     //Restore saved data
     $(this).val( $(this).data("txt") );
   }
 });
});

Demo here : link text
Answer: I like to structure my script similar to this. For me it keeps all my page controls together.
It also allows me to maintain my scripts more easily for each page.
/*   CONTROLS GLOBAL  */
var Controls;

var Class = {
    create: function () {
        return function () {
            this.initialize.apply(this, arguments);
        }
    }
}

//Set up page control objects
PageControls = Class.create();
PageControls.prototype = {
    initialize: function () {

        //Use jquery to initialize our controls,
        //one should probably use more appropriate names other than ctrl1, ctrl2 ..
        //but for demo purposes  ...
        this.ctrl1 = $($("#Control1"));
        this.ctrl2 = $($("#Control2"));
        this.ctrl3 = $($("#Control3"));

    }
}

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

    /* Initialize our global page controls */
    Controls = new PageControls();

    //Now we can use our controls
    Controls.ctrl1.val("Text for control 1");
    Controls.ctrl2.val("Text for control 2");
    Controls.ctrl3.val("Text for control 3");
});


Evaluating accuracy of a multi classifier

Question: One Class
I trained a classifier to find the most likely category per user out of a set of 16 possible categories.
Each user can belong to one or more categories, and on average, a user belongs to 4 categories.
I am trying to evaluate the accuracy of the classifier, and I came up with this metric:
tp=0.0
for user in train_data
   if user.predicted_class in user.actual_classes:
      tp=tp+1

precision=tp/len(train_data)

Multiple class
Next, I'd like to predict not only the most-likely class, but also the second and third most likely classes.
How should I measure accuracy if I were to predict more than one class per user ?
Comment: And instead of talking about most likely classes, second most likely, etc. use a proper probability accuracy scoring rule to evaluate the accuracy of all the probability estimates.
Comment: @UriGoren, did you try the approach I mentioned in my answer below? Please do share any interesting findings you may have. Also, if you found this answer satisfactory, would you please mark it as Accepted? Thank you.
Comment: Are you trying to select the best classifier based on the accuracy score, or just trying to measure the predictive accuracy for a classifier that you've already selected? Also, regarding the metric that you've described above, I would look at the classification accuracy **by class** as well (in addition to the overall precision metric. Especially if you have unbalanced classes. For instance, let's say your largest class contains 50% of all users. A classifier may just put **all** of your users into the largest class, and get a precision score of 50%.
Comment: I am trying to select the best classifier based on this metric. How would you suggest dealing with the problem given that the classes are unbalanced ?
Answer: This is a fun challenge. Here's my suggestion. Construct an overall weighted accuracy score such that it incorporates not just whether a classifier succeeded or not in predicting the correct class (like in your calculation) but also by how much it succeeded or failed. In other words, the calculation should include the estimated probability as well, in addition to a binary (success/failure) measure.
To demonstrate, I will use an example of 10 users, five original classes, and we will make three predictions -- for top, second best, and third best classes. Below is an example of the original classes (C1 through C5) and estimated probabilities (p1 through p5) for a given classifier.

The next step is to find out the top three estimated probabilities (max_p1 through max_p3), and the true class membership associated with each prediction (C_pred1 through C_pred3):

For instance, the highest estimated probability for User #1 is 0.26 which corresponds to C1. And User #1 does not belong to that class (because C1 = 0), you get a 'failed' flag of 0 (instead of 1 for success) in column C_pred1. Similarly, the second best estimated probability (0.25) belongs to C4, and since User #1 does belong to C4, we get C_pred2 = 1.
Now, you can multiply 'max_p1' with 'C_pred1', and get a set of three scores for each user:

Note that these scores incorporate two things: (1) whether or not the first/second/third best prediction was correct, and (2) the respective estimated probability for the correct prediction. This way, a classifier that assigns high probabilities to correct classes will tend to get a higher score.
The sum of those three scores will give the overall score for each user, which can then be summed up across all users to get the overall weighted accuracy score for a given classifier.

Note that instead of taking a straight sum of the three scores for each user, you can assign weights such that the first prediction gets the highest weight and the third prediction gets the lowest. This can be based on a rule of thumb – depending on how much more important your top/second prediction is versus the others.
You can add some more nuances to this as well: before taking the sum of the triplet scores for each user, divide each of the three scores by the size of the corresponding segment. This will add an adjustment for the unbalanced classes. In other words, a classifier will have to perform better than the baseline probability (i.e., the original size of the class) in order to get a better score.
To summarize, the general idea is this: Make three predictions (class memberships) based on the top three estimated probabilities for each user. Then take the sum of those three probabilities -- but consider only those probabilities where the class predictions were correct. Finally, the overall weighted accuracy score is the sum of those user-level scores across the entire sample. This sum can be divided by the sample size to restrict its value between zero and one. Choose the classifier that has the highest overall weighted accuracy score (preferably on a separate validation set).


declare an object in typescript

Question: I have the following object :
{
  "catalogue1": {
    "content": [
      {
        "id": 2,
        "sourceId": "bookit-catalogue",
        "recordId": "ATEST003-68545",
        "createdDate": "2022-08-10"
      }
    ],
    "last": true,
    "totalPages": 1,
    "totalElements": 3,
    "first": true,
    "numberOfElements": 3,
    "size": 10,
    "number": 0
  },
  "catalogue": {
    "content": [
      {
        "id": 9,
        "sourceId": "catalogue",
        "recordId": "ATEST003-123892",
        "createdDate": "2022-08-10"
      }
    ],
    "last": true,
    "totalPages": 1,
    "totalElements": 1,
    "first": true,
    "numberOfElements": 1,
    "size": 10,
    "number": 0
  }
}

I am fetching the object from an API, and consuming it in a react project using axios.
but I am trying to declare it in typescript, so I can use the benefit of typescript during the development, but I do not know how usually I just export an interface with the names of properties, but in this object, I do not have a property for the first data (catalogue1),
by the way, if it is an array, so it is easy.
Anyone can help how i can declare the interface, and how I fetch the data as well?
Comment: Does [this approach](https://tsplay.dev/wQ8ZVW) meet your needs?  If so I will write an answer explaining it; if not, please tell me what I'm missing.
Comment: That is a separate issue and therefore out of scope of your original question.  The fix for *that* would be to iterate your object as an object and not as an array, like [this](https://codesandbox.io/s/react-typescript-playground-forked-8kzhhv) perhaps.  But that is just the next problem you encountered after you resolved the first one.  Can I write up my answer to the original question now? Or do you need to [edit] the original question to ask something else?
Comment: thank you, @jcalz seems to be working, but I still cannot see the fields in the project,
I mean how I can get the data from it ?
Comment: I don't understand your question, sorry.  Please provide a [mre] if you want any more information.
Comment: you can see the demo :
https://codesandbox.io/s/react-typescript-playground-forked-3hpr99?file=/src/index.tsx

as you can see I cannot iterate or get any data from the object
Comment: okay, I edited my question , and you can write your answer to the original question
Answer: You can use a string index signature to represent an object type whose keys you don't know but whose values are all of the same type.  It looks like {[k: string]: ValueType}.  For your example, you could define an interface with an index signature like this:
interface Catalogues {
  [k: string]: {
    content: {
      id: number;
      sourceId: string;
      recordId: string;
      createdDate: string;
    }[];
    last: boolean;
    totalPages: number;
    totalElements: number;
    first: boolean;
    numberOfElements: number;
    size: number;
    number: number;
  }
}

You can verify that your example value is assignable to this type:
const cats: Catalogues = {  // okay
  "catalogue1": {
    /* ...snip... */
  }
}

That is still just a regular JavaScript object, and to iterate over its properties you should use the standard JavaScript methods for doing so.  For example, you could use a for...in loop, or the Object.keys() method, or the Object.entries() method, etc.
Here's an example using Object.entries():
function processCatalogues(catalogues: Catalogues) {
  Object.entries(catalogues).forEach(
    ([k, v]) => console.log(k + ": " + v.content.map(c => c.recordId).join("; "))
  );
}

That compiles without error.
(Aside: note that iterating over properties this way will only work easily in TypeScript for object types with index signatures; if your type had known keys, then for...in or Object.entries() or Object.keys() would run into the  wouldn't be as easy because objects may have more properties than are explicitly mentioned in their types; see TypeScript: Object.keys return string[] for more information.)
And here's what we get when we pass your example value to that function:
processCatalogues(cats);
/*
"catalogue1: ATEST003-68545"
"catalogue: ATEST003-123892"
*/

Playground link to code

declare an object in typescript


How to ng-repeat element's attribute?

Question: I'm using an external script to rotate thumbnails (http://sladex.org/images-rotation/).

{{entry.title}}

entry.thumbs is array of thumb urls like entry.thumbs[0].src, entry.thumbs[15].src, etc.
The script requires to place the thumbs urls in data-images attribute
data-images="['1.jpg','2.jpg']"

How can I do it with ng-repeat so it will output correct data-images attribute? Should I use a custom directive for this? Thanks.
Comment: Explain the entry.thumbs structure.
Comment: What your getting in entry.thumbs?
Comment: Every entry.thumbs[ NUMBER ].src is url to image for each entry
Comment: can you add snippet?
Comment: @ManikandanVelayutham hmm snippet of what?
Answer: You create such a structure in your controller and use it:
$scope.imageData = entry.thumbs.map(function(img){ return img.src; });

and use this imageData in the html

 ....

Update 1 - updating according to OP's comment/updated question
$scope.getImageArray = function(images){
  return images.thumbs.map(function(img){ return img.src; });
};

   ....

Or if your entries is an array of array and you need normalized list of src then please find the snippet below:

var entries = [

  [{
    name: 1,
    src: 'img1.png'
  }, {
    name: 2,
    src: 'img2.png'
  }, {
    name: 3,
    src: 'img3.png'
  }],

  [{
    name: 4,
    src: 'img4.png'
  }, {
    name: 5,
    src: 'img5.png'
  }, {
    name: 6,
    src: 'img6.png'
  }]

];

var images = entries.map(function(data) {
  return data.map(function(image) { return image.src; });
});

images = images.reduce(function(a, b){
     return a.concat(b);
});

console.log(images);
Comment: Maybe I forgot to add that entry.thumbs comes from ng-repeat (entry in entries) and if I try to get it in my controller I get in console "Error: entry is not defined"
Comment: @RafcioKowalsky - In that case, call a method form the template. will update the code

How to ng-repeat element's attribute?


Getting client denied when accessing a wsgi graphite script

Question: I'm trying to set up graphite on my Mac OS X 10.7 lion, i've set up apache to call the python graphite script via WSGI, but when i try to access it, i get a forbiden from apache and in the error log.
 "client denied by server configuration: /opt/graphite/webapp/graphite.wsgi"

I've checked that the scripts location is allowed in httpd.conf, and the permissions of the file, but they seem correct. What do i have to do to get access. Below is the httpd.conf, which is nearly the graphite example.
<IfModule !wsgi_module.c>
   LoadModule wsgi_module modules/mod_wsgi.so
</IfModule>
WSGISocketPrefix /usr/local/apache/run/wigs
<VirtualHost _default_:*>
    ServerName graphite
    DocumentRoot "/opt/graphite/webapp"
    ErrorLog /opt/graphite/storage/log/webapp/error.log
    CustomLog /opt/graphite/storage/log/webapp/access.log common
    WSGIDaemonProcess graphite processes=5 threads=5 display-name='%{GROUP}' inactivity-timeout=120
    WSGIProcessGroup graphite
    WSGIApplicationGroup %{GLOBAL}
    WSGIImportScript /opt/graphite/conf/graphite.wsgi process-group=graphite application-group=%{GLOBAL}
    # XXX You will need to create this file! There is a graphite.wsgi.example
    # file in this directory that you can safely use, just copy it to graphite.wgsi
    WSGIScriptAlias / /opt/graphite/webapp/graphite.wsgi
    Alias /content/ /opt/graphite/webapp/content/
    <Location "/content/">
            SetHandler None
    </Location>
    # XXX In order for the django admin site media to work you
    Alias /media/ "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-   packages/django/contrib/admin/media/"
    <Location "/media/">
            SetHandler None
    </Location>
    # The graphite.wsgi file has to be accessible by apache.
    <Directory "/opt/graphite/webapp/">
            Options +ExecCGI
            Order deny,allow
            Allow from all
    </Directory>
</VirtualHost>

Can you help?
Answer: Since apache 2.4, Require all granted is required:
<Directory /opt/graphite/conf>
    Require all granted
</Directory>

Up to apache 2.2, you would write:
<Directory /opt/graphite/conf>
    Order deny,allow
    Allow from all
</Directory>

See upgrading notes.
Note that you can activate mod_access_compat to use old (pre 2.4) directives in apache 2.4. It might be useful if you want to quickly rule out this as the cause for your initial issue, but frankly, the migration to Require is easy enough, there is not point using this module just to postpone it.
Comment: You may only need `Require all granted`
Answer: http://wiki.apache.org/httpd/ClientDeniedByServerConfiguration
It is always one of those reasons.
Comment: Sometimes it's necessary to remind the obvious. For me, it was a wrong path in ``.
Comment: The link 404s...
Answer: You are missing:
<Directory /opt/graphite/webapp>
Order deny,allow
Allow from all
</Directory>

<Directory /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-   packages/django/contrib/admin/media>
Order deny,allow
Allow from all
</Directory>

You also don't need:
<Location "/content/">
        SetHandler None
</Location>
<Location "/media/">
        SetHandler None
</Location>

That 'SetHandler None' stuff is old mod_python stuff and not needed for mod_wsgi.
Comment: Is the `media` alias & `` necessary?  The only `contrib/admin` directory I can find in my Django 1.4 installation doesn't contain a `media` subdir.
Comment: Don't assume your issue is the same. Post a fresh question with all your specific details.
Comment: Thanks, Graham;  I don't actually have an issue as Graphite seems to be working fine when including the `media` alias & ``.  I'll ask a fresh question if it hits problems.
Answer: Setting execute permissions fixed it for me:
chmod u+x graphite.wsgi


Is this Integral always continuous?

Question: PROBLEM:

Let $K:[a,b]\times [a,b]\to\mathbb{R}$ y $f:[a,b]\to\mathbb{R}$ continuous functions. Let $\hat{f}:[a,b]\to\mathbb{R}$ given by:
\begin{equation*}
    \widehat{f}(x):=\int_{a}^{b}K(x,y)f(y)dy
  \end{equation*}
Prove or disprove the continuity of $\widehat{f}(x)$.

My ideas:
I know that K is uniformly continuous because $[a,b]$ is compact and also $f$ is uniformly continuous.
Also if I proving that $\int_{a}^{b}K(x,y)f(y)dy$ is differentiable, then $\widehat{f}(x)$ would be continuous but I don't know how to find the right path. Any idea would be nice ♥
Comment: No :c I gonna see it my analysis course but in a month:/
Comment: Do you know dominated convergence theorem ?
Comment: You will see, it will be a very efficient hammer to kill all these kinds of questions ;)
Answer: Yes, it is true, and here's an elementary way of proving it. Let $M= \sup\limits_{y\in [a,b]}|f(y)|$; this is finite because $f$ is continuous and $[a,b]$ is compact. Now, for any $x_1,x_2\in [a,b]$, we have
\begin{align}
\left|\hat{f}(x_1) - \hat{f}(x_2)\right| &= \left|\int_a^b K(x_1,y) f(y)\, dy - \int_a^b K(x_2,y) f(y)\, dy\right|\\
&\leq \int_a^b \left|K(x_1,y) - K(x_2, y)\right| \cdot \left|f(y)\right|\, dy \\
&= M \cdot \int_a^b\left|K(x_1,y) - K(x_2, y)\right| \, dy
\end{align}
Can you now see how to use uniform continuity of $K$ to complete the proof?
Comment: Yes, that last integral is bounded and we need to integrate $M \epsilon' $ from a to b with a good epsilon!

Is this Integral always continuous?


In an Android app, how do I make a linear view with transparent text so that the parent view is visible?

Question: Any ideas on how to make a view containing some text transparent so that it overlaps on top another view?
Here's an example image of what im referring to
I'm trying to create a feature to display the bio of a user in the chat page just like that of Whatsapp messenger.
Answer: Use next Code
<code>  <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:textSize="16sp"
       android:textColor="#fff"
       android:text="Your text "
       android:paddingTop="8dp"
       android:paddingBottom="8dp"
       android:textAlignment="center"
       android:background="#60000000"
/>
</code>
You can add the above XML in any view you are using for example next view
<code>                <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="100dp">

                <androidx.constraintlayout.widget.ConstraintLayout
                    android:layout_width="match_parent"
                    android:background="#343"
                    android:layout_height="match_parent">
                 <!--                        more views here -->
                </androidx.constraintlayout.widget.ConstraintLayout>
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="16sp"
                    android:textColor="#fff"
                    android:text="Your text "
                    android:paddingTop="8dp"
                    android:paddingBottom="8dp"
                    android:textAlignment="center"
                    android:background="#60000000"
                    />
            </FrameLayout>
</code>


How best to explain the $\sqrt{2\pi n}$ term in Stirling's?

Question: I recently showed my Algorithms class how to bound $\ln n! = \sum \ln n$ by integrals, thereby obtaining the simple factorial approximation
$$ e \left(\frac{n}{e}\right)^{n} \leq n! \leq en\left(\frac{n}{e}\right)^{n} $$
But one student, having seen Stirling's approximation, asked where the $\sqrt{2 \pi n}$
term comes from in
$$ n! \sim \left(\frac{n}{e}\right)^n \sqrt{2 \pi n} $$
which I couldn't readily answer.  Looking around, I can't find a straightforward and intuitive explanation.  Can someone explain this in terms understandable to a Computer Science undergrad (ie, no analysis beyond first-year calculus)?
Comment: Sterling's formula is typically derived from the Gamma function, so you will probably be interested in [this post](http://math.stackexchange.com/questions/3444/intuition-for-the-definition-of-the-gamma-function) on the intuition behind the Gamma function.  See in particular the 2nd to last paragraph in George's answer.
Answer: This blog post by Terence Tao explains how to get this constant from the central limit theorem (equivalently, from the normalization factor we use to define the normal distribution). The question remains where it came from in the central limit theorem, and I think the most honest answer to that question is Fourier analysis; $\frac{1}{\sqrt{2\pi}}$ is the normalization factor which makes the Fourier transform and its inverse look the same, and the Gaussian distribution is its own Fourier transform.
(That is, I don't think you should look for a straightforward and intuitive explanation because I think this is actually a rather deep fact which is not really explained in most courses. On the other hand, just the $\sqrt{n}$ term is straightforward to explain: instead of using the left Riemann sum or the right Riemann sum, you use the trapezoid rule.)
Comment: @Qiang: [Enjoy](http://arxiv.org/abs/0711.4412).
Comment: Do you know where to find "article of Joe Keller" referred in Tao's post? The link does not seem to work any more. Thanks.
Comment: @Qiang: unfortunately I do not.
Answer: One way is to apply Euler-Maclaurin Summation (which can be viewed as a clever application of repeated integration by parts) to $\displaystyle \log x$ to show that
$$n! \sim C \sqrt{n} \left(\frac{n}{e}\right)^n$$
Then use Wallis formula (another clever application of integration by parts)
$$\frac{\pi}{2} = \frac{2}{1} \times \frac{2}{3} \times \frac{4}{3} \times \frac{4}{5} \dots $$
to show that $\displaystyle C = \sqrt{2\pi}$.
If I recall correctly, this is how this was derived historically.
Of course, this does not give an intuitive reason as to why the constant is $\displaystyle \sqrt{2\pi}$
Comment: There is a saying that any analyst worth his salt can do wonders with only Cauchy-Schwarz and integration by parts.
Answer: If You want to see the connection between the term $\sqrt{\pi}$ and factorial, explained in the geometric terms, You can watch Knuth's lecture entitled Why Pi?
Answer: I'm not exactly sure how much analysis is covered by first-year calculus, but this is probably the shortest proof I know of this fact. It doesn't go very far in terms of making this intuitive, though, and I don't know that this can be done at all.
Answer: I think that the most intuitive explanation of this factor is as the total mass of a Gaussian integral in the evaluation of the stirling formual by means of steepest descent on the Gamma function defining integral. See, for example, section 2.4 of the following lecture note.
Comment: If all you want is the constant $\sqrt{2\pi}$, you can get it by using the normal approximation to approximate the central binomial coefficient.
Answer: I would definitely keep $\sqrt{n}$ and  $\sqrt{2\pi}$ apart.
Explanation for $\sqrt{n}$ is that subsequently $n^{n+\frac1{2}}$ is a better approximation than purely $n^n$.
For $\sqrt{2\pi}$ the best explanation is that $\sqrt{\pi}$ is coming from $\frac{1}{2}!$ and there is a connection with integrals in this form
$$\int_0^1 (1-\sqrt[n]x)^m dx = \frac{m!n!}{(m+n)!}$$
which is coming to for $m=n=\frac1{2}$
$$\int_0^1 \sqrt{1-x^2} dx = \frac1{2}!^2 = \frac{\pi}{4}$$
because it is nothing more than a formula for area of the circle.
And about where the connection between factorial and the above exponential form is coming from, it is simply from a binomial theorem, which is valid even for non-integer values:
$$(a+b)^n=\sum_{k=0}^{n}\binom{n}{k}a^{n-k}b^{k}$$
$$(a+b)^x=\sum_{k=0}^{\infty}\binom{x}{k}a^{x-k}b^{k}, |a|>|b|$$