"$X$ is an ordered set in the order topology." What is the meaning of this sentence? (James R. Munkres "Topology 2nd Edition")

Question: I am reading "Topology 2nd Edition" by James R. Munkres.
There is the following sentence on p.90 in this book:

Now let $X$ be an ordered set in the order topology, and let $Y$ be a subset of $X$.

I am very poor at English.
What is the meaning of the following sentence?:

$X$ is an ordered set in the order topology.

Does the above sentence mean the following?:

$X$ is an ordered set and the topology on $X$ is the order topology.
Comment: Yes, that is what it means.
Comment: @JoséCarlosSantos Thank you very much for your answer.
Answer: Yes, it means exactly that.
Munkres considers an ordered set $X$ and puts the order topology on it.
If you take a subset $Y \subseteq X$, there are two possible topologies on $Y$:
(1) $Y$ is itself an ordered set, so it obtains an order topology as well.
(2) $Y$ is a subset of $X$, so it obtains a subspace topology.
A natural question is whether these topologies are the same. This turns out to be false, as Munkres demonstrates.
Comment: MathQED, Thank you very much for your answer.
Comment: @tchappyha You are very welcome!


OpenSSL dgst: Error opening signature file

Question: I'm attempting to verify a trust-store that's contained in a .zip file. I've been able to validate it within my workstation (which has ubuntu with OpenSSL 1.0.1f 6 Jan 2014).
openssl dgst -ecdsa-with-SHA1 -verify <(openssl x509 -sha1 -in signature-certificate.pem -noout -pubkey) -signature truststore.zip.dgst truststore.zip

As said, this works on my workstation, however, running this on my server I get this error:
Error opening signature file truststosre.zip.dgst
3069867216:error:02001002:system library:fopen:No such file or directory:bss_file.c:165:fopen('truststosre.zip.dgst','rb')
3069867216:error:2006D080:BIO routines:BIO_new_file:no such file:bss_file.c:168:

I should mention that the 'server' has OpenSSL 1.0.2 22 Jan 2015 and a /bin/bash version of 14.3.30(1)-release
Could anyone shed any light on why my server isn't validating the same file-pair?
Answer: The error in the OpenSSL meant that it couldn't find the file you had specified:
3069867216:error:02001002:system library:fopen:No such file or directory:bss_file.c:165:fopen('truststosre.zip.dgst','rb')

This can happen if you're running openssl without setting environmental variables or when openssl is launched from another process.
First of all, try specifying full path to your truststosre.zip.dgst file, if it won't help - you should check if the user, who launched openssl (i.e. if it is launched inside a PHP-script, it would be the www-data user) has enough rights to access the file.
The command for www-data user will be:
sudo -u www-data cat /path/to/truststosre.zip.dgst

If the user hasn't got enough permissions - you'll get Permission denied error.
P.S. A closer look reveals a possible ingenious solution, which involves fixing the most widespread type of IT-related error - mistype:
When you are trying to verify the file on your PC it is called truststore.zip.dgst, while on remote sever you access truststo**s**re.zip.dgst. Try to remove that "s" and I bet it will start working right away!
Comment: First of all, I've made sure to match the runtime-user and my personal account, so I don't think it's the user, although the ENV setup is probably something I need to look at.

But second of all....holy crap! `openssl dgst -verify pubkey -ecdsa-with-SHA1 -signature truststo**.zip.dgst truststore.zip` == `Verified OK` how!? and why!?! I virtually copy and pasted the command from one machine to the next???

I'm so confused right now!!
Comment: ok. I see the typo. Dang, I seriously thought I had a legitimate, technical bug for you guys!!!


Pull single records from csv file into excel

Question: I have a 2 gig csv file that I want to read into an excel vba macro process one record at a time, or one datum at a time.  How can I?  Can I?
Answer: You can use the Scripting.FileSystemObject to do that:
As a sample of how you can read in a file line by line:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ServerList.txt", 1)
    Do Until objFile.AtEndOfStream
       strLine = objFile.ReadLine
       ... You code here ...
    Loop
objFile.Close

Just remember to add a reference to the Microsoft Scripting Runtime (where the FileSystemObject is)
How do I use FileSystemObject in VBA?


Inequalities relating the cardinality of finite sets

Question: Take $A$ and $A$ to be finite sets whose cardinalities are denoted $|A|$ and $|B|$ respectively. Are the follow two inequalities about the union and intersection of $A$ and $B$ true?
$$\mathrm{max}(|A|,|B|) \leq |A \cup B| \leq |A| + |B|$$
$$0 \leq |A \cap B| \leq \mathrm{min}(|A|,|B|)$$
If these inequalities are true are the upper and lower bounds optimal?
Comment: Yes. Take $A=B$ and $A= \emptyset$ and you will see that these bounds are optimal.
Answer: Both inequalities are true for simple reasons:
$A$ and $B$ are subsets of $A \cup B$ thus $|A|, |B| \le |A \cup B|$. And $$\begin{align*}|A \cup B| &= |A \setminus B| + \underbrace{|B \setminus A| + |A \cap B|}_{\le |B|} \\
& \le |A| + |B|
\end{align*}$$
Now, since $A \cap B \subseteq A, B$, we also get
$$
|A \cap B| \le \min(|A|, |B|).
$$
However, I don't know what you mean when you ask whether these bounds are 'optimal'. Do you mean that equality holds? If so, the answer is no and I'll leave it to you to find counterexamples (there are plenty easy counterexamples).
Comment: Define an optimal lower bound as the greatest lower bound and an optimal upper bound as the lowest upper bound.
Comment: Optimal with respect to which restrictions? If there are no restrictions, then the only optimal bounds are the exact values, i.g. $|A \cup B|$ and $|A \cap B|$ respectively.
Comment: You are correct I need to specify restrictions. Say that $A$ and $B$ may be disjoint, joint or equal.
Comment: Those are not restrictions relevant to your question. I also don't know what it means for two sets to be 'joint'.


Does pointwise decidability imply total decidability?

Question: Does it hold that if I can decide a proposition P n for each specific n, then I can also decide whether or not forall n, P n ?  It feels like it should be doable by some induction over n, but how can I prove that in Coq?
Lemma dec_forall:
  forall (P : nat->Prop),
    (forall n, decidable (P n)) ->
    decidable (forall i, P i).

Comment: I am not sure this would be provable, take `P n = some Turing machine reaches the halt state in n steps`. Obviously, `P n` is decidable, by running `P` up to `n` steps, however, I am not sure you are gonna be able to construct a decision procedure for all `n`.
Comment: If you could, a lot of people would be thrilled if you could run it on `fun n => n > 2 -> even n -> exists p q, prime p /\ prime q /\ n = p + q` and then report the results.
Comment: @DanielSchepler Touché!  :-)
Comment: You can tell whether a duck has one or two heads. Can you say whether all ducks have one or two heads? Have you considered space ducks?
Answer: This shouldn't be doable. If forall i, P i is true, the only way to confirm so is to run decidable (P n) infinitely many times. Any terminating decision procedure could only analyze finitely many values of i and therefore could never conclude that forall i, P i is true.
On the other hand, forall i, P i is semi-decidable: you can return a proof that it is false (by finding a counter-example) or not terminate, simply by checking each value of i in turn.
Comment: @TejChajed indeed you may want to be careful, recall there is a whole family of "Limited Principles of Ommiciense" that are non-constructive but neither classical, so they kind of stay in the middle and can be realized in some weird ways.
Comment: @larsr you cannot formalize this inside Coq in a shallow way due to this axiom being actually compatible with Coq's theory. But indeed my idea should, you just need to turn the Turing machine with number `m` into the predicate `P`, that's kind of a standard transformation.
Comment: Can this be shown formally, with something like ejgallego's  idea?
Comment: Btw, @Tej Chajed, I saw your answer to https://cs.stackexchange.com/questions/80590/is-possible-to-prove-undecidability-of-the-halting-problem-in-coq which was a nice proof using diagonalization.
Comment: > This shouldn't be doable. If forall i, P i is true, the only way to confirm so is to run decidable (P n) infinitely many times.

Umm, that's strange, there may be many other realizers for that proposition, unless I'm misunderstanding what you mean by "only".
Comment: @ejgallego: admittedly my comment is not precise or formal, but more an intuition based on the fact that this lemma is supposed to work for _all_ P, and an intuition about how Coq functions work. There's surely a stronger and more formal answer.


Probability of exactly 2 goals in soccer

Question: Suppose we know that the probability of x goals in a given soccer game is:

$10$% when $x = 0$
$20$% when $x=1$
$25$% when $x = 2$
$45$% when $x >2$

Every week $45$ games are played, contestants will choose $8$ matches from these $45$ and are given the following:
A) if the selected $8$ matches all have exactly $2$ goals scored each then the contestant will win \$$50$k
B) If there is EXACTLY $8$ matches with $2$ goals in each game then the contestant will win \$$100$k (i.e. if there is $>8$ matches with $2$ goals each then this scenario will not be possible, but A might be if the contestant chose the correct $8$ games)
I am trying to find the probability of scenario A and B.
Perhaps I am missing something, but is this not a binomial with parameters $Bin(45, 0.25)$ i.e. in any given game we have a probability of $0.25$ of getting exactly two goals.
Then scenario B will be $P(X=8)$ and scenario A will be $P(X>8)$?
It seems a little too simple - any advice
Answer: If $X$ is the number of matches with exactly two goals, then you are correct that $X$ is a binomially distributed random variable with parameter $p:=0.25$.  However, there is a catch.  A contestant has pre-chosen the matches, and cannot change his mind.  Even if $X\geq 8$, it is no guarantee that this contestant will win anything.
To give an answer to this problem, we just look at the eight chosen matches.  The probability to win the prize $B$ equals the probability that all the chosen matches turn up with exactly two goals, but no other matches (outside the chosen matches) result in two goals.  That is,
$$\text{Prob}(\text{winning }B)=p^8(1-p)^{45-8}=p^8(1-p)^{37}\,.$$
On the other hand, to win $A$, all eight chosen matches must turn up with exactly two goals, but at least one of the other matches result in exactly two goals.  This means
$$\text{Prob}(\text{winning }A)=p^8-\text{Prob}(\text{winning }B)=p^8-p^8(1-p)^{37}=p^8\big(1-(1-p)^{37}\big)\,.$$


Calculating Simple Functions of Discrete Random Variables

Question: Say I have a random variable $X$ that has some distribution (e.g. the value obtained when rolling a standard dice). I'm trying to find out whether the probability distributions of functions of that variable are calculated by simply taking the probability for $x_1$, $x_2$, $x_3$.... $x_n$ and assigning them to $f(x_1),~ f(x_2),\dots,~f(x_n)$ or whether there is a more complicated process, and that depends perhaps on the functions and types, number of etc r.v.'s themselves?
For example, say the player of a game scores points based on the value of the above dice they roll (whose r.v. is $X$), according to:
$$f(X) = X^2 + 2X + 2 $$
For the dice: $X = 1, 2, 3, 4, 5$ or $6$. And of course $\Bbb P(X = x_{1-6}) = 1/6$
Calculating $f(X)$ for the dice's values, the possible points you can score are: $5, 10, 17, 26, 37$ and $50$.
Is then the probability distribution for the points you can score simply: $$\Bbb P(f(X) = 5) = 1/6; \Bbb P(f(X)=10) = 1/6,\dots, \Bbb P(f(X) = 50) = 1/6 $$? Would it be accurate too to say that the score $f(X)$ is itself a random variable?
I'm hoping to extend this concept to things like the addition of different r.v.'s - i.e. to understand what it means to add two r.v.'s $X + Y$ - but I've heard this is much more complicated, so I thought I'd start with this.
Many thanks for all your insight, really appreciate it.
Comment: Basic approach is sound for a discrete random variable (taking finite or countably many values). You have to be careful if $f$ is not 1-to-1 [for example if two values of $X$ produce one value of $f(X)$]. // A different approach is usually necessary for continuous random variables. (For example, the square of a normal random variable.)
Answer: Yes, that is indeed how it works in this case, and that $f(X)$ is indeed a random variable in its own right.
To see this more clearly, we can calculate
\begin{align} \\
\ \Bbb P(f(X)=5) & = \Bbb P(X^2+2X+2=5) \\
\ & = \Bbb P(X^2+2X-3=0) \\
\ & = \Bbb P((X+3)(X-1)=0) \\
\ & = \Bbb P(X=-3)+\Bbb P(X=1) \\
\ & = 0 + 1/6 \\
\ & = 1/6
\end{align}
Similarly for the others.
Answer: Yes, a function of a random variable is a random variable as well. There are a few cases where the function can "remove all randomness" (e.g. $X$ is $-1$ or $1$ with equal probability and $f(X)=X^2$), but even in these cases $f(X)$ can still be considered a random variable.
Your probabilities for $f(X)$ with the die roll example are correct. Generally, for a discrete random variable the calculation is identical: you just plug in the $X$ values to get the $f(X)$ values and carry over the same numerical probability for each outcome. Of course you have to be a little careful if multiple $X$ values give the same function output, and, in this case, you need to combine the probabilities appropriately.
There is a general result for continuous random variables. You need to know calculus to apply this method though. See the Wikipedia page here. You have to be careful with functions that don't satisfy certain properties (they need to be one-to-one), e.g. $f(X)=X^2$ can be tricky.
For two random variables (or three more random variables, and so on), you need the concept of a joint probability distribution. This can become more complicated though. For multiple discrete random variables, you can generally calculate the probabilities similarly to the way you have already done.
Comment: (+1) But maybe _one-to-one_ instead of _monotone_ in 3rd paragraph?
Comment: I did think to write one-to-one. I was actually thinking strictly monotone and continuously differentiable for the simple case. How about I just edit it to say "certain properties, e.g. one-to-one"? As I think the answer at this level shouldn't include too many technical details.
Answer: Comment: Consider $Y = g(X) = (X - 2.5)^2,$ just to see what happens when two $X$-values can yield a single $Y$-value. Here is a graph of the four $Y$-values and their
probabilities. (Horizontal green lines at $0, 1/6, 2/6.$)

Also, notice that $E(X) = 3.5,$ but $E(Y) = 47/12 \approx 3.9167,$ not $(3.5-2.5)^2 = 1.$


How to use exponentiation method to find each inverse?

Question: Completely lost in this topic. I was unable to get help through any documentation (from class), and hoping if someone can help me on this.
Use exponentiation method to find each inverse. Recall ^−1   =
()^−1  .
(a) Inverse of 5 mod 17
(b) Inverse of 5 mod 21
It's using Fermat's Little Theorem to explain but I'm just lost on how to use that equation to even begin with. Can someone break this down for me?
Answer: Since $\gcd (5,17) = 1$ there exists some $n$ such that $5^n \equiv 1 \pmod {17}$
since 17 is prime
$5^{16} \equiv 1 \pmod {17}\\
5^{15} \equiv 5^{-1} \pmod {17}$
There may be a $n$ smaller than 16 such that $5^{16} \equiv 1 \pmod {17}$ but we know that that will work.
However, this approach seems like a lot of work.
We can use the Euclidean algorithm to find
$5m + 17n = 1$
$17 - 3\cdot 5 = 2\\
17 - 8\cdot 2 = 1\\
(-8)\cdot (-3)\cdot 5 \equiv 1\pmod {17}\\
(24-17)\cdot 5 \equiv 1\pmod{17}$
$7 = 5^{-1}$
Comment: I think this is Euclidean not exponentiation method.. I understand this part.
Comment: I gave a brief explanation of the exponential method, and then said that it is a lot of work.
Answer: To use the exponentiation method, just do repeated multiplication. By Fermat's little theorem:
$5^{16} \equiv 1 \pmod {17}\\
5^{15} \equiv 5^{-1} \pmod {17}$
But also, $5^{15} = 5\cdot 5^2\cdot5^4\cdot5^8 $. Do repeated squaring:
$5^2 \equiv 8 \pmod {17}\\
8^2 \equiv -4 \pmod {17}\\
(-4)^2 \equiv -1 \pmod {17}$
So $5 \cdot 8 \cdot -4 \cdot -1 \equiv 7 \pmod {17}$, and therefore $5^{-1} \equiv 7\pmod {17}$


Ways to test bar charts with few bars to see if they come from the same distribution?

Question: I have survey data with ordinal/categorical data. Most of the time the answers to question are Yes/No. I want to compare the bar charts (normalized) of yes/no from participants who gave a particular answer to a previous question.

Eg. Looking at users who answered yes to Q.4, then those that answered no to Q.4, did they answer similarly to Q.6? This will give two distributions/ratios for instance (0.4,0.6) and (0.35,0.65).

Should I use a Chi-squared test? Or use a measure of distribution distance similarity like the Jensen–Shannon divergence?
Answer: You can use a Chi-squared test of independence in this case.
I think it will be much easier to apply than the (slightly overkill) Jensen-Shannon divergence.
Comment: what does **test of independence** mean when using this test?
Comment: This refers to the test, developed by Karl Pearson, which is used to asses the **independence** of two categorical variables. It employs a **Chi-squared test statistic**, but many other tests do, so it is important to specify that we are using the Chi-squared test of independence. For more information, see http://en.wikipedia.org/wiki/Pearson's_chi-squared_test or http://stattrek.com/chi-square-test/independence.aspx .
Comment: The independence refers to whether or not the two categorical variables depend on each other. If some variable X and Y are independent, the distribution of X is the same for all levels of Y (in your case 2, yes/no), and vice versa.
Comment: great thanks, so the independence refers to them not being essentially the same distribution?


Allow FTP and Database on single IP address

Question: I am using Ubuntu 14.04 server, and i use this in the lab with local ip address (192.168.0.1) and configured with live IP too (22.214.171.124 this is a static IP)
so, i want to allow users to access the FTP and database service only from lab not from outside. Please help me.
Comment: There are multiple (very basic) solutions to that, such as a firewall, binding services to a specific ip-addresses, TCP wrappers etc.
Answer: It looks like you need a firewall to do that. First, install ufw on your server:
sudo apt install ufw
Then, deny incoming requests by default:
sudo ufw default deny incoming
After that you will want to allow reuests from your lab on every port:
sudo ufw allow from 192.168.0.0/24
Now reload and enable the firewall with the following commands:
sudo ufw reload
sudo ufw enable
To allow access to a TCP port (in this example port 21) from everywhere (that means from the outside network), run this:
sudo ufw allow 21/tcp
To deny it again (delete the rule) run this:
sudo ufw delete allow 21/tcp
DON'T run sudo ufw deny 21/tcp because it will also block access from your local net.
Always reload ufw after a change with this command:
sudo ufw reload
There are also other solutions (like editing the configs of the respective programs), but I think this is the easiest one.


PHP unpack zip and insert content into database

Question: I need to be able to extract a zip file, and insert the names of the files in the zip file into a database.
I've searched around, and found multiple scripts to unpack a zip file, but it seems that I'm not able to get the individual filenames of the files in the zip file.
Answer: I would probably suggest to use two system calls:
1) unzip to tmp folder
2) read files from that folder
(updated full working script):
<code><?php

if (isset($_POST["fsubmit"])){
    echo "<pre>";
    var_dump($_POST);
    var_dump($_FILES);
    $tmp_dir = "tmp/" . microtime(true);
    if (!file_exists($tmp_dir)){
        mkdir($tmp_dir);
    }
    if (is_uploaded_file($_FILES["file"]["tmp_name"])){
        move_uploaded_file($_FILES["file"]["tmp_name"], $tmp_dir . "/a.zip");
        exec("unzip -z -j $tmp_dir $tmp_dir" . "/a.zip");
        exec("ls $tmp_dir", $out);
        echo "Files in the archive:\n";
        foreach ($out as $file){
            $file = trim($file);
            echo "File: $file,", filesize($tmp_dir . "/" . $file)."b\n";
        }
        exec("rm -rf $tmp_dir");
    }
} else {
?>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="fsubmit" value="upload">
</form>
<?
}
</code>
Pre-requisites
0) will work if you are under unix/linux/mac (won't work under windows)
1) create test.php and paste in it the code above
2) make sure in the same folder where test.php, is folder tmp
3) make sure apache user can write that folder (e.g. chmod 777 tmp)
4) make sure your php allows file uploads
5) make sure your server has "unzip" command line tool

Regards.
Comment: Yeah okay, so I got that, but all that happens now, is the $tmp_dir being created.

the file looks like this:

http://pastebin.com/19CGCaXg
Comment: where is zip file coming from? in my example it assumes it's uploaded through a form e.g.
Comment: also, make sure "unzip" is present on your server.
Comment: Yeah, the zip is uploaded through af form.
Comment: is zip file being copied in the temporary folder?
Comment: No, the temp folder is created, but is left empty.
Comment: see updated code above, just follow instructions below the script.


How to sort bar charts synchronous with the ticks of x axis

Question: I am adopting the example from Mike Bostock to sort bar charts - http://bl.ocks.org/mbostock/3885705.
However, the transition of the bars and the ticks of the x axis are not occuring at the same time.
The reason is that the transition is called separately for the bars and the ticks (in the function change():
transition.selectAll(".bar")
    .delay(delay)
    .attr("x", function(d) { return x0(d.letter); });

transition.select(".x.axis")
    .call(xAxis)
  .selectAll("g")
    .delay(delay);

The solution should be when constructing the svg, I would like to add each bar to the corresponding tick.
However I didn't succeed to correctly adjusting the line
  svg.selectAll(".bar")
  .data(data)
.enter().append("rect")...

e.g.
svg.selectAll("g.tick")
  .data(data)
.enter().append("rect")...// would put all the bars under each g.tick

or
svg.selectAll(".x.axis")
  .data(data)
.enter().append("rect")...// would put the bars after all g.tick's at the end. So again I can't grap the whole group together later.

Answer: Interesting idea.
You can get the rects grouped with each tick's g by:
svg.selectAll(".x>.tick")
  .data(data)
  .append("rect")
  .attr("class", "bar")
  .attr("x", function(d) {
    return -x.rangeBand()/2; // set x to be half width, tick g will position it
  })
  .attr("width", x.rangeBand())
  .attr("y", function(d) {
    return -(height - y(d.frequency)); // set y to negative
  })
  .attr("height", function(d) {
    return height - y(d.frequency);
  });

You then have to rewrite the transition since calling .call(xAxis); will recreate the tick g and remove the bars.
transition.selectAll(".x>.tick")
  .delay(delay)
  .attr("transform", function(d) {
    return "translate(" + x0(d.letter) + ",0)";
  });

Putting this together.
Comment: The reason any approach with ...selectAll(".bar").data(data).enter().append("rect")... does not work is that any enter() selection contains a group that stores the parent node. All elements form the enter() selections are then either append or inserted IN SUCCESSION after the parent node. So with the enter() selection it is not possible to distribute the elements in a non subsequent fashion.
Comment: Bingo. That seems to be the right solution. Thanks so much, I will accept and upvote the answer later today when I have a chance to try it. Can you please just elaborate a bit why this css selector works (e.g.in comparison with my selectors) since all articles I read about the data joins explain the join not how to append the elements at different places in the DOM tree.
Comment: @ee2Dev, `g.tick` won't work, that'll return the y ticks as well.  `.x.axis` doesn't work since it returns the `g` containing the x ticks and not the ticks themselves.  Finally, `.bar` returns the rects, but you want the rects in the ticks, not the ticks in the rects (to take advantage of the d3's axis helper).  Finally, I found I need to drop the `.enter()` after my `.x>.tick` as the axis data is already bound to each tick and d3 would not re-enter after binding the rect data.
Comment: Thanks so much for the great and quick reply! The difference is not so visible in M Bostocks example but in my own code it really shows...I looked back what I did wrong. Actually, unlike I wrote above, I tried: svg.select(".x.axis").selectAll(".tick").selectAll(".bar").data(data).enter().append("rect").... following the typically enter,update pattern. But that created all bars for each tick! I have to think through your approach, I guess you just attach the data and append the bars knowing they match...


Time Zone keeps changing after sync with PDC in different site

Question: Background: I have a single domain, running in 2 sites that is connected using Site-to-Site VPN.

Site A is running in time zone 2:00+ UTC
Site B is running in time zone 4:00+ UTC

DCs are correctly placed into their own corespondent subnet in the Active Directory Sites and Services. All DCs are running Windows 2012 R2, all clients are running Windows 8.1
What I am trying to achieve: sync all users in the domain with an external NTP server for login purposes with an online service, I enabled NTP on the PDC to sync with an external source using the Microsoft FixIT article http://support.microsoft.com/en-us/kb/816042.
What really happened: users in Site A are working correctly, users in Site B are syncing from the PDC too, but their time zone keeps changing from 4:00+ UTC to 2:00+ UTC, users in Site B can change the TZ back to 4:00+ UTC, but whenever their machines resync with the PDC, the TZ changes back to 2:00+ UTC.
How I tried to solve this problem: I created a group policy computer start up script that reads
<code>Tzutil.exe /s "Arabian Standard Time"
</code>
The syntax should change the TZ to 4:00 UTC, I linked the login script to Site B, I can confirm that the script is running successfully and the time changes to 2:00+ UTC upon login, however, after awhile, the machines sync to the PDC and the TZ goes back to 2:00+ UTC.
Help?
Comment: The thing about this that I'm confused on, is that it appears as though you are conflating two separate issues.  NTP and time zones are two separate things.  In other words, NTP doesn't confer any time zone to the client. It's all UTC. So the timezones being changed is something else...
Comment: That's where my puzzlement come, my problem started right after we configured the NTP service on the PDC using the Microsoft FixIt tool, I went to read the technicalities of the the tool several times, it shows nothing regarding the time zone change, I have tired to look all over the internet how both are related and I couldn't find any, I thought of asking here hoping to find the missing piece of the puzzle.
Comment: It is also possible to set client timezone via DHCP. Perhaps you have that option enabled on your DHCP server, which overrides other settings on the clients?
Comment: I'm using two different DHCP servers, one for each site, I have rechecked my settings on both, I have only the default scope options enabled. so I believe that DHCP got nothing to do with this.
Answer: So I contacted Microsoft for this, they were very puzzled as well, we never figured out why the time zone change by it self or which process was causing this behavior, but they gave me a work around that fixed my problem, I'm going to post here for future referencing (copy/pasting from Microsoft communication with me)

Regarding the current issue, if it is possible, I suggest you define the group policy

Computer Configuration\Policies\Windows Settings\Security
  Settings\Local Policies\User Rights Assignment\Change the Time Zone

to determine which users and groups can change the time zone. Please check my test:

The users which don't have rights will unable to change the time zone:
Answer: Know this is an old issue, however, we were experiencing the same problem at our 2 sites recently so thought we'd share our experience.
There is a Scheduled Task built into Windows called SynchronizeTimeZone that runs tzsync.exe which syncs the Time Zone to the closest RWDC.  In our case we disabled this task on clients & used TZUtil.exe to set the correct time zone again.


Matplotlib spectrogram versus STFT

Question: I'm currently computing the spectrogram with the matplotlib. I specify NFFT=512 but the resulting image has a height of 257. I then tried to just do a STFT (short time fourier transform) which gives me 512 dimensional vectors (as expected). If I plot the result of the STFT I can see that half of the 512 values are just mirrored so really I only get 257 values (like the matplotlib). Can somebody explain to me why that is the case? I always thought of the FT as a basis transform, why would it introduce this redundancy?
Thank you.
Comment: See https://en.wikipedia.org/wiki/Fourier_transform#Basic_properties in the section about conjugation.  You are plotting either the real component or the magnitude which for a real signal will be mirrored for positive and negative frequencies.
Answer: The redundancy is because you input a strictly real signal to your FFT, thus the DFT result is complex conjugate (Hermitian) symmetric.  This redundancy is due to the fact that all the imaginary components of strictly real input are zero.  But the output of this DFT can include non-zero imaginary components to indicate phase.  Thus, the this DFT result has to be conjugate symmetric so that all the imaginary components in the result will cancel out between the two DFT result halves (same magnitudes, but opposite phases), indicating strictly real input.  Also, the lower 257 bins of the basis transform will have 512 degrees of (scaler)freedom, just like the input.  However, a spectrogram throws away all phase information, so it can only display 257 unique values (magnitude-only).
If you input a complex (quadrature, for instance) signal to a DFT, then there would likely not be Hermitian redundancy, and you would have 1024 degrees of freedom from a 512 length DFT.
If you want an image height of 512 (given real input), try an FFT size of 1024.
Comment: the DF argument makes sense but I still don't get why the lower 256 components would be the same as the top 256. But tcaswell also gave a link to Wikipedia so I think I will read up on that. Thanks :)

Matplotlib spectrogram versus STFT


Placement of critical points of Morse function on the sphere

Question: On a similar note to my previous question, I am still thinking about functions on the sphere.
Assume I have a $C^2$ function on the sphere $ f : S^{d-1} \mapsto \mathbb{R} $ which is Morse (i.e. all critical points are non-degenerate and thus all critical points are isolated) and assume that this function has at least one saddle point.
Now, if we say $ d = 3 $, if I am not mistaken, then we will actually have at least two saddles, since by the Poincare-Hopf theorem, the sum of the indices of any vector field must sum up to its Euler characteristic, which in this case is 2.
Now, my question is, are there any restrictions regarding where these critical points are exactly on the sphere (when $ d = 3 $, but also in general) ? Can they be arbitrarily close to each other? If there are some restrictions, what exactly is causing them?
Again, apologies if my question is really basic, as I am absolutely unknowledgeable about differential topology. Any references or comments are appreciated!
Answer:
Theorem: For any $v, f \in\{1, 2,\cdots \}$, $e\in \mathbb \{0, 1, \cdots\}$ such that $v-e + f = 2$, and for any distinct $p_1, \cdots, p_v , q_1, \cdots, q_e, r_1, \cdots ,r_f \in \mathbb S^2$, there is a Morse function $F$ on $\mathbb S^2$ so that
$$\text{Crit}(F) = \{p_1, \cdots, p_v , q_1, \cdots, q_e, r_1, \cdots r_f\}$$
and
$$\text{Ind}(p_i) = 0, \ \text{Ind}(q_i) = 1, \ \text{Ind}(r_i) = 2.$$

Thus, there is absolutely no constraint on the location of the critical points, and no constraint on the number of saddle points (besides the one coming from the Euler formula)
Proof of Theorem: Given any $k\ge 1$ let $g_k$ be a function on $[-1,1]$ with the following properties:

$g_k$ is continuous and smooth and positive in $(-1, 1)$,
$g_k(t) = \sqrt{1-t^2}$ away from $[-1/2, 1/2]$
$g_k$ has exactly $k$ local maximum and $k-1$ local minimum (excluding endpoints $\pm 1$), and $g''_k\neq 0$ at each critical points.

Now for any $v, f\in \{1, 2, \cdots\}$ let
\begin{align}
r(t)=r_{v,f}(t) &= \frac{g_f(t) + g_v(t)}{2},\\
c(t)=c_{v,f}(t) &= g_{f}(t)- r_{v,f}(t) \\
&= -g_v(t)+ r_{v,f}(t).
\end{align}
Note that both $r_{v,f}$, $c_{v,f}$ are smooth functions on $[-1,1]$, $r_{v,f}(t) = \sqrt{1-t^2}$ and $c_{v,f} = 0$ away from $[-1/2,1/2]$.
Now define the function $F = F_{v.f}$ on $\mathbb S^2$ as follows: for each $(t, y, z)\in \mathbb S^2$, write
$$(t, y, z) = (t , \sqrt{1-t^2 }\cos\theta, \sqrt{1-t^2}\sin\theta)$$
for some $\theta\in \mathbb S^1$. Then define
$$ \tilde F(t, y, z) = c(t) + r(t)\sin\theta. $$
The proof of the following is direct and skipped.

Claim 1: $\tilde F$ is a morse function. All critical points occurs at $\sin \theta = \pm 1$. There are $v$ local minimum, $f$ local maximum, and $e:= v+f-2$ saddle points.

Thus we have found, for every $v, f\ge 1$ and $e\ge 0$ such that $v-e+f=2$, a morse function $\tilde F$ so that
$$\text{Crit}(\tilde F) = \{\tilde p_1, \cdots, \tilde p_v , \tilde q_1, \cdots, \tilde q_e, \tilde r_1, \cdots \tilde r_f\}$$
and
$$\text{Ind}( \tilde p_i) = 0, \ \text{Ind}( \tilde q_i) = 1, \ \text{Ind}(\tilde r_i) = 2$$
for some distinct $\tilde p_i, \tilde q_i, \tilde r_i \in \mathbb S^2$.
The proof of the theorem is finished using the following claim:

Claim 2: Let $M$ be a connected smooth manifold of dimension $n\ge 2$, and let
$$S = \{s_1, \cdots, s_K\}, \ \ \ \tilde S = \{\tilde s_1, \cdots, \tilde s_K\}$$
be two finite subsets of $M$. Then there is a diffeomorphism $\phi : M\to M$ so that $\phi(s_i) = \tilde s_i$ for $i=1, \cdots, K$.

Proof of Claim 2 (Sketch): Since $M$ is connected, there is a smooth regular curve $\gamma$ in $M$ joining $\gamma(0)=s_1$ to $\gamma(1)=\tilde s_1$, and there is an open neighborhood $U$ of the image of the curve that does not pass through $s_2, \cdots, s_K, \tilde s_2, \cdots, \tilde s_K$ (this we need $n\ge 2$). Now let $X$ be a smooth vector field compactly supported in $U$ so that $X(\gamma(\tau ))= \gamma'(\tau )$ for all $\tau \in [0,1]$. Let $\phi^t_X:M\to M$ be the one parameter group of diffeomorphism generated by $X$. Then $\phi_1 :=\phi^1_X$ satisfies
$$\phi_1(s_1) =\tilde s_1$$
and $\phi_1$ fixes every other elements in $S\cup \tilde S\setminus\{s_1, \tilde s_1\}$ since the support of $X$ does not intersect $S\cup \tilde S\setminus\{s_1, \tilde s_1\}$.
Then one can similarly construct $\phi_2, \cdots, \phi_K$ so that $\phi_i (s_i) = \tilde s_i$ and $\phi_i$ fixes elements in $S\cup \tilde S\setminus\{s_i, \tilde s_i\}$. Then
$$\phi := \phi_K\circ \phi_{K-1}\circ\cdots \circ \phi_1$$
is a diffeomorphism which satisfies the conclusion of claim 2.
Lastly, to finish the proof of the theorem: let $\phi$ be a diffeomorphism on $\mathbb S^2$ so that
$$ \phi (p_i) = \tilde p_i, \ \ \phi (q_j) = \tilde q_j, \ \ \phi (r_k) = \tilde r_k$$
for all $i=1, \cdots, v$, $j=1, \cdots, e$, $k=1, \cdots, f$. Then $F:= \tilde F\circ \phi$ is a Morse function which satisfies the conclusion of the theorem.


If I ever compose minor key music, for the original key, should I use A minor or C minor?

Question: The A minor scale is the first and easiest minor key to learn in music since it has no sharps and flats just like its relative key called the C major scale but I've seen some composers like Grant Kirkhope used both C major and C minor as the main key for most of the songs from 2 of the Nintendo 64 games called Banjo Kazooie and Banjo Tooie since C major and C minor are parallel keys so I'm wondering should I use the A minor scale as the main key since it's the first minor scale to learn just like relatively the C major scale or should I use the C minor scale as the main key since it's the parallel of the first major scale called C major.
Comment: @MatthewtheMusicFan2022 It does matter! C major is the easiest key on the piano, but not on every instrument. It's certainly not the easiest key on the violin, where G, D and A are arguably easier, and a beginner playing the trombone would probably prefer Bb, Eb, Ab or even Db major.
Comment: Considering that the reference is about a synthesized music played by a "program", the key is almost irrelevant as long as "it sounds good" with the chosen "instrument". But, as said, the instrument *does* matter if it's going to be played by somebody: certain instruments do not even have certain keys, cannot play some of them at the same time or cannot switch easily (consider the harp) or have a range that limits the available sounds based on the key (if the part uses a bigger range). The instrument must *always* be considered when composing, especially if the target musician is a beginner.
Comment: Which instrument(s) are you composing for?
Comment: It also doesn't matter in which key. Play it in both keys and write it in both keys. You will learn more and you'll have the greatest profit.
Comment: I mean it doesn't matter what instruments.
Comment: Indecisively flip between A minor and C minor, just like Kirby games do. Occasionally, indecisively flip between those two keys *in the same theme* (e.g. the *Kirby Squeak Squad* regular boss theme). As a result, also occasionally try a minor key other than those two (e.g. the regular boss theme of *Kirby's Return to Dream Land* being in F minor instead).
Comment: I mean in music softwares, not necessarily on actual instruments.
Comment: @MatthewtheMusicFan "should" implies that there might be an advantage to using one key over another.  Whether there's an advantage to a given key depends on what _you_ find advantageous, which is of course subjective.  What do you find advantageous?
Comment: I don't even know.
Answer:
...some composers like Grant Kirkhope...since C major and C minor are parallel keys so I'm wondering should I use the A minor scale as the main key since it's the first minor scale to learn...

It is natural to start learning minor keys using either A minor or C minor for the reasons you mention, but I don't really see the connection between your comment about Kirkhope, and what key you should choose.
But, I don't think that makes a difference. You could use any minor key A, C, etc. And you could try working in parallel key changes too if you want to emulate Kirkhope. You could look to other composers as well. (Haydn minuets often go to the parallel minor for the "trio" section is another example.)
Two caveats:
Regarding this comment...

...The A minor scale is the first and easiest minor key to learn in music since it has no sharps and flats...

...if you are working with standard minor key harmony, that really is not true. Research the dominant chord in minor, or the use of the raise sixth and seventh scale degrees in minor key music. In a nutshell, the seventh degree gets raised for dominant chords in minor, so for example, in A minor, the E chord will use a G sharp and so the chord will be an E major chord. For some practical examples try looking at those Haydn minuet trios I mentioned earlier, or any of the many short keyboard works of JS Bach, stuff like the "little preludes."
Second, it doesn't really matter which minor key you first choose to learn from. But try to learn all the minor keys. You can start with a small set at the beginning, like A minor with no sharps/flats, D minor with one flat, and E minor with one sharp.
If you are playing on keyboard, you may also want to start early with one minor key with tonic on a black key, like F# minor with only three sharps, but starting on a black key.
To learn a minor key probably, play with various forms of scales - natural, harmonic, and melodic. Most method books would have you just play the scales, but I think it's better to put them into a harmonic context to see how the various changes to the sixth and seventh degree actually work. For a dominant chord use the raised seventh degree, for a subdominant chord use the lowered sixth and seventh degrees, for a tonic chord it's a bit of a mix but a reasonable rule of thumb is probably to not use the lowered sixth and seventh for an ascending scale for a tonic chord.

...those are just a few basic examples, of course you could do many other things.
Getting the feel of minor keys can take a while, because of the variable sixth and seventh degrees. Just give it time and stick with it, it should make sense to your ears, and then it will make sense in your hands and on the page. Understanding this flexible use of scale tones will become very valuable knowledge.
Comment: I like the pun in your 1st sentence - intended or not...
Comment: Yeah, hear that in my head when I wrote it too :-)
Answer: A minor has the parallel key of A major. Often pieces don't modulate into their parallel keys - not as often as into their relative keys, anyway.
Using C minor will incorporate 3 flats, against 0 for C major. Using A major will incorporate 3 sharps, against 0 for A minor. So it's as long as it's broad !
For simplicity, at the stage you seem to be at, stick with the key signature of C major/A minor - no ♯ or ♭.


Find linear equations based on the given function

Question: Question:
The function h is given by $h(x) = ax^3 + bx^2 +cx +d$.
where a,b,c and d are real constants
The graph of $y =h(x)$ passes through the points $(1,1)$ and $(2,2)$. Given that $(2,2)$ is a maximum point , find three linear equations involving a,b,c and d.
It is given further that the point (-4 ,14) lies on the graph of y=|h(x)| , and that h(x) is strictly decreasing for $x \geq 2$ . Find the values of a,b,c and d.
I tried to find 3 required equations , but the results,which I found , are not satisfied with the requirement . I hope that I would be given a nice method to solve these questions . Thank you !
Comment: May I suggest you show what you already did ?
Comment: I just replace y and x as the coordinate of 2 points which h(x) passes .Those are all I can do
Answer: Considering $$h(x) = ax^3 + bx^2 +cx +d$$ apply the formula to get
$$a+b+c+d=1\tag 1$$ $$8a+4b+2c+d=1\tag 2$$ You are also told that the function is maximum at $(2,2)$ which means that $$h'(x)=3ax^2+2bx+c$$ is zero at this point. So, $$12a+4b+c=0\tag 3$$ Is it so complex ?
Answer: You have $a+b+c+d=1$ and $8a+4b+2c+d=2$.
Because $(2,2)$ is maximum point, so $h'(2) = 12a + 4b + c = 0$.
Point (-4,14) lies on $|h(x)|$, then $14 = |-64a+16b-4c+d|$.
From here, you have two cases.
Case 1
$\begin{cases}a+b+c+d&=&1\\8a+4b+2c+d&=&2\\12a+4b+c&=&0\\-64a+16b-4c+d&=&14\end{cases}$
Case 1
$\begin{cases}a+b+c+d&=&1\\8a+4b+2c+d&=&2\\12a+4b+c&=&0\\-64a+16b-4c+d&=&-14\end{cases}$
Solve it, you got $a,b,c,d$.
Because $h(x)$ decreases strictly for $x\geq 2$, so $h'(x) < 0$ for all $x\geq 2$, or $$3ax^2 + 2bx + c < 0.$$


NLP: pre-processing dataset into a new dataset

Question: I need help with processing an unsorted dataset.  Sry, if I am a complete noob. I never did anything like that before. So as you can see, each conversation is identified by a dialogueID which consists of multiple rows of "from" & "to", as well as text messages.
I would like to concatenate the text messages from the same sender of a dialogueID to one column and from the receiver to another column. This way, I could have a new csv-file with just [dialogueID, sender, receiver].

the new dataset should look like this

I watched multiple tutorials and really struggle to figure out how to do it. I read in this 9-year-old post that iterating through data frames are not a good idea. Could someone help me out with a code snippet or give me a hint on how to properly do it without overcomplicating things? I thought something like this pseudo code below, but the performance with 1 million rows is not great, right?
while !endOfFile
  for dialogueID in range (0, 1038324)
    if dialogueID+1 == dialogueID and toValue.isnull()
      concatenate textFromPrevRow + " " + textFromCurrentRow
      add new string to table column sender
    else
      add text to column receiver

Answer: Edit 1
According to your clarification, this is what I believe you're looking for.
Create an aggregation function which basically concats your string values with a line-break character. Then group by dialogueID and apply your aggregation.
d = {}
d['from'] = '\n'.join
d['to'] = '\n'.join
new_df = dialogue_dataframe.groupby('dialogueID', as_index=False).agg(d)

After that rename the columns as you'd like:
df.rename(columns={"from": "sender", "to": "receiver"})

Original answer
Not quite sure I understood what you try to achieve, but maybe this will give some insights. Maybe write a couple of rows of the table you expect to get, for better clarification
Comment: Hi, I added a new picture of how I meant it. Sry, I am bad with words. I hope this is more clear. Also thanks for the link.
Comment: Yep, I understood you correctly. Please see the accepted answer by the link I gave. I suppose you can use something like
`d = dict.fromkeys(dialogue_dataframe.columns.difference(['dialogueID']), 'first')
d['from'] = ', '.join
d['to'] = ', '.join
new_df= dialogue_dataframe.groupby('dialogueID', as_index=False).agg(d)`
After that just rename the columns `from` and `to` to `sender` and `receiver`
Answer: While the exact structure of the data (and thus your task) is not completely clear, maybe DataFrame.apply or rather DataFrame.aggregate can help you speed things up. Also, I would aggregate into either a dictionary or dataframe indexed by dialogue id. This way you can easily check if a given dialogue / sender already exists.


Docker compose run bash with special characters

Question: I've been looking through the internet but I haven't found anything about this.
I'm trying to use special characters (e.g.: ç, ã, í, etc) inside a ruby string in my web app container rail's console, but when I type any of those the letter just don't appear.
I thought it could be something with my terminal's encoding set, but when I exit from the container's console, I can type any special character.
To verify that, try running (supposing you have a web container image)
sh
$ docker-compose run web bash
root@<container_id>:/var/www/cegonha$ <try to put any special character or letter with accent here>

Can anyone help me with this? I really need to put a ruby script that contains a string with special characters.
Comment: check container's console encoding. Also, try your script despite the fact that console does not work as expected. please read [how to ask good questions](https://stackoverflow.com/help/mcve).
Answer: Did you try to set any $TERM value?
in my container

user@localhost-:~$ docker exec -e TERM=xterm -it localcontainer bash -c "echo ç, ã, í"
ç, ã, í
user@localhost-:~$


Como atualizar conteúdo sem recarregar pagina HTML?

Question: Montei uma API Flask conectada a uma banco de dados MySQL, o qual tem suas entradas exibidas em uma página HTML.
player_manager.py:
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://xre:sdhjsdhsj2562@localhost:3306/team'

db = SQLAlchemy(app)

@app.route("/", methods=["GET"])
def get():
    try:
        players = Player.query.all()
    except Exception as e:
            print("Failed")
            print(e)
    return render_template("home.html", players=players)

@app.route("/", methods=["POST"])
def post():
    player = Player(
        nome=request.args.get("nome"),
        posicao=request.args.get("posicao"),
        numero=request.args.get("numero"),
        gols=request.args.get("gols"),
        partidas=request.args.get("partidas"))
    db.session.add(player)
    db.session.commit()
    return redirect("/")

class Player(db.Model):
    nome = db.Column(db.String(80), unique=True, nullable=False, primary_key=False)
    numero = db.Column(db.Integer, primary_key=True)
    posicao = db.Column(db.String(80), unique=True, nullable=False, primary_key=False)
    gols = db.Column(db.Integer, primary_key=False)
    partidas = db.Column(db.Integer, primary_key=False)

    def __repr__(self):
        return "Nome: {}, Numero: {}, Posicao: {}, Gols: {}, Partidas: {}".format(
            self.nome,
            self.numero,
            self.posicao,
            self.gols,
            self.partidas
            )

if __name__ == "__main__":
    app.run(debug=True)

home.html:

Jogadores

    {% for player in players %}

{{player}}

    {% endfor %}

Gostaria que a página que exibe as entradas do banco fosse atualizada automaticamente conforme novas entradas fossem adicionadas ao banco. Pelo que pesquisei, seria possível conseguir esse resultado através de Server Sent Event, como neste exemplo, ou através de AJAX, como neste outro exemplo. Como eu sou novo em desenvolvimento web, não sei como implementar essas alterações em meu código.
Tentativa de usar Ajax:
player_manager.py:
@app.route("/", methods=["POST"])
def post():
    player = Player(
        nome=request.args.get("nome"),
        posicao=request.args.get("posicao"),
        numero=request.args.get("numero"),
        gols=request.args.get("gols"),
        partidas=request.args.get("partidas"))
    db.session.add(player)
    db.session.commit()
    return redirect("/")

home.html:

Jogadores

    {% for player in players %}

{{player}}

    {% endfor %}

Contudo, ainda não consigo atualizar o conteúdo sem recarregar o conteúdo.
Answer: Bem, realmente você precisa utilizar alguma coisa além do próprio Flask para essa tarefa e o Ajax é uma boa solução. Porém, a atualização de dados deve ocorrer dado algum evento. Como você precisa que ocorra uma atualização o tempo inteiro, você pode setar um timeout (você tem um exemplo aqui). Do jeito que você fez a função só é chamada uma única vez, quando a página é carregada.
Porém, eu aconselharia algo mais robusto. Você pode pensar em soluções usando o React e até mesmo mudar a sua base para o Firebase, por exemplo (você pode apenas avaliar pra saber se vale a pena). O Jinja2 do Flask é muito bom e tem muita coisa, mas você vai sempre precisar de algo mais e isso pode ser alcançado mesclando tecnologias. Tipo embutindo scripts JavaScript, usando Vue.js, etc.
Enfim, é isto. Boa sorte no seu projeto!


Preciso de ajuda, não consigo fazer esse script funcionar

Question: Queria fazer o efeito desse video: https://www.youtube.com/watch?v=lZ-OO7x75Rc. Se alguém puder me ajudar, agradeço.

*
{
    margin: 0;
    padding: 0;
}
body
{
    height: 200vh;
    background: #111;
}
section
{
    position: absolute;
    width: 100%;
    height: calc(100% - 200px);
    background: #2abbff;
}
section .curve
{
    position: absolute;
    bottom: -200px;
    height: 200px;
    width: 100%;
    transform-origin: top;
}
section .curve img
{
    width: 100%;
    height: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">

Answer: O erro está no seguinte trecho:
scroll.style.transform = 'scaleY(${value})';

Veja que você atribui uma string a propriedade transform do style.
Porém na verdade, isso deveria ser uma template string:

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/template_strings

Portanto para corrigir, faça da seguinte forma:
scroll.style.transform = `scaleY(${value})`;

Com isso, seu código ficará da seguinte forma (Coloquei uma outra imagem como exemplo):

*
{
    margin: 0;
    padding: 0;
}
body
{
    height: 200vh;
    background: #111;
}
section
{
    position: absolute;
    width: 100%;
    height: calc(100% - 200px);
    background: #2abbff;
}
section .curve
{
    position: absolute;
    bottom: -200px;
    height: 200px;
    width: 100%;
    transform-origin: top;
}
section .curve img
{
    width: 100%;
    height: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">


What to do when the sum of probabilities is greater than one?

Question: I have this problem. Imagine that somebody will pay after I contact him by sending an email, text message, letter, or calling him. I have the probability of how likely he will pay after being approached with one of the mentioned methods.
The sum of these probabilities is greater than one. How can I transform them so that the sum is less than or equal one?
Comment: There is no reason why those probabilities should add to $1$ or less.  Maybe the fellow will always play however he is contacted.  Then each conditional probability is $1$ so the sum is $3$.  No problem.
Comment: Cannot happen. Probabilities are between 0 and 1. Maybe you have a normalization problem.
Comment: If their sum is $s$, then divide each by $s$ such that their sum is $1$.
Comment: The need that their sum is one is coming from the expected return that I can get by multiplying the probability by the amount of money that they owe to me.
Comment: I think that this formula might be the solution P(A) + P(B) - P(A∩B)
Answer: The problem is that these are not probabilities of mutually exclusive events. When rolling a die, you can take the probability of rolling a 1 and add it to the probability of rolling a 2 to get the probability of rolling a 1 or 2, but only because getting a 1 and getting a 2 are mutually exclusive events.
Suppose the person has a 50% chance of paying after being approached with any of the methods - the probability of them paying after a text or after an email is not the probability of them paying after a text plus the probability of them paying after an email, since them paying after a text and them paying after an email are not mutually exclusive - they may pay after both a text and an email.
You need joint probabilities describing the probability of payment given multiple approaches. Unfortunately, there is no way to go from marginal univariate probabilities to the joint probabilities for arbitrary probability distributions. If both text and email are 50% effective individually, they together could have as little as 50% effectiveness (if they cover the same 50%), or as much as 100% (if they cover completely distinct halves). The person may respond to both or neither method in the first case, or one method but not the other in the second.
Without knowing more about what kind of "overlap" is involved in the joint probabilities, summing the individual probabilities and transforming them is meaningless. The formula mentioned in the comments is the correct way of accounting for non-exclusive events - rather than just summing the probability of paying after a text and the probability of paying after an email, you also need to subtract the "double counted" part, which is the probability of paying after a text and an email.
Comment: Thanks for your help


How to prove this using Fermat's Little Theorem?

Question: Suppose that $p$ and $q$ are distinct odd primes and $a$ is an integer such that $\text{gcd}(a,pq)=1$.
Prove that $a^{(p-1)(q-1)+1}\equiv a \pmod{pq}$.
Comment: Welcome to Math Stack Exchange.  Can you use the Chinese Remainder Theorem?
Comment: We are not taught that theorem yet, so I'd really appreciate if there is any other way to prove this. Thank you!
Comment: See my comment to my answer below
Answer: Use Fermat's Little Theorem to say $a^{p-1}\equiv1 \mod p$ and $a^{q-1}\equiv 1 \mod q.$
Therefore $a^{(p-1)(q-1)}\equiv 1 \mod p,q.$
Therefore $a^{(p-1)(q-1)}\equiv 1 \mod pq,$ using the Chinese Remainder Theorem.
Now multiply both sides by $a$.
Comment: If you don't want to invoke CRT, will you accept primes $p,q|x-1\implies pq|x-1$ ?
Comment: Okay, but then I cannot figure out how I can apply this rule to prove it...
Comment: which rule?  Fermat's little theorem?  that was used to prove $a^{p-1}\equiv1\mod p$ and same for $q$; then $x=a^{(p-1)(q-1)}\equiv1 \mod p,q$; the next line in my answer uses either CRT or the alternative in my comment
Comment: Ah okay, that was very helpful. Thank you so much!
Answer: Hint: $(p-1)(q-1)$ is the value of Euler's phi-function; then go from there.


Plotting binomial proportions on a box & whiskers plot using R

Question: Apologies in advance - I'm a bit of a newbie with R but I've been Google-ing this for weeks and I haven't found a straight answer.
The problem
Basically, I'm looking to plot proportions with their confidence intervals on a box and whiskers plot using the R environment.
i.e. Plot the results of binom.test(100,1000) and binom.test(125,1000)
What is the best package (I don't have a preference either way) and way to go about doing this?
Answer: This really does look to be more appropriate to an [r] tagged question in SO but there seems to be a surprisingly wide degree of tolerance for such questions in CV, so here goes. The answer also assumes you did not really want to use the existing boxplot() function which is what would be used to construct a true box-and-whiskers plot (and which doesn't really use binomial CI's, but rather uses the Tukey defined fivenum() function ). The plotrix and gplots packages both have what appears to be the same plotCI function;
est1 <- binom.test(100,1000) ; est2 <- binom.test(125,1000)
estvals <- rbind( c(est1$estimate, est1$conf.int[1], est1$conf.int[2]),
                  c(est2$estimate, est2$conf.int[1], est2$conf.int[2]))
plotCI(x = c(1,2), estvals[,1], ui=estvals[,3], li=estvals[,2],
         xlim=c(0.5,2.5), ylim=c(0, 0.15) , xaxt="n", xlab="Groups")

The basic function is the arrows() plotting function with an argument that splays the points of the arrows to 90 degrees in both directions.


Delete node: Remove header, footer and rightbar in delete node page

Question: I want to remove the header, footer and rightbar in a delete node page (node/.../delete). How can this be reached?
I already tried editing page--node--delete.tpl.php, but this does not work.
Answer: Please follow suggestion from this link for page https://www.drupal.org/docs/7/theming/template-theme-hook-suggestions
If you have created a page using views then you can call template for views like (page--viewname.tpl.php).
if you go with the content node, You need to call template like (page--node--nodeid.tpl.php)
Comment: Thanks for your answer. But I want to do this for all delete pages (node/.../delete) pages on my site, so no specific node id.
Comment: Ohh. Go to your theme directory and enter templates folder after create file name "page--node--delete.tpl.php" add your code to this file. It will call when you reached node/nid/delete
Comment: I tried page--node--delete.tpl.php, but this does not work
Comment: You can also find which template is calling for the active page!! Go on default folder edit setting.php and enable # $conf['theme_debug'] = TRUE; (remove #).

Now go to active page and open developer tools using F12 (window/ubuntu) and check HTML code.

You will find red comment link which define template file.


How to convert inorder(LDR) binary tree packed in an array back to binary tree in C+working with files

Question: Consider I already have a function called int* binToArrayInOrder(TreeRoot* tr) which creates a sorted array of tree values (because it's in order).
Is there anyway to construct back the tree from the in order given array, without other information such as the same tree representation in pre order array?
How can I write the array to a text file in C, please show me code.
Comment: I think that maybe there is an option to do so but I must mark somehow which cells of the array are leaves. But I'm not sure yet.
And I can do it by changing the data structure of treeNode to have a  boolean flag isLeaf
Answer: [1] You can reinsert the array elements into a binary tree again. Depending on the balancing algorithm, the tree may not look exactly like it did when you extracted them into the array, though.
[2] How about this?
void print_array (int *array, size_t sz, FILE *f) {
    if (!sz) return;
    fprintf(f, "%d\n", *array);
    print_array(array+1, sz-1, f);
}

From your comments, your actual question is how to save a binary tree to disk, and then restore it. This is a data structure serialization problem. For this problem, an in-order walk is probably not what you want. Instead, the serialization should reflect how the data structure is laid out. So, you need a record that describes a binary node:
struct binary_node_file_data {
    char data_[MAX_BINARY_NODE_DATA_SIZE];
    int parent_;
};

Now, you can perform a pre-order traversal of your binary tree to populate your nodes.
struct binary_node_fila_data *bfd = malloc(sizeof(*bfd)*nodeCount);
int count = 0;
populate_binary_node_file(tree, bfd, &count, -1);

void populate_binary_node_file(binary_tree_t *tree,
                               struct binary_node_file_data *bfd,
                               int *count,
                               int parent) {
    if (tree) {
        int me = *count;
        *count += 1;
        export_binary_node_data(tree, &bfd[me], parent);
        populate_binary_node_file(tree->left_subtree, bfd, count, me);
        populate_binary_node_file(tree->right_subtree, bfd, count, me);
    }
}

Here, I expect -1 to be treated like a NULL pointer. Then, dump the bfd to a file. I'll leave restoring the tree as an exercise. Reflecting on the problem a little more, it doesn't really matter if the traversal is pre-order or in-order (or post-order). The restoration step just needs to be able to allow all the children to find the parent so that they can populate the left and right pointers properly.
Comment: okay but do you see any option to get the same tree without having another array of pre order or post order as an additional input to the algorithm
Comment: @JavaSa: Why do you need the same tree?
Comment: Because consider I want to save the tree as is to a file, I'll convert it to an array of it's values and write it to a file.
Now I want to load it again, so it must be the same
Comment: @JavaSa: You could write the tree to the file, if that is what you really want. But re-building a new tree from the array is just as good in a semantic sense. Saving the tree would make restoring the tree faster, but at the cost of more information saved to disk.
Comment: @JavaSa: Thanks for accepting my answer, +1 on your question.
Answer: For the first question: no, an inorder list of nodes doesn't allow you to reconstruct the same tree.
For example, the tree
  3
 2
1

produces the inorder traversal 1 2 3
The tree
 2
1 3

also produces 1 2 3. Thus, you can't tell which tree was used to produce a given 1 2 3.
For the second question: I haven't used STL file I/O yet, sorry.


Snare drum tuning- "doofy" sound and 2 fundamentals, what causes this?

Question: For the last song I recorded, I tuned the snare very wet, since it sounded much drier on recording than in person.  I ended up getting a good sound, but when I went to mix the song, I found that the snare really had 2 fundamentals- one which dominated for rim shots at about 195Hz, and one which dominated for taps at about 170Hz.

Now, it turned out that I could use heavy eq to remove the "doofy" 170Hz tone, leaving only the higher fundamental and barely affecting the rim shot sound.  The end result was good, but how did this happen in the first place?
I also came across this sound in a professional track too- The snare in "Resister, Resist Her" sits around 200Hz, but there's a small tap section at 1:08 where the "doofy" sound comes through, and the fundamental is around 180Hz.  Very similar to what I experienced.
Comment: "Doofy" ... Is that a technical term? :-)
Comment: What FFT window size are you using for the spectrum graphs?  BTW "fundamental" may not be a meaningful term in the context of an inharmonic sound like this.
Comment: ...not just FFT size, but sample rate.
Answer: Drums respond very differently depending on where you hit them, how hard you hit them, what you hit them with, and so on.  They're very dynamic instruments in every sense of the word.  So I think the short answer is just that.  If the drummer does something different, the drum will sound different.
Why specifically is there a difference with your rimshots?  Well, I think the general consensus is that rimshots give you more attack and woody pop but less body.  So perhaps the "doofy" sound you're referring to is just the darker tone that you get with more body and less attack.  From the images, it appears the rimshot has a lot more midrange energy.  Beyond that, I can't give you a detailed breakdown of the physics involved.
I would be cautious about taking those snapshots from the frequency analyzer too seriously.

Are each of those pictures truly representative of all the strokes of that type?
The difference may have been exagerated by processing.  Are these frequency spectrums of the raw tracks or have these post EQ and/or compression?
The resolution in the low end is iffy and the bottom ends look almost identical except for the peaks.  Look at the down slopes on the left side.  Almost identical.
These 2 hits are clearly at very different dynamics so it's not really a fair comparision.  I can see there is WAY more energy in the rimshot -- at least 2dB across the board and as much as 5dB in the mids and low mids.  Cumulatively across the whole spectrum, that's a huge difference!  So it's hard to know without doing a controlled experiment how much of the difference in timbre is attributable to the different technique vs the dynamics.  In the commerical track you reference, the snare at 1:08 is being played more softly than the usual backbeats in the surrounding sections, so it's a similar situation.

Finally, gotta say, why would you EQ out that sound?  I didn't hear your "doofy" snare sound, but I like the "doofy" sound in the referenced track.  I wouldn't EQ that out in an effort to make non-rimshots sound like rimshots.  Generally, I wouldn't EQ out frequencies unless they're actually problematic.
Comment: It sounds like YOU yourself are the drummer, so I don't know what I'm going to tell you that will be news to you.  Technique will change timbre.  Dynamics will change timbre.  Tuning will change timbre.  Maybe your taps and rimshots are hitting different spots on the head.  On a snare head, a 1 inch difference can be huge.
Comment: 1) They are representative of... 80+% of strokes of that type.  2) I put one eq in broad strokes before the FFT.  Very wide bass boost and mid scoop.  No compression or other effects, this isn't the version I used in the actual mix.  3) I can upload some more spectra with no effects, different windowing, etc...  But that's getting off topic.  I don't have a problem with the way the FFT looks, I have a problem with the sound.  The FFT is just a visualization to help explain the problem.  4) Of course they're at different dynamics.  I'm comparing a tap to a rimshot.  ...
Comment: ... I suppose I can look back at the original recording later and see if I have any loud taps or soft rimshots in there, but yes I'm playing rimshots louder because I use rimshots for the backbeat and taps for the, well, taps.  I eq'ed out the sound because I didn't like it.  It wasn't an attempt to make the taps sound like rimshots, it was an attempt to make them sound more like the taps should sound, in my vision for the track.
Comment: Your direct answer to my question seems to be "I don't really know, it's different because you did something different." I use both taps and rimshots often...  Why doesn't this stark difference come up often?
Comment: The FFT is all I have to go on because I can't hear the actual sounds.  So I'm trying to gather additional information.
Comment: You seem dissatisfied with that answer.  What were you expecting, a detailed breakdown of the physics involved?  Try https://physics.stackexchange.com/
Answer: Snare wires too tight.
That seems to be the strongest contributor here.
My initial assumption is that it was most likely related to the relative tunings of the batter and resonant heads.  I did an experiment where I tried 9 or so different tunings on the same drum, recorded them, and analyzed them, but I could find no pattern.
Eventually, I realized that I get more consistency between taps and shots with loose snare wires. Tightening your snare wires too much chokes the resonance of the drum, this is pretty well known.  But it seems that this dampening effect can be non-constant with velocity.  So, it is possible to get a tuning where the fundamental can speak fairly loudly at low volumes, but gets choked at higher velocities (i.e. rim shots.)
You engineer your rim shots to sound good, but then the taps are super "doofy" by comparison.  You're stuck wondering why the taps are so doofy, when the problem is really that the rim shots are not doofy enough!
The tuning that gave me problems was a tom-like tuning with snares pulled too tight.  Wet, yes, but only for taps.


How do I know the old os level in AIX?

Question: I am stuck to find what was the older/previous version of my AIX OS?
To find the current OS version we use :-
<code>oslevel -s
</code>
what is the command to find the previous version from which it was upgraded?
Any help is appreciated.
I am stuck, could anybody tell some workaround, how to get the info of
previous TL/SP installed?
Answer: I don't believe there is any such command. There may be such information in the logs, but trolling through "alog -o -t boot" on one of our AIX machines, I don't see OS version info reported.
Comment: I am not a root user. If you could suggest something else, that would be better.
Comment: If you're not the root user, you're on the wrong site. Please read the FAQ - this site is for systems admins.
Comment: Pls suggest something meaningful so that the problem can be solved. I wrote it would be better. I can request the root to do the work but for that we should come up with solution.
Comment: Another option would be to review your inventory and/or change control documentation to see what work has been done to this server at what times.
Answer: I'm assuming your SysAd doesn't know what level their machine is at, and is thus not qualified to be it's SysAd, or doesn't know how to find out, and is probably not really qualified to do anything other than change tapes that don't actually back anything up. Otherwise, ask your SysAd this question.
If you have AIX 5 you can run 'oslevel -r' and it will give you the Base OS Level and Maintenance Release Level: 5.1.x.x, say.
Prior to AIX v5 the AIX command 'oslevel' returned the Base OS Level; that is, 4.1.5, or 4.3.3. You still don't know what Maintenance Levels---if any---have been applied.
EDIT: AIX 4.3.2, and some MLs of 433, have the '-r' command. There IS a caveat: it has the same reporting behaviour that the AIX 6 mechanism has---it reports the LOWEST complete fileset level. So if you Migrate from AIX 421 to 433, you get '433' for 'oslevel' and '432-04' for 'oslevel -r'. The "work around" is to use the "Replace Same or Newer Versions?" 'yes' option when migrating (bad idea), or when updating (usually safe). I'm still not sure '-r' will give you the right answer, though, so it's always better to check your 'bos.rte' files and make sure they're at the last level for an "old" release.
What you CAN do in the absence of a useful single command is use 'lslpp -l' on 'bos.rte.*' (or a key fileset, like 'bos.rte.archive', 'bos.rte.boot', 'bos.rte.bosinst' or 'bos.rte.commands'). This will give you the fix level for these filesets, and then you can try and back-track to the filesets list for each Maintenance Level and figure out where you're at. Yep, that is as arduous as it sounds. As has been pointed out, albeit rudely, is that you will need to be root.
The other, slightly riskier, but MUCH easier option is to get a hold of the 4.3.3 Maintenance Level Packages (at least 4330 -> 43310 and 43310postml11). Try and apply the 4330-43310 ML and see  what happens. If it yells at you for trying to re-do the same levels, you know where you are; if it doesn't, it'll run and you'll know where you are. Same with the 43310post fix package. Trick here, of course, is you have to be a Privileged User (really, root). So you're kinda stuck with 'oslevel -f' to force a clean report to Base Maintenance Level.
Hope this helps you some. If you can find the AIX 5 'oslevel' command that supports the '-r' option and copy it to your 433 machine, it might run. Maybe.

How do I know the old os level in AIX?


Authentication error sending messages to Windows Service Bus 1.0 on AWS

Question: I am trying to send and receive messages from a local workgroup machine (Windows 7), call it the 'client', to Service Bus 1.0 set up on a workgroup server (hosted on AWS EC2). After many trials and research I'm unable to send messages from the client machine to the server. I've followed a number of articles that appear to indicate that it is possible to do, but I cannot resolve the authentication issue I'm seeing.
Connecting to Windows Server Service Bus on AWS
Microsoft Service Bus on a Windows Workgroup
I note the Microsoft system requirements appears to indicate that it is "not supported" and "not possible". My question is can this be done, and has anyone had success? Any help would be greatly appreciated.
msdn.microsoft.com/en-us/library/windowsazure/jj193011(v=azure.10).aspx
My attempts include using either the WindowsTokenProvider and OAuthTokenProvider. I get the same result:
System.UnauthorizedAccessException: The token provider was unable to provide a security token while accessing 'https://xx.xx.xx.xx:9355/ServiceBusDefaultNamespace/$STS/Windows/'. Token provider returned message: ''. ---> System.IdentityModel.Tokens.SecurityTokenException: The token provider was unable to provide a security token while accessing 'https://xx.xx.xx.xx:9355/ServiceBusDefaultNamespace/$STS/Windows/'. Token provider returned message: ''. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
The Service Bus namespace is set up with AddressingScheme "Path" for a workgroup install. And the client side connection string includes the IP to reach the server, and I've set a RemoteCertificateValidationCallback before creating the queues.
Endpoint=sb://xx.xx.xx.xx/ServiceBusDefaultNamespace;StsEndpoint=https://xx.xx.xx.xx:9355/ServiceBusDefaultNamespace;RuntimePort=9354;ManagementPort=9355;WindowsUsername=SBUser;WindowsDomain=[NotUsed];WindowsPassword=[Password]

Code to attach to the remote queue and send a message is as follows:
ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]); // Gets the connection string above
TokenProvider tokenProvider = WindowsTokenProvider.CreateWindowsTokenProvider(connBuilder.StsEndpoints, new NetworkCredential(connBuilder.WindowsCredentialUsername, connBuilder.WindowsCredentialPassword));
MessagingFactorySettings messagingFactorySettings = new MessagingFactorySettings();
messagingFactorySettings.TokenProvider = tokenProvider;
MessagingFactory messagingFactory = MessagingFactory.Create(connBuilder.GetAbsoluteRuntimeEndpoints(), messagingFactorySettings);
requestQueue = messagingFactory.CreateQueueClient("RequestQueue");
...
requestQueue.Send(sendMessage);  // Fails here

The server account is SBUser with a password and I have left the domain/host specified blank on the token provider. I note that the Event Viewer on the server shows the authentication being attempted is the client's user account not the one from the token provider. Why is this? I'm obviously missing something in order to authenticate on the server.
An account failed to log on.

Subject:
  Security ID: NULL SID
  Account Name: -
  Account Domain: -
  Logon ID: 0x0

Logon Type: 3

Account For Which Logon Failed:
  Security ID: NULL SID
  Account Name: [ClientLogin]
  Account Domain: [ClientMahcine]

Failure Information:
  Failure Reason: Unknown user name or bad password.
  Status: 0xc000006d
  Sub Status: 0xc0000064

Appreciate any help. Thanks.
Answer: Try with the OAuthTokenProvider and make sure that connBuilder is passing the right values.
TokenProvider tokenProvider = TokenProvider.CreateOAuthTokenProvider (connBuilder.StsEndpoints, new NetworkCredential(connBuilder.WindowsCredentialUsername, connBuilder.WindowsCredentialPassword));
Once you try this, please, reply with the exception you get in your client.  Also, in the server, search for a event in the Service Bus section that would give more details about the exception.
With that information we should continue to the next step.
Comment: I've retested with OAuthTokenProvider and verified the correct credential is passed (SBUser plus password).
This initially gives me the error: X.509 certificate CN=AMAZONA-PQxxxxx is not in the trusted people store.
I am able to resolve by exporting the certificates and importing onto the client.
Now it gives this error:
MessagingCommunicationException: Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was '126.96.36.199' but the remote endpoint provided DNS claim 'AMAZONA-PQxxxxx'.
Comment: I'm using the same connection string as per initial post.
There is nothing in Service Bus event logs on the server.. Is this the right location?  Event Viewer->Applications and Services Logs->Microsoft->ServiceBus->CASSink and Client.
Answer: Did you get to the bottom of this?
I have managed to get around the exact same issue by setting the Fully Qualified domain name of the server that the certificate is bound to in the client machine hosts file.
So where you have entered the IP address in the connection string, you should instead enter 'AMAZONA-PQxxxxx'. And in your hosts file, have the 'AMAZONA-PQxxxxx' resolve to the IP address.
Comment: I never managed to resolve this. I've since switched to running across computers on a domain instead and this works fine, and is sufficient for my needs.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment).
Comment: If you have a new question, please ask it by clicking the [Ask Question](http://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context.
Answer: we had the same issues. Server W2k12R2, standalone, Workgroup; Client Windows 7, same Workgroup.
It's necessary to have the same user accounts on both systems. Looks like this is some kind of "authentication proxy stuff" running.
Take a look at the compatibility matrix mentioned above:
http://msdn.microsoft.com/en-us/library/windowsazure/jj193011(v=azure.10).aspx
Thank you,
Holger


How does the NFL decide which teams play in London?

Question: How does the NFL decide which teams play in London every season?  Do any teams actually volunteer to play in London, considering the jet lag and also the fact that you might have to give up a home game?  Does the NFL provide any sort of compensation to the teams that play in London?
Answer: Yes, teams agree to play in the games, presumably for a significant portion of the proceeds (though that, as with most things in the NFL, isn't made public).  The reasons vary; for example, teams with small home stadiums and/or difficulty selling out seats will likely make a profit, as Wembley Stadium is reasonably large and typically sells over 80,000 seats per game, buying relatively expensive tickets ($150-$200 depending on the exchange rate, which is on par for a large-market team and more than smaller market teams will typically get).  That's why teams like Jacksonville and Tampa Bay agree to do this, as they have relatively light attendance and can't charge as much for tickets.  Presumably you also have higher jersey sales around the game in the UK; a lot of folks I know in the UK became Bucs fans after the first few games there.  See the wikipedia page for more information and links to other sources.
As far as the downsides, the jet lag isn't all that bad; 6 hours from the east coast to London versus 3 hours to Seattle, and the other team has it just as bad or worse.  You also get a slightly favorable schedule around that game (no Sunday-Thursday or Monday-Sunday, and they often coincide with bye weeks afterwards).


Using one function to update an object value used by another function using jquery?

Question: I am writing a quiz app that references an object with values, everything is working well, even though this is beginner code.  Specifically, I want the first question to be replaced by the second question when the user clicks the "next question" button.  But while my nextQuestion() is increasing the variable in the object, it's not changing in the rest of the code.

var quiz = { //the questions, you get the idea//
  correctCount: 0,
  currentQuestion: 0, //THIS IS WHAT I WANT TO UPDATE IN EACH ITERATION
  questions: [{
    question: "Question 1?",
    answers: ["A", "B", "C", "D"],
    correct: "A"
  }, {
    question: "Question 2?",
    answers: ["A", "B", "C", "D"],
    correct: "C"
  }]
};

$(document).ready(function() {
  $(".question").hide();

  //jquery event delegation
  function generateQuestion() {
    $("div.question").prepend(quiz.questions[quiz.currentQuestion].question);
    var answerList = quiz.questions[quiz.currentQuestion].answers;
    console.log(answerList);
    for (var i = 0; i < answerList.length; i++) {
      $("ul").append("
" + answerList[i] + "
");
    }
    console.log(quiz.currentQuestion);
  }

  function questionCheck() {
    $(".question-space").on('click', 'li', function(e) { //
      e.preventDefault();
      console.log($(this).val());
      if ($(this).text() === quiz.questions[quiz.currentQuestion].correct) {
        alert("Yes! The correct answer was " + quiz.questions[quiz.currentQuestion].correct + "!");
        quiz.correctCount += 1;
        $(".numCorrect").text(quiz.correctCount);
      } else {
        alert("Sorry! The correct answer was " + quiz.questions[quiz.currentQuestion].correct + "!");
      }
    });
  }

  function nextQuestion() {
    $(".next-question").on('click', function(e) {
      e.preventDefault();
      quiz.currentQuestion += 1;
      console.log(quiz.currentQuestion);
    });
  }

  //Event listeners
  $(".start-quiz").click((function() {
    $(".box").hide();
    $("div.question").show();
    generateQuestion();
    questionCheck();
    nextQuestion();
  }));

});
Comment: You're missing the `]` at the end of the `questions:` array, and the `}` at the end of the `quiz` object.
Comment: What is `quiz.questions[ * * quiz.currentQuestion * * ]` supposed to mean? You can't use `*` like that.
Comment: If that was supposed to be code highlighting, you can't do markup inside code blocks on SO.
Comment: I've updated the syntax, thanks for taking a look.
Comment: Can you add the HTML to the snippet so we can try it out?
Comment: https://gist.github.com/anonymous/43b0c634ccef271f5b4696a22b46a2f8
Comment: just put a gist in case you wanted to play with the HTML, sorry this was my first SO question so still learning the best way to post code.
Answer: Ok. I was able to solve it after realizing I wasn't rendering anything in the function:
function nextQuestion() {
  $(".next-question").on('click', function(e) {
    e.preventDefault();
    quiz.currentQuestion += 1;
    console.log(quiz.currentQuestion);
    $("div.question").empty();
    generateQuestion();
    questionCheck();
  });
}

I needed to change some of my jquery in the generate question function because of the empty() method taking out ALL of the descendants, but this at least got the functionality working.


Qual é a necessidade dessa variável nesse laço?

Question: Eu fiz um simples programa em Python que renomeia com um número aleatório todos os arquivos da pasta em que o arquivo do programa está. Após algumas tentativas e erros, eu percebi em alguns exemplos da internet que no laço que fazia a "leitura" dos arquivos tinha uma variável a mais do que o laço que eu tinha pensado. Alguém pode me dizer a utilidade dele?
Nesse caso aqui está com a variável x
import os, random
dirs = os.listdir(".")

for x, file in enumerate(dirs):
    src = file
    newName = str(random.randint(1, 1000000))
    os.rename(src, newName)

Porém quando eu retiro essa variável...
import os, random
dirs = os.listdir(".")

for file in enumerate(dirs):
    src = file
    newName = str(random.randint(1, 1000000))
    os.rename(src, newName)

... dá o seguinte erro:
TypeError: rename: src should be string, bytes or os.PathLike, not tuple

Answer: O método enumerate retorna um objeto iterável.
Quando você faz o enumerate de uma lista, ao percorrer essa lista você acessa tuplas com 2 elementos.
No seu segundo código, a variável de loop file é algo do formato (index, file_name), e como o método rename recebe uma string como primeiro parâmetro, o erro ocorre, pois você está passando um objeto tipo tupla e não tipo string.
No primeiro código, ao fazer a decomposição
for x, file in enumerate(dirs)

A primeira variável x recebe o primeiro elemento da tupla ( index ) e a variável file recebe o segundo elemento ( file_name ) da tupla gerada pelo método enumerate.
Como em nenhum momento você utiliza a variável x, não é necessário o método enumerate, o método os.listdir já retorna uma lista iterável.
import os, random
dirs = os.listdir(".")

for file in dirs:
    src = file
    newName = str(random.randint(1, 1000000))
    os.rename(src, newName)


Newest 5 per group with fulltext search

Question: I have some table more than 300,000 records, the table structure:
id  |  title | source | description | date | fullindex

id is PRIMARY key, date has added index, source has added index, fullindex has added full-text index.
Now I want to make a query. newest 5 per group with fulltext search.
I have tried
SELECT 'a' as t_name,id,title,source,description,date,fullindex
FROM table1 a1
WHERE MATCH (fullindex) AGAINST ('+bool' IN BOOLEAN MODE)
and 6>(select count(*) from table1 where source=a1.source and date>a1.date)

but this query would cost 6.5987s, the affection is very low.
So how to make a quicker query?
PS: I have searched mysql greatest n per group in google, but with my limited skill, I did not make a better code for myself, waiting some mysql master for a help.
Comment: You can go this similar question. http://stackoverflow.com/questions/16560770/sql-select-top-5-every-month/16561220#16561220   Post if you have any doubts in it.
Comment: @Meherzad, so where to add `MATCH (fullindex) AGAINST ('+bool' IN BOOLEAN MODE)`?
Comment: Add within the inner query that gives records to the `from` part of the outer query.
Comment: @Meherzad, 17.2221s, such a slowly query.
Comment: @Meherzad, `SELECT 'a' as t_name,id,title,source,description,date,fullindex from
(select
@rn:=if(@prv=source, @rn+1, 1) as rid,
@prv:=source as source,
 'a' as t_name,id,title,description,date,fullindex
from it_nt1
join
(select @prv:=0, @rn:=0)tmp
order by
source, date desc) a
where rid<=5 and MATCH (fullindex) AGAINST ('+bool' IN BOOLEAN MODE)` is my code right?
Comment: Check my answer add the full text search in the inner part.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30017/discussion-between-fish-man-and-meherzad)
Answer: Try this query
SELECT * from
(SELECT @rn:=if(@pv=source, @rn+1, 1) as rId,
'a' t_name,id,title,@pv:=source,description,date,fullindex
FROM table1 a1
JOIN (SELECT @pv:=0, @rId:=0)tmp
WHERE MATCH (fullindex) AGAINST ('+bool' IN BOOLEAN MODE)
ORDER BY source, date)a
WHERE a.rId <=5;

Add compound index on (source, date)
Hope this helps..
Comment: `ALTER TABLE `table1` ADD INDEX `index1` (`date`, `source`);` run your code, why each source still output more than 5 results? checked, some are 10.

Newest 5 per group with fulltext search


What is the reason for the error message "Library not loaded: libmysqlclient.18.dylib"?

Question: I have no experience working with Perl, and I'm trying to run the geo_to_mysql.pl program for a project I'm working on. I made no modifications to the program other than the database, username, password and file directory path in the first few lines.
When running the program, I keep getting this error:

install_driver(mysql) failed: Can't load '/Library/Perl/5.10.0/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle' for module DBD::mysql: dlopen(/Library/Perl/5.10.0/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle, 1): Library not loaded: libmysqlclient.18.dylib
Referenced from: /Library/Perl/5.10.0/darwin-thread-multi-2level/auto/DBD/mysql/mysql.bundle
Reason: image not found at /System/Library/Perl/5.10.0/darwin-thread-multi-2level/DynaLoader.pm line 207.
at (eval 7) line 3
Compilation failed in require at (eval 7) line 3.
Perhaps a required shared library or dll isn't installed where expected

I've made sure that I installed the DBD required for MySQL from CPAN, so I don't think that's the issue. Can anyone shed some light on this issue?
Comment: Perl's DBI (database interface) module requires a DBD (database driver) for each database type you're connecting to. Looks like you're missing the DBD for MySQL. It should be easily installable from CPAN, or available as a pre-built package for your system somewhere.
Comment: I installed the DBD::mysql from CPAN, but I'm still getting the exact same error message...any thoughts? Thanks again :)
Comment: Did you compile DBD::mysql? Run the tests?
Comment: How did you install mysql? How do you call the script?
Answer: It sure sounds like you might want to read this blog post:
http://probably.co.uk/problems-installing-dbdmysql-on-os-x-snow-leopard.html
The issue seems to be that the mysqlclient dynamic library doesn't have path information in it.  You need to manaully fix this (as the post above notes).
One of the cheaper solutions is to symlink or copy the libmysqlclient library to /usr/lib.
Hope this helps anyone looking for this question in the future.
Comment: Worked for me when attempting to install DBD::mysql on OSX Yosemite. I created a symlink to the dylib in /usr/lib and all was well: `sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib`
Comment: I encountered exactly the same problem. Copying libmysqlclient to /usr/lib and reinstalling DBD::mysql did the trick.
Comment: Also, make sure your using the right mysql arch with your perl.  I'm using 32bit perl.  mysql x86_64 won't work with that, I think.
Answer: The DBD::mysql module needs access to the MySQL client libraries in order to work. I'm surprised that DBD::mysql even installed without them being on your system. How did you install the DBD::mysql module?
Comment: I followed these instructions: http://cpansearch.perl.org/src/CAPTTOFU/DBD-mysql-4.019/INSTALL.html
Comment: Like i said, i pretty much have no idea what I'm doing here... I've already installed MySQL and these other relevant software though, following instructions listed on the respective websites. Any ideas are much appreciated!


Negative binomial pairwise comparison in R

Question: I have fitted a negative binomial regression model to my data, and the summary of this compares latency of 3 resources to that of burrows:
NegativeBinomalLatencyModel <- glm.nb(Latency_s ~ Resource, data = Cricket)

summary(NegativeBinomalLatencyModel)
Coefficients:
           Estimate Std. Error z value Pr(>|z|)
(Intercept)      4.9416     0.3055  16.178   <2e-16 ***
ResourceFemale   0.3292     0.4895   0.672    0.501
ResourceFood     0.1878     0.4228   0.444    0.657
ResourceNone    -0.2179     0.4231  -0.515    0.606

I was wondering how to produce a pairwise comparison of this, comparing each resource to all the other resources.
Answer: You could do it using the emmeans package.
Then simply do:
m_means <- emmeans(NegativeBinomalLatencyModel, ~ Resource)
#TO GET PAIRWISE COMPARISONS WITH DIFFERENCES INDICATED AS LETTERS
cld(m_means, Letters = letters)

The emmeans package has a very good documentation (see link above).
Edit to address OPs comments:
If you want to plot the data, you can do it simply via the emmip() function (from the emmeans package). Have look at ?emmip for details. Using your specific example a basic plot could be generated like this:
#BASIC PLOT
emmip(m_means, ~ Resource)
#BASIC PLOT WITH CONFIDENCE LIMITS
emmip(m_means, ~ Resource, CIs=T)
#BASIC PLOT WITH CONFIDENCE LIMITS ON THE RESPONSE SCALE
emmip(m_means, ~ Resource, CIs=T, type="response")

Another way of plotting can be achieved by simply using the plot() function. For that have a look at ?plot.emmGrid.
If you want more control, you can store the output of cld() in an object such as this:
m_means_table <- cld(m_means, Letters = letters)

This can then be used in ggplot2 for example:
require(ggplot2)
ggplot(m_means_table, aes(x=Resource, y=emmean)) + geom_point() +
       geom_errorbar(aes(ymin=emmean-SE, ymax=emmean+SE))

If you want upper and lower confidence limits, you can simply replace emmean-SE with asymp.LCL and emmean+SE with asymp.UCL, respectively (from the m_means_table object).
Also have a look at my answer on poisson and glm.nb models here:
poisson glm to observe whether effects of artificial light on the number of bat passes in each location were significant
Comment: @Harry I added some more detail. Have a look and see if this answers you questions.
Comment: that's exactly what I needed. Thank you very much for your help.
Comment: Thanks, I'm having some trouble interpreting the output. It looks like this

 Resource   emmean        SE  df asymp.LCL asymp.UCL .group
4     None 4.723694 0.2927040 Inf  4.150004  5.297383      a
1   Burrow 4.941642 0.3054607 Inf  4.342951  5.540334      a
3     Food 5.129405 0.2922820 Inf  4.556543  5.702268      a
2   Female 5.270799 0.3825413 Inf  4.521032  6.020567      a

Is there a way to plot this?
Comment: cld() doesn't appear to be part of emmeans any more, it was deprecated. They suggest using pwpp() or pwpm()


SAVED QUERIES ARE HIDDEN

Question: My SAVED QUERIES section is hidden somewhere on bigquery that I could not find it. Still be able to save new queries but I could not find them afterwards. Do you guys know how to fix it? Thanks a lot!!! enter image description here
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: I've got this message in the UI:

We've moved all saved queries (personal, project, and public) into the
Explorer for easier access. Expand projects to access saved queries.
Comment: I don't see it in the Explorer too :( do you know how to expand projects to access saved queries?
Comment: ahhhhhhh I found it! Thanks a lot!!!!!! :D :D :D

SAVED QUERIES ARE HIDDEN