Textbooks with problem sets to prepare for predictive analytics masters

Question: I know there are some other questions out there on book recommendations, but I've looked into a lot of the books in those answers and haven't quite found what I'm looking for.
I am going to be starting a Masters program in Predictive Analytics this fall.  My background is Bachelor's in CS with a couple years experience doing software development in the industry.  I had an introductory statistics course in college, but it was rather worthless and, having not used it for a couple years, I've forgotten most of the information I did learn.
The topics for the prereq introductory course (for which I will likely receive a waiver, given my background) include: descriptive statistics, elementary probability rules, sampling, distributions, confidence intervals, correlation, regression and hypothesis testing.  A book that provides at a minimum a solid understanding of these topics would be great.  I imagine this is more of an applied statistics situation, versus deep mathematical foundations.
I'm looking for some recommendations on books that can get me prepared for the Masters program again.  Introductory level and beyond.  What I really want is some books that have problem sets and availability of corresponding answers.  In order to learn, I really need to put the concepts to work, and would like to be able to check the answers I come up with.
Comment: @FrankHarrell: Isn't Predictive Analytics only a smaller subset of Statistics? Those two terms don't seem identical to me.
Comment: You may need several books, depending on what you want to cover, & how far you want to go. So a list might be helpful. Also, it would help to know something about the level of mathematical difficulty you want; are you looking for mathematical statistics (mainly proofs) or applied statistics (primarily conceptual understanding)?
Comment: @gung, I've added another paragraph in the original post that I think addresses your questions.
Comment: @FrankHarrell, my cynical answer is that these days, the expression "Predictive Analytics" sells and sounds hot, but "Statistics" doesn't sound as hot.
Comment: Sounds like an educational problem.
Comment: As a side question why call the program "predictive analytics" as opposed to "statistics"?
Answer: What about Larry Wasserman: "All of statistics":
http://www.amazon.com/All-Statistics-Statistical-Inference-Springer/dp/1441923225/ref=sr_1_1?s=books&ie=UTF8&qid=1345051096&sr=1-1&keywords=larry+wasserman
This covers also more of newer ideas than the usual introduction. High on ideas, low on proofs.
To test out ideas with software, get some book on R, like Venables & Ripley: "MASS" or, if that is to heavy, Peter Dalgaards's book.
For challenging data sets to try out ideas, Andrews & Herzberg: "DATA" (springer)
Comment: Dalgaard's book includes exercise solutions (with code) as an appendix. Wasserman's All of nonparametric statistics does not. What about "All of statistics" and Venables & Ripley?
Answer: I think some of the books I mentioned for advanced undergraduate or first year graduate school are appropriate based on your description of what you need.
Something like Hogg and Tanis Probability and Statistical Inference 8th Edition would be very suitable.  Here is a link to amazon where there are 48 customer reviews of the book.
http://www.amazon.com/Probability-Statistical-Inference-Robert-Hogg/dp/0321584759/ref=sr_1_1?s=books&ie=UTF8&qid=1342453674&sr=1-1&keywords=probability+and+statistical+inference+eighth+edition
Comment: Should I be concerned at all that a majority of folks on Amazon don't seem to like the book much at all?
Comment: I haven't read the reviews. But often it is an issue of the level of the book.  This is a book at an intermediate level.  Many amazon reviewers that complain could be in need of something more elementary.  I perosnally have the third and sixth editions of the book and think it is excellent at the level of your interest.
Comment: What about exercise solutions (a big part of the original question)?
Answer: If you want a basic introductory statistics book, I recommend (undergraduate 1 year) "The Practice of Statistics for Business and Economics", 3rd edition BY David S. Moore, ISBN-13: 978-1429242530.
A higher level book is "Introduction to Econometrics", 3rd edition By James H Stock, ISBN-13: 978-0138009007.
I think they both have low cost International editions available on eBay. You can also try to find pdfs of both books.
Comment: What about exercise solutions (a big part of the original question)?


How to call a function in Woocommerce when order processing email is sent?

Question: I would like to know if there is any way to call a function when a Woocommerce order is successfully placed and the processing order email is sent.
Thank you for your help!
Answer: Sure, you could use the following hook that fires when the order changes to "processing": 'woocommerce_order_status_processing'
So, you can call your function in this way:
<code>add_action( 'woocommerce_order_status_processing', 'bbloomer_call_when_processing' );

function bbloomer_call_when_processing() {
    whatever();
}
</code>


Calculate $\lim_{x \to 0^+} \frac{3x + \sqrt{x}}{\sqrt{1- e^{-2x}}}$

Question: I need to calculate:
$$\displaystyle \lim_{x \to 0^+} \frac{3x + \sqrt{x}}{\sqrt{1- e^{-2x}}}$$
I looks like I need to use common limit:
$$\displaystyle \lim_{x \to 0} \frac{e^x-1}{x} = 1$$
So I take following steps:
$$\displaystyle \lim_{x \to 0^+} \frac{3x + \sqrt{x}}{\sqrt{1- e^{-2x}}} = \displaystyle \lim_{x \to 0^+} \frac{-3x - \sqrt{x}}{\sqrt{e^{-2x} - 1}}$$
And I need to delete root in the denominator and make nominator equal to $-2x$. But I don't know how.
Comment: Your step has a mistake.
Answer: Note that\begin{align}\lim_{x\to0^+}\frac{\left(3x+\sqrt x\right)^2}{1-e^{-2x}}&=\lim_{x\to0^+}\frac{9x^2+6x\sqrt x+x}{1-e^{-2x}}\\&=-\lim_{x\to0^+}\frac x{e^{-2x}-1}\left(9x+6\sqrt x+1\right)\\&=-\frac1{\lim_{x\to0^+}\frac{e^{-2x}-1}x}\times\lim_{x\to0^+}\left(9x+6\sqrt x+1\right)\\&=-\frac1{-2}\times1\\&=\frac12.\end{align}Therefore, the limit that you're after is $\sqrt{1/2}$.
Answer: $$\lim_{x \to 0^+} \frac{3x + \sqrt{x}}{\sqrt{1- e^{-2x}}} =\lim_{x \to 0^+}\frac{\sqrt{x}}{\sqrt{1- e^{-2x}}} \cdot(3\sqrt{x} + 1) = \lim_{x \to 0^+} \sqrt{\frac{x}{1- e^{-2x}}} \cdot\lim_{x \to 0^+} (3\sqrt{x} + 1)$$
$$\lim_{x \to 0^+} \sqrt{\frac{x}{1- e^{-2x}}} = \lim_{x \to 0^+} \sqrt{\frac{-2x}{(2)( e^{-2x} -1)}}= \frac{1}{\sqrt{2}}$$
Answer: $$\sqrt{1-e^{-2 x}}\sim \sqrt{2} \sqrt{x};\;\text{as }x\to 0$$
$$\lim_{x \to 0^+} \frac{3x + \sqrt{x}}{\sqrt{2} \sqrt{x}}=\lim_{x \to 0^+}\left(\frac{3}{\sqrt 2}\sqrt x +\frac{1}{\sqrt 2} \right)=\frac{1}{\sqrt 2} $$


What is proper way to update D8 DEV?

Question: I'm not having any luck with Drush (just hangs) to update a (non-production) D8 site, dev branch (from around beta2) to Head.  How would one manually update the files db/config?
Comment: See the comment chx left in the other question.
Answer: The proper way is "not".
Upgrade path is not supported and not possible.
Comment: Didn't we have a beta1 -> beta2 question about this already? I was trying to find it so we can close dup, but I can't locate it.
Comment: There were a few already yes, the last one only two days ago: http://drupal.stackexchange.com/search?q=%5B8%5D+upgrade+is%3Aquestion
Answer: Use documentation provided by Drupal on THIS link. I'm did core upgrade by following steps from this document.

What is proper way to update D8 DEV?


Calculate curvature necessary for line segment to cover given X-axis distance

Question: (This is very similar to my previous question. In fact, I feel I probably have all the answers there, but I don't quite know how to apply them in this new problem. I'm essentially trying to solve the same problem as in the linked question, but on the X axis, rather than the Y axis.)
Consider a line segment of known, fixed length, being curved into an arc:

Imagine these lines are exactly the same length. The rate of curvature for each is constant (they are circular arcs). Observe that as the degree of arc increases, the horizontal distance covered by the arc increases.
My question is twofold:

Given a fixed arc length, how can I calculate the amount of curvature needed to reach a given width?

How can I determine the maximum width a line of a given length could arc in this manor? (This would be the upper limit of the function requested above. By my testing, it seems that after ~110°, the arc begins to grow narrower and continues shrinking as the angle increases. I would need to know the maximum width of a of my arc length to determine if a given horizontal distance was within reach in the first place.)

Let me know if anymore information is needed or if you need anything clarified. I'm not the best at reading mathematical formulas, so I can only hope you'll be patient with me if I have questions. Thank you for your time.
Answer: Assuming the line segment is originally along the $y$-axis, extending between $(0,0)$ and $(0, L)$.
Next the linear segment is bent to form an arc, whose subtended angle at the center of the arc is $\theta$, and the radius of the arc is $r$
Then the equation of points on the arc is
$ p(\alpha) = (r, 0) + r (-\cos(\alpha), \sin(\alpha) ) $
where $0 \le \alpha \le \theta $.
From the length, we know that
$ r \theta = L $
Therefore,
$ p(\alpha) = \dfrac{L}{\theta} ( 1 - \cos(\alpha), \sin(\alpha) ) $
Scanning the values of $\alpha \in [0, \theta]$, we find the range of values of the $x$ coordinate of $p(\alpha)$.
Now $(1 - \cos(\alpha))$ is increasing over $[0, \pi]$ and decreasing over $[\pi, 2 \pi]$.  Therefore, for $0 \le \theta \le \pi $, the horizontal distance covered is
$ X_{Max} = \dfrac{L}{\theta} (1 - \cos(\theta) )  $
And for $ \pi \le \theta \le 2 \pi $
$ X_{Max} = \dfrac{2 L}{\theta} $
This piecewise-defined function is plotted using Desmos and shown below

So, given a certain $ \dfrac{X_{Max}}{L} $, one should be able to find the corresponding value of $\theta$.  In many cases there will be two possible value for $\theta$, in which case, one can choose the minimum of the two.
To automate this, you have to find the peak point of the function $\dfrac{(1 - \cos(\theta)) }{\theta} $, and this can be done numerically using Newton's method, applied to the derivative.  Once the peak is found, lets say it is $(\theta_1, Y_1)$, then given any $ 0 \le y \le Y_1$ one would be able to find the values of $\theta$ that result in $f(\theta) = y $, using simple numerical techniques, such as bracketing, combined with Newton's method, which is very robust.
The details are as follows.
Let $f(\theta) = \dfrac{ 1 - \cos(\theta) }{\theta} $, then the derivative is
$ f'(\theta) = \dfrac{ sin(\theta)\theta + \cos(\theta) - 1}{\theta^2} $
Setting $f'(\theta) = 0 $ we want to find the solution of
$ \sin(\theta) \theta + \cos(\theta) - 1 = 0 $
And this can found using Newton's method applied to
$g(\theta) = \sin(\theta) \theta + \cos(\theta) - 1 $
whose derivative is
$ g'(\theta) = \cos(\theta) \theta $
Here's the code I used to find $\theta_{peak}$
Public Function theta_peak() As Double
Dim g, gp As Double

' Find t such that g(t) = 0

' g(t) = t sin(t) + cos(t) - 1

' derivative gp(t) = t cos(t)

p = WorksheetFunction.Pi()

lconverged = 0

t =  1.2 * p / 2

For i = 1 To 100

g = t*sin(t) + cos(t) - 1

gp = t*cos(t)

If Abs(g) < 0.00000001 Then
   lconverged = 1
   Exit For
End If

dt = -g / gp

If Abs(dt) < 0.00000001 Then
   lconverged = 1
   Exit For
End If

t = t +  dt

Next i

If Not (lconverged = 1) Then
   MsgBox ("did not converge")
   Exit Function
End If

theta_peak = t

End Function

The angle returned by this function is approximately $2.3311 \text{  radians} $ (equivalent to $133.56^\circ$)
Now you should calculate the maximum value of $\dfrac{W}{L}$ as
$\bigg(\dfrac{W}{L}\bigg)_{Max} = Y = f(\theta_{peak}) $
where $f(\theta) = \dfrac{1 - \cos(\theta)}{\theta} $
Looking at the graph given above, we know that for $ 0 \le y \le Y $ there will always be at least one solution for $f(\theta) = y $.  Moreover, one can say that for $ 0 \le y \le \dfrac{1}{\pi} $ there will be only one solution $\theta$ and that solution satisfies $0 \lt \theta \lt \theta_{peak}$.  While if $ \dfrac{1}{\pi} \lt y \lt Y $ , then we will have two solutions, one being less than $\theta_{peak}$ and one greater than $\theta_{peak} $.
The following subroutine and the function that follows find the values of the solutions (whether it is one or two solutions).
Public Sub Find_Thetas(W2L, t1, t2, n )

t0 = theta_peak()

Ypeak = (1 - cos(t0))/t0

If W2L > Ypeak Then

n = 0
Exit Sub

Elseif Abs(W2L - Ypeak) < 1E-5 Then

n = 1
t1 = t0

Exit Sub

Endif

' now there will one solution t1 < t0 and another solution
' t2 > t0

t1 = t0 - 0.2
t1 = Find_Single_Solution( W2L , Ypeak , t1 )

t2 = t0 + 0.2
t2 = Find_Single_Solution( W2L , Ypeak, t2)

n = 2

End Sub

Public Function Find_Single_Solution( W2L, Ypeak, t ) As Double

'   we want to solve  (1 - cos(t)) / t = W2L  or  2 / t = W2L
'   The function f(t) = W2L t + cos(t) - 1  for 0 < t < pi
'   and f(t) = t W2L - 2

p = WorksheetFunction.Pi()

For i = 1 To 100

If t < p then
f = W2L*t + cos(t) - 1

fp = W2L - sin(t)

Else

f = W2L*t - 2
fp = W2L

Endif

If Abs(f) < 0.00000001 Then
   lconverged = 1
   Exit For
End If

dt = -f / fp

If Abs(dt) < 0.00000001 Then
   lconverged = 1
   Exit For
End If

t = t +  dt

Next i

If Not (lconverged = 1) Then
   MsgBox ("did not converge")
   Exit Function
End If

Find_Single_Solution = t

End Function

Comment: Thank you very much (*again*) for offering your help on this. To make sure I understand correctly: there is no non-iterative formula which can be used to calculate the angle I require, right? I need to use Newton's method to find the peek, and then again to find the angle for the given x which is below that peak?
Comment: Yes.  That's correct.
Comment: I was lucky enough last time that you had an implementation of Newton's method for my scenario that you could share. If you have that this time too, I'd be very thankful if you'd share it, since I don't like my chances trying to figure it out myself with my level of mathematical understanding. Either way, I'm glad you pointed me in the right direction.
Comment: Sure.  Check my updated solution.
Comment: btw, by "multi-valued function" for $X_{\max}$ you probably meant "piecewise-defined function".
Comment: Yes.  You're right, that's what I meant.
Comment: Your VBA function `theta_peak()` always shows the "did not converge" message (even with 100000000 iterations).
Comment: I don't have that problem with my implementation.
Comment: I opened a blank workbook, copied the code for `theta_peak()` from here without any changes, and ran it. I did this on two different machines. Neither converged. Are you sure your code is exactly what you posted here? I notice that I *do* get your result if I change `t =  p / 2` to `t =  p`. Google and Desmos both show that `p/2*cos(p/2)` = 0, which *should* lead to a divide by zero error, but Excel's floating point inaccuracies instead give a very small number (E-17). Using `t =  p / 3` and `t =  p / 4` each give different results.
Comment: Sorry, my bad, the initialization should not be $\text{p/2}$ because the derivative is zero there, so I've actually corrected it in my own code to $ \text{1.2 * p / 2 } $, and it did work.  I just forgot what I did, that's why I thought it was working as was given in the solution.
Comment: Hopefully this should be the last question, just trying to figure out how to apply your solution to my original problem. Let's say I have `W` as the amount of horizontal distance I'm trying to cover, and `L` as the length of the arc. Keeping in mind that I *only* care about calculating curves that are < peak in the graph you created, and assuming I've already limited `W` into that range, how do I feed the variables `W` and `L` into your function(s) to get out the single angle I need?
Comment: Compute $W2L = W/L$ and input that to the function 'Find_Thetas'.  When the function returns, if n=0 then there are no solutions.  If n=1 or n=2, then take t1 as your angle, and disregard t2.


If $b=8q+k$, what are the values of $c$ and $r$ if $8b-75=8c+r$?

Question:
If the quotient and the rest of the integer division between $b$ and $8$ are $q$ and $k$, respectively, what are the values of the quotient and rest of division between $8$ and $8b-75$?

Work:
If the quotient and the rest of the integer division between $b$ and $8$ are $q$ and $k$ it means $$b=8q+k.\tag{1}\label{1}$$ Let $c,r\in\Bbb{Z}$ be the rest and division between $8$ and $8b-75$ i.e., $$8b-75=8c+r.\tag{2}\label{2}$$
From $\ref{1}$ we observe that $$8q=b-k\implies8\mid(b-k)\tag{3}\label{3}.$$ From $\ref{2}$ we observe that $$8b=8c+r+75\implies8\mid(8c+r+75)\tag{4}\label{4}.$$
$\ref{3}+\ref{4}$ means $$16\mid(8c+r+75+b-k)\tag{5}\label{5},$$ and now I am stuck here.

Also I tried: plugin $\ref{1}$ into $\ref{2}$ we get $$8(8q+k)-75=8c+r\implies64q+8k-75=8c+r\implies\text{???}$$

Am I following the right steps?
Comment: I think you have (2) the wrong way round. Should it not be $8=(8b-75)c+r$?
Comment: @tomi probably. I get confused all the time with this kind of statements.
Answer: By $(1)$ and $(2)$ you have that $$8b-75=8(8q+k)-75=8(8q+k-10)+5.$$ So we get that $$c=8q+k-10, \ r=5$$because $0\leq 5<8.$


Using an admin account as the sender for an action rule instead of site:current-user

Question: I am using a reaction rule that triggers, when a new user is registered. This rule sends a private message to a role ( service-role ).
The sender of the message is the actual logged in user - in this case the user that was just created, the new user.
I want the sender to be the admin but I have no change to select the admin the the data-selection field. How can I archive any other user that the actual logged in user?
Answer: I was able to select the wanted sender User by typing in the USER ID when the form is in direct input mode. To get to this "direct input mode", use the button "switch to direct input mode", as shown here:

After doing so, the form will look like so:

So in the end, the result of doing so is that if you read your private messages, then the sender is not the new user anymore, but the user you selected by ID manually (as shown in the above form).
Comment: Please review my attempt to further improve your answer (eg I also integrated the 2nd screenprint you linked to, but which didn't show up yet). Feel free to further adapt/refine, or just perform a rollback to the original version of your answer if you don't like my edit at all. OK?
Comment: Sorry for my short answer. I can't find the image anymore. All I like to add is that it is not only working for the id number one, the admin. You can choose any valid user id, but you have to be in direct edit mode.
Comment: I hope other users can use this if they want to send a private messages to a role and need a specifiy sender. In my case people with the role service recieve the message and in case of technical problems reply directly to the admin and not to the new user.
Comment: About the image you cannot find anymore: the first version of your answer included a hyperlink to a 2nd screenprint (without showiing the screenprint). My edit only transformed that in the (first) image shown in your answer now (it's the same image). And yes it's working for any userid you'd enter (cfr the "be aware" in my own answer for more details).
Answer: If you don't find what you're looking for, you could try to use the Switch to the direct input mode button and then enter the userid of the admin.
That's a kind of "hardcoding" one may say, but at least it is "a" way to use what you're asking for.
Be aware: that userid to be entered can be an identifier of just any userid (so if the userid entered is not a user who is "the admin" (as in your question), that should work too.
Comment: Thank you, yes there is another display, but it will not change my question. Maybe I have to create a condition to reach the depth I want. Unfortunably I don't know the condition that is necessary.
Comment: @Katasun : What do you mean by "***yes there is another display***, which display do you mean? Also, why did you write "***it will not change my question***"? Moreover, I don't see how adding whatever "condition" would help you. Please try explaining your prior comment again.
Comment: Could you please verify my answer. If you are in the direct input mode, please type in a valid user id. This will be the sender of the message then.


Acoustic guitar to a macbook?

Question: First I want to say that I am totally sorry for my incompetence, but I have tried googling this and nothing came up.
So, I got my hands on an acoustic guitar and it has an output on the bottom of the body. The cable has an 1/4" audio jack and I bought an adapter to make it fit in my macbook. My question is, in order to record sound from the guitar, do I need any other devices like an amplifier or anything?
In GarageBand preferences it says 0 MIDI devices found and I can't choose anything else besides my built-in mic and also I can't hear any sound from the built-in speakers when the guitar is plugged in.
That sums it up, thanks!
Comment: This really belongs on the Audio-Video Production site. You may find this useful: [How to hook up guitar to Mac Pro?](http://avp.stackexchange.com/questions/726/how-to-hook-up-guitar-to-mac-pro)
Answer: First, you need to understand the difference between MIDI, digital audio and an analogue electrical signal.
MIDI is a sequence of instructions like "start playing middle C at volume 200", "stop playing middle C", "shift the pitch +3" and so on. MIDI is generated by things like keyboards and sequencers, and understood by things like synthesisers and drum machines; what GarageBand calls "software instruments". It's probably not relevant to your guitar.
An analogue electrical signal is what comes out of a microphone, an electric guitar, or the transducer in your electro-acoustic guitar. It's simply a continuously varying voltage, going up and down in the same way as the sound waves that you eventually want to hear.
A digital audio signal is the computer's representation of the analogue signal - the analogue signal "sampled" into a sequence of numbers.
What you are asking, is how to convert the analogue signal from your guitar into the digital audio signal your computer needs.
Note that what you have is an electro-acoustic guitar. If it was just an acoustic guitar, it would not have any kind of socket.
First, make sure the transducer in your guitar works. A transducer is a lot like a microphone or pickup, except that it detects vibrations in the surface it is attached to, instead of having its own diaphragm or detecting vibrations in metal strings. Borrow an amplifier, plug your guitar into it, and verify that sound plays from the amp. Like microphones and pickups, some transducers are "active" and need a battery. Others are "passive" and don't need a battery. If there is no obvious battery compartment, it's likely yours is passive.
Next, you need a suitable socket in your computer. There are a few options here:

If your computer has a microphone socket, you can use that. It may not be ideal, but it will work
If your computer has a line-in socket, you can use that. However, the signal from a transducer/microphone/pickup is too quiet for a line-in. You need to first amplify the signal to line level. There are several options for this. Anything that can drive headphones is good enough -- a pocket practice amp, a multi-fx pedal etc.
If your computer has no built in audio input, you can add one. You can fit internal sound cards to desktop systems, or you can get USB sound interfaces. The Griffin iMic is a compact and affordable USB option. You can pay more for fancier interfaces with more inputs, professional connections (such as balanced microphone sockets), better sound quality etc.

Before trying to use these inputs in a program such as GarageBand, check that they work in the OS's control panel. This varies depending on your OS, but in both Mac and Windows, there are sound control panels where you can select an input, and watch a signal bar respond to the sound you make.
Once you know it is working, and you know the name the OS is using for the input your guitar using, telling your music application to use it should be straightforward.
Hint: in GarageBand, choose either "electric guitar" or "real instrument". Even though your instrument is electro-acoustic, follow the GarageBand help pages for an electric guitar.
Comment: Thanks a lot, I think I understand it now. I will try tonight to plug the guitar in the line-in of my desktop PC and see if it works or not. If it doesn't work, you say that I should try to amplify the signal? I have a headset with something like a box which has line-out and mic (or line-in) ports. Can I use that to amplify the guitar?
Comment: Your "something like a box" sounds like it should work, although I can't promise great quality.
Answer: Acoustic guitars aren't generally MIDI devices, but your computer should recognize that something is connected to the microphone jack.  Mic jacks are amplified so you wouldn't want to amplify the guitar before connecting it to the mic jack.  Laptops don't normally have Line In ports, but they are unamplified.
You'll need to have a battery in your guitar, usually there's a slot in the top of the body with a button and LED you can use to test if it's got enough charge.  Once that's working you should also ensure that the cable is working and that you properly convert from stereo to mono or vice versa if need be.  I would suspect both ports (guitar + computer) are mono so in that case you would ensure you're using mono cables and that the size converter is also mono to mono.  However it appears that (some) Macbooks have combined ports, so in that case it's probably stereo.  Perhaps that post can help you figure it out.
Then ensure OSX is detecting the microphone.  I don't use a Mac so unfortunately I can't help with that, but there should be Sound Properties or something similar in the OS settings where you can view input levels and so on.
Comment: Well, my guitar has two control sliders on the top - one for volume and one for passive tone control, but there isn't a slot for a battery, LED light or a button. As far as the cable, it's brand new, so I assume that It's working, as well as the adapter. But in the store they asked me if I wanted a stereo adapter or mono, and since it's going to go in a computer, I said stereo.
Comment: @NikolayDyankov Hmm, maybe the battery's inside?  My acoustic's a little strange so I'm not sure where else to look.
Comment: Don't make me unscrew the bolts, please :)
Comment: @Nikolay Make and model of your guitar?  Maybe we can help you find it =)
Comment: It's a HOHNER HC06E. Btw, just found out that I don't have line-in port for my macbook, haha. But same problem on my PC, so the question still goes :)
Answer: Nikolay - you need an MAudio guitar connector for your macbook. It has USB to your computer, and guitar 1/4" plug in, which you need to connect an acoustic guitar pre-amp to, and either a mic or a pickup on your guitar.

Acoustic guitar to a macbook?


Longest uninterrupted session in a single football game

Question: What is the longest duration over which a football game ran in which there was no foul or ball going out of court?
Basically game went on without any interruptions.
Which game and how long was the duration?
I am interested in country vs country matches or national level club games.
Answer: From this Quora thread:

I remember this particular phase in a Premier League game involving
  Manchester United and Blackburn which ended 1–1. Manchester United
  played around 10 minutes(!) of uninterrupted football - aimlessly
  passing the ball at the back as a draw was enough for them.

Youtube link


T-test p-value from lm() function does not equal t.test() function in R

Question: I thought the the following code in R should run equivalent t-tests. But the p-value obtained from each method differs. The p-value using lm() is 3.415937e-05 but using t.test() it is 0.0001098368.
Why are p-values different?
<code>summary(lm(mpg ~ vs, mtcars))$coefficients -> coefs

as.vector(coefs)[8] -> lm_pvalue

t.test(mpg ~ vs, mtcars)$p.value -> ttest_pvalue
</code>
Comment: Also see [Is the t-test miscalibrated in R?](https://stats.stackexchange.com/q/593170/237901). This thread explains what's going on with the t-test.
Comment: Or even just read the help on `t.test`  (`?t.test`) in R, which also explains what the function does and how to get it to do what you wanted instead (see the discussion in the description of the  `var.equal` argument)
Answer: If you call t.test and set var.equal = TRUE I think you will find that the outputs agree. By default t.test does the Welch method which allows for the variances to vary. In fact the values of t are not that different but do give rise to the p-values you quote.


Swift SearchBar inTableView doesn't show the correct Data in the filtered rows

Question: My app is using Firebase Realtime Database to store information of each user. The tableView works fine. I added a searchBar and when I type letters in the searchBar, I can see that the amount of rows presented in the tableView is equal to the amount of users which contain these letters in their names. The problem is that the rows presented in the tableview (after typing letters in the search bar), contain the information of the first user till x user (x = amount of users which contain these letters in their names).
import UIKit
import FirebaseDatabase
import Firebase

class VideoListScreen: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    var blogPost: [BlogPost] = []
    var searchBlogPost = [BlogPost]()
    var searching = false

    override func viewDidLoad() {
        super.viewDidLoad()

        blogPost = []
        createArray()
        tableView.delegate = self
        tableView.dataSource = self

    }

    func createArray() {
        let ref = Database.database().reference().child("Users")

        ref.observe(.childAdded, with: { (snapshot) in
            if let postDict = snapshot.value as? [String : String] {
                let post = BlogPost(name:postDict["name"] ?? "" , gaf: postDict["gaf"] ?? "", place: postDict["place"] ?? "", phone: postDict["phone"] ?? "", notes: postDict["notes"] ?? "", elsertext: postDict["elsertext"] ?? "")

                self.blogPost.append(post)
                self.tableView.reloadData()
            }
        })
    }
}

extension VideoListScreen: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching{
            return searchBlogPost.count
        }else{
           return blogPost.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let blogp = blogPost[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Tavla") as! Tavla
        if searching{
            cell.setBLogPost(blogPost: searchBlogPost[indexPath.row])
        }
        else{
            cell.setBLogPost(blogPost: blogPost[indexPath.row])
        }
        cell.setBLogPost(blogPost: blogp)
        return cell
    }
}

extension VideoListScreen: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchBlogPost = blogPost.filter({$0.name.prefix(searchText.count) == searchText})
        searching = true
        tableView.reloadData()
    }
}

I Believe the problem is in the if and else statments in this function:
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let blogp = blogPost[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "Tavla") as! Tavla
    if searching{
        cell.setBLogPost(blogPost: searchBlogPost[indexPath.row])
    }
    else{
        cell.setBLogPost(blogPost: blogPost[indexPath.row])
    }
    cell.setBLogPost(blogPost: blogp)
    return cell
}

Answer: You have extra cell.setBLogPost(blogPost: blogp) in your delegate methode
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let blogp = blogPost[indexPath.row]
      let cell = tableView.dequeueReusableCell(withIdentifier: "Tavla") as! Tavla
      if searching{
          cell.setBLogPost(blogPost: searchBlogPost[indexPath.row])
      }
      else{
          cell.setBLogPost(blogPost: blogPost[indexPath.row])
      }

      return cell
  }

I think this will solve your problem and you can use
    import UIKit
import FirebaseDatabase
import Firebase

class VideoListScreen: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    var blogPost: [BlogPost] = []
    var searchBlogPost = [BlogPost]()

    override func viewDidLoad() {
        super.viewDidLoad()

        blogPost = []
        createArray()
        tableView.delegate = self
        tableView.dataSource = self

    }

    func createArray() {
        let ref = Database.database().reference().child("Users")

        ref.observe(.childAdded, with: { (snapshot) in
            if let postDict = snapshot.value as? [String : String] {
                let post = BlogPost(name:postDict["name"] ?? "" , gaf: postDict["gaf"] ?? "", place: postDict["place"] ?? "", phone: postDict["phone"] ?? "", notes: postDict["notes"] ?? "", elsertext: postDict["elsertext"] ?? "")

                self.blogPost.append(post)

                self.searchBlogPost = self.blogPost
                self.tableView.reloadData()
            }
        })
    }
}

extension VideoListScreen: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return searchBlogPost.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let blogp = searchBlogPost[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "Tavla") as! Tavla
        cell.setBLogPost(blogPost: blogp)
        return cell
    }
}

extension VideoListScreen: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if ((searchText.trimmingCharacters(in: .whitespaces).isEmpty) {
          searchBlogPost = blogPost
        } else {
          searchBlogPost = blogPost.filter({$0.name.prefix(searchText.count) == searchText})
        }

        tableView.reloadData()
    }
}

I hope this will helps.


Whining noise from one piano key

Question: I recently bought a 2nd-hand upright piano and had it tuned after a couple of weeks. The tuner (who came well recommended) says he got it up to concert pitch.
However I noticed one key in particular - about an octave and a half about middle C - causes a nasty whining buzz. It's reminiscent of a dentist drill almost. The note itself seems in tune and opening the lid doesn't make it stop (I thought it could be a buzz).
What could cause this? It's maybe only noticeable to the player but it's a key that gets a lot of use. Could it be a tiny issue in the tuning between the strings on that key - it seems too high-frequency to me personally? Or does it suggest something is loose?
The tuner man did say that it's really only when he does a 2nd tuning on a piano he can see which strings have particular issues (which pegs slip, etc) and I'm loath to get him out just for this one issue.
Comment: What a great opportunity to play in a different key!!!
Comment: Ha, sadly it's one that is used in many keys and I'm only a beginner so transposing on the fly might be a bit of a struggle :)
Answer: There's a possibility of something touching the string; either some foreign body dropped in there & wedged against it, or even part of the mechanism touching the string.
I'd recommend visual inspection first.
Grab a torch, get the front off & go have a look.
Very gently wiping down the length of the string with a lint-free cloth may help - be extremely careful as you go past the dampers not to knock anything.
Comment: By *torch* I assume you mean what I call a flashlight and not a flaming stick ;)
Comment: Yeah. We don't do 'flashlights' here. Same word covers both.
Answer: This type of noise can be hard to track down, because it might not be coming from the piano at all. It could be almost anything in the room resonating at the pitch of the note. If your piano tuner changed the pitch, that's enough reason why the problem only started after the tuning.
it's very hard to hear the direction the sound is really coming from, and if you are playing the piano, your brain will assume it is coming from the instrument. Get one person to keep playing the note while somebody else walks around the room and checks out every hard object that might be rattling, before you assume it's coming from the piano. When you get close to the source (i.e. your head is only a foot away from it) it should be apparent where the sounds is really coming from.
Any glass, ceramic, metal, or similar object in the room (including things like glass panels in the door) is a possible cause. The weirdest one that I've encountered was a light bulb!
Comment: Interesting point. It does sound like the kind of noise you get when a cup is sitting slightly crooked on a glass table and the TV/washing machine causes it to rattle at a very high pitch. Worth some investigation.
Answer: Something rattling or resonating.  Or just a bad string.  It happens.
Did you watch the piano tuner at work?  Remember how he used felt or rubber wedges to damp two of the three strings of each note so he could concentrate on tuning each one seperately?  You could do the same to pin the noise down to one string.
Answer: You need to let the piano settle into its new environment before a second tuning. If the first tuning got it into concert pitch, it was already in tune from its last owner (my spinet took two tunings, 6 months apart to get it up to pitch after being neglected for 8 years)
If nothing is touching the strings as others have suggested, a miniscule difference in tunings of the strings could cause a discordant sound as you suspect. You may need to put up with it until the instrument settles and you can have your second tuning.
Answer: If you don't notice a foreign object upon visual inspection, the pin that holds the string in place may have come loose, often this causes a muffled or tinny sound. Your piano tuner should be able to repair it by hammering the pin more firmly in place.

Whining noise from one piano key


drop - down menu using JS onclick - what is wrong?

Question: Just learing JS. I have created 3 dropdown menu with different choices and added JS function. HTML and CSS seems to be right. I am concerned about my JS, because it just does not work. Is the even right for that purpose? I am not sure if I use ".this" in the right place.
I would really appreciate any hints!
my JAVASCRIPT:

document.addEventListener("DOMContentLoaded", function() {
console.log("DOM fully loaded and parsed");

var arrow= document.querySelectorAll(".list_arrow");
var panel= document.querySelectorAll(".list_panel");

for (var i= 0; i < arrow.length; i++) {
  arrow[i].addEventListener('click', function showDiv(event) {

    if (panel.this.style.display == 'none') {  //panel(this.style.display=='none')?
        panel.this.style.display = 'block';
    }

    else {
        panel.this.style.display = 'none';
    }
  });
}

  });

HERE IS MY CSS
.form {
  margin-top:50px;
}
.drop_down_list {
  border:1px solid #8de0d2;
  width: 280px;
  height:38px;
  background-color: white;
  margin-top:22px;
  padding: 8px 12px;
  position: relative;
}

.list_label {
  font-size: 30px;
  color: #e2e2e2;
  font-family: 'ralewaylight', Arial, Tahoma, sans-serif;
}

.list_arrow {
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 15px solid #24baa0;
  display:block;
  position: absolute;
  right: 14px;
  top: 20px;
  cursor: pointer;

}

.list_panel {
  background-color: white;
  border: 1px solid #ccc;
  width: 288px;
  padding-left: 15px;
  padding-bottom: 10px;
  list-style: none;
  margin: 0;
  left: 0px;
  z-index: 2;
  position: absolute;
  top: 54px;
  display:none;
}

.list_panel li {
  margin-top:10px;
  cursor: pointer;
  color: #585858;
}

                      Choose a chair

Clair

Margarita

Selena

                      Choose color

red

black

orange

                      Choose material

a

b

Answer: The this keyword refers to the current scope. It is of no use in the state you are using it. What I suggest is to locate the list_panel that is associated with the clicked arrow. There are numerous ways to do that, but you can use the following:
Note that I also added default display-none classes so that they get shown on the first click (this wasn't the case).

document.addEventListener("DOMContentLoaded", function() {
console.log("DOM fully loaded and parsed");

var arrow= document.querySelectorAll(".list_arrow");

for (var i= 0; i < arrow.length; i++) {
  arrow[i].addEventListener('click', function showDiv(event) {

    // Find the panel associated with the clicked arrow.
   var parent = event.target.parentNode,
       currentPanel = parent.children[2];

    if (currentPanel.style.display == 'none') {
        currentPanel.style.display = 'block';
    }

    else {
        currentPanel.style.display = 'none';
    }
  });
}

  });</script>
.form {
  margin-top:50px;
}
.drop_down_list {
  border:1px solid #8de0d2;
  width: 280px;
  height:38px;
  background-color: white;
  margin-top:22px;
  padding: 8px 12px;
  position: relative;
}

.list_label {
  font-size: 30px;
  color: #e2e2e2;
  font-family: 'ralewaylight', Arial, Tahoma, sans-serif;
}

.list_arrow {
  width: 0;
  height: 0;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
  border-top: 15px solid #24baa0;
  display:block;
  position: absolute;
  right: 14px;
  top: 20px;
  cursor: pointer;

}

.list_panel {
  background-color: white;
  border: 1px solid #ccc;
  width: 288px;
  padding-left: 15px;
  padding-bottom: 10px;
  list-style: none;
  margin: 0;
  left: 0px;
  z-index: 2;
  position: absolute;
  top: 54px;
  display:none;
}

.list_panel li {
  margin-top:10px;
  cursor: pointer;
  color: #585858;
}

                      Choose a chair

Clair

Margarita

Selena

                      Choose color

red

black

orange

                      Choose material

a

b

Answer: You may want to try using jQuery to help you with show() and hide() functions, though it is said that you might not need it :P
I don't understand the declaration of panel.. Thus I cannot go along panel.this.  My solution is attached here:
http://codepen.io/anon/pen/akXqwA
The main problem is that, during the for-loop, the i will end at the value 3.  When the event is triggered, i will always be 3, and I cannot access the panel with panel[i].
So I made a "hack" around it, by getting its nextElementSibling and changing its style.display.  Also, I have initialised the value with the HTML (style="display: none;").  If you removed that part, the first click on the arrow will not show the items as the style.display value is not "none".  There is a way to avoid changing that in HTML: try playing with the line ;)
Answer: Check this:
document.addEventListener("DOMContentLoaded", function() {
      console.log("DOM fully loaded and parsed");

      var arrow = document.querySelectorAll(".list_arrow");
      var panel = document.querySelectorAll(".list_panel");

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

        arrow[i].addEventListener('click', function showDiv(event) {
          var ulelm = this.parentNode.querySelector("ul");

          if (ulelm.style.display == 'none') {
            ulelm.style.display = 'block';
          } else {
            ulelm.style.display = 'none';
          }
        });

      }

    });

working example is here.


Network outage - Mapping, Checking network, BGP, Traceroute, RIPE

Question: At first, I'm not able to name my question properly, so this will be adjusted

I recently experienced an international network gap. Mean when some part of world wide network is unavailable.
I'm able to find out using ping,traceroute,nmap tools where the gap occurs and where are my requests thrown away or discarded.
example of recent gap:
traceroute to 184.108.40.206 (220.127.116.11), 64 hops max, 52 byte packets
 1  comtrend.home (10.0.0.1)  3.934 ms  0.860 ms  0.775 ms
 2  188.8.131.52 (22.214.171.124)  24.264 ms  24.790 ms  23.823 ms
 3  188.8.131.52 (188.8.131.52)  25.447 ms  25.848 ms  26.754 ms
 4  184.108.40.206 (184.108.40.206)  34.816 ms  27.087 ms  27.312 ms
 5  184.108.40.206 (184.108.40.206)  29.056 ms  27.352 ms  43.560 ms
 6  ae0-0-grtprach1.red.telefonica-wholesale.net.7.16.84.in-addr.arpa (22.214.171.124)  25.538 ms  26.177 ms  25.337 ms
 7  xe3-3-0-0-grtpartv1.red.telefonica-wholesale.net.121.142.94.in-addr.arpa (188.8.131.52)  45.752 ms
    xe-4-0-0-0-grtpartv2.red.telefonica-wholesale.net.121.142.94.in-addr.arpa (220.127.116.11)  104.951 ms  46.658 ms
 8  xe7-0-0-0-grtparix1.red.telefonica-wholesale.net (184.108.40.206)  44.561 ms
    xe7-1-6-0-grtparix1.red.telefonica-wholesale.net (188.8.131.52)  48.202 ms
    xe0-3-0-0-grtpartv2.red.telefonica-wholesale.net (18.104.22.168)  47.801 ms
 9  xe7-0-0-0-grtparix1.red.telefonica-wholesale.net (18.104.22.168)  44.551 ms
    cogent-0-0-0-0-grtparix1.red.telefonica-wholesale.net (126.96.36.199)  288.925 ms
    cogent-1-0-0-grtparix1.red.telefonica-wholesale.net (126.96.36.199)  158.111 ms
10  cogent-1-0-0-grtparix1.red.telefonica-wholesale.net (18.104.22.168)  198.061 ms
    cogent-7-3-0-grtparix1.red.telefonica-wholesale.net (184.108.40.206)  48.478 ms
    te0-4-0-4.mpd21.par01.atlas.cogentco.com (184.108.40.206)  48.574 ms
11  te0-4-0-4.mpd21.par01.atlas.cogentco.com (188.8.131.52)  50.303 ms
    te0-3-0-5.mpd21.ams03.atlas.cogentco.com (18.104.22.168)  55.350 ms
    te0-0-0-5.mpd21.ams03.atlas.cogentco.com (18.104.22.168)  56.176 ms
12  te0-1-0-5.mpd21.ams03.atlas.cogentco.com (22.214.171.124)  56.409 ms
    te0-2-0-5.mpd21.ams03.atlas.cogentco.com (22.214.171.124)  55.947 ms
    te7-7.mpd01.ams04.atlas.cogentco.com (22.214.171.124)  56.371 ms
13  184.108.40.206 (18.104.22.168)  57.218 ms
    te8-4.mpd01.ams04.atlas.cogentco.com (18.104.22.168)  55.703 ms
    18.104.22.168 (22.214.171.124)  56.929 ms
14  * * *
15  * * *
16  * * *
17  * * *
18  * * *
19  * * *
20  * * *
21  * * *
22  * * *
^C

icmp_echo gave me request timeout, so I traced the request to 18.104.22.168 (which is my VPS)
This last IP 22.214.171.124 is (according to http://www.infobyip.com/) located in Washington DC, USA. Does it mean, that in Washington, they're blocking traffic to this network node or what?

First, I wonder, if we can trace to where and who specific IP was allocated

I tried RIPE DB Query, but I wonder if this is the right way
I know about reverse DNS query, but this is what traceroute does automatically

Second, If there is any world wide network monitoring system, where we can find out if there is any maintenance or network problem

I tried RIPE Atlas, where status of some (every? public?) nodes is displayed on map

Third (from question title), if we can somehow detect why this outage occurred

If it was some kind of bgp routes change or whatever it can be (I honestly don't know what reasons can be there)

Please excuse my language skills, I'm not sure if everything is laid down correctly and clearly. Ask if anything is unclear. Thanks
Comment: also worth pointing out that machines can block traceroute without being down as well
Comment: try traceroute -I (thats cap I for india, not l for lemon)
Answer: Reverse-DNS to gather the 'owner' of an IP really isn't the way to go. The reverse tables are most often not updated by IPs provider and doesn't provide much in term of diagnostic. (This is different in the email world - as filtering rules are often added to determine the validity of reverse lookup).
To get the 'block owner', you should go to the attribution authority. RIPE is only 1 of 5 Regional Internet Registry (RIR). AfriNIC, ARIN, APNIC, LACNIC are the others one. Their WHOIS tables are SUPPOSED to be up-to-date and give you the official owner & some contact informations.
For more in depth investigation, I like ROBTEX (http://www.robtex.com). It shows you the owner (as per their own database) along with its registered peers and AS numbers (required for BGP).
For outage detection, things get a little more tricky as 'Internet' isn't really that 'big homogeneous network' everybody seems to think it is. Your route toward a single IP depend on your upstream and all the peer along the way. Normally, a outage should be automatically detected and 'next available peer' used, but...
The easiest way to detect that kind of problems would be to use "Looking Glasses" (such as http://www.bgp4.as/looking-glasses) to see if you are the only one having problem to route traffic toward that target network.
Comment: thanks, looks like this outage was just malfunctioned switch on the route. Not the one from big nodes, the smaller one on data center side. But I'm going to test suggested tools on next outage (which are quite common in here)
Answer: That last IP (220.127.116.11) is actually not in washington DC.  Providers don't generally register each IP of their backbone devices because when they move links around etc, there's no need to register them.  Also, a lot of the usual tricks for determining location (see where people using that IP ship things to using amazon) don't work for routers - they don't usually buy things.
For Telefonica, the first ISP, you have to decode it a little bit.  Let's go from left to right, with hop 9 as an example.
xe-7-0-0-0-grtparix1.red.telefonica-wholesale.net
xe-7-0-0-0 is an interface name, XE means 10gigabit ethernet on a juniper, and 7-0-0-0 is the slot and port.
grtparix1 is a combination of the router name 'grt' and site 'parix1'.  grt is just noise in this context, but 'parix1' is a hint that this router lives in PARIX, which is a large interexchange site in Paris.
.red. is spanish for network, so that's telling you that's part of the customer/revenue network
and telefonica-wholesale.net is the domain.
Let's try another one.
hop 12:
te0-1-0-5.mpd21.ams03.atlas.cogentco.com
te0-1-0-0-5 is again ten gigabit ethernet (but maybe not a juniper, as it's te vs xe' and the slot and port designation
mpd21 is the particular device name
ams03 is the site name - guessing this is most likely in Amsterdam (from AMS)
and atlas is the 'backbone network' subdomain, with 'cogentco.com' being the large domain'
Unfortunately, every provider has a different scheme, but they generally use some useful code scheme that isn't impossible to figure out - usually 3 or 4 letters.  Some providers use airport codes, and some make up their own.
In order to find out what's wrong, you need to compare a working traceroute with a non-working one.  I traced to the same IP you did and got this at the end:
11  te2-1.mpd01.ams04.atlas.cogentco.com (188.8.131.52)  89.837 ms
te1-7.mpd01.ams04.atlas.cogentco.com (18.104.22.168)  90.029 ms
te4-1.mpd01.ams04.atlas.cogentco.com (18.104.22.168)  93.493 ms
12  188.8.131.52 (188.8.131.52)  94.595 ms  94.891 ms  94.903 ms
13  220.127.116.11 (184.108.40.206)  91.821 ms  90.328 ms  90.380 ms

In this case, the trace succeeded, and all we can tell from your trace above is that yours ended after 188.8.131.52.  Was 188.8.131.52 blocking traffic?  Maybe.  Or maybe 220.127.116.11 was unable to send packets back to you - either because of a failure or because of a misconfiguration.  Remember, traceroutes and pings have to go both ways, and it's not always apparent who is at fault, it can get murky sometimes.


Create a page with database data in a module

Question: I am new to drupal and in a process of developing a custom module. My module will do a couple of things:

(ADMIN) User will be able to select a zip file and upload it
(ADMIN) The module will than take that file, extract it to files folder
(ADMIN) Upload the content from a certain file to the database table
(ADMIN/front end) Create a link/page/node on the front page in navigation where the data will be displayed with some additional js required

I got first 3 things going but I am struggeling with the last one.
Any pointers in the right direction will be much appreciated.
Answer: if all the uploaded Zips contain similar data you could expose the custom table to Views using hook_views_data and then make a View path with a contextual filter to show the content of a given table.
If you really need a link look at the hook_menu function and make a menu entry that loads a custom page ... which can then load a custom View to show your data on a page.


How to print the HTML content of the text field in Drupal 6 programmatically

Question: I am printing the $node->field_abc[0]['value'] in php code where node is node content and field_abc is text field .
How can I print the html format of the field in Drupal 6
Answer: You can use content_view_field

content_view_field : Render a single field, fully themed with label
  and multiple values.

Code
$node = node_load('NODE_ID');
echo content_view_field(content_fields("field_example"), $node, FALSE, FALSE);

Reference

Print a formatted CCK field with PHP
Comment: Just one case How can I prevent the label field in the display of the field??


Como pegar o nome do site?

Question: Imaginem um cenário em que eu possua somente URLs da seguinte forma, cadastradas no meu banco de dados:
https://www.google.com
https://www.facebook.com
https://www.youtube.com
https://www.twitter.com

Pensando nesse caso, e que somente haverão URLs dessa maneira citada, como eu poderia elaborar uma maneira de pegar o nome do site?
Por exemplo, através de regex, quando eu invocar um determinado método, e passar como valor https://www.google.com, ele me devolva somente a string Google?
Answer: function nome_dominio($url)
{
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
    $nome = explode('.',$regs['domain']);
    return ucfirst($nome[0]); // converto primeira letra para maiúscula
  }
  return false;
}

// Exemplos (todos retornam Google):
echo nome_dominio("https://mail.google.com"); // Retorna Google
echo nome_dominio("https://google.com"); // Retorna Google

Comment: Tem alguns problemas, por exemplo o site `http://www.saopaulo.sp.gov.br`, ele retorna `sp` ao invés de `saopaulo`, que é o nome correto. Ele trata saopaulo como subdomínio do `sp`. A solução disso é bem mais complexa, não pode ser *simples* REGEX, a não ser que liste todos os casos e coloque num REGEX.
Comment: Um outro exemplo, `http://meusite.floripa.br`, retorna `Floripa`. Ele é um TDL válido, [veja aqui](https://serverdo.in/ja-pensou-em-ter-um-dominio-floripa-br/).
Comment: @Inkeliz Eu entendo, mas esse código não é universal, serve apenas pra atender os sites no padrão da pergunta, ou seja, _site.com_ ou _site.com.br_.
Answer: Segue um exemplo do regex em JavaScript:

var urls = [
  'https://www.google.com',
  'https://www.facebook.com',
  'https://www.youtube.com',
  'https://www.twitter.com'
];

var $saida = document.getElementById("saida");

urls.forEach(function(url) {
  var nome_site = /(https\:\/\/www.)([^.]+)(.*)/g.exec(url)[2];
  nome_site = nome_site.charAt(0).toUpperCase() + nome_site.slice(1)
  $saida.value = $saida.value + "\n" + url + ': ' + nome_site;
});
textarea {
  height: 200px;
  width: 100%;
}
<textarea id="saida"></textarea>
Answer: A solução mais próxima para todos os casos é muito mais complexa do que um REGEX.
Infelizmente não consegui tornar isto mais amigável,o código final ficou um pouco confuso, mas creio que ainda sim dará para entender e irei explicar todo o processo.

Vantagens (em relação a essa resposta)

Possui maior suporte para todos os tipos de dominios, tais como floripa.br ou adult.ht.
Possui suporte para subdominios públicos, como por exemplo <seusite>.blogspot.com e até <seusite>.s3.amazonaws.com e afins.

Requisitos:
Não é preciso nenhuma extensão, plugin, framework... Somente é preciso que baixe a lista pública de todos os domínios/TLD isso está disponível aqui (https://publicsuffix.org/list/public_suffix_list.dat) e que especifique o local do arquivo na linha mencionada.
Esse documento é atualizado periodicamente.
Código:
function pegaNome($url)
{

    $url = parse_url($url, PHP_URL_HOST);
    if (empty($url)) {
        return false;
    }

    $generico = ['com', 'org', 'net', 'edu', 'gov', 'mil'];

    $lista = array_filter(file('public_suffix_list.dat.txt'));                                             // Download: https://publicsuffix.org/list/public_suffix_list.dat
    $lista = array_merge($lista, ['*']);

    $dominio = explode('.', $url);
    $dominioTamanho = count($dominio) - 1;

    $encontrado = [];

    foreach ($lista as $tld) {

        if (!in_array(substr($tld, 0, 1), ['!', '/', "\n"], true)) {

            $correto = 0;
            $partes = explode('.', $tld);
            $partesTamanho = count($partes);

            foreach ($partes as $i => $pedaco) {

                if (!isset($dominio[$dominioTamanho - $partesTamanho + $i + 1])) {
                    break;
                }

                $pedaco = (array)trim($pedaco);
                $pedaco = $pedaco === '*' ? $generico : $pedaco;

                $correto += (int)(in_array($dominio[$dominioTamanho - $partesTamanho + $i + 1], $pedaco, true));

            }

            if ($correto === $partesTamanho) {
                $encontrado[] = $correto;
            }

        }

    }

    if ($encontrado !== 0){
        rsort($encontrado);

        foreach($encontrado as $encontro){
            if(!empty($dominio[$dominioTamanho - $encontro])){
                return $dominio[$dominioTamanho - $encontro];
            }
        }

    }

    return $url;

}

Explicações:
Arquivo:
O arquivo possui quatro tipos de situações (ignorando espaços em branco):
!tld
*.tld
// tld
tld

O código acima ignora tanto // tld, que são comentários, como também !tld, que não sei o motivo exato.
Caso seja *.tld indica que ele seria net.tld, com.tld por exemplo, na maior parte dos casos.
Verificações:
Quando você pede para verificar um URL, por exemplo https://seusite.blogspot.com é feito exatamente o seguinte:

Usa o PHP_URL_HOST para obter seusite.blogspot.com.
Divide seusite.blogspot.com para seusite, blogspot e com.

Depois, precisamos verificar o é o dominio usado pelo seu website:

Verifica se o último elemento é igual ao ac: com != ac
Verifica se o último conjunto é igual ao com.ac, de forma que:

Compara o penúltimo elemento igual a com: blogspot != com
Compara o último elemento igual a ac: com != ac

Isso se repete por cada linha deste arquivo.
Em determinado ponto vai fazer exatamente:

Verifica se o último conjunto é igual ao blogspot.com:

Compara o penúltimo elemento igual a blogpost: blogspot == blogpost
Compara o último elemento igual a com: com == com

Então irá salvar $encontrado[] = $correto, isso irá armazenar o valor 2, que é o número de partes que o "subdomínio" tem (.blogspot.com = 2, .net = 1, .a.b.c = 3).
Neste mesmo domínio, nas últimas comparações vai fazer:

Verifica se o último elemento é igual ao .com: com === com

Isso também irá armazenar o valor 1 ao $encontrado.
Resultado:
No final pegamos o maior número de $encontrado e então pegamos o nome do dominio baseado nele.
Então se seusite.blogspot.com tem o maior $encontrado como 2 então basta fazer $dominio[count($dominio)-2-1].
Então porque cria uma array? Porque pode ser que informe https://blogspot.com, então ele iria também ser válido nos dois casos, porém o count($dominio)-2-1 seria então -1. Por isso então ele passa para o proximo dominio encontrado, neste caso .com e irá retornar blogspot, normalmente.

Como pegar o nome do site?


Can a pattern synonym have a different type signature in each direction, like numeric literals do?

Question: Consider the numeric literal 1. It has a different type depending on whether it's used on the left or right of the equals sign. In f True = 1, 1 has type Num p => p. But in f 1 = True, 1 has type (Eq a, Num a) => a. Is it possible to create a pattern synonym that works the same way? For example:
pattern LooksLikeFoo :: (Read a, Show a) => a
pattern LooksLikeFoo <- (show -> "Foo")
  where LooksLikeFoo = read "Foo"

That pattern only works if it has both the Read and Show classes, no matter which side of the equals sign it's on. Is there a way to make it have type Show a => a on the left side of the equals sign, but Read a => a on the right side? Non-working pseudo-code:
pattern LooksLikeFoo :: Show a => a
pattern LooksLikeFoo <- (show -> "Foo")
  where LooksLikeFoo :: Read a => a
        LooksLikeFoo = read "Foo"

Comment: No this isn't possible, I know Edward Kmett has wanted this
Comment: I don't think it would be too theory-heavy to implement, but giving good ergonomics would be tricky. Patsyn types are already quite complicated.
Comment: @Iceland_jack If you post that as an answer, I'll accept it. Also, can you include a link in it to where Edward Kmett talked about wanting it?
Answer: This is not possible currently but it has been brought up by Edward Kmett as a possibility a few times, for example: https://www.reddit.com/r/haskell/comments/eqhcgx/comment/fetsa54


Como escolher o o melhor em cada ano de uma coluna no R?

Question: Tenho uma tabela com a eficiencia de cada jogador, o ano da temporada e o nome do jogador. Como posso fazer com que me dê uma tabela final com o melhor jogador (maior eficiencia) de cada ano? Me dando o nome do jogador e sua eficiencia e ano em uma tabela
Answer: Utilizando o pacote dplyr ou data.table é possível fazer isto.

Criando dados:

# dados ficticios
set.seed(1)
df <- data.frame(ano = rep(2015:2018, each = 5),
                 nome = rep(letters[1:4], 5),
                 eficiencia = rnorm(n = 20, mean = 0.6, sd = 0.1))
df

> df
    ano nome eficiencia
1  2015    a  0.5373546
2  2015    b  0.6183643
3  2015    c  0.5164371
. . .
18 2018    b  0.6943836
19 2018    c  0.6821221
20 2018    d  0.6593901

Aplicando o pacote dplyr com top_n:

library(dplyr)

df2 <- df %>%
  dplyr::group_by(ano) %>% # agrupar por ano
  dplyr::top_n(1)          # apenas o melhor (1) em cada ano
df2

> df2
# A tibble: 4 x 3
# Groups:   ano [4]
    ano nome  eficiencia
  <int> <fct>      <dbl>
1  2015 d          0.760
2  2016 d          0.674
3  2017 c          0.751
4  2018 b          0.694

Ou com slice:
df3 <- df %>%
  dplyr::group_by(ano) %>%
  dplyr::slice(which.max(eficiencia))
df3

> df3
# A tibble: 4 x 3
# Groups:   ano [4]
    ano nome  eficiencia
  <int> <fct>      <dbl>
1  2015 d          0.760
2  2016 d          0.674
3  2017 c          0.751
4  2018 b          0.694

Aplicando o pacote data.table:

library(data.table)
dft <- data.table::data.table(df)

df4 <- dft[dft[, .I[eficiencia == max(eficiencia)], by = ano]$V1]
df4

> df4
    ano nome eficiencia
1: 2015    d  0.7595281
2: 2016    d  0.6738325
3: 2017    c  0.7511781
4: 2018    b  0.6943836

Ou com:
df5 <- data.table::setDT(dft)[, .SD[which.max(eficiencia)], by = ano]
df5

> df5
    ano nome eficiencia
1: 2015    d  0.7595281
2: 2016    d  0.6738325
3: 2017    c  0.7511781
4: 2018    b  0.6943836


Access submitted form data in custom callback before hook_mail_alter()

Question: I wan't to alter contact form recipient according to what user chose in one of the dropdown fields of my Contact form.
I implemented hook_form_FORM_ID_alter() in order to add custom submit callback like this
 $form['actions']['submit']['#submit'][] = 'my_custom_callback';

to get submitted data.
I thought I could use State API in my_custom_callback() to store received data temporally and use it's value in hook_mail_alter() but it looks like hook_mail_alter() is called before my custom callback.
This is what the order of callbacks looks like:

Default Submit callback of Contact form;
hook_mail_alter();
my_custom_callback.

I wander if there is any way to change this order to this:

my_custom_callback;
Default Submit callback of Contact form;
hook_mail_alter().
Answer: Why do you need a submit callback at all? The built contact message is available in hook_mail_alter(), you can just access the submitted data there?
This is from a custom project where we did something similar:
/**
 * Implements hook_mail_alter().
 */
function yourmodule_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_message->bundle() != 'feedback') {
      return;
    }

    $recipient_address = $contact_message->get('yourfield')->value;
    if (\Drupal::service('email.validator')->isValid($recipient_address)) {
      $message['to'] = $recipient_address;
    }
  }
}

Answer: I would store the relevant values for sending the mail in a temporary table when my_custom_callback is executed, and then process the data in this table using a cron job or batch job.  Batch would probably be better - gives you the tools to lock records, etc.  You could run the batch using a cron job :)


Limit operations with viscosity solutions

Question: I'm reading the [user's guide to viscosity solutions][1]. In Lemma 4.2 we define $w(x) = \sup\{u(x):u\in\mathcal{F}\}$, where $\mathcal{F}$ is a family of subsolutions to a certain equation. Next we consider the upper-semicontinuous envelope $w^*(x)$ and the lemma claims that $w^*$ is a subsolution as well. So far so good.
Later in section 6, we encounter a similar construction as before. Given a sequence $u_n(x)$ of subsolutions to an equation, we define the 'limit' $\bar{U}(z)=\limsup_{j\to\infty}\{u_n(x):n\geq j, |z-x|\leq\frac{1}{j}\}$, that is, we take the limsup and * operation simultaneously, instead of limsupping followed by * as before. Lemma 6.1 then claims that $\bar{U}(z)$ is a subsolution as well.
My question is, what is the difference between these two constructions; are there examples of sequences of solutions of functions whose 'limits' in the lemma 4.2 sense and the lemma 6.1 sense are different?
Edit: I noticed that in 4.2 we took the sup and in section 6 it is the limsup. I think that doesn't change the core of the question: Let $\mathcal{F}$ be a countable family of subsolutions and replace sup with limsup. The question remains: is simultaneous limsupping and *-ing the same as limsupping followed by *-ing?
[1]: https://arxiv.org/pdf/math/9207212.pdf
Answer: The two operations apply to different objects, so although they share similarities, they are not strictly equivalent in any way I'm aware of. In the Perron method, one has a family of subsolutions $\mathcal{F}$, and it is the pointwise supremum over this family. In the end, one shows that $w(x)$ is a viscosity solution of the equation of interest, and so $w\in \mathcal{F}$, and the supremum is thus attained (and there is no limit).
On the other hand, the limsup operation applies to a sequence of functions. The context here is usually some approximation scheme for the viscosity solution (e.g., vanishing viscosity or finite difference schemes) where there is a natural ordering to the family of functions (e.g., increasing grid resolution, decreasing viscosity parameter).
The two operations indeed share a lot of similarities. They are both based on utilizing the maximum principle to pass to limits within the viscosity solution framework.
EDIT: To answer your edited question, taking the limsup and * separately gives a different operation. Consider the sequence of functions $u_n(x) = 1_{(0,1/n)}(x)$. Then $\limsup_n u_n(x)=0$, but the combined limsup and * operation gives a value of $1$ at $x=0$.
Answer: From what I understand (and recall from working in this area), the constructions are equivalent. It is therefore more convenient to do both steps at the same time.


How can we prove for the solutions of the equation $x^y=y^z=z^a...$?

Question: How can we prove for the solutions of the equation $x^y=y^z=z^a...$? You could natural log all of them and then proceed but I'm kind of confused. How would you solve for the solutions of a simpler case then, for example $x^y=y^z=z^x$? Since I think the problem above might be too hard...
Comment: $x^y=y^z=z^x$ has the solution $x=y=z$. Can you give any solution besides this case? Also you might enjoy reading about the [Lambert function](https://en.wikipedia.org/wiki/Lambert_W_function) which is related to your query.
Comment: Which variables are you solving for? Are the variables natural numbers? Positive real numbers? Complex numbers?
Comment: In the title and in the first sentence are "$z^a$". Do you mean "$z^x$"?
Comment: All positive real numbers. Also my original question was solving for a solution of infinite variables
Comment: How do you prove the solution set is $x=y=z$?
Answer: Consider your simpler case of
$$x^y = y^z = z^x \tag{1}\label{eq1}$$
If any of $x$, $y$ or $z$ is $1$, say $x = 1$, then $z^x = 1$ with $x = 1$ only if $z = 1$ and, likewise, $y^z = 1$ with $z = 1$ only if $y = 1$, so all $3$ values would be $1$. In general, $x = y = z$ is always a solution.
For the case where none of the values are $1$ and not all equal to each other, I assume that $x$, $y$ and $z$ are positive real numbers (I'll leave the cases where any of them may be negative to you) so you can then take the logarithm to any base $\gt 1$ (say the natural one, i.e., to the base $e$) of each value to get
$$y\ln x = z\ln y = x\ln z \tag{2}\label{eq2}$$
Since $\ln a \lt 0 \iff a \lt 1$ and $\ln a \gt 0 \iff a \gt 1$, this shows that all $3$ values of $x, y, z$ are either $\lt 1$ or $\gt 1$. First, assume they are all $\gt 1$ so the values in \eqref{eq2} are all positive. Due to symmetry, WLOG let
$$y \gt z \tag{3}\label{eq3}$$
Thus, \eqref{eq3} shows from the first & second parts of \eqref{eq2} that, since the logarithm function is strictly increasing, that
$$\ln y \gt \ln x \implies y \gt x \tag{4}\label{eq4}$$
Next, \eqref{eq4} means the first & third parts of \eqref{eq2} gives that
$$\ln z \gt \ln x \implies z \gt x \tag{5}\label{eq5}$$
This latest inequality of \eqref{eq5} means the second & third parts of \eqref{eq2} gives
$$\ln z \gt \ln y \implies z \gt y \tag{6}\label{eq6}$$
However, \eqref{eq6} contradicts \eqref{eq3}! Note you can use similar arguments for the case where all $x$, $y$ and $z$ are less than $1$, so the logarithm values are negative.
Also, you can extend this cyclic type argument to additional odd number of values & equations, which I'll leave up to you to do. However, note if the number of values is even, then there are exceptions, e.g., where the values alternate between $2$ and $4$, such as $2^4 = 4^2 = 2^4 = 4^2$.
Comment: @Dxe69 I'm sorry but I made a mistake in my answer. I stated it was the first & third parts while I meant it was from the first & second parts of (2). I've now corrected this mistake. Also, there was another small mistake in the next part where I referenced the wrong equation, i.e., (1) instead of (2). I trust it's now correct & makes sense to you, but please let me know if it does not. Thanks.
Comment: How did you get $\ln{y}>\ln{x}$?


ASP.Net GridView memory leak with large result set?

Question: I have a GridView that is bound to an ObjectDataSource that is calling a Business Service object which returns a List<> of POCO's.
Recently my client removed the Page Limit number on the GridView due to their customer's request.  This resulted in the GridView displaying over 10K items.
When this page is called we're seeing the ASP.NET process eat up roughly 30MB on each refresh and not letting it go.  (eventually the web server throws an out of memory exception)
I'm 100% certain this is not the BSO (I've created a page that calls the BSO 20 times and seen no memory leak).  I ran the ANTS Profiler and saw that most of the memory is indeed from the Web UI.
<code><asp:TextBox ID="uxQuery" runat="server" Width="300px" MaxLength="300"></asp:TextBox>
<asp:Button ID="uxSearch" runat="server" Text="Search" OnClick="uxSearch_Click" />
<asp:GridView ID="GridView1" Width="100%" Visible="True" DataSourceID="MyDataSource"
    runat="server" AllowSorting="True" AutoGenerateColumns="False"
    OnRowDataBound="GridView1_RowDataBound" EnableViewState="False">
    <PagerSettings FirstPageText="<<" LastPageText=">>" Mode="NumericFirstLast"
        NextPageText=">" PreviousPageText="<"></PagerSettings>
    <Columns>
        <asp:TemplateField HeaderText="Name" SortExpression="OrganizationName">
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("Name") %>' CommandName="Name"
                    CommandArgument='<%# Eval("ID") %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="CityName" HeaderText="City" SortExpression="CityName" />
        <asp:BoundField DataField="PhoneNumber" HeaderText="Phone" SortExpression="PhoneNumber" />
    </Columns>
    <HeaderStyle CssClass="MasterHeader" />
    <AlternatingRowStyle CssClass="AlternateRow" />
</asp:GridView>
<asp:ObjectDataSource ID="MyDataSource" runat="server" OldValuesParameterFormatString="original_{0}"
    SelectMethod="GetBySearchString" TypeName="BLL.BSO.SummaryBSO"
    SortParameterName="sortExpression" EnablePaging="True">
    <SelectParameters>
        <asp:ControlParameter ControlID="uxQuery" Name="searchString" PropertyName="Text"
            Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>
</code>
I've talked my client and customer out of this "feature" but I'm still curious why the memory leak exists.
Answer: I doubt it's the GridView.  Too many people are using it; if it had a memory leak, others would have noticed and reported it.
If you're sure it's not in your BLL, then that leaves the glue logic in between, or possibly something peripheral, but related.
Are you using any static references?
Are you assigning any event handlers?  There's a common memory leak scenario that involves assigning event handlers, and not unassigning them later. One unpleasant corner case is where a the event handler references are held by a long-lifetime or static object.
Are you calling all required Dispose() calls?  Do any of the associated objects use unmanaged memory?
Comment: Thanks for the suggestions.  Ended up I was using an event handler for my sitemap. (sitemapresolve)  Funny, because I had followed the example at http://msdn.microsoft.com/en-us/library/system.web.sitemap.sitemapresolve.aspx and the community comments on that post really helped.


If X~$\mathscr N(-5,1)$ what would be $\Bbb P(X \ge -4)$?

Question: Can anyone explain the following solution,
$=\Bbb P\left(\displaystyle\frac{X-\mu}{\sigma} \ge \frac{-4-(-5)}{1}\right)$
$=\Bbb P(Z \ge 1)$
$=0.5 - \Bbb P(0<Z<1)$
$=0.5 - 0.3413$
$=0.1587$ Ans.
Comment: If $X$ is normal with mean $\mu$ and variance $\sigma^2$ then $(X-\mu)/\sigma$ is standard normal (mean 0, variance 1). You can use tables or software to get probabilities for the standard normal distribution.
Comment: @mark999, when should I understand that my problem requires a Table to solve the problem?
Comment: If you need probabilities relating to a normal distribution then it's very likely that a table or software is required.
Answer: The idea behind that solution is that your original distribution is invariant to translation;  simplistically that one can add (or subtract) a quantity $a$ to the probability distribution of $X$ and the shape of that probability distribution of $X$ will remain the same.
The solution you present effectively says  that the question $P(X \ge -4)$   for $X \sim N(-5,1)$ can be answered for $X_{new} \sim N(0,1)$ if you also shift your original question such that is asks: $P(X_{new} \ge 1)$; here $\alpha$ is simply $5$ so you have $X_{new} = X + 5$. The answer emphasises the fact that the new distribution is $N(0,1)$ by using the symbol $Z$ to show that the new variable is standardised.
In any case you need to use the cumulative distribution function of the normal distribution to get your answer (function pnorm in R).
In R you could do something like:
1- pnorm( -4, mean = -5, sd = 1)
# 0.1586553

to get the exact answer directly without resorting to translating the probability distribution $X \sim N(-5,1)$. The answer you describe prompts you to use:
1- pnorm( 1, mean = 0, sd = 1)
# 0.1586553

so you query the distribution $X_{new} \sim  N(0,1)$. Both methods will return the same results:
all.equal( 1- pnorm( 1, mean = 0, sd = 1), 1- pnorm( -4, mean = -5, sd = 1))
# TRUE

My suggestion would be to forget about tables, tabulations and related stuff and focus to the idea that each probability is an area under a curve. If you appreciate that, then you just look around for a function that gives the size of the slice you are examining.


A question about CDF dependent upon multiple random variables

Question: If $f_h$ is the pdf of channel $h$, where $h \sim exp(\mu)$. And $I_i$ is the total interference and $I_i \forall i\in \{1,2,...n\}$ is also a random variable. The pdf of $h$ is given as:
$$f_h = \frac{P_mhr^{-\alpha}}{\sum_{i=0}^nI_i} = SINR$$
Where $P_m$ is the Transmitter (Tx) power, $r$ is the distance between Tx and Rx, and $\alpha$ is the pathloss exponent.
For a given threshold, the probability of success for successful communication is then :
$$p = \mathbb{P} \bigg[  SINR > T\bigg] = \mathbb{P} \bigg[  \frac{P_mhr^{-\alpha}}{I_r} > T\bigg]$$
$$ p = 1 - \mathbb{P}\bigg[  \frac{P_mhr^{-\alpha}}{\sum_{i=0}^nI_i} \leq T\bigg]$$
$$ p = 1 - \mathbb{P}\bigg[  h \leq \frac{TI_rr^\alpha}{P_m}\bigg]$$
Now, my question is do I calculate $\mathbb{P}\bigg[  h \leq \frac{T\sum_{i=0}^nI_ir^\alpha}{P_m}\bigg]$ as follows ?
$$\mathbb{P}\bigg[  h \leq \frac{T\sum_{i=0}^nI_ir^\alpha}{P_m}\bigg] = \mathbb{E}_{\sum_{i=0}^nI_i}\Bigg[ \mathbb{P}\bigg[  h \leq \frac{T\sum_{i=0}^nI_ir^\alpha}{P_m}\bigg]\Bigg]$$
i.e. the CDF of $h$ depending on expected value of random variable $\sum_{i=0}^nI_i$
Furthermore, how can I get the solution for it? Note that $I_i = Ag$, where $A$ is a constant and $g \sim exp(1)$
Comment: It would help to remove indices when they are not needed (and when the are confusing).  For example, there seems no reason for the $r$ subscript in $I_r$, and it confuses the meaning of $I_i$ for $i \in \{1, ..., n\}$.  Now, it also does not make sense to use $f_h$ to denote both a PDF of an exponential random variable, as well as a random variable $P hr^{-\alpha}/I_r$.  A PDF is a different type of thing from a random variable, both cannot be $f_h$.  So your presentation of the problem needs work. [I also observe that $P_m$ can be simplified to $P$ as there seems to be no $m$ in the problem.]
Answer: $$\mathbb{P}\bigg[  h \leq \frac{T\sum_{i=0}^nI_ir^\alpha}{P_m}\bigg] = E_{I_r}\Bigg[\exp\Bigg(-\frac{T\sum I_rr^a}{Pm}\Bigg)\Bigg]$$
Now, we know that there is a relation between the Expectation of random variable $X$ and its Laplace transform ie.e. $\mathcal{L}_X(s) = E[e^{-sX}]$. So we can write above equation as (considering s = $Tr^a/\text{P_m}$):
$E_{I_r}[exp(...)] = \mathcal{L}_I(s) = \int_v^\infty\frac{1}{1 + v^a/s} dv$ (according to a paper titled "Tractible Approach to Coverage and Rate in Cellular Networks". Following this paper, rest of the steps can be solved.


If an inverse covariance matrix is sparse, what can I say about the covariance matrix?

Question: How does the sparsity condition on an inverse covariance matrix affect the actual covariance matrix?
Comment: Unfortunately, it does not
Comment: There's got to be something. For instance identity matrix is sparse, and its inverse too.
Answer: As already commented by Yair there is no specific sparsity condition of the inverse covariance matrix that affects the actual covariance matrix or vice versa. Anything other than trivial sparsity matrix patterns (ie. diagonal) have no guarantee that they will reflected on both a particular matrix and its inverse. Even tridiagonal matrices can easily have non sparse inverses.
For particular cases where the sparsity of the matrix occurs in blocks you might be able to derive some results stemming from the Block matrix pseudoinverse algorithm which states that:
$\left[\begin{array}{cc} A & B \\C & D \end{array}\right]^{-1} =\begin{bmatrix}
                 (A - BD^{-1}C)^{-1}         & -A^{-1}B(D - CA^{-1}B)^{-1} \\
                 -D^{-1}C(A - BD^{-1}C)^{-1} & (D - CA^{-1}B)^{-1}
\end{bmatrix}$
but that's probably about it (purely anecdotally, I have tried to impose sparsity patterns through the Cholesky decomposition of a PSD matrix but I failed in my trial-and-error foray). You might also want to consider looking into the Cuthill–McKee algorithm (CM) if you expect some adjacency feature to be reflected in the covariance matrix. The CM algorithm permutes a sparse matrix that has a symmetric sparsity pattern into a band matrix form with a small bandwidth, this might help preserve some sparsity towards the off-diagonal entries of the inverse matrix but that is not guaranteed. (Applying CM -if reasonable- can be very helpful for particular applications (eg. in 2D smoothing routines) and may significantly speed-up your computations.)
Comment: (+1) Because the block-diagonal matrices of any given shape are a ring, their inverses (whenever they exist) have the same block-diagonal structure and so preserve that much of sparsity pattern.  As an extreme example, diagonal matrices are block-diagonal, thereby exemplifying the case pointed out by @Aksakal. The furthest one can go in this direction is to conjugate block-diagonal matrices by permutation matrices (which obviously preserves all zero and non-zero entries, but just moves them around).
Comment: (+1) Thank you for this comment (short answer really). It is really insightful. I will definitely consider it in the future.


Closed form of $\sum_{n=0}^\infty \frac{x^{(2n+1)k}}{((2n+1)k)!}$

Question: I encountered the following series and I have been unable to find a closed form, except for the values $k=1$ and $k=2$
$$\sum_{n=0}^\infty \frac{x^{(2n+1)k}}{((2n+1)k)!}$$
Is there a general form of writing this for any $k$ in terms of elementary or special functions? (being $k$ a positive integer).
Thanks in advance
Comment: https://en.wikipedia.org/wiki/Series_multisection
Answer: These are  generalized hypergeometric functions.
$$f_k(x)=\sum_{n=0}^\infty \frac{x^{(2n+1)k}}{((2n+1)k)!}$$
I do not simplify in order you see the patterns
$$f_3(x)=\frac{x^3}{3!}  \,
   _0F_5\left(;\frac{4}{6},\frac{5}{6},\frac{7}{6},\frac{8}{6},\frac{9}{6};\left
   (\frac{x}{6}\right)^6\right)$$
$$f_4(x)=\frac{x^4}{4!}  \,
   _0F_7\left(;\frac{5}{8},\frac{6}{8},\frac{7}{8},\frac{9}{8},\frac{10}{8},\frac
   {11}{8},\frac{12}{8};\left
   (\frac{x}{8}\right)^8\right)$$
$$f_5(x)=\frac{x^5}{5!}  \,
   _0F_9\left(;\frac{6}{10},\frac{7}{10},\frac{8}{10},\frac{9}{10},\frac{11}{10},
   \frac{12}{10},\frac{13}{10},\frac{14}{10},\frac{15}{10};\left
   (\frac{x}{10}\right)^{10}\right)$$
For sure, you could write
$$f_3(x)=\frac{\sinh (x)}{3}-\frac{2}{3} \cos \left(\frac{\sqrt{3} x}{2}\right) \sinh   \left(\frac{x}{2}\right)$$
$$f_4(x)=\frac{1}{4} (\cos (x)+\cosh (x))-\frac{1}{2} \cos \left(\frac{x}{\sqrt{2}}\right) \cosh
   \left(\frac{x}{\sqrt{2}}\right)$$
I prefer not to type the next one.
The advantage with the hyeprgeomatric function is that there are very efficient codes for their computations.
Answer: $\frac{\tanh^{-1}(x^k)}{k!}$ is one way to write the closed form of the infinite sum with a trigonometric function.
Note: $\tanh^{-1}=\frac{e^{2z}-1}{e^{2z}+1}$.
Answer: Here is the general way of obtaining a closed formula for $\sum_{n\ge 0}a_{nk}x^{nk}$ from $f(x)=\sum_{n\ge 0}a_{n}x^{n}$.
We will make use of the following fact. Let $\omega_k$ be any $k$th primitive root of unity, say $\omega_k=e^{2\pi i/k}=\cos(2\pi/k)+i\sin(2\pi/k)$, and let $n$ be any integer. Then
$$
\frac{1}{k}\sum_{j=0}^{k-1}\omega_k^{nj}=
\begin{cases}
1, & \text{if} \ k\mid n,\\
0, & \text{if} \ k\not\mid n.\\
\end{cases}
$$
Obviously, this is true in the first case, because each summand is $1$. In the second case, this is true because
$$
\sum_{j=0}^{k-1}\omega_j^{nj}=\frac{\omega_k^{kn}-1}{\omega_k^n-1}=\frac{1-1}{\omega_k^n-1}=0,
$$
since $\omega_k^n\ne 1$ when $k\not\mid n$. Therefore,
$$
\sum_{n\ge 0}a_{nk}x^{nk}=\sum_{n\ge 0}\left(\frac{1}{k}\sum_{j=0}^{k-1}\omega_k^{nj}\right)a_{n}x^{n}=\frac{1}{k}\sum_{j=0}^{k-1}\left(\sum_{n\ge 0}a_n\omega_k^{nj}x^n\right)=\frac{1}{k}\sum_{j=0}^{k-1}f(\omega_k^jx)
$$
Now we just need to find the closed formula for $f(x)=\sum_{n\ge 0}\frac{x^{2n+1}}{(2n+1)!}$, but by essentially the same logic, this is the odd part of $e^x$, i.e.
$$
f(x)=\frac{e^x-e^{-x}}{2}=\sinh x.
$$


What are the small ">" signs above the notes?

Question: Take a look:

What are the > markings above the notes? I know of a decrescendo and a crescendo but can they be applied to specific notes?
Comment: You have obviously not yet encountered the [dolmetsch page](http://www.dolmetsch.com/musicalsymbols.htm) which deserves to be bookmarked for future reference in case of similar questions.
Comment: The decrescendo sign should not be confuse with the accent - thought it sometimes can be. See related: https://music.stackexchange.com/questions/44999/why-crescendo-or-decrescendo-over-one-long-note-in-piano-music/45016
Answer: Simply called an accent. Indicates that note gets played louder (accentuated) than the surrounding notes. How much louder is open to interpretation. An accent can be applied to any note value, and probably works better on an instrument which can sustain that note for its full value, although if a 'suddenly loud' note is needed, it would most likely not have an accent but a sforzando (sf or sfz). The first note in a bar is often accented slightly anyway, so here on the first note, it means give it even more volume.
Comment: I don't quite agree with your explanation. "More volume" isn't really a sensible interpretation here – Tchaikovsky clearly intends the beginning chords to be not quite as _loud_ as the second and third time the theme is played, where the dynamic is _ff_.
Comment: @leftaroundabout I think by "even more volume" Tim means more volume relative to the level of volume you would give the note if it weren't accented. Of course, in the *ff* passage, you need "still more volume," and would still need to slightly accent the first beat relative to the fourth, the sforzandi notwithstanding. (But after reading your answer, I can see that I'm thinking pianistically. The distinctions that you draw there make sense.)
Comment: To be played louder there will need to be more attack at the onset of @leftaroundabout - by 'more volume' I meant 'louder'. To me they are synonymous in music. Obviously that extra volume will be achieved in different ways, for instance a trumpet, violin and piano would take  quite different methods to make a note accentuated. To become accentuated, the attack at the beginning of the note will have to be louder/more distinct compared with other non-accented notes.
Comment: The point is, I think neither "more volume" nor "louder" properly describes what an accent does. "More aggressive" might be an accurate choice, if you want to reduce it to a single adjective.
Comment: @leftaroundabout - I like that. But isn't that going to effectively be  'louder' anyway? Or is it, in some cases, going to be a change of tone/timbre?
Answer: What an accent denotes is actually that the notes' attack should be particularly emphasized. Loudness is already indicated by the f, it wouldn't make sense to simply say "every note should be played louder", as Tchaikovsky seems to do here. What he wants is that despite the slow tempo, the notes should not become "rubbery", but with a clear, present initial impulse. Instead of continuing to write out accents, he then expresses the same with the sempre marcato (at least that's how I understand it).
Note the contrast with the third iteration of the theme, which is even louder but puts ties over everything, emphasising how the fat, pulsating feel is replaced by soaring, ethereal sound:
Comment: It has to do with volume, but it's not just "play the note louder". The _attack_ should be louder, i.e. put extra pressure on the bow in preparation an release it with deliberation, in a quick and clear movement, when starting the note. The remainder of the note should not be louder than it would be without the accent. Hence, the "decrescendo" appearance is actually quite fitting.
Comment: I am still a little confused on an actual definition. Are we saying that the way they are played is to be different? Or is it more to do with volume?
Comment: That is clearer, thank you, how would you play the accent on a piano I wonder? The bow example does make perfect sense.
Comment: @cmp playing a piece like the Serenade For Strings on piano would necessarily fall short of the proper thing... but yes, in such a case, just making the entire note slightly louder is the standard makeshift solution. Theoretically, the best option would be to slightly damp the note at the beginning but then let it ring freely immediately afterwards; on guitar this can be done quite well with palm mute or left-hand mute, on piano it would require half-pedalling. I don't think many people would do either of this though; you just can't replicate a proper bowed string anyway.
Comment: Another option that isn't appropriate here (only in a faster tempo) is to make the note both louder and slightly shorter entirely.
Comment: Like the Tenuto mark? I believe you posted about that recently. That's another odd one :-)
Comment: Well, tenuto is kind of the opposite: it makes the note "body" louder _without_ giving it a particularly sharp initial attack. On piano, you'd approximate tenuto by making the note slightly louder and slightly longer.
Comment: I suppose as a pianist I don't have as many options as you're describing here. :)
Answer: As is the case with most aspects of music notation, there is no exact definition. This is an 'accent' as people have already explained, and it has to do with loudness and attack quality. The exact meaning depends on context. One general rule of thumb that I learned is that an accented note is one dynamic marking higher than the notated dynamic---e.g. if you are playing piano, the accented notes are mezzo-piano.
But this is just the beginning. For example, if you are playing a piano instrument, this basically applies. But what if you are playing the violin? Usually in context of string music, accents apply to the attack of a note (stronger articulation). In a piano, there is no way to control articulation and volume separately (slurring and pedalling aside). The velocity with which the key goes down controls both the attack and volume. In a sustained instrument (voice, strings, winds, brass, etc.), there is no such direct coupling of these parameters.
It also depends on the composer. Schubert sprinkles these marks around like salt on french fries. Their meaning (which is totally subjective because Schubert is long gone and to my knowledge there is no extant document that gives his reason for using them so often) is somewhat different than in Beethoven---who also uses the 'v' (or 'wedge accent'), 'sfz' (sforzando), and 'rfz' (rinforzando), which are all types of accents that have to do with attack and dynamic.
People have written volumes about these issues, but at the end of the day you just have to have experience and musicianship to make sense of it all.
Claims that always hold are that different types of accented notes should be differentiable form eachother and from non-accented notes, and they should be stronger than non-accented notes.
Comment: Thanks for joining Music.StackExchange and sharing your expertise! I think this is a great answer which explores the subtleties with lots of detail to help readers understand and navigate the nuances. +1


Analytical Expression of complex roots of a polynomial

Question: Can someone give analytical expressions for the complex roots of the polynomial of the form:
$$(1+x)^n + (1+x)^m - 1,$$
where $n$ and $m$ are arbitrary integers.
Basically, I want an analytical explanation of the following region (which are the roots achieved from mathematica):
Roots of the Polynomial
Comment: Any context/effort?
Comment: @Sean Please take a look at the picture I added. This picture shows the zeros of the polynomial where $m$ and $n$ are integers between 20 and 30.
Answer: I doubt that in general there is a closed-form for the roots in terms of $n$ and $m$, except for the easy cases where $n=m$, or one of them is zero.  For an "analytical explanation" of your plot, suppose without loss of generality that $n>m\geq 1$, and make the natural substitution $z=1+x$, so the polynomial is $z^n+z^m-1$. Then for all $\zeta$ such that $\vert \zeta\vert=1.62$, you can check that $\vert \zeta^n\vert>\vert\zeta\vert^m+1\geq \vert\zeta^m-1\vert$. Rouche's Theorem then implies all $n$ roots lie in the disc of radius $1.62$ centered at $0$. Translating back, all the roots of your polynomial are in the disc of radius $1.62$ centered at $x=-1$ in the complex plane. For specific choices of $n,m$ with $n>m$, you can make this tighter.
Also, there's always a real root between $-1$ and $0$ by the intermediate value theorem. There are no positive roots.
Edit: If you want an even better bound on the roots, going back to $z^n+z^m-1$, it follows from Landau's inequality that the product of the magnitudes of the roots with magnitude at least $1$ here is bounded by $\sqrt{3}$. Any nonreal root will come with a conjugate pair with the same norm, so each must have magnitude at most $3^{1/4}\approx 1.32$. You can use Descartes' Law of Signs and probably the intermediate value theorem to show there are only a couple of real roots, and they are pretty close to $0$. So Landau's inequality gives a pretty good radius on almost all of the roots.
Comment: Yes, that makes sense. It seems  1.62  is the most one can get using Rouche's theorem. But can you give a better bound for the radius of the circle (The picture seemed to have a lower radius)? May be using some other technologies? In this context what are the other method to show location of zeros?
Comment: @Unknown I added some more.
Comment: Thanks a lot for the pointer.


How to get an unknown web directory name?

Question: I have a web root directory which is setup like this:
apps_unknown_dir
    |__ mylife.php
.htaccess
index.html
get-app-dir-name.php

The problem is that the application directory [apps_unknown_dir] name is periodically or randomly gets changed.  I would like to have a code into the file "get-app-dir-name.php" that will echo the new apps unknown directory name when run.
How can I go about getting the apps unknown directory name?
Comment: XY problem detected - http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem You shouldn't ever need to know that directory.
Comment: Are you executing from within `mylife.php`?
Comment: I willbe executing from "get-app-dir-name.php.
Comment: `randomly gets changed` by who, what? why? if its for protecting files from direct access, your doing it wrong. Cant you store the new foldername somewhere, is a kinda expensive operation scanning for the directory on every page load.
Comment: I will be executing from "get-app-dir-name.php.  The "get-app-dir-name.php" is included into the index.php which will then define a constant for the "apps_unknown_dir".
Comment: @Danack perhaps more like the abcdefghijklmnopqrstuvwxyz problem ;p
Comment: I know it's kinda expensive to rescanning, I am trying to figure a better way.
Comment: I added an answer, but it still does scanning.
Answer: I'd iterate over folders in that directory, looking for one that's not on known-list, or that has mylife.php file in it.
You may do it like in answers to that question: how to get all subdirectories that has specific folder name in php?
Comment: I think this should do it. Thanks for the idea.
Answer: Just from the top of my head you could try this: (warning untested code)
$knownFolders = array('folderIKnow', 'folderKnown', 'anotherFolderNameIKnow');
$unknown = array_diff(glob("/folder/to/app/*", GLOB_ONLYDIR), $knownFolders);
echo $unknown;

So you have a list of known folders, then scan the folder for all directories, see the difference between the scan and the white-list.
Comment: This did it! `$__path = realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR .'*';

foreach (glob($__path . DIRECTORY_SEPARATOR ."mylife.php") as $filename) {
    echo $filename . "\n";
}
`


How to write the form of partial fraction decomposition of the function.

Question: How to write the form of partial fraction decomposition of the function.
$$I= \dfrac{2\,x^3+24\,x^2+20\,x+10}{x^2+10\,x+25}$$
I used long division I get$$Quotient= 2\,x+4\\Remainder =-70\,x - 90\\$$
But don't know how to solve further steps. Thanks in advance.
Answer: Dividing the function you get$\text{Quotient}= 2\,x+4\\\text{Remainder} =-70\,x - 90\\\text{Divisor}= x^2+10\,x+25\tag*{}$So,$2\,x^3+24\,x^2 +20\,x+10=(2x+4)(x^2+10x+25)+(-70x-90)\tag*{}$Rewrite the function,$I = \dfrac{(x^2+10\,x+25)(2\,x+4)+(-70\,x-90)}{x^2+10\,x+25}\\=(2\,x+4) -\dfrac{70\,x+90}{(x+5)^2}\tag*{}$Now decompose $\dfrac{70\,x+90}{(x+5)^2}$  by using  partial fraction.$\Rightarrow\dfrac{70\,x+90}{(x+5)^2} = \dfrac{A}{(x+5)} +\dfrac{B}{(x+5)^2}...(1)\\=70\,x+90 = A\,x+5\,A+B\tag*{}$comparing coefficients of both side of equation$Ax=70x,5\,A+B=90\\A=70,B=-260\tag*{}$Therefore,$ I=(2\,x+4) -\dfrac{70}{x+5}+ \dfrac{260}{(x+5)^2}\tag*{}$
here is the similar problem with complete solution:
partial fraction decomposition
Answer: HINT:
As $x^2+10x+25=(x+5)^2$
using Partial Fraction Decomposition, write $$\dfrac{-70x-90}{(x+5)^2}=\dfrac A{x+5}+\dfrac B{(x+5)^2}$$
Answer: Here, $I=(2x+4)+\frac{-70x-90}{x^2+10x+25}=(2x+4)+\frac{-70x-90}{(x+5)^2}=(2x+4)+\frac{A}{x+5}+\frac{B}{(x+5)^2}$.$\ $To determine A and B, we solve the equations $$A=-70;\\5A+B=-90$$ to obtain $I=(2x+4)+\frac{-70}{x+5}+\frac{260}{(x+5)^2}$