Chord symbols don't match tabs

Question:
Im trying to learn Pure imagination on guitar following the tabs. Im going well, but I realised that when I see the fret board numbering with words above them like Fmaj7, Am and C, following the fret numbers does not sound right.
If I look up Fmaj7 and play that, it fits the song, but the frets on the tabs sound completely wrong. Why is this?
Comment: What exactly sounds wrong? The fret numbers in the tab you've shown are exactly the notes in the named chords. Unless the guitar is out of tune and you're checking the chords on a different instrument, they should be the same.
Comment: Are you using standard tuning? If you're in, say, drop D, your chords are going to sound weird
Comment: One big thing that I will point out is that tablature that you find on the internet, as opposed to purchased from an official publication that has an editor, is very, very, very frequently wrong and often times incomplete.  The fact that any random person can post tab and no one reviews it before it's posted means that there is no vetting.  A whole lot of people viewing tabs don't have a keen enough ear to know if it's right or wrong/wouldn't notice small issues.  So always second guess tabs and trust your ears.
Answer: Those 'words' are actually chord names. Most songs will have a chord or two that fit with the bar they're next to.
In this case, Fmaj7 tells that the full chord is F major 7th, which cotains the notes F A C and E. The tab shows exactly that - F on the fat E string, and ACE on the top three strings. That couldn't be clearer or more accurate!
The 'Am' word means A minor, consisting of A C and E. Exactly what the top three strings produce from the tab. The 'C' that follows is also accurate with two c notes, a G and an E.
It may be that the tab is inaccurate as far as following the actual song as it's recorded on the track. That happens all too frequently! But as far as the tab and the chord symbols go, they're exactly together.
Comment: That's an interesting F chord - g b and f..! I certainly leave C F  (and G)  chords for a good few weeks. E A and B7 are all in the same plane, and have common notes.
Comment: TAB's don't have to be accurate when they are meant as starters for beginners. I often taught the children just to play only the strings 1-3 changing the index finger form fret 1 of the e and the b string: C ( g,c,e) and an F (g,b,f). So they were able from the 1st lesson to sing and accompany a children song with tonic and dominant.
Comment: yes, Tim, E7 and A7  played with 2 fingers are the best starters, indeed!
Comment: @Tim An F chords with g b and f would be an Fsus2 5-
Comment: @MichelKeijzers - more likely Fsus2b5, although that would need Cb, not B. I'd rather go for G7(no5).
Comment: @Tim I thought b5 == 5- (both 5th tone lowered), and Cb == B
Comment: @MichelKeijzers - just writing 5 =5 isn't 5 =b5.. B is enharmonically the same as Cb, but to be b5 it would be called Cb, not B. Honest!
Answer: There are 3 different ways of Guitar-chord notation and reading:

staff of 5 lines like almost all other instruments

Chord-TAB (as you are showing here) they are used for finger picking and more differentiated accompaniments e.g. bass licks.

Chord diagram: mostly used for lyrics and added chords - what you're  calling "words"
(from  the chord-diagrams (patterns) you can also play a differentiated accompaniment when you have some experience of finger picking or bass passing notes.)

Why are there words that appear on guitar tabs?

As you know the chord TAB shows the 6 strings and the numbers indicate in which fret they are "hold" by the fingers of the left hand.
The terms C, Am Fmaj7 etc. are the names of the  guitar-chords that are played in the chord TAB and the chord diagrams are just another representation of what we are doing when we want to play a chord:
Chord diagrams:
The strings are shown vertically, the chord-names ("words") are written on the top and at the bottom are notated the fingers that have to work on the specific strings.

If you turn one of these patterns 90°  to the left you will recognize that they're resembling to what you have learnt by reading the chord-TAB. But instead of the numbers the diagram shows where (in which fret) you have to put your fingers and the numbers on the right side of the rotated diagram indicate which finger you must use.)

So the example of Am means a-minor (A-C-E) shows we have from string 6 to 1:
E (open)
A (open)
D (2nd fret= E) -> finger 2
G (2nd fret= A) -> finger 3
B (1st fret= C) -> finger 1
E (open)
You will recognice the similarity with the 2nd chord named Am in your TAB: notice that the bass tones are not played there.
Now you should be able to derive all the other chords and write your self the corresponding TABs from the chord diagrams and vice versa.
Edit: I think the fingering of A major (2nd diagram) has a typo. I've never seen A = 213! we better use 123. That's why I poste another list of diagrams where you can compare also "your" Fmaj7. It is exactly like Tim has described.
You'll find 100reds of lists looking up: Guitar chords (images).
Comment: The '**x**' means not played. So your example of the Am chord isn't exactly right - it shows no note played on bottom (fat) E. And fingering for open A, I use 234, often with index (1) on 3rd string 1st fret. It's quite tight for a lot of folks, so 234 is smaller than 123!
Comment: I always play A 345 as it is a good practice to play barré chords later. Btw. you can always take the fingering you like - that seems most comfortable to you. And yes, x  means this string is not played, but most amateurs play it too schrumming on their guitar, and the E (6) can be used as a changing 4th in the bass for picking accompaniment. Those examples were not meant to explain the whole diagram theory - this would lead too far - they are just posted to show the analogy to the TABs. I think the chord patterns have been explained enough here and also the meaning of an 'x`.
Comment: Yes, I meant I play with middle, ring and pinky, just as I would when barring an A shape chord - except then, I usually use only ring across strings 2 3 and 4. Not sure numbering fingers on fretting hand would include thumb as no.1. Except when playing Jimi style!
Comment: I think it's  world wide use 1234 for the longer fingers, when I meant to notate the thumb I wrote a d (for "Daumen"). We can agree with the "students" any sign or abbreviation that we want ;)
Answer: Fmaj7 looks pretty ok to me regarding its notes once you realize that you are supposed to retain the already fingered notes (0 on the A string, 2 on the D string) while playing the rest.
The authoritive information is in the tablature.  The chord symbols above for one thing indicate the basic harmony one should be hearing (so they can be used for prompting on an instrument like the piano), for another they are often helpful for sightreading in that they give you information about the kind of pattern the fingers have to be placed in, particularly if the notes don't arrive all at once.
For example, people have different preferences about which fingers to use for chords like Em or Am and when this chord is the pattern one arrives in and there is freedom of choice, not prescribing the exact fingering will make it easier to choose your preferred pattern.
That does not mean that the actual combination of strings and frets will be as found in a typical chord table, in particular not when playing in higher positions.  Authoritive is what is written in the tablature itself.  But I'd be surprised if you'd not, over time, find those chord symbols helpful for faster orientation in new stuff you learn.
They are even comparatively frequent for scores spelt out in notes: the chords are quite easier to recognize in those, but it tends to help if you are going to improvise additional material to see the harmonic framework.
But that's something for the future...
Comment: Where does it say retain the two previous notes? They're in the bar before, and there's no indication. O.k., they could both belong to Fmaj7, but probably don't.

Chord symbols don't match tabs


Integrating basic equation

Question: In the following question I am just wondering if there is another way to solve this integral without using partial fraction decomposition.
$$\int \frac{1}{x(2-x)}dx$$
If there is another way what is it called?
Answer: We can also complete the square. We see $$\frac{1}{x(2-x)}= \frac{1}{2x-x^2}= \frac{1}{1-(x-1)^2}.$$ Thus, the integral becomes
$$\int \frac{1}{1-(x-1)^2} \ dx = \tanh^{-1}(x-1) + C.$$
Comment: @jh123 note that $\tanh^{-1}(x)=\frac 12\ln(\frac{1+x}{1-x})$ so $\tanh^{-1}(x-1)=\frac 12\ln(\frac{x}{2-x})=\frac 12\ln(x)-\frac 12\ln(2-x)$ which is the result obtained by partial fractions.
Comment: @jh123 and that can sometimes happen when using different approaches to a problem.  Both can be correct and both appear different, but in the case that they are both correct that simply implies that the two solutions differ only by a constant.
Comment: This is different than the solution I worked out via partial fractions
Comment: Awesome, thanks for your answer and that helpful comment
Comment: @zwim thanks for that comment, I should touch up on my trig identities for future questions

Integrating basic equation


Create a table from a given array using inner.HTML

Question: I'm asked to create a table which can be sorted with a press of a button. The table is supposed to be created by a given array.
What I don't understand is how can I use an array loop inside a string so that the .innerHTML function would print the table body with the given object properties.

    main = document.getElementById('body');
    listArray = [{name: 'Second', value: 2},{name: 'Fourth', value: 4},{name: 'First', value: 1},{name: 'Third', value: 3}];
    let showAll = () => {
      main.innerHTML = '';
      template(listArray);
    }
    let template = (arr) => {
      let loopArray = arr.forEach((item) => {return `<tr><td>${arr.name}</td><td>${arr.value}</td></tr>`});
      let html = `

Name	Value

` + loopArray + `

`;
        main.innerHTML += html;
    }
    showAll();
Comment: I'm ignoring the sorting part for this question as I'm already informed about it...
Answer: Use map instead of forEach so that the returned
 HTML string can then be joined together and set as the content of the table. You also need to refer to the properties of the item in the callback, not the arr.

main = document.getElementById('body');
listArray = [{name: 'Second', value: 2},{name: 'Fourth', value: 4},{name: 'First', value: 1},{name: 'Third', value: 3}];
let showAll = () => {
  main.innerHTML = '';
  template(listArray);
}
let template = (arr) => {
  const tableContentHTML = arr
    .map((item) => {return `<tr><td>${item.name}</td><td>${item.value}</td></tr>`})
    .join('');
  let html = `

Name	Value

` + tableContentHTML + `

`;
    main.innerHTML = html;
}
showAll();

But concatenated HTML has security risks. If the input isn't known to be 100% trustworthy, a better approach would be to assign to the textContent of s.

const main = document.getElementById('body');
const listArray = [{name: 'Second', value: 2},{name: 'Fourth', value: 4},{name: 'First', value: 1},{name: 'Third', value: 3}];

let showAll = () => {
  template(listArray);
}
let template = (arr) => {
  main.innerHTML = '';
  const table = main.appendChild(document.createElement('table'));
  for (const item of arr) {
    const tr = table.appendChild(document.createElement('tr'));
    tr.appendChild(document.createElement('td')).textContent = item.name;
    tr.appendChild(document.createElement('td')).textContent = item.value;
  }
};
showAll();


show that the integral converges or that is diverges: $\int_{1}^{\infty}{\frac{2 + cos x}{x-1}dx} $

Question: show that the integral converges or that is diverges: $$\int_{1}^{\infty}{\frac{2 + \cos x}{x-1}dx} $$
i know that it does converge from the solution, but i have no idea how to arrive at the conclusion. we are probably supposed to use p-integrals, but not sure how.
Comment: For any $L>1$, both the integrals $\int_1^L \frac{2+\cos(x)}{x-1}\,dx$ and $\int_L^\infty \frac{2+\cos(x)}{x-1}\,dx$ diverge.
Comment: okei, but i am not sure how to show it.
Comment: I've posted a full solution.
Answer: Hint It diverges. How to see it?
$$\frac{2+\cos x} {x-1} \geq \frac{1}{x-1} $$
Comment: hmm, i can not really see how that helps. what results/theorems should i use from here?
Comment: @JoakimHauger have you heard about  comparison test? What are the methods to show convergence of integrals that you have studied? Comparison test must be one of them
Comment: yes, but dosen't that require that i show that f(x) > (2+cosx) / (x-1 ). and then show that f(x) converges?
Comment: @JoakimHauger yes that is to show convergence. There is something similar for divergence of the integral. Do you remember?
Comment: @JoakimHauger yes that is to show convergence. There is something similar for divergence of the integral. Do you remember?
Comment: ahh, damn. though the integral converged, but it actually diverge. it all makes sence now. thanks
Answer: For any $L>1$, both the integrals $\int_1^L \frac{2+\cos(x)}{x-1}\,dx$ and $\int_L^\infty \frac{2+\cos(x)}{x-1}\,dx$ diverge.
First, we write $\frac{2+\cos(x)}{x-1}=\frac{2-\cos(1)}{x-1}+\frac{\cos(x)-\cos(1)}{x-1}$. Therefore, we have for $\epsilon>0$
$$\begin{align}
\int_{1+\epsilon}^L \frac{2+\cos(x)}{x-1}\,dx&=\int_{1+\epsilon}^L \frac{2-\cos(1)}{x-1}\,dx+\int_{1+\epsilon}^L \frac{\cos(x)-\cos(1)}{x-1}\,dx\tag1
\end{align}$$
The first integral on the right-hand side of $(1)$ is equal to $(2-\cos(1))\left(\log(L-1)-\log(\epsilon)\right)$, which diverges as $\epsilon\to 0$, while the second integral has a removable discontinuity at $x=1$ and is therefore integrable.

For the integral $\int_L^\infty \frac{2+\cos(x)}{x-1}\,dx$ we see that $\int_L^\infty \frac{2}{x-1}\,dx$ diverges logarithmically, while the integral $\int_L^\infty \frac{\cos(x)}{x-1}\,dx$ converges (integrate by parts with $u=\frac1{x-1}$ and $v=\sin(x)$).  Hence, the sum of a convergent integral and a divergent integral is divergent.


How to clone an existing View and change the format from table to CSV?

Question: I have managed to figure out how to Install the Views data export module and create a View in order to export to CSV so that I can import this into WordPress.
Someone else has already created all the Views. Here is a screenprint of how the view looks like:

What I want to achieve next is to clone these views and then convert them to CSV format from a Table format. I simply cannot see how or where this can be done.
What I am trying to do is click on the "Working Papers Other" and then clone this View. Once it is cloned I am trying to change the Format from Table to CSV.
There surely has to be a way to do this easily, else it will take an eternity to do all of these Views.
Comment: What exactly do you want to convert: the **design** (specs) of it, or only the **data** (the Views results)?
Comment: Only the data @Pierre.Vriens please
Answer: Here are the steps to get you going (referring to the screenprint you added):

Click the drop-down list in the upper-right that says view Working Papers Other, where you should then see another list item with label clone Working Papers Other.
Select (click) on that list item with label clone Working Papers Other.
Note that you'll then have an extra (and same named!) button to the right (or below) the 8 buttons you already have, with the very same label Working Papers Other, and the newly added one will be highlighted (grey / black), and selected.
To improve readability, hurry to go change the line (upper-left) that says "Display name: Working Papers Other" (by clicking on that Working Papers Other link). I suggest you change the Display name to (eg) Working Papers Other (CSV).
Change the line (upper-left) that says "Format: Table | Settings" (by clicking on that Table link). At this point you should be able to change the style of the view from Table to the Views display offered by the Views data export module, with label "Data export".
Tune (refine) the "Settings" of the Data export views display to fit your needs, whereas you can see how the result will look like in the preview near the bottom of your page.
Change the line (upper-middle) that says "Path: /publications/working-pa..." (by clicking on thatPathlink). I suggest you change the path by only adding some suffix such as-csv`.
Don't forget to use the Save button (upper-left) to permanently store the updated configuration of your view.
Click the button (upper-right) that says view Working Papers Other (CSV) (if you used my suggestiuon in item "4.") to actually view (browse) the Views result produced by the various changes described above ... Is it a CSV file that fits your requirements? If not: must be that you did something wrong in the steps described above ...

Note: If you want to become more familiar with Views, checkout the (free) set of 30 video tutorials about the Views module.


Parsing two isomorphous XML schemas into one class structure using JAXB

Question: Consider two isomorphous XML schemas. By isomorphism here I mean that these two schemas have identical structures except attributes and tags names. More specifically I have live example when was schema, say A, and its copy B, where all tags and attribute names were translated from English into national lamguage equivalents.
For example, as input we can have two different variants of one object:
<tag_1_v1>
    <tag_2_v1 id="blabla" name="xxxxx">
        Some value1
    </tag_2_v1>
    <tag_3_v1 id="alalala" name="yyyyy">
        Some value2
    </tag_3_v1>
</tag_1_v1>

and
<tag_1_v2>
    <tag_2_v2 special_id_2="blabla" name="xxxxx">
        Some value1
    </tag_2_v2>
    <tag_3_v2 id="alalala" special_name_2="yyyyy">
        Some value2
    </tag_3_v2>
</tag_1_v2>

The problem is to map these two schemas on single class structure, say
class Tag1 {
    Tag2 tag2;
    Tag3 tag3;
}

class Tag2 {
    String id;
    String name;
    String value;
}

class Tag3 {
    String id;
    String name;
    String value;
}

There are various ideas how to workaround this issue, but all of them aren't so convinient, as any possibility to use single JAXB annotation scheme on same class structure. They are:

create two different class-sets and then copy values from objects of
one schema into another;
create own SAX parser implementation and "translate" inside it tag and attribute names into appropriate ones;
use own preprocessor of XML and use string replacement (will not work if id and attributes name aren't identical within all schema).
Comment: I'd probably have selected option 2. It sounds like the least hacky option.
Answer: Since each <tag_i> can have different attributes, a clean solution would be to use inheritance:

Create an abstract class Tag1 that is inherited by Tag1V1 and Tag1V2. Factor all the common code into Tag1.
The same would go Tag2 and Tag3.

To get you started, here would be an implementation of Tag2:
@XmlRootElement
@XmlSeeAlso({Tag2V1.class, Tag2V2.class})
abstract class Tag2 {

    private String name;
    private String content;

    @XmlAttribute(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlValue
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

@XmlRootElement(name = "tag_2_v1")
class Tag2V1 extends Tag2 {

    private String id;

    @XmlAttribute(name = "id")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

@XmlRootElement(name = "tag_2_v2")
class Tag2V2 extends Tag2 {

    private String specialId2;

    @XmlAttribute(name = "special_id_2")
    public String getSpecialId2() {
        return specialId2;
    }

    public void setSpecialId2(String specialId2) {
        this.specialId2 = specialId2;
    }

}


Is fingering choice correct in this score La Moldau : right hand : 4 followed by 2 in an increasing scale?

Question: Is fingering choice correct in this score La Moldau : right hand : 4 followed by 2 in an increasing scale, in the measure 8th : 6th and 7th note.
https://www.free-scores.com/PDF/smetana-bedrich-vltava-la-moldau-68511.pdf

(remark : I use piano, but it maybe it seems that the score is not for piano ?)
Bonus question :

when a eighth note is staccato in this score, should I play it as if it would be a sixteenth note ? If so, why isn't it directly written directly written a sixteenth note, without writing staccato ? I have the feeling that a staccato eight note is no more a eight note : it transforms a sixteenth note (?)
Answer: First question. Don't believe published fingerings! They might well suit the editor, but no-one's hands are the same shape, as has already been pointed out. Work out your own - this has two advantages: you end up with something that works for you, and as you're doing this quite slowly you get to know the music better.
This piece wasn't originally for piano - it's a piano reduction of an orchestral piece by Smetana - 'Vltava' ('Moldau' in German - no idea why) from 'Ma Vlast' ('My country'). So there might be passages which are not ideally set out for the pianist.
On the second question, a staccato isn't necessarily half the length of the written duration. It's up to you to decide how long or short you make it. If you get hold of the orchestral score, the first note is played by the flute, and also the harp, which is why the arranger has put it into the left hand - you'll get a slightly different tone-colour that way. Personally, I'd play it more legato to link it with the f# in the right hand - it's a legato flute tune. The last left-hand chord is marked 'Violons pizz' (i.e. 'plucked'), so should be quite short, probably less than a 16th note.
But in the end it's up to you. Playing orchestral reductions is really hard work (I have to do a lot of it, as an accompanist). It's worth while getting to listen to the original orchestral version so you can hear the effects you're trying to achieve.
Have fun!
Comment: certainly did research on this reply that was significantly more specific than mine. His attention to understanding the intent of this particular transcription is invaluable and can be applied across a wide range of material.
Answer: When a published fingering appears questionable, the performer should take it upon themselves to alter it to suit their individual needs. In this case and others that appear to implement scales as part of the melody, the fingering would be improved by mapping the the notes to standard scale fingering, e.g., fingering from Hanon or other acknowledged sources. In general, this both makes the fingering more intuitive and also greatly aids pattern recognition and retention for performance. On the piano keyboard, following a key struck by the fourth finger by a key to be struck by the second (index) finger seems awkward. In general, published fingering for any piece should be used as a guideline, not a rule. We were not all born with hands like Duke Ellington's, and need to adapt.


how many kilometers can i do on 25L of fuel

Question: someone please help me .. my fuel gauge is not accurate and i need to know how many kilometers i can do on a full tank which is 25L
50922km was what it was on when I filled 18L of petrol.
the next time I filled up the car it was at 51064km and I put 15 and a half liters..
so I figured out that I did 142km between those two times filling it up (51064km-50922km=142km) .. but I need to know how many kms for a FULL tank of petrol .. helppp!
Comment: so correct me if im wrong here ...
Comment: so correct me if im wrong here ...
18-25=7L so say I had about 5L left in the tank coz I don't think I got it full to the brim time before last, then I put 18L in, it does 142km before I (think) its empty again and I put 15L to the brim .. that means I still had about 10 L still in the tank from that 18L so does that mean I just need to work out how many kms I do per L of fuel .. anyone help???
Answer: ok, so assuming that you filled it completely when you put the $18L$, and you filled it completely when you put the $15.5L$, then that means that you spent a total of $15.5L$ (what you reloaded) to drive the difference, $142Km$. That means that on average you spent $142Km/15.5L=9.47$ Km per liter. So on average a liter drives you a little less than $9$ and a half kilometers, if you want to know how far that takes you, we multiply: $9.47*25=236.7 Km$.
Comment: according to the numbers you gave, this should be correct
Comment: In practice, the "full" level is not all that precise (especially if you're rounding to the half-litre), and your fuel consumption will depend on driving conditions.  So I wouldn't trust these numbers well enough to go on a 236 km trip on a road with no gas stations....
Comment: are you sure about that? 236 km seems like a bit much for a mini clubman
Comment: well im not good at maths, hense why I am asking smart people, I edited my question .. how I came to get 142km .. I don't even know if that is right the way I worked that out
Comment: so I should just stick with a close number of say 200kms? would that be the best option?


How to evaluate $\sum_{ i}\sum_{ j}\sum_{ k}\sum_{ l} 2 \ \ where \ \ 1\le i \le j \le k \le l\le n $?

Question: Any hint on how to tackle these types of problem?
$$\sum_{ i}\sum_{ j}\sum_{ k}\sum_{ l} 2 \ \ where \ \ 1\le i \le j \le k \le l\le n $$
Comment: $$\begin{align}
\sum_{1 \le i \le n} 1 &= n\\
\sum_{1\le i \le j \le n} 1 &= \sum_{j=1}^n \sum_{1 \le i \le j} 1 = \sum_{j=1}^n j =  \frac{n(n+1)}{2}\\
\sum_{1\le i \le j \le k \le n} 1 &= \sum_{k=1}^n \sum_{1 \le i \le j \le n} 1 = \sum_{k=1}^n \frac{k(k+1)}{2} = \frac{n(n+1)(n+2)}{3!}
\end{align}
$$
Do you see the pattern?
Comment: @bof the point is recognize the existence of such a pattern and point out where to look for an answer, not memorization of any formula.
Comment: @achillehui, thanks for the nice explanation. Better you post it as an answer.
Answer:
In how many ways can we pick $i,j,k,l\in[1,n]$ such that $i\leq j\leq k\leq l$?

By setting $a=i-1, b=j-i, c=k-j, d=l-k, e=n-l$ we have that the answer is given by the number of ways for writing $n-1$ as $a+b+c+d+e$ with $a,b,c,d,e\in\mathbb{N}$, i.e. by the coefficient of $x^{n-1}$ in $(1+x+x^2+x^3+\ldots)^5 = \frac{1}{(1-x)^5}$. By stars and bars
$$ \frac{1}{(1-x)^5} = \sum_{m\geq 0}\binom{m+4}{4}x^m $$
hence the answer to OP's question is $2\binom{n+3}{4}=\color{blue}{\frac{n(n+1)(n+2)(n+3)}{12}}$.
 I am assuming $0\in\mathbb{N}$ as I am used to.
Answer: A lot of problem/exercise one encounter in school can be attacked by pattern recognition. One work out simpler version of the problem, guess what the answer should look like and use this as a hint to figure out what steps to follow.
Let use this as an example to illustrate this approach. It is clear the factor $2$ in the summand is a distraction, we can move it outside all the sum. Let's work out what the shorter form of the sum should look like first.
Summing over a single index is trivial, we have
$$\sum_{1 \le i \le n} 1 = n$$
Summing over two indices is not that hard, we have
$$\sum_{1\le i \le j \le n} 1 = \sum_{j=1}^n \sum_{1 \le i \le j} 1 = \sum_{j=1}^n j =  \frac{n(n+1)}{2}$$
Summing over three indices starts to become tricky, we first obtain
$$\sum_{1\le i \le j \le k \le n} 1 = \sum_{k=1}^n \sum_{1 \le i \le j \le k} 1 = \sum_{k=1}^n \frac{k(k+1)}{2}$$
The last sum is a problem. We can break it as a sum over $k^2$ and $k$, lookup the formula for a sum of $k^2$. Combine all the mess and simplify. The end results looks surprisely simple and looks similar to what we have for two indices.
$$\sum_{1\le i \le j \le k \le n} 1 = \frac{n(n+1)(n+2)}{3!}$$
One may wonder is there a way to derive this directly to avoid the same mess for sums for more indices. The answer is yes, we have
$$\sum_{k=1}^n \frac{k(k+1)}{2}
= \sum_{k=1}^{n}\frac{(\color{red}{k+2})-(\color{blue}{k-1})}{3}\frac{k(k+1)}{2}
= \sum_{k=1}^{n}\frac{k(k+1)(\color{red}{k+2}) - (\color{blue}{k-1})k(k+1)}{3!}
$$
The sum can be transformed to a telescoping one! With this discovery, the sum for four indices become a piece of cake. We have
$$\begin{align}
\sum_{1\le i \le j \le k \le \ell \le n} 1
&= \sum_{\ell=1}^n \sum_{1 \le i \le j \le k \le \ell} 1
= \sum_{\ell=1}^n \frac{\ell(\ell+1)(\ell+2)}{3!}\\
&= \sum_{\ell=1}^n \frac{\ell(\ell+1)(\ell+2)(\ell+3) - (\ell-1)\ell(\ell+1)(\ell+2)}{4!}\\
&= \frac{n(n+1)(n+2)(n+3)}{4!}\end{align}$$
The desired sum is simply twice of this:
$$\sum_{1\le i \le j \le k \le \ell \le n} 1 = 2\binom{n+3}{4} = \frac{n(n+1)(n+2)(n+3)}{12}$$
Comment: Wonderful explanation!!
Answer: $$\begin{align}
\sum_{1\le i\le j\le k\le l\le n}
&=\;\;\;\sum_{i=1}^n\sum_{j=i}^n\sum_{k=j}^n\sum_{l=k}^n 2\\
&=\;\;\;\sum_{l=1}^n\sum_{k=1}^l\sum_{j=1}^k\sum_{i=1}^j 2\\
&=2\sum_{l=1}^n\sum_{k=1}^l\sum_{j=1}^k\sum_{i=1}^j \binom {i-1}0\\
&=2\sum_{l=1}^n\sum_{k=1}^l\sum_{j=1}^k\binom {j+0}1\\
&=2\sum_{l=1}^n\sum_{k=1}^l\binom {k+1}2\\
&=2\sum_{l=1}^n\binom {l+2}3\\
&=\color{red}{2\binom {n+3}4}\end{align}$$


Unable to use images from document directory in JavaScript file

Question: I am storing user specific images getting from server in document directory. Then I want to display this images on bing map at certain pins(inside pin InfoBox). I am loading the images dynamically using javaScript. But images are not displaying on map.
I am setting images as HTML content of infoBox like,
pinInfoBox.setHtmlContent('

'+pin.Title+'

');

If I use any remote file and access it via http protocol it will work,
pinInfoBox.setHtmlContent('

'+pin.Title+'

');

I don't know why it is not taking image saved in my document directory.
Please help me to resolve this.
Comment: have you tried altering the src URL with the localhost directory path  example : `src="localhost:port/var/mobile/Containers/Data/Application/395E5EED-2FB4-4505-861E-2DA9AB96433B/Documents/my_image.jpg/"`
Comment: @anusha-k I feel like you have 1 missing forward slash and one extra. Change to: ``pinInfoBox.setHtmlContent(''+pin.Title+'')``.

This example will only work if the image serving page is also opened from file:/// location. When the serving page is opened from url (eg. http://foo.com) this will never work.
Comment: @tiblu I didn't understand. my .js file is in application bundle and and loading dynamically. When desired location information is received, a method in .js file is called with image path(which is in document directory). Is there any problem in that?
Comment: @anusha-k  Try the suggestion above to fix the image source. I added the extra notice just in case. If it is an application bundle, I guess it should be fine. But I lack experience with the bundles.
Comment: @anusha-k Sorry, now when I think about it, maybe ``file:///`` is disabled for a reason. You could possibly reference any another bundles files if it was allowed. Sorry for long-shotting here, but this may be related - http://stackoverflow.com/questions/747407/using-html-and-local-images-within-uiwebview
Comment: @tiblu Bundle file will work directly with the imageName just like in other objective c file. But this document directory path not working.
Comment: @tiblu Answer was in your `extra notice`. But I can't write images to bundle. So I copy my javaScript file to document directory. Now I can dynamically load image directly specifying its name only. No need of root directory components. Thank you..:)
Answer: I solved this based on @tiblu's comment.
JavaScript file and images should be in same path.

But I can't write images to bundle as these images are downloaded from server at runtime. So I copied JavaScript file to documentDirectory during application launch to work with images. Then we can simply access the image directly with it's name and no need of specifying full path.
pinInfoBox.setHtmlContent('

'+pin.Title+'

');


How can we programmatically use a DSA key to connect to an SFTP server?

Question: Has anyone at SO been able to connect to an SFTP server using DSA or RSA (using any free library)?
I've tried SharpSSH, and I can see some references to DSA in the code. However, I can't seem to find any methods that allow me to specify the DSA key to use to connect. I tried searching for the documentation for this library, but I could only find the distributable.
I hope someone here would have used SharpSSH, and could advise me how to pass a key instead of a password or would know where I could find the documentation for this library.
Alternatively, a solution with any other free library would also be appreciated.
Thanks in advance.
Answer: You need to use the addIdentityFile method, and pass the path to the private key.


nodejs fs.writeFile to sysfs (/sys) doesn't seem to work

Question: I'm using the w1_therm kernel module to read temperature of a few DS18B20 temperature sensors on a Raspberry Pi 4. This works well by just reading the temperature files in /sys/bus/w1/devices/<ROM>.
Since I have quite a few sensors I want to make use of the bulk temperature conversion feature (see linked docs above). This can be triggered by writing trigger to /sys/bus/w1/devices/w1_bus_master1/therm_bulk_read. This write will take a bit over 750ms (that is how long the temperature conversion takes for full precision on DS18B20s). The temperature reads after that are just reading from the fs and don't trigger another conversion, meaning they are very fast.
Now to the problem: If I manually write using echo trigger > /sys/bus/w1/devices/w1_bus_master1/therm_bulk_read everything works, but if I try to do this from node js (v18.17.1) using await writeFile(...) (where writeFile is imported from fs/promises) the write takes only ~20ms (doesn't throw) and the following temperature reads are slow, meaning the bulk trigger didn't work. I tried opening the file in nodejs, writing and then calling sync() on the file descriptor to no avail.
The node process has permission to write to that file.
I tried spawning a process form node that just echos to the file as a debugging step and that works perfectly fine.
Any ideas why writeFile doesn't work are appreciated.
Answer: ♂ As usual, you try to find a solution for hours and the second you ask the question you find it.
I forgot to add a new line when writing to the file, i.e. writeFile(path, 'trigger\n'). echo does that by default.
Comment: Congrats, you actually found a bug (and I looked thru w1 subsystem code, it's old and ugly, one can easily create 50+ cleanup patches for it!) in the kernel code: https://elixir.bootlin.com/linux/latest/source/drivers/w1/slaves/w1_therm.c#L1948. This `if` with followed up `if (!strncmp)` (so, both conditionals) have to be replaced with a single `if (sysfs_streq(...))`. With that it wouldn't require, but allow to still use, bogus `\n`. You may create a patch and send to the kernel mailing list.


Spectral density for the operator $A u = - u''$?

Question: How to prove that the spectral density for the operator $A u = - u''$ on the whole real line is
$$ e(x,y;\lambda) = \frac{\chi(\lambda) \, cos\lambda^{1/2} (x-y)}{2\pi \lambda^{1/2}} $$
where $\chi $ is the Heaviside function.
Thank you in advance
Answer: Let $s=\sqrt{\lambda}$ in the following, with $ds = \frac{1}{2\sqrt{\lambda}}d\lambda$,
$$
      \int_{0}^{\infty}\left(\int_{-\infty}^{\infty}f(y)\frac{\cos\sqrt{\lambda}(x-y)}{2\pi\sqrt{\lambda}}dy\right)d\lambda \\
  = \frac{1}{\pi}\int_{0}^{\infty}\left(\int_{-\infty}^{\infty}f(y)\cos s(x-y)dy\right)ds \\
  = \frac{1}{\pi}\int_{0}^{\infty}\int_{-\infty}^{\infty}f(y)\cos(sy)dy\cos(sx)ds
   + \frac{1}{\pi}\int_{0}^{\infty}\int_{-\infty}^{\infty}f(y)\sin(sy)dy\sin(sx)ds \\
  = \frac{2}{\pi}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(y)\cos(sy)dy\cos(sx)ds+\frac{2}{\pi}\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}f(y)\sin(sy)dy\sin(sx)ds
$$
You can also write the original expression in terms of the exponential form.
Comment: good evening T.A.E. is what you can detail your proof a little because I did not understand how you calculated $e(\lambda,x,y)$. is what you calculated \the spectral density $e_\lambda$ or the spectral family $E_\lambda$? Tank you in advance
Comment: @Z.Alfata : I didn't calculate it. I showed you that it is what you claim it to be by integrating the density to obtain the identity operator expressed, in this case, as the Fourier transforms and their inverses.


Why would one Virtual Host be slower than the rest?

Question: I've got multiple virtual hosts on my Ubuntu server. I am running Apache 2.4 & mod_php. At the moment, one website is receiving a lot of traffic - and it is taking time to respond (6+ seconds at times). However - the other websites on this server are all responding instantly. The server isn't under heavy load:
I've got 16 CPUs and the load is currently: 2.27
I'm nowhere near reaching the max memory as there is 48GB and I'm only using around 10GB.
My Virtual Host config file for the site in question is pretty straight forward:
<VirtualHost 0.0.0.0:8080>
        ServerName MySite.com
        ServerAlias *.MySite.com
        ServerAdmin email@example.com
        DocumentRoot /var/www/html/MySite.com
        ErrorLog ${APACHE_LOG_DIR}/error.log
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

Note that I am using Varnish - which explains the port 8080.
Latest mod_status output for the server:
Server uptime: 1 hour 49 minutes 21 seconds
Server load: 2.70 2.69 2.63
Total accesses: 943706 - Total Traffic: 17.8 GB
CPU Usage: u717.5 s40.96 cu0 cs0 - 11.6% CPU load
144 requests/sec - 2.8 MB/second - 19.8 kB/request
91 requests currently being processed, 24 idle workers

Because this particular site utilises sessions and varnish isn't of any real use to it, I use the following in my default.vcl file to "bypass" varnish altogether:
if (req.http.host ~ "(www)?(mysite).com") {
    set req.http.connection = "close";
    return (pipe);
}

My mpm_prefork.conf file, which applies to all sites on the server:
<IfModule mpm_prefork_module>
        ServerLimit              4000
        StartServers              2
        MinSpareServers           2
        MaxSpareServers          5
        MaxRequestWorkers        4000
        MaxConnectionsPerChild   0
</IfModule>

Screenshot of current top:
Any ideas why this might be happening?
I switched to PHP-FPM using the following mpm_worker settings:
<IfModule mpm_worker_module>
    ServerLimit             250
    StartServers             10
    MinSpareThreads          75
    MaxSpareThreads         250
    ThreadLimit              64
    ThreadsPerChild          32
    MaxClients             8000
    MaxRequestsPerChild   10000
</IfModule>

Site is still taking a while to load - whereas other sites are responding instantly. Top results while using PHP-FPM:

My /etc/php5/fpm/pool.d/www.conf settings:
pm = static
pm.max_children = 1200
pm.start_servers = 16
pm.min_spare_servers = 1
pm.max_spare_servers = 36
pm.max_requests = 800

Answer: mod_php's only running your application in one thread, as that's all it can do - the application's only able to run on one of those 16 CPU cores (confirm in top, one process is probably pegged at 100% of one core)
You'll need to use a different method than mod_php - see here.
Comment: I've added a screenshot of my current top results to the original question. I don't see anything at 100%. You're saying that mod_php will only use 1 of the 16 CPUs regardless of its config?
Comment: I switched to FPM (see original question) and there doesn't seem to be that much improvement - even though the other sites are responding instantly.


Solving restricted/one-sided limits

Question:
Is the function $f(x) = \sqrt{x^{2} - 9}$ continuous at $x = 3$?

I tried to check by solving each requirement for continuity, which are the following:

The limit at the point must exist;
The function at the point must exist;
The limit at the point must be equal to the function at the point.

The second requirement can be easily checked as 'satisfied' as $f(3) = 0$. Thus, I only need to check if the first requirement is satisfied.
I started by solving for the left-hand limit as follows:
\[L^{-} = \lim_{x \to 3^{-}}\left[\sqrt{x^{2} - 9}\right]\]
Then, I eventually got $L^{-}$ to be zero.

My question is this: Is it correct to rewrite the problem by substituting $x = 3 - a$, where $a \geqslant 0$, then solving for the limit as $a$ approaches zero?

Edit: This is a question about solving one-sided limits, and not about the continuity of the square root function.
Comment: It is correct, for this case.
Comment: You've used the notation for a limit from the left (from below), but when $x \lt 3$, the expression $\sqrt{x^2 - 9}$ is not well-defined (as taking the square root of a negative number.  Perhaps you meant for $x$ to approach $3$ from above?
Answer: You do not need to evaluate for left-hand limit simply because it does not belong to the domain of the function. In general for obtaining continuity of boundary point we consider the limiting value of the function as the value of the one-sided limit. Thus if,
$$\lim_{x\rightarrow 3^+}f(x)=f(3)$$
you can say that the function is continuous at $x=3$. as the function is defined only for $|x|\ge3$ assuming you are working over $\mathbb R$.
Comment: I was basically saying that as the function is not defined in $-3<x<3$ we cannot argue that we are approaching x=3 from left since that is logically incorrect as we are square rooting a negative number for a real valued function.
Comment: Yes, I am working over $\mathbb{R}$. Also, I didn't quite get your answer because we need to prove that it is continuous at $x = 3$, thus stating where $f$ is defined for values of $x$ will not help.
Answer: About substitutions in limits in general:
In general, that's absolutely right (here, in particular, something more important is to be noted. See the Addendum). $x\to 3^-$ can be thought of as $x = 3-h$ where $h\to 0^+$ or $x = 3+h$ where $h\to 0^-$. Guess what, that's exactly the substitution you made.
Subtle point to note: You say $x = 3-a$, where $a\ge 0$. While that is perfectly fine (in general it is fine, but for this particular case please check the addendum), I just want to mention that $a > 0$ is no problem either. When talking about $\lim\limits_{a\to 0^+}f(a)$ for some $f$, $a$ is approaching $0$ from the positive side, but is never equal to $0$. Hence, $a>0$ suffices and the substitution $x = 3-a$ works.
Before making substitutions though, one must be extremely careful about the domain of the function.

Addendum/Warning:
The domain of $f(x) = \sqrt{x^2-9}$ is $x^2 \ge 9$, i.e. $|x| \ge 3$ or $x \in (-\infty,-3]\cup [3,\infty)$. So, it does not make sense to talk about the left hand limit at $3$, since values immediately to the left of $3$ are not in the domain of $f$. You may ask, does $$\lim_{x\to 3} \sqrt{x^2-9}$$ still exist? Yes, it does! This is because the only one-sided limit we can even talk about at $3$ is the right-handed one. We define the limit at $3$ to be equal to this one-sided limit.
Comment: Yeah, that's kind of the case here. To find the limit, you are generally supposed to find the left-hand and right-hand limit both, see if they are equal, and that's your answer. When one of the two limits doesn't make sense (like in our case, the left-handed one at $3$), you simply evaluate the one-sided limit that *does make sense* and call that the limit of your function at that point. Sounds good?
Comment: Can I ask if the limit exists and is equal to zero?
Comment: Please see my edit @soupless. It should clarify things further.
Comment: Does that mean that I used limits wrong, but I got the answer _somehow_ correct?
Comment: Ok, that makes more sense.

Solving restricted/one-sided limits


Online estimation of quartiles without storing observations

Question: I need  to compute quartiles   (Q1,median  and Q3)  in real-time on a large set of data without storing the observations.  I first tried the P square algorithm (Jain/Chlamtac) but I was no satisfied with it (a bit too much cpu use and not convinced by the precision at least on my dataset).
I use now the FAME algorithm  (Feldman/Shavitt)  for estimating the median on the fly and try to derivate the algorithm to compute also Q1 and Q3 :
M = Q1 = Q3 = first data value
step =step_Q1 = step_Q3 = a small value
for each new data :
        # update median M
        if M > data:
            M = M - step
        elif M < data:
            M = M + step
        if abs(data-M) < step:
            step = step /2

        # estimate Q1 using M
        if data < M:
            if Q1 > data:
                Q1 = Q1 - step_Q1
            elif Q1 < data:
                Q1 = Q1 + step_Q1
            if abs(data - Q1) < step_Q1:
                step_Q1 = step_Q1/2
        # estimate Q3 using M
        elif data > M:
            if Q3 > data:
                Q3 = Q3 - step_Q3
            elif Q3 < data:
                Q3 = Q3 + step_Q3
            if abs(data-Q3) < step_Q3:
                step_Q3 = step_Q3 /2

To resume, it simply uses median M obtained on the fly  to divide the data set in two and then reuse the same algorithm for both Q1 and Q3.
This appears to work somehow but I am not able to demonstrate (I am not a mathematician) .  Is it flawned ?
I would appreciate any suggestion or eventual other technique fitting the problem.
Thank you very much for your Help !
==== EDIT =====
For those who are interested by such questions, after a few weeks, I finally ended by simply using Reservoir Sampling  with a revervoir of 100 values and it gave very satistfying results (to me).
Comment: @Theja thank you, I am not looking for a proof (too much work) but merely advices and comments,  The main problem I see is to base the computation on running estimate of the median,  as whuber has pointed.
Comment: Are you looking for a proof that Q1 and Q2 converge to the true quantiles as the number of examples increase in a manner similar to the markov chain analysis in the slides you linked? In terms of implementation, the above algorithm does not seem flawed (I tested approximating quantiles for standard normal in R and the algorithm works fine).
Answer: The median is the point at which 1/2 the observations fall below and 1/2 above. Similarly, the 25th perecentile is the median for data between the min and the median, and the 75th percentile is the median between the median and the max, so yes, I think you're on solid ground applying whatever median algorithm you use first on the entire data set to partition it, and then on the two resulting pieces.
Update:
This question on stackoverflow leads to this paper: Raj Jain, Imrich Chlamtac: The P² Algorithm for Dynamic Calculation of Quantiiles and Histograms Without Storing Observations. Commun. ACM 28(10): 1076-1085 (1985) whose abstract indicates it's probably of great interest to you:

A heuristic algorithm is proposed for dynamic calculation qf the
  median and other quantiles. The estimates are produced dynamically as
  the observations are generated. The observations are not stored;
  therefore, the algorithm has a very small and fixed storage
  requirement regardless of the number of observations. This makes it
  ideal for implementing in a quantile chip that can be used in
  industrial controllers and recorders. The algorithm is further
  extended to histogram plotting. The accuracy of the algorithm is
  analyzed.
Comment: This reply overlooks two subtle points, one unimportant but the other possibly very important. The unimportant one is that the double-splitting technique computes the upper and lower *hinges* which can differ slightly from the median, depending on sample sizes. The important one is that the double-splitting appears to be based on a running *estimate* of the median. Any variation between this estimate and the actual median will cause the hinges to vary as well. Intuitively, this should not be a problem as the amount of data grows larger, but it is an issue that needs some analysis.
Comment: @Avraham , thanks for pointing the paper,  as I mentioned I already tried P-square algorithm from Chain and Chlamtac. on my data set the algo I decribed gives a better result (MSE) and is faster. So I was questionning if it could have some problem nevertheless. As whuber remarked the fact that it uses a running estimate is a potential problem ; but  I do not know if its really important or not .
Comment: Wouldn't directly estimating the quartiles be subject to similar issues? Direct estimation would partition the $n$ data points into a $1:3$ ratio. This partitions the elements into $2:2$ and then takes one of those "2"s and splits it $1:1$. I'm no theoretician, true, but, in general, wouldn't the difference between the two be different by at most one spot to the left or right and would converge as $n$ increases? Yes, a pathological distribution could be created, but that would suffer from direct median estimation as well. Obviously, storing all the values is better, of course.
Comment: Whoops, saw that and forgot it. My apologies.
Answer: A very slight change to the method you posted and you can compute any arbitrary percentile, without having to compute all of the quantiles. Here's the Python code:
class RunningPercentile:
    def __init__(self, percentile=0.5, step=0.1):
        self.step = step
        self.step_up = 1.0 - percentile
        self.step_down = percentile
        self.x = None

    def push(self, observation):
        if self.x is None:
            self.x = observation
            return

        if self.x > observation:
            self.x -= self.step * self.step_up
        elif self.x < observation:
            self.x += self.step * self.step_down
        if abs(observation - self.x) < self.step:
            self.step /= 2.0

and an example:
import numpy as np
import matplotlib.pyplot as plt

distribution = np.random.normal
running_percentile = RunningPercentile(0.841)
observations = []
for _ in range(1000000):
    observation = distribution()
    running_percentile.push(observation)
    observations.append(observation)

plt.figure(figsize=(10, 3))
plt.hist(observations, bins=100)
plt.axvline(running_percentile.x, c='k')
plt.show()

Comment: Small correction: according the FAME paper, step is initialized as `self.step = max(abs(observation/2), self.step)`. I think in this case, it would become `self.step = max(abs(observation), self.step)`, since the halving is applied by the `step_up/down` multiples.


local variable referenced before assignment for decorator

Question: I'm using decorator with the functional syntax as it's described here.
I loop over a list of dict. In this loop I wrap a generic function with a decorator taking a parameter. Then i call the wrapped function with the current dict as parameters.
My problem is that i get an local variable 'generic_evaluator' referenced before assignment error.
Here is my code:
The concerned decorator:
def log(logfile_name):
    def inner_log(func):
        def wrapped(*args, **kwargs):
            import os
            ret = func()
            # business code...
        return wraps(func)(wrapped)
    return inner_log

And here the place where I wrap generic_evaluator function with the log decorator.
for evaluation in generic_evaluations:
    generic_evaluator = log(evaluation['suffix'])(generic_evaluator)
    generic_evaluator(evaluation['suffix'], evaluation['id'])

EDIT
It'll be probably more clear with this piece of code in addition:
@tictoc
def generic_evaluator(suffix_url, id):
    xml = etree.parse(get_resource(base_url + "/" + suffix_url + "/" + str(id)))
    links = fetch_urls_from_xml(xml)
    return links

Comment: Why do you think it should work. Here: `log(evaluation['suffix'])(generic_evaluator)` you are using `generic_evaluator`, which is not yet assigned. Hence the error. What exactly are you trying to achieve?
Answer: If generic_evaluator is a global function, and you actually want to rebind the global name generic_evaluator, declare this name as global:
global generic_evaluator

If you don't want to rebind the global name, use a different local name and initialise it:
local_generic_evaluator = generic_evaluator

This answer gives an explanation of what's going on.
Answer: generic_evaluator = log(evaluation['suffix'])(generic_evaluator)

You are referrencing generic_evaluator before assignment here log(evaluation['suffix'])(generic_evaluator)
try this:
for evaluation in generic_evaluations:
    generic_evaluator = log(evaluation['suffix'])(use_some_other_variable)
    generic_evaluator(evaluation['suffix'], evaluation['id'])

Comment: I forgot to precise that ``generic_evaluator`` is already defined. (See my EDIT)
Comment: @renard you ve problem wit this line generic_evaluator = log(evaluation['suffix'])(generic_evaluator)
Comment: It's not another variable i need to use. It is a function object i use here, and it's a function already defined as i said in my edit.
Comment: @renard, `ev = log(evaluation['suffix'])(generic_evaluator)` good for you? or cascade wrapping of generic_evaluator is needed?


Java Swing Use Date for Timer

Question: Trying to make a timer that displays the time that has elapsed since a button has been pressed. I am using a Date instance and am trying to have it be initalized to 00:00:00 and have it increase by seconds, mins, then hours. it works as just a clock of the current time if I do not enter any values into Date currentTime = new date()
Here is my code, I have tried setting the Date to all 0 values, and it displays as all zeros, but when my button is pressed, it no longer functions as a timer. What is the problem?
 Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Date currentTime = new Date(0,0,0,0,0,0);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                laserOnTimeTF.setText(sdf.format(currentTime));
            }
        });

        laserOnOff.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!laserSetting) {
                    timer.start();
                    laserSetting = true;
                    laserOnOff.setText("Laser On");
                } else {
                    timer.stop();
                    laserSetting = false;
                    laserOnOff.setText("Laser Off");
                }

            }
        });

Comment: I recommend you don't use `Date`. That class is poorly designed and long outdated. And even if you insist (1) Don't use `Date` for a duration, an amount of time, it's something completely different. (2) Don't use the 6-arg constructor, it's been deprecated for decades (literally) because it's unreliable. Instead use `Duration` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/).
Answer: That Date constructor is deprecated, like all Date constructors other than the one that takes a milliseconds argument.  APIs are deprecated for a reason, usually because they don't work as intended.  To be notified when you use deprecated APIs, turn on all compiler warnings in your IDE, and pay attention to those warnings.
Date is not a good fit for storing elapsed time, since it represents an absolute point in time.  The class which is designed to represent a time difference is java.time.Duration.
You can calculate a Duration from two time values.  The simplest time value is probably Instant, so you will want a private field of type Instant in the class which creates the Timer and adds a listener to the button, to keep track of when the button was pressed:
private Instant timeOfLastButtonPress;

Then you can initialize it each time the button is actually pressed:
laserOnOff.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (!laserSetting) {
            timeOfLastButtonPress = Instant.now();
            timer.start();
            laserSetting = true;
            laserOnOff.setText("Laser On");
        } else {
            timer.stop();
            laserSetting = false;
            laserOnOff.setText("Laser Off");
        }
    }
});

Finally, your Timer can calculate the Duration using Duration.between:
Duration elapsedTime =
    Duration.between(timeOfLastButtonPress, Instant.now());

If you're using Java 9 or later, you can extract the numbers from a Duration directly:
Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Duration elapsedTime =
            Duration.between(timeOfLastButtonPress, Instant.now());
        laserOnTimeTF.setText(String.format("%02d:%02d:%02d",
            elapsedTime.toHoursPart(),
            elapsedTime.toMinutesPart(),
            elapsedTime.toSecondsPart()));
    }
});

In Java 8, you will need to calculate it yourself:
Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        Duration elapsedTime =
            Duration.between(timeOfLastButtonPress, Instant.now());
        laserOnTimeTF.setText(String.format("%02d:%02d:%02d",
            elapsedTime.toHours(),
            elapsedTime.toMinutes() % 60,
            elapsedTime.getSeconds() % 60));
    }
});

Comment: Oops, my mistake, it's `getSeconds()` in Java 8.  Answer updated accordingly.  And clarified where the private Instant field should go.
Comment: also for  the ```elapsedTime.toSeconds()``` i get an error, it says that ```.toSeconds has private access in java.time.duration``` ?

Java Swing Use Date for Timer


HLA (Higher Level Assembly) Installation and Linker

Question: I am trying to install the executalbles to compile programs in HLA on a Mac OS 10.8. Although the tools seem to be in the right place and working I am getting the following error when trying to compile the first program
ld: warning: -macosx_version_min not specified, assuming 10.8
Undefined symbols for architecture i386:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture i386
Error returned by ld = 256

The hla executalbe seems to output the object file but something in the linker seems to not be working. I have previously managed to install it on other machines but in most cases I get this error.
Any ideas?
Answer: You can tell HLA to use "_main" as the entry point by using "-main:_main". You may also need to link with libSystem.dylib and get rid of some linker warnings, so that the whole command would be
hla -main:_main -l"macosx_version_min 10.9" -l"lSystem" -l"no_pie" source.hla
Comment: I ended up adding a shell function in my .bashrc  hlac() { hla -main:_main -l"macosx_version_min 10.9" -l"lSystem" -l"no_pie" $1; }
Comment: Is there a way I can add this somewhere so I don't have to type it into the terminal every time, or is that wishful thinking?
Comment: It's possible to use XCode's build system with HLA.  Create a project of type 'External Build Tool' and set the build tool to `/usr/bin/make`. Create a Makefile with the accepted answer's command line as the action for your target, add in the 'hlalib' and 'hlainc' to your build settings, as well as the path to the hla directory (PATH is `$(PATH):/path/to/hla`).  Building should now produce a runnable binary in the source directory.  You don't get syntax highlighting but you do get an IDE.  Rinse and repeat with your Makefile to add in more files.


How show that: $A, B, C$ are collinear iff $\frac{\overline{GF}}{\overline{GH}}=\frac{\overline{JI}}{\overline{JK}}$

Question: In the figure two red lines are parallel.
How show that: $A, B, C$ are collinear iff $\frac{\overline{GF}}{\overline{GH}}=\frac{\overline{JI}}{\overline{JK}}$
Answer:
Consider this assertion instead: $A, B, C$ are colinear iff the cross-ratio of $F, G, H, R$ is equal to the cross-ratio of $I, J, K, R$. It can be easily proven using the cross-ratios of the two pencils centered at $P$ and $Q$. And when $R$ becomes the infinite point, the assertion becomes the original question.


Repositioning and resizing when i change the size of my frame

Question:
Moderator's Note: This question is cross-posted on gamedev.SE.

I am trying to write a game.
When someone resizes the window of my game, I need all the graphics i have drawn on the screen to reposition correctly so that the ratio of the graphics' width and height remain correct and that the new position determined by x and y, have been adjusted for the new size screen.
In the following image, the top left corner is 0,0... all coordinates / widths / heights are measured from this point.

What do I need to do to x, y, width and height from the variable width and height of my screen in order to keep this aspect ratio correct?
SIDE NOTE: the aspect ratio of the screen will always be 16:9!
Comment: All you have to do is to multiply the coordinates by the scaling factor.
Comment: This seems like it might be better over on gamedev.SE; I've suggested to the mods that it be moved.
Comment: Note, this question has been crossposted to [gamedev.se](http://gamedev.stackexchange.com/questions/57378/repositioning-and-resizing-when-i-change-the-size-of-my-window). Crossposting without at least mentioning that you are crossposting is considered rude and begs to have redundancy in answers across the sites.
Comment: @mixedmath - No, what is rude is that you assume i am doing this without due care and maliciousness. I have asked in two places because this is both a math question and a code question. Here i get a formula i can understand, in the other site I get a bit of code to help me see what others do. Please do not assume things, it's extremely unfair. Doing what i have done has meant i have an accurate solution to my problem and i truly understand the entirety of the solutions.
Answer: Here's an idea, assign each pixel as follows:
$$
x_1=\left\lfloor x_0\cdot \frac{1376}{1920}\right\rfloor \\
y_1=\left\lfloor y_0\cdot \frac{768}{1080}\right\rfloor
$$
where $(x_0,y_0)$ are the large screen coordinates, and $(x_1,y_1)$ are the small screen coordinates.
Obviously, there are more pixels in the bigger screen than in the small screen, so some pixels map to the same location.  In those cases, you need some way of choosing which pixel to take.
This method will change the proportions very slightly.
Comment: Rightt, let me run this through my code.. hang on :)


Prove the relationship between Walsh averages and Wilcoxon signed rank test

Question: In my lecture notes it is stated that

sum of all positive signed ranks (defined in Wilcoxon signed rank test) = the number of Walsh averages that are greater than median

How can I prove this statement?
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info).
Answer: For clarity: The sample Walsh averages are the pairwise averages $(x_i+x_j)/2$, $i=1,2,...n,$ $j=1,...,i$. The median of the Walsh averages is the Hodges-Lehmann estimator, also called the pseudo-median.
Here's some (hopefully useful) hints to get you started -- which is basically one of several ways to just arrange the calculation methodically, but it makes it easier to see the connections between the two calculations.
Here the observations are from a single sample (in the case of a paired test the observations are the pair-differences, at which point we're dealing with a single sample of pair-differences). Further assume that the $X$'s are continuous (so for example, there are no tied ranks and no Walsh averages at 0)
Consider without loss of generality that we're comparing to a specified median of zero.
Let $X_i = S_i M_i$ where $M_i=|X_i|$ and $S_i = \mathop{\mathrm{sgn}}(X_i)$ (and similarly for $j$, when we deal with pairs of observations).
Then let $R_i = \mathop{\mathrm{rank}}(M_i)$. We now have some notation in place to describe the basic components of the signed rank test.
Now order the $X$-values from smallest magnitude to largest magnitude (i.e. sort them by the $M$-values).
(It helps to play with a small numerical example. Consider data values $1.0, -2.4, 3.6$ say -- these have deliberately been ordered as just described)
Write an $n \times n$ table with row and column headings being the ordered $X_i$ values (you may like to write a small $(S_i,R_i)$ under the columns).
Inside the table, for values on or above the main diagonal, put a "+" if the Walsh average of the corresponding row- and column- $X$-values is above 0 and "-" if it's below it. For each column, count how many "+" values there are.
Note that looking down a column we're just seeing $X_i$ compared with each other value that is no larger in magnitude than $X_i$ (i.e. with each observation to it's left in the ordered list, plus itself).
For the column labelled $X_i$, the count will either be positive or $0$. What determines which of the two things it is? Now note the connection between the column "+" count and $R_i$.
Hopefully you should be able to work your way to an argument from that.

Here's the example I mentioned above. Note that if $X$'s are 1.0, -2.4,  3.6 then the signed ranks are +1, -2 and +3:
<code>           1.0  -2.4   3.6
     1.0    +     -      +
    -2.4          -      +
     3.6                 +

    (S,R)  +,1   -,2    +,3
</code>
It should be clear that if $S_i$ is $-1$ then there are no "+" terms in the column of positive Walsh averages, but if  $S_i=+1$ then there are $R_i$ positive Walsh averages. What you need to do is make this observation a bit more formal and then argue a small step to the needed result from that.
Comment: Because "Walsh average" is a fairly obscure term--there isn't even a Wikipedia reference, much less an entry for it--it would be nice to include a definition or explanation of it in your answer.
Comment: @whuber Good thought. Done
Comment: @Glen_b What happen if you change 1.0 by 2.6? How do we interpret the table? This contradicts the fact that if $S_i$ is −1 then there are no "+" terms in the column of positive Walsh-averages,
Comment: I'm sorry I don't quite follow what you're asking. Perhaps you could ask a new more explicit question (i.e. give complete details of the sample and so on); you can refer back to this one with a link if need be.
Answer: I'll give a direct proof:
Suppose we have continuous data $X=(X_1, ..., X_n)$, assumed to be symmetric about the mean $\mu$. We consider the hypothesis $H_0: \mu_0 = \mu$.
The signed rank statistic is:
\begin{equation}
W(X)=\sum_{i=1}^n{Z_iR_i}
\end{equation}
where
\begin{equation}
Z_i = \mathbb{I}(X_i>\mu_0)
\end{equation}
and $R_i$ is the rank of $|X_i-\mu_0|$ in $\{ |X_1-\mu_0|,...,|X_n-\mu_0|\}$, that is,
\begin{equation}
R_i=\sum_{j=1}^n{\mathbb{I}(|X_j-\mu_0|\leq|X_i-\mu_0|)}
\end{equation}
Now
\begin{equation}
W(X)=\sum_{i=1}^n\sum_{j=1}^n{\mathbb{I}(|X_j-\mu_0|\leq|X_i-\mu_0|, X_i>\mu_0)}\\
=\sum_{i=1}^n\sum_{j=1}^n{\mathbb{I}(|X_j-\mu_0|\leq X_i-\mu_0, X_i>\mu_0)}\\
=\sum_{i=1}^n\sum_{j=1}^n{\mathbb{I}(|X_j-\mu_0|\leq X_i-\mu_0)}
\end{equation}
We can remove dependence on the $X_i>\mu_0$ as the remaining indicator function will return zero if $X_i<\mu_0$.
\begin{equation}
W(X)=\sum_{i=1}^n\sum_{j=1}^n{\mathbb{I}(\mu_0-X_i \leq X_j-\mu_0\leq X_i-\mu_0)}\\
=\sum_{i=1}^n\sum_{j=1}^n{\mathbb{I}(2\mu_0\leq X_j+X_i\leq 2X_i)}\\
=\sum_{i=1}^n\sum_{j=1}^n{\mathbb{I}\left(\frac{X_i+X_j}{2}\geq \mu_0,X_j\leq X_i\right)}\\
=\sum_{1\leq i\leq j \leq n}{\mathbb{I}\left(\frac{X_i+X_j}{2}\geq \mu_0\right)}
\end{equation}
The justification for this last step is that we see the order of $X$ makes no difference to the value of the statistic, so we may assume WLOG it is decreasing, in which case $X_j\leq X_i \Rightarrow i\leq j$.


Query for retrieving top two rows from a table in SQL Server

Question: I have a table called Employee with the following fields:

EmpID
Salary
Name

I want to get top two employees with maximum salary.  How do I write this query ?
Answer: SQL Server 2000+:
  SELECT TOP 2
         e.*
    FROM EMPLOYEE e
ORDER BY e.salary DESC

MySQL & Postgres:
  SELECT e.*
    FROM EMPLOYEE e
ORDER BY e.salary DESC
   LIMIT 2

Oracle:
SELECT x.*
  FROM (SELECT e.*,
               ROWNUM as rn
          FROM EMPLOYEE e
      ORDER BY e.salary DESC) x
 WHERE x.rn <= 2

Oracle: ROW_NUMBER vs ROWNUM
Answer: Try this ..
SELECT * from Employee  order by Salary  desc limit 2 ;

Comment: Or, if using SqlServer, _select top 2 * from employees order by salary_.
Answer: SELECT TOP 2 * FROM Employee ORDER BY Salary DESC;
Answer: You should write something like this.
SELECT TOP 2 EmpID,Salary,Name FROM Employee ORDER BY Salary
Answer: Yet another solution:
With NumberedItems As
    (
    Select EmpId, Salary, Name
        , Row_Number() Over ( Order By Salary Desc ) As SalaryRank
    From Employee
    )
Select EmpId, Salary, Name
From NumberedItems
Where SalaryRank <= 2

Comment: `ROW_NUMBER()` (CTE too) is SQL Server 2005+
Comment: Although technically the OP did not specify the version of SQL. Technically, it could have been SQL Server 4.2 in which the TOP command would not exist. ;)


How to find the longest interval of 1's in a list [matlab]

Question: I need to find the longest interval of 1's in a matrix, and the position of the first "1" in that interval.
For example if i have a matrix: [1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 ]

I need to have both the length of 7 and that the first 1's position is 11.
Any suggestions on how to proceed would be appreciated.
Answer: Using this anwser as a basis, you can do as follows:
a = [1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 ]

dsig = diff([0 a 0]);
startIndex = find(dsig > 0);
endIndex = find(dsig < 0) - 1;
duration = endIndex-startIndex+1;
duration

startIdx = startIndex(duration == max(duration))
endIdx = endIndex(duration == max(duration))

This outputs:
duration =

     1     3     7

startIdx =

    11

endIdx =

    17

Please note, this probably needs double checking if it works for other cases than your example. Nevertheless, I think this is the way in the right directions. If not, in the linked anwser you can find more info and possibilities.
Answer: If there are multiple intervals of one of the same length, it will only give the position of the first interval.
A=round(rand(1,20)) %// test vector
[~,p2]=find(diff([0 A])==1); %// finds where a string of 1's starts
[~,p3]=find(diff([A 0])==-1); %// finds where a string of 1's ends
le=p3-p2+1; %// length of each interval of 1's
ML=max(le); %// length of longest interval
ML %// display ML
p2(le==ML) %// find where strings of maximum length begin (per Marcin's answer)

Answer: I have thought of a brute force approach;
clc; clear all; close all;
A=  [1 0 0 1 1 1 0 0 0 0 1 1 1 1 1 1 1 ];
index = 1;
globalCount = 0;
count = 0;
flag = 0; %// A flag to keep if the previous encounter was 0 or 1
for i = 1 : length(A)
    if A(i) == 1
        count = count + 1;
        if flag == 0
            index = i
            flag = 1;
        end

    end
    if A(i) == 0 || i == length(A)
        if count > globalCount
            globalCount = count;
        end
        flag = 0;
        count = 0;
    end

end


Menu hide/show ao clicar

Question: Estou com uma duvida estou utilizando Wordpress
esse é meu jquery para pegar o link que eu estou clicando e atravez de uma ancora ID # ele desce o scroll ate o conteudo desejado porem preciso que esconda tudo e quando clicar apareça somente o conteúdo clicado.
$('.sub-menu a').click(function() {
    var anchor;
    var link = $(this).attr('href');
    if (link.indexOf('#') !== -1) {
        anchor = '#' + link.split('#').pop();
    }

    if (anchor !== undefined) {
        show().$(anchor)
        $('html, body').animate({scrollTop: $(anchor).offset().top}, 2000);
    }

});

Comment: Cara coloca pelo menos seu HTML ai, está meio difícil de entender o que vc quer...
Comment: resolvi fiz assim $('.sub-menu a').click(function() {
        var anchor;
        var link = $(this).attr('href');
        if (link.indexOf('#') !== -1) {
            anchor = '#' + link.split('#').pop();
        }
        $('.id-sub').slideUp("slow");
         if (anchor !== undefined) {
            $(anchor).slideDown("slow");

         }

    });
Answer:  $('.sub-menu a').click(function() {
    var anchor;
    var link = $(this).attr('href');
    if (link.indexOf('#') !== -1) {
        anchor = '#' + link.split('#').pop();
    }
    $('.id-sub').slideUp("slow");
     if (anchor !== undefined) {
        $(anchor).slideDown("slow").addClass('#sobre');

     }

});

Menu hide/show ao clicar


Retornar todos os valores de uma determinada propriedade em uma Array de objetos Javascript

Question: Tenho uma determinada array
var people = [
  {
    name: 'Leandro',
    age: 36
  },
  {
    name: 'Joaquim',
    age: 29
  },
  {
    name: 'Maria',
    age: 25
  }
]

Se desejo retornar a propriedade name na primeira posição faço o seguinte
console.log(people[0].name)

Como faço para retornar todos os nomes contidos na propriedade name?
O resultado desejado é esse:
Leandro, Joaquim, Maria
Answer: Você cria uma nova array utilizando o método map da array original:

var people = [
  {
    name: 'Leandro',
    age: 36
  },
  {
    name: 'Joaquim',
    age: 29
  },
  {
    name: 'Maria',
    age: 25
  }
];
var names = people.map(person => person.name);
console.log(names);


Update row in a table based on multiple rows in another table

Question: I have two tables: table1 and table2:

table1 has columns id and integer
table2 has columns id and boolean
table2 can have multiple rows with the same id

I want to update the integer column of table1 by looking at all rows with the same id in table2 and seeing if any of the boolean values are true. If so I want table1.integer to be 1, else I want it to be 0.
I have tried something like this:
UPDATE table1,
(
   SELECT table2.id, Sum(table2.boolean) > 0
) AS 'condition'
from     table2
WHERE    1
GROUP BY table2.id) table3
SET table1.integer =IF(table3.condition, 1, 0) where table1.id = table3.id

And it seems to work, but I wanted to ask if there is a nicer/cleaner/more succinct way of updating the rows of table1 according to multiple rows of table2.
Comment: First figure out which RDBMS you're using. Then see: [Why should I provide an MCRE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-a-minimal-reproducible-example-for-a-very-simple-sql-query)
Comment: What RDBMS are you really using, you tag 2 here (I have removed them). The above looks like you're trying to `UPDATE `the values of 2 tables at the same time (one via a subquery); a DDL operation can only effect 1 object at a time, not many, and it can't reference a subquery (though you can create updatable CTEs).
Answer: I would recommend EXISTS:
UPDATE table1 t1
    SET t1.integer = (EXISTS (SELECT 1
                              FROM table2 t2
                              WHERE t2.id = t.id AND
                                    t2.boolean
                             )
                     );

This can take advantage of an index on table2(id, boolean).  With such an index, it should be faster than an approach that uses JOIN and AGGREGATION.
Answer: The syntax of your query is MySql like, so you can do a join like this:
UPDATE table1 t1 INNER JOIN (
  SELECT id, MAX(boolean) maxboolean
  FROM table2
  GROUP BY id
) t2 ON t2.id = t1.id
SET t1.integer = t2.maxboolean

If there are ids in table1 without a corresponding id in table2 and you want the integer column for them to be updated to 0 then use a LEFT join:
UPDATE table1 t1 LEFT JOIN (
  SELECT id, MAX(boolean) maxboolean
  FROM table2
  GROUP BY id
) t2 ON t2.id = t1.id
SET t1.integer = COALESCE(t2.maxboolean, 0)


R: Import data from multiple file paths and store in a list

Question: I have some data which I would like to read in from seperate .txt files based on individual paths. A sample folder structure with txt files can be downloaded here.
The (sample) data.frame I have looks like this
data <-   structure(list(Name = structure(c(1L, 3L, 4L, 2L), .Label = c("Test1", "Test10", "Test2", "Test6"), class = "factor"), Metadata = structure(c(3L, 4L, 1L, 2L), .Label = c("asdajl7", "asfhas", "sgash", "uashas8"), class = "factor"), Filepath = structure(c(2L, 3L, 4L, 1L), .Label = c("", "Folder1/File8.txt", "Folder7/file2.txt", "Folder9/File19.txt"), class = "factor")), .Names = c("Name", "Metadata", "Filepath"), class = "data.frame", row.names = c(NA, -4L))

data
    Name Metadata           Filepath
1  Test1    sgash  Folder1/File8.txt
2  Test2  uashas8  Folder7/file2.txt
3  Test6  asdajl7 Folder9/File19.txt
4 Test10   asfhas

In order to make a reproducible example I tried to implement the following function to adjust the filepath to the place where you saved the Folder structure from the Download above.
# Choose path to unzipped Data directory
choose.dir <- function() {
  system("osascript -e 'tell app \"R\" to POSIX path of (choose folder with prompt \"Choose Data Folder:\")' > /tmp/R_folder",
         intern = FALSE, ignore.stderr = TRUE)
  p <- system("cat /tmp/R_folder && rm -f /tmp/R_folder", intern = TRUE)
  return(ifelse(length(p), p, NA))
}
a <- choose.dir()
if(is.na(a)) stop("No folder", call. = F)
# paste ready to use path together
data$completepath <- paste0(a,"/",data$Filepath)
data$completepath <- gsub("//", "/", data$completepath)

The data.frame now looks like this (I unzipped the folder structure to my Desktop):
data
    Name Metadata           Filepath                               completepath
1  Test1    sgash  Folder1/File8.txt  /Users/XYZ/Desktop/Data/Folder1/File8.txt
2  Test2  uashas8  Folder7/file2.txt  /Users/XYZ/Desktop/Data/Folder7/file2.txt
3  Test6  asdajl7 Folder9/File19.txt /Users/XYZ/Desktop/Data/Folder9/File19.txt
4 Test10   asfhas                                      /Users/XYZ/Desktop/Data/

How could I read in the data from the different .txt files using a loop so that I get the following list structure?
   List with 3 elements
        1.1 (5 observations and 5 Variables)
        $Name chr[1:5] Test1 Test1 Test1 Test1 Test1
        $Year num[1:5] 1783 1784 1785 1786 1787
        $data1 num[1:5] 12 53 13.1 12.9 16
        $data2 num[1:5] 56 5 532 27 9
        $data3 num[1:5] 0.1 9 42 2 13
        1.2 (4 observations and 3 variables)
        $Name chr[1:4] Test2 Test2 Test2 Test2
        $Year num[1:4] 1387 1388 1389 1390
        $data num[1:4] 78.9 27 12.3 0.9
        1.3 (3 observations and 3 variables)
        $Name chr[1:3] Test6 Test6 Test6
        $Test1 chr[1:3] hajshf asfhah ashsa
        $Year num[1:3] 2001 2002 2003

What I tried is the following, but this doesn't work as the empty filepath of Test10 is causing problems. Can someone help me?
# read in the data
f <- file.path(data$completepath)
d <- lapply(f, read.table)

Answer: You don't have to do it this way, you could write the path out instead
setwd("/home/christie/Downloads/Data/")

This will give all of the paths to every file in the working directory
files<-list.files(getwd(),recursive=TRUE)

This reads them all into the list
d<-lapply(files,function(x) read.table(x, header=T))

str(d)
List of 3
 $ :'data.frame':   5 obs. of  4 variables:
  ..$ data1: num [1:5] 12 53 13.1 12.9 16
  ..$ data2: int [1:5] 56 5 532 27 9
  ..$ data3: num [1:5] 0.1 9 42 2 13
  ..$ year : int [1:5] 1783 1784 1785 1786 1787
 $ :'data.frame':   4 obs. of  2 variables:
  ..$ data: num [1:4] 78.9 27 12.3 0.9
  ..$ year: int [1:4] 1387 1388 1389 1390
 $ :'data.frame':   3 obs. of  3 variables:
  ..$ data1: int [1:3] 18 39 371
  ..$ Test1: Factor w/ 3 levels "asfhah","ashsa",..: 3 1 2
  ..$ Year : int [1:3] 2001 2002 2003

Comment: this works partially, thank you! but with this approach all the data in the 'Data' folder is read in. For example if I have some additional files and folders I don't want to have imported I am running into problems as this approach imports everything...
Comment: You'd need to manually remove the paths from files that you do not wish to read, or if there is something shared amoung all file names or folder names that are not to be read you can write a script to remove them from files. You could also just move the folders and/or files out of ../Data/ that you didn't want.


Submit form on press of specific key

Question: Is there any way how to submit form when you press some predefined key on your keyboard (for example ; key)? I was thinking about something with onkeypress, but dont know how to set it just for one specific key.
Answer: Yes, and you were right with thinking onkeypress, just pass in the event, and check which key is pressed with event.which:
function keyPressed(event) {
    if (event.which == 186) //keycode for semi-colon
        console.log("Semi-colon pressed!");
    }
}

Now just attach this function to a keypress handler.
Edit: Got the keycodes from here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Answer: You'll want to get the keycode and submit the form if it's the right keycode.
To get the keycode from an event, do:
$(document).on("keypress", function(event) {
    var keyCode = event.keyCode;
    var keyWhich = event.which;
    if(keyCode = 'yourkey' || keyWhich = 'yourkey') {
        $(form).submit();
    }
});

For a full list of keycodes to replace 'yourkey' with, I'd recommend something like this cheat sheet. Just type your key in the input and use whatever value it provides as your function's logic
Answer: You can do this in jQuery:
$(document).ready( function() {
    $(document).keydown(function(e){
        if (e.keyCode == 186) { // ; key
           $('#theform').submit();
        }
    });

});

See fiddle.

Submit form on press of specific key


Função Recursiva no TypeScript retornando Array com Objetos Dinâmico

Question: Sou iniciante no TypeScript e tb no JavaScript, portanto confesso não ter muito conhecimento da linguagem, portanto, vou descrever meu problema.
Tenho a seguinte tabela em um banco de Dados PostGres:

Como podem ver, uma estrutura simples onde um registro referencia o outro em um estrutura pai-filho hierárquica.
O que preciso fazer é uma função no typescript que seja recursiva que me retorne um array com objetos mais ou menos assim:
[
  {
    id: 1,
    filhos: [
      {
        id: 11,
        filhos: null
      },
      {
        id: 12,
        filhos: [
          {
            id: 121,
            filhos: null
          },
          {
            id: 122,
            filhos: null
          },
          {
            id: 123,
            filhos: null
          },
          {
            id: 124,
            filhos: null
          }
        ]
      }
    ]
  },
  {
    id: 2,
    filhos: [
      {
        id: 21,
        filhos: null
      },
      {
        id: 22,
        filhos: null
      },
      {
        id: 23,
        filhos: null
      }
    ]
  }
]

Reparem que o Objeto Pai contem todos os seus filhos dentro, e assim sucessivamente.
Alguém pode me ajudar?
Answer: Supondo que você tenha recebido um array com os dados do Postgres, da seguinte maneira:
var arr = [
  {id: 1, idPai: null},
  {id: 2, idPai: null},
  {id: 11, idPai: 1},
  {id: 12, idPai: 1},
  {id: 21, idPai: 2},
  {id: 22, idPai: 2},
  {id: 23, idPai: 2},
  {id: 121, idPai: 12},
  {id: 122, idPai: 12},
  {id: 123, idPai: 12},
  {id: 124, idPai: 12}
];

Um exemplo de código pra percorrer o teu array e montar a hierarquia recursivamente:
var resultado = [];

function teste(arrEntrada, arrSaida){
    for (let i = 0; i < arrEntrada.length; i++) {
        let item = arrEntrada[i];
        let obj = {
            id: item.id,
            filhos: []
        };
        let filhos = arr.filter(elemento => elemento.idPai === item.id);
        teste(filhos, obj.filhos);

        arrSaida.push(obj);
    }
}

teste(arr.filter(elemento => elemento.idPai === null), resultado);
console.log(JSON.stringify(resultado));

Você pode facilmente adaptar para outros tipos de retornos.
Este exemplo está em Javascript puro, mas pode ser usando dentro do teu TS sem problemas
Aqui o fiddle para teste.
Answer: Um jeito bem simples apenas utilizando o método filter

const arr = [
  { id: 1, idPai: null },
  { id: 2, idPai: null },
  { id: 11, idPai: 1 },
  { id: 12, idPai: 1 },
  { id: 21, idPai: 2 },
  { id: 22, idPai: 2 },
  { id: 23, idPai: 2 },
  { id: 121, idPai: 12 },
  { id: 122, idPai: 12 },
  { id: 123, idPai: 12 },
  { id: 124, idPai: 12 }
];

let resultado = arr.filter(pai => {
  pai.filhos = arr.filter(filho => filho.idPai === pai.id);
  return pai.idPai === null
});

// Apenas para demonstrar a saída!
document.querySelector('pre').innerHTML = JSON.stringify(resultado, null, 2);


SBT Scala Assembly Plugin

Question: How to enable Assembly plugin on my repo. https://github.com/rmuhamedgaliev/skala-skeleton i tried fix them. But can't run this with command sbt assembly]

assembly
  [error] Not a valid command: assembly
  [error] Not a valid project ID: assembly
  [error] Expected ':' (if selecting a configuration)
  [error] Not a valid key: assembly
  [error] assembly
  [error]         ^
  exit
Answer: You're missing some configuration (which is in details described here).
First you have to import sbtassembly.Plugin._ before importing AssemblyKeys.
import sbtassembly.Plugin._
import AssemblyKeys._

Then you have to add settings to your build (note extra assemblySettings):
lazy val root = Project(
  "root",
  file("."),
  settings = buildSettings ++ assemblySettings ++ Seq (
    libraryDependencies ++= rootDependencies
  )
)

SBT Scala Assembly Plugin


jQuery click function change body overflow property

Question: I'm using a very simple piece of code to change the body overflow to hidden when a pop up fades in.
$(".more").click(function() {
    $(".about-pop").fadeIn(1000);
    $('body').css('overflow', 'hidden');
});

$(".close").click(function() {
    $('body').css('overflow', 'visible');
    $(".about-pop").fadeOut(1000);
});

Related HTML:

    <?php the_field('about'); ?>

<?php the_field('about_intro'); ?>

My problem is, when the user clicks .more the viewport jumps to the top of the html document
so when the user clicks .close they are not in the same place. I've used this technique before and never had this problem.
Comment: can you create jsfiddle for such questions?
Comment: in short you need a simple popup right..?
Answer: in my understanding you have some issue with positioning, so i have added the following styles and it works fine.
let me know if this helps or please clarify your question using jsfiddle.
i have added the following styles

thanks


Survival event simulation with time-varying confounders and treatment-confounder feedback

Question: I'm trying to generate survival data that contain time-varying treatment and time-varying confounding. The goal is to test inverse probability of treatment method developed by Hernan and James Robins.
Ideally, the simulation process could be realistic, i.e., reflecting some real physical/physiological processes (e.g., patient progression, nuclear decay, events in computing cluster, etc). The simulator should be able to generate a sequence of time-varying confounders, a sequence of actions, and the final event time. It's even better if we have access to the groundtruth hazard curves.
I haven't been able to find a good reference. Could anyone give a pointer to existing literature or possible directions that I can explore?
Answer: Havercroft & Didelez (2012) wrote exactly about this problem. You can also check out the simcausal R package, which provides an interface for simulating data for causal inference applications.


Onde armazenar arquivos binários nos unit tests do JUnit com Maven?

Question: Eu tenho a seguinte estrutura de diretório para a pasta resource dos unit tests:
src/test/resources/*.files

Para que eu possa ler arquivos binarios (como um PDF por exemplo) para concluir um unit test, estou colondo estes arquivos na pasta test/resources, porém lendo a documentação do Maven, esse diretório é apropriado para arquivos que são carregados em runtime, e tais arquivos seriam chamados com getClass().getClassLoader().getResourceAsStream().
Qual seria a melhor prática para armazenar e ler arquivos PDF que serão utilizados para testes em um ou mais unit test?
Answer: O correto é colocar nesse diretório mesmo. Quando você executar o teste, os arquivos serão lidos em runtime, só que no runtime do teste. Então o que a documentação diz também está correto.
Você deve criar uma estrutura de pasta igual a estrutura da classe que será testada. Exemplo, digamos que a classe que irá ler o pdf se chama PdfReader e que ela esteja nessa hierarquia:
-src/main/java
    -com/example/PdfReader.java

O seu arquivo de teste deverá seguir a mesma hierarquia, dessa forma:
-src/test/resources
    -com/example/arquivo.pdf

A única diferença é que o diretório root da classe java é o src/main/java e o diretório root do arquivo de teste é o src/test/resources
Como o arquivo será lido fica a seu critério. Você pode usar tanto o getClass().getResource("") quanto o getClass().getResourceAsStream(""). Vai depender se você precisa de uma stream ou não.
Comment: Além do getClass().getResource(), eu posso utilizar o FileInputStream? Pq geralmente usam o getClass().getResource() e não um File, FileInputStream e similares para ler arquivo nos unit test?
Comment: Não tem problema usar o `FIleInputStream`, o que você tem que se atentar é que o seu teste unitário tem que rodar em qualquer máquina. Se você usar o `FileInputStream`, você não pode usar um path que só existe na sua máquina. O `getResource` irá procurar o arquivo na pasta resources do projeto independente de qual diretório o projeto se encontra. Se os arquivos necessários também forem comitados, qualquer um que baixar o seu projeto vai conseguir rodar os testes unitários.
Comment: O mesmo comportamento pode ser alcançado utilizado o `FIleInputStream`, porém pode dar mais trabalho porque você vai ter que montar o path na mão. O correto é colocar os arquivos na pasta resources, então não faz muito sentido não usar os métodos que já buscam os arquivos de lá.


How to select the anchor tag which is inside the li in Selenium WebDriver?

Question: Below is my code. I want to click the anchor tag , which is inside the
. I have tried to get the value using By.tagName("//li/a"). I didn't get any data.
There are many lists with class="dropdown-menu" in my HTML. I should be able to select a single list from which to click the drop down values.

1

2

3

4

5

6

7

8

9

10

Comment: Show what you tried. What do you mean "between the anchor tag"? There are no other elements between the anchor tags.
Comment: What element between the anchor tag? Did you just mean the anchors text ?
Comment: I have tried the following code to click the element:List drop = button.findElements(By.tagName("//li/a"));
   for(int i=1; i<drop.size(); i++){
    if(!(drop.get(i).getText().isEmpty())){
    drop.get(3).click();} Here i have tried to click the value 3 from the drop down.
Comment: Please update the code into your question, it's far easier to read from there.
Answer: It's easy to get list of all anchors, just use CSS Selectors
List<WebElement> anchors = webDriver.findElement(By.cssSelector("ul li a"));

Then choose whatever anchor you want to click at, let's say
anchors.findElement(By.linkText("10")).click();

Answer: First get the NodeList of the anchors:
var res = document.querySelectorAll('ul.dropdown-menu li a.dropdown-add');

Then force a click on the 3rd, if it's not empty:
if(res[2].childNodes[0].nodeValue.length) { res[2].click() };

Comment: OP mistagged the question, this isn't about JavaScript.


the literal x of type int is out of range

Question: The method is the following:
public static long repeatedString(String s, long n) {

    int convertedLong = (int) n;
    String repeated = new String(new char[convertedLong]).replace("\0", s);
    System.out.println(repeated);

    long numberOfAs = 0;
    for (int i = 0; i < convertedLong; i++ )
    {
        if (repeated.charAt(i) == 'a')
        {
            numberOfAs += 1;
        }
    }
    System.out.print(numberOfAs);
    return numberOfAs;
}

method works fine when the parameter n is small, however when it is large like 1000000000000 it throws an exception:
The literal 1000000000000 of type int is out of range

Comment: The biggest int is 2147483647.
Comment: Yes, you have to use `long` instead of int when using too high numbers
Comment: [`java.math.BigInteger`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigInteger.html) may be useful.
Answer: Issue is coming because your convertedLong is of type int. Why?
Make it long and also variable i to be long.
This error is coming because you are calling the function by just 1000000000.
Append L to it, to pass it as "long" like
100000000000L

else it will take as int.
Answer: All number literals in java, unless otherwise specified, are typed as an int. So what you'll need to do is define your literal as a long by adding the L suffix to the literal.
1000000000000L
Also why are you casting your long to an int? that seesm to defeat the purpose?
Check out this question for more info
Answer: You are trying to call the method with the following parameters repeatedString("anyText",1000000000000) right? This would not even compile you have to extend a L at the end of your number to give the compiler the information that this is a long and not an int, so at first you call your function like this: repeatedString("anyText",1000000000000L) but if you think about it it's useless because you casting it to an int which then removes all the bytes which the int is not able to hold. So stop converting the long to an int and just use the given parameter as long.
Answer: The int type in Java can be used to represent any whole number from -2147483648 to 2147483647.
It seems you've reach the limitation of what the int type can hold. Consider using long. As the method you are using takes a long.
From:
int convertedLong = (int) n;

To:
long convertedLong = n;

Answer: Try this.
static long repeatString(String s, long n) {
    int length = s.length();
    long mod = n % length;
    long count = 0, rest = 0;
    for (int i = 0; i < length; ++i) {
        if (s.charAt(i) == 'a') {
            ++count;
            if (i < mod)
                ++rest;
        }
    }
    return count * (n / length) + rest;
}

public static void main(String[] args) {
    String s = "aabca";
    for (long i = 0; i < 10; ++i)
        System.out.println(i + " : " + repeatString(s, i));
    long x = 1000000000000L;
    System.out.println(x + " : " + repeatString(s, x));
}

output:
0 : 0
1 : 1
2 : 2
3 : 2
4 : 2
5 : 3
6 : 4
7 : 5
8 : 5
9 : 5
1000000000000 : 600000000000


interpretation of correlation matrix of regression coefficients in Cox regression?

Question: I am using SPSS to perform Cox regression. After finding all the significant covariates, there is a table called correlation matrix of regression coefficients.
My question is what kind of information can I interpret from this table? If I see high correlations between the regression coefficients of two covariates, for example it is 0.99 between the regression coefficients of PCPT and LTCPT in the table below.
Does it mean that I need to be more careful with the results? I have checked the similarity among all the variables. According to the similarity matrix, there is no high correlation between PCPT and LTCPT though.
Correlation Matrix of Regression Coefficients:
<code>              ACT    ATP      ALT   LTCPT   MALTCPT OIWSF_YEAR
 ATP         .109
 ALT        -.126   .044
 LTCPT       .055   .008    -.240
 MALTCPT     .031   .025     .052   .169
 OIWSF_YEAR  .058   .062    -.079   .166    .062
 PCPT        .044  -.072    -.252   .990    .053    .156
</code>
Answer: High correlations between coefficient estimates indicate a nearly singular fisher information matrix, which indicates near non-identifiability of your model. A common source of non-identifiability is when you have complete separation (e.g. everyone with a particular covariate combination does, or does not survive; this is most common with categorical predictors) or you have a covariate that is (nearly) a linear combination of the others. In this case, it looks like PCPT and LTCPT are probably highly correlated.
Answer: Regarding the correlation coefficients of the regression coefficients, they will be useful for simulation, but their original use stems from the original covariance matrix, where the square root of the diagonal elements forms the standard errors of regression coefficients used to calculate the t-test for each coefficient, i.e, $t_j=\beta_j/s.e.(\beta_j)$.


Recuperar informações de um sharedPreference Android

Question: Boa noite, tenho algumas informações salvas em SharedPreferences(email e senha) e preciso recuperar as mesmas em diversos locais para uso.
Criei um fragment para o usuário poder salvar a tela:
<?xml version="1.0" encoding="utf-8"?>

<EditTextPreference
    android:key="@string/pref_user_email"
    android:title="Email"
    android:inputType="textEmailAddress"/>

<EditTextPreference
    android:key="@string/pref_user_password"
    android:title="Senha"
    android:inputType="textPassword"/>

Isso está funcionando perfeitamente, porém como posso fazer para por exemplo recuperar a informação do email(pref_user_email)?
Grato.
Answer: Como você quer usar em vários lugares, pode criar um método estático que retorne a string que quer.
  Crie uma classe e crie esse método estático dentro dela.
 public class Preferencias_Usuario
{
    public static String getEmail(Context pContext)
    {
        SharedPreferences settings = pContext.getSharedPreferences(pContext.getString(R.string.pref_user_email), Context.MODE_PRIVATE);
        String result = settings.getString(pContext.getString(R.string.pref_user_email), "");
        if (result.length() > 0)
            return result;
        return "";
    }
}

Assim retorna o email, pode fazer pra retornar os outros dados também.
Pra usar: Preferencias_Usuario.getEmail(Main_Activity.this)
No Main_Activity.this pass a activity que está usando.
Answer: tenta isso ó:
// ...
private SharedPreferences prefs;
//...
private void emUmMetodoQualquer(){
    //...
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    ppf = prefs.getString("ppftexto", "texto");
    // ppftexto eh a referencia, texto eh um valor default
    showTooltip = prefs.getBoolean("showtooltips", false);
    // no caso pega um valor booleano
    if (prefs.getString("ppftexto", "texto").equals("TextoquequeroA")) {
        // faz algo aqui
    }
}

Espero que ajude