$\sin^2$ notation and uses of the alternative.

Question: So I was taking my calculus class and I was shocked by the following:
Apparently its a convention for
$\sin^2(\alpha)=(\sin(\alpha))^2$
As opposed to what I thought made more sense which was
$\sin^2(\alpha)=\sin^2(\alpha)=\sin(\sin(\alpha)))$.
This made more sense to me because for two reasons.
reason 1 : $\sin^{-1}(\alpha)\neq(\sin(\alpha))^{-1}$
in other words it denotes the inverse function of sine, not the multiplicative inverse of sine of a number.
reason 2:
writing $(\sin(\alpha))^n$ is a lot faster than writing $\underbrace{\sin(\sin(\dots(\sin(}_{n\text{ of these}}\alpha\underbrace{))\dots))}_{n\text{ of these}}$
So I guess that the justification for this is that the composition of the sine function is not very useful.
My question is, are there any interesting things that actually do use composition of trigonometric functions? is there an agreed upon definition for the composition of trigonometric functions?
Regards.
Comment: The convention is correct, what you thought made more sense, is actually wrong. Taking the sine of a sine is not sin²   I guess better get used to it....
Answer: Please feel free to write (if you wish) $(\sin x)^2$ and $\arcsin x$ to avoid this confusion.  But learn to recognize the standard notations $\sin^2 x$ and $\sin^{-1} x$ for them, when others use these.
You are correct that $\sin(\sin(x))$ is not often seen (because it is not often useful).  Do not write $\sin^2 x$ for it, unless you are writing a specialized paper, and include this convention at the beginning.  Also do not write $\sin^{(2)} x$ for it, as that usually means
$$
\frac{d^2}{dx^2} \sin x .
$$
Notations you can use for $(\sin \circ \;\sin)\, x$ are $\sin^{[2]} x$ and $\sin^{{\displaystyle \circ} 2} x$.  But even then, it would be best to include the explanation.
Comment: Very few.  One that I do know (for kiddies with a new calculator):  Start with any numbe and repeatedly press the "cos" button; what do you get? (Be sure you are in radian mode.)  Now explain why this works...
Comment: @Omnitic: In the field of analytic number theory one often encounters the logarithm function iterated 2, 3, and 4 times, and I've sometimes seen the notation $(\log \circ \log) = {\log}_{2},\;$ $(\log \circ \log \circ \log) = {\log}_{3},\;$ $(\log \circ \log \circ \log \circ \log) = {\log}_{4},\;$ etc.$\;$ Thus, $\;{\sin}_{n}$ seems like a natural and easy-to-use notation for the $n$'th iterate of the sine function. Of course, if you use this, you'd want to define it--don't assume the reader will know the notation.
Comment: @Omnitic: In this [31 December 2007](http://mathforum.org/kb/message.jspa?messageID=6049132) sci.math post, and this [11 October 2008](http://mathforum.org/kb/message.jspa?messageID=6456600) sci.math post, iterated sine's appear. It is not really an application, however, but instead it is a puzzle-math type problem that I suspect someone just made up (rather than something that arose from a legitimate mathematical investigation).
Comment: do you know of any uses for composition of trigonometric functions?
Answer: $\sin^2 x=(\sin x)^2=(\sin x)(\sin x)$ and that is not equal to $\sin(\sin x))$
Similarly: $(\sin x)^{-1}=\frac{1}{\sin x }$ but $\sin^{-1}x=\arcsin x$ Lastly, $\sin(x^2)=\sin(x*x)$.
Comment: This does not actually answer the question. The OP is aware (though surprised by) the convention.
Comment: Yes, that may be true, but he was...shocked! And so I got shocked as well. I just thought to clear it out to be on the safe side.
Answer: Conventions are what somebody decided they'd be.
For a parallel, consider that mathmeticians say i = sqrt(-1) while electrical engineers say j = sqrt(-1).  For EE's, i was already in use for current.
Note, however, that in naming unit vectors, i parallels the x axis, j parallels y, etc.  And since the complex plane LOOKS like an x-y coordinate system, it would seem more logical that sqrt(-1) be called j.
Just learn to live with it.  All the rest of did.
Comment: It's also a convention to call the unit vector parallel to the $x$-axis $i$, etc., so I'm not sure how much more logical it is to use $j$ for the imaginary unit, especially when there is an 'i' in 'imaginary'.  Although, I agree with the point overall ... it is something we just have to get used to.


Accessing filename through a form

Question: I'm trying to get the filename of an uploaded file through a form. params returns data like so:
(byebug) pp params
{"enable_test"=>"1",
 "tokens_per_day"=>"0",
 "unlimited_tokens"=>"0",
 "test_scripts_attributes"=>
  {"0"=>
    {"seq_num"=>"1.0",
     "script_name"=>
      #<ActionDispatch::Http::UploadedFile:0x00000007b370c0
       @content_type="application/pdf",
       @headers=
        "Content-Disposition: form-data; name=\"assignment[test_scripts_attributes][0][script_name]\"; filename=\"ass5import.pdf\"\r\nContent-Type: application/pdf\r\n",
       @original_filename="ass5import.pdf",
       @tempfile=#<File:/tmp/RackMultipart20151115-5586-patihn.pdf>>,
     "description"=>"",
     "max_marks"=>"2",
     "run_on_submission"=>"0",
     "run_on_request"=>"0",
     "halts_testing"=>"0",
     "display_description"=>"display_after_submission",
     "display_run_status"=>"display_after_submission",
     "display_marks_earned"=>"display_after_submission",
     "display_input"=>"display_after_submission",
     "display_expected_output"=>"display_after_submission",
     "display_actual_output"=>"display_after_submission"}}}
{"enable_test"=>"1", "tokens_per_day"=>"0", "unlimited_tokens"=>"0", "test_scripts_attributes"=>{"0"=>{"seq_num"=>"1.0", "script_name"=>#<ActionDispatch::Http::UploadedFile:0x00000007b370c0 @tempfile=#<Tempfile:/tmp/RackMultipart20151115-5586-patihn.pdf>, @original_filename="ass5import.pdf", @content_type="application/pdf", @headers="Content-Disposition: form-data; name=\"assignment[test_scripts_attributes][0][script_name]\"; filename=\"ass5import.pdf\"\r\nContent-Type: application/pdf\r\n">, "description"=>"", "max_marks"=>"2", "run_on_submission"=>"0", "run_on_request"=>"0", "halts_testing"=>"0", "display_description"=>"display_after_submission", "display_run_status"=>"display_after_submission", "display_marks_earned"=>"display_after_submission", "display_input"=>"display_after_submission", "display_expected_output"=>"display_after_submission", "display_actual_output"=>"display_after_submission"}}}

Right now, the code im trying to fix is storing script_name as the filename, which is wrong/ I'd like to store the filename instead. How can I access the @headers filename?
The code im trying to modify previously accessed it like so, but it seems like this is out dated and no longer works (code is from RoR 3.0)
# Filter out test support files that need to be created and updated
    unless testsupporters.nil?
      testsupporters.each_key do |key|
        tfile = testsupporters[key]

        # Check to see if this is an update or a new file:
        # - If 'id' exists, this is an update
        # - If 'id' does not exist, this is a new test file
        tf_id = tfile['id']

        # If only the 'id' exists in the hash, other attributes were not updated
        # so we skip this entry. Otherwise, this test file possibly requires an
        # update
        if !tf_id.nil? && tfile.size > 1

          # Find existing test file to update
          @existing_testsupport = TestSupportFile.find_by_id(tf_id)
          if @existing_testsupport
            # Store test file for any possible updating
            updated_support_files[key] = tfile
          end
        end

        # Test file needs to be created since record doesn't exist yet
        if tf_id.nil? && tfile['file_name']
          updated_support_files[key] = tfile
        end
      end
    end

Answer: The code you posted doesn't reference params anywhere, and there's no way to know what kind of object techsupporters is. So I can't tell you exactly how to modify your code.
But from the params you posted, I believe that what you want is params['test_scripts_attributes']['0']['script_name'].original_filename.
In the end, the method you're looking for is ActionDispatch::Http::UploadedFile#original_filename.
From the looks of it, the params could contain anything from zero to multiple files. So be sure to account for that.

Accessing filename through a form


Setting field2=field1 in MongoDB

Question: I am unable to update my document when I run
db.xx.updateOne({_id: ObjectId(""}, {$set: {lq: uq}) I get the error uncaught exception: ReferenceError: uq is not defined
uq field exists and contains integers, not sure why it don't work. Please help.
Answer: db.collection.update({
  "_id": ObjectId("5a934e000102030405000000")
},
[
  {
    "$set": {
      "field1": "$field2"
    }
  }
])

mongoplayground
Comment: It didn't work. It set the value for 'lq' to '$uq' not actual uq value
Comment: you need `[` & `]`

Setting field2=field1 in MongoDB


Create an array from MySQL query, average the values of that array, then round that average up

Question: Ok.  Here is the code I have so far...
mysql_query($userrating);
$userratingquery =  "SELECT rating FROM user_rating WHERE user_id=$sellerid";
$userrating = mysql_query($userratingquery) or die('SQL Error :: '.mysql_error());
$userrating = array();

while(($row =  mysql_fetch_assoc($userrating))) {
   $rating[] = $row['rating'];
}

if (!empty($userrating)) {
   $averagerating = array_sum($userratingary);
   print_r($userratingary);
} else {
   echo '';
}

What I'm trying to do is create an array of the database values called "rating", average the values in that array, then I want to round those values up.  So, for instance, if the average of those values ends up being 3.7, then the average will then become 4.
From there I can apply the results to the code... I'm just having a lot of trouble with my array right now.  The error I'm getting right now is...

Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL
  result resource in

Can someone point me in the right direction?
Answer: Your problem is here:
$userrating = mysql_query($userratingquery) or die('SQL Error :: '.mysql_error());
$userrating = array();

You are resetting the $userrating variable to an array so when you try to fetch a mysql row the $userrating mysql result is no longer valid.
Use a different variable name for your $userrating array or else another one for your mysql result.
Comment: You were right.  Thanks.  I also realized that in the while loop I didn't have the array variable set to the same variable I had designated in the first place.  That's also why the array wasn't being created.


Different layout for just one certain page in Rails

Question: I want to have a different layout for just one certain action in my Rails app. How do I do that?
Comment: http://guides.rubyonrails.org/layouts_and_rendering.html
Comment: Possible duplicate of [rails 3, how add a view that does not use same layout as rest of app?](http://stackoverflow.com/questions/5090084/rails-3-how-add-a-view-that-does-not-use-same-layout-as-rest-of-app)
Answer: <code># controller that calls the page
def action
  render :layout => 'other'
end
</code>
Comment: So in my case, my "def action" is "def homepage" AKA the index. I made a layout.css.scss file and placed it in my stylesheets folder and added in your render line with 'other' being 'layout' and my application crashed. I'm confused as to what I'm doing wrong. My new layout file is the same as my original layout file.
Comment: Hard to say without checking the code, open a new question and I can have a look
Answer: <code>class MyController < ApplicationController
  layout "special", :only => :action

  def action
    #action code
  end
end
</code>
Comment: I haven't tried, but what about put another line on top for default? something like `layout 'normal' # :except => :action`
Comment: @ecologic, that won't work (in rails 3.0.X anyway).  You can only have global one layout declaration per controller
Comment: Hmm. Actually, that makes all my other actions for that controller have NO layout. Any way to bring those back?
Answer: <code> layout :resolve_layout

  .
  .
  .
     private
      def resolve_layout
       case action_name
         when "new"
          "alternate"
         else
          "application"
         end
      end
</code>


C# How to read commit time with libgit2Sharp

Question: I am trying to list all commits in repository, their Authors and date of commit using libgit2Sharp, but the commit object doesn't have property of date/time where the commit was created.
 using (var repo = new Repository(path))
 {
     ///get commits from all branches, not just master
     var commits = repo.Commits.QueryBy(new CommitFilter { Since = repo.Refs });

     //here I can access commit's author, but not time
     commits.Select(com => new { Author = com.Author.Name, Date = com.???
  }

I didn't find any documentation of the libgit2sharp project, on the official page it says:

Let's put it simply: we currently lack proper documentation. Any help on this subject would be greatly appreciated ;-)

How can I access commit's time?
Answer: The date a commit was authored or committed is part of the Signature, along side the name and email address.  The When member of the signature is a DateTimeOffset it was authored or committed.  If you're looking for the authorship date in your example, then you want:
com.Author.When


Is there an intuitive way to understand a sequential Monte Carlo Markov Chain?

Question: I was wondering if there was an intuitive way to understand what a sequential Monte Carlo Markov Chain is. It also goes by the name of particle filtering. Is there an intuitive way to think about it/teach it to someone? Thanks!
Comment: Can you be more precise? For instance point out the entries you have read so far and explain why it is not sufficiently intuitive. I acknowledge the Wikipedia page is too advanced for most readers, but Nando de Freitas has [Matlab codes](http://www.cs.ubc.ca/~nando/smc/) on line that could help you. And the [on-line course of Arnaud Doucet for the MLSS 2012](http://yosinski.com/mlss12/MLSS-2012-Doucet-Sequential-Monte-Carlo-Methods/) is quite accessible.
Comment: Did you perhaps mean 'sequential Monte Carlo' rather than 'sequential Monte Carlo Markov Chain'? Otherwise, do you have a reference for the term 'sequential Monte Carlo Markov Chain'?
Answer: The term is "Markov Chain Monte Carlo" and it is a technique used for approximating expectations/integrals involving probability distributions that are difficult to sample from.
Monte Carlo methods require sampling to approximate expectations.  The Markov Chain is the tool used to sample.  In particular this method is used when one has access to a non normalized probability mass/density function.
A Markov Chain is a probabilistic model for movement on a graph.  I will let you look up the details.  Consider a random walk on a Markov Chain with states $X_0, X_1, \dots$.  Suppose we start the walk at state $s$.  Now consider:
$$
P(X_n = t | X_0 = s).
$$
When $n$ is small this depends greatly on the starting state, but as $n$ goes to infinity (under reasonable Markov Chain assumptions that I'll let you look up) this converges to a distribution that does not depend on $s$.
In MCMC we construct a Markov Chain whose stationary distribution is the distribution we're trying to sample from.  Then a sufficiently long random walk on that Markov Chain closely resembles drawing samples from that distribution.  The construction of this Markov Chain is too involved for this post, but you can look up Metropolis Hastings.  I hope this helped with the intuition.
edit
My apologies.  The word sequential didn't give me the sense that this was a separate idea (there are many sequences in MCMC already).  As it appears that MCMC is a common technique used in sequential MC, I will leave this answer up.
Comment: This answer does not seem to be related to particle filters / sequential Monte Carlo.


Let R be a ring and M a maximal ideal on R, let x,y∈R such that xy∈M, prove that x∈M or y∈M

Question: I Need help to prove this:
Let $R$ be a ring and $M$ a maximal ideal of $R$, let $x,y\in R$ such that $xy\in M$, prove that $x\in M$ or $y\in M.$
R is commutative ring with identity
I tried to prove M is a prime ideal but i couldn't figured  it out
Comment: $R$ is a ring with identity? Commutative or non-commutative? What you have tried? Please add these in the "body" of the question.
Comment: Welcome to MSE. [Here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a reference for MathJax. Please keep in mind that this is *not* a "do my homework for me" site. You will find more help here if you add your thought and/or work. This question, as it stands now, will attract negative votes and will be closed. (Also, don't be discouraged by negative votes; it will help you to understand [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question)).
Answer: By contrapositive:
Suppose neither $x$ nor $y$ belong to $M$. Then $(x,M)$ and $(y,M)$ strictly contain $M$.  $M$ being maximal, these ideals  are equal to $R$, which means there exist $a, b\in R$ and $m,n\in M$ such that $ax+m=1$, $by+n=1$. Multiply them:
$$1=(ax+m)(by+n)=abxy+axn+bym+mn.$$
In the last sum, the last three terms belong to $M$, so the the first cannot be in $M$ since $1$ doesn't. This implies that $xy$ doesn't belong to $M$.
Added – A shorter-better proof by @egreg:
We prove that if one of $x, y$ doesn't lie in $M$, the other does. Say $y\notin M$. As $M$ is maximal, this means there exists $b\in R,\: n\in M$, such that $by+n=1$, so
$$x=x(by+n)=b(xy)+xn\in M.$$
Comment: I think the direct way is simpler: if $y\notin M$, then $1=yr+z$ for $r\in R$ and $z\in M$; then $x=xyr+xr\in M$.
Comment: @egreg: Much shorter than  the contrapositive indeed. If you don't mind, I'll add it to my answer (with due credits,of course).
Comment: You're welcome!
Answer:
$xy\in M \implies $ $x\in M$ or $y\in M$

Hint: This condition defines prime ideals. Prove that every maximal ideal is prime by considering $R/M$.
(I assume that $R$ is a commutative ring with unit.)
Comment: Yes, in the assumption that the ring is commutative.
Comment: @Math_QED, yes, of course. Otherwise: https://math.stackexchange.com/questions/973066/give-an-example-of-a-maximal-ideal-in-a-noncommutative-ring-which-is-not-prime


Using Parseval's identity to evaluate a symmetric infinite sum

Question: Let $f(x) = e^{i\alpha x}, x\in(-\pi,\pi)$ where $\alpha$ not an integer and an orthogonal basis $\{e^{ikx}\}$, show that
$$\sum_{n\in\mathbb{Z}} \frac{1}{(n+\alpha)^2} = \frac{\pi^2}{\sin^2(\alpha\pi)}$$
using Parseval's identity i.e. $\sum_{n\in\mathbb{Z}} \vert\langle f, e_n\rangle\vert^2 = \Vert f\Vert^2$ where $\{e_n\}$ is an orthogonal basis.
Naturally, I first computed the Fourier coefficient of $f$
$$\hat{f}(n) = \frac{1}{2\pi}\int_{-\pi}^\pi f(x)e^{-inx}dx = \frac{1}{\pi (\alpha - n)}\sin((\alpha - n)\pi),$$
which yields the Fourier series
$$f(x) = \frac{1}{\pi}\sum_{n\in\mathbb{Z}} \frac{\sin((\alpha - n)\pi)}{\alpha - n}e^{inx}.$$
Computing $\langle f, e^{ikx}\rangle$ we get
\begin{align}
\langle f, e^{ikx}\rangle = \langle e^{i\alpha x}, e^{ikx}\rangle &= \langle \frac{1}{\pi}\sum_{n\in\mathbb{Z}} \frac{\sin((\alpha - n)\pi)}{\alpha - n}e^{inx}, e^{ikx}\rangle\\
&= \frac{1}{\pi} \sum_{n\in\mathbb{Z}} \frac{1}{\alpha - n}\langle \sin((\alpha - n)\pi)e^{inx}, e^{ikx}\rangle\\
&= \frac{1}{\pi} \sum_{n\in\mathbb{Z}} \frac{\sin((\alpha - n)\pi)}{\alpha - n}\langle e^{inx}, e^{ikx}\rangle
\end{align}
where
$$\langle e^{inx}, e^{ikx}\rangle = \int_{-\pi}^\pi e^{inx}e^{-ikx} dx = \begin{cases}2\pi, \text{ if }n=k\\ 0, \text{ if } n\neq k\end{cases}$$
Thus if $n=k$,
\begin{align}
\langle e^{i\alpha x},e^{ikx}\rangle = \frac{2\sin((\alpha - n)\pi)}{\alpha -n}
\end{align}
On the other hand,
$$\Vert f\Vert = \int_{-\pi}^\pi e^{i\alpha x}e^{-i\alpha x}dx = 2\pi\implies \Vert f\Vert^2 = 4\pi^2$$.
Therefore by Parseval,
\begin{align}
\sum_{n\in\mathbb{Z}} \vert\langle e^{i\alpha x}, e^{ikx}\rangle\vert^2 &= \sum_{n\in\mathbb{Z}}\left\vert\frac{2\sin((\alpha - n)\pi)}{\alpha -n}\right\vert^2\\
&= \sum_{n\in\mathbb{Z}}\frac{4\sin^2((\alpha - n)\pi)}{(\alpha - n)^2}\\
&= \Vert f\Vert^2 = 4\pi^2.
\end{align}
Thus
$$\sum_{n\in\mathbb{Z}}\frac{\sin^2((\alpha - n)\pi)}{(\alpha - n)^2} = \pi^2,$$
which is not the desired result. How do I resolve this? please point out the mistakes I have made. Thanks!
Comment: aren't $\alpha - n$ and $\alpha + n$ the same since the index set is $\mathbb{Z}$?
Comment: i tried $e^{-i\alpha x}$ but got the same result unfortunately
Comment: The function $\sin^2x$ has period equal $\pi.$ Therefore $\sin^2(\alpha \pi -n\pi)=\sin^2(\alpha \pi).$
Answer: Notice that:
$$(\sin((a-n)π))^{2}=(\sin(aπ)\cos(-nπ)+\cos(aπ)\sin(-nπ))^{2}$$
Now $\sin(-nπ)=0$ and $\cos(-nπ)= (-1)^{n}$, for all $n\in\mathbb{Z}$.
So you are left with: $$(\sin((a-n)π))^{2}=((-1)^{n}\sin(aπ))^{2}=\sin^{2}(aπ)$$
Dividing both sides of the equality you've arrived at with $\sin^{2}(aπ)$ gives the desired result.


Comparing a two different sequences of values to a third, correct sequence, and determining which of the two is more accurate.

Question: I have a question in mind and would be thankful for any help:
Consider some values:
$a_1, a_2, \cdots, a_n$. Assume that these values are the true, correct values.
Now consider two other sets of values:
$b_1, b_2, \cdots, b_n$ and $c_1, c_2, \cdots, c_n$. The $b$ values are determined experimentally with one method, and the $c$ values are determined experimentally with a different method. Both attempt to be as close as possible to the $a$ values.
If I want to find out which method produces the closest values to $a$ overall, is it mathematically sound to graph $b$ vs $a$, and separately $c$ vs $a$, and then compare the slopes? Is it fair to say that whichever graph ($b$ or $c$) has a slope closer to 1 is the more accurate method?
If so, how should I compare the slopes? (E.g., by finding the ratio between them?)
If not, how should I compare the $b$ and $c$ values to the $a$ values in order to determine which method is most accurate?
Answer: I think the most common way to deal with your problem is to see $a,b,c$ as elements on $\mathbb R ^n$ and check if $b$ or $c$ is the closest element to $a$. In a general setting (i.e. if you replace $\mathbb R^n$ by an arbitrary set) this problem is very difficult because you have to tell what it means to be far or close. A way to do so is to introduce a distance (or a metric) on your set. That is, $d(x,y)$ tells you how far is $x$ from $y$.
Here in $\mathbb R^n$ we have norms, which produce nice distances via
$$
d(x,y) = ||x-y||
$$
and we know they are all equivalent. That is, if you pick a norm $||.||$ on $\mathbb R^n$, compute $||a-b||$ and $||a-c||$ and select the smallest result, your conclusion wont depend on the choice of the norm. So the answer to your first question would be : choose your favourite norm.


Every year I'll withdraw $10 from the bank where I've a 2.5% interest rate. I've no money left after 10 years. How much did I have from the beginning?

Question: Ok, I will try to explain my problem in plain text:

Every year I'll withdraw $\$10$ from the bank where I have a $2.5\%$ interest rate. I have no money left after $10$ years. How much did I have from the beginning?

I've tried to come up with some kind of differential equation. But I'm probably just making in harder than it is.
Comment: Do you withdraw at the beginning or the end of the year?
Comment: Sorry. The 10 dollar is actually the total of every year. I withdraw in the end of every month. So (5/6) last day of every month.
Comment: @user156523 When do you withdraw money - once per year or every month? What do the mentioned (5/6) mean?
Comment: @user156523 but the interest rate it per year? That would make no sense.
Answer: If you had $X$ dollar at the beginning you will have
$$(X- c) \cdot p $$ after one year , where p=1 +2.5/100 and c=10.
Iterating this 10 times leaves you with
$$0 = (X-c)\cdot p^{10} - c \cdot \sum_{i=1}^9p^i $$
therefore you had
$$X = c \cdot \sum_{i=1}^9 p^{i-10} +c$$
in the beginning.
Edit: This solution works if you take 10$ at the beginning of each year.
Answer: Note: This calculation assumes interest payment at the end of the year, and one withdrawal at the end of the year.
Calling your unknown initial sum $x_0$, the interest rate $p$, the withdrawal sum $d$, the growth factor $f$ defined as
$$
f = 1 + \frac{p}{100}
$$
one gets for the sum after the first year $x_1$:
$$
x_1 = f x_0 - d
$$
and for the sum after the second year $x_2$:
$$
\begin{align}
x_2 &= f x_1 - d \\
    &= f\left(f x_0  - d\right) - d \\
    &= f^2 x_0 - f d - d
\end{align}
$$
and for the sum after the following years:
$$
\begin{align}
x_3 &= f x_2 - d \\
    &= f\left(f^2 x_0 - f d - d \right) - d \\
    &= f^3 x_0 - f^2 d - fd - d \\
\\
    &\vdots \\
x_{10} &= f^{10} x_0 - d \sum_{k=0}^9 f^k \\
    &= f^{10}x_0 - d \frac{f^{10}-1}{f-1} \quad (*)
\end{align}
$$
where the result
$$
\sum_{k=0}^N q^k = \frac{1 - q^{N+1}}{1-q}
$$
for a geometric sum is used. After 10 years the money is exactly gone: $x_{10} = 0$. We therefore get
$$
x_0 = d \frac{f^{10}-1}{f^{10}(f-1)}
$$
as initial sum. With $p = 2.5$% and $d=10$\$ this results in $x_0 = 87.52$\$.
In regard of Robert's answer:
At what initial sum the sum stays constant? Just checking this with equation $(*)$ gives:
$$
(f^{10} - 1) x_0 = d \frac{f^{10} - 1}{f - 1} \iff
x_0 = \frac{d}{f - 1}
$$
which is independent from the number of iterations and gives $x_0 = 400$\$ too.
Answer: That $\$10$  would be $2.5\%$ interest on a $\$400$ investment, i.e. if you had $\$400$ in the bank you could go on forever in this manner and your bank account would stay constant.  Since your account is actually depleted, you must have started with less.
But let's say your friend has an account earning the same interest rate, and together you have $\$400$: you start with $A$ and your friend with $\$400 - A$.  Your friend never withdraws any money.  Since your $\$10$ withdrawal represents the total interest on the two accounts, as time goes on
the sum of your fortune and your friend's stays constant.  After $10$ years your account has $0$ and your friend's has grown to $\$400$.  Now at a $2.5\%$ interest rate, your friend's account was multiplied by $1.025$ every year,
so your friend started out with $$ \dfrac{400}{1.025^{10}} = \$312.48$$
and so you must have started with
$$ 400 - 312.48 = 87.52$$
This works for any type of compounding as long as the $2.5\%$ is the effective annual rate rather than the nominal rate, and withdrawals happen at the same time as interest is paid.


Origin point of a normal vector to a given point, from a given plane

Question: I have a plane $P: 2x + y - z -1 = 0.$
I have a point $A_1( 0, 1, 1).$
Question asks to find the coordinates of $A_2$, which is symetrical to $A_1$ with respect to $P$.
I tried using the formula for distance between a point and a plane(for $A_1$ and $P$) and with it, tried to find the coords of $A_2$, but that was unsuccesful.
I believe the last prospects are in finding a normal vector $N_1$, colinear to the normal to $P$ $n(2,1,-1)$, whose module is equal to the distance between $A_1$ and $P$, then multiplying by $-1$ and getting the answer.
I ask for help in finding this $N_1$ vector.
Comment: Did you succeed in finding the distance from the plane $P$ to the point $A_1$? What was the result?
Answer: The vector $v=(2,1,-1)$ is orthogonal to $P$. So, the point of $P$ which is closer to $A$ is the intersection of $P$ with the line passing through $A_1$ and with the direction given by $v$, which is the line$$\{(0,1,1)+t(2,1,-1)\mid t\in\Bbb R\}=\{(2t,t+1,-t+1)\mid t\in\Bbb R\}.$$And $(2t,t+1,-t+1)\in P$ if and only if $4t+(t+1)-(-t+1)-1=0$; in other words, if and only if $t=\frac16$. So, the intersection point is $I=\left(\frac13,\frac76,\frac56\right)$. And then\begin{align}A_2&=I-(A_1-I)\\&=2I-A_1\\&=\left(\frac23,\frac43,\frac23\right).\end{align}
Answer: Suppose (signed) distance of $A_1$ from plane $P$ is $D$. Then coordinates of its image $A_2$ will be given by
$$A_2 = A_1 -2D\hat{n}$$
Factor of $2$ is there since $A_2$ is at twice the distance from $A_1$ to the plane. Negative sign because $\vec{n}=(2,1,-1)$ points outward from the plane.  The unit vector $\hat{n}=\dfrac{1}{\sqrt{6}}(2,1,-1)$.
Signed distance $D$ of a point $(x_0,y_0,z_0)$ from a plane $ax+by+cz+d=0$ is given by
$$D=\frac{ax_0+by_0+cz_0+d}{\sqrt{a^2+b^2+c^2}}$$
Hence
$$A_2=(0,1,1)-2\cdot \Big(\frac{-1}{\sqrt{6}}\Big) \cdot \dfrac{1}{\sqrt{6}}(2,1,-1)=\left(\frac23,\frac43,\frac23\right)$$
Answer: You can take $n = (2, 1, -1)$ as your normal vector to the plane. Then, we can define $r(t) = A_1 + t\cdot n$. This is a line going through $A_1$ which goes in the direction of the normal vector to the plane.
If you can find the time $t_0$ where this line intersects the plane, continuing along the line for the same amount of time will allow you to find $A_2$. In other words, if $r(t_0) \in P$, then  $r(2t_0)$ will be $A_2$.
You can find $t_0$ by solving $n \cdot r(t) = 1$, which is just a linear equation.


Let $q$ be a prime of the form $4k+3$. If $2q+1$ is prime, then $2q+1$ divides $2^q−1$.

Question: This is the theorem I need to show: "Let $q$ be a prime of the form $4k+3$. If $2q+1$ is prime, then $2q+1$ divides $2^q−1$."
I need to show this to show that $2^{251} - 1$ is not a Mersenne Prime.
Answer: Since $p=2q+1$ is a prime of the form $8k+7$, it follows that $2$ is a quadratic residue of $p$. (Recall that $2$ is a quadratic residue of the odd prime $p$ iff $p$ is of the form $8k\pm 1$.)
Thus by Euler's Criterion, $2^{(p-1)/2}\equiv 1\pmod{p}$, and therefore $2^q\equiv 1\pmod{p}$. This says that $p$, that is, $2q+1$,  divides $2^q-1$.
Note that $2q+1$ is a proper divisor of $2^q-1$ unless $2q+1=2^q-1$. That happens when $q=3$, but nowhere else, since for $q\gt 3$, $2q+1\lt 2^q-1$.


How do I translate the tab menu of a view?

Question: I cannot translate the tabs menu shown in a view. Does anyone know how to do it?
Comment: Can you check in admin/config/regional/translate/translate if you find the tab titles?
Comment: Dis you enable the menu translation module?
Comment: yes i have enabled it but it allows me to translate the menus not the tab menu in view like i uploaded the image above.i can not get those menus in the navigation
Answer: Go to admin/config/regional/translate/translate and search for the tab titles you want to translate. Since you have the required modules installed you should be able to find them there.


Set operations on commutative ring epimorphisms (intersections, unions and complements)

Question: Given a commutative ring $R$, I am interested in the ring epimorphisms outgoing from $R$. In the opposite category of affine schemes, those quotient objects become subobjects of Spec $R$ and I study their set operations like union, intersection and complement.
Epimorphisms from $R$ are ordered by factorization, have a maximum element $\text{id}_R:R\to R$, a minimum element $R\to 0$, and any two epics $f:R\to A, g:R\to B$ have a lower bound which is their pushout $A\otimes_R B$. The lower bounds represent the intersections of the corresponding affine schemes. For upper bounds (unions), I am considering the pullback of the pushout of $f$ and $g$, which is $(f,g):R\to U$ with
$$U=\{(a,b)\in A\times B \;/\; a\otimes_R 1 = 1\otimes_R b\}$$
When the pushout $A\otimes_R B$ is zero, then $U$ is just the product $A\times B$, and $(f,g):R\to A\times B$ is the upper bound indeed. We can prove $(f,g)$ is an epimorphism by computing tensors to get $(a,b)\otimes_R (1,1)= (1,1)\otimes_R (a,b)$. When the pushout is not zero, then we don't have $(1,0)\in U$ and cannot separate the tensor into a sum of simpler terms. As another possible definition of unions, observe that epimorphisms out of $R$ have arbitrary intersections (infinite tensor products), so we could think of the intersection of all epimorphisms out of $R$ that are greater than both $f$ and $g$. However those epimorphisms form a proper class, not a set, so this union is not well defined, unless we manage to reduce it to a set. If this fails too, is there still another proof of existence of unions?
For the complement of an epic $f:R\to A$, my first tentative was searching for an epic $g:R\to B$ such as $f\lor g =\text{id}_R$ and $f\land g=0$. However, from what we just said, $f\land g=0$ yields $f\lor g = (f,g) : R\to A\times B$. And the product $A\times B$ is never an integral domain, because $(1,0)(0,1)=0$, so when $R$ is integral, they cannot be isomorphic. Therefore Boolean complements fail. We can still search for Heyting complements, i.e. the greatest $g:R\to B$ such as $f\land g=0$. But those probably fail too, because the punctured plane is not an affine scheme. Can we prove the epimorphism $K[X,Y] \to \frac{K[X,Y]}{\langle X,Y\rangle}$ does not have a Heyting complement?
I imagine the answers to those questions give some of the motivations of the upgrade from affine schemes to general schemes.
Comment: When you know that you are interested in epis, why do you insist to misnome them as quotients? Anyway what is your question precisely? The question title is vague and based on your text I could not quite figure out your question…
Answer: Let $R$ be a commutative ring. In this answer, an $R$-epi will be an epimorphism of commutative rings $R↠A$. A commutative $R$-algebra $A$ is an $R$-epi if and only if $A⊗_RA = A$. We order $R$-epis in the "geometrical" direction, by saying that $A ≤ B$ if there is a morphism $B→A$ such that $R↠B→A = R↠A$.
Since the category of commutative rings is cocomplete, $R$-epis are a (not necessarily small) complete poset. But actually, there is a set of $R$-epis, as shown in the paper Caractérisation des épimorphismes par relations et générateurs (as was pointed out to me in this answer). Let's just summarize the argument here. Isbell's zigzag lemma says that $R→A$ is epi if and only if every element $a ∈ A$ can be written as $XYZ$ with $X$, $Y$ and $Z$ matrices over $A$ such that:

The resulting product $XYZ$ is a $1×1$ matrix whose only entry is $a$.
All the entries of $Y$, $XY$ and $YZ$ are in the image of $R$ in $A$.

We can show that $a$ is characterized not only by $X$,$Y$,$Z$ (as their product), but also by $Y$, $XY$ and $YZ$. Indeed, if $b = X'Y'Z'$ is another element of $A$ with $X'Y' = XY$, $Y' = Y$ and $Y'Z' = YZ$, then
$$a = XYZ = X'Y'Z = X'YZ = X'Y'Z' = b\text{.}$$
As a consequence, $|A| ≤ \max(|R|,\aleph_0)$.
We conclude that $R$-epis are a complete poset, and hence also cocomplete: to build the supremum of a subset, take the infimum of all the upper bounds. This infimum is also described as an infinite tensor product over $R$, see this question.

You want to construct the union of $R↠A$ and $R↠B$ as the pullback of $A$ and $B$ over $A⊗_RB$. This works if $A⊗_RB = 0$, but it may fail otherwise.
Let's first see why it works if $A⊗_RB = 0$. This is because the pullback is then $A×B = A⊕B$ and we have
$$(A⊕B)⊗(A⊕B) = (A⊗A)⊕(A⊗B)⊕(B⊗A)⊕(B⊗B) = (A⊗A)⊕(B⊗B) = A⊕B\text{.}$$
More concretely, we have for all $(α,β) ∈ A×B$ the following computation.
$$\begin{align*}
(α,β)⊗(1,1) &= (α,0)⊗(1,0) + (α,0)⊗(0,1) + (0,β)⊗(1,0) + (0,β)⊗(0,1)\\
&= (1,0)⊗(α,0) + 0 + 0 + (0,1)⊗(0,β)\\
&= (1,1)⊗(α,β)
\end{align*}$$
If $A⊗_RB ≠ 0$, we still can reproduce the same computation but it shows that if $(α,β) ∈ A×B$ is such that $α⊗1 = 1⊗β$ in $A⊗B$, then $(α,β)⊗(1,1) = (1,1)⊗(α,β)$ in $A×B$ but not in $\{(x,y)∈A×B\,|\,x⊗1=1⊗y\}$ since we go out of this subring for the computation below.
$$\begin{align*}
(α,β)⊗(1,1) &= (α,0)⊗(1,0) + (α,0)⊗(0,1) + (0,β)⊗(1,0) + (0,β)⊗(0,1)\\
&= (1,0)⊗(α,0) + (1,0)⊗(0,β) + (0,1)⊗(α,0) + (0,1)⊗(0,β)\\
&= (1,1)⊗(α,β)
\end{align*}$$
Here is a counter-example where $R → \{(x,y)∈A×B\,|\,x⊗1=1⊗y\}$ is not epi. Take $R = k[x,y]$ for $k$ a field. Take $A = k[x,y,x^{-1}]$ and $B = k[x,y]/(y)$. (Geometrically, the union is the plane minus a punctured line.) Then $A⊗B = k[x,x^{-1},y]/(y)$ and the pullback of $A$ and $B$ over $A⊗B$ is the set of $P(x,y) ∈ A$ such that $P(x,0) ∈ k[x]$. In other words, it is
$$k[x,y,y/x^n\text{ for $n≥1$}] = \{u(x) + (y/x^n) v(x,y) \,|\, u(x) ∈ k[x],\,v(x,y)∈k[x,y],\,n≥1\}\text{.}$$
To prove $k[x,y]→k[x,y,y/x^n\text{ for $n≥1$}]$ is not epi, we must find a commutative $k$-algebra $T$ with two elements $x,y$ and two sequences $(u_n)_{n≥1}$, $(v_n)_{n≥1}$ such that:

$u_1 x = y = v_1 x$
$u_{n+1}x = u_n$ and $v_{n+1}x = v_n$ for all $n≥1$
$u_1 ≠ v_1$

If we can find that, we have two different morphisms $k[x,y,y/x^n\text{ for $n≥1$}] → T$ coinciding on $x$ and $y$, sending $y/x^n$ to $u_n$ or $v_n$. I don't know if there is a "standard" ring satisfying these conditions... But we can always take the free one. We start by building the free commutative monoid $M$ satisfying these conditions. It is generated by elements $x$, $y$, $u_n$ and $v_n$ for $n≥1$. We also put $u_0 = v_0 = y$. The axioms are that $u_n = u_{n+1} x$ and $v_n = v_{n+1} x$ for all $n$. Here is an explicit description of it (I won't prove it is the free such monoid but we don't need that).

The elements of $M$ are the pairs $(x,y) ∈ ℤ^2$ with $y≥0$, and $y>0$ if $x<0$, plus eventually a decoration if $x<0$ and $y=1$. Here is a drawing of this monoid (the black dots are the elements). We have $x = (1,0)$, $y = (0,1)$, $u_n = (-n,1)$ and $v_n = (-n,1)^*$.

Multiplication is simply addition, and we keep the decoration whenever it is possible.

We take $T = k[M]$, the formal combinations of elements of $M$, and this shows $k[x,y] → k[x,y,y/x^n\text{ for $n≥1$}]$ is not epi.

The last question is to know if $R$-epis are a Heyting algebra. They are not. The pseudocomplement of $k[x,y]→k[x,y]/(x,y)$ doesn't exist: this pseudocomplement has to be bigger than $k[x,y]→k[x,y,x^{-1}]$ and $k[x,y,y^{-1}]$, but the union of these two is the whole plane $k[x,y]$ (in our setting), which is not disjoint from the point.
Comment: By the way, do you know how the situation improves when we upgrade from affine schemes to general schemes? Monomorphisms into Spec $R$ would form a Heyting algebra I believe.
Comment: @V.Semeria I really don't know! I don't even know what is a subscheme. Looking online, they speak mostly of open and closed subschemes. I believe it has better properties than in our case, but I don't know much about algebraic geometry. It could also be a coHeyting algebra as in the case of frames (in pointless topology, the subspaces of a space form a *co*Heyting algebra!).
Comment: @V.Semeria See here: https://math.stackexchange.com/questions/816288/what-is-a-subscheme
Comment: I am also confused by those various definitions of subschemes. The standard categorical definition does apply: subschemes could be scheme monomorphisms, ordered by factorization. Maybe open and closed subschemes are meant to refine scheme embeddings, i.e. monomorphisms that induce isomorphisms between their source and image schemes.
Comment: @V.Semeria I really have no idea about all of that...


Checking string for various (different) patterns

Question: I have a function that will do various regex-matches to find out which courier belongs to the provided tracking-id.
Right now, I'm using many elif statements which works fine but I got the feeling that this isn't very scalable in terms of maintanance.
import re

def get_courier(tracking_id):
    """ Retrieves the courier from a given tracking-id """

    if re.match(r'^ABC\d*$', f'{tracking_id}'):
        courier = "Courier 1"
    elif re.match(r'^\d*-\d$', f'{tracking_id}'):
        courier = "Courier 2"
    elif re.match(r'^PREF\d*$', f'{tracking_id}'):
        courier = "Courier 3"
    # ...
    else:
        courier = None

    return courier

Would there be a possibility to maybe "outsource" the patterns into a file or database where I can define the patterns and their related courier?
I can't get my head around a solution that could work like this
import re

def get_courier(tracking_id):
    """ Retrieves the courier from a given tracking-id """

    patterns = database_select_function()

    courier = re.match(patterns, tracking_id)

    return courier

Comment: What is in `tracking_id`?
Comment: `tracking_id` will be an (alphanumeric) string like `ABC123456` or `123-456`
Answer: A simple better solution for regex pattern matching in python is the following:
import re

courier_patterns={r'^ABC\d*$': 'Courier 1',
                  r'^\d*-\d$': 'Courier 2',
                  r'^PREF\d*$': 'Courier 3'}

def get_courier(tracking_id):
    """ Retrieves the courier from a given tracking-id """

    courier=None

    for pattern, courier_name in courier_patterns.items():
        if re.match(pattern):
            courier=courier_name
            break

    return courier

As you can see, I'm not loading courier patterns from file or DB,
but adapting this solution is simple.
Comment: would have been nicer should you extract the matching logic into a separate more generic function (that possibly accepts the set of patterns and the string)
Comment: @Tibebes.M Please explain better or give your answer. I'm curious and I want to improve my code.
Comment: That's brilliant thanks Stefano! The loop through `.items()` is exactly what I was missing. The rest will be done relatively easy as you already said! :-)


How to display linear day ticks on x time-axe in Chartjs

Question: I have dataset width random time moments and I'd like to display round dates on x axe like
|   |   |   |   |
12  13  14  15  16
oct oct oct oct oct

Looks like time.round iss the proper option, but it not works, my code
const myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: chart_labels,
        datasets: [{
            label: 'Время доступа',
            data: chart_values,
            borderColor: ["#03A9F5"],
            borderWidth: 1,
            fill: true,
            backgroundColor: "#03A9F522",
            pointRadius: 1,
            pointHoverRadius: 5,
        }]
    },
  options: {
    interaction: {
      intersect: false,
      mode: 'index',
    },
    tension: 0.4,
    scales: {
      x: {
        type: 'time',
        'time.round': 'day',
      },
      y: {
        title: {
          display: true,
          stacked: true,
          text: 'Секунды',
          beginAtZero: true
        }
      }
    },
  }
});

And ticks go by 3 hours: 5pm 8pm 11pm...
Edited
time: {round: 'day'} is not a correct parameter, it moves dots to the beginning of a day, when I need to keep dots where they are but draw ticks on the begining of the days.
https://jsfiddle.net/7y2L9ueq/
Comment: I think the config is not correct. 'time.round' sounds not correct, try using time: { round: 'day'}. Also the 'y' scale sounds not correct because you added stacked and beginAtZero options in the title, but they should stay at upper level.
Comment: Yes, you wrote right syntax for round.day, but it makes absolutly another thing, I edited the question since it relates it's essence.
Comment: I think you don't need round: 'day but unit: 'day'. trying with unit: 'day' sounds work as you want.
Comment: Super! It is. You'd better write the answer and I mark it.
Answer: I think the issue is that you are using round option in the time.
For what you need, you should use unit option, which is defining the time unit on the axis.
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day' // <-- to use
        }
      },
      y: {
        title: {
          display: true,
          stacked: true,
          text: 'Секунды',
          beginAtZero: true
        }
      }
    }


How to notate fingerings on chords/double stops?

Question: I have a chord that requires a different hand position from the music surrounding it. Because it is only one note, I think it is unnecessary to indicate recommended position instead of recommended fingering. How do I show which finger number belongs to which note? I've come up with this:

but there is uncertainty about what string the notes are on at a glance (the whole reason for adding fingerings in the first place) and about whether the fingerings go from top to bottom or bottom to top. How would this be notated?
Note: I realize that sustained three note chords are (almost) impossible to play on a violin/viola/cello, but they can still be rolled, and the same problem applies to double stops.
EDIT: The fingering in the image is wrong. It should be 5 (or 4+), 3, 1. The fingering is for viola, starting on C string.
Comment: " It should be 5 (or 4+), 3, 1" What is finger 5 supposed to mean, for a string player? The thumb is irrelevant on violin and viola - the fingers are numbered 1 2 3 4, and 0 means an open string. On the cello, the thumb (used in higher positions) is marked as +. As @MattPutnam said, unless you have specified a non-standard tuning there is only one way for a player with normal sized hands to play this chord, so fingering it is irrelevant.
Comment: @alephzero I use 5 or 4+ to mean an extended fourth finger. That is, place your fourth finger one note (either half or whole step, depending on position and key) above where it would normally be. I'm not sure what is usually used, but I've seen 4+ before. And fingering is quite relevant. Try glancing at that image and see if you could play that with one look, and no fingerings, while in an orchestra.
Answer: I'm used to seeing this for chord fingering:

Image source
In case it's not clear, as spacing requires, sometimes the numbers are above the staff rather than below, but they are always arranged vertically and corresponding to the notes of the chord. I.e., the bottom of the three numbers is the finger to use for the lowest note of the chord, etc.
Answer: I'm not a violist, but I'm thoroughly confused by your fingering.  There's only one way to play this chord, and I can't see how "3-3-1" describes it.
At any rate, since there's only one way to play this chord, there's no need to mark a fingering at all.
Comment: I upvoted this answer, but I would say that even if there is only one way to finger something, making fingering explicit in sheet music can be useful for many reasons, such as when doing one's own transcriptions for one's own reading, or when teaching.
Comment: I realized I screwed up the fingering when I tried to play it. Also, it's for viola, on C, G, and D strings. As for "one way to play it" (a common fallacy), there are **always** multiple ways. They may involve alternate tunings, but they exist. Also, the fingerings are there so a violist can reasonably play it the first or second time though, without having to stop and read all three notes, scratch head, and try to play it. Obviously, one would figure out the best fingering for the individual later.
Answer: I most commonly see fingerings for double-stops placed above or below the staff (or even the finger for the top note above and the finger for the lower note below the staff), as in the last pair shown here:

For 3- and 4-note chords such a stacked fingering tends to disrupt staff spacing, so I often see fingerings stuffed next to the chord in the staff itself, as on the first chord shown in the image.  (The four-note chord in the image also has the redundant shorthand III underneath which indicates that it should be played in third position.)


Jquery: Click () to scroll specific div and hide top div

Question: Code Example:
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

jQuery:
$("#showfullsite").click(function() {

    $('html, body').animate({
        scrollTop: $("#fullsite").offset().top
    }, 2000);

    $('html, body').css('overflow', 'auto');
    $('#intro').hide(2000);

});

Simple CSS:
body {
overflow: hidden;
}

Hi everyone, I am not a jQuery expert. I am the beginner. So, I have a problem. I have two div wraps, one for the intro and one for full site. I am making a site like this, When I will open my site in a browser only the top #intro div will visible and the full site will hidden. I am using the overflow: hidden; to hide everything other side of the computer screen. I have a control in the #intro div screen to unlock the full site. So, When I will click in the control the site will scroll to #full-site. I am doing it using query and I am adding $('html, body').css('overflow', 'auto'); to show the hidden part of the site. Also, I am adding $('#intro').hide(2000); to hide the top #intro.
At this time top #intro is hiding and the scroll effect is working. But the #intro div content going left side, right side when the #intro is hiding and the scroll effect is not going targeted id. It's going very down from the targeted div. How can I do the work properly?
Comment: its overflow:hidden;  not overfolow:hidden ;
Comment: For one fullsite is not an id. its a class. So either change the pound to a dot or change the class attribute to an id. Same goes for intro.
Comment: Your div is `class="intro"`, not `id`.
Comment: Have you linked a jQuery file?
Comment: @AtheistP3ace sorry for writing mistakes. I am using ID both HTML and jQuery. The top part is hiding perfectly now. But the scroll is going down from targeted DIV. Can you tell me how can I  fix that.
Comment: @k97513 sorry for writing mistakes. I am using ID both HTML and jQuery. The top part is hiding perfectly now. But the scroll is going down from targeted DIV. Can you tell me how can I  fix that.
Comment: @k97513 Yes. I have linked with jQuery
Comment: Does your intro div take up the entire window? And then you hide that and full site is below it? Because it seems to me if you just hide the intro and remove overflow full site should be viewable without scrolling to it.
Comment: @imGaurav sorry for writing mistakes.
Comment: @ZakirHossain I wrote how to fix 10 minutes ago... :) see my answer
Comment: @AtheistP3ace Yes. You are right. I have made the intro full window height using jQuery.
Comment: Sorry but it seems like there is a lot more going on here that is not in the original question. Other functions and html I am unaware of. I don't see full-home anywhere in your html above. Perhaps expand your question with more info. Because if all you are doing is giving intro the full height and width of window, setting overflow hidden on body, then when they click control hiding intro and removing overflow. Then at that point full site should be visible without any animated scrolling.
Comment: post whatever you are using so that it can replicate your problem
Comment: @imGaurav everything is working fine. But the scrollTop is doing problems. When I am clicking the trigger the site is scrolling, But is going down from the targeted ID. Is there any solution?
Comment: instead of js  try go to fullsitehttps://jsfiddle.net/n6LLg2uw/1/
Answer: You wrote #fullsite in your javascript, but

 in your HTML.
You need to change your HTML as

.
The same error for intro.
Remember: for accessing to ID you should prefix with #, for classes you should use ..
You can read more about the selectors here: http://api.jquery.com/category/selectors/basic-css-selectors/
In your case I prefer the solution based on "id" and not on "classes". Infact any valid HTML document can contain many elements using the same class, but shouldn't exist more element with the same id.
This means that $(".aaa") will return a list containing any element with aaa class, but $("#aaa") will return the only element with aaa id.
Answer: is this how you want to run the code

$("#showfullsite").click(function() {

  $('html, body').animate({
    scrollTop: $(".fullsite").offset().top
  }, 2000);

  $('html, body').css('overflow', 'auto');
  $('.intro').hide(2000);

});
.container {
  overflow: hidden;
  height: 18px;
}

      go to fullsite

this is fullsite


react-native-fbsdk LoginManger is not defined

Question: I am having an issue with react-native-fbsdk LoginManager. I am keep getting error, "Cannot read property 'loginWithReadPermissions' of undefined.
I have tried multiple solutions that I have found in other posts but nothing seem to fix my issue.
I successfully install ed react-native-fbsdk and properly imported FBSDK frameworks into the Xcode project. I also properly linked libRCTFBSDK.a file. After doing this, my build comes out to be successful but I just keep getting that error saying "LoginManager is not defined"..
Could anyone please help me with this?
Here is my code with LoginManager and LoginButton:
<code>import React from 'react';
import { Container, Content, Text, Button, View } from 'native-base';
import Loading from './Loading';
import { AccessToken, LoginManager, LoginButton } from 'react-native-fbsdk';

    class Login extends React.Component {
      constructor(props) {
        super(props);
      }

      onLoginFacebook = () => {
        LoginManager
          .logInWithReadPermissions(["public_profile", "email"])
          .then((result) => {
            if(result.isCancelled) {
              return Promise.reject(new Error("The user cancelled the request"));
            }

            console.log(`Login success with permissions: ${result.grantedPermissions.toString()}`);
            //get the access token
            return AccessToken.getCurrentAccessToken();
          })

          .then((data) => {
            const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
            return firebase.auth().signInWithCredential(credential);
          })

          .then((currentUser) => {
            console.log(`Facebook Login with user : ${JSON.stringify(currentUser.toJSON())}`);
          })

          .catch((error) => {
            console.log(`Facebook Login fail with error: ${error}`);
          });
      }

      render() {
        const {
          loading,
          error,
          success,
          locale,
        } = this.props;
        const { email } = this.state;

        if (loading) return <Loading />;

        return (

          <Container style={{backgroundColor: 'white'}}>
            <Content>
                <View padder>
                  <Button
                    containerStyle={{
                      padding: 10,
                      width: 150,
                      margin: 20,
                      borderRadius: 4,
                      backgroundColor: 'rgb(73, 104, 173)',
                    }}
                    style={{marginTop: 20}}
                    onPress={this.onLoginFacebook}
                  >
                    <Text style={{fontSize: 18, color: 'white'}}>
                      Login Facebook
                    </Text>
                  </Button>
                </View>
            </Content>
          </Container>
        );
      }
    }

    export default Login;
</code>
Here are the screenshots of xCode configuration:
Comment: Is your Facebook SDK in the default location `~/Documents/FacebookSDK`?
Answer: I had the same error and after a long search I found out I had to downgrade to SDK version 4.38.0 (I was using v4.39.0 at the time).
After installing the previous version everything worked as expected.
Hope it helps.


How to add custom class in custom module?

Question: I am not able to add custom class in custom module, I need to add class "ajax-link" in the anchor link to make it ajax based page load  .
function hook_node_view(array &$build, \Drupal\node\Entity\Node
$node, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display,
 $view_mode) {

 if ($display->getComponent('prevnext_next')) {
$build['prevnext_next'] = [
  '#theme' => 'prevnext',
  '#direction' => 'next',
  '#text' => t('Next'),
  '#nid' => $previous_next['next'],
  '#attributes' => array(
  'class' => array(
  'ajax-link'
      ),
    ),
  '#url' => Url::fromUserInput('/node/' . $previous_next['next']."?an=left")->toString(),
  '#void' => empty($previous_next['next']),
];
 }
   }

What am I doing wrong in the code ?
I want to create link something like this:
Next

Comment: What does your prevnext theme / template code look like?
Comment: What @Clive means is that theme function doesn't use an "attributes" variable so putting that key in there has no effect. If all you want is an A tag you could use a #type link instead. See. https://drupal.stackexchange.com/a/187780/13727
Comment: `theme_prevnext` isn't making use of `#attributes`, it's pretty much that simple
Comment: I am not getting you @clive , so what should i use instead of #attributes to add class.
Answer: you can try code :
  $url = Url::fromRoute('entity.node.canonical', ['node' => $previous_next['next'],'an'=>'left']);
  $url->setOptions([
      'attributes' => [
          'class' => ['ajax-link custom-class']
      ],
  ]);

  $build['prevnext_next'] = [
      '#type' => 'link',
      '#title' => t('Next'),
      '#url' =>  $url,
  ];


Regex-like construction to match %([text]) where [text] can contain escaped parens

Question: I'm trying to resolve tokens in a string.
What I would like is given input like this:
string input = "asdf %(text) %(123) %(a\)a) asdf";

That I could run that through regex.Replace() and have it replace on "%(text)", "%(123)" and "%(a\)a)".
That is, that it would match everything between a starting "%(" and a closing ")" unless the closing ")" was escaped. (But of course, then you could escape the slash with another slash, which would prevent it from escaping the end paren...)
I'm pretty sure standard regular expressions can't do this, but I'm wondering if any of the various fancy expanded capabilities of the C# regular expression library could, rather than just iterating across the string totally manually? Or some other method that could do this? I feel like it's a common enough program that there has to be some way to solve it without implementing the solution from scratch, given the immensity of the .net framework? If I do have to implement iterating through the string and replacing with string.Replace(), I will, but it just seems so inelegant.
Answer: How about
var regex = new Regex(@"%\(.*?(?<!\\)(?:\\\\)*\)");
var result = regex.Replace(source,"");

%\( match literal %(
.*? match anything non-greedy
(?<!\\) preceding character to next match must not be \
(?:\\\\)* match zero or more literal \\ (i.e. match escaped \
\) match literal )
Comment: Yep, that "preceding character to next match" was exactly what I suspected might exist but couldn't find. That's a pretty ugly regex, but still nicer than doing it by hand. Thanks!
Answer: This is working for me :
    String something = "\"asdf %(text) %(123) %(a\\)a) asdf\";";
    String change = something.replaceAll("%\\(.*\\)", "");
    System.out.println(change);

The output
"asdf  asdf";

Comment: That's because your regex is greedy, and your replacement is empty. Try replacing it with something other than the empty string, and you'll see that it's not quite what I asked for: it's matching the whole substring "%(text) %(123) %(a\\)a)", rather than each piece individually. (In actuality I want to capture the text inside each %() and run the group through the Replace overload that takes a MatchEvaluator, but that should be the easy part.) In your simple example, if you told it to replace each match with "!", I would expect to see "asdf ! ! ! asdf", not "asdf ! asdf".


jQuery dialog theme and style

Question: How do I change the background color of the title bar of a jQuery dialog?
I have looked at the themeroller but it does not seem to work for me.
Thanks
Comment: Depends on which plug-in you use for displaying such dialog (there are no any dialogs in jQuery itself).
Answer: You can change it by modifying the ui-dialog-titlebar CSS class, but I highly recommend you to use the ThemeRoller tool.
See also:

UI/Dialog/Theming
UI/Theming/API
Answer: I do this way (adding "ui-state-error" style for header):

Comment: Don't change it with javascript. Use CSS.
Answer: There are classes associated with each element in the dialog.
Use Firebug to inspect the elements and use CSS to style them.  For example, the title bar has the class "ui-dialog-titlebar".
(this assumes that you are using the jQuery UI Dialog)
Answer: Use the dialogClass property. You can apply to whatever css in jquery dialog.
Below we are formatting header and content blocks.

Hello StackOverflow!

Comment: I agree. Applying or removing classes with javascript seems the wrong way to go about it. The css classes are accurately describing the state of the element, you just want to change the appearance of the element while in that state.
Comment: what about changing the colors of the buttons of the modal popup?
Answer: The previous example works well but with only the red color of the error theme.
Here a simple solution with just changing the header image in the css:
css:
.ui-widget-header-custom{
    background: #f6a828 url(../images/ui-bg_flat_95_0a43ac_40x100.png) 50% 50% repeat-x;
}

javascript:
$('#my_dialog').dialog({
    open: function(event, ui){
        $(this).parents(".ui-dialog:first").find(".ui-widget-header")
            .removeClass("ui-widget-header").addClass("ui-widget-header-custom");
    }
});

Notice that contrary to the previous example, I removed the:
removeClass("ui-widget-header")

instead of just adding the class on the:
find(".ui-dialog-titlebar")

Must note that this example works with the dialog header without its link.
Answer: Sometimes you can't edit the css file. So you can try this:
dialog = $('
').dialog({
  title: 'Dialog with css for title bar',
  open: function() {
    $(this).parents(".ui-dialog:first").find('.ui-dialog-titlebar').css('background-color','#275D9E');
  }
});

jQuery dialog theme and style


is it possible to install java without the browser plugin?

Question: I need java, but I don't want any browser to be able to access it.
Is it possible to remove the whole applet/browser plugin code?
Answer: As of Java Version 7 Update 10, the Java Control Panel (in the Security tab) can disable the Java plug-in completely: http://www.java.com/en/download/help/disable_browser.xml

This should avoid the possibility that a Java upgrade might re-enable the plug-in, which might be a risk with some other approaches.
Answer: If you install the JRE; you can delete or rename npjp2.dll or libnpjp2.so (on linux); or on Linux make it non executable (chmod 0000 libnpjp2.so). This single file is the plugin file.
They're located in %ProgramFiles%\jre<x>\bin\plugin2 on Windows. On Linux, they're where ever your java is installed. You can run locate libnpjp2.so to find the location.
The same also applies to the JDK.
Comment: Disabling the plugin would alleviate most java security concerns right? (Since java attacks happen through the browser)
Comment: But if this is a server, people should not be using it for browsing web sites anyway...
Comment: I really don't think anything is located in "jre/bin/plugin2" on Windows. :)
Answer: One method to disable the Windows/IE browser plugin is to set a deny ACE on the following files:
"C:\Program Files\Java\jre6\bin\ssv.dll"
"C:\Program Files\Java\jre6\bin\jp2ssv.dll"
"C:\Program Files\Java\jre7\bin\ssv.dll"
"C:\Program Files\Java\jre7\bin\jp2ssv.dll"
"C:\Program Files (x86)\Java\jre6\bin\ssv.dll"
"C:\Program Files (x86)\Java\jre6\bin\jp2ssv.dll"
"C:\Program Files (x86)\Java\jre7\bin\ssv.dll"
"C:\Program Files (x86)\Java\jre7\bin\jp2ssv.dll"
This could be performed in a computer startup script.
If you run this command manually, it must be done from an elevated command prompt.
icacls "C:\Program Files (x86)\Java\jre7\bin\ssv.dll"
C:\Program Files (x86)\Java\jre7\bin\ssv.dll
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)
Successfully processed 1 files; Failed processing 0 files
icacls "C:\Program Files (x86)\Java\jre7\bin\ssv.dll" /deny Everyone:(X)
processed file: C:\Program Files (x86)\Java\jre7\bin\ssv.dll
Successfully processed 1 files; Failed processing 0 files
icacls "C:\Program Files (x86)\Java\jre7\bin\ssv.dll"
C:\Program Files (x86)\Java\jre7\bin\ssv.dll
Everyone:(DENY)(S,X)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Administrators:(I)(F)
BUILTIN\Users:(I)(RX)
Successfully processed 1 files; Failed processing 0 files
Comment: What if a process replaced the files?  This is not inconceivable, for example if an installer had the files on a manifest to determine relevancy.  A script to remove the files may not be applied until the next restart.  Applying the deny ACE works in most cases.
Comment: is deleting it not easier?
Answer: Starting from Oracle JDK/JRE 7u21 (Release Notes), a Server JRE is available which can serve such requirement.

A new Server JRE package, with tools commonly required for server deployments but without the Java plug-in, auto-update or installer found in the regular JRE package, is available starting from this release. The Server JRE is specifically targeted for deploying Java in server environments and is available for 64-bit Solaris, Windows and Linux platforms. For more information on installing this package, see Installation Instructions.


Evaluate $\int z ds $ over the curve $x=y=z^2$ from $(1,1,1)$ to $(4,4,2)$

Question: Let r denote the path $x=y=z^2$ from $(1,1,1)$ to $(4,4,2)$. Evaluate
$$\int_rz ds.$$
I am not sure where to even begin on this one. Any help would be much appreciated.
Comment: Kindly have a look at [Line Integrals](https://en.wikipedia.org/wiki/Line_integral#Line_integral_of_a_scalar_field).
Answer: Such an integral is called the line integral of a scalar field. You can see here for some introduction. Here $ds$ is the infinitesimal of the arc length. In the 3-dimensional space we have $ds = dz\sqrt{(\frac{dx}{dz})^2+(\frac{dy}{dz})^2+1}$. By the relationship of $x,y,z$ in this problem $\frac{dy}{dz} = \frac{dx}{dz} = 2z$, so we have $ds = dz\sqrt{8z^2 + 1}$. Therefore the original integral is
$$
\int_r zds = \int_1^2 z\sqrt{8z^2 + 1}dz \overset{t=z^2}{=} \frac{1}{2}\int_1^4\sqrt{8t+1}dt = \frac{1}{24}[(8t+1)^{3/2}]^4_1 = \frac{1}{24}(33^{3/2}-27).
$$
Comment: Thanks! I've been pulling my hair out trying to find material on this but because I didn't know that this was a special case of line integrals I couldn't find anything. Thanks again
Comment: You are welcome :)


run script on shutdown

Question: I have the following script, how do I run it on shutdown in debian linux? (don't want to use GUI)
#!/bin/bash
vms=$(vmrun list | grep '/');
for vm in ${vms}
do
        echo 'suspending ' $vm
        vmrun suspend $vm soft
done

I tried adding it to /usr/local/bin with chmod +x permissions. Then I created symbolic links to rc0.d (shutdown) and rc6.d (reboot).
I then did update-rc.d shutdown_vms 0 6 .
When I do shutdown -r now, it switches to console mode to restart....at that point I can see a error message stating shutdown_vms has failed.
I this the proper way to install the shutdown script and why is it failing (where do I look in the logs?)
Edit:
I used the command update-rc.d -f shutdown_vms start 0 0 6 .
When I look at the start up list for rc0.d (shutdown), i see that both shutdown_vms, vmware, and gdm are all order of 0. I think if gdm fires before shutdown_vms, it will kill the vms. I think this is what's happening because when I log the number of vms running when the script executes, it logs 0.
Can I change the order of gdm/vmware to 1 so that shutdown_vms run first?
Answer: This looks like you should put it into a proper init-script as "stop" method. Your current script propably fails, because of an exit-code that is not equal to zero.
Apart from that you should enclose "$()" because your list of vms propably contains white space.
Test your script by sh -x YOURSCRIPT stop.
Comment: Running that outputs: + vmrun list
+ grep /
+ vms=
+ exit 0
Answer: try adding: exit 0 under done.
so it looks like gdm does this during the shutdown process.
maybe a better way is that you let your vms script test if it really is necessary to go through the shutdown procedure. In that case it does nothing to shutdown a non-existent process. This non-existent process probably caused your error message.
Comment: Did that, didn't work. Is there anyway to know whether the script failed (some kind of log stored in var)? I ran the script manually and it runs fine
Answer: Have you named the file starting with a 'K' in the /etc/rc[06].d directories?  If you don't then they will not be executed on shutdown.
Comment: I presume it works when you run it NOT in a shutdown scanario but NOT when in /etc/rc.d directories?
Comment: I used update-rc.d -f shutdown_vms start 99 0 6 . which automaticaly puts K01shutdown_vms in /etc/rc0.d and /etc/rc6.d, it still doesn't work
Answer: Hmmmm...It would be nice if the failure output could be shown.  This would likely easily clearup some things.
One other thought, try putting in a PATH statement right after #!/bin/sh.
 #! /bin/sh
 PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:.....<anything else you need>
 export PATH
 .
 .   (rest of script)
 .
 exit 0

I'm not familiar with vmlist.

run script on shutdown


Who wants a hat? Come and get your hats (2016 edition)!

Question: 'Tis the season! Winter Bash is back on participating Stack Exchange sites.
Winter Bash is an annual event that can run on any Stack Exchange site that chooses to participate. Users earn "hats" for their gravatars by completing certain tasks (analogous to badges). Certain actions trigger the user receiving a hat, which their gravatar can "wear":

Sites vote explicitly to participate, and if the idea is welcomed by site's users, it will be enabled in the aforementioned period. It's important to know that even if Winter Bash is enabled, users can explicitly opt out if they want to (there will be "I hate hats" option on their profile page which will revert the site to its familiar look for the user).
So, it's time to decide if we want hats on our Expats.SE! Vote on the answers below until Friday 9 December 2016. We'll enable hats only if there's sufficient support for it (for some yet undetermined value of "sufficient"). Please don't downvote an option, rather upvote only the one you choose. Of course, comment as necessary.
Your mod friends at Expats.SE remind you to enjoy hats responsibly.
Comment: Not sure how much the voting will be affected by my profile picture
Answer: YES
Hats are fun and it's good to have some fun even on sites with serious topics
Comment: **YES.** Let the hat times roll!
Answer: NO
This is a serious site and we should not pollute it with hats


Chord Leading Question

Question: I've been writing for quite some time, but only recently have I begun to earnestly study up on music theory to a greater level than the basics. Given that, I'm a bit confused on one thing:
Do chord-leading principles change in accordance with the mode you are using or would the rules remain consistent with the Ionian?
Thanks! :)
Comment: Are you talking about Palestrina style counterpoint? In that case the principles remain unchanged as far as I know.
Answer: Interesting question! When you say "chord-leading," do you mean "voice-leading" or "chord progressions"? Voice-leading is controlled by the chord progression, so I suppose the rules of the one inform the rules of the other. But my answer, in short, is this: the chord progressions of the modes may differ from one another, but voice-leading rules will probably always stay the same.
In the Ionian mode, the music usually continuously reaffirms the tonic, which is accomplished most powerfully by use of the dominant seventh chord. In the dominant seventh, the double half-step motion combined with the root motion of a fifth is what causes the ear to be drawn inexorably back to the tonic chord. For example, in the key of C major, the dominant seventh chord would consist of G-B-D-F. When the chord resolves back to the tonic, the B moves a half-step back to C, the F moves a half-step back to E, and the G moves a fifth down to C.
The question, I think, is whether we expect this sort of dominant-tonic relationship (and other similar chord relationships) to apply in other modes. From my own experience, it seems much harder to accomplish the reaffirmation of "tonic" because of the lack of half-step motion. Certainly, one can still utilize the root motion of a fifth to add a sense of final resolution, but it's not nearly so satisfying without the half-step motions (for whatever reason) as in the Ionian. In the Dorian and Mixolydian modes, for instance, one can just as comfortably resolve to the tonic from the dominant as from the subtonic chord.
However, the rules of voice-leading still apply, regardless of the mode. It is generally bad form to use parallel fifths, fourths, and octaves; or to use cross-voicing; or to double pitches other than the root of the chord excessively; etc. It is just as easy or difficult to avoid these problems in any other mode as it is to avoid them in Ionian mode. For instance, it's always a good idea to have a leading tone resolve to its upper neighbor. In Dorian mode, the leading tones fall in different places functionally than in the Ionian mode, but it's nevertheless bad form to use them in such a way that they fail to resolve to their upper neighbor. As always, one can break the voice-leading rules to accomplish a certain effect, but in general, they seem to apply in all modes.

Chord Leading Question


Where does Grail's errors property come from?

Question: Grails has a bug with regards to databinding in that it throws a cast exception when you're dealing with bad numerical input. JIRA: http://jira.grails.org/browse/GRAILS-6766
To fix this I've written the following code to manually handle the numerical input on the POGO class Foo located in src/groovy
void setPrice(String priceStr)
{
    this.priceString = priceStr

    // Remove $ and ,
    priceStr = priceStr.trim().replaceAll(java.util.regex.Matcher.quoteReplacement('$'),'').replaceAll(',','')

    if (!priceStr.isDouble()) {
        errors.reject(
            'trade.price.invalidformat',
            [priceString] as Object[],
            'Price:[{0}] is an invalid price.')

        errors.rejectValue(
            'price',
            'trade.price.invalidformat')
    } else {
        this.price = priceStr.toDouble();
    }
}

The following throws a null reference exception on the errors.reject() line.
foo.price = "asdf" // throws null reference on errors.reject()
foo.validate()

However, I can say:
foo.validate()
foo.price = "asdf" // no Null exception
foo.hasErrors() // false
foo.validate()
foo.hasErrors() // true

Where does errors come from when validate() is called?
Is there a way to add the errors property without calling validate() first?
Answer: I can't exactly tell you why, but you need to call getErrors() explicitly instead of accessing it as errors like a property. For some reason, Groovy isn't calling the method for it. So change the reject lines in setPrice() to
getErrors().reject(
        'trade.price.invalidformat',
        [priceString] as Object[],
        'Price:[{0}] is an invalid price.')

getErrors().rejectValue(
        'price',
        'trade.price.invalidformat')

That is the easiest way to make sure the Errors object exists in your method. You can check out the code that adds the validation related methods to your domain class.
Answer: The AST transformation handling @Validateable augments the class with, among other things

a field named errors
public methods getErrors, setErrors, clearErrors and hasErrors

The getErrors method lazily sets the errors field if it hasn't yet been set.  So it looks like what's happening is that accesses to errors within the same class are treated as field accesses rather than Java Bean property accesses, and bypassing the lazy initialization.
So the fix appears to be to use getErrors() instead of just errors.
Comment: Hrm, I must have glossed over the POGO bit and assumed it was a domain class
Comment: @doelleri I think the same transform applies to domain classes too, the code you linked to only fires for those domain classes that weren't enhanced at compile time (which can happen for dev mode auto-recompiles).  You deserve the accept, I was just addressing your "I can't exactly tell you why" :-)
Answer: The errors are add to your validateable classes (domain classes and classes that have the annotation @Validateable) dinamically.
Allowing the developer to set a String instead of a number doesn't seem a good way to go. Also, your validation will work only for that particular class.
I think that a better approach is to register a custom property editor for numbers. Here's a example with dates, that enable the transform of String (comming from the form) to Date with a format like dd/MM/yyyy. The idea is the same, as you will enforce that your number is parseable (eg. Integer.parseInt() will throw exception).
In your domain class, use the numeric type instead of String, so by code developers will not be allowed to store not number values.


Two-way fixed effects model: Is non-random treatment a problem here?

Question: Consider the following panel regression model, were we try to estimate whether Photovoltaic Panels (PV) installations on apartment blocks have a driving effect on adoption speed of surrounding dwellings:
\begin{align}
  Y_{it} &= \gamma_i  + \beta X_{it-1} + \theta_t +  \epsilon_{it} \\\\
    \end{align}
$\gamma_i$ denotes an area fixed effect.
$Y_{it}$ corresponds to the increase of PV panels on detached dwellings in area $i$ in year $t$.
$X_{it-1}$ denotes the increase in PV panels on apartment blocks in the surrounding radius, in the year before.
$\theta_t$ is a year fixed effect.
We assume the treatment $X$ here is not random, as the selection process for renovating apartment blocks is not random. Apartment blocks with certain building characteristics (e.g., age) are targeted first.
We also assume that surrounding detached houses share similarities in these predictive indicators for renovation. We assume that e.g., they roughly share the same built year.
We face an endogeneity issue here, as the estimates of $X$ could be biased, and the driving effect $X$ on $Y$ could be explained because of the fact the surrounding dwellings are also old.
My question is: since we added an area fixed effect, we control for unobservables, such as building age, which we believe have an effect on $Y$. However, can we still consistently and reliably estimate $\beta$? In other words, does the inclusion of the fixed effect solve our described non-random treatment?
Answer: As with any causal effect estimation, if your intervention assignment is random given the controls, the estimate would be unbiased.
Whether or not this applies in your case would require a lot of domain knowledge to answer.
A good way forward would be to explicitly formulate the structural causal model, including the confounding you suspect affects your data. This will force you to make your assumptions explicit and give you a way of checking whether your current model would give you an unbiased estimate under these assumptions.


Bootstrap carousel-fade no longer working with maxcdn 3.3.bootstrap.min.css

Question: I've had the fade transition working in a Bootstrap 3 build for a while now, but I just changed the call from a locally held copy of bootstrap.min.css (Bootstrap v3.1.1) to    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet"> and the the fade transition is no longer working. It just flips straight to the next slide. No transition at all.
I've tried adding the id of the carousel but that didn't work.

etc.
The CSS is:
.carousel-fade .item {
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
-ms-transition: opacity 3s;
-o-transition: opacity 3s;
transition: opacity 3s;
}
.carousel-fade .active.left {left:0;opacity:0;z-index:2;}
.carousel-fade .next {left:0;opacity:1;z-index:1;}

[BTW: When I put #myCarousel in front of those it defaults to the slide transition.]
You can see a version here using the  maxcdn v3.3.0 CSS here: bizharbour.net/projects/jambalaya/index.html
The one using the call to the locally held v3.1.1 css is here: bizharbour.net/projects/jambalaya/crewed-yacht-charter-sample-menu.htmlThe fade is working on this one.
One other thing I changed is the call to jquery and bootstrap js file. I'm now using:

Previously I was using:

The local bootstrap.js is v3.1.1 which includes Bootstrap: transition.js v3.1.1, if that means anything.
How do I get the carousel in Bootstrap 3.3.0 to recognise the carousel-fade transition?
Thanks for any help.
Cheers,
Tracy
Comment: The Bootstrap CSS rules take higher precedence than yours. You need something that beats `.carousel-inner > .item`. Try `.carousel-fade > .carousel-inner > .item`
Comment: Hi Phil, Thanks for the help. I changed the line as you suggested and have a little progress. When I view it on Firefox the slide starts the fade transition, but the next slide just pops up. You can see at the `bizharbour.net/projects/jambalaya/index.html`. I also tried adding `.carousel-fade > .carousel-inner > .item.active` but that made no difference. When I view it Safari there's no difference, still just swapping the slides without any transition or the default slide transition. So, right direction but still missing something. Any ideas?
Comment: You need to look at the current Bootstrap styles for the carousel and override everything you need to achieve a fade transition. See https://github.com/twbs/bootstrap/blob/v3.3.0/less/carousel.less
Comment: Thanks for the link. I don't read less yet. Why make it so difficult to customise in this version [sigh]. I've tried `.carousel-fade > .carousel-inner > .item > .transition { -webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}` in my css file. Just goes back to the default slide. So I'm guessing that .transition isn't a class. The bit `// WebKit CSS3 transforms for supported devices` in your link I don't understand. I do know I don't need the rest of the stuff as I'm not using left/right controls. Cheers
Comment: The compiled CSS is [here](https://github.com/twbs/bootstrap/blob/v3.3.0/dist/css/bootstrap.css#L5842). The carousel part starts at line 5842
Comment: Thanks Phil, but I've just made things worse. You can see at the same link, it's still sliding but much more slowly---so I've made some effect! The css is from line 205 at `bizharbour.net/projects/jambalaya/css/jambalaya.css`. I feel I'm being a tad dumb!
Comment: I also note that it's now affecting all the text on the page, changing to bold and back to normal! Something is definitely not right ...
Comment: This issue has been driving me nuts forever. I eventually downgraded my bootstrap version.
Comment: I'm thinking of doing the same but it seems nuts. Will continue to look for a working solution, and hope someone is able to post an answer.
Answer: I faced the same problem and I think I have a solution for what you need. In 3.3 they added CSS transforms to improve carousel performance in modern browsers so you need to override some styles. Tell me if it worked for you. :)
-webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);

My solution here: http://codepen.io/transportedman/pen/NPWRGq?editors=110
Comment: Sorry for the delay in getting back to you. Thanks, I implemented your CSS and it's fixed it for Firefox and Chrome (on the Mac) but not Safari 6.0.2. It's also working on the default browser on my Samsung Galaxy Tab BTW. If anybody else could check it on Safari on a Mac that would be helpful, maybe it's just me! What do you think @transportedman?
Comment: The solution seems to be working for me. A few other things: Ensure to remove the `class="sld-transition-2"` from the body tag; this shows up on some Bootstrap templates and can interfere with the transition effect. Also, I added `data-ride="carousel" data-interval="7000"` to the main carousel div for my requirements.


Statistics - Binomial and Poisson Distribution Problem

Question: I am given:

I get 11 text messages per hour according to a Poisson process.
The probability that a given text message is from my mother is $0.62$.

I then have to find the probability that I receive exactly two text messages from my mother in a 40 minute period.
My thought process is:

Find the expected number, $E(X)$, of text messages in a 40 minute period.
Use this value as the number of trials, $n$, in a binomial distribution to calculate $P(Y = 2)$ where $Y =$ "the number of text messages I receive from my mother in a 40 minute period".

However, $E(X) = 11 \cdot \frac{40}{60} = \frac{22}{3}$ meaning my idea won't work without rounding the number of trials - giving two wildly different answers (as expected). Am I meant to round up or down, or am I doing this completely wrong? I did try averaging the probabilities of the two answers I obtained, but I'm not sure if this is correct either.
Comment: Please do not delete your questions immediately after getting an answer.  This is rude to the person who took the time to answer the question, rude to future readers who might find value in the question and answer.
Answer: If the probability that a given text message is from my mother is independent from other text messages, you can split the poisson process: you can say that the stream of messages from my mother is a poisson process too with rate $0.62 \cdot 11 = 6.82$. This is known as 'splitting'.
The number of text messages in a 40 minute interval follows a poisson distribution with parameter $6.82 \cdot 40/60 = 341/75$. The probability that I receive exactly two text messages from my mother in a 40 minute period is:
$$\frac{e^{-341/75} (341/72)^2}{2!} \approx 0.12.$$


Writing unions as intersections

Question: I am trying to write
$$|A_1\backslash\cup_{i=2}^{m}A_i|,$$
and
$$|\cup_{i=1}^{m}A_i|,$$
as intersections.
For example, for $m=3$, I can write
$$|A_1\backslash(A_2\cup A_3)|=|A_1|-|A_1\cap A_2|-|A_1\cap A_3|+|A_1\cap A_2\cap A_3|.$$
Also,
$$|A_1\cup A_2\cup A_3|=|A_1|+|A_2|+|A_3|-|A_1\cap A_2|-|A_2\cap A_3|-|A_1\cap A_3|+|A_1\cap A_2\cap A_3|.$$
Is it possible to generalize this for any $m$?
Answer: The second example is called the principle of inclusion-exclusion. Basically, it says that if you have a family of sets $F$ and you want to count the elements of $\cup F$, you can look at all subsets of $F$ and count the total number of elements in the intersection of each subset ... but with subsets with an odd number of things counting positively and subsets with an even number of things counting negatively. This is easy to see in the case where $F$ has two sets in it.
$$ | A \cup B | = -0 + |A| + |B| - |A \cap B|$$
In this case $F = \{A, B\}$, the singleton subsets have an odd number of elements, $F$ itself and the empty set each count negatively.
It can be succinctly written as:
$$ \left|\cup F \right| =  \sum_{x \in P(F)} (-1)^{(|x|+1)} \cdot | \cap x | $$
With $P(F)$ being the powerset of $F$ (i.e. the set of all subsets).
The first example does not have a name, but is given by the following formula:
$$ \left| A \setminus (\cup F) \right| = \sum_{x \in P(F)} (-1)^{\left|x\right|} \cdot \left|A \cap (\cap x)\right| $$
Here's the derivation for this formula, assuming we believe the principle of inclusion-exclusion given above
start with expression we want.
$$ | A \setminus (\cup F) | $$
cardinality of relative complement.
$$ | A | - \left|A \cap \left(\bigcup_{B \in F} B \right)\right| $$
distributive property
$$ | A | - \left|\left(\bigcup_{B \in F} A \cap B \right)\right| $$
let $G$ be defined as $ \{ A \cap x \;\text{where}\; x \in F \} $.
$$ |A| - |\cup G| $$
apply principle of inclusion-exclusion
$$ |A| - \sum_{x \in P(G)} (-1)^{(|x| + 1)} \cdot |\cap x| $$
Here's where we remember that $\cap x$ refers to the intersection of a subset of $G$. The elements of $G$ are the elements of $F$, except that I intersected each element with the set $A$. I can perform this intersection last instead of first, as below.
$$ |A| - \sum_{x \in P(F)} (-1)^{(|x|+1)} \cdot |A \cap (\cap x)| $$
combining into a single sum:
$$ \left| A \setminus (\cup F) \right| = \sum_{x \in P(F)} (-1)^{\left|x\right|} \cdot \left|A \cap (\cap x)\right| $$
Comment: What about the first one with set difference?
Comment: @zdm I included the formula and how to derive it from PIE.

Writing unions as intersections


Magento onestepcheckout change billing address fields order

Question: I want to change the order of the billing address fields on onestepcheckout page. I found from  the admin onestepcheckout settongs "field position management" But a message displays here "Configure positions of fields in Section Billing and Shipping Address. You can display fields into 2 columns (eg: First name + Last name) or 1 full column (eg: Address + Null)".
I change the order her but its not reflecting. Also I am unable to find the billing and shipping address section. Pleas help me to find this secion.
Answer: You are probably using a paid 3rd party extension so the best option would be to contact extension provider support to get the answer.
And in all cases when you are using paid extensions try to solve your issues with support first then ask as:

other developers most probably don't have access to source to help you out
your questions in open internet are indexed and may just cost a sale for the extension provider
your questions in open internet might not get the extension provider attention
Answer: You can do that from Admin > System > Configuration > Onestepcheckout
http://www.YOURWEBSITE.com/index.php/admin/system_config/edit/section/onestepcheckout/


Einstein Notation Summing Order

Question: When summing an expression using Einstein notation we start with the leftmost index?
For example in that case of $$a^{i}_jb^j_kc^k_l$$
We start with $k$ or $$\sum_{j=1}^{\#}\sum_{k=1}^{\#}a^{i}_jb^j_kc^k_l=a^{i}_1b^1_1c^1_l+a^{i}_1b^1_2c^2_l+a^{i}_1b^1_3c^3_l...$$?
Comment: Addition is commutative, so it doesn't matter.
Answer: It doesn't matter which order you sum over $j$ and $k$ in.  Either way you get the same terms and addition is commutative.

Einstein Notation Summing Order


3 internet line in a single network

Question: i'm going to bond 3 internet line in a single network.
i'm using Mikrotik RB750 router, I configured this router like this:
/ip firewall mangle
add chain=input in-interface=WAN2 action=mark-connection new-connection-mark=WAN2_conn
add chain=input in-interface=WAN3 action=mark-connection new-connection-mark=WAN3_conn
add chain=input in-interface=WAN4 action=mark-connection new-connection-mark=WAN4_conn
add chain=input in-interface=WAN5 action=mark-connection new-connection-mark=WAN5_conn

add chain=output connection-mark=WAN2_conn action=mark-routing new-routing-mark=to_WAN2
add chain=output connection-mark=WAN3_conn action=mark-routing new-routing-mark=to_WAN3
add chain=output connection-mark=WAN4_conn action=mark-routing new-routing-mark=to_WAN4
add chain=output connection-mark=WAN5_conn action=mark-routing new-routing-mark=to_WAN5

add chain=prerouting dst-address=192.168.2.0/24 action=accept in-interface=bridge1
add chain=prerouting dst-address=192.168.3.0/24 action=accept in-interface=bridge1
add chain=prerouting dst-address=192.168.4.0/24 action=accept in-interface=bridge1
add chain=prerouting dst-address=192.168.5.0/24 action=accept in-interface=bridge1

add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/0 action=mark-connection new-connection-mark=WAN2_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/1 action=mark-connection new-connection-mark=WAN3_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/2 action=mark-connection new-connection-mark=WAN4_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/3 action=mark-connection new-connection-mark=WAN5_conn passthrough=yes

add chain=prerouting connection-mark=WAN2_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN2
add chain=prerouting connection-mark=WAN3_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN3
add chain=prerouting connection-mark=WAN4_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN4
add chain=prerouting connection-mark=WAN5_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN5

/ip route
add dst-address=0.0.0.0/0 gateway=192.168.2.1 routing-mark=to_WAN2 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.3.1 routing-mark=to_WAN3 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.4.1 routing-mark=to_WAN4 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.5.1 routing-mark=to_WAN5 check-gateway=ping

add dst-address=0.0.0.0/0 gateway=192.168.2.1 distance=1 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.3.1 distance=2 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.4.1 distance=2 check-gateway=ping
add dst-address=0.0.0.0/0 gateway=192.168.5.1 distance=2 check-gateway=ping

/ip firewall nat
add chain=srcnat out-interface=WAN2 action=masquerade
add chain=srcnat out-interface=WAN3 action=masquerade
add chain=srcnat out-interface=WAN4 action=masquerade
add chain=srcnat out-interface=WAN5 action=masquerade

Note: The router has 5 physiccal ports (WAN1,WAN2,WAN3,WAN4,WAN5) and 1 wireless port. WAN1 and Wireless port connected together via Bridge1 and all of the nodes in the network connected to Bridge1 (WAN1 or Wireless), now there is no problem in internet bonding, and it's working fine. but when a node in this network wants to visit a website (for example: google.com), the request will send to google.com from all of the internet lines! so for each nodes we are sending 2 more request to a single website!
I want to divide these internet lines between network nodes, for example each rang of IP use a specific Internet line, like this:
192.168.1.1 - 192.168.1.64: Use first Internet line
192.168.1.65 - 192.168.1.128: Use second Internet line
192.168.1.129 - 192.168.1.254: Use third Internet line

is it possible? can you help me?
Comment: Where exactly do you do bonding? I think you are confused with the terminology.
Answer: You are trying to use PCC (Per connection Classifier) but what you ask is load balancing based on the source IP address range.
Remove the following rules from your configuration:
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/0 action=mark-connection new-connection-mark=WAN2_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/1 action=mark-connection new-connection-mark=WAN3_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/2 action=mark-connection new-connection-mark=WAN4_conn passthrough=yes
add chain=prerouting dst-address-type=!local in-interface=bridge1 per-connection-classifier=both-addresses-and-ports:4/3 action=mark-connection new-connection-mark=WAN5_conn passthrough=yes

add chain=prerouting connection-mark=WAN2_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN2
add chain=prerouting connection-mark=WAN3_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN3
add chain=prerouting connection-mark=WAN4_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN4
add chain=prerouting connection-mark=WAN5_conn in-interface=bridge1 action=mark-routing new-routing-mark=to_WAN5

And add the following:
add chain=prerouting src-address=192.168.1.0/26 in-interface=bridge1 dst-address=!192.168.1.0/24 action=mark-routing disabled=no new-routing-mark=to_WAN2 passthrough=no
add chain=prerouting src-address=192.168.1.64/26 in-interface=bridge1 dst-address=!192.168.1.0/24 action=mark-routing disabled=no new-routing-mark=to_WAN3 passthrough=no
add chain=prerouting src-address=192.168.1.128/25 in-interface=bridge1 dst-address=!192.168.1.0/24 action=mark-routing disabled=no new-routing-mark=to_WAN4 passthrough=no

There is no need to mark the connections and then route-mark after. You can route-mark directly based on the source address range.

3 internet line in a single network


Django : join without related object

Question: I have two models in django :
class Matching(models.Model):
    representative_remote_id = models.CharField(max_length=200, null=True)
    representative_name = models.CharField(max_length=200)
    representative_group = models.CharField(max_length=200)

class Vote(models.Model):
    representative_name = models.CharField(max_length=200, blank=True, null=True)
    representative_remote_id = models.CharField(max_length=200, blank=True, null=True)
    # ...

As you can see, there are no relation between these two models.
What I want is select all votes where :
vote.representative_name = CONCAT(matching.mep_name, ' (', matching.mep_group, ')')
AND matching.representative_remote_id IS NULL
AND vote.representative_remote_id IS NOT NULL

I can't find a way to do this with django (without using 'raw' sql query)
Comment: make your join on rep_name = concat(match.mep_name etc...) and put your matching.rep_rem_id is null and vote.rep_rem_id is not null in your where clause --------- It's not that you have no relation it's that your relation is split in multiple fields in the second table if you use "=" anywhere between 2 tables and there is a result, that is a relation
Comment: Thank you Jeremy C, but I don't see how to do that, could you provide a small code example ?
Comment: would you mind if it's straight up sql and could you provide me with some data from your tables? I'll create a sqlfiddle to explain what I mean, that is if I can get this done within 45 minutes because that's when I need to leave
Comment: Hum, I know the sql request but I'd like to do it with django database functions.
Comment: I'm going to have to disappoint you then because I don't really have any experience even with python in general
Comment: Maybe this might help though:https://docs.djangoproject.com/en/dev/ref/models/querysets/#raw Appearantly you can run straight up sql in django and still run through the Queryset afterwards
Answer: I think you could get all the Matching objects with a filter applied on them, then get the Vote objects using that results.
Something like:
representative_names = ["{name} ({group})".format(name=field[0], group=field[1]) for field in Matching.objects.filter(representative_remote_id=None).values_list('representative_name', 'representative_group')]
Vote.objects.exclude(representative_remote_id=None).filter(representative_name__in=representative_names)

Comment: http://stackoverflow.com/questions/252976/full-outer-join-in-django

Django doesn't support "joins" in the usual SQL sense -- it supports object navigation.

Note that a relational join (inner or outer) creates a new "class" of entities. One that doesn't have a definition in Django. So there's no proper "result set" since there's no class definition for the things you get back.
Comment: That's two SQL queries, it could be done in SQL with only one query. I don't know if is it possible with django…

Django : join without related object