Understanding survival at time function

Question: This question is related to a few others (Here,Here) on the topic as I have been searching for information. Hopefully this one is sufficient.
1) I am seeing differences in the relationship between survival at time t, S(t) and the hazard at time t, h(t).
In Singer and Willet page 337 (10.5) they define the estimated survival $\hat{S}(t_{j})$ = $[1-\hat{h}(t_{j})][1-\hat{h}(t_{j-1})][1-\hat{h}(t_{j-2})]....[1-\hat{h}(t_{1})]$. They also define a life table as such:

In other sources Will Potts and others, they define $\hat{S}(t)$=$\prod_{t_{j}< t}(1-h(t_{j}))$ implying that the value of the hazard at time t is not included in the calculation for Survival at time t.
Which is correct? Is the difference in how the life table is set up?
2) How would you calculate the mean time time (restricted since there is censoring at the end of the collection period). Would you sum all $\hat{S}(t)$ (including the 1 at time zero) to arrive at 7.7? You always her it is the "area under the survival curve".
3) How would you calculate the residual mean lifetime for those that survived to the end of, say year 4? Is it summing all $\hat{S}(t)$ from 0.6209 through 0.41123 divided by 0.6209
Using the fact that the formula for the mean residual survival time mrl(u)  = E(T -u | T>u) is given by $\frac{1}{S(u)}\int_u^{\infty} S(t)\, dt$ and our "u" is 4 here (since we are saying T>4 in the conditional expectation)?
Comment: The numbers and presentation are slightly suspicious: nobody seems to have left in the first year at all, and in educational terms, many teachers leave exactly at the end of an academic year, so the number employed at the end of one year is usually not equal to the number employed at the beginning of the next.
Answer: I give some elements for 1 and 2 and I let the residual survival time  for you ;-)
You can get more details by googling "grouped survival data" or something like that...
(Take care of distinguishing between "grouped" and "clustered"!)
1
Let $h(t_j)$ be the probability that a teacher employed at the beginning of the year $t_{j - 1}$ left during the year:
$h(t_j) = \Pr[T < t_j \mid T \geq t_{j - 1}]; \hspace{0.75cm} j = 1, 2, \ldots$
As for the survival function at $t_j$, we have
$S(t_j) = \Pr(T \geq t_1) \Pr(T \geq t_2 \mid T \geq t_1) \ldots \Pr(T \geq  t_j \mid T \geq t_{j - 1})$
$\phantom{S(t_j) } = (1 - h(t_1)) (1 - h(t_2)) \ldots (1 - h(t_j))$
which is your first formula.
For example
$\hat{S}(t_3) = (1 - \hat{h}(t_1)) (1 - \hat{h}(t_2)) (1 - \hat{h}(t_3))$
$\phantom{S(t_3)} = (1 - 0.1157) (1 - 0.1102) (1 - 0.1158) = 0.6957$
Now, $S(.)$ is constant between two $t_j$'s and therefore
$S(t) = \prod_{t_j \leq t} (1 - h(t_j))$
which should be your second formula.
For example, $\hat{S}(t) = 0.6957$ for all $t \in [t_3, t_4)$.
2
$\hat{S}(t_6)=0.5189$ and $\hat{S}(t_7)=0.4877$. Therefore, the median survival time is $t_7$, i.e., the year at which $50 \%$ of the teachers have already left.
Comment: Thank you. I found the same thing for #1 - I believe that Will Potts paper had a typo and that the calculation of the survivorship function is as shown in Singer and Willett. For #2) I was asking about the mean, not the median. I later found explicit calculation of this in Hosmer and Lemeshow where they did exactly as I show - i.e. including the "1" of S(0). This is at odds with answers I received in the linked questions. Which leads me to believe that my #3 question above (MRL) is as I show here and not in the linked answer.....
Answer: I believe you are correct in questioning the Potts' citation (which I took the liberty of using as my template for editing the expression in your question). Looking at both Therneau and Gramsch "Modeling Survival Data" and Kalbfleisch and Prentice "Statistical Analysis of Failure Time Data", the definition of S(t) is Pr(T>t) and all of their interval survival estimates are closed on the right ... so it should be $\hat{S}(t)$=$\prod_{t_{j} \leq t}(1-\hat{h}(t_{j}))$. Any other interpretation would either leave vacant all of the interval between time_0 and the first event or would assign it a lower probability than unity. Either choice seems counter-factual.
Answer: Let us take your example of those who lasted at least four years, and then look at the residual mean lifetime.
$295$ of those left in the time interval $[4,5)$, which means that these lasted strictly less than five years, i.e. they did not last a full further year.
By including $0.6209$ in the sum in the numerator of your calculation, you are treating them as all lasting the full fifth year, when in fact they all left earlier in that year. Similarly with all the other years.  So your method is biased upwards.
If you wanted to adjust for this bias and you thought that teachers left on average a quarter of the way through the year, you could take your method and subtract $0.75$ from the final result, or you could leave out the initial term in the sum in the numerator of your calculation and add $0.25$ to the final result.  Both methods come to the same answer.
Comment: If you were working out the mean residual lifetime for the 2742 teachers still there at $t=4$, you might add up their remaining lifetimes and divide by 2742.  The survival function $S(t)$ is essentially the number of teachers remaining at time $t$, divided by the 3941 teachers at the start.  So using the survivor function, you need to adjust the results by dividing by a factor of $\frac{2742}{3941} \approx 0.6958$ which is $S(4)$ though shown at the end of the row that starts "3 [3,4)"
Comment: I think I am finally seeing the point here. But, what is the intuition for dividing by S(u) in the MRL? That one escapes me so far.

Understanding survival at time function


Restore xen image deleted with xen-delete-image

Question: I deleted a xen image using xen-delete-image and was wondering if there's a way in which I can restore this since 'xen-delete-image' only removes it from the list of xen images but doesn't delete the actual image files (disk.img and swap.img).
Is there a command to achieve this?
Answer: Probably the best thing to do is to copy the existing disk.img and swap.img out of the way, create a new instance using xen-create-image and move the original img files back over the new ones. You may need to set some config options like the block device names and mac address to to old values before it boots correctly.
Comment: I already tried that but when loading it gets stuck at some point with the message "Waiting for root file system"
Comment: Sounds like the block device name is wrong. Try changing hd to sd in the xen config file or vis versa.
Comment: Hey thanks david, tried this as well but still no luck
Answer: The folowing procedure has worked for me, provided that the image is not corrupted in any way.
Using the gui, I created a new server, named it differently from the original one, and created a new drive image with the same capacity as the deleted server.
I cancelled the installation at the first chance, leaving a virtual server without a bootable os.
After this I stopped the server, and overwrote the image I just created with the image of the deleted server (naming it identically to the new image).
All I had to reset where the network settings...


Error in starting the jboss server

Question: I installed Jboss server in windows xp . When I try to execute "run.bat" I got an error as
" To start JBoss Application Server please see C:\Program Files\jboss-as-7.1.1.Fin al\bin..\README.txt"
Before executing "run.bat" I set the environment variable
JBOSS_HOME =  C:\Program Files\jboss-as-7.1.1.Final;
After getting an error I saw that "readme.txt", it says that "This jar should be used
with standalone clients only, not with deployments are that deployed to an AS7 instance."
What is the problem? What should I do?
Answer: Don't use run.bat. Use either %JBOSS_HOME%\bin\standanlone.bat or %JBOSS_HOME%\bin\domain.bat. I would start with standalone as that's probably the one you want. Domain is for running multiple instances and wanting one management interface to interact with each server.

Error in starting the jboss server


What instrument is inexpensive and can be self-taught?

Question: I have never played any instrument. Now I want to learn some instrument. My deciding parameters are - it should be compact, inexpensive and can be learnt without a teacher.
I search over internet and found recorder and Harmonica as my options.
Please suggest if these can be the options.I recently developed this option as I need to impress a girl who likes music.
Comment: [This](http://www.youtube.com/watch?v=F5QCs3PnQBc) [is for you](http://www.youtube.com/watch?NR=1&v=Q0Frja3_q3E)
Comment: If you're starting any instrument from scratch, even with excellent teachers, you're going to need a few months to build up stamina and muscle memory enough to even play one slightly impressive song well. If this is your only strategy, I would guess your girl would have moved on by then. Probably best to look at other options for now, and learn an instrument because *you want to*. Or at least as a preparatory strategy for next time.
Comment: Although you may not want a teacher, you'll never reach your fullest potential without one.
Comment: Maybe not never, but it'll definitely take *longer!*
Comment: An harmonica is very compact, you can bring it everywhere you want but you have to choose the right one... Chromatic harmonicas are cool because you can play in any key, you do not need a specific harmonica for each song you play nor transpose a song in a different scale. However, they are a bit more expensive than diatonic harmonicas. What genre of music would like to play?
Comment: I hope that bad reason will result in good activity. IMHO for impressing girls guitars are best.
Comment: I am downvoting, because, frankly, the whole idea is silly and is not gonna work.
Answer: I suggest you get a ukulele.
It's fairly compact and rather easy to get started playing some chords on. With only three chords you can soon play millions of songs!
However you should probably be able to sing ok along with playing - beginners ukulele alone isn't too impressive after a minute or so...
Comment: Interestingly, almost all the rock and metal guitarists and bassists I know now take ukuleles on tour with them - just for plinking and jamming.
Comment: It's also appropriately hipster, and sure to impress ;-)
Comment: I like this suggestion. Anything from that Eddie Vedder album is sure to impress.
Answer: Your voice.
It is very inexpensive, very portable, and you already have a great deal of familiarity with it. Granted, there may be some work to be done to learn how to use it musically, but that is true for any instrument.  Also, as with any other instrument, a good teacher is highly recommended, especially in the beginning.
Comment: Your voice is a beautiful instrument and you can improve and change it any time you like.
Comment: It doesn't have to be singing either, I know quite a few people that cannot sing well but can rap or beatbox.
Comment: Don't forget [whistling](http://www.youtube.com/watch?v=zO-aCQ6xH-8), it's very underrated!
Answer: It depends on the girl, of course. It also depends on your taste in music.
If you and she both like blues, then blues harmonica would fit your criteria.
The instruments are compact and inexpensive. Note that harmonica players tend to end up buying several instruments, since you need a different one for each key.
You can learn "tricks" that sound impressive fairly quickly, from books, videos etc., and of course you can improve forever.
Answer: I suggest harmonica (if you prefer blues) or MIDI keyboard plugged to computer. MIDI keyboard with Reaper (a computer program)& VSTi plugins is powerful instrument maybe not for playing live, but for creating music.
Have you thought about any guitar? There are some minified versions, which have less frets, but are still playable. After learning just a few chords you can play almost all songs-remember girls love guitarists :)
Answer: Electric Keyboards are fairly inexpensive.
You can get some for around $300 which have light-up keys to show you what to play.
Lots of teach-your-self books out there too. However, a few lessons would be very helpful.
Otherwise, the recorder is a great instrument. If you have big hands start with an alto (also known as treble). It has a lovely tone, more mellow than a descant. Buy a plastic one - yamaha is a good brand - cost about $60.
Comment: I've found Aulos also has a good alto. It's about $30. Both brands are pretty good, though.
Answer: You could learn to play the Spoons. These come in a variety of sizes, each sounding at different pitches.
These are Piccolo Spoons (also known as Soprano Spoons):

Below is a demonstration of how to play the Tenor Spoons:

Spoons can also be made from a variety of different materials. These wooden Baritone Spoons have an earthy timbre.

If you are not able to impress a girl with your Spoon playing, you may be able to use them to impress her in alternative ways. The Soprano Spoons can be used to make a nice cup of tea; Tenor Spoons can be used to share a delicious trifle; wooden Baritone Spoons can help you to cook a romantic meal.
Comment: Failing that, I suppose you could always learn to play the Saw, which also comes in handy if you need to build furniture.
Comment: I don't care, I am always gonna call them "soprano spoons" from now on.
Comment: By the way those must be Tenor Spoons - where as serving spoons must be Baritone.
Answer: Try the recorder, that's what used to be taught at school :-)
Comment: Agreed - this is a very easy instrument to begin on. However it may not fulfil the 'impress a girl' requirement :-)
Comment: @MatthewRead I pity your lack of musical taste. Listen to [this piece](http://conquest.imslp.info/files/imglnks/usimg/9/9d/IMSLP103839-PMLP01586-S005-01-128k.mp3), or [this one](http://www.youtube.com/watch?v=WXkRgUvY6PM). Horrible screeching, my foot! There's a reason the recorder is called "sweet flute" in Spanish.
Comment: Unless she's into classical music. :P
Comment: Unless she's into horrible screeching.  Heh.  Even a well-played recorder sounds terrible IMO.
Comment: @Luke Alright, I won't call that screeching ... but yeah I don't like the sound of the recorders.
Answer: I would recommend xaphoon. Not much more expensive than a recorder, similar to play, but the saxophone-like sound is definitely more impressive and it is applicable to a wide range of music styles.
Comment: Especially for Woodwinds I would not suggest someone to begin learning without a teacher. It is very hard to get rid of a wrong embouchure. So imho at least the first few months should be supervised by a teacher.
Answer: I think a guitar is the best bet.
You can play and sing with it, which can not be done with blow instruments, and someone else can join in the singing.
Ukulele sounds OK too, but I never used one - except in a store the other day, and I kind of liked it. And it is small too.
Keep in mind that plain harmonicas or "harps" can not readily play all notes, unless bending notes, which  takes time to learn, plus they are somewhat fixed as to a key or scale they are tuned too. Harmonicas are great, though. I also play them, but they do amount to cost. I sometimes play harmonica together with guitar with a neck brace. So maybe don't limit to just one choice - except for starting - and for starting, I think the guitar is better, and I mean an accoustic one, which needs no gadgets and is more portable.
Harps may be cheaper than a guitar, but they do go bad, then you may have to buy another one, since repairing is not that easy.
I think it should be more to what you like more than hoping to please others, which is inherent if you like and dedicate yourself to it. But this is just my thought, and surely not a total truth.
Comment: Why has this answer been down voted? I see nothing wrong with it (except the grammar).
Comment: The guitar is easy instrument and not that expensive.
Answer: I recommend Harmonica since it is probably the easiest instrument to pick up and play right away. If you are looking for a easy to moderate challenge pick a ukulele. Do not see it as a smaller guitar though. It really is an instrument on its own.
Comment: +1!  You can get a harmonica and simple how-to-play book as a set, um, everywhere, it seems!  Just search "How to play harmonica" on a shopping site.
Answer: I'd skip on the "recorder" recommendations: it is a "girly" instrument.  For one thing, you'll only vaguely impress the "good" girls which are going to applaud politely and go elsewhere for the less civilized fun.  For another, particularly those are likely to run circles around you in that department anyway, so you'll have to put in a lot of work to become impressive.
Instead, get a tin whistle.  They are nominally cheaper ("nominally" because like with any "cheap" instrument, if you want to get into the "instrument is an ally rather than an opponent" category, you can invest a lot more than the "standard" price).
Then get a good tin whistle playing book and practice Irish tunes.  It's actually easier than a full recorder and cooler.  You are also moving into a genre where most girls don't have a full comparison readily at hand.
If you are going for harmonica instead, refrain from chromatic ones.  They are more "versatile" and you "can play in any key", but you don't want or need to for impressiobatics.  Just go for the straight "blues" or "diatonic" harmonica.  Multiple keys are only a consideration when playing along with others, and you'll need a lot longer to get impressive there.
In theory, a harmonica can serve as both melody and accompaniment, but you'll still be more likely to hear unaccompanied tin whistle (the harmonies of typical folk are rather simple and are more or less sketched by embellishments and the whole of the melody line).
Answer: First, what's the instrument you want to play? If you are interested in it, you'll be more willing to practice, and, therefore, more likely to become a proficient musician using whatever instrument that is. For the most part, I wouldn't worry so much about how easy the instrument is to learn if you're really wanting to learn it anyway. I'd argue that you can teach yourself pretty well any instrument given enough time and effort.
Also, "portable" and "cheap" are very relative terms, so I'll try to give you (and whomever else reads this) a variety of ideas to help you find what best fits your needs. Also, anyone that wants to add to this - be my guest.
The harmonica is a great choice (I have no clue how to play it). It's about as compact as an instrument can get, and it can go surprisingly well with many songs. No other equipment is needed to amplify the sound, either. I've seen fairly decent, brand-name harmonicas go for less than $20.
The acoustic guitar is one I'd personally recommend, but I don't know your taste or situation. It has a moderate learning curve. It's compact in the sense that it can be carried in a car or in a case. You may be thinking "guitars aren't cheap," but, starting out, you can get a guitar for less than $100 at times. You can easily find one for less than $200 (compare this to "cheap" wind/brass instruments). The main thing is making sure the neck is in good condition and has a consistent tuning down the neck. Good strings can make even a cheap acoustic guitar sound fairly good. Again, there's nothing needed to amplify the sound. Finally, there are a HUGE amount of online resources helping you to learn various songs for the guitar. Also, I've yet to find a single song that doesn't sound good with the sound and note range a guitar offers.
Singing is musical, and is the most "compact" music-making method named. However, I believe that the learning curve for non-natural-born-singers tends to be quite steep (someone please comment if I'm wrong - this is personal experience with other musicians). Amplifying the sound isn't always necessary, but when you add in accompanying music, you'll need something to play the music (e.g. other musicians/instruments, or a sound system). That harms the s "portability" advantage for singing.
The recorder is certainly cheap and rivals the harmonica in portability. There are some really great songs that can be played on the recorder too! However, the recorder tends to have more limited resources to encourage learning than some of the other instruments. Also, there may be fewer songs/genres you see "fit" the sound of the recorder well. I personally see the recorder as a good short-term instrument to learn a couple songs on rather quickly.
Also, there is the keyboard. It is probably only compact when compared to an actual piano or a full-sized harp, but it is still portable in the sense you can carry it in car/truck fairly easily. A keyboard can be purchased cheaply, but there tends to be a strong relation between realistic sound and price. I haven't found a keyboard that sounds great without any help for less than a few hundred dollars. There is the option of MIDI connectivity, which can make a horrible sounding keyboard sound pretty darn good, but then you need more cables, software, hardware (often a laptop), etc. - in other words, probably not what most people consider cheap or portable. However, all that equipment can fit comfortably in most small rooms. Also, many schools, churches, and other places have pianos or keyboards for you to play and learn on. There are, like the guitar, a seemingly endless amount of resources to help one to learn piano. Also, pretty well all songs sound great on a good keyboard (sometimes modification of the song is needed). Also, I'd say learning the chords of a couple songs is really easy on the piano. Timing the two hands and intricate melodies are usually what trip up players, but learning chords on a piano is pretty easy. The melodic parts can be added later.
TL;DR
In the end, it's still up to you. What do you want to play, and how much effort will go into it? How much money are you willing to invest or not invest? How much portability is really needed? You'll get it.
Answer: As others have mentioned, ukulele is a particularly easy and inexpensive "gateway drug" into the world of guitars.
I'll also add the melodica as another good option. All the breath control of a recorder, with all the fingering of the keyboard. Not sure how impressive they are to girls, though...


Commutative unital Banach algebra with nilpotent elements

Question: What would be a concrete example of a commutative unital Banach algebra that contains nilpotent elements?
Comment: Take your favorite Banach algebra, a non invertible element $x$ and factor out by the closure of the ideal generated by $x^2$. If this ideal is proper, you can easily get a Banach algebra with a nilpotent element.
Comment: Since you tagged OA, it is not hard to come up with a nilpotent operator $T\in B(H)$. Then $\mathbb{C}[T]\subseteq B(H)$ does the job. But of course, you can't find a commutative $C^*$-algebra with nontrivial nilpotents.
Answer: If you consider a closed (two-sided) ideal $I$ of the Banach algebra $A$, then you can endow $A/I$ with the quotient norm
$$
\|a+I\|=\inf_{x\in I}\|a+x\|
$$
and this norm makes $A/I$ into a Banach algebra (see proof on PlanetMath).
If you now consider $a\in A$ and the closure $I$ of the ideal generated by $a^n$, then $a+I$ will be nilpotent in $A/I$.
Another example. Let $A$ be a commutative Banach algebra and consider $B=A\oplus A$ endowed with the norm $\|(a,v)\|=\|a\|+\|v\|$. Then $B$ is a Banach space. Define an operation on $B$ by
$$(a,v)(b,w)=(ab,aw+bv)$$
It's easy to check that this is a good multiplication turning $B$ into an algebra. For the norm we have
\begin{align}
\|(a,v)(b,w)\|&=\|(ab,aw+bv)\|\\
&=\|ab\|+\|aw+bv\|\\
&\le\|ab\|+\|aw\|+\|bv\| &&\text{(triangle inequality)}\\
&\le\|a\|\,\|b\|+\|a\|\,\|w\|+\|b\|\,\|v\| &&\text{($A$ is a Banach algebra)}\\
&\le\|a\|\,\|b\|+\|a\|\,\|w\|+\|b\|\,\|v\|+\|v\|\,\|w\|\\
&=(\|a\|+\|v\|)(\|b\|+\|w\|)\\
&=\|(a,v)\|\,\|(b,w)\|
\end{align}
Thus $B$ is a Banach algebra and every element of the form $(0,v)$ is nilpotent, because $(0,v)^2=(0,0)$.
Comment: How does the set "closure $I$ of the ideal generated by $a^n$ exactly look like?
Answer: Upper triangular Toeplitz matrices give another example, i.e., the unital subalgebra of the $n$-by-$n$ matrices generated by the matrix with $1$s on the superdiagonal and $0$s elsewhere.
More generally, take any (nonzero) nilpotent element $a$ of a unital Banach algebra $B$, then take the unital Banach subalgebra of $B$ generated by $a$.


Best practice for adding data to a PostgreSQL database?

Question: I'm trying to add a static amount of data from a csv file into a postgresql database that im hosting on Heroku.
Initially, I was doing this programmatically in my application.py file, which was serving the web server with flask. I'm interacting with the database using SQLalchemy
Basically, I have this block of code where I'm committing data to my database before I'm handling routes.
for el in books:
   db.execute("INSERT INTO books (isbn, title) VALUES (:isbn, :title)",
             {"isbn": el[0], "title": el[1]})
   db.commit

I think that the biggest problem with doing this is the web server is that I'm commiting the same data each time I restart my web server. Does anyone have advice for the best way that I should be doing this process?
Comment: Does the data in the CSV ever change?
Comment: @AdrianKlaver the data in the CSV never changes. It's just 5000 entries in a format that I know how to parse already.
Comment: @AdrianKlaver Tov suggested something below, but it still doesn't really get around the fact that I'd be checking EACH time i restart the web server to see changes. There has to be a better way where we could just do this once? I'm not sure though.
Answer: You write: "I'm commiting the same data each time I restart my web server".
A database stores the data persistently, meaning the data stays in your database (an exception is an in-memory-db, but even this kind of dbms allows for storing the data on disk).
In result, after you have run your code n times, the data should be in there n times (assuming that you are not also dropping an creating the table each time).
You can easily check that, e.g. by counting the isbn occurrences:
select count(isbn) as c, isbn from books group by isbn order by c desc;

Assuming in the csv each isbn is unique, all the count values should be 1, but in your case it is rather n.
So clean your table and do the import once. Insert only new data, update only existing, changed data.
Comment: So, I just need to do a simple check for that books ID before I try to insert it into the database again? I think you're right about the data being in there n times that's what I meant.
Comment: Yes, if you want to check if a book is already in the table you could check for the ISBN before you insert it.
Answer: I realized that because the data doesn't change I could just use sql's COPY command.
After starting the command line with psql DATABASE_URL I was able to TRUNCATE the table to delete everything in it and then I just did:
\copy books(column_name_1, column_name_2,...) from 'path/to/csv' delimiter ',' csv header;
the delimiter is how your field values are separated in the csv header and the csv header option tells sql what the breakdown of the csv file is. In my case the csv header was the first line, which sql ignores with the csv header option, it looked like this:
isbn,title,author,year
Thanks to everyone that responded.
Answer: If the data in the CSV never changes then \copy it into the database once outside the application and then drop the code that does that on start up. If you anticipate that there might be changes in the future then have code that you can trigger from either inside the application(in admin section if that exists) or outside. What that code does would be dependent on what the changes would be. If the changes are just adding or deleting complete entries then you could get by with something like(pseudo code):
CREATE TEMP table data_staging(fields to match CSV);
\copy data_staging FROM  csv_file
--INSERT new items
INSERT INTO books() SELECT * from data_staging AS ds  LEFT JOIN books ON ds.isbn = books.isbn WHERE books.isbn IS NULL;
--If you want to DELETE
INSERT INTO books() SELECT * FROM books LEFT JOIN  data_staging AS ds    ON books.isbn = ds.isbn WHERE ds.isbn IS NULL;

UPDATEing rows would require more work as you would need to walk over the records and see if there are any changes between those in the staging table and the books table.


Diagnostic plot for assessing homogeneity of variance-covariance matrices

Question: Is there a handy plot for comparing the variance-covariance matrices of two (or perhaps more) groups?  An alternative to looking at lots of marginal plots, especially in the multivariate Normal case?
Comment: [Corrgrams](http://www.datavis.ca/papers/corrgram.pdf)? [Ellipses](http://dx.doi.org/10.1214/12-sts402)?
Comment: Came across this old question of yours. For two covariance matrices $S_1$ and $S_2$, I am wondering if one can compute $S_1^{-1} S_2$ that should be close to $I$ if $S_1 \approx S_2$, so one can plot the eigen-spectrum of this product and visually check how close it is to the horizontal line. Perhaps one can compute and plot, for comparison, the expected eigen-spectrum under the null: it will not be a flat line due to the finite sample size. I don't know how to compute it analytically given $n_1$, $n_2$, and $p$ (starting with Marchenko-Pastur?), but it should be easy to estimate numerically.
Comment: Well, at least we are getting somewhere! Here are two questions ([Q1](http://stats.stackexchange.com/q/16557/1036) & [Q2](http://stats.stackexchange.com/q/14986/1036)) that mention a Box M test that may be of interest. You may be able to decompose that test to provide the plot you want, not sure though (this is getting beyond anyway I can help though!)
Comment: Something smart like assessing multivariate Normality by putting squared Mahalanobis distances on a quantile-quantile plot against the chi-squared distribution.
Comment: @amoeba: Thanks; that sounds like an interesting approach. For more than two matrices, perhaps a 2x2 grid of eigen-spectra. I've also got two papers on the subject mouldering in my desk pile; & I need to think about decomposing the Box M-test.
Comment: Thanks for the links. Ellipses is a really nice paper.  But I'd still effectively be looking at lots of marginal distributions - I was wondering about something tailored to comparing two groups to see if they have the same variance-covariance structure.
Comment: It may help to be more specific about what you want. My suggestion was aimed at your ok with assuming multivariate normality, you just want a diagnostic to see if the variances and covariances are similar between groups (for which I fail to see how superimposing ellipses doesn't successfully do that). Your second comment seems more like your interested in some type of data reduction and you want to visualize the original sample observations and see if it deviates from multivariate normality.
Comment: Sorry - the second comment was just an attempt at analogy - I was thinking there's perhaps something similar based on the Wishart distribution to compare variance-covariance matrices.
Answer: An article Visualizing Tests for Equality of Covariance Matrices, by Michael Friendly and Matthew Sigal, has just appeared in print in The American Statistician (Volume 74, 2020 - Issue 2, pp 144-155).  It suggests several graphical procedures to compare covariance matrices.
The authors' R package heplot supports these procedures.  The illustrations in this post are modifications of those in the article based on the supplemental code maintained at https://github.com/mattsigal/eqcov_supp/blob/master/iris-ex.R.  (I have removed some distracting graphical elements.)
Let's go there step by step, using the well-known Iris dataset, which will require us to compare three covariance matrices of $d=4$ variables.
Here is a scatterplot of two of its four variables with symbol size and color distinguishing the three species of Iris.

As usual, the first two bivariate moments of any group can be depicted using a covariance ellipse.  It is a contour of the Mahalanobis distance centered at the point of means.  The software shows two such contours, presumably estimating 68% and 95% tolerance ellipses (for bivariate Normal distributions).  (The contour levels are found, as usual, by referring to quantiles of a suitable chi-squared distribution.)

Provided the data don't have outliers and strong nonlinearities, these provide a nice visual summary, as we can see simply by erasing the data:

The first innovation is to plot a pooled covariance ellipse.  This is obtained by first recovering the sums of squares and products matrices upon  multiplication of each covariance matrix by the degrees of freedom in its estimation.  Those SSP matrices are then summed (componentwise, of course) and the result is divided by the total degrees of freedom.  We may distinguish the pooled covariance ellipse by shading it:

The second innovation translates all ellipses to a common center:

For example, the Virginica covariance is similar to the Versicolor covariance but tends to be larger.  The Setosa covariance is smaller and oriented differently, clearly distinguishing the Setosa sepal width-length relationship from that of the other two species.
(Note that because the contour level (such as 68% or 95%) merely rescales all ellipses equally, the choice of which level to use for this plot is no longer material.)
The final innovation emulates the scatterplot matrix: with $d \gt 2$ variables, create a $d\times d$ array doubly indexed by those variables and, in the cell for variables "X" and "Y," draw all the covariance ellipses for those two variables, including the pooled ellipse. Distinguish the covariances graphically using the line style for the contours and/or a fill style for the polygons they bound.  Choose a relatively prominent style for the pooled ellipse: here, it is the only one that is filled and it has the darkest boundary.

A pattern emerges in which the Setosa covariance matrix departs from those for the other two species and that of Virginica (still shown in red) tends to exhibit larger values overall.
Although this "bivariate slicing" approach doesn't allow us to see everything that's going on in these covariance matrices, the visualization is a pretty good start at making a reasoned comparison of covariance matrices.  Further simplification of the graphical representation is possible (using design principles inspired by, say, Tufte or Bertin) and, I think, likely to make this approach even more effective.

When $d$ grows large (in my experience, greater than $8$ becomes unwieldy unless you're willing to produce output on a high-resolution large-format printer, but even then $40$ is around an upper limit), some kind of variance reduction technique is called for.  Friendly and Sigal explore PCA solutions.  Of interest are the applications that focus on the principal components with smallest eigenvalues.
Comment: Why is it considered important for the pooled elipse to be more prominent?  To me that seems to make it harder to see the distinctions amongst the rest, especially in the smaller panels w/ a plot matrix. (However, I haven't seen it the other way, it may well be worse for different reasons.) Regarding the issue of too many variables to see in a plot matrix, one possibility is to break out sections of the matrix. I did that in my answer to [How to extract information from a scatterplot matrix when you have large N, discrete data, & many variables?](https://stats.stackexchange.com/a/144741/7290)
Comment: @Gung The pooled ellipse is a reference.  It deserves the same kind of visual prominence as any reference, such as the box of a boxplot.  Although displaying blocks of a large matrix is what one often must resort to, it is less than satisfactory because it ruins the gestalt of seeing the entire thing.


How to export private images from Drupal

Question: I want to export private images from Drupal to an external client. How to I authenticate an external client to access private files from Drupal DB?
Comment: Could you expand on the 'secure' requirement? With your files being stored at publicly accessible URLs I'm not sure what concerns you'd have there
Comment: Ok, tried to change it. If you have any suggestions how to change body to a more Drupal question I would appreciate the help.
Answer: You can use file_create_url($uri) to create an externally accessible url for the file.
If used with private file mode files, you will need to implement hook_file_download
You might also be interested in the Services module, to expose an API for the files, which can provide authentication methods such as Drupal session and OAuth authentication.


Docker-ce oppening Firewalld ports on rocky 8

Question: Docker-cd, when run with -p 3010:3010 bypass the firewall and open the container port to the world...
If i disable docker and run a python -m http.server, the port is blocked to the outside (as it should, the default rule is drop) but after the docker run, docker opens it.
This prevents me from running a database or a redis with docker, without these services beeing expoded to the world.
I tried: --iptables=false, but got: unknown flag: --iptables
(as sugestes in a similar question: firewalld not blocking docker container ports)
Anyone knows how to prevent docker from oppening holes in my firewall?
Answer: If you don't want to expose a containerized service to the world, just bind it to the loopback address:
docker run -p 127.0.0.1:3010:3010 ...

Now -- regardless of your firewall settings -- this service will only be accessible locally.
Comment: i didnt even know that syntax was valid! Thx!


Constructing a measure on $(S, \mathcal{S})$ with a initial distribution and a transitional probability

Question:
Let $(S, \mathcal{S})$ be a measure space and $\mu$ is an initial distribution on $(S, \mathcal{S})$.
   Also, $p: S \times \mathcal{S} \to \mathbb{R}$ is a transitional probability satisfying
(i) For each $x \in S, A \to p(x, A)$ is a probability measure on $(S, \mathcal{S})$.
(ii) For each $A \in \mathcal{S}, x\to p(x,A)$ is a measurable function.

If we define
$$\lambda(B_1 \times \cdots \times B_n) = \int_{B_1} \mu(dx_1)\int_{B_2} p(x_1, dx_2) \cdots \int_{B_n} p(x_{n-1}, dx_n)$$ where $B_i \in \mathcal{S}$, then is there a measure $\nu$ on $(S^n, \bigotimes_{i=1}^n\mathcal{S})$ such that $$\nu(B_1 \times \cdots \times B_n) = \lambda(B_1 \times \cdots \times B_n)$$? Can we show this by $\pi-\lambda$ system? Any help would be appreciated!
Comment: The way you wrote it, $\nu$ should be rather defined on $\bigotimes_{n=1}^\infty \mathcal S$.
Comment: $\mathcal S^{\otimes n}$ is generated by products like $B_1\times ...\times B_n$, where $B_i \in \mathcal S$, so the answer is yes.
Comment: Thanks for your comment! Here, $\bigotimes_{i=1}^n \mathcal{S}$ is enough for me.
Comment: Yes, I also know that it is a measure since the book states it is. The thing is I cannot show. Could you show me how to show this is a measure?
Answer: The set $\mathcal J_n = \{ B_1\times \ldots \times B_n: \forall i\ B_i \in \mathcal S\} $ forms a semi ring.

$\emptyset \in \mathcal J_n$
if  $B, C\in \mathcal J_n$, then $B\cap C\in \mathcal J_n$, since
$$ B\cap C = (B_1\times \ldots \times B_n)\cap  (C_1\times \ldots \times C_n) = (B_1\cap C_1)\times \ldots \times (B_n\cap C_n) $$
and $B_i\cap C_i\in \mathcal S$ for all $i$.
For any $B,C \in \mathcal J$, $B\setminus C = \bigcup_{i=1}^{2^n-1} A_i$ with disjoint sets $A_i\in \mathcal S$, since
$$ B\setminus C = \bigcup_{\mathbf a\in\{0,1\}^n\\ \sum_{i}a_i\geq 1}  D_1^{a_1}\times\ldots \times D_n^{a_n}  $$
where $$D_j^{a_j} = \begin{cases} B_j \cap C_j & \mbox{ if } a_j = 0 \\
B_j\setminus C_j & \mbox{ if } a_j  =1.
\end{cases} $$
Choose $A_{a} = D_1^{a_1} \times \ldots \times D_n^{a_n}.$

According to Carathéodory's extension theorem, $\lambda : \mathcal J_n\to [0,1]$, being a $\sigma$-additive premeasure, can be uniquely extended to the $\sigma$-algebra generated by $\mathcal J_n$. The generated $\sigma$-algebra coincides with $\mathcal S^{\otimes n}$ by definition.
The $\sigma$-additivity of $\lambda$. Let $n=2$. Then
$$ \lambda(B^1\times B^2) = \int_{B^1}\int_{B^2} p(x_1,dx_2) \mu(dx_1)  $$
Let $ (C_n)_n = (B^1_n\times B_n^2)_n  $ be a collection of pairwise disjoint sets, s.t. $\bigcup_n C_n \in  \mathcal J_2$. We have to show that
$$ \lambda(\bigcup_n C_n)= \sum_{n}\lambda(C_n). $$
The key here is that $\bigcup_n C_n \in\mathcal J_2 $ is a strong restriction on $(C_n)$, i.e. it has to be such that $\bigcup_n C_n =  D^1 \times D^2$. Note that usually for general sets $(A^1 \times A^2) \cup (B^1\times B^2) \neq D^1 \times D^2$ for some $D^1,D^2$ does not hold, even if the two product sets are disjoint. If $C_n = A_n \times B_n$ is a family of disjoint sets and $\exists D^1, D^2 \in \mathcal S$ s.t.
$$  \bigcup_n (B^1_n \times B^1_n) = D^1\times D^2 $$
then
$$ (x,y)\in \bigcup_n C_n \Leftrightarrow \ \exists n\in \mathbb N: \ \ x\in B^1_n \wedge y\in B^2_n \Leftrightarrow x\in D^1 \wedge y \in D^2 $$
which means that $D^1 = \bigcup_n B^1_n $ and $D^2=\bigcup_n B_n $.
Now assume that $C_n = B^1_n \times B_2$ or $C_n = B^1 \times B_n^2$. Let us consider the first case
$$ \lambda(\bigcup_n C_n ) = \lambda(\bigcup (B^1_n \times B^2)) = \lambda((\bigcup_n B_n^1) \times B^2) = \int_{ \bigcup_n B_n^1} \int_{B_2} p(x_1,dx_2) \mu(dx_1) = \int_{\bigcup_n B_n^1} \bigg( \int_{B^2} p(x_1,dx_2) \bigg) \mu(dx_1) = \sum_n \int_{B_1^n} \int_{B^2} p(x_1,dx_2) \mu(dx_1) = \sum_n \lambda(B_n^1\times B^2) = \sum_n \lambda(C_n) $$
where the second last equality is due to the fact that $\mu$ is a measure.
Now let consider the other case, i.e. $C_n = B_1\times B_2^n$. Then
$$ \lambda(\bigcup_n C_n )= \lambda(\bigcup_n(B_1\times B_n^2)) = \lambda(B_1\times \bigcup_n B_n^2) = \int_{B_1} \int_{\bigcup_n B_n^2} p(x_1,dx_2) \mu(dx_1) = \quad \int_{B_1} \sum_{n} \int_{B_n^2} p(x_1,dx_2) \mu(dx_1) = \int_{B^1} \sum_{n} p(x_1,B_n^2) \mu(dx_1).  $$
According to Beppo-Levi's theorem (monotone convergence) we have that
$$ \int_{B^1} \sum_n p(x_1,B_n^2) \mu(dx_1) = \sum_n \int_{B^1} p(x_1,B_n^2) \mu(dx_1) = \sum_n \lambda(B^1\times B_n^2) = \sum_n \lambda(C_n) $$
Now consider the case $C_n = B^1_n \times B^2_n$. Then $\bigcup_n C_n \in \mathcal J_2$ implies that $\bigcup_n C_n = \bigcup_n B_n^1 \times \bigcup_n B_n^2$. The set $(B_n^j)_n$ ($j=1,2$) need not to be disjoint, but since the $C_n$'s are disjoint so for fixed $n\neq m$ $B_n^1\cap B_m^2= \emptyset $ or $B_n^2\times B_m^2 = \emptyset$.  We also have
$$ \forall m,n:\ m\neq n \quad B_n^j\cap B_m^j = \begin{cases} \emptyset \\ B_n^j. \end{cases}  $$
The $\emptyset$ part is clear. Suppose $B_n^j \cap B_m^j \neq \emptyset$ for some $n\neq m$. Then $B_n^{3-j}\cap B_m^{3-j} = \emptyset$ has to hold, and $\exists (x,y)\in B_n^j\setminus B_m^j \times B_m^{3-j} \subset \bigcup_n B_n^1 \times \bigcup_n B_n^2  $, but $(x,y) \notin B_m^j \times B_m^{3-j}$, futhermore $(x,y)\notin B_k^1\times B_k^2 $ for any $k\neq m$. This would mean that
$$ \bigcup_n B_n^1 \times B_n^2 \subsetneq \bigcup_n B_n^1 \times \bigcup_n B_n^2$$
which is a contradiction. This all means that
$$ \bigcup_n B_n^1 \times \bigcup_n B_n^2 = \bigcup_n A_n^1 \times \bigcup_n A_n^2 = \bigcup_n \bigcup_m A_n^1\times A_m^2$$
where the sets $(A_n^j)_n \subset \mathcal S$ ($j=1,2$) are all disjoint. Now
$$ \lambda(\bigcup_n C_n) = \lambda(\bigcup_n A_n^1 \times \bigcup_m A_m^2) = \lambda(\bigcup_n (A_n^1 \times \bigcup_m A_m^2)) = \sum_n \lambda(A_n^1 \times \bigcup_m A_m^2) = \sum_n \sum_m \lambda(A_n\times A_m)  $$
due to what we have proven before.
Comment: Thank you for your answer! Actually, I am struggling with the part that $\lambda$ is a $\sigma$-additive premeasure. Can you show me how to do it? You can just show me when $n =2$. I will try to do it when $n > 2$. Thanks again!
Comment: Updated my answer as you requested.
Comment: Thank you very much for your answer, but I don't understand why all $C_n$'s has to be either  $B_n^1 \times B_2$ or $B_1 \times B_n^2 \cdots (*)$. For example, take  $C_1 = A \times B$, $C_2 = A_2 \times B_1$ and $C_3 = A_2 \times B_2$, where $ C_i \in \mathcal{J}_2$, $A \cap A_2 = \emptyset$ and $B_1 \cup B_2 = B$. They  don't satisfy $(*)$, but their union $\bigcup C_i  = (A\cup A_1) \times B \in \mathcal{J}_2$.
Comment: I updated my answer. Hopefully it is more clear now.


PHP wiki markup parser

Question: I've been told that writing a wiki markup parser in PHP that relies on regex and preg functions is a bad idea. But I don't know why.
So what's the best way to go about writing a wiki markup parser in PHP? This is more an academic 'project' than anything else, so the whole point is to write it myself.
Thanks in advance for your help.
Comment: Not knowing the reasoning for the cited advise it's difficult to assess its merits. Pretty much all contemporary wiki parsers are based on regular expressions however. Having implemented both a regex formatter and a state machine parser, I can only tell you that the regex approach is simpler, usually speedier and likely easier to maintain.
Comment: Using regex is a bad idea for the same reason you can't parse HTML like this: every component/template has a different inner syntax, and you can nest and combine then. Like HTML, the 'best' way is to 'stream parse' it, byte-by-byte, opening and closing components/templates along the stream. Very hard to do right.
Answer: You've been told that because "wiki languages" are ill defined to say the least.
The really bad part is "trying to parse" them, not "using php and regexps".
In fact I believe they are actually processed with regexps (straight into html, without passing from an intermediate abstract syntax tree representation) in softwares like mediawiki. And AFAIK actual parsing without regexps is quite inefficient in PHP. (unless you're using a specific compiled PHP module for parsing)
Be aware that those softwares also have a number of syntax features that can be activated on demand, and that might prove hard to write efficiently.
Only real trouble? You have to use a lot of escapes to parse chars like [ and ], it's easy to get confused when you use many backslashes with preg_match() and php. Apart from that, a simple preg_match_all('#\\[\\[(.*?)\\]\\]#',$data,$matches,PREG_SET_ORDER); should get you up and running.
(unless I got confused by too many levels of backslashing, that is) :)
Comment: Don't forget about nestable `{{` templates, and nestable `{|` templates.
Answer: Probably the issue is that you have to run your regular expressions one at a time each across the entire contents of the wiki page, and that takes a lot of processing time.  A simple solution is to use some sort  of delimiter for tags, such as [[, and you process the text sequentially from beginning to end.  Each time you find a tag, you search for the end tag ]].
Next, you process the contents in between with whatever rules you have defined.  This can be accomplished using simple string indexing and replace operations, and doesn't require processing the entire string many times, but instead by passing through the entire string just once.
Comment: Finding the end tag is tricky, because you can nest `[[` templates in `{{` templates in `{|` templates. And those inside themselves. Etc.

PHP wiki markup parser


How to set background color of Android ListView entries/items?

Question: I have a ListView with entries that have a lighter background color than the application's layout, and I don't know why.This is a snapshot with red arrows indicating the difference in color: Main_Activity
I have no idea where to start on this.
This is the manifest.xml file that takes up the theme, AppTheme:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gtfp.workingmemory"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".appController"
            android:launchMode="singleTop"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
                android:name=".editToDoItem"
                android:theme="@android:style/Theme.Holo.Dialog" >
        </activity>
        <receiver android:name=".ToDoAlarm">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <activity
                android:name=".AlarmActivity"
                android:theme="@android:style/Theme.Holo" >
        </activity>
        <activity
                android:name=".SettingsActivity"
                android:theme="@android:style/Theme.Holo" >
        </activity>
    </application>

</manifest>

That theme in fact is Theme.Holo in the resources file:
<resources>

    <corners android:radius="5dp" />

    <padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />

    <stroke android:width="3dp" android:color="#E6E6E6"/>
</shape>`enter code here`

I just happened upon this while investigating another matter (I hate porgramming). Appreciate your efforts regardless.


Correct way to calculate time to an event variable

Question: Is this the correct way to calculate time to an event(death) for survival analysis?
t2death column calculated using SQL as:
case when death_dt is not null
then death_dt - admission_dt else study_end_dt - admission_dt end as t2death

The final data looks like:
id  time0       study_end_dt    admission_dt    death_dt        t2death
1   2021-05-24  2022-08-31      2021-05-24      NA              464
2   2019-12-10  2022-08-31      2020-01-19      2020-01-23      4
3   2020-10-14  2022-08-31      2020-11-22      2020-12-03      11
4   2021-11-23  2022-08-31      2021-11-26      NA              278

My concern is that there is t2death value for id: 1, 4, but they are still alive.

How does a survival analysis algorithm know that they have been
censored?
Any reading resources or explanation would be greatly appreciated.
Comment: Could you please explicitly show us your calculation?  All the date differences do look correct.
Comment: Wouldn't the answer depend on what your software expects?  There are different conventions for indicating which data have been censored.  I suspect you can find the answer by consulting your software's documentation.  Running any examples that come with it can be helpful.
Comment: Thanks for suggestion, whuber. I have updated my post.
Comment: Do you have specific survival software in mind? The R [`survival` package](https://cran.r-project.org/package=survival) is a good choice. It comes with many helpful vignettes to explain its use in different circumstances, and is the basis for a few thousand questions with answers on this site.
Answer: For question 1: Software expects an indicator variable to distinguish time values that represent events from those that represent censoring. The coding depends on the software. In R for this type of data, 0 is typically used for censored and 1 for an event. In contrast, at one time at least, Matlab used opposite coding; that led to some interesting conversations with a colleague until we figured out that difference. That coding can be extended to allow for multiple types of state transitions.
For question 2: The vignettes of the R survival package can be very helpful. The main vignette, "The survival package," is a good overview. Other vignettes go into detail about specific aspects of survival analysis. This Cross Validated site has some
Book suggestions for survival analysis and about 2000 pages to date on the topic.


Measure Theory Uncountable example with real line in $\sigma$ algebra

Question: I have an example of an unmeasurable set in the measure space defined as follows:
If $\Omega$ is the real line, we can consider a $\sigma$-algebra consisting of all the closed intervals of the real line and a measure that is just the length of the interval. This $\sigma$-algebra does not contain all the subsets of the real line and thus some sets are not measurable in this measure space.
I am confused as to, what are the subsets that are not contained in this measure space? I am guessing the subset of open intervals is missing, but can't all open intervals be expressed as closed intervals?
Comment: Why do you think the set of all closed intervals of the real line is a $\sigma$-algebra? What is your definition of a $\sigma$-algebra?
Comment: What makes you think all open intervals can be expressed as closed intervals? How would you express the open interval $(0,1)$ as a closed interval?
Comment: @bof I think I am bit confused there. The difference between open and closed interval is that the open interval does not contain boundary points. Doesnt that mean we have a new boundary that we can define the open interval with making it a closed interval?
Comment: It looks like you need experience with "open" and "closed" before you advance to $\sigma$-algebras.
Comment: The set of closed intervals is not a $\sigma$-algebra. Check the def'n.
Answer: Not everything is a closed interval or a union of closed intervals. For example, $(0,1)$, $\mathbb{Q}$, $\mathbb{R\backslash Q}$, and the Cantor Set. Later on these can assign a measure to these sets, but in the way you defined measure they are non-measurable.


Magento 1.9 Session Files clearing

Question: Hi I currently have a magento 1.9 site which i use session storage as files as i find that using the database is very slow.
I currently have about 16 gig of session files which i want to delete.
If I run:
find . -name 'sess*' -mtime +7 -exec rm -f {} \;
The site grinds to a halt and then kills the database attached.
I then looked at garbage collection I changed:
session.gc_probability = 1
session.gc_divisor = 100
When I did this and restarted apache the site crashed too?
What would be the best way to remove these files?
Comment: just remove them at a time when the site does not have many visitors with rm -rf var/session. This will logout everyone from the website though, customers and admins.
Answer: You can delete the whole folder, from your Magento Root with the following
rm -rf var/session/*

Also, if you have enought RAM, you should consider using Redis to store session. Here is a nice tuto for Magento 1.
Answer: first go to the var/session folder of the magento root directory
find . -name "*" -print | xargs rm -rf

This command will delete all the data in the current folder without prompting you.

Magento 1.9 Session Files clearing


Specification pattern - creating compound specifications using lambdas (C#)

Question: If I have a specification defined as an Expression as below:
public Expression<Func<Foo, bool>> IsSuperhuman =
  x => x.CanFly && x.HasXRayVision;

And I want to define another specification 'IsSuperheroine' with the logic 'is superhuman and is female', how can I reuse the existing specification within the new one?
Comment: Because you can't use simple delegates in the Where clause of IQueryables, as I discovered yesterday.
Comment: Why are you using Expressions for this? It would seem a delegate would suffice.
Answer: Have you checked out predicate builder in LinqKit? It builds up expressions by letting you and and or expressions together.
Comment: I believe that NCommon has something similar but I'm down with rolling my own at the moment.
Comment: I'm an absolute spanner. If I'd read your link properly, it could have saved me loads of work. You are a god!
Answer: Here's a way to do it :
Expression<Func<Foo, bool>> IsSuperhuman = x => x.CanFly && x.HasXRayVision;

Expression<Func<Foo, bool>> IsSuperheroine = AndAlso(IsSuperhuman, x => x.IsFemale);

...

public static Expression<Func<T, TResult>> AndAlso<T, TResult>(Expression<Func<T, TResult>> expr1, Expression<Func<T, TResult>> expr2)
{
    var arg = Expression.Parameter(typeof(T), expr1.Parameters[0].Name);
    var andExpr = Expression.AndAlso(
        ReplaceParameter(expr1.Body, expr1.Parameters[0], arg),
        ReplaceParameter(expr2.Body, expr2.Parameters[0], arg));
    return Expression.Lambda<Func<T, TResult>>(andExpr, arg);
}

public static Expression ReplaceParameter(Expression expr, ParameterExpression oldParam, ParameterExpression newParam)
{
    return new ReplaceParameterVisitor(oldParam, newParam).Visit(expr);
}

internal class ReplaceParameterVisitor : ExpressionVisitor
{
    private ParameterExpression _oldParam;
    private ParameterExpression _newParam;

    public ReplaceParameterVisitor(ParameterExpression oldParam, ParameterExpression newParam)
    {
        _oldParam = oldParam;
        _newParam = newParam;
    }

    protected override Expression VisitParameter(ParameterExpression node)
    {
        if (node == _oldParam)
            return _newParam;
        return node;
    }
}

It is probably not the simplest way to do it, but it works...
Comment: Thanks! I'm going to take your word for it until such a time as I've been through the Expressions API and worked out what it all means.


Element type "settings" must be followed by either attribute specifications, ">" or "/>"

Question: <code><settings xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0
                              http://maven.apache.org/xsd/settings-1.1.0.xsd"
          xmlns="http://maven.apache.org/SETTINGS/1.1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance ">
</code>
Comment: Welcome to StackOverflow. As a general rule, take your time to write your question so that we readers can see clearly: What do you want, what have you tried, what happened then.
Comment:
Comment: this is the actual text that is throwing error at the begging of the xml document . can somebody suggest what is the problem ?
Answer: All XML Elements Must Have a Closing Tag
So the error is quite clear. You either need to write
<code>...stance "></settings>
</code>
or
<code>...stance " />
</code>
at the end of your XML.
Also have a look at: http://www.w3schools.com/xml/xml_syntax.asp


Once instead of foreach in rss feed?

Question: This outputs all the images of the feed, but i just want to display the first one, what do i have to put in the tag instead of foreach?
        <?php foreach ($feed->get_items() as $item): ?>

        <?php $media_group = $item->get_item_tags('', 'enclosure');
        $file = $media_group[0]['attribs']['']['url'];
         ?>

       <?php echo '

    '; ?>

       <?php endforeach; ?>

Answer: <?php $items = $feed->get_items(); $item = $items [0]; ?>
<?php $media_group = $item->get_item_tags('', 'enclosure');
      $file = $media_group[0]['attribs']['']['url'];
?>
<?php echo ''; ?>

Comment: `$item = reset($items)` might work better with different array keys.

Once instead of foreach in rss feed?


Integral Of $\int \frac{y}{e^{3y^2}}dy$

Question: I want to integrate the following :
$$\int \frac{y}{e^{3y^2}}dy$$
what I did so far is:
set $t=e^{3y^2}$ and $dt=6y\cdot e^{3y^2}dy$ from here I get get the expression:
$\frac{dt}{t}=6ydy$, there is another way to do it? any suggestions? thanks.
Comment: Clean your substitution glasses: the given integral is $-\dfrac{1}{6}\int -6y\cdot e^{-3y^2}\,dy$.
Answer: $$ I = \int ye^{-3y^2} \ dy $$
put $ -3y^2 = u \Rightarrow du = -6y dy $
$$ \Rightarrow I = -\frac{1}{6}\int e^u \ du = \frac{-e^u}{6} + c $$

Integral Of $\int \frac{y}{e^{3y^2}}dy$


Hidden rows in SSRS report while rendering in Excel format

Question: I am encountering an very unusual behavior while rendering a SSRS report in EXCEL format. I have a simple SSRS report with one parameter (Country).It has only one tablix (table) with no report header and footer. This report will be generated by executing a SSIS package. The SSIS package will pass the country parameter (one parameter at a time) and invoke the data driven subscription associated with the report. Three reports will be generated in Excel format in the specific location provided for each parameter passed. Say, one report for parameter India, one for Pakistan and final one for Srilanka. After the report generation, Sometimes I find that the last row is hidden in any one or all of three reports generated. So, I converted the specification of table height & width, row height and column width from inches to pt as per the workaround suggested by Microsoft. But, it is behaving in unusual pattern after this modification too. Sometimes the report has no hidden last row and sometimes it has. Please note that every time, I have used the same sample data for this report generation.
Also, I have changed below properties of textboxes in tablix as per suggestion in one of the workaround post
Padding - 2pt,2pt,0pt,0pt
Vertical align - Middle
Can grow - false
an shrink - false
And tried increasing the row height from 15pt to 22pt. But above same unusual behavior persists. I have attached the screenshots of report design and sample report here Did anyone experienced this issue before. Any suggestions on this issue will be really helpful.
Report Design

Here row 10045 is hidden
Answer: After spending around an hour, I figured out the fix for it.
As mentioned by Microsoft the row height/width measurement has to be in points.
The main part is you have to apply it for all the cells of the tablix. Select ALL the cells and Press F4 to get the properties window and do the required changes in points (shown below).

Note: The default height of excel row is 14.4pt.
Comment: Thanks for the suggestion. I have already applied this conversion from inches to pt for all the cells of tablix. But no luck. still the issue persists :(
Comment: Also, I have been using the same rdl for generating all the reports by passing different country parameters. I am not getting this hidden last row for all the reports generated.
Comment: Strange! Can you try textboxes padding with 0pt,0pt,0pt,0pt? What is the count of the rows where you have no issue?
Comment: Count of rows after which this hidden row exists is unpredictable too. For example, for country parameter India, report with 18555 records is generated with no hidden last row. But for Pakistan, report with 10043 records is generated with hidden last row. In another case, I could find hidden last row for 375 records itself. Really strange and inconsistent. Also, changing the padding of each textbox and tablix to 0pt,0pt,0pt,0pt didn't work too.
Comment: Last option, convert all the fields measurement to [pt] from [inch] (if left any). Open your report in XML mode (View code) and search for [in] and convert that to [pt].
Comment: Thanks for the suggestion. All the field measurements are converted to pts. But still cant get rid off the hidden last row. I have implemented a workaround as of now (height - 36pt and cangrow - true). It works most of the times. But still few times, reports are generated with hidden last row. Not sure, what is the issue and what might be the solution :(
Answer: I have been facing the same issue, what I did to fix:
1. Converted all the size from cms to pts, page size, report size, columns size, row size, tablix size.
2. It didnt work even after changing row height to 14.2pt, because font was verdana 10pt, and for that minimum 14.3pt is needed in excel
3. I have changed row height to 14.3 pt, and now it works always. No more hidden rows.
Hope this helps.


Computer-controlled portable reed organ?

Question: The "Melauton" is a  computer-controlled reed organ built from a melodica. Is there any record of similar instruments being built?
Answer: Yes.

Device Orchestra
uses electric toothbrushes, handheld printers, etc.
The Floppotron is a giant array
of floppy disk drives.
Hard disks and scanners
have been used too.
A terrifying collection of plush toys.
A piano that can speak human languages.


Label se movendo como letreiro digital

Question: Olá, gostaria de saber como que faço em Swift uma frase ficar passando da direita pra esquerda e quando toda frase passar ela ficar fazendo o mesmo procedimento eternamente, como um letreiro digital.
Answer: Para criar esse efeito da label se movendo (chamado efeito Marquee) você pode usar essa biblioteca: https://github.com/cbpowell/MarqueeLabel-Swift
Se estiver usando cocoapods é só adicionar pod 'MarqueeLabel-Swift' no seu podfile, ou caso queira adicionar manualmente é só colocar a classe MarqueeLabel.swift para dentro do seu projeto.
Agora basta criar uma label no no seu storyboard e colocar a classe dela como custom do tipo MarqueeLabel e conectar com seu @IBOutlet:
  @IBOutlet weak var marqueeLabel: MarqueeLabel!

  override func viewDidLoad() {
    super.viewDidLoad()

    marqueeLabel.type = .Continuous
    marqueeLabel.scrollDuration = 5.0
    marqueeLabel.animationCurve = .EaseInOut
    marqueeLabel.fadeLength = 10.0
    marqueeLabel.leadingBuffer = 30.0
    marqueeLabel.trailingBuffer = 20.0
  }

Label se movendo como letreiro digital


Does windows xp contain GdiPlus.dll?

Question: I have a question about deploying application, my application need gdiplus.dll for load images.
Does windows xp contain GdiPlus.dll as default?
Many Thanks!
Answer: I don't think it is a guarantee, but in my experience it has almost always been there already.  There is a GDI+ redistributable:
Edit:  Here they state quite plainly that GDI+ "is included in Windows XP".  So unless you are deploying to one of those other operating systems, it sounds like you can assume that on Windows XP that it is already there.
Answer: Microsoft's DLL Help Database will tell you for each DLL exactly which versions of which products ship it. You can search it for your specific DLL and see, for example, what is the earliest OS version that ships with it.
Comment: DLL Help Database _`was retired on February 8, 2010 and is no longer accessible.'_

Does windows xp contain GdiPlus.dll?


how to make three inside divs the same height?

Question: I have a container div#content, which contains three divs inside. Now, how could I make sure that three divs inside have the same height? Of course, I hope each div's height could be expanded according to its content. For example:
here is what I tried
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">

<title></title>

Comment: Sounds like you're after an a-typical three column layout, which is not only the holy grail of CSS, but the subject of a gazillion blog posts and tutorials. I've hate it when people say "Google it", but in this case I feel it's actually the best answer you'll get.
Comment: Oh, and Loren.... erm.... sorry, but this drives me nuts for no reason.... it's like a sickness but um... it's "I could *not* care less". "I could care less" doesn't mean anything.
Comment: Please format your code correctly. Four spaces indenting.
Comment: Well, I could care less about the actual size of indenting... But agreed, at least give it to us in a readable fashion...
Comment: It might be better to ask that question on doctype.com (sth like SO, but about html/js/...)
Answer: A very useful technique for creating divs of equal height is to emulate it with a technique called "Faux Columns". This was an idea first suggested by Dan Cederholm (You can read his original article here), and has since evolved. You can see a good tutorial here. If you need it in a liquid layout environment, you might want to read this article.
Basically, the idea builds on NOT trying to force the divs to be of equal height, but have a wrapper of the three divs with a background-image that simulates the background of the columns. This approach works consistently among all modern browsers (ie6 even counts as modern in this context). The negative part is that you'll need a background image that is at least as wide as the page is allowed to expand. i.e. X pixels wide and 1px high.
Answer: I regularly get bashed by the CSS purists for this suggestion, but whenever I run into a problem like this for which – to the best of my knowledge – CSS simply doesn't offer a solution (no, "change your design" doesn't count!)...
I recommend using a table for that part of your layout.
Tables do equal vertical sizing easily and correctly across all major browsers. I'll continue to recommend them until CSS offers workable solutions for those problems.
Comment: If one major browser doesn't handle it, it's not a solution. I know that isn't CSS' fault, but it also doesn't solve the problem.
Comment: I´m getting a bit tired of that same old misunderstanding. CSS DOES OFFER A SOLUTION, it's one mayor browser that just doesn´t know how to handle ccc correctly.
Comment: Well, there are different ways to solve the problem: fake it, use css + javascript for some browsers, use javascript, use tables, etc. They're all valid solutions; I was commenting on your css remarks which are not correct, not your table solution, which works just fine.
Answer: First of all: if you have an equal attribute on different elements, please adhere to the DRY principle (Don't Repeat Yourself) and write it like so:
.content div{
    border:1px solid #404040
}

That way you'll only have to change it in one place.
Now about your question. For a dynamic height, I'd specify that the div's should have a height of 100%, so they fill all the vertical space. This doesn't work nicely cross-browser so look for a hack that does this. If you don't want the div's to fill up the content div, put another div inside the content div and put that around the 3 divs.
So:

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Comment: as the example you made here, just add height:100% to .innerContent will make all 3 divs inside have the same height? I don't think so. Of course, in your example, 3 divs have the exactly same content. How about different contents with different heights?
Comment: I know that height:100% does not work, a combination of one or more hacks and min-height:100% should. The div with the most content will dictate how high div.innerContent is and therefore the other two divs will adapt their height to be 100% and thus the same.
Comment: could you be more specific about "combination of hacks"?
Comment: Here's some more info on exactly how to do that. http://www.456bereastreet.com/archive/200406/equal_height_boxes_with_css_part_ii/

and

http://www.dave-woods.co.uk/?p=144
Answer: I may be wrong, but I think you either put the same values for the heights in the divs (either in percent or px) or you'll have to do some script (for example in JavaScript) that will check on the content height and set the other heights. I don't think it's doable with CSS. If I'm wrong I'd like to know the answer though:P
Comment: percentage height is not widely supported
Answer: You could try it using css for modern browsers (display:table-cell, etc.), however, that will not work in IE6 and IE7.
If IE6 and IE7 are a requirement (I suppose it is...), you can include some javascript just for them using conditional statements and have that javascript set the height of all columns to the tallest. Not really pretty, but the percentages of IE6 and 7 should be going down fast anyway.
By the way, Machine's solution (faux columns) is another solution that works for a lot of designs.
Comment: I promise this is the last comment I will make on this question, but I can't resist: It's really amazing to what lengths the no-tables crowd will go to avoid the most workable solution.
Comment: Just offering alternatives that were not mentioned before, take your pick for a working solution...


Is it possible to use a path like that : user/%user/word with MENU_NORMAL_ITEM instead of MENU_LOCAL_TASK

Question: i hope you understood the title of my topic because i have difficulties to express this problem in english.
I would like to change the menu item which is a tab (saved searches) and put it on my menu block.

So i went to the files of the module and found this:
search_api_saved_searches.module
$items['user/%user/saved-searches'] = array(
'title' => 'Saved searches',
'description' => 'View and edit your saved searches.',
'page callback' => 'search_api_saved_searches_user_listing',
'page arguments' => array(1),
'access callback' => 'search_api_saved_search_edit_access',
'access arguments' => array(1),
'weight' => 5,
'type' => MENU_LOCAL_TASK,
'file' => 'search_api_saved_searches.pages.inc',
);

I know that MENU_LOCAL_TASK is a generally a tab, so i tried MENU_NORMAL_ITEM but it didn't work.
I tried some other thing and removed %user $items['user/saved-searches'] but after that i had many error, i tried to debug them but after many hours i stopped, it was clearly not a good solution to change code directly on a module.
So my question is: Is there a easy way to move a menu item from a tab to a menu block when the path has a wildcard components ? If it's not possible, do you think there is, maybe, a workaround to accomplish what i want to do?
Thanks,
Answer: i used views to achieve what i wanted to do but it was not easy because :

Fields was not the same and didn't have the good format
There was no filter "current user"
So i create a custom template using views-view-table.tpl.php.

I don't know if what i did is very good:

I call global $user in my template, maybe it's a mistake, i don't know if we can do that
Thxs to criticguy, i improved the following code by removing current user test
 <?php foreach ($rows as $row_count => $row): ?>
    <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
    <?php foreach ($row as $field => $content): ?>
     <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
     <?php if($field == 'last_execute') : ?>
       <?php $last_execute = t('@time ago', array('@time' => format_interval(REQUEST_TIME - $content))); ?>
         <?php print $last_execute; ?>
       <?php elseif($field == 'created'): ?>
         <?php $created = format_date($content, 'short'); ?>
         <?php print $created; ?>
       <?php elseif($field == 'notify_interval'): ?>
         <?php $interval = format_interval($content, 1); ?>
          <?php print $interval; ?>
       <?php elseif($field == 'results'): ?>
          <?php $tab = explode(',', $content); ?>
          <?php $x = 1 ?>

          <?php foreach($tab as $value): ?>

            <?php print 'Resultat '.$x.''; ?>

            <?php $x++ ?>
          <?php endforeach ?>

       <?php else: ?>
        <?php print $content; ?>
       <?php endif ?>

<?php endforeach; ?>

Final result:

I'm always interested by my question about MENU_NORMAL_ITEM and MENU_LOCAL_TASK.
Comment: For "current user" in views, see @googletorp's answer here. http://drupal.stackexchange.com/a/22431/1747


How to get a class name dynamically?

Question: I have a classA which contains following code snippet:
 public classA {

    public static Integer getValue(int x) {
      system.out.println(x);
      System.out.println(Qualifiedclassname that where you got the xvalue);
      return x;
    }
 }

The above class contains a method called getValue() which returns int as its declared as argument. This method would be called in another class files like below:
 public class B {

   @Parameters{value}
   public static void setValue(int value) {
     ClassA.getValue(value);
    }
 }

I just want to get a "class name" of the value where I'm getting it. As per above code Class B is giving a value for the getValue() method. I would like to print a class name of b in output console as "com.online.getvaluecode.ClassB".
As per my requirement, I can't use any of the below code in ClassB(client level code, but it can be used in Class A inside getValues()method):
    this.getClass().getName(); or
    Class<?> enclosingClass = getClass().getEnclosingClass();
    enclosingClass.getName();

Class B always used to call ClassA.getValue(x) method, and It has to print the value as well "class name" where I'm getting int value for that method. I don't have permission to use any object creation in ClassB. All I have to do, call the ClassA.getValue(x);
Comment: Your question is unclear.  Do you want `ClassA.getValue` to print the name of `ClassB` ?  Or do you want it to print out `java.lang.Integer` because that's the type of its argument?
Comment: Yes. I want to print a ClassB in classA.getValue() method.
Comment: Is `ClassA.class` what you're looking for here? Or are you looking to pass the ClassB class to the method? In which case, just change the method signature of getValue to accept a Class as well as an int.
Comment: ClassA.java file will just get some int value from class files. Along with I want to print the class name where it gets the value. like i got 10 from  ClassC, and 20 from ClassD. So, I just want to print ClassC, and ClassD in output console along with int values. the problem is , I can't create any object in ClassC and ClassD to get class name. I have permission to invoke ClassA.getValue() method and single int as its argument.
Answer: The straight-forward way is to generate a stacktrace, parse it, and find the caller:
Exception ex = new Exception();
ex.fillInStackTrace();
StackTraceElement[] trace = ex.getStackTrace();
String caller = trace[1].getClassName(); // trace[0] is us, trace[1] is our caller

Though this is generally not very performant, and should not be used in regular operation. "Who called this method" is generally not relevant in the majority of situations, and due to runtime optimizations (inlining, among other things) this information may not even be available at all. Some JVMs do not provide stack trace information because it is very expensive to provide.
I would reconsider your approach and make sure you really need to know who called your method.
Comment: If using later versions of Java, use `Thread.currentThread().getStackTrace()` instead of creating an Exception. It will provide better performance. Note the offset in the array is probably [2] in using the `.getStackTrace()`.
Comment: +1 for the admonishment against doing this.  In general, if your method needs to figure out who called it, *you're doing it wrong*
Answer: in the method getValue(...) you get the int as parameter, the class that is calling that method is not relevant for that method per se, so java is not giving any way to get that info inside the method...
Answer: One option is to create Exception object and call fillInStackTrace method and finally call getStackTrace() method. It returns StackTrace array from which you can get the caller of this method.

How to get a class name dynamically?


Is this is a valid pattern and what is it called?

Question: I find myself writing the following JavaScript more and more and I would like to know if this is a common pattern and if so, what is it called?
Part of the code and pattern:
var fruits = ["pear", "apple", "banana"];

var getNextFruit = function() {
    var _index = 0,
        _numberOfFruits = fruits.length;

    getNextFruit = function() {
        render(fruits[_index]);
        _index = (_index + 1) % _numberOfFruits;
    }
    getNextFruit();
};

I have a function which takes no parameters, inside the function I redefine the function and immediately call it. In a functional language this might be a function being returned, JavaScript just makes it easier because you can reuse the name of the function. Thus you are able to extend the functionality without having to change your implementation.
I can also imagine this pattern to be very useful for memoization where your "cache" is the state we wrap around.
I even sometimes implement this with a get or a set method on the function where I can get the state if it's meaningful. The added fiddle shows an example of this.
Because this is a primarily JavaScript oriented question: The obligatory fiddle
Comment: The pattern is called a "self-defining function", the name has been introduced in Stoyanov's book "Javascript Patterns"
Comment: Not sure what `render` does, but "producing" the elements of a collection one-by-one without caring about the underlying data type is called the [iterator](https://en.wikipedia.org/wiki/Iterator_pattern) pattern.
Comment: Why wouldn't you define the `fruits` variable and array inside the function too?
Comment: This is just a silly example, but imagine `fruits` coming from somewhere else, a service or a call to the server. Now I don't want to put all of *that* logic in there. Wrapping the reference to `fruits` in a self executing function is also something which would have made the code better...
Answer:
I have a function which takes no parameters, inside the function I redefine the function and immediately call it.
  Is this is a valid pattern and what is it called?

A function redefining itself is usually an antipattern, as it complicates stuff a lot. Yes, it sometimes can be more efficient to swap out the whole function than to put an if (alreadyInitialised) condition inside the function, but it's very rarely worth it. When you need to optimise performance, you can try and benchmark both approaches, but otherwise the advice is to keep it as simple as you can.
The pattern "initialises itself on the first call" is known as laziness for pure computations (in functional programming) and as a singleton for objects (in OOP).
However, most of the time there's no reason to defer the initialisation of the object/function/module whatever until it is used for the first time. The ressources taken for it (both time and memory) are insignificant, especially when you are sure that you will need it in your program at least once. For that, use an IIFE in JavaScript, which is also known as the module pattern when creating an object.
Comment: I need some more time to really wrap my head around this concept of laziness and how it would apply to JavaScript. I do think you might be right that this is meant to be a lazy implementation.
Answer: Creating a function via a closure is a pretty common pattern in JavaScript. I would personally do that differently:
var fruits = ["pear", "apple", "banana"];

var getNextFruit = function(fruits) {
    var index = 0,
        numberOfFruits = fruits.length;

    function getNextFruit() {
        render(fruits[_index]);
        index = (_index + 1) % numberOfFruits;
    }

    return getNextFruit;
}(fruits);

There's no good reason (in my opinion) to clutter up the variable names with leading underscores because they're private to the closure anyway. The above also does not couple the workings of the closure with the external variable name. My version can be made a reusable service:
function fruitGetter(fruits) {
   var index = 0, numberOfFruits = fruits.length;

    function getNextFruit() {
        render(fruits[_index]);
        index = (_index + 1) % numberOfFruits;
    }

    return getNextFruit;
}

// ...

var getNextFruit = fruitGetter(someFruits);

var otherFruits = fruitGetter(["kumquat", "lychee", "mango"]);

Comment: A "closure" is a language feature. It's the term for the "object" that's created and sustained to hold the local variables that are "captured" when a function-returning-a-function is called (as in your code).
Comment: You are absolutely right about the underscore, there is no good reason except for some weird "coding standard" I normally use. Makes it easier to refactor and not miss a variable. To come back to the question, is a closure a pattern? Or is a closure just a language feature?
Comment: And if you want to use underscores, then please do so and feel good about it. They just annoy me :)
Comment: Thank you, yes, I had a feeling I was actually doing some OO in a weird way, I just can't find the actual name of the pattern behind it.
Comment: I would love an IDE where the closed over variables has a different color but I think that's some other guy's rant ;)


Bootstrap Radio Addon Behaviour

Question: I'm trying to have a number of radio buttons but I want only 1 to be selected at a time. If one is selected then the previous should get deselected.
Currently all radio buttons can be selected and they don't deselect on change.
How do I fix this?

Existing Users

            <input type="radio" aria-label="...">

        User-1

            <input type="radio" aria-label="...">

        User-2

JSFiddle:
https://jsfiddle.net/a8Lteg1p/
Answer:

Existing Users

                    <input type="radio" name="my-radio-group" aria-label="...">

    User-1

                    <input type="radio" name="my-radio-group" aria-label="...">

    User-2

Add Name attr to your radio button. There is no unique about the radio buttons you have entered.
Answer: Please add name of radio button like this

Existing Users

            <input type="radio" name="radio" aria-label="...">

        User-1

            <input type="radio" name="radio" aria-label="...">

        User-2

Answer: use common name attribute value for all the checkboxes you want.
name='grouped' value can be anything.just used `grouped` for your reference.

see the working fiddle
 here

Bootstrap Radio Addon Behaviour


Integral of two functions which differs to each other in a point

Question: I'm dealing with a base exercise of analysis: given
$$f,g:[a,b]\to \mathbb{R}$$
such that $f(x)=g(x)$ for all $x \in [a,b]$ but not for a certain $x_{0}\in [a,b]$ then $$\underline{\int}_{a}^{b}f(x)dx=\underline{\int}_{a}^{b}g(x)dx$$
I know that it comes as a corollarium of more general theorems but I have to prove this directly by using Darboux's integration.
Comment: So $f,g$ are general bounded functions but not necessarily Riemann integrable?
Answer: Let $\alpha=|f(x_0)-g(x_0)|$. Choose a partition $P$ such that $mesh \,P<\epsilon$ for some $\epsilon>0$. Then $|\mathcal{L}(f-g,P)|<\alpha\epsilon$. This holds for all refinements of $P$. Since $\epsilon>0$, is arbitrary, and $\alpha$ is fixed, the result follows.


How to convert int array to bitmap array list

Question: I have an int array list which is used in an adapter to display images in gallery component.
int[] images = { R.drawable.hm1, R.drawable.hm2, R.drawable.hm3,
        R.drawable.hm4, R.drawable.hm5, R.drawable.hm6, R.drawable.hm7,
        R.drawable.hm8, R.drawable.hm9, R.drawable.hm10, R.drawable.hm11,
        R.drawable.hm12, R.drawable.hm13, R.drawable.hm14, R.drawable.hm15,
        R.drawable.hm16, R.drawable.hm17, R.drawable.hm18, R.drawable.hm19,
        R.drawable.hm20 };

Also i have a link to camera from my application, where we r saving the image to bitmap..i want to update the bitmap image to gallery component everytime i save it.
Can u help me for this..?
Thanks in advance.
Comment: Fetch all the images taken from that "your" camera link that you have, and then call adapter.notifyDataSetChanged() method.
Comment: iam not knowing how to add bitmap image (saved from camera to my app) to the int array list, do i need to convert int array to bitmap array.. or can we get the int value of the bitmap to add it to the array??
Answer: To Make Bitmap from the Resource
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

If you need can make array of the bitmap like this decoding each element.
When you take new image you can add that image to your array/list and update the adapter using notifyDataSetChanged.
Bitmap[] images = { BitmapFactory.decodeResource(getResources
(),R.drawable.hm1),BitmapFactory.decodeResource(getResources
(),R.drawable.hm2),BitmapFactory.decodeResource(getResources(),R.drawable.hm3)};

Comment: So, do i need to change every image's resource id (all) to bitmap and create a bitmap list..??
Comment: yeh, if you using your Resource then this is the way to make drawable image to Bitmap object.
Comment: Initially, i have 50-60 images.. Can we create a loop or method to convert all drawable images to bitmap object at once..??
Comment: you can make Bitmap array as you are creating int Array. just use the above method to create Bitmap instance..if gets OOM error then use createScaledBitmap() to minimize the size of bitmap BUT i will suggest you to do some RnD on Your App Requirement and find minimal and efficient way to do the thing.


Is there any way to recover source code from a deleted revision history?

Question: I want to restore the source code that I accidentally deleted, but I can't find it in the revision history.
Is it possible to revert to a version that is not in the history?
Answer: Every change saved in your project should appear in the version history
By using the legacy editor if you click on your file.gs and then click File > See version history you'll be able to Restore this version in the editor. Otherwise it means that you haven't saved a change made in your code.
If you accidentally deleted a file not only the code as per the documentation says this file can't be recovered despite of using clasp.
In order to avoid accidentally deleted files
I'd recommend you to use a system version control such as Git in conjunction with Clasp as you already used, in doing so you can keep the code up to date either in Git or your Script Project.
Comment: I Can't find it in version history.
Is there a possibility that the history before the push will be lost if I push from clasp?
I want to restore only specific files to the state before they were pushed with clasp.
Comment: I made an edit in order to better explain my answer.