copying contents of a text file in c

Question: I want to read a text file and transfer it's contents to another text file in c, Here is my code:
             char buffer[100];

             FILE*  rfile=fopen ("myfile.txt","r+");
             if(rfile==NULL)
            {
              printf("couldn't open File...\n");
            }

            fseek(rfile, 0, SEEK_END);
            size_t file_size = ftell(rfile);
            printf("%d\n",file_size);
            fseek(rfile,0,SEEK_SET);
            fread(buffer,file_size,1,rfile);

            FILE* pFile = fopen ( "newfile.txt" , "w+" );
            fwrite (buffer , 1 ,sizeof(buffer) , pFile );
            fclose(rfile);
            fclose (pFile);
            return 0;
          }

the problem that I am facing is the appearence of unnecessary data in the receiving file,
I tried the fwrite function with both "sizeof(buffer)" and "file_size",In the first case it is displaying greater number of useless characters while in the second case the number of useless characters is only 3,I would really appreciate if someone pointed out my mistake and told me how to get rid of these useless characters...
Comment: Most files are  bigger than 100 bytes long. Therefore, you need to read the file in chunks to avoid buffer overflow.  I'd user a bigger buffer size (like 4096 or even 65536 bytes), and iterate on that.  The other advice in the answers about paying attention to the order of the arguments to `fread()` and the return value are also correct.
Answer: Your are writing all the content of buffer (100 char) in the receiving file. You need to write the exact amount of data read.
fwrite(buffer, 1, file_size, pFile)

Adding more checks for your code:
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE   100

int main(void) {
    char buffer[BUFFER_SIZE];
    size_t file_size;
    size_t ret;

    FILE* rfile = fopen("input.txt","r+");
    if(rfile==NULL)
    {
      printf("couldn't open File \n");
      return 0;
    }

    fseek(rfile, 0, SEEK_END);
    file_size = ftell(rfile);
    fseek(rfile,0,SEEK_SET);

    printf("File size: %d\n",file_size);

    if(!file_size) {
        printf("Warring! Empty input file!\n");
    } else if( file_size >= BUFFER_SIZE ){
        printf("Warring! File size greater than %d. File will be truncated!\n", BUFFER_SIZE);
        file_size = BUFFER_SIZE;
    }

    ret = fread(buffer, sizeof(char), file_size, rfile);
    if(file_size != ret) {
        printf("I/O error\n");
    } else {
        FILE* pFile = fopen ( "newfile.txt" , "w+" );
        if(!pFile) {
            printf("Can not create the destination file\n");
        } else {
            ret = fwrite (buffer , 1 ,file_size , pFile );
            if(ret != file_size) {
                printf("Writing error!");
            }
            fclose (pFile);
        }
    }
    fclose(rfile);
    return 0;
}

Comment: yes I've tried with file_size but it reduces the number of useless characters not eliminates them...@Bechir
Comment: @AaymanKhalid, which can be because the fread() did not read everything. Check its return value.
Comment: @Bechir,the file does exist,otherwise I'll get the error"couldn't open file",and the data is copied too,it's the useless characters I don't want in the newfile...
Comment: @AmigableClarkKant,I checked the value of fread and indeed is "zero":(
Comment: @AaymanKhalid Please note that you are opening the input file with the option `r+`. If the file `myfile.txt` doesn't exist, it will be created with zero data length. That could explain why you are reading zero size data.
Comment: @AaymanKhalid I updated my answer to add more checks. Shall give you a hint why you have an issue.
Answer: You need to check the return values from all calls to fseek(), fread() and fwrite(), even fclose().
In your example, you have fread() read 1 block which is 100 bytes long. It's often a better idea to reverse the parameters, like this:  ret = fread(buffer,1,file_size,rfile). The ret value will then show how many bytes it could read, instead of just saying it could not read a full block.
Comment: @AaymanKhalid, excellent. Then you can create a loop around your reads and writes, which keeps reading and writing until `feof(rfile)` is set. (Or until you have read file_size bytes, if you trust the file not to change.) If you use `feof(rfile)`, you don't really need to know how large the file is in total, your loop will copy until the end of the file. (This can even avoid trouble with very very large files, but that is another story...)
Comment: @ Amigable Clark Kant,Thank you so much:)
Comment: and one more thing,could you explain to me why there is a difference between the file size and the size of the data read from the file?
Comment: @AaymanKhalid, the operating system has the right to read as little as it wants. It does not *have* to use all the buffer space you give it.  In extreme cases it can even read 0 bytes, but read more at next call. Therefore, always check feof()
Answer: Here is an implementation of an (almost) general purpose file copy function:
void fcopy(FILE *f_src, FILE *f_dst)
{
    char            buffer[BUFSIZ];
    size_t          n;

    while ((n = fread(buffer, sizeof(char), sizeof(buffer), f_src)) > 0)
    {
        if (fwrite(buffer, sizeof(char), n, f_dst) != n)
            err_syserr("write failed\n");
    }
}

Given an open file stream f_src to read and another open file stream f_dst to write, it copies (the remainder of) the file associated with f_src to the file associated with f_dst.  It does so moderately economically, using the buffer size BUFSIZ from <stdio.h>.  Often, you will find that bigger buffers (such as 4 KiB or 4096 bytes, even 64 KiB or 65536 bytes) will give better performance.  Going larger than 64 KiB seldom yields much benefit, but YMMV.
The code above calls an error reporting function (err_syserr()) which is assumed not to return.  That's why I designated it 'almost general purpose'.  The function could be upgraded to return an int value, 0 on success and EOF on a failure:
enum { BUFFER_SIZE = 4096 };

int fcopy(FILE *f_src, FILE *f_dst)
{
    char            buffer[BUFFER_SIZE];
    size_t          n;

    while ((n = fread(buffer, sizeof(char), sizeof(buffer), f_src)) > 0)
    {
        if (fwrite(buffer, sizeof(char), n, f_dst) != n)
            return EOF;  // Optionally report write failure
    }
    if (ferror(f_src) || ferror(f_dst))
        return EOF;  // Optionally report I/O error detected
    return 0;
}

Note that this design doesn't open or close files; it works with open file streams.  You can write a wrapper that opens the files and calls the copy function (or includes the copy code into the function).  Also note that to change the buffer size, I simply changed the buffer definition; I didn't change the main copy code.  Also note that any 'function call overhead' in calling this little function is completely swamped by the overhead of the I/O operations themselves.
Answer: Note ftell returns a long, not a size_t. Shouldn't matter here, though. ftell itself is not necessarily a byte-offset, though. The standard requires it only to be an acceptable argument to fseek. You might get a better result from fgetpos, but it has the same portability issue from the lack of specification by the standard. (Confession: I didn't check the standard itself; got all this from the manpages.)
The more robust way to get a file-size is with fstat.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd>

struct stat stat_buf;
if (fstat(filename, &buf) == -1)
    perror(filename), exit(EXIT_FAILURE);
file_size = statbuf.st_size;

Answer: I think the parameters you passed in the fwrite are not in right sequence.
To me it should be like that-
fwrite(buffer,SIZE,1,pFile)
as the syntax of fwrite is
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The function fwrite() writes nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the  location given by ptr.
So change the sequence and try again.

copying contents of a text file in c


log transform fixed PH in Cox model - how?

Question: I have survival data to which I am fitting a Cox model with a continuous predictor. The cumulative martingale residual method (supremum test)  of Lin, Wei and Ying
suggested that both proportional hazards (PH) and functional form assumptions of the predictor were significantly in error. I log transformed the predictor and the functional form p-value improved (now non significant) but the p-value for the PH assumption is now also non-significant indicating no significant deviation from PH.
How can this be ? How can transforming a predictor make the hazard ratio between different levels of the predictor constant over time ??
Answer: If you don't specify the correct linear form for a continuous predictor in a Cox proportional hazards (PH) model, it's quite possible to get this behavior. Tests for PH come after the regression coefficients for the predictors have been estimated. If there is an error in the model for the regression coefficients then that error can also lead to failure of a PH test.
Consider the Schoenfeld residuals, each of which is the difference between the observed predictor value and the predictor value expected from the Cox model, based on the observed event time. If you don't specify a correct linear form for the continuous predictor, then the Cox regression will be approximating a true non-linear relation with a linear relation. That will necessarily lead to residuals between observed and expected predictor values. If there is a trend in those residuals over time, then that trend will provide evidence against the PH assumption. Using the correct transformation to meet the linearity requirement can prevent both problems.
A simple example illustrates this with analysis based on linear regressions. Let's say that you know that the hazard for each individual is constant in time; that is, survival times fit exponential distributions. A predictor $z$ (which might represent a transformation of the originally measured predictor values $x$) has the standard linear relation assumed by a Cox model, so that that the fraction surviving over time is:
$$S(t) = \exp(-\lambda \exp(\beta z)t)$$ or
$$\log S(t)= -\lambda \exp(\beta z) t$$
Say you have known values of $z$ and enough individuals examined for each value that you have precise estimates of the corresponding median survival times. Call those median survival times $T_{50}$ values. Then the $T_{50}$ values bear a simple relation to $z$, as $S(T_{50})=1/2$:
$$\log(T_{50})= \log (-\log (1/2))- \log \lambda-\beta z $$
So if $z$ meets the linearity assumption, a plot of $\log (T_{50})$ against $z$ will give a straight line with a slope equal to the negative of $\beta$, the regression coefficient for $z$, and with the intercept providing information about the baseline hazard value $\lambda$ when $z=0$.
Now let's apply this to the situation in the OP. We have measured predictor variable values $x$, but they need to be transformed to $z=\log x$ to meet the linearity requirement for the Cox regression. If we do the plot suggested above on this log-transformed scale (with $\lambda =1$ and $\beta = 1$ as an example), we get a straight line with slope of -1:

Note that the observed and predicted values of the predictor on this scale agree. If instead we omit the log transform of $x$ and try the same plot we get:

where the points are the actual values and the solid line represents an attempt at a linear least-square fit. This isn't how the Cox PH model fitting works but the basic idea is the same: you try to find the best linear approximation to this inherently non-linear relation with the predictor values.
Note that the horizontal distance between each point and the solid line is the residual between the observed value of $x$ and the value expected based on this attempt at a linear fit. Now plot the values of those residuals against the untransformed $T_{50}$ values, which is one way to evaluate the PH assumption:

The straight line shows the linear least-squares trend of this decidedly non-linear relationship between residuals and median survival times. This plot would argue that the PH assumption doesn't hold as there is a clear trend in residuals over time. Again, this analysis based on median survival times isn't how standard tests for PH are done for Cox models. Nevertheless the implication is clear: if you don't specify the correct form of a relationship between a continuous predictor and outcome, the failure to meet the linearity assumption can also lead to failure to pass a PH test.
Answer: This paper (Proportionally Difficult: Testing for Nonproportional Hazards in Cox Models) covers this topic nicely
From page 190

The power of the test to detect nonproportionality is dependent on the correct specification of the model. Specifically, omitted covariates and interactions as well as nonlinear functional forms can appear as violations of the proportional hazards assumption complicating the detection of nonproportionality.

And from page 204

The standard test, the Therneau and Grambsch nonproportional hazards test, sees widespread use as it is easy to conduct and interpret. Unfortunately, application of the standard test requires some care as it is sensitive to several forms of misspecification. Analysts must be aware that omitted predictors, omitted interactions, and nonlinear covariate functional forms can all trigger a significant result from the test. Correcting nonlinear functional forms is an important way to improve the specification before testing for nonproportional hazards.
Comment: Thanks for the reference (I wasn't aware of it before) and the helpful addition to this thread. (+1)


Guitar Picking improvement... is forcing EVER good

Question: Long story, and I don't expect magic answers. But I'm always striving to improve and learn, and some of this might elicit good advice. Read if you have the time.
I've been playing a long time, well over 40 years. You may or may not have heard of me as the "internet Peter Pan" guy. Some of my music is here on reverb nation, and it is indeed "fairy tale themed" rock. http://www.reverbnation.com/peterpanrandyconstan  I have some jazz stuff elsewhere, though there is one up-tempo jazz tune on that reverb nation page at the bottom of the song list too (Zing). You may or may not like any of this stuff, but its always good to share what you're doing when you approach anyone discussing technique, so they have an idea where you're coming from musically.
Now the guitar has always been a struggle for me, and most teachers have only been able to help my technical problems so much. Truth be known, the lion's-share of all I have gained technique-wise over the years has come by my violating many of the so-called "right ways" in favor of finding something that at least works. Here is some history of my problem, which has always been 90% a right hand issue, and what I've done so far to push my barriers.
My practice, at least the technical part, has always involved the standard protocol... various scales, arpeggios, chords, inversions, rythems, and rhythmic accent combinations, obviously always practiced with a metronome at progressively higher tempos. But sooner or later I'll get to that point where my picking hand just doesn't want to go faster. There are some reasonable gains by putting in more hours of practice, trying different picking angles, widely different techniques, wrist angles, different amounts of pick motion from the fingers holding the pick, wrist motion (at least a dozen wrist muscle choices), and even elbow and arm motion blended in. But still, sooner or later for some of us it becomes obvious that where some guitarists become better and better, we are stuck in a rut.  So what happens then? many players give up, or submit to the fact that they just will never have the chops to play the things they would like. And lets face it, there are only so many time you can revisit the road of starting over, with some teacher telling you the "right" way to pick... the right way to focus or relax tension. All good advise usually, but as the years tick on its obvious you have to either give up or find a way to break through. Most teachers are GOOD, meaning they didn't have these problems, and so can only understand these ruts to a limited degree.
Now my approach was a little different. Call it a terrible choice, but after years of frustration as a teenage player not getting anywhere, I finally took the first tempo on that metronome that was giving me grief and I FORCED my hand to pick it. Lo and behold after doing so for a while and then resting, that tempo was now comfortable. So...I'd play a while more at that tempo, rest, and then move  up to the next tempo. Force some more, Rinse, repeat, and with enough hours in the day, this would get me up to about 1/16 notes at 120 (or 1/8 notes depending on whether you call 120 the 1/4 note or the 1/2 note. But anyway, that's pretty good for most rock 'n' roll, even if its not shredding tempos. Interestingly, at some point around that tempo, it felt like I was driving at high speed in first gear, and so I began exploring technique variations. I found that some muscle combinations were better for the speeds beyond about 112, others better for tempos up to that amount. And over time I've learned many more technique variations that seem to help me better focus my energy, make the best use of consecutive vs alternate picking, and tons of other little solutions I'm sure you're heard enough times to get tired of it. All totaled, I can now play at pretty much any tempo as long as I'm willing to put in non-stop practice.
So OK, so what if I had to force? If it works it works, right? Well every good player I know still advises against such forcing, so I'm still always pressing for better solutions. For one thing, my muscle memory was never a strong point for me. At least not to extent I'd hoped. To this day, for me to be at my best, I still have to start relatively slow (maybe 1/16th notes in the mid 90s), gradually move up to my find my problem zone, and then start climbing the force ladder again. It takes hours... hours of time dedicated to what I'd call relatively non-musical things. I'm encouraged when players I respect tell me that if I want good muscle memory, I have to play at least 4 hours a day. That's encouraging because it reminds me that even the best players don't skimp when it comes to practice time. But I don't have that kind of time anymore. So I'm continually looking for shortcuts or advice that might help.
Now over the past couple of years i have in fact re-visited all aspects of my right hand technique, and it has yielded some good time saving results. Even if I have to force, for example, it is helpful for me to spend a little time in the beginning of my practice at a very slow tempo, so that I can channel that force into making my motions crisp, short, and with just the right twist or bounce so that cross string alternate picking will work without colliding. And here's another... I've learned that playing small groups of notes at problem tempos yielded a lot better retained accuracy, and somewhat less forcing. Seems that its not the speed that requires the force as much as the non stop playing up and down the scales. Playing groups of 5, then 9, then a few more notes at a time with rests in-between seems to be easing the problem. But still, forcing has always seemed to be the only constant that always yields results, even if I'd prefer that was not the case.
So this is the reason I'm asking this question... to see how many others are in a similar bind, and what they are doing about it. I'm sure there are many players who could chime in and say things like... "playing at any tempo should be effortless, and require zero force". Yeah, and we should all have John McLaughlin's chops on an acoustic guitar with .013 strings too, but this is more a discussion for the "rest" of us, that have struggled some, but have refused to give up, and have gained ground as a result.
Anyway, thanks for listening.
One recent discovery, which I'm adding quite a long time after writing the above. An interesting thing I've added to me practice is that when I get to a troublesome tempo, I play short groups of notes for a while at that tempo instead of whole scales, and gradually work my way up. It feels as though my 'speed" muscles are executing the shorter runs just fine, but my slower "endurance" muscles soon take over, and I end up tensing up, followed by forcing. By doing, say, 5 notes of a scale, so that the first and last end dead on the tick, the metronome is still keeping me honest, but I'm now mainly exercising the speed muscles cell, and resting in between. The hope was to slowly increase the endurance of the speed muscles, rather than increase the speed of the endurance muscles. And after almost 1/2 year of doing this, I can say that it works! It doesn't work miracles, but it does work, and I'm gradually moving to greater accuracy, and less forcing. the practice time unfortunately takes longer, because the key is coming to a complete rest between these note groups. But soon I can get to groups of 9 (2 bars of 1/6th notes), and soon 2 octaves up  two octaves down, and soon 2 octaves up and down followed by the rest. Sometimes on moves that have given me grief (often cross string combinations), I'll just focus on 3 notes, resting , repeat.
I'm absolutely sure I'm on to something here! It comes down to this. They say you can make a sprinter into a long distance runner, but not the other way around. But now methods of speed training for athletes have shown that this technique, using short bursts of speed followed by resting, works. You may not be able to make a long distance runner into a world class sprinter... but you definitely can make him into a BETTER sprinter than he was, by exercising in manner that targets the muscle cells most in need of work.
I won't say this is a magic bullet... I've not totally eliminated the need to force certain things. But it definitely helps. And as we all know, especially if you've been playing a long time, anything that actually does help is gravy!
Comment: minor side comment: John McLaughlin has been criticized for being sloppy, esp. circa 1972 style. This is kind of the opposite of "making my motions crisp, short, and with just the right twist or bounce so that cross string alternate picking will work without colliding." I love Inner Mounting Flame (for example) but a lot of what makes it great is him riding the edge of ability and his relentlessness (the whole band really)
Answer: Playing faster isn't a sign of playing better. Some people, well respected players, can put a huge number of notes in a measure, yet they don't say anything with them.
These are songs and players I've always kept in mind:

Clapton's version of Hideway with John Mayall. He wasn't playing super fast, he was concentrating on phrasing, letting his notes breathe, and waiting for the right moment to play the right note.
David Gilmore from Pink Floyd; He chooses his notes carefully and plays the right thing.
Robbie McIntosh, who backs up John Mayer, is another who really inspires me. The man plays beautifully phrased lines, not fast, just... at... the... perfect... moment and finds just the right notes.
Duane Allman and Dickie Betts, especially on the Fillmore album, played solos that are well thought out, yet they're not blinding fast. The melodies are there, the improvisations play games with the melodies and they build up some classic solos, yet none of it is flashy, every note counts.
At the moment I have Gov't Mule playing, and Warren Hayes is an excellent example of balancing speed and accuracy with phrasing and soul. His solos breathe and I've never thought he'd sacrificed the emotion for the speed. I think that's what we all aspire to, being good enough to accurately play what we're hearing inside.

I believe our brains can only output creative lines at a certain pace. Try to exceed that and the brain isn't in control, the muscles are, and muscle memory isn't nearly as interesting as where a well-versed and inspired musician can go.
I work on scales, intervals, chords, and some riffs, going for accuracy and cleanliness, and to maintain that as I bump up the speed, then practice at that speed to lock it in, but my goal is to get the ideas out of my head as I hear them. I don't care to be blindingly fast, just fast enough to play what I want to say. Sure, there'll always be someone faster, but I'd rather play what I hear in my head as I build a solo when it's my turn to play. If it's fast I want it to come out fast, if it's got holes to breathe, those will come out too.
Comment: This is absolutely the way I see it, supported by bands like Dragonforce, who are fast, but don't seem to put much feeling into their music. Of course the exceptions include Malmsteen, Vai etc...
Comment: I also agree absolutely, musically. However, this is bound to be subjective, and if some people just consider perfectly-played super-fast lines without much "true feeling" (for me, the prime example is Al DiMeola) the top notch of musical expression, than that's fine. Even if you don't, some hard precision & speed practise can't really hurt even if you're ultimately after just a reduced but expressive Blues tone. — So, I don't think this is a good answer.
Comment: I agree that speed and accuracy practice is important, it's just not the end-all goal. Of course some people measure perfection by notes/second, and that's fine. The end goal is to accurately reproduce what we hear in our head. That said, music is an attempt to say something; *I* prefer to say the right thing at the right time. That's just me.
Answer: I'll expand later, but I've found that potentially yes. There's a 6 minute trill exercise by Vai in which you literally just trill with every combo of fingers for a full minute each.  To start with my fingers were slow and the blood just couldn't flow fast enough by the end of the minute, but repeating regularly over a few weeks dramatically improved my left hand technique, both in speed, tone and accuracy.
On the other hand, there are other times when trying to go faster or harder before I'm ready has just messed with my technique and I've been forced to go back to absolute basics and take it slow.
On the other hand sometimes your mind makes you think you're not ready for a speed when you totally are.  You just have a mental block, I believe that's why you can play faster using a metronome and incrementing the tempo than you can going straight to the target tempo, because in your mind it's only a little faster than the last tempo rather than "OMIGOSHLISTENTOALLTHOSECLICKS"
For now, on "is forcing ever good" I'll say yes, but it must be for a reason, the majority of time forcing leads to poor technique.
Answer: I just forced my technique last night with the metronome at higher level than before. Call it lack of patients, but it worked. Sometimes the excitement of just going for it will motivate your mind and hands to accomplish a new level of technique. Then what I did was to slow the metronome down and clean up the technique. This whole process allowed me to have faith that I can achieve faster speeds. Most importantly it was fun and I enjoy it. Now that I know I can play faster at speeds that I didn't play before I am excited to keep practicing and feel more confident to slow down, work on technique, and speed up the metronome.
Answer: One method I've used to work up speed on a piece when I was already at my physical limit is to put the instrument down, and just try to read the music faster. Do it with and without the metronome. Force your mind to cognize the notes faster, considering larger and larger phrases. Doing this for a day or two without picking up the guitar has enabled me to increase by one or two tempo markings without having to push so much. Unfortunately this doesn't take you all the way, but it's another trick to rotate into the normal practice.


Hash Function for 3 Integers

Question: I have 3 non-negative integers and a number n such that
0 <= a <= n, 0 <= b <= n, and 0 <= c <= n.

I need a one-way hash function that maps these 3 integers to one integer (could be any integer, positive or negative). Is there a way to do this, and if so, how? Is there a way so that this this function can be expressed as a simple mathematical expression where the only parameters are a, b, c, and n?
Note: I need this function because I was using tuples of 3 integers as keys in a dictionary on python, and with upwards of 10^10 keys, space is a real issue.
Comment: The first thing which comes to mind is `a * (n + 1)^2 + b * (n + 1) + c`. It won't collide :) Of course, it depends on maximum `n`, so that it can fit into an integer \ 64-bit integer.
Comment: You've determined that existing hashing algorithms don't work already? Or that using nested dictionaries isn't a workable solution?
Comment: I tried using nested dictionaries, but they don't seem to improve the memory usage much. The existing hashing algorithms do work, but speed is a concern and since this was a one-way hash and with very specific constraints, I thought there might be a faster and simpler way.
Comment: Hashing or not you'll still have the same number of entries-are you sure it's the key "depth" that's causing the issue?
Comment: No, I think it's just that Python allocates much more memory for tuples:
sys.getsizeof((1, 2, 3)) is 72, while sys.getsizeof(100000000) is just 28.
Comment: It worked perfectly! Thanks so much.
Answer: How about the Cantor pairing function (https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function)?
Let
H(a,b) := .5*(a + b)*(a + b + 1) + b
then
H(a,b,c) := .5*(H(a,b) + c)*(H(a,b) + c + 1) + c
You mentioned that you need a one-way hash, but based on your detailed description about memory constraints it seems that an invertible hash would also suffice.
This doesn't use the assumption that a, b, and c are bounded above and below.
Comment: I used an integer version of this and you quickly get overflow when the integers get too large. I note that you use the floating point literal 0.5 -- is this done using floating point to avoid overflow?
Comment: @wcochran Good point, honestly I used this as a way to generate keys for floating point numbers read in from stl files (e.g., 3D printing).  Even for unsigned integers experiencing overflow, I imagine this wouldn't be an issue since you only care about generating mostly unique keys.  (But overflow indeed means that this hash is no longer invertible.)
Comment: @wcochran As for the comment about 0.5, I actually coded this as a divide by 2 (via a reinterpret_cast on the arguments) and just let overflow happen.
Answer: Augmenting the answer above for a more concise implementation:
int cantor(int a, int b) {
   return (a + b + 1) * (a + b) / 2 + b;
}

int hash(int a, int b, int c) {
   return cantor(a, cantor(b, c));
}

The easiest way to understand this is that Cantor algorithm assigns a natural number to every integer pair of numbers.
Once we've assigned a natural number N = cantor(b, c), then we can assign a new unique natural number M = cantor(a, N), which we can use as a hash code and is a unique natural number for every triple a, b, c.
As a more general case, you could hash more integers by just another cantor with the next integer (e.g. cantor(a, cantor(b, cantor(c, d)))).
Comment: No hash is collision free where can I found the collision of cantor for 3 integers?

Hash Function for 3 Integers


show a map of complex projective space is lefschetz

Question: This is a problem from a qualifying exam. Let $A \in GL_{n+1}(\mathbb{C})$. Then $A$ defines a smooth map on $\mathbb{CP}^n$ by $A \cdot [z] = [Az]$ for $[z] \in \mathbb{CP}^n$. We will denote this map by $\tilde{A}$.
Fixed points of $\tilde{A}$ correspond to eigenvectors of $A$ for the following reason. Let $z \in \mathbb{C}^{n+1}$ be an eigenvector of $A$, so that $Az = \lambda z$ for some nonzero $\lambda \in \mathbb{C}$. Then we have that $\tilde{A}[z] = [Az] = [\lambda z] = [z]$. Conversely, if $[z]$ is a fixed point of $\tilde{A}$, then $\tilde{A}[z] = [Az] = [z]$, which means that $Az = \lambda z$ for some nonzero $\lambda \in \mathbb{C}$.
I wish to show that if the eigenvalues of $A$ all have multiplicity 1, then $\tilde{A}$ is Lefschetz map. Recall that $\tilde{A}$ is a Lefschetz map if, for all fixed points $[z]$ of $\tilde{A}$, we have that $d\tilde{A}_{[z]}$ does not have $+1$ as an eigenvalue. This is the infinitesimal analog of the demand that $[z]$ be an isolated fixed point. Intuitively, this makes sense, because $A$ having distinct eigenvalues means that $\mathbb{C}^{n+1}$ has a basis of distinct eigenvectors, and so fixed points of $\tilde{A}$ ought to be separated.
My trouble comes from not knowing the correct way to compute the differential. We have that $T_{[z]}\mathbb{CP}^n \cong \mathbb{C}^n$, but $A$ is map of $\mathbb{C}^{n+1}$, and so computing something like
$$
\lim_{h \to 0} \frac{A(z + hv) - A(z)}{h}
$$
doesn't make any sense in $T_{[z]}\mathbb{CP}^n$. If $z_1,\ldots,z_{n+1}$ are the eigenvectors for $A$, then I think that $z_1,\ldots,z_{i-1},z_{i+1},\ldots,z_{n+1}$ should be a basis that can be used for $T_{[z_i]}\mathbb{CP}^n$, but this is more of a hunch than anything I've been able to make rigorous or useful.
Answer: Here's a hint: You can think of $T_{[z]}\mathbb CP^n$ as $\mathbb C^{n+1}/\text{Span}(z)$. Thus, to differentiate a map $f$ to projective space $\mathbb CP^n$, thinking of a lifted map $\tilde f$ to $\mathbb C^{n+1}$, you want to compute $d\tilde f_p \pmod{f(p)}$. (You can check this is all well-defined independent of the lift.)
Comment: Dear Ted, actually $T_{[z]}\mathbb CP^n= L(\text{Span}(z),\mathbb C^{n+1}/\text{Span}(z))$
Comment: @GeorgesElencwajg: Yes, i know the vector bundle structure intimately. For the local purposes of the OP, the twist by $\mathcal O(1)$ is not relevant and would have only confused matters. IMHO.
Answer: In addition to Ted's excellent answer (which I, unfortunately, cannot upvote due to my daily vote limit being transgressed), if you like to think in terms of local coordinates on $\mathbb{CP}^{n}$, then note that $\mathbb{CP}^n$ admits an affine open covering $\mathbb{CP}^n=\bigcup_{i=0}^{n} U_i$ where $U_i=\{[z_0,\dots,z_n]\in \mathbb{CP}^n:z_i\neq 0\}$ ($[z_0,\dots,z_n]$ are the usual homogeneous coordinates on $\mathbb{CP}^n$). Local coordinates on $U_i$ are, e.g., given by $[z_0,\dots,z_n]\to (\frac{z_0}{z_i},\frac{z_1}{z_i},\dots,\widehat{\frac{z_i}{z_i}},\dots,\frac{z_n}{z_i})$; $\widehat{}$ indicates that the coordinate in question is omitted. You can now do explicit calculations in these local coordinates if you wish!
I hope this helps!


Changing elements positions with sql database

Question: I have element with position property. So that you can select them with ORDER BY pos
item | pos
aaa  | 1
bbb  | 2
ccc  | 3

and change them to
item | pos
aaa  | 2
bbb  | 3
ccc  | 1

What is the common way to work with changing positioning?
I am using PHP+SQLite, but I think it doesn't matter.
All I can think about is changing them step by step, swapping every two adjusted things. But it will be messy if they are not adjust, for example, changing element with position x to position 1.
What is the common practices for this? Or what are the keywords for googling it?
Answer: Just found http://jqueryui.com/sortable/ . It can be used to rearrange and then bulk update database values. Sounds like a solution, I will try it.
It has nice serialize( options ) for passing a new order to a server script.


How to change the preferences so that each window displays something different?

Question: I'm trying to override values of preferences, but nothing overrides.
Does anyone know how to fix this?
portlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd">
    <portlet>
        <portlet-name>cool_portlet</portlet-name>
        <portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
        <supports>
            <mime-type>text/html</mime-type>
            <portlet-mode>view</portlet-mode>
        </supports>
        <supported-locale>en</supported-locale>
        <resource-bundle>com.app.portlet.cool_portlet</resource-bundle>
        <portlet-info>
            <title>Cool Portlet</title>
        </portlet-info>
        <portlet-preferences>
            <preference>
                <name>KEY</name>
                <value>TEST</value>
                <read-only>false</read-only>
            </preference>
        </portlet-preferences>
    </portlet>
</portlet-app>

portlet-instances.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE deployments PUBLIC "-//JBoss Portal//DTD Portlet Instances 2.6//EN" "http://www.jboss.org/portal/dtd/portlet-instances_2_6.dtd">
<deployments>
   <deployment>
      <instance>
         <instance-id>coolPortlet_IMPORT_newInstance</instance-id>
         <portlet-ref>cool_portlet</portlet-ref>
          <preferences>
              <name>KEY</name>
              <value>IMPORT</value>
          </preferences>
      </instance>
   </deployment>
    <deployment>
        <instance>
            <instance-id>coolPortlet_EXPORT_newInstance</instance-id>
            <portlet-ref>cool_portlet</portlet-ref>
            <preferences>
                <name>KEY</name>
                <value>EXPORT</value>
            </preferences>
        </instance>
    </deployment>
</deployments>

cool_portlet-object.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE deployments PUBLIC "-//JBoss Portal//DTD Portlet Instances 2.6//EN" "http://www.jboss.org/portal/dtd/portlet-instances_2_6.dtd">
<deployments>
    <deployment>
        <parent-ref>comportal.import</parent-ref>
        <if-exists>overwrite</if-exists>
        <window>
            <window-name>impWindow</window-name>
            <content>
                <content-type>portlet</content-type>
                <content-uri>coolPortlet_IMPORT_newInstance</content-uri>
            </content>
            <region>center</region>
            <height>1</height>
            <supported-window-states>
                <window-state>normal</window-state>
                <window-state>maximized</window-state>
                <window-state>minimized</window-state>
            </supported-window-states>
            <initial-window-state>normal</initial-window-state>
        </window>
    </deployment>
    <deployment>
        <parent-ref>comportal.export</parent-ref>
        <if-exists>overwrite</if-exists>
        <window>
            <window-name>expWindow</window-name>
            <content>
                <content-type>portlet</content-type>
                <content-uri>coolPortlet_EXPORT_newInstance</content-uri>
            </content>
            <region>center</region>
            <height>1</height>
            <supported-window-states>
                <window-state>normal</window-state>
                <window-state>maximized</window-state>
                <window-state>minimized</window-state>
            </supported-window-states>
            <initial-window-state>normal</initial-window-state>
        </window>
    </deployment>
</deployments>

MainController.java
@RequestMapping(value = "VIEW")
@Controller(value = "mainController")
public class MainController {
    @RenderMapping
    public String init(@RequestParam(value = "key", required = false) String key, Model model, PortletRequest request) throws Exception {
        PortletPreferences preferences = request.getPreferences();
        String preferencesKey = preferences.getValue("KEY", "Not Found!!!");
        System.out.println("KEY is : " + preferencesKey);
        model.addAttribute("preferencesKey", preferencesKey);
        return "index";
    }
}

Output:
13:49:54,860 INFO  [STDOUT] KEY is : TEST
13:50:21,088 INFO  [STDOUT] KEY is : TEST

Comment: Are you logged in as a user with admin rights?
Answer: You need to call setValue and then store your PortletPreferences object. Note that preferences can only be stored in action phase. visit


Skip "square chars" from edit on OnKeyDown with Ctrl+BkSp

Question: I wrote an TEdit OnKeyDown handler to make custom Ctrl+BkSp handling. In my example i delete last 2 chars. Seen bad behaviour: after my code "square" char appended to text. How to not "add" such square?
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (key=vk_back) and (shift=[ssCtrl]) then
  begin
    with edit1 do
    begin
      if text<>'' then
        text:= Copy(text, 1, length(text)-2);
      selstart:= length(text);
    end;
    key:= 0;
    Exit
  end;
end;

Comment: Not really related to the issue, but the `Exit` at the end is very superfluous. Also, the test `text<>''` can safely be removed. Finally, ideally `Shift+Ctrl+BkSp` should also work, so replace `Shift = [ssCtrl]` with `ssCtrl in Shift`.
Comment: Are you sure any of your code is really running? What you describe appears to be [what ordinary edit controls do already](http://superuser.com/q/332026/9291), which suggests that what you're seeing has nothing to do with your code.
Comment: @Rob. Sure. My code runs, it deletes last 2 chars. after, OS adds "square" char at end. What for my code needed? i want custom Ctrl+BkSp behavious as "default" SHAutoComplete method doesn't work- coz of some reason- i followed docu to call SHAutoComplete but Ctrl+BkSp not handled.
Comment: SHAutoComplete works. You are doing it wrong. Probably window recreation. You've got to call it in overridden CreateWnd.
Answer: This is a simple to way make Ctrl+BkSp remove the two last characters:
procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin

  if Key = #127 then
  begin
    Edit1.Text := Copy(Edit1.Text, 1, Length(Edit1.Text) - 2);
    Edit1.SelStart := Length(Edit1.Text);
    Key := #0;
  end;

end;

Comment: Please add a comment how `#127` is equivalent to `Ctrl+BkSp`


$A$ and $B$ are p.d,show that $A$ - $B$ is p.s.d iff $B^{-1}$ - $A^{-1}$ is p.s.d

Question:
$A$ and $B$ are p.d,show that $A$ - $B$ is p.s.d  iff $B^{-1}$ - $A^{-1}$ is p.s.d

I have no idea how to prove it.Any hint? Thanks in advance!
Comment: Related question: https://math.stackexchange.com/questions/2402563/positive-definiteness-of-difference-of-inverse-matrices/.
Answer: Since $A$ has full rank you may as well replace $A$ and $B$ with $I$ and $A^{-1/2}BA^{-1/2}$ by a change of coordinates.  Let $C=A^{-1/2}BA^{-1/2}$, let its eigenvalues be $c_i$.  Now the assumption is that the eigenvalues of $I-C$ are all nonnegative, and you want to conclude that those of $C^{-1}-I$ are also all nonnegative. That is, from $1-c_i\ge0$ you want to deduce $c_i^{-1}-1\ge0$.
Answer: For fun, here is the sketch of a deliberately long-winding answer. For every vector $x$, let
$$
y=A^{-1/2}(A^{-1/2}BA^{-1/2})^{-1/2}A^{-1/2}x.
$$
One may verify that
$$
y^\ast Ay=x^\ast B^{-1}x,\quad y^\ast By=x^\ast A^{-1}x.
$$
Therefore $y^\ast(A-B)\,y\ge0$ if and only if $x^\ast(B^{-1}-A^{-1})\,x\ge0$. Since $x\mapsto y$ is bijective, we conclude that $A-B$ is PSD if and only if $B^{-1}-A^{-1}$ is PSD.
Answer: First we will show that if $(A-B)$ is psd, then $(B^{-1} - A^{-1})$ is also psd. Then we will do it the other way round.
Now let $A - B$ be psd. Then $x^\top (A-B) x \ge 0$, which implies that
$x^\top Ax \ge x^\top Bx$
Note that $x^\top A x$ is a scalar and so is the other term and they are both positive because A and B are pd. Now let $x^\top Ax$ be a scalar $k$, and let $x^\top Bx$ be p.
$$k \ge p$$
$$1/k \le 1/p$$
Now since, $k = x^\top Ax$ it follows that $1/k = x^\top A^{-1}x$
$$x^\top A^{-1} x \le x^\top B^{-1} x$$
$$x^\top (B^{-1} - A^{-1}) x \ge 0$$
which shows that $(B^{-1} - A^{-1})$ is psd.
Now we can follow the same pattern and prove it the other way. Don't forget that for an iff proof you need to work in both directions!
Comment: It is not true that "since, $k = x^\top Ax$ it follows that $1/k = x^\top A^{-1}x$".
Take $A=I_K$ (the identity matrix) and $x=\iota_K$, a $(K \times 1)$ vector of ones. Then $x^\top Ax=K$ and $x^\top A^{-1}x=K \neq 1/K$ for $K>1$.


Can we solve for $a$ in $b(x) =\int_{-\infty}^\infty b(s)a(x,s)ds$

Question: For all $x \in \mathbb{R}$, $$b(x) =\int_{-\infty}^\infty b(s)a(x,s)ds.$$  If it helps, we can assume that $a, b$ are continuous, nonnegative, and $\int_{-\infty}^\infty$ of $a$ or $b$ are both bounded.

Two questions: (1) Is $a$ unique?  and (2) to what extent can we solve for $a$?
Comment: A corresponding matrix problem:  Given an eigenvector $b$ for an $n \times n$ matrix $A$, solve for the matrix.  Answer: no, $A$ is not unique.
Comment: This looks like a special case of Fredholm Integral Equations of the Second Kind, with f(x) = 0, $\lambda$ = 1, and where $\phi$ is known instead of the Kernel.  That might be useful.
Comment: This sounds helpful, but I'm not sure what you mean: in what sense is that a corresopnding matrix problem?  Thanks for your help.
Comment: Ah, because $\int_{-\infty}^\infty$ is an inner product.  That's a very interesting way to look at this problem.
Answer: The solution for your integral equation is the Dirac Delta function, that is $$a(x,s) = \delta(s-x).$$ It is known as the sifting propert of the dirac delta function.
Comment: The dirac delta is a functional and not a function. This is of course an extent to which the equation can be solved by means of distributions.
Comment: the Dirac delta function is not continuous, nor bounded.
Comment: He said "if it helps, we assume continuity and boundedness".
Comment: Note that, Dirac delta function is not a function in the usual sense! Why?
Answer: Uniqueness is not necessarily guaranteed. For example, when definable, take $a(x,s)=\frac{b(x)}{b(s)}f(s)$ where $f$ is any probability density, that is $\int_{-\infty}^\infty f(s) ds=1$.


Converting to Floating Point Image from .tif

Question: I am relatively new to C++ and coding in general and have run into a problem when attempting to convert an image to a floating point image. I am attempting to do this to eliminate round off errors with calculating the mean and standard deviation of pixel intensity for images as it starts to effect data quite substantially. My code is below.
Mat img = imread("Cells2.tif");

cv::namedWindow("stuff", CV_WINDOW_NORMAL);
cv::imshow("stuff",img);
CvMat cvmat = img;
Mat dst = cvCreateImage(cvGetSize(&cvmat),IPL_DEPTH_32F,1);
cvConvertScale(&cvmat,&dst);
cvScale(&dst,&dst,1.0/255);
cvNamedWindow("Test",CV_WINDOW_NORMAL);
cvShowImage("Test",&dst);

And I am running into this error
OpenCV Error: Bad argument (Array should be CvMat or IplImage) in an unknown function, file ......\modules\core\src\array.cpp, line 1238
I've looked everywhere and everyone was saying to convert img to CvMat which I attempted above.
When I did that as above code shows I get
OpenCV Error: Bad argument (Unknown array type) in unknown function, file ......\modules\core\src\matrix.cpp line 697
Thanks for your help in advance.
Answer: Just use C++ OpenCV interface instead of C interface and use convertTo function to convert between data types.
Mat img = imread("Cells2.tif");
cv::imshow("source",img);
Mat dst;  // destination image

// check if we have RGB or grayscale image
if (img.channels() == 3) {
    // convert 3-channel (RGB) 8-bit uchar image to 32 bit float
    src.convertTo(dst, CV_32FC3);
}
else if (img.channels() == 1) {
    // convert 1-chanel (grayscale) 8-bit uchar image to 32 bit float
    img1.convertTo(dst, CV_32FC1);
}

// display output, note that to display dst image correctly
// we have to divide each element of dst by 255 to keep
// the pixel values in the range [0,1].
cv::imshow("output",dst/255);
waitKey();

Second part of the question To calculate the mean of all elements in dst
cv::Salar avg_pixel;
double avg;

// note that Scalar is a vector.
// If your image is RGB, Scalar will contain 3 values,
// representing color values for each channel.
avg_pixel = cv::mean(dst);

if (dst.channels() == 3) {
    //if 3 channels
    avg = (avg_pixel[0] + avg_pixel[1] + avg_pixel[2]) / 3;
}
if(dst.channels() == 1) {
    avg = avg_pixel[0];
}
cout << "average element of m: " << avg << endl;

Comment: Hmm it works. However, this didn't seem to actually eliminate my round off errors. When I run the code now my average spits out a value of 1656.76 while the mean function in Matlab is returning 1776.23 and cv::Scalar z = mean(dst); is returning 1612.36... Any ideas?
Comment: You are asking a different question. The conversion approach is correct, it is probably how you calculate the mean value. Can you show your Matlab or OpenCV code for calculating the mean?
Comment: if it awnswered your question consider accepting it by clicking on the check mark beside the answer to toggle it from hollow to green
Comment: Done! Sorry never used stackoverflow before.
Comment: Thanks :)! Hmm, So I tried your edit and it's returning 1612.36 just like I had said using that cv::mean(dst); function. Do you know why the built in MATLAB function mean is returning 1776? That's quite the discrepancy.
Comment: hmm, there should't be a discrepancy. are you sure you are calculating mean on the same input image in Matlab? Is the image also converted to grayscale in Matlab?
Comment: Yes and yes. I checked and it said that it was grayscale 220448 bytes uint16 class. Those bytes are double the image size which i suspect the way MATLAB calculates the average is the cuplrit using that byte size and the classing.
Answer: Here is my code for calculating the average in C++ OpenCV.
int NumPixels = img.total();

double avg;
double c;
    for(int y = 0; y <= img.cols; y++)
        for(int x = 0; x <= dst.rows; x++)
        c+=img.at<uchar>(x,y);
        avg = c/NumPixels;

    cout << "Avg Value\n" << 255*avg;

For MATLAB I just load the image and take Q = mean(img(:)); which returns 1776.23
And for the return of 1612.36 I used cv:Scalar z = mean(dst);
Comment: Yes it inputs as color(although it's a really dark microscope image that looks black and white); but immediately after loading it I convert to gray using cvCvtColor(img, dst, CV_BGR2GRAY);


Sites or youtube videos to learn algebraic geometry

Question: Is there any sites or free lecture videos to learn algebraic geometry? or should I call abstract algebra?
I want to understand about rings, ideals, and real spectrum of rings but my understanding on it is near 0.
If anyone have some recommendation video or anything  (as long as it is free :) ) for commoners (for people whose major is not math) to learn things that I mentioned above, please let me know. Many thanks in advance.
Cheers!
Comment: Just so you know, algebraic geometry is different from abstract algebra.
Comment: Have you tried searching "algebra" in youtube? I remember I have seen quite a few good quality math related videos from channels backed by MIT.
Comment: I thought abstract algebra and algebraic geometry is the same thing ^^
Answer: In order to learn algebraic geometry you will be best off with a good grounding in abstract algebra (groups, rings etc.) and then some commutative algebra (though I guess it's possible to learn some of this as you go along).
Searching MIT opencourseware and similar sites for these topics might work out well, and http://www.extension.harvard.edu/open-learning-initiative/abstract-algebra looks like a good start to me.
As for videos on algebraic geometry, these may be harder to find, but there are some at https://www.youtube.com/playlist?list=PLY28_CByrwHZ0UOqfuw6KVgKIE6-Go0RG at least and there are probably others elsewhere.
Comment: So I should learn Abstract Algebra first before I go to Algebraic Geometry?
Comment: @mathNewbie89 Yes, otherwise it will be really hard to understand anything!
Answer: There're numerous online resources for preliminary materials such as MIT open courseware. There's a growing list in this MO topic Video Lectures in Algebraic Geometry containing rather more advanced materials. Including more math areas, there's the following list Video lectures of mathematics courses available online for free as well.


How to hide div that is referenced by an anchor href on click with javascript (jQuery)

Question: I have several blocks of text separated into their own divs. I also have several links in a navigation bar that reference these divs with an anchor link. On click, I'd like to hide all other divs except the one referenced by the clicked link. I have:

Link 1

Link 2

Link 3

Link 4

So, when I click 'Link 3'. I'd like to hide all divs except #section3.
I'm fine actually hiding/showing each section of text using CSS, but I can't figure out how to use the link's href attribute to reference the div name.
Thanks for your help, and let me know if you need clarification of what I'm asking.
Answer: Try this:
$('#navbar a').click(function() {
    $('div:not(#navbar)').hide();
    $($(this).attr('href')).show();
    return false; // You may or may not want this line.
});

You can see an example here.
Answer: You can use the anchor's .hash property as a selector, all you need to so is hide the divs you want first, like this:
$('#navbar a').click(function(e) {
    $('.container > div').hide();
    $(this.hash).show();
    e.preventDefault(); //to prevent scrolling
});

This assumes you have the
 elements you want to show in a container of some sort, like this:

Section 1

Section 2

Section 3

Section 4

You can test it out here.
Comment: Wow - great. This is exactly the functionality I was looking for. I didn't know that I could use `.hash` as a selector - perfect! Thank you!
Comment: @tsrich - yup, since it's identical to an ID selector it's pretty handy *and* cheaper, win-win :)


What is the equivalent of #page & #page-wrapper in Bootstrap theme?

Question: In most of the Drupal themes I find the IDs #page and #page-wrapper, but it is not available in the Bootstrap theme.
I tried to find in theme, but maximum I could find is class .container but is covers only that particulate section i.e. header, main-content, footer.
Is there any ID or class in Bootstrap theme which covers entire webpage like #page does in almost all other themes OR if there is not how can I add that?
To experiment, I did try to add following to page.tpl.php like other themes,

And added following CSS to check,
#page {
    border: 5px solid red;
}
#page-wrapper {
    border: 5px solid blue;
}

But it applies to border of the browser not to actual width of the page  as shown in the following image.

Hence looks like this way we can not add this to Bootstrap theme.
Any idea or suggestion how to apply #page and #page-wrapper to Bootstrap theme? Thanks.
Comment: No, there isn't any id or wrapper equivalent to #page or #page-wrapper. Saying so, what is exactly you are trying to achieve?
Comment: @MalabyaTewari In process of styling the theme. I wan to add  the page-border and other stuff around the entire-webpage, So I need some Id or class which represent that. In all other theme, most of it is #page and #page-wrapper, but as you said it is not available, might be equivalent also not available. Even I try to add by looking at otehr theme as mentioned in my question. is there way to add?
Answer: After several try and error method, I did find the solution for this.
For a note, I am using LESS.
Step-1: Add a
 to page.tpl.php
Add following code in the page.tpl.php file of your sub-theme.

Step-2: Add the following CSS in the style.less of your sub-theme.
@media(min-width:@screen-sm-min) {
      #page-wrapper {
      width: @container-tablet;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red; }
    }
@media(min-width:@screen-md-min) {
      #page-wrapper {
      width: @container-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }
@media(min-width:@screen-lg-min) {
      #page-wrapper {
      width: @container-large-desktop;
      margin-left: auto;
      margin-right: auto;
      border: 1px solid red;}
    }

So, this way, the added
 will be in harmony of Responsive theme of bootstrap and it will not displace any other container in the site and will not interfere with the native responsive design of Bootstrap.

Further Any suggestion or comment are welcome.


Como gerar nomes randômicos para imagems que vão ser upadas?

Question: Galera estou tendo problema para criar nomes randômicos para minhas imagens.
   Estava tendo usando a função md5(mt_rand(1,10000) mas não obtive sucesso  utilizando em conjunto com has::file.
<code>    public function anexar () {
        if(Input::hasFile('file')){
          $file = Input::file('file');
          $file->move('uploads', $file->getClientOriginalName());
          return 'Anexado com sucesso';
          }
        }
    }
</code>
Answer: Você pode utilizar a função uniqueid() do PHP. Ela gera um id único levando em consideração o tempo, em microssegundos. Você pode passar um prefixo para a função que ela concatenará com o id gerado.
Para mais informações: http://us.php.net/manual/en/function.uniqid.php
Comment: Márcio Lordelo, sou iniciante n programação não consegui entender muito bem o uniqueid ! Tem como vc mandar um exemplo baseado no meu problema acima ?
Comment: Oi @Márcio, consegui resolver o problema aqui usando o uniqueid ! Valeu pela dica brother.
Comment: opa, não tinha visto antes você pedindo um exemplo, desculpe, fiquei alguns dias sem acessar. Que bom que conseguiu =)


onclick effect using just css

Question: I'm trying to increases my skill on html and CSS, i wanted to have on click effect using just css. i know the way to do so using JavaScript put wondering if there is a way to do so using just css

.frame {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 400px;
  margin-top: -200px;
  margin-left: -200px;
  border-radius: 2px;
  box-shadow: 4px 8px 16px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: #fff;
  color: #333;
  font-family: "Open Sans", Helvetica, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #3faf82;
  border-radius: 10px;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.box:hover {
  cursor: pointer;
}

.box:active span:nth-child(1) {
  transform: translate3d(0, 25px, 0) rotate(45deg);
}

.box:active span:nth-child(2) {
  opacity: 0;
}

.box:active span:nth-child(3) {
  transform: translate3d(0, -25px, 0) rotate(-45deg);
}

span {
  margin: auto;
  height: 10px;
  width: 110px;
  background-color: #ffff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s ease-in-out;
}

I thought :active CSS pseudo-class would work but the effect only lasts when your clicking it if not clichéd it goes back to normal. my desired result is on one click to change on another cilice to go back to the original style. is that possible to be obtained using just CSS or am i wasting my time.
Comment: Your best option would be to add an onclick effect where you add or remove a class in javascript: https://www.w3schools.com/howto/howto_js_remove_class.asp
Comment: You could use a checkbox and label if you are wanting pure css - then you can style things with `input:checked` and either sibling combinators - `+` or `~`
Answer: Yes, it is possible using an invisible input type checkbox so that with the pseudo class checked it acts as a trigger to activate and deactivate the animation, as follows:

.frame {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 400px;
  height: 400px;
  margin-top: -200px;
  margin-left: -200px;
  border-radius: 2px;
  box-shadow: 4px 8px 16px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: #fff;
  color: #333;
  font-family: "Open Sans", Helvetica, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #3faf82;
  border-radius: 10px;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 15px;
  z-index: 1;
}
#label{
  position: absolute;
  top: -50px;
  left: -50px;
  width: 200%;
  height: 200%;
  cursor: pointer;
  z-index: 10;
}

#toggle:checked + label + .box span:nth-child(1) {
  transform: translate3d(0, 25px, 0) rotate(45deg);
}

#toggle:checked + label + .box span:nth-child(2) {
  opacity: 0;
}

#toggle:checked + label + .box span:nth-child(3) {
  transform: translate3d(0, -25px, 0) rotate(-45deg);
}

#toggle {
  display:none;
}

span {
  margin: auto;
  height: 10px;
  width: 110px;
  background-color: #ffff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s ease-in-out;
}

    <input id='toggle' type='checkbox'>

Comment: @Pete You are absolutely right, now I am looking for an alternative solution, thanks.
Comment: @Pete It's fixed and working.

onclick effect using just css


STL algorithm to find all tuples with first element within a range

Question: I have a list of tuple, the list was sorted based on the first element of the tuple but the second and last elements are in random order. Now I want to find all tuples with the first element within a range, i.e. return all tuples for (tuple.first>-X and tuple.first<X). Among all these returning tuples, I need to find the maximum and minimum value in the second element of the tuples. How can a STL algorithm implement this?
Answer: ListType::iterator itrFirst = std::find_if( ls.begin(), ls.end(), boost::bind( &TupleType::get< 0 >, _1 ) >= rangeStart );
ListType::iterator itrLast = std::find_if( itrFirst, ls.end(), boost::bind( &TupleType::get< 0 >, _1 ) > rangeEnd );
for( ;itrFirst != itrLast; ++itrFirst ) // Print keys for elements in range
    std::cout << itrFirst->get<0>() << std::endl;

I presume boost:: can be replaced with std:: if you have a recent compiler ( I don't ).
Comment: Thank you a lot. The code looks neat :) I found that it might be too complicate for me to use tuple in my code. So I modify it to use pair instead.
[code]
vector > ls;
vector >::iterator itrFirst = std::find_if( ls.begin(), ls.end(), boost::bind( &pair::first, _1 ) >= -0.01 );
vector >::iterator itrLast = std::find_if( itrFirst, ls.end(), boost::bind( &pair::first, _1 ) > 0.01 );

[/code]

But it doesn't work.
Comment: What's your compiler error? This code requires boost to work, or if you have a compiler post c++98 you can instead include  and use std::bind.
Answer: Since it is already sorted, you can use equal_range to get a pair of iterators that delimit the range of "interesting" tuples:
It const begin = std::lower_bound(list.begin(), list.end(),
                                  [X](Tuple const& t) {
                                      return t.first > -X;
                                  });

It const end = std::upper_bound(begin, list.end(),
                                [X](Tuple const& t) {
                                    return t.first < X;
                                });

std::pair<It,It> const range = std::make_range(begin, end);

Then, you can simply iterate over this range, and register the minimum and maximum values that you see:
int min = INT_MAX, max = INT_MIN;

for (Tuple const& t: range) {
  if (t.second < min) { min = t.second; }
  if (t.second > max) { max = t.second; }
}

// min and max are correctly set

So... it's not a single STL algorithm.
Note: std::min_element and std::max_element do exist, but that would mean looping twice over the range, it's certainly feasible though.
Tuple const& min = *std::min_element(range.first, range.second,
                       [](Tuple const& left, Tuple const& right) {
                           return left.second < right.second;
                       });

Tuple const& max = *std::max_element(range.first, range.second,
                       [](Tuple const& left, Tuple const& right) {
                           return left.second < right.second;
                       });

// Or as noted by Vitali, slightly more efficient:

auto const minmax = std::minmax_element(range.first, range.second,
                       [](Tuple const& left, Tuple const& right) {
                           return left.second < right.second;
                       });

Tuple const& min = *minmax.first;
Tuple const& max = *minmax.second;

Note that it gives a tuple, and not the .second member.
Comment: HI Matthieu M. the first code doesn't pass my compiler (VS2011). by the way, how do I pass the third parameter such that I modify the compare function as (t.first-thirdparameter>-X) && (t.first-thirdparameter)<X ? Thanks.
Comment: @user1285419: you are right, equal range does not seem to cut it because the range is not sorted by absolute value here. You have to use `lower_bound` and `upper_bound instead.
Comment: I would use minmax_element which gives you O(max(floor(3/2(N−1)), 0)) as opposed to O(2N)
Comment: @Vitali: Indeed! Let me amend my answer.


Solving minimization problem $L_2$ IRLS

Question: In the article ''' Chartrand, Rick, and Wotao Yin. "Iteratively reweighted algorithms for compressive sensing." Acoustics, speech and signal processing, 2008. ICASSP 2008. IEEE international conference on. IEEE, 2008. '''
It is given that one iteration of  iterative reweighed least squares problem can be written as $\min \sum_{i=1}^N w_i u_i^2 $ subject to $\Phi u = b  $ which has a closed form solution given as
$u^{(n)} = Q_n \Phi^T (\Phi Q_n \Phi^T)^{-1} b$. where $Q_n$ is the diagonal matrix containing entries $1/w_i$
And the closed form equation can be derived from the Euler Lagrange equation. Can someone please help me to get the derivation of the iteration
Comment: Lagrange multipliers... Better asked at math.se.
Comment: I understood till $\min_u u^T W u + \lambda ||\Phi u - b  ||_2^2$. which can be written as ($ \grad =0$)  W u + \lambda (\Phi^T \Phi u - \Phi^T b) =0
Answer: What you did in your comment was to penalize the constraint. That's something different.
Here you form the Lagrangian
$$
L(u,\lambda) = \tfrac12u^TQ_n^{-1} u + \lambda^T(\Phi u-b)
$$
with a (vector) Lagrange multiplicator $\lambda$ (the factor $\tfrac12$ is for convenience and does only scale $\lambda$).
Now a pair $(u,\lambda)$ is optimal if
$$
\partial_u L(u,\lambda) = Q_n^{-1}u + \Phi^T\lambda = 0
$$
$$
\partial_\lambda L(u,\lambda) = \Phi u-b = 0.
$$
Multiply the first equality by $\Phi Q_n$ to get
$$
\Phi u = -\Phi Q_n\Phi^T\lambda
$$
and by the second equality you get
$$
\lambda = -(\Phi Q_n\Phi^T)^{-1}b.
$$
With this, go back to the first equality to get
$$
Q_n^{-1} u -\Phi^T(\Phi Q_n \Phi^T)^{-1}b
$$
which is (basically) what you want.

Solving minimization problem $L_2$ IRLS


Failure to compile Android application

Question: I am on a Linux Mint 20.X distro.
I installed open source Qt Creator by using the online installer mainly targeting the building native Android applications with C/C++.
I had no experience with Qt Creator so I spent a couple of days trying to figure out how to install, what version, whether bugs existed in a version etc.
Since building native Android applications with C++ required the use of Qt Creator which includes many sub-components I realized there would be lots of different configurations and possible incompatibilities between them.
To start with I am attaching basic information screenshots of my Qt Creator setup:
About dialog: Based on Qt 5.15.2 (GCC 7.3.1 20180303, Red hat 7.3.1-5 64 bit)
I am using Oracle Java JDK 16.0.2 64bit but also tried openJDK from the distro's repos.
Tools->Options->Kits:

In Tools->Options->Qt Versions I could see 6.13 in the auto-detected section and 5.12.8 in the manual (maybe a left over from previous installation attempts)
In Tools->Options->Devices->Android I could see that Java was reported with an OK, SDK location was the one I defined after being prompted by Qt creator during installation, NDK list was /home/manos/Android/sdk/ndk/21.3.6528147. I could see a green tick saying "Android settings are OK (SDK version 5.0, NDK version 21.3.6528147)"
I created two Android virtual devices at the bottom of the same dialog under the AVD tab and I ticked & installed the SDK platform and APIs for Android 10 & 11 under the SDK tab.
After installing Qt Creator, I went straight to Tools->options where I get to download all required components by Qt Creator.
That went smooth after confirming licenses.
Next, I created a desktop pc new application which also went smooth ant built without errors.
I then created my first Android application by following the screenshots below:
In New project dialog I chose Qt Quick Application - Empty.
In Project location I named the project folder "new-mobile-app-ARM64-v8a" and create in field value was /home/manos/Projects/Qt-Creator.
In Define build system dialog I chose qmake.
In Required Qt version - I chose ver. 6 from the drop down list that contained 5.12, 5.13, 5.14, 5.15 & 6.0.
In Kit selection dialog I chose ARM64-v8a clang compiler.
After creating the project I got no errors.
When trying to build it I got the following error:
Could not initialize class org.codehaus.groovy.runtime.InvokerHelper
Full error log:
FAILURE: Build failed with an exception.

What went wrong:
Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

Try:
Run with & ndash; stacktrace option to get the stack trace. Run with & ndash; info or & ndash; debug option to get more log output. Run with & ndash; scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 326ms
Building the Android package failed!
& Ndash; For more information, run this command with & ndash; verbose.

03:49: The process "/home/manos/.programs/qt6/6.1.3/gcc_64/bin/androiddeployqt" exited with code 14.
Error while building/deploying project new-mobile-app-ARM64-v8a (kit: Android Qt 6.1.3 Clang ARM64-v8a)
When executing step "Build Android APK"

03:49: Elapsed time: 00:02.

Later I noticed that gradle was involved in this error.
I searched in S.O and found that one of the suggestions was to change the
distributionUrl value to another version greater than 6.3. Mine was 5.6.4.
I went to https://gradle.org/releases/ and saw that the latest was 7.2
So I tried:
distributionUrl=HTTPS://services.gradle.org/distributions/gradle-7.2-bin.zip
I tried to build again and I got this error:
Execution failed for task ':processDebugManifest'.
Full error log:
FAILURE: Build failed with an exception.
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
You can use ' & ndash; warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings
9 actionable tasks: 9 executed

What went wrong:
Execution failed for task ':processDebugManifest'.
Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @289b717

Try:
Run with & ndash; stacktrace option to get the stack trace. Run with & ndash; info or & ndash; debug option to get more log output. Run with & ndash; scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 701ms
Building the Android package failed!
& Ndash; For more information, run this command with & ndash; verbose.

14:59: The process "/home/manos/.programs/qt6/6.1.3/gcc_64/bin/androiddeployqt" exited with code 14.
Error while building/deploying project new-mobile-app-ARM64-v8a (kit: Android Qt 6.1.3 Clang ARM64-v8a)
When executing step "Build Android APK".

14:59: Elapsed time: 00:02.

Even though I searched I could not find any simple solution.
I tried a few different combinations of qt versions & kits when creating a new project.
I always got the same error.
I have been struggling to make this work for at least 2 full days.
Answer: Problem was solved by downgrading my java version to ver. 11.
Turns out i was looking at the wrong place for 2 days straight.
There is a comprehensive table of compatibility between gradle and java.
Look here: https://docs.gradle.org/current/userguide/compatibility.html.
The default version of gradle being used was unfortunately 5.6.4 as i discovered in the file gradle-wrapper.properties located in the build folders that will be created after you try to build your project.
There is a line:
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip
where the 5.6.4 must be replaced with a valid version.
After you select Build you will notice in the log that the new gradle zip file will be downloaded.
I tried java open jdk 11 with gradle 5.6.4 (default) which worked.
Then i tried java open jdk 13 with gradle 6.5 which also worked.
So the conclusion here is that the correct java version must be used with respect to gradle.
Don't forget to update the java version in menu Tools->Options->Devices, Tab Android->JDK location: /usr/lib/jvm/java-XX-openjdk-amd64/ (which applies for openJDK. Substitute XX with the version that you want to use.
In linux you have to install off course the java that you want to use by typing: sudo apt install openjdk-XX-jdk which may be different in your distro.

Failure to compile Android application


Create circular reveal for pre-Lollipop devices (Android)

Question: Is it possible to get this new Animator for pre-Lollipop devices?
I am newbie and I am trying to get the java files from its official documentation, but I am really lost, I don't know how to find it, etc.
Comment: just use CircularRevealCompat and com.google.android.material.circularreveal.CircularRevealFrameLayout
Answer: I find a library for you. Circular reveal, is compatible with 2.3 devices.
Hope it helps for you!!
Comment: But it requires minSDK 15
Comment: the library isn't being maintained from a long time
Comment: Is it possible to use this on Activity transition?
Comment: this library works great for me, except for API 16, where the animation is square instead of circular. Anybody experienced similar problem?
Answer: This is an update to Alejandro's and BadYous's answers.

Best library is still Circular Reveal.

The right description is implementation 'com.github.ozodrukh:CircularReveal:2.0.1'

Use the right import for ViewAnimationUtils
 import io.codetail.animation.ViewAnimationUtils;

Answer: Yes! you can use CircularReveal library :  as @Alejandro said.
But you have to modify the library dependency to :
dependencies {
    compile 'com.github.ozodrukh:CircularReveal:1.1.1' //without "@aar" contrary to what the documentation says
}

If not, you'll get an Exception on some devices running on pre-lollipop version.
Answer: The best library is : CircularReveal
use :
Use regular RevealFrameLayout & RevealLinearLayout
<io.codetail.widget.RevealFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
...
        />

</io.codetail.widget.RevealFrameLayout>

and :
  View myView = findView(R.id.awesome_card);

    // get the center for the clipping circle
    int cx = (myView.getLeft() + myView.getRight()) / 2;
    int cy = (myView.getTop() + myView.getBottom()) / 2;

    // get the final radius for the clipping circle
    int finalRadius = Math.max(myView.getWidth(), myView.getHeight());

    SupportAnimator animator =
            ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius);
    animator.setInterpolator(new AccelerateDecelerateInterpolator());
    animator.setDuration(1500);
    animator.start();

This library is simple and works very nice in pre lollipop.
Comment: Is it possible to use this on Activity transition?
Comment: in transition structure ! i don't think so , if you find any solution share with us
Answer: Hope this will help you... otherwise just use this http://pulse7.net/android/android-create-circular-reveal-animation-and-ripple-effect-like-whatsapp/
compile ('com.github.ozodrukh:CircularReveal:1.1.1@aar') {
    transitive = true;

Answer: We cannot use Animator to pre Lollipop devices.
Here is the Animator.java
package android.animation;

import java.util.ArrayList;

public abstract class Animator implements Cloneable {

/**
 * The set of listeners to be sent events through the life of an animation.
 */
ArrayList<AnimatorListener> mListeners = null;

/**
 * The set of listeners to be sent pause/resume events through the life
 * of an animation.
 */
ArrayList<AnimatorPauseListener> mPauseListeners = null;

/**
 * Whether this animator is currently in a paused state.
 */
boolean mPaused = false;

/**
 * Starts this animation. If the animation has a nonzero startDelay, the animation will start
 * running after that delay elapses. A non-delayed animation will have its initial
 * value(s) set immediately, followed by calls to
 * {@link AnimatorListener#onAnimationStart(Animator)} for any listeners of this animator.
 *
 *
The animation started by calling this method will be run on the thread that called
 * this method. This thread should have a Looper on it (a runtime exception will be thrown if
 * this is not the case). Also, if the animation will animate
 * properties of objects in the view hierarchy, then the calling thread should be the UI
 * thread for that view hierarchy.

 *
 */
public void start() {
}

/**
 * Cancels the animation. Unlike {@link #end()}, cancel() causes the animation to
 * stop in its tracks, sending an
 * {@link android.animation.Animator.AnimatorListener#onAnimationCancel(Animator)} to
 * its listeners, followed by an
 * {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} message.
 *
 *
This method must be called on the thread that is running the animation.

 */
public void cancel() {
}

/**
 * Ends the animation. This causes the animation to assign the end value of the property being
 * animated, then calling the
 * {@link android.animation.Animator.AnimatorListener#onAnimationEnd(Animator)} method on
 * its listeners.
 *
 *
This method must be called on the thread that is running the animation.

 */
public void end() {
}

/**
 * Pauses a running animation. This method should only be called on the same thread on
 * which the animation was started. If the animation has not yet been {@link
 * #isStarted() started} or has since ended, then the call is ignored. Paused
 * animations can be resumed by calling {@link #resume()}.
 *
 * @see #resume()
 * @see #isPaused()
 * @see AnimatorPauseListener
 */
public void pause() {
    if (isStarted() && !mPaused) {
        mPaused = true;
        if (mPauseListeners != null) {
            ArrayList<AnimatorPauseListener> tmpListeners =
                    (ArrayList<AnimatorPauseListener>) mPauseListeners.clone();
            int numListeners = tmpListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                tmpListeners.get(i).onAnimationPause(this);
            }
        }
    }
}

/**
 * Resumes a paused animation, causing the animator to pick up where it left off
 * when it was paused. This method should only be called on the same thread on
 * which the animation was started. Calls to resume() on an animator that is
 * not currently paused will be ignored.
 *
 * @see #pause()
 * @see #isPaused()
 * @see AnimatorPauseListener
 */
public void resume() {
    if (mPaused) {
        mPaused = false;
        if (mPauseListeners != null) {
            ArrayList<AnimatorPauseListener> tmpListeners =
                    (ArrayList<AnimatorPauseListener>) mPauseListeners.clone();
            int numListeners = tmpListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                tmpListeners.get(i).onAnimationResume(this);
            }
        }
    }
}

/**
 * Returns whether this animator is currently in a paused state.
 *
 * @return True if the animator is currently paused, false otherwise.
 *
 * @see #pause()
 * @see #resume()
 */
public boolean isPaused() {
    return mPaused;
}

/**
 * The amount of time, in milliseconds, to delay processing the animation
 * after {@link #start()} is called.
 *
 * @return the number of milliseconds to delay running the animation
 */
public abstract long getStartDelay();

/**
 * The amount of time, in milliseconds, to delay processing the animation
 * after {@link #start()} is called.

 * @param startDelay The amount of the delay, in milliseconds
 */
public abstract void setStartDelay(long startDelay);

/**
 * Sets the duration of the animation.
 *
 * @param duration The length of the animation, in milliseconds.
 */
public abstract Animator setDuration(long duration);

/**
 * Gets the duration of the animation.
 *
 * @return The length of the animation, in milliseconds.
 */
public abstract long getDuration();

/**
 * The time interpolator used in calculating the elapsed fraction of the
 * animation. The interpolator determines whether the animation runs with
 * linear or non-linear motion, such as acceleration and deceleration. The
 * default value is {@link android.view.animation.AccelerateDecelerateInterpolator}.
 *
 * @param value the interpolator to be used by this animation
 */
public abstract void setInterpolator(TimeInterpolator value);

/**
 * Returns the timing interpolator that this animation uses.
 *
 * @return The timing interpolator for this animation.
 */
public TimeInterpolator getInterpolator() {
    return null;
}

/**
 * Returns whether this Animator is currently running (having been started and gone past any
 * initial startDelay period and not yet ended).
 *
 * @return Whether the Animator is running.
 */
public abstract boolean isRunning();

/**
 * Returns whether this Animator has been started and not yet ended. This state is a superset
 * of the state of {@link #isRunning()}, because an Animator with a nonzero
 * {@link #getStartDelay() startDelay} will return true for {@link #isStarted()} during the
 * delay phase, whereas {@link #isRunning()} will return true only after the delay phase
 * is complete.
 *
 * @return Whether the Animator has been started and not yet ended.
 */
public boolean isStarted() {
    // Default method returns value for isRunning(). Subclasses should override to return a
    // real value.
    return isRunning();
}

/**
 * Adds a listener to the set of listeners that are sent events through the life of an
 * animation, such as start, repeat, and end.
 *
 * @param listener the listener to be added to the current set of listeners for this animation.
 */
public void addListener(AnimatorListener listener) {
    if (mListeners == null) {
        mListeners = new ArrayList<AnimatorListener>();
    }
    mListeners.add(listener);
}

/**
 * Removes a listener from the set listening to this animation.
 *
 * @param listener the listener to be removed from the current set of listeners for this
 *                 animation.
 */
public void removeListener(AnimatorListener listener) {
    if (mListeners == null) {
        return;
    }
    mListeners.remove(listener);
    if (mListeners.size() == 0) {
        mListeners = null;
    }
}

/**
 * Gets the set of {@link android.animation.Animator.AnimatorListener} objects that are currently
 * listening for events on this Animator object.
 *
 * @return ArrayList<AnimatorListener> The set of listeners.
 */
public ArrayList<AnimatorListener> getListeners() {
    return mListeners;
}

/**
 * Adds a pause listener to this animator.
 *
 * @param listener the listener to be added to the current set of pause listeners
 * for this animation.
 */
public void addPauseListener(AnimatorPauseListener listener) {
    if (mPauseListeners == null) {
        mPauseListeners = new ArrayList<AnimatorPauseListener>();
    }
    mPauseListeners.add(listener);
}

/**
 * Removes a pause listener from the set listening to this animation.
 *
 * @param listener the listener to be removed from the current set of pause
 * listeners for this animation.
 */
public void removePauseListener(AnimatorPauseListener listener) {
    if (mPauseListeners == null) {
        return;
    }
    mPauseListeners.remove(listener);
    if (mPauseListeners.size() == 0) {
        mPauseListeners = null;
    }
}

/**
 * Removes all {@link #addListener(android.animation.Animator.AnimatorListener) listeners}
 * and {@link #addPauseListener(android.animation.Animator.AnimatorPauseListener)
 * pauseListeners} from this object.
 */
public void removeAllListeners() {
    if (mListeners != null) {
        mListeners.clear();
        mListeners = null;
    }
    if (mPauseListeners != null) {
        mPauseListeners.clear();
        mPauseListeners = null;
    }
}

@Override
public Animator clone() {
    try {
        final Animator anim = (Animator) super.clone();
        if (mListeners != null) {
            ArrayList<AnimatorListener> oldListeners = mListeners;
            anim.mListeners = new ArrayList<AnimatorListener>();
            int numListeners = oldListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                anim.mListeners.add(oldListeners.get(i));
            }
        }
        if (mPauseListeners != null) {
            ArrayList<AnimatorPauseListener> oldListeners = mPauseListeners;
            anim.mPauseListeners = new ArrayList<AnimatorPauseListener>();
            int numListeners = oldListeners.size();
            for (int i = 0; i < numListeners; ++i) {
                anim.mPauseListeners.add(oldListeners.get(i));
            }
        }
        return anim;
    } catch (CloneNotSupportedException e) {
       throw new AssertionError();
    }
}

/**
 * This method tells the object to use appropriate information to extract
 * starting values for the animation. For example, a AnimatorSet object will pass
 * this call to its child objects to tell them to set up the values. A
 * ObjectAnimator object will use the information it has about its target object
 * and PropertyValuesHolder objects to get the start values for its properties.
 * A ValueAnimator object will ignore the request since it does not have enough
 * information (such as a target object) to gather these values.
 */
public void setupStartValues() {
}

/**
 * This method tells the object to use appropriate information to extract
 * ending values for the animation. For example, a AnimatorSet object will pass
 * this call to its child objects to tell them to set up the values. A
 * ObjectAnimator object will use the information it has about its target object
 * and PropertyValuesHolder objects to get the start values for its properties.
 * A ValueAnimator object will ignore the request since it does not have enough
 * information (such as a target object) to gather these values.
 */
public void setupEndValues() {
}

/**
 * Sets the target object whose property will be animated by this animation. Not all subclasses
 * operate on target objects (for example, {@link ValueAnimator}, but this method
 * is on the superclass for the convenience of dealing generically with those subclasses
 * that do handle targets.
 *
 * @param target The object being animated
 */
public void setTarget(Object target) {
}

// Hide reverse() and canReverse() for now since reverse() only work for simple
// cases, like we don't support sequential, neither startDelay.
// TODO: make reverse() works for all the Animators.
/**
 * @hide
 */
public boolean canReverse() {
    return false;
}

/**
 * @hide
 */
public void reverse() {
    throw new IllegalStateException("Reverse is not supported");
}

/**
 *
An animation listener receives notifications from an animation.
 * Notifications indicate animation related events, such as the end or the
 * repetition of the animation.

 */
public static interface AnimatorListener {
    /**
     *
Notifies the start of the animation.

     *
     * @param animation The started animation.
     */
    void onAnimationStart(Animator animation);

    /**
     *
Notifies the end of the animation. This callback is not invoked
     * for animations with repeat count set to INFINITE.

     *
     * @param animation The animation which reached its end.
     */
    void onAnimationEnd(Animator animation);

    /**
     *
Notifies the cancellation of the animation. This callback is not invoked
     * for animations with repeat count set to INFINITE.

     *
     * @param animation The animation which was canceled.
     */
    void onAnimationCancel(Animator animation);

    /**
     *
Notifies the repetition of the animation.

     *
     * @param animation The animation which was repeated.
     */
    void onAnimationRepeat(Animator animation);
}

/**
 * A pause listener receives notifications from an animation when the
 * animation is {@link #pause() paused} or {@link #resume() resumed}.
 *
 * @see #addPauseListener(AnimatorPauseListener)
 */
public static interface AnimatorPauseListener {
    /**
     *
Notifies that the animation was paused.

     *
     * @param animation The animaton being paused.
     * @see #pause()
     */
    void onAnimationPause(Animator animation);

    /**
     *
Notifies that the animation was resumed, after being
     * previously paused.

     *
     * @param animation The animation being resumed.
     * @see #resume()
     */
    void onAnimationResume(Animator animation);
}

/**
 *
Whether or not the Animator is allowed to run asynchronously off of
 * the UI thread. This is a hint that informs the Animator that it is
 * OK to run the animation off-thread, however the Animator may decide
 * that it must run the animation on the UI thread anyway.
 *
 *
Regardless of whether or not the animation runs asynchronously, all
 * listener callbacks will be called on the UI thread.

 *
 *
To be able to use this hint the following must be true:

 *

 *
The animator is immutable while {@link #isStarted()} is true. Requests
 *    to change duration, delay, etc... may be ignored.

 *
Lifecycle callback events may be asynchronous. Events such as
 *    {@link Animator.AnimatorListener#onAnimationEnd(Animator)} or
 *    {@link Animator.AnimatorListener#onAnimationRepeat(Animator)} may end up delayed
 *    as they must be posted back to the UI thread, and any actions performed
 *    by those callbacks (such as starting new animations) will not happen
 *    in the same frame.

 *
State change requests ({@link #cancel()}, {@link #end()}, {@link #reverse()}, etc...)
 *    may be asynchronous. It is guaranteed that all state changes that are
 *    performed on the UI thread in the same frame will be applied as a single
 *    atomic update, however that frame may be the current frame,
 *    the next frame, or some future frame. This will also impact the observed
 *    state of the Animator. For example, {@link #isStarted()} may still return true
 *    after a call to {@link #end()}. Using the lifecycle callbacks is preferred over
 *    queries to {@link #isStarted()}, {@link #isRunning()}, and {@link #isPaused()}
 *    for this reason.

 *

 * @hide
 */
public void setAllowRunningAsynchronously(boolean mayRunAsync) {
    // It is up to subclasses to support this, if they can.
}
  }

Comment: I hope it will be ported later by google or someone else to lower apis but untill then no way.
Comment: No way to get it to work in pre-Lollipop or something similar?
Answer: Google finally ported it. It is now in the material components library under the name CircularRevealCompat


Command line regular expression '*' and python sys.argv

Question: I have a folder with a number of files that are different by one number (foo1.inp, foo2.inp, foo3.inp, ...).  I want to pass to python, using command line arguments and sys.argv, a string like 'foo*.inp' so I can glob a list of all the files.  However, the argument passed to python when I execute python script.py foo*.inp, ends up being whatever file is listed first in the folder: foo1.inp, instead of foo*.inp.
How can I do this correctly?  Thanks in advance.
Comment: Your *shell* interprets unquoted wildcards...but it's probably doing exactly what you want.  Why not just use all of `sys.argv` instead of the first argument?
Comment: You're right, I just need a list with all the files names.  I didn't stop to think that now my sys.argv is going to contain all the file names. I just was focused on sys.argv[1], where I was expecting to find 'foo*.inp'.  Thanks.
Answer: <code>python myscript.py "foo*.inp"
</code>
I think should work (and not expand your glob)
otherwise as mentioned in the comments its your shell that is expanding foo*.inp to a list of files and then passing them to your script ... and your shell will always do that ... the solution is to quote the glob pattern (it is not regex...) assuming that you actually want the glob pattern and not the files it matches


Abrir 2 janelas e fechar uma de cada vez

Question: No fancybox eu abro duas janelas do plugin e preciso fechar uma de cada vez...
Exemplo: quando abrir a primeira janela só fecha a primeira e quando abrir a segunda só fecha a segunda, a primeira continua aberta quando fecha a segunda...
fiz um exemplo no jsfiddle com as duas janelas e ele fecha as duas quando fecho a segunda...
http://jsfiddle.net/g3R75/1/
Comment: A princípio, o fancybox reutiliza o mesmo DOM para os dois overlays (o que gera o problema), há uma pergunta do SO EN que sugere um workaround para resolver o problema. http://stackoverflow.com/questions/10973380/using-fancybox-version-2-when-closing-2nd-fancybox-reopen-first-fancybox-inste.
Answer: Em 30 de Julho de 2013, o utilizador @JFK abriu um Bug Report para o cenário com que estás a lidar:
Multiple inline content and lock issue when opening fancybox from within fancybox
Essencialmente, se tu tens vários conteúdos inline e tentas abrir uma FancyBox a partir do conteúdo de uma já aberta, recebes um erro:
TypeError: this.overlay is null

E a operação é interrompida.
Até  ao momento não existe resolução para este problema reportado pela FancyBox.

Solução
Como solução podemos trabalhar apenas com uma instância da FancyBox, a que o utilizador vai abrir em primeiro lugar, alterando o conteúdo da mesma mediante a navegação do utilizador:
Ver demonstração no JSFiddle
HTML
Abrir FancyBox 01

        Abrir FancyBox 02

        Teste2

jQuery
// Instanciar a primeira popup
$("#fancy1").fancybox({
    closeBtn: false,
    hideOnContentClick: true,
    padding: 0,
    fitToView: false,
    autoCenter: true,
    type: 'inline',
    helpers: {
      overlay: {
        css: {
          'background': 'rgba(0, 0, 0, 0.55)'
        }
      }
    }
});

/* Anexar um evento de clique no que seria a chamada da segunda popup
 * para que possamos trocar o HTML da primeira pelo HTML da segunda
 */
$('body').on("click", '#fancy2', function(){
    $.fancybox.open({
        closeBtn: false,
        href: "#modal2",
        type: 'inline',
        afterClose: function() {
            /* Chamar a primeira popup quando o
             * utilizador quer sair da segunda
             */
            $("#fancy1").trigger("click");
        }
    });
});

Explicação

Utilizador clica para abrir a primeira popup, a FancyBox executa normalmente;
utilizador clica para abrir a segunda popup, o que fazemos é substituir o conteúdo da primeira popup pelo conteúdo da segunda;
O utilizador fecha a segunda popup, disparamos um click na chamada da FancyBox, trazendo assim de volta o conteúdo original.
O utilizador fecha a primeira popup, a FancyBox fecha normalmente.

Essencialmente estamos sempre a lidar com a chamada da FancyBox, mas duma forma em que não temos o evento da mesma anexado à chamada da segunda modal inline. Desta forma contornamos o problema existente na FancyBox e resolvemos o teu.

Nota:
O que o utilizador @Wakim mencionou no comentário está correcto, a FancyBox faz uso de uma única estrutura de DOM para alternar entre conteúdos e/ou chamadas diferentes, motivo o qual o Bug que salientei existe.
Quando dizes na tua pergunta que ele fecha as duas, o que acontece é que ele fecha a única que existe instanciada. Na realidade nunca existe mais que uma instância da FancyBox.
Answer: Descobri uma outra forma de fazer isso tambem no stackoverflow gringo...
https://stackoverflow.com/questions/24463658/close-2-modal-and-open-1-again/24465132#24465132
JSFiddle: http://jsfiddle.net/RR9Z4/
Usando o callback afterClose,
afterClose: function () {
    if (this.element.attr("id") == "fancybox-button3") {
        $("#button2").click();
    }
}


An trick involving indicator variables, conditional probabilities and expepectation

Question: I am reading a paper on a statistical model for credit risk management. The details of the model are not important, but I mention for context.
Suppose that we are interested in a stochastic process $(A_t)_{t\in[0,T]}$ which has stationary and independent increments. Let $c$ be some fixed positive constant, from which we are interested in finding the conditional probability $P(A_{t_j}>c|A_T<0)$. The paper goes on to find this probability as follows.
$$ P(A_{t_j}>c|A_T<0) = \frac{P(A_{t_j}>c, A_T-A_{t_j}<-A_{t_j})}{P(A_T<0)}
$$
and here's the trick which I am having trouble justifying:
$$
P(A_{t_j}>c|A_T<0) = \frac{E[\boldsymbol{1}_{A_{t_j}>c}E[\boldsymbol{1}_{A_T-A_{t_j}<-A{t_j}}|A_{t_j}]]}{P(A_T<0)}.
$$
Can someone give me some insight into the origin of this identity?
Answer: This is an application of the law of total expectation:
$$
\begin{aligned}
P(A_{t_j} > c, A_T - A_{t_j} < -A_{t_j})
&= E\left[\mathbf{1}_{\{A_{t_j} > c, A_T - A_{t_j} < -A_{t_j}\}}\right] \\
&= E\left[\mathbf{1}_{\{A_{t_j} > c\}}\mathbf{1}_{\{A_T - A_{t_j} < -A_{t_j}\}}\right] \\
&= E\left[E\left[\mathbf{1}_{\{A_{t_j} > c\}}\mathbf{1}_{\{A_T - A_{t_j} < -A_{t_j}\}}\,\middle|\, A_{t_j}\right]\right] \\
&= E\left[\mathbf{1}_{\{A_{t_j} > c\}} E\left[\mathbf{1}_{\{A_T - A_{t_j} < -A_{t_j}\}}\,\middle|\, A_{t_j}\right]\right].
\end{aligned}
$$
The second-to-last equality uses the law of total expectation, and the last equality uses the fact that $\mathbf{1}_{\{A_{t_j} > c\}}$ is $A_{t_j}$-measurable (so that it can be "pulled out" of the conditional expectation given $A_{t_j}$).