Will my orchestral compositions be disregarded if I do not hold a degree in music?

Question: I want to get a grasp of the current state of things, and my question is quite simple.
If a person does not have a university degree in music, does he have any chance to get his orchestral works performed or get a world premiere anywhere? How much will his work be disregarded just because he does not have 'formal' education? How much will renowned festivals ignore him just because of that? How will this prospect change if the person holds a BA in music and how much will it change if the said person gets an MA?
The assumption is that the person who has written the score has great knowledge of music theory and composition and his score is clear and of great quality.
Comment: Quite similar [question](https://music.stackexchange.com/q/53241/2600). The problem is not so much to find a reason for rejection but to provide ample reasons for performing.
Comment: @jjmusicnotes I'm not *sure* why, but I can easily *guess* why. To me, the "question" looks very much like a rant: "I know I'm a musical genius, but I don't have any formal music education so nobody will believe me". Yeah, right... I'm no musical genius, I don't have a music degree, and I don't spend much time hustling my compositions - but I've had performances in four continents so far, and commissions for more music that followed from them.
Comment: There is a lot of negativity posited towards the OP, and I'm not sure why. I'm also not sure of the reason for the down-vote?
Comment: ... maybe it's because people actually *like the music*. But then, I hardly every bother to write anything that *isn't* either going to be performed (often by people who I perform with anyway) or at least is *intended* to be performed. If that means I don't write anything at all for two or three years on end, that doesn't bother me - I don't believe in the 19th century notion of a "Great Artistic Genius" starving in a garret, obsessed with "Creating Great Works Of Art Even When No-one Else Seems To Understand How Great They Are".
Comment: @alephzero Agreed. I interpreted that as the OP just being young. People who are younger / inexperienced sometimes have a warped view - I know that I myself did (I grew up self-taught in a very rural town; it wasn't until I moved to a Big City that I learned the right way 'round). I think maybe people are getting stuck on the bold text at the bottom of the question. I interpreted the intended the meaning to be "competent". Last, good on you for being a creator. :)
Comment: I'm a little concerned about this question. I translate it as 'If I have MA/BA after my name, will it make a difference to my music being played?' Rather than 'Do I actually need a masters degree (and therefore the more than adequate music education) to have my music played?'
Answer: When I was thinking about applying for graduate school, I asked my teacher at the time, who was Ivy-league educated, "Please be honest, does it really matter where I go to school; does anybody actually care?"
My professor smiled at me and said, "I'll put it this way: no matter where people went to school or currently teach, we all see each other at the same conferences and the same festivals. Even though their school might not be well-known or fancy, they're still doing good work."

To answer your question, I'll say it this way: I've learned as much from school as I've learned working in professional settings - the difference is in one of those environments nothing really bad happens if you goof up. Just about every "success" I've experienced has not been because of my education, but because I've hustled for every opportunity - I've created them for myself.
An educational institution does make it more likely that your "orchestral" piece will be programmed - they have concerts entirely devoted to student compositions, some of which are orchestra-themed (to give them experience of writing for large ensemble). However, a specific education does not increase your likelihood of being rejected.
As others have alluded to, it comes down to product, not just the music, but you yourself. Here are three things that actually matter:
1.) The score must look good. It's gotta be perfect, publishing-house or better quality. I judge scores for competition and also do engraving work, and any issues in the visual score reveal glaring problems in a composer's skill-set.
2.) The music must be good. Don't waste your time wondering what other people want you to write. If you're grooving on it, then the rest is out of your hands - your job at that point is to shop that piece around until it resonates with somebody. It'll eventually happen, you just gotta play the odds. That said, irrespective of content, the piece must be well-crafted. People can see a well-crafted piece of music even if it's not stylistically in their wheelhouse. (Also, as an aside, unless a group/organization has a specific concert theme, almost no-one cares about artistic style.)
3.) You have to be active. When you apply for festivals, commissions, competitions, residencies, workshops, etc, people (like me) want to see that you're really active in the music community. So if you've got regular performances, some commissions lined up, maybe some teaching or outreach, cool collaborations, active professional development (workshops / festivals), then you'll be more likely to be programmed. If you've never had a performance and you're looking to make your world-debut with an orchestral piece, good luck.
Bonus:) Just for you. You have to hustle, and you can't stop. Me personally, I get rejected by about 100 things a year, at least. I apply to so many things I don't remember what they are. (In fact, earlier this year I got an email saying that I was a finalist for a major award, but I needed to sign and return a confirmation of the score I submitted. I had no idea I applied for the award or even what piece I submitted. That's an instance where not keeping track can hurt you, or at least it did me.) Once during a phone call with a famous composer, I was shocked to find out that he knew who I was. He said, "oh yeah, I judge on a lot of things and I see you come up all the time." I hadn't ever won anything he judged, but he knew who I was because he saw I applied for (and still do) just about everything that comes up.
The point of this isn't about bragging - I don't need the ego-boost (I'm puffed enough as it is.) The point here is that nowhere in any of those stories or experiences did school or education play a determining factor. It was work, product, tenacity, and professionalism that has been and continues to be the glue of how I engage with the music community.
So, do the work, do your best work, and don't stop doing it.
Hope this helps.
Answer: Take a look at Piazzolla.  I think the premiere of his first orchestral composition including bandonion in Buenos Aires ended in riots and brawls.  He did win a stipend for composition school in Paris in that contest, however, and the most seminal thing he learnt from his teacher there was to stop trying to compose classical music.  He did take classes in counterpoint at her advice and ended up creating his own avantgarde style of music, Tango Nuevo.
In spite of him taking lessons over decades with various instrumentalists and teachers, I don't think he ever earned any degree (and nobody likely would have cared) but still would not have been the same without his formal education.
But whether he got to perform orchstral compositions somewhere or not did not really hinge on any degree or not.
The world hasn't changed all that much since then.  To make it with orchestral compositions, you have to offer something that hasn't already been covered well or better by the old masters.  Without actually studying anything closely, the centuries of music they drew from make for a rather high bar to clear.
Answer: An academic qualification may initially open a few doors.  But it soon comes all about the actual product!
But I detect a subtext in the question.  Yes, your music WILL be rejected if the score isn't clear, readable and playable.  This isn't like elementary school where the teacher says 'Yes, dear, very creative!' and ignores the poor spelling, untidy handwriting and lack of structure.  You need the skills of your trade. If you didn't acquire those skills on a degree course, make sure you acquired them somewhere else!
Comment: @CarlWitthoft A score can be typeset by computer and still be horribly illegible - I can point to dozens of scores I've seen (written by professionals) that look sad.
Comment: Really --  does *anyone* these days expect to distribute a hand-written manuscript?  Every new piece I've seen (and this is at small-town level) is  typeset via Sebelius or LilyPond or equivalent.
Comment: Indeed.  In fact computers have enabled MUCH greater notational sins that would ever have been handwritten.  Like when a novice believes the claims made for Flexitime input to Sibelius...
Comment: @CarlWitthoft computers allow people to produce scores (1) quicker, and (2) with less thought. Neither of those two things improves legibility. If you don't know *how* to lay out a legible score by hand, using a computer won't help you much. "Knowing how to lay out a legible score" has little to do with "having neat handwriting." You don't need a college education - just spend time *looking at well-laid out scores*. There are thousands of them (created by professional engravers who spent years learning their craft) on IMSLP - and thousands of bad ones, for comparison, on the rest of the web.
Answer: To be blunt:  if your music doesn't get play, there are only two reasons.  One, it sucks.  Two, you are not a good salesman.  Even in the 'shooting star' timeline of rock/pop groups, very few headliners were just plain "discovered."  Lady Gaga, for example,  played small theatre and college venues 3 or 4 times a week for a couple years before building enough following to break out.  The same goes for your compositions: you'll have to build a following or a network of conductors or music directors who will at least look at your scores.
Comment: You are taking the liberty to decide that the posted question and the "true question" are different. If that is truly what you believe, the first step is proposing an edit of the question.
Comment: This answer doesn't accurately address the question. The question is not: "Why is my music not getting played?", the question is, "Does having a formal education increase my chances of getting played? / Does not having a formal education increase my chances of not getting played?"
Comment: @jjmusicnotes  I respectfully disagree.  My answer covers the true question; further I'm implying rather clearly that a diploma is a much less important cofactor than other issues.
Answer: If a university education would not be able to add any refinement to your skills in composition and orchestration, chances are that your orchestral compositions will be disregarded regardless of whether or not you formally hold a degree.
Comment: This doesn't answer the question at all, and is borderline rude to the OP. There's no need to be quite so dismissive.
Comment: Please read the post carefully. You have almost responded to a reversal of my inquiry.
Comment: @Wone  no, he's accurately responded.
Comment: Let me put it in simpler terms. I'm not speaking of 'skills'. Imagine two people with the same copy of a particular composition, one holds absolutely no university degrees in music, the other does (BA, MA, whatever). Does the person with no degree have a higher chance of being disregarded to get premiers just because he does not hold a degree? Will he have more difficulty to be even 'considered' by festivals, etc.?
Comment: Agreed with Bob, this answer doesn't adequately or accurately address the question.


How does Binary Relevance work on multi-class multi-label problems?

Question: I understand how binary relevance works on a multi-label dataset: the data is split up into L data sets, where L is the number of labels. Each subset has a column where either a 0 or a 1 is assigned to an instance, indicating the presence or absence of that label on that instance. A separate classifier is trained on each data set.
But, in the case of a multi-class multi-label problem, where some labels may take on different, mutually exclusive class values, is each class treated as a separate label, or is the split still done the same way, except that instead of a "0" or "1", the class is assigned in the label column, thus requiring a multi-class classifier/ classification scheme?
Answer: I think binary relevance should be done still in the way that you proposed.
For an overview of different methods for multilabel classification look here: https://journal.r-project.org/archive/2017/RJ-2017-012/RJ-2017-012.pdf
I don't know how they could be adapted for multiclass multi-label problems. I would also rather call them multitarget problems.


Subsets subspaces rotation

Question: Let $\varphi: \Bbb R^3 \to \Bbb R^3$ be the rotation around the line through the origin and the point
$(1, 1, 1)$ by 120 degrees. Decompose $\Bbb R^3$ as a direct sum of two subspaces that are each stable under $\varphi$.
This is the exercise. So I though that this answer is good??? But I am not sure though. I am really doubthful about it.
My answer:
Let $\varphi: \Bbb R^3\to \Bbb R^3$ be a rotation around the line through the origin and the point $(1,1,0)$ by 60 degrees. Also let $\lambda : \Bbb R^3\to \Bbb R^3$ be the rotation through the points $(1,1,0)$ and $(1,1,1)$ by 60 degrees. Then their sum equals the rotation that is described above?
Comment: You're writing the rotation as the sum of two rotations. You need to write the space as the sum of two subspaces.
Comment: I don't know what "correcting it right" means, but you sure didn't answer the question correctly.  Again, you're giving the wrong *kind* of answer.
Comment: You're asked to write $\Bbb R^3=U\oplus V$ where $U$ and $V$ are stable by $\varphi$. This is very different from writing $\phi$ as a sum of 2 rotations. Is it clear ?
Comment: Try looking through the textbook to figure out what a "direct sum of spaces" is supposed to mean.  Try looking up "direct sum" in the index.
Comment: So I am correcting it right when I let lambda be the rotation though the line (0,0,1) and the origin?
Comment: Hmmm then I do not really understand the question. :(
Answer: The question asks for a decomposition $R^3 = U \oplus V$ such that $\phi(U) \subset U$ and $\phi(V) \subset V$.
Hint: What happens to the axis of rotation (a one-dimensional subspace) under $\phi$? What is a complementary subspace of the axis of rotation that is also invariant under $\phi$?

Subsets subspaces rotation


Fastest sport based on reaction time

Question: Whether it be a goal keeper making a save or a fielder taking a close range catch or a sprinter off the block, reaction time is very essential in sports.
With regard to this, I assumed the fastest games on the planet would be badminton, tennis or table tennis. But tennis players stand at a distance from each other, badminton cock has wind resistance and table tennis balls are slowest of the three.
So which is the worlds fastest game based on reaction time?
Comment: I would guess that motorsports rely heavily on the drivers reaction time, so I would say that an F1 or NASCAR driver would be a safe bet, but it's hard to answer this question reliably since I know of no scientific study that has focused on reaction times of individuals from different sports.
Comment: I guess in order to answer the question with any rigor one would have to try and define what counts as reaction, since the reaction to sudden stimuli could be very different from sport to sport. All in all, I don't think this question will get a factual answer any time soon :)
Comment: A batter hitting a 90mph fastball from 60 feet, 6 inches away in baseball has to be up there.
Comment: 100m is the first thing I can think about, Reaction time at the start can be the difference between winning and losing.
Comment: I'm pretty well convinced by this comment stream that this question is not constructive.
Answer: It's very hard to compare sports in this regards. If we define the reaction time as the time between signal and action, I would say sprinters and swimmers do the purest form of reaction time. It goes straight from audio signal to leg and body muscles. A racket player or bat hitter on the other hand has to process the visual signal to assess ball trajectory, shot selection, then activate muscles.
It doesn't necessarily mean a sprinter has a better reaction time, but that we can get more quantifiable results. Slower reaction times in other sports can be more impressive because of all this extra processing that has to be done.
In track and field sprint start, we basically first defined what is physically possible, and if you do better than that it's considered a false start. One false start and you're out, but the best can still get close to the limit, so when we consider the reaction times of the best sprinters I think we get quite close to what is achievable.

Fastest sport based on reaction time


adding on elements of a paired record to the original record (perhaps using a subselect?)

Question: My data and model looks more or less like this:
      ID      NAME   STUFF    PAIRED_AGAINST
      1       john    xxx       3
      2       jane    yyy       4
      3       jill    zzz       1
      4       jake    aaa       2

class Swaps(models.Model):
    name = models.CharField()
    stuff = models.CharField()
    paired_against = models.IntegerField()

I need help, I think with a subselect, that will return a queryset that gives
me:
id, name, stuff, paired_against, paired_against.name, paired_against.stuff

Many thanks!
Answer: Is paired_against the primary key for a different person? Then you should be using a ForeignKey instead of an integer field.
class Swaps(models.Model):
    name = models.CharField()
    stuff = models.CharField()
    paired_against = models.ForeignKey(self, blank=True, null=True)

Edit
Thanks Daniel!
Comment: Should be `ForeignKey('self')`
Comment: Thanks for the suggestion. I'll give it a try. But one question first ... there are times where the entry is not paired against another entry. Can I have an entry of None as a default?
Comment: @Kevin sure, just set `null=True, blank=True`.


How to add the tail of a line to a hash table

Question: I am trying to use this code to add lines of file to a hash table. Currently it reads a file of the format.
289016164,279211721,462102225
341714666,132189021,299107290
362328497,466836829,47952622

That is with three comma separated lines. I would like it to be able to read lines of the format
289016164,279211721,462102225, some random text
341714666,132189021,299107290, some more random text
362328497,466836829,47952622, even more random text

The struct that should hold each line should be
typedef struct Row {
    uint32_t a;
    uint32_t b;
    uint32_t t;
    char text[40];
} Row;

The routine that reads in the file is called readAll (see below) and  I am having problems modifying it to do this.

How can I change readAll to be able to cope with this new format?

I have included most of the code that uses readAll to give some context.
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

// Should be 37% occupied with 50m entries
#define TABLE_SIZE 0x8000000
#define MASK (TABLE_SIZE - 1)
#define BUFFER_SIZE 16384
#define END_OF_FILE (-1)
#define DEFAULT_VALUE (-1)

typedef struct Row {
    uint32_t a;
    uint32_t b;
    uint32_t t;
} Row;

int32_t hash(int32_t a) {
    return a * 428916315;
}

void insert(Row * table, Row row) {
    long loc = hash(row.a) & MASK; // Entries are hashed on a
    long inc = 0;
    while (inc <= TABLE_SIZE) {
        loc = (loc + inc) & MASK;
        inc++;
        if (table[loc].a == DEFAULT_VALUE) {
            table[loc] = row;
            break;
        }
    }
}

int readChar(FILE * input, char * buffer, int * pos, int * limit) {
    if (*limit < *pos) {
        return buffer[(*limit)++];
    } else {
        *limit = 0;
        *pos = fread(buffer, sizeof(char), BUFFER_SIZE, input);
        if (*limit < *pos) {
            return buffer[(*limit)++];
        } else
            return END_OF_FILE;
    }
}

void readAll(char * fileName, Row * table) {
    char* buffer = (char*) malloc(sizeof(char) * BUFFER_SIZE);
    int limit = 0;
    int pos = 0;

    FILE * input = fopen(fileName, "rb");

    int lastRead;
    Row currentRow;
    uint32_t * currentElement = &(currentRow.a);

    // We read rows with an FSM. We can
    // roll up some of the code using the `currentElement` pointer
    while (1) {
        switch(lastRead = readChar(input, buffer, &pos, &limit)) {
            case END_OF_FILE:
                fclose(input);
                return;
            case ',':
                if (currentElement == &(currentRow.a))
                    currentElement = &(currentRow.b);
                else
                    currentElement = &(currentRow.t);
                break;
            case '\n':
                insert(table, currentRow);
                currentRow.a = 0;
                currentRow.b = 0;
                currentRow.t = 0;
                currentElement = &(currentRow.a);
                break;
            default:
                *currentElement = *currentElement * 10 + (lastRead - '0');
                break;
        }
    }  //printf("Read %d", lastRead);
}

int main(int argc, char** argv) {
    Row* table = (Row*) malloc(sizeof(Row) * TABLE_SIZE);
    memset(table, 255, sizeof(Row) * TABLE_SIZE);

    readAll(argv[1], table);

    //[...]
}

Comment: You might want to change the function to use [`fgets`](http://en.cppreference.com/w/c/io/fgets) instead, and then use e.g. [`strtok`](http://en.cppreference.com/w/c/string/byte/strtok) to "tokenize" the input into its three numbers and the remainder of the line (which is the text).
Comment: Some ways to add an extra state: If `currentElement` is `NULL` then you're reading the trailing text. And you need a new pointer (or array index) into the array where to store the next character. And you need to check for text longer than your array (39 characters plus terminator). And you might need to be able to handle the case where there is no extra text?
Comment: @JoachimPileborg The problem is speed. This method is being used as it is a lot faster and the file is GBs in size.
Comment: Are you sure the code, as shown, is faster than the normal buffering that the standard I/O functions already have? It's using another layer of buffering on top of the existing buffering (which usually is tuned to fit the disk block size).
Comment: @JoachimPileborg Pretty sure. It comes from http://codegolf.stackexchange.com/questions/26643/filter-a-large-file-quickly .  The code as it is runs faster than `wc` which is pretty amazing.
Comment: If you're certain, then you need to add another state to the `','` case so you know that you're done with the numbers and now read text. Then of course modify the `default` case so it knows about this text-reading state. And on newline, terminate the string.
Comment: Oh and the code-golf author couldn't have been to knowledgeable about C, because in C you [should not cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc).
Comment: @JoachimPileborg Thank you. I had the general idea but I just had problems getting that to work and was hoping for some help. I would be grateful for any improvements to the code.
Comment: One last thing, you have to try it yourself. You can't rely on code you just copy (and maybe not understand?) from sites on the Internet, then you won't be able to actually learn anything. The best (only?) way to learn is by *doing*, i.e. writing code yourself.
Comment: Also, just because someone says "this code is fast", it might be fast for that persons use-case, but not for your, and also don't blindly trust it, but do measurements and profiling yourself. First write a "naive" version, try to optimize it, and if still not acceptable efficiency (and you might want to specify the requirements and use-case for us to know about it) then you can try to find more efficient code (just remember to measure it and compare it to what you have).
Comment: @JoachimPileborg I have tested it. It is very very fast. It's easy to test, you should give it a go.  I also have a slow version already. Thank you for the advice however.
Comment: Oh and a very last last thing... ;) Even if there are more efficient or faster ways of doing something, those ways often have other drawbacks, the most important being readability/maintainability. A slower solution might still have acceptable speed, but is probably way more readable (and therefore more maintainable) than the one you have here. If you have a hard time understanding this now, think about how it will be in a few months if you need to come back and look at it again when it's not fresh in memory.
Comment: @JoachimPileborg It would have been great if your final comment had been code :)
Comment: Simply expand the `if()` block in `case ',':` to cope with the 3rd `,` to get and store the comment.
Answer: You need to recognize the third comma and fill in .text when you find it, something along these lines:
        case ',':
            if (currentElement == &(currentRow.a)) {
                currentElement = &(currentRow.b);
                break;
            }
            if (currentElement == &(currentRow.b)) {
                currentElement = &(currentRow.t);
                break;
            }
            {   int i = 0;
                int maxchars = sizeof(currentRow->text) - 1;

                while ((lastRead = readChar(input, buffer, &pos, &limit)) != '\n') {
                    if (i < maxchars) currentRow->text[i++] = lastRead;
                }
                currentRow->text[i] = '\0';
            }
            /* fallthrough*/

Comment: Suggest `i < sizeof(currentRow->text) - 1`
Answer: This will probably do what you want, which is considerably different than how I would have done any of this, but its your code, and I'm looking for a minimal solution.
First, define a macro for your text field length
#define TEXT_LEN    40

and use it in your structure:
typedef struct Row {
    uint32_t a;
    uint32_t b;
    uint32_t t;
    char text[TEXT_LEN];
} Row;

Next, modify your readAll to do this:
void readAll(char * fileName, Row * table)
{
    char* buffer = (char*) malloc(sizeof(char) * BUFFER_SIZE);
    int limit = 0;
    int pos = 0;

    FILE * input = fopen(fileName, "rb");

    int lastRead;
    Row currentRow;
    uint32_t * currentElement = &(currentRow.a);
    size_t txt_len = 0;

    while (1)
    {
        switch(lastRead = readChar(input, buffer, &pos, &limit))
        {
            case END_OF_FILE:
                fclose(input);
                return;

            case ',':
                // move from a to b
                if (currentElement == &(currentRow.a))
                    currentElement = &(currentRow.b);

                // move from b to t
                else if (currentElement == &(currentRow.b))
                    currentElement = &(currentRow.t);

                // move from t to NULL, begin trailing text
                else
                    currentElement = NULL;
                break;

            case '\n':
                // terminate text string
                currentRow.text[txt_len] = 0;
                insert(table, currentRow);
                currentRow.a = 0;
                currentRow.b = 0;
                currentRow.t = 0;
                txt_len = 0;
                currentElement = &(currentRow.a);
                break;

            default:
                // only if  there is a current element to parse as uint32_t
                if (currentElement)
                    *currentElement = *currentElement * 10 + (lastRead - '0');

                // else we're parsing trailing text
                else if (txt_len < (TEXT_LEN-1))
                    currentRow.text[txt_len++] = lastRead;

                // else we consume the char. as we have no space for it anyway
                break;
        }
    }
}

Notes:
Worth mentioning, your code will skip the last entry in the file if it is not terminated by a newline. Addressing that is not entirely trivial, in particular because of the double-buffering being done. The double buffering is a waste, and frequently done to avoid the overhead of the mandated locking characteristics of fgetc() and getc(). If only a single thread is reading the file, you can avoid this and significantly boost your performance by doing the following:

Open the file in read-only mode (you're doing this already)
Invoke flockfile(input) to lock the file for your thread.
Consume the file with your loop using getc_unlocked(input)
Upon reaching EOF, invoke funlockfile(input) and then fclose(input);

Doing the above will eliminate the need for readChar entirely, and reduce your code base significantly.
Best of luck.
Comment: Thank you very much. I will try this as soon as I can. I am interested that you say it could be made even faster. It is very fast currently (even faster than wc for example). It is certainly only one thread using it. How much of a speed up do you get? I also really like the idea of getting rid of readChar entirely!
Comment: @user2179021 As I don't have your data files, I can't really comment on the speed difference; it is simply the way I would likely implement it rather than using trying to double-buffer, and in some platform cases (AS/400 for example) double buffering actually *hinders* performance, as you're actually robbing the system of memory it would otherwise use to efficiently buffer for you. You should try the above and see how it performs.


Evitar a abertura de mais de uma da mesma JInternalFrame

Question: Estou desenvolvendo uma aplicação que utiliza JInternalFrame dentro de um JDesktop. Quando aperto o botão, essa JInternalFrame é instanciada e a janela é aberta, porém, se eu apertar o botão novamente, ele vai abrindo várias janelas iguais. Qual a melhor forma de identificar essa JinternalFrame aberta para que quando o botão for apertado, ela não abra outra igual?
Tentei utilizar isvisible() porém não obtive resultados.
O evento que chama o JInternalFrame é esse:
private void jButton13MouseClicked(java.awt.event.MouseEvent evt) {
    Fimplantar n = new Fimplantar();
    jDesktopPane1.add(n);
    n.setPosicao();
}

Answer: Guarde um seu JInternalFrame como um campo da classe que contém esse evento e verifique se ele contém algo antes de criar um exemplar do frame.
Algo assim:
public class MeuJDesktop extends JDesktop {

    FImplantar meuJInternalFrame;
    // .....

    private void jButton13MouseClicked(java.awt.event.MouseEvent evt) {

        if (meuJInternalFrame != null) {
            this.meuJInternalFrame = new Fimplantar();
            jDesktopPane1.add(this.meuJInternalFrame);
            this.meuJInternalFrame.setPosicao();
        }

    }

    // .....
}

Answer: Consegui resolver com o código abaixo.
public void actionPerformed(ActionEvent evt){

            if(frameUm == null){
                frameUm = new InternalFrameUm();
                frameUm.setVisible(true);
                desktopPane.add(frameUm);
            }
            else if(!frameUm.isVisible()){
                frameUm.setVisible(true);
                desktopPane.add(frameUm);
            }
        }


Cannot seem to find a solution for jQuery $.post

Question: 'SELECT * FROM table WHERE id < '$random' ORDER BY id DESC LIMIT 1'
Comment: But if you're just starting to learn PHP, learn using the MySQLi or PDO extensions with prepared statements and bind variables, rather than blindly injecting user input into your SQL query.
Comment: You need to concatenate them properly. See [the documentation](http://www.php.net/manual/en/language.operators.string.php).
Comment: +1 to what @AmalMurali said.  Use prepared statements to protect yourself from SQL injection methods:  http://us3.php.net/pdo.prepared-statements
Answer: Your concatenation is incorrect on line 9:
$db->query('SELECT * FROM table WHERE id < ' . $random . ' ORDER BY id DESC LIMIT 1');

. is the concatenation operator in PHP.
And unless you enjoy SQL injection, I would strongly suggest escaping the POST input, unless your $db object does this for you.
Comment: This is the correct answer, but please do not use this code on a public web server, someone can corrupt your database because you're not escaping the data in the SQL query.
Comment: @MichaelButler I was actually just editing my post to include that. :)


Onde guardar a informação?

Question: Tenho uma aplicação em angular, básica com formulários que guarda os dados em arrays e recebe os dado in dados em div's. Agora como eu poderei armazenar estes dados? Que opções tenho estando a utilizar AngularJS?
Estando familiarizado com php e MySql, sei que posso passar os dados por $http e chamar o ficheiro .php que insere na base de dados relacional, mas também sei que existe o MongoDB...
Uma aplicação que utiliza MongoDB funciona em um servidor PHP/Linux?
Mais uma coisa, na página do Angular eles fazem referência ao Firebase que me deixou com mais duvidas ainda. Qual a melhor maneira de "jogar" com dados no AngularJS?
Answer: Não existe uma "melhor" maneira de salvar dados com AngularJs, tudo vai depender das suas necessidades/projetos. O MongoDB funciona sim em servidores Linux e para utiliza-lo com php é necessário instalar um driver
Já o FireBase é um serviço BaaS(Backend as a Service) que já fornece a maioria das funcionalidades que você teria que implementar em um Backend. Dessa forma você irá fazer a conexão direto com o serviço.
Referências:
Utilizando a dupla MongoDB e PHP
BaaS - Backend as a Service
Comment: Obrigado pela resposta!
Answer: Depende de como você deseja modelar sua aplicação:

No seu browser - Você pode escrever uma solução completamente client-side, mantendo os dados do usuário na instância do browser. Para tanto, utilize a Web Storage API ou uma biblioteca que lide com ela, como a angular-webstorage. A desvantagem é que seus dados persistirão apenas para aquele browser.
Em um servidor - Você precisará de um back-end para armazenar seus dados. Modelos variam: Desde uma implementação NodeJS + object-storage para aplicações simples, passando por bancos de dados relacionais (MySQL, PostgreSQL, SQLite, MariaDB, Oracle, MS SQL Server e outros) ou não (MongoDB, Redis, DynamoDB, etc).

Onde guardar a informação?


Problemas com o popup menu e o Immersive Mode

Question: Eu configurei o meu aplicativo para usar o Immersive Sticky Mode, mas eu também utilizo alguns elementos que estão acima do contexto da Activity e que, quando o usuário interage com eles, o aplicativo sai do Immersive Mode e a status bar volta a ser exibida. Esses elementos são um dialog box e um popup menu de uma toolbar. Consegui impedir que a status bar aparecesse quando o dialog fosse chamado através do seguinte código dentro do meu método showDialog:
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
Porém, não estou conseguindo fazer o mesmo com o popup menu. Esses são os métodos de criação e de seleção do menu:
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_view, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int choosenId = item.getItemId();

    switch (choosenId){
        case R.id.btn1:
            lblTitle.setText(R.string.btn1);

        break;
        case R.id.btn2:
            lblTitle.setText(R.string.btn2);

        break;
        case R.id.btn3:
            lblTitle.setText(R.string.btn3);

        break;
        case R.id.btn4:
            lblTitle.setText(R.string.btn4);

        break;
    }
    return super.onOptionsItemSelected(item);
}

E esse é o xml da minha toolbar:
       <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorBackgroundDarker"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="?attr/actionBarSize">

                <Button android:id="@+id/btnBack"
                    android:layout_width="35dp"
                    android:layout_height="35dp"
                    android:layout_centerVertical="true"
                    android:background="@mipmap/button_back_orange" />
            </RelativeLayout>

            <TextView android:id="@+id/lblTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/title"
                android:textSize="22sp"
                android:textColor="@color/white"
                style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
                android:layout_gravity="center"/>

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

Answer: Tente adicionar isso em sua Activity:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

Comment: Eu já tenho isso adicionado a todas as minhas Activities e funciona perfeitamente para elas, mas a questão é que isso não funciona para o popup menu.


How to send a PHP *variable* back to jQuery without echoing?

Question: I am using the ajax() function to send a string to a PHP file.
In case of a success, the PHP file echoes "the validation of the string was successful". But I would also like to send the actual string back to jQuery and put it in a div.
How can send back that string, without having to echo it along with the confirmation message?
Or should I put both messages into a string, send it to jQuery and have jQuery split that string?
What's the best way?
Comment: You can use [`json_encode($response)`](http://php.net/manual/en/function.json-encode.php), where `$response = array('success or failure', $your_string);`. Or something to that effect. The advantage of doing that is that it will escape things for you and it will generate an object JS can use without further parsing.
Comment: The comment above is a good way to do it, but I'm intrigued: do you want to send back the same string you passed to PHP? If that's the case, you don't have to. You already have the string in jQuery, just use it.
Comment: Hi, thanks for your responses. I want to sanitize the string server-side because I want to append the user's input into my HTML page. Regards
Comment: @alexx0186 If you want to sanitize it, it can be done using JS as well. It would also have the benefit of not using your bandwidth or your users' bandwidth.
Answer: Putting what others have said into code, you might set up your PHP script to return a JSON-encoded object like so:
<code>$result = array(
  'message' => 'the validation of the string was successful',
  'original' => 'string sent by client'
);

echo json_encode($result);
</code>
On the client side, you can then access each piece from your callback function like so:
<code>function (result) {
  alert(result.message);
  // do something with result.original
}
</code>
Comment: Hi rjz, thanks for your response. Actually I want to send the escaped version of the original string. But I'd like to know how you handle that array in JS? Just the usual `$result[0]`? Thanks a lot
Comment: Oh ok, you just answered my question! So $result[0] would work? EDIT: nevermind, I'll use your way. Thanks!
Comment: Hi rjz, I get "undefined" when I `alert(result.message)`. I did it within the "success" callback function of `ajax()`. Would that cause a problem? Thanks a lot
Comment: Hard to tell for sure, but you might try calling `console.log(result)` to make sure that you're getting the `result` you expect from the server.
Comment: Hi, thanks for your message. The problem was that I had to add "dataType: 'json'" to make it work. Regards
Answer: I would return JSON with the string and the validation message.


Different confidence interval results in R, why?

Question: Using the following population:
sample <- c(41.5, 56.7, 54.2, 98.9, 56.7, 43.9, 35.8, 28.8)

I get a different result for the upper and lower confidence intervals when calculating them "manually" than what result from the standard library t.test() function.
s <- sd(sample) # standard deviation
se <- s/sqrt(NROW(sample)) # standard error

# Using t.test()
lower <- (t.test(sample))$conf.int[1] # yields 34.11755
upper <- (t.test(sample))$conf.int[2] # yields 70.00745

# Calculating manually
lower <- mean(sample)-(1.96*se) # yields 37.18821
upper <- mean(sample)+(1.96*se) # yields 66.93679

Can somebody explain what is going on here?
Update:
Thanks for the information everybody! This was really enlightening.
Answer: You are using 1.96, which is the Normal quantile, rather than the quantile from the t distribution with appropriate degrees of freedom (length(sample)-1). Your manually-calculated confidence interval is too narrow.
Comment: +1. In other words, change the manual calculations to `mean(sample) + qt(c(.025, .975), length(sample) - 1) * se`.
Comment: And be careful with `length(x)` (or `NROW(x)`) since it will return the size of the vector, including missing values if any. In case of doubt, `sum(!is.na(x))` or `sum(complete.cases(x))` are to be preferred. (BTW, `sample` is the name of a specific function in R.)
Comment: @shootingstars You're welcome. Re: your preceding comment; if you know the population variance (or SD) you don't need to estimate it from your sample and you can use a z-test (or, equivalently, refer to standard N(0;1) quantiles) --  but this is rarely true (that we know the true SD).
Comment: Interestingly, `NROW` (as in the OP) would be needed here as it will treat a vector as a one-column matrix. `length` would be another option. (`NROW` was actually new to me, I had to look it up.)
Comment: Oh, interesting. Thanks for the correction. I'll change it to `length()`.
Comment: @JonathanChristensen Just to clarify, is this due to the t-test calculation being made assuming [the standard deviation is unknown](http://en.wikipedia.org/wiki/Student%27s_t-distribution), which "uses" one degree of freedom?
Comment: @chl Thanks. That is really useful. I only used `sample` for this example, and I try to follow typical naming conventions.


How does one play baseball and football (professionally) at the same time?

Question: The question is pertinent because both sports are played professionally, simultaneously, in September.
It came about, because the Texas Rangers "drafted" the Seahawks quarterback Russell Wilson in a Rule 5 Draft. Wilson had played baseball earlier in his career.
More to the point, apparently "Neon" Deion Sanders actually played both in the late 1980s, with the Atlanta Braves and Falcons. How did he manage it?
Answer: There have been two men in recent history who have managed to play both professional baseball and professional football at the same time. Deon Sanders and Bo Jackson.
At the most basic, the baseball and football seasons don't overlap very much. Football's preseason and early season does overlap somewhat with baseball's late and post season, and players will have to make a choice between which sport they play during that time (as it would be difficult to be in two places at once to be able to practice with your football team and keep a nightly baseball schedule). However, if you don't practice with the football team (and the team is OK with that), you can in theory play baseball during the week and play football on Sunday, only missing the Sunday (and maybe Saturday or Monday) baseball games.
This requires a great deal of good will from both your NFL and MLB teams (and obviously sufficient star power in both sports for them to be willing to let you have this much flexibility).
This is something that both Sanders and Jackson shared, both were very good at both sports to the extent that teams were willing to let them do both even though they had to sacrifice a roster spot to a player who would not be there 100% of the time.
However, this kind of schedule takes a toll. Sanders eventually chose football, Jackson eventually chose baseball.
Comment: Note that Jackson chose baseball because of a football career-ending injury.
Comment: @edmastermind29: Good point And if you are a coach, how do you explain to your fans that the "star player" you signed got injured playing the OTHER sport?
Answer: I was about to post that Brian Jordan was another player who played in both the NFL and MLB, but he was still in minor league baseball when playing in the NFL for the Atlanta Falcons. When he signed a new contract with the St Louis Cardinals (MLB) before the start of the 1992 NFL season, there was a $1.7 million bonus if he stopped playing football. So, in short, Jordan never played both baseball and football at the major league level simultaneously.


iproute2 interface statistics seem wrong

Question: For some reason, ip -s link does not show the same numbers as /proc/net/dev, specifically the overrun count.
For a given interface, ip shows no overrun packets:
$ ip -s link show eth-ext1
7: eth-ext1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 00:08:a2:0d:00:74 brd ff:ff:ff:ff:ff:ff
    RX: bytes  packets  errors  dropped overrun mcast
    1038103044434 1099087192 0       0       0       401298
    TX: bytes  packets  errors  dropped carrier collsns
    543051882227 844808055 0       0       0       0

While in proc we see non-zero overrun (which is what I am assuming fifo is referring to):
$ cat /proc/net/dev
Inter-|   Receive                                                |  Transmit
face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
[...]
eth-ext1: 1038106099296 1099090833    0    0 467554     0          0    401301 543052535442 844810749    0    0    0     0       0          0

I'm inclined to believe that there actually were overrun packets on the interface, so it appears that the output of ip link is not correct. Is there anything I am missing?
Answer: fifo and overrun are not the same. Just type ip -s -s a, there would be something like this
RX: bytes  packets  errors  dropped overrun mcast
53152      864      0       0       0       0
RX errors: length   crc     frame   fifo    missed
           0        0       0       0       0
TX: bytes  packets  errors  dropped carrier collsns
53152      864      0       0       0       0
TX errors: aborted  fifo   window heartbeat transns
           0        0       0       0       0

overrun — the total number of receiver overruns resulting in dropped packets.
As a rule, if the interface is overrun, it means serious problems in the kernel or
that your machine is too slow for this interface.
fifo (file input file output) errors
Comment: Can you also explain the different meaning?
Comment: You can read about it there http://homepage.smc.edu/morgan_david/cs70/ip-cref.pdf
Comment: Thanks! I think I got confused between the two because `netstat -i` actually shows the FIFO count as `RX-OVR`.


How to convert raw json from a url to json or csv?

Question: I have a URL that is providing me with raw json-based data, and I am having some trouble importing that raw text as a json file, or even converting it to a csv.
I have tried using urllib3 and BeautifulSoup to import that data, and store it as a soup object. What I am not able to do is store that data as json and csv (I need both).
One of the issues I believe is causing this problem is the presence of a line at the top of the page describing the results returned, but is not technically part of the json data:
Code at the top that may be causing the issue:
{
"response":{"numFound":1161,"start":0,"docs":[
  {
    "applicationType":"UTILITY",
    "documentId":"US10010749B2",
    "applicationNumber":"US14422067",

Libraries I am using:
import urllib3
from bs4 import BeautifulSoup
import json

Some Code:
url = "https://developer.uspto.gov/ibd-api/v1/patent/application?assignee=alexander&start=0&rows=5"
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data, "html.parser")

print(soup)

json_data = json.load(url)
print(json_data)

AttributeError: 'str' object has no attribute 'read'

My ultimate goal is to be able to "organize and download" all the data from the url and store them in json and csv formats.
Answer: First, your code is mostly correct:
import urllib3
from bs4 import BeautifulSoup
import json
import pandas as pd

url = "https://developer.uspto.gov/ibd-api/v1/patent/application?assignee=alexander&start=0&rows=5"
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data, "html.parser")

json_data = json.loads(soup.text)
print(json_data)

Having the right json data, you can import it into a panda dataframe and then export it to csv:
df = pd.DataFrame(json_data['response']['docs'])
df.to_csv('my_csv.csv', index=False)

EDIT
Added code for exporting to csv
Comment: Thanks Sebastien. The issue is still that first line being treated as part of the file. I am trying to get rid of:
{
  "response":{"numFound":1161,"start":0,"docs":[

...as well as the "}" at the end.
Comment: you want to save each doc as a line in your csv file ?
Comment: Yes, where each column is one of the attributes above, and each line is a different patent document
Comment: do you need `numFound` attribute?
Comment: Nope, just the results themselves
Comment: Thanks Sebastien! I appreciate it!
Answer: You seem to have mistaken how to load JSON using json.load. A simple fix is shown below.
if response.code == 200:
     json_data = json.load(response.data)
     print(json_data)

This returns the data in a dictionary format. You can then convert it to a CSV file. Here is some sample code for that:
with open('test.csv', 'w') as f:
for key in json_data.keys():
    f.write("%s,%s\n"%(key, json_data[key]))

Comment: You can get the individual documents by then iterating over `json_data['response']['docs']`
Comment: @Vaibhav Bajaj Thanks. Can you explain what the "response.code == 200" means?
Comment: @TomNash Thanks. Do you mean to iterate for the purposes of converting that to a CSV?
Comment: @alkhalifas response.code == 200 checks if your HTTP request succeeded. 200 is the code for a Success, like 404 is for Page Not Found.


Difference-in-Difference with two control groups and one treatment group over the same period of time using RStudio

Question: So I'm trying to run a regression for one of my economics classes with one treatment group and two control groups over a period of time. I'm currently trying to create a dummy (binary) variable to account for the fixed effects, but the dependent variable that I'm trying to calculate is also a dummy (binary variable). When trying to create the dummy variable one of my treatment groups is unaccounted for due to perfect multicollinearity. Here's my code for trying to create the dummy variable if it helps. Any help would be greatly appreciated. I am by no means an expert when using R, so if you need some further clarification feel free to ask.
Edit: DH is the binary variable stating whether or not the country received the treatment. I'm pretty sure that is where the error is occurring because the two control groups both have values of 0.
dummyvar = lm(GDP ~ DH + factor(Year) + factor(Country), data = datar)
summary(dummyvar)

Comment: Welcome. It appears the fixed effects absorb your treatment variable. It could just be a coding issue. When does treatment start? Your policy variable should 'switch on' for treated units *and* only in the periods when treatment is actually in effect. Could you provide more detail?
Comment: Hello Thomas, thank you for replying. I've done some more research pertaining to my question, and I've concluded that the model above cannot be used due to the fact that my variable of interest is a binary variable. My question now is how one account for time fixed effects and state fixed effects does when the variable of interest is time-invariant?
Comment: The effect occurs in 2004 which is treated as a "breakpoint" year and is not included in the regression.  My regression I'm trying to run is of the form: realGDP~treatment. Basically I'm trying to determine the effect of the treatment on GDP.
Comment: Please help me understand something. I see you indicated that you're working with a limited **dependent** variable, but the left-hand side of your equation is annual GDP. Are you referring to the dichotomous treatment variable or the outcome?
Answer:
I'm currently trying to create a dummy (binary) variable to account for the fixed effects, but the dependent variable that I'm trying to calculate is also a dummy (binary variable).

I am not sure whether you're referring to the policy variable or the country fixed effects, or both. The country "dummies" (plural) represent country fixed effects, while the year "dummies" (plural) represent year fixed effects. The treatment "dummy" (singular) should be one variable representing when treatment 'turns on' (i.e., switches from 0 to 1) in treated countries. In other words, HR equals 1 for treated countries and only in their post-treatment years, 0 otherwise. The equation you're considering allows for almost any treatment pattern. For example, the onset of treatment is allowed to start at different times in different countries; treatment is even allowed to reverse, meaning that the treatment variable may 'turn off' (i.e., switch from 1 back to 0) within countries after a brief exposure period. I would pay close attention to the treatment variation within countries over time.

When trying to create the dummy variable one of my treatment groups is unaccounted for due to perfect multicollinearity.

You didn't really show us "how" you coded the policy variable. Instead, all you've showed us is the equation you estimated in R. Let's first consider what you're estimating:
$$
\text{GDP}_{it} = \delta\text{DH}_{it} + \alpha_i + \lambda_t + u_{it},
$$
where you observe $\text{GDP}$ in country $i$ in year $t$. The parameters $\alpha_i$ and $\lambda_t$ denote fixed effects for countries and years, respectively. The policy variable $\text{DH}_{it}$ is the primary variable of interest. It should equal 1 in only those country-year combinations where the policy is in effect, 0 otherwise.
Now you indicated that software is dropping $\text{DH}_{it}$, which shouldn't be the case assuming you observe countries before and after the policy and you acquired control group. I suspect the country fixed effects fully absorb your treatment variable, which suggests it's a time-invariant regressor. The country fixed effects already account for time-constant factors, which include a country's membership to the treatment group. Again, your treatment variable should switch from 0 to 1 in only those country-year pairs where the treatment in effect, 0 otherwise.
On the other hand, assuming the policy goes into effect at the same time in all countries, then it's also possible that your treatment variable is being absorbed by the time fixed effects. This would happen in settings where all countries experience the same shock/exposure and in precisely the same year. I find this scenario less plausible, as you already indicated that you have a subset of countries never exposed to treatment. To avoid this issue, ensure $\text{DH}_{it}$ is equal to unity in treated countries and in their post-treatment periods, 0 otherwise. Note how "0 otherwise" means $\text{DH}_{it}$ is equal to 0 in the years before the policy in treated countries, and 0 in all years in control countries.


read only property for checkbox

Question: Is there a read only property for a checkbox?
Because I can still tick on the checkbox even if I have this code, is the read only property only for text box? What's the code if you want the check box to be read-only?
<input name="stats1" type="checkbox" id="SSS" readonly="readonly" value="<?php echo $row["STAT"]; ?>" <?php echo $row["STAT"] ? 'checked="checked"' : ''; ?> >SSS

Answer: The readonly attribute on HTML input elements actually means that the value is readonly.
You actually want to make a checkbox uncheckable, in that case grab Javascript:
<input type="checkbox" onclick="return false;">

Comment: True, that also applies on `readonly` attribute. One can always disable it using JS or tamper the request parameters. Always, always, always check at serverside, regardless of the input flavor.
Comment: Since js is ultimately unreliable, though, make sure you check on the backend.
Answer: Try disabled="disabled" instead ;)
Comment: That works, but this way the value won't be sent to the server anymore. That's the difference with `readonly`.
Comment: It would matter in for example requestbased confirmation screens or previews.
Comment: You can avoid that problem by creating a hidden INPUT that represents the value that you want sent back to the server.
Answer: here i have inserted 7 checkboxes and set their name as c1,c2....c7 in the html page
<input type="checkbox" name="c1" value="english" />
 <input type="checkbox" name="c2" value="hindi" />
 <input type="checkbox" name="c3" value="gujarati" />
 .
 .
 .
 <input type="checkbox" name="c7" value="Marathi" />

 here we will use for loop with upto 7 times iteration

  for($i=1;$i<=7;$i++)
{
    echo $_GET['c'.$i] ."
";
}

here 'echo' statement will print values from gettig name of checkboxes c1 ...c7

Here $_GET['c'.$i] will print only its value if that checkboox is checked

read only property for checkbox


How to Increase left hand speed?

Question: My left hand speed isn't good enough to do fast hammer on pull offs or similar stuff. I want to learn some basic iron maiden solos and go from there but I simply can't get the hammer pull offs right. My friends who play tell me to practice with a metronome but that never improves my speed. Whenever I increase the tempo a bit too high I struggle. What are some good ways to get hang of it?
Comment: I appreciate this question. I'm pretty old school music wise and recently revisit d the licks from the old Chicago song 25 or 6 to 4. This solo is pretty fast, around 148, and it was a good reminder of how fast you can string riffs together by rapidly hammering on and pulling off, mostly with just the ring finger. Sadly it also showed me how limited is my endurance, making me realize its not just speed, but the ability to keep it going like a machine. I'm sure  the only way I'll progress toward both speed AND endurance is by putting in the practice hours with that metranome.
Answer: Play it slow but correct and then speed up. Try to play it perfectly, as slow as you need it to be. It's better to be able to play it slowly and well then to play it fast and sloppy.
Your friends are right, a metronome can help. First, set it to a speed at which you can comfortably play it. From there on, put it a bit faster each time. The song is at 120 bpm? And you can play it at 80 bpm? Try it at 85 or 90. And up it once you're comfortable at that speed. Don't just go from 80 bpm to 120, it won't work.
Answer: Chromatic finger exercises with a metronome will help if your fingers are really weak. This is where you play 4 notes on each string from low (low e) to high (high e), and then back up again to low e. One finger on each fret, and when you have done all 6 strings, you start by moving one note up and do the exercise in the next position. (for example, you would start on the f note of the low e string, play f#, g, G#, g, f#, f, and then move down to the a string, play a#, b, c, c#, etc.)
"Play it slow but correct and then speed up"
As Carra said, the key is really to play as slowly as necessary to play it correctly and get a LITTLE faster each time, because THIS is where you will strengthen your fingers and develop the timing necessary to play it at the correct speed. There is no quick way to do this.
I would also like to add that it is important to ensure your hand is in the correct position while you are practicing.
Make sure you are practicing correctly, and you will save lots of frustration. Progress can be slow but just make sure that you are progressing and you will get there.
Remember if you are practicing poorly, you are essentially practicing mistakes, which could cause you years of frustration.
Comment: are you talking about starting with index, then hammering on with middle, then hammer on with ring, then with little finger, then pull off with little, then ring, etc? It's a good exercise, but very difficult. If you're doing that, start around fret 9/10, and go TOWARDS the headstock by one fret each time - the frets get wider, so it gets more tricky.
Comment: Incidentally with long fingers I found it easier on the lower frets to start off with, and started there from day one, but you make a good point, it may be easier for some higher up.
Answer: according to my personal experience:

Be patient , it may take for years to reach your ideal speed .
play every day ,seems exaggerating ! it's better to play half an hour a day but every day than to play 7 hours but 4 day per week. if you don't have practice schedule make one as soon as possible.
warm up before start practicing, it strengthens your fingers and helps you play more fluently and efficiently.
play with metronome , set the metronome tempo a little slower than to what you feel comfortable with, then very very slowly speed up , you will reach to the ceiling of your playing tempo that can not speed up no more , now it's time to leave your instrument for 10 minutes , then come back again and start practicing with little slower tempo of your maximum speed.Amazing! after a while you've improved your maximum speed.
play notes in scale and practice rock cliches, it improves your muscle memory and improvising skills.
many songs have repetitive pattern you've practiced .
start covering with simpler songs such as wasting love (1992, Fear Of The Dark-iron maiden) and keep on.
follow your hero ,preferably John Petrucci :)
Answer: Practice the left hand more.  It's as simple as that really.
One of the big problems with piano is that you make some sort of breakthrough with the right hand and the left hand can't keep up.  Then it's easy to get discouraged.  But your left hand will make progress too.  Just don't keep letting your right hand tell your left how deficient it is, if you take my meaning.
I've talked to famous concert pianists who say that they spend three or four times as much time on their left hand as their right, so you're not alone.  Persevere.  Work with the left hand alone.
Also, when you've gotten as far as you can at any point, walk away for a while.  When you come back to it, you'll be surprised to see that it has improved, apparently without any further work.  Think of it like this.  You're trying to lift weights.  You go until you're tired.  You can't keep going past a certain point.  You quit.  When you come back, you can lift more.  It works the same way with your hands.  Keep that in mind.  That's worth repeating: keep that in mind.
Comment: the OP is asking about fretting hand work on a guitar. It's quite different, although the principle of practice is similar.
Comment: Oops!  Thanks for the correction.  There's a "fast hammer" in blues piano as well, having to do with hitting the blue note and the note a half step up quickly, although come to think of it it's rare in the left hand.  A good example that comes to mind is Otis Spann's improv on Muddy Waters's rendition of "Five Long Years".

How to Increase left hand speed?


How to get string as sequence of UTF-8 codes

Question: How to encode String to something like \u0412\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0435?
I tried Sting newString = new String(oldString.getBytes("UTF-8"),"UTF-8"); but it just return string I already have
Comment: it's not UTF-8 but unicode
Comment: Here's an [example](http://www.java2s.com/Tutorial/Java/0120__Development/Convertsthestringtotheunicodeformat.htm) which you can get by searching in [Google](http://www.google.com) like [parse string to unicode](https://www.google.com.mx/search?client=ubuntu&channel=fs&q=parse+string+to+unicode&ie=utf-8&oe=utf-8&gfe_rd=cr&ei=JlD-U6LzI-aS2AXCj4GIBQ#channel=fs&q=parse+string+to+unicode+java)
Comment: Your example doesn't look like it has anything to do with UTF-8.
Answer: Consider using StringEscapeUtils.escapeJava from apache-commons
Demo:
System.out.println(StringEscapeUtils.escapeJava("Введенные"));

prints:
\u0412\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0435

Answer: There is also classic way that is putting escape characters before '\'.
  String oldString= "\\u0412\\u0432\\u0435\\u0434\\u0435\\u043d\\u043d\\u044b\\u0435";
  System.out.println(oldString);

output :
\u0412\u0432\u0435\u0434\u0435\u043d\u043d\u044b\u0435


Are substitutions allowed in curling?

Question: Most curling teams has an alternate players.
Are the substitutions allowed during a match?
I mean in those cases:

injury of a player
technical choice
Answer: Teams may substitute a player for injury, but not for technical choice.
R3 (d) clearly allows for a "qualified alternate" in the case of "a player being unable to continue, and details what will occur.

Where  a  player  is  unable  to  continue  to  play  in  a  game,  the  team  may either:
...
(ii)  bring  in  a  qualified  alternate  at  the  beginning  of  an  end,  in  which case  the  delivery  rotation  and  the  skip  and  vice-skip  positions  may be  changed  (the  revised  rotation  of  play  applying  for  the remainder  of  that  game),  and  the  replaced  player  may  not  reenter  the  game.

R3 (f) further limits the number of alternates to one (1) per team, or none of competition does not allow it.

Are substitutions allowed in curling?


Convert date string to MM DD in react - not vanilla JS

Question: I understand how to do this outside of react. I have a date string that is returned from API in an object. I need to reformat it so instead of "2022-12-13T06:00Z" it would read "December 13". The object holds utcStart as "2022-12-13T06:00Z". Currently the below displays as "2022-12-13T06:00Z"
const eventDates = useRecoilValue(eventDatesState);
return (
    <Grid item xs={12}>
        eventDates.map (data =>(
            <ListItem>
                {eventDates.utcStart}
            </ListItem>
        ))
    </Grid>
)

Since it is in a map function, I don't know how to do this for each one.This doesn't work
{new Date(calendarContent.utcStart)}

Comment: it's all just vanilla JS so long as you embed it correctly in the JSX
Comment: Then you aren't putting out a string, so possibly read through the duplicate. `toLocaleDateString()` outputs a string while your example is just trying to render a complete Date object.
Comment: I think you're just forgetting the brackets.

instead of

```jsx
eventDates.map (data =>(
...
))
```

You could do

```jsx
eventDates.map(data => {
   [JS logic where you convert the date and create a variable for each item here]
   return (
      [JSX components with the variable declared above here]
   )
}
```
Comment: @pilchard - no, if it was just in vanilla JS I'd be done. But I get several "react-dom.development.js:14887 Uncaught Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead." errors using react
Comment: It probably is formatting Im having issue with, but just doesn't work for me inside the map.
Comment: Have you tried the curly brackets? You can do Vanilla JS before returning a JSX (React) component.

You can use the code to convert the data after the curly bracket and declare a variable to store the result. Then you can do `return ()`  with the JSX inside the parenthesis. On the JSX you can instantiate the variable with the date.

I'll create an answer to exemplify what I'm saying here.
Answer: You can do something like this:

var date = new Date('2022-12-13T06:00Z');

// Use the options object to specify the desired format
var options = { month: 'long', day: 'numeric' };
var formattedDate = date.toLocaleDateString('en-US', options);

console.log(formattedDate);
// OUTPUT
// December 13

Here's how to do this in React
export default function MyComponent() {
  var date = new Date('2022-12-13T06:00Z');

  // Use the options object to specify the desired format
  var options = { month: 'long', day: 'numeric' };
  var formattedDate = date.toLocaleDateString('en-US', options);

  return (
    {formattedDate }
  )

}

Comment: I updated my answer on how to use it in React. It should work, but I don't have all the details about how it doesn't it work for you
Comment: maybe accept `date` as a prop instead of as a static variable in the component, might be clearer for the OP.
Answer: Example using the answer above:
export default function GridWithFormattedDates() {
    const eventDates = useRecoilValue(eventDatesState);
    return (
        <Grid item xs={12}>
            {eventDates.map(eventDate => {
                const date = new Date(eventDate.utcStart);

                const options = { month: 'long', day: 'numeric' };
                const formattedDate = date.toLocaleDateString('en-US', options);
                return (
                    <ListItem>
                        {formattedDate}
                    </ListItem>
                );
            })}
        </Grid>
    );
}


Eclipse refactoring: move method inside collaborator

Question: I have the following scenario:
public class Controller {

  private ModelRepository repository;

  public int getModelCount() {
    int count = 0;
    List<Model> models = repository.getModels();

    for (Model model : models) {
      if (model.somePredicate()) {
        count++;
      }
    }

    return count;
  }
}

Now, I'd like to move the getModelCount method inside ModelRepository by using some automated Eclipse refactoring so that I end up with this in the controller:
public class Controller {

  private ModelRepository repository;

  public int getModelCount() {
    repository.getModelCount();
  }
}

Is this possible in Eclipse Indigo? If yes, how? Thanks!
Answer: I don't think there is a single-hop refactor, but you can do it in two.
First, highlight the contents of the getModelCount() method and do a refactor->extract method, calling the new method something like countModels.
Secondly, do a refactor->move on the new countModels() method, selecting the repository field as the destination.
This will leave you with a method on the ModelRepository called countModels rather than getModelCount. For completeness you could do a refactor->rename on this, but I prefer countModels anyway.
Comment: Thanks for your answer. It seems the `refactor->move` operation works directly on that method. My problem was that the type of the `repository` field was an interface, instead of a class. That's why Eclipse had problems moving it.


Python 3.6 ~ AttributeError: module 'servicemanager' has no attribute 'Initialize' ~ When creating windows service exe

Question: When using any version of servicemanager with Python 3.6.6 I get AttributeError: module 'servicemanager' has no attribute 'Initialize'*
Code Snippet:
if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(RelayService3)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(RelayService3)

This seems to be the standard main function of any windows service written in python.
Any help would be greatly appreciated!
Answer: I think install servicemanager for error:
\Python38-32\Scripts\pip3 uninstall servicemanager

After it works.
Comment: It looks like pywin32 provides servicemanager, and installing the standalone library conflicts with that version.  Uninstalling servicemanager 2.0.10 worked for me.


Sphinx adding a link to an image or a figure

Question: I am trying something rather basic in Sphinx. I have some images, but I prefer to keep them pretty small, and I want to allow the user to click on them to get the larger image.
I do not find a syntactic way to combine image: or figure: with ref: or link:.
.. image:: _static/my_image_small.png

and I have in the same folder my_image_large.png.
If you come up with a solution, should the larger image just be a file with an explicit link to it or do I create a reSt file with an additional image: tag?
An alternative could be to play with the image sizes in the reSt file, but then I still do not know how to create the link from the small image to the large image.
Thank you for helping me.
Answer: Just use the target directive. You would end up with something like:
.. image:: _static/my_image_small.png
   :target: _static/my_image_large.png

It is not strictly necessary to use the references to the static folder in your source. They will be copied to the _images folder anyway when you build the docs (so you will have them twice in your builds, without needing them there).
I always use a folder called figures next to the source folder where I manage the images. The my_image_large.png files, however, you would want to place in the _static folder as the contents will be copied on build.


Parallelizing codes for efficiency in R

Question: I am trying a variable screening using the SIS package in R using different tunings and penalties. I have for loops which will take long for relatively large data. I am trying to parallelize this piece of code for efficiency. But I am running into some errors.
Please kindly help if you can. Thanks for your time and help.
#load library
library(parallel)
library(doParallel)
library(foreach)
library(SIS)
library(dplyr)
data('leukemia.train', package = 'SIS') #data for practice
y.train = leukemia.train[,dim(leukemia.train)[2]]
x.train = as.matrix(leukemia.train[,-dim(leukemia.train)[2]])
x.train = standardize(x.train)
#penalties for screening
penalty <- c("lasso", "SCAD", "MCP")
#storeage
RESULT <- NULL
alldat <- NULL
for(pen in penalty){
  #tuning para
  tune  <- c("aic", "bic", "ebic", "cv")
#storage
  OUT <- NULL
  dat <- NULL
  for(tun in tune){
#SIS model for ultra-high dimensional screening
    mod=SIS(x = x.train, y = y.train, family = 'binomial',
            penalty = pen, tune = tun, varISIS = 'aggr', seed = 21)  #model
    out <- mod$ix
    coff <- mod$coef.est
    x <- x.train %>% as.data.frame()
    dat0 <- x[c(out)]
    if(dim(dat0)[2] >= 1) attr(coff, "names")[-1] <- c(colnames(dat0))
    df1 <- coff %>% as.data.frame()
    OUT[[tun]] <- cbind(CpG = rownames(df1), data.frame(coef = df1[, 1], row.names = NULL))
    names(OUT[tun]) <- paste(tun)
    dat[[tun]] <- dat0
     #store as list for cases
    names(dat[tun]) <- paste(tun)
    }
#list of all results of coef
  RESULT[[pen]] <- OUT
dat #list of data sets
  alldat[[pen]] <-
  names(RESULT[pen]) <- paste(pen)
  names(alldat[pen]) <- paste(pen)
}

#parallelize here
pentune.df <- expand.grid(
  tune  = c("aic", "bic", "ebic", "cv"),
  penalty = c("lasso", "SCAD", "MCP")
)# use expand for to obtain possible combinations

#create and register cluster
n.cores <- parallel::detectCores() - 2
my.cluster <- parallel::makeCluster(n.cores)
doParallel::registerDoParallel(cl = my.cluster)
foreach(
  tun = pentune.df$tun,
  pena = pentune.df$pena,
  .combine = 'list',
  .packages = "SIS"
) %dopar% {

  #fit model
  mod <- SIS(x = x.train, y = y.train, family = 'binomial',
          penalty = pena, tune = tun, varISIS = 'aggr', seed = 21)
  out <- mod$ix
  coff <- mod$coef.est
  x <- as.data.frame(x.train)
  dat0 <- x[c(out)]
  if(dim(dat0)[2] >= 1) attr(coff, "names")[-1] <- c(colnames(dat0))
  df1 <- as.data.frame(coff)
  OUT <- return(cbind(CpG = rownames(df1), data.frame(coef = df1[, 1], row.names = NULL)))
  }
parallel::stopCluster(cl = my.cluster) #end job

Answer: normally it is best if you can narrow in on the error that you are getting it makes it easier to help. The main issue seemed to be simplifying your iterator within the foreach and ensuring the penalty and tune variables for SIS
are character. The expand.grid function is exactly what you need but the resulting columns are factors. So these need to be converted back when inserting into the SIS function.
Finally, in your last line of the %dopar% {} don't define a variable and you don't need to return. The last object returns automatically. So you can remove OUT <- return().
I have added some comments in the code below to indicate exactly what I have changed.
foreach(
  i = 1:nrow(pentune.df), # define a simpler iterator
  .combine = 'list',
  .packages = "SIS"
) %dopar% {

  # define loop variables and ensure they are character
  pena <- as.character(pentune.df[i, 'penalty'])
  tun <- as.character(pentune.df[i, 'tune'])

  #fit model
  mod <- SIS(x = x.train, y = y.train, family = 'binomial',
             penalty = pena, tune = tun, varISIS = 'aggr', seed = 21)
  out <- mod$ix
  coff <- mod$coef.est
  x <- as.data.frame(x.train)
  dat0 <- x[c(out)]
  if(dim(dat0)[2] >= 1) attr(coff, "names")[-1] <- c(colnames(dat0))
  df1 <- as.data.frame(coff)

  # don't define a variable here just create the object you want
  cbind(CpG = rownames(df1), data.frame(coef = df1[, 1], row.names = NULL))
}

Comment: the easiest might be to just add them as columns in the last line where you use `cbind`. Otherwise you could use `purrr::set_names`. something like `foreach() %dopar% {} |> set_names(paste(pentune.df$tune, pentune.df$penalty))`. this last would add the combo to each list element
Comment: Is there a way to get names for the list based on the expand grid pairs ? For e.g.,  1st set of run based on the expand grid aic vs lasso, aic vs SCAD, etc.

Parallelizing codes for efficiency in R


Change login screen behavior to ignore Enter key?

Question: We are running a Windows domain environment with many PCs that are running Windows XP. Users log on to the PCs with their domain user.
Many users attempt to login, enter their username but then hit Enter to try and move down to the password field. This submits a login process and results in an error saying invalid login (due to no password entered) and ends up with many support calls in about this constantly (we train our users, but it does not always stick).
Is there a way to have something (like Group Policy rules) roll out a change to either disable the Enter key in this situation, or have it act like the Tab key?
Comment: This is a user training issue: You need a bigger bat.
Comment: Sadly we use other major software here where the `Enter` key does move down to the next field, and training is never going to stick when they do both daily.
Comment: This is not an expected behavior, though--enter means submit in most applications, as well as on the web forms.  This is something they use (hopefully) several times a day, and is not all that difficult to comprehend.
Comment: Unfortunately there are still many major applications that still use the `Enter` key as `Return` (even on login screens), thus acting like a `Carriage Return`. We happen to use one and users login to that more than Windows itself.
Answer: There is no built in method (Group Policy or otherwise) that will let you alter the default behavior of the login screen.  You can, however, write your own Graphical Identification and Authentication (GINA) component to replace the default.  Custom GINAs are typically written in unmanaged C++.  This link can help you get started: http://msdn.microsoft.com/en-us/magazine/cc163803.aspx
If you're not down with that, you might want explore an alternative logon method, like smart card authentication.
Sidenote: GINA was replaced in Windows Vista and later with the Credential Provider API: http://msdn.microsoft.com/en-us/magazine/cc163489.aspx


change column names after refreshing JTable java

Question: I dont know why column names are named "A","B","C" ... after refreshing JTable.
I created a class to refresh JTable.
public class TableModelClass extends AbstractTableModel
{
    Object[][] data;
    Object[] title;

public TableModelClass(Object[][] dat, Object[] tit)
{
    data = dat;
    title = tit;
}

@Override
public int getColumnCount()
{
    if(title != null)
        return title.length;
    return 0;
}

@Override
public int getRowCount()
{
    if(data != null)
        return data.length;
    return 0;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
    return data[rowIndex][columnIndex];
}

}
I set JTables values default in my class:
Object[] titlesDefault = { "tit1", "tit12","tit3"};
Object[][] dataDefault = {{ "1", "2","3"},
            {"1", "2","3"}};

       _jTable = new JTable(dataDefault, titlesDefault);

_bAddTable.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
                try
                {
                Object[] titles2 = { "1", "2","3", "1", "2","3"};
                Object[][] data = {{ "1", "2","3"},
                                   { "1", "2","3"},
                       {"1", "2","3"}};
                data.setModel(new TableModelClass(data, titles2));
                }
                catch (ClassNotFoundException)
                {

                    e1.printStackTrace();
                }

         };
        });

And after this I receive letters in column names. Why?
Comment: 1) does that code compile? Your Object[][] variable is not a 2-D array but rather a 1-D array of String. 2) Never use a MouseListener on a JButton when an ActionListener is called for.
Comment: code compiles, so what should I use?
Comment: 1) Your 2-D array should hold a 2-D array. 2) Again, JButtons should use ActionListeners. The tutorial will explain all. I'm no JTable pro, but you may need to use a column model as well.
Comment: I tried to use ActionListener but result was the same
Answer: Without overriding getColumnName, the TableModel uses default values of "A", "B", "C", etc.
@Override
public String getColumnName(int column) {
    return title[column];
}

For this to work you need to return a String so that it corresponds to the return type in the super class. The title variable should be defined as a String[] type.


Humming while practicing a piece - good or bad practice?

Question: As a novice piano player (started with guitar, switched to piano about one year ago), I often catch myself humming along to a piece's tune while playing - is this bad?
The humming is not distracting to myself and my playing, but I have been told that it would be bad practice to get into a habit of it (for possible performances/recitals).
What do you think?
Comment: A post that might be of interest: [Does voice doubling an instrument's melody while improvising have a name?](https://music.stackexchange.com/questions/102218/does-voice-doubling-an-instruments-melody-while-improvising-have-a-name).
Comment: To answer this question we have to know why you play the piano.  I hum while playing whenever I feel like it, and it's not a problem at all for me, nor does it interfere with any of the reasons why I choose to play the piano.
Comment: as long as you hum at the correct pitch I dont see it as an issue. BAss players are often told to sing along quietly - Ed Friedland explicitly states this in his book
Answer: I agree with Tim: it could be a problem in performance, but as long as it's limited to practice it should be fine.
In fact, there's a great historical example of it being troublesome in performance: the  Canadian pianist Glenn Gould was (in?)famous for humming while playing, something only made more uncomfortable by the fact that it was often off-pitch!
Now, you may think "if this guy can do it, why not me?" Well, perhaps so. But keep in mind that Gould was a once-in-a-generation performer and musical thinker, and so the quality and innovations of his performances help us overlook the humming. It's also possible that recording technology at the start of his career helped him become famous before his humming became all that noticeable, but that's just conjecture.
In any event, singing/humming as a practice method can be incredibly helpful as a means of clarifying your interpretation of a melodic line. My personal suggestion would be to do it away from the instrument, and perhaps only occasionally while playing. Because in performance, nerves often result in us doing things we don't intend to do, or doing things that comfort us. Thus you may find yourself getting nervous and humming along without even intending to, which could be problematic.
Answer: It's not problematic to you, and probably helps you keep in time/pitch. But it may be a problem for those you play with - maybe not now, but in the future, when you do.
As long as you do it alone, and can turn it off and on at will - and not let it continue once turned off - it's not bad practice, but could be seen as such by others.
Answer: As Richard indicates in his answer, humming during public or recorded performances is a no-no.
It's probably a bad sign that none of my 3 piano teachers ever recommended humming as a practice strategy - at least one of them recommended listening to other performances of my repertoire instead to know what the notes are (and sight-read or "sight-read" it faster) and get a better idea of what my interpretation should ideally sound like. Note the intense overlap these reasons have with reasons why humming would be a decent practice strategy.
Through these, my piano teachers collectively implied that humming as a practice strategy is not worth it and quite possibly is more harm than it's worth by ingraining the iffy to bad habit of humming during possibly inappropriate moments.
Answer: I wouldn't do it in front of your teacher.  but it definitely won't interfere with your playing, in fact, it might help you keep in time. The famous virtuoso pianist, Glenn Gould, was well known for humming while playing, and his humming would even make it into his recordings!


How to deal with such OutOfMemoryErrors

Question: I'm testing my android App in some devices, and I've noticed a weird behavior in a certain mobile. When I open an Activity (which shows a bitmap) the first time it crashes generating this stack trace:
<code>   java.lang.RuntimeException: Unable to start activity ComponentInfo{example.perifereia_hpeirou/com.epirus.MonumentProjection}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:626)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700)
at android.view.LayoutInflater.inflate(LayoutInflater.java:470)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:361)
at com.actionbarsherlock.internal.ActionBarSherlockNative.setContentView(ActionBarSherlockNative.java:133)
at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:261)
at com.epirus.MonumentProjection.onCreate(MonumentProjection.java:77)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
... 11 more
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
at android.view.LayoutInflater.createView(LayoutInflater.java:600)
... 24 more
Caused by: java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:596)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:832)
at android.content.res.Resources.loadDrawable(Resources.java:2988)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.view.View.<init>(View.java:3563)
at android.view.View.<init>(View.java:3492)
at android.view.ViewGroup.<init>(ViewGroup.java:469)
at android.widget.RelativeLayout.<init>(RelativeLayout.java:242)
... 27 more
</code>
However, if I try to open the activity again this doesn't happen.Also this doesn't occur in any other devices I've tested. I guess the mobile doesn't have enough ram atm and this exception helps it clean memory but this is just my guess.What can I do in order to overcome such a problem?
Comment: Well at least you could catch the exception so the activity does not crash. Load it by code instead through xml. How big is that image?
Comment: it's 1024x1024, I'm loading it by code..
Comment: Are you resizing it? There is also an InflateException. Why?
Comment: Try to add "android:largeHeap" to the application tag in the AndroidManifest.xml. This will allocate a large heap space for your application if the device is capable of doing that. But this is only a quick solution. You should implement a proper memory management system for dealing with bitmaps. I had similar issues in my Android project as well.
Comment: Yes but this is a problem of the OS right? since it works correctly after It crashes the first time or if I clean the memory before I launch the application
Answer: some ideas you can try:
a) Try with a small image to see if it is due to the size of the bitmap.
b) The first cause you have states:
<code>Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
</code>
I would also check if the class you are using here is supported by that particular device.
For example I remember an application I developed crashing with devices that weren't google certified because I assumed all devices would have google maps and this is not the case.
I had to add a runtime check before instanciating the object.

How to deal with such OutOfMemoryErrors


QueryBuilder TypeORM

Question: No meu sistema de gestão patrimonial eu tenho as seguintes tabelas:
patrimonios: Os bens patrimoniais.
patrimonios_cedidos: A cedência, a lista dos patrimônios cedidos/emprestados.
patrimonios_cedidos_itens: Tabela intermediária, que vai registrar o estado de cada patrimônio ao ser emprestado.
Como eu faria para criar uma query utilizando o QueryBuilder da seguinte requisição em PostgreSQL:
select * from patrimoniodb.patrimonios
where id in (
    select patrimonio_id from patrimoniodb.patrimonios_cedidos_itens
    where patrimonio_cedido_id = 1
)

Estou utilizando TypeScript (não sei se tem alguma diferença para o JS), e caso for necessário os campos da tabela ou algo mais, basta me informar que eu edito o post.
Answer: O nome da propriedade que você precisa usar nessa consulta se chama subquery. É possível criar essa query de duas maneiras (Usando o TypeORM):
const qb = await getRepository(Patrimonios).createQueryBuilder("patrimonios");
const patrimonios = qb
    .where("patrimonios.id IN " + qb.subQuery().select("patrimonios_cedidos_itens.id").from(PatrimoniosCedidosItens, "patrimonios_cedidos_itens").where("patrimonios_cedidos_itens.patrimonio_cedido_id = :patrimonio_cedido_id").getQuery())
    .setParameter("patrimonio_cedido_id", 1)
    .getMany();

Ou de uma maneira mais sofisticada:
const patrimonios = await connection.getRepository(Patrimonios)
    .createQueryBuilder("patrimonios")
    .where(qb => {
        const subQuery = qb.subQuery()
            .select("patrimonios_cedidos_itens.id")
            .from(PatrimoniosCedidosItens, "patrimonios_cedidos_itens")
            .where("patrimonios_cedidos_itens.patrimonios_cedido_id = :patrimonio_cedido_id")
            .getQuery();
        return "patrimonios.id IN " + subQuery;
    })
    .setParameter("patrimonio_cedido_id", 1)
    .getMany();

Aqui está a referência da resposta (https://typeorm.io/#/select-query-builder/using-subqueries), nesse site você consegue achar outras explicações de como utilizar esse ORM.

Caso queira entender mais sobre essa propriedade subquery, basta acessar o link https://imasters.com.br/back-end/como-fazer-subconsultas-um-passo-passo

QueryBuilder TypeORM


MySQL error: cannot add foreign key constraint, but data types match

Question: I'm trying to create tables with foreign keys, but I keep getting error 1215 saying that it cannot add foreign key constraint. I double checked the datatypes and the REFERENCES part of the constraint, and that seems to be in order. I added ENGINE=InnoDB after reading through some of the MySQL documentation for the error, and that didn't solve it. I'm new to creating new databases, so I think I'm missing something. What can I add to resolve this error?
CREATE DATABASE cemc;
USE cemc;

CREATE TABLE CALENDAR(
    year            INT                 NOT NULL,
    term            VARCHAR(25)         NOT NULL,
    term_start      DATE                NOT NULL,
    term_end        date                NOT NULL,

    CONSTRAINT      CALENDAR_PK         PRIMARY KEY(year, term)
)ENGINE=InnoDB;

CREATE TABLE COURSE(
    course_id       VARCHAR(6)          NOT NULL,
    skill           VARCHAR(25)         NOT NULL,
    level           VARCHAR(25)         NOT NULL,

    CONSTRAINT      COURSE_PK           PRIMARY KEY(course_id)
)ENGINE=InnoDB;

CREATE TABLE TEACHER(
    teacher_id      VARCHAR(50)         NOT NULL,
    teacher_last    VARCHAR(25)         NOT NULL,
    teacher_first   VARCHAR(25)         NOT NULL,
    email1          VARCHAR(50)         NOT NULL,
    email2          VARCHAR(50)         NULL,
    phone1          INT                 NOT NULL,
    phone2          INT                 NULL,

    CONSTRAINT      TEACHER_PK          PRIMARY KEY(teacher_id)
)ENGINE=InnoDB;

CREATE TABLE COURSEASSIGNMENT(
    course_id       VARCHAR(6)          NOT NULL,
    year            INT                 NOT NULL,
    term            VARCHAR(25)         NOT NULL,
    teacher_id      VARCHAR(50)         NULL,
    room            VARCHAR(3)          NULL,

    CONSTRAINT      COURSEA_PK          PRIMARY KEY(course_id, term),
    CONSTRAINT      COURSEA_FK1         FOREIGN KEY(term)
                                        REFERENCES CALENDAR(term),
    CONSTRAINT      COURSEA_FK2         FOREIGN KEY(course_id)
                                        REFERENCES COURSE(course_id),
    CONSTRAINT      COURSEA_FK3         FOREIGN KEY(year)
                                        REFERENCES CALENDAR(year),
    CONSTRAINT      COURSEA_FK4         FOREIGN KEY(teacher_id)
                                        REFERENCES TEACHER(teacher_id)
)ENGINE=InnoDB;

Answer: The problem is that you try to reference Calendar. So far you are doing it correct with the data types. BUT  Calendar has a combined primary key. Thus you need to define the foreign key in one go instead of both separated, as mysql interprets these 2 as SEPARATE foreign keys instead of a combined one. And that leads to it not able to create the foreign key.
Thus you need to do:
CONSTRAINT      COURSEA_PK          PRIMARY KEY(course_id, term),
CONSTRAINT      COURSEA_FK1         FOREIGN KEY(year, term)
                                    REFERENCES CALENDAR(year, term),
CONSTRAINT      COURSEA_FK2         FOREIGN KEY(course_id)
                                    REFERENCES COURSE(course_id),
CONSTRAINT      COURSEA_FK4         FOREIGN KEY(teacher_id)
                                    REFERENCES TEACHER(teacher_id)

Comment: Can happen. Saw it a few times in the last few days. And that is one of the reasons why I tend to avoid combined keys where possible. Btw if an answer helps (solves a question) then pls set it as approved answer.
Answer: A foreign key must reference a primary key in the foreign table:
CONSTRAINT      COURSEA_FK1         FOREIGN KEY(term) REFERENCES CALENDAR(term)

And term is not the PK of table Calendar. The correct form should be:
CONSTRAINT      COURSEA_FK1         FOREIGN KEY(year,term) REFERENCES CALENDAR(year,term)