Mysterious SQLiteBindOrColumnOutOfRangeException in Android.

Question: So I've been working on setting up an SQL Databse of words, which as far as I can tell from debug logs, actually does load and set up properly.  However, when I try to query it, regardless of whether it is in the process of set-up or already done, my program is forced closed because of an exception.  Investigation of the log reveals this:
07-12 13:47:02.000: W/dalvikvm(5247): threadid=1: thread exiting with uncaught exception
(group=0x40a401f8)
...
07-12 13:47:02.010: E/AndroidRuntime(5247): Caused by:
android.database.sqlite.SQLiteBindOrColumnIndexOutOfRangeException: bind or column index out of
range: handle 0x14a6548
...
07-12 14:41:36.250: E/AndroidRuntime(6326):     at com.example.wordsearchandroid.WordListProvider.query(WordListProvider.java:70)

A search of SQLiteBindOrColumnIndexOutOfRangeException on the Android API reveals a fairly... spartan page (http://developer.android.com/reference/android/database/sqlite/SQLiteBindOrColumnIndexOutOfRangeException.html) that mentions nothing of what the "handle" refers to.
Unfortunately, as far as I can tell, nothing in my queries is referring to non-existent columns.  This is my query method in my ContentProvider:
public class WordListProvider extends ContentProvider {
private WordListOpenHelper listOpenHelper;
....

public static final String ID = "_ID";
public static final String WORD = "WORD";
public static final String LENGTH = "LENGTH";
...

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
    qBuilder.setTables(DB_NAME);
    Cursor c;

    switch(matcher.match(uri)) {

        case SEARCH_WORD_LIST:

            Log.d("WORDLISTPROVIDER", "Entered Search");
            c = qBuilder.query(listOpenHelper.getReadableDatabase(), projection, null,
                    selectionArgs, null, null, null);
            Log.d("WORDLISTPROVIDER", "Query Completed");
            if (c == null)
                return null;
            c.setNotificationUri(getContext().getContentResolver(), uri);
            break;

            default:
                Log.d("WORDLISTPROVIDER", "Default Entered");
                throw new IllegalArgumentException("Unknown URI " + uri);

    }
    Log.d("WORDLISTPROVIDER", "Exited Search");
    return c;
}

^The exception occurs at the line
c = qBuilder.query(listOpenHelper.getReadableDatabase(), projection, null,
                    selectionArgs, null, null, null);

For reference, here is how the projection and selectionArgs strings for this particular call are set:
String[] proj = {
            WordListProvider.ID,
            WordListProvider.WORD
    };
String[] selectionArgs = {""};

And here is the builder for my database, which is an inner class in WordListProvider:
private static class WordListOpenHelper extends SQLiteOpenHelper {

    private SQLiteDatabase wordDb;
    private Context helperContext;

    private static final String WORD_LIST_CREATE = "CREATE TABLE "+ DB_NAME  +
            " ( " +
             ID +  " INTEGER PRIMARY KEY, " +
             WORD + " TEXT, " +
            LENGTH + " INTEGER " +
            ");";

    WordListOpenHelper(Context context) {
        super(context, "wordlist", null, 1);
        helperContext = context;
        Log.d("OPENHELPER", "Constructed");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d("OPENHELPER", "Creating");
        wordDb = db;
        Log.d("OPENHELPER", "DB set");
        wordDb.execSQL(WORD_LIST_CREATE);
        Log.d("OPENHELPER", "SQL Execed");
        loadWordList();
    }

    private void loadWordList() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    loadWords();
                } catch (IOException e) {
                    Log.d("OPENHELPER", "Exception Caught");
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    private void loadWords() throws IOException {
        ...
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        ...
    }

}

loadWords does finish eventually, but I get the exception whether the table has finished loading or not (sometimes the table will not have finished loading, I'll get the exception, and the program will quit.  The table will then finish loading).  Also, my column names are consistent, at least they outwardly appear to be--and the exception even occurs if I pass a null (aka return all rows) for the projection to the query;  Anyone have any ideas of what could be causing the exception, or what the handle means?
Answer: Please, check this line in your provider:
c = qBuilder.query(listOpenHelper.getReadableDatabase(), projection, null,
                    selectionArgs, null, null, null);

You use selectionArgs without selection parameter. If You pass not null selectionArgs query will fail because there is no place where selection arguments can be bind to.
This line should looks like this:
 c = qBuilder.query(listOpenHelper.getReadableDatabase(), projection, selection,
                        selectionArgs, null, null, null);

You can't use selectionArgs without selection, so try to pass null instead of
String[] selectionArgs = {""};

Comment: Yep that does it.  The API Reference mentions nothing of this and the API guide shows exactly the opposite.  Thank you.
Comment: Thanks, I'm not sure if I understand your question from comment but you can read about accepting questions [here](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)
Comment: I'm referring to the fact that I've accepted the answer but there's still an "unanswered" tag to it.


Rhythm training : Metronome vs Recording

Question: Is one of these two methods more fitting as an exercise to improve the overall sense of rhythm : Playing along a recording of a piece, or playing the piece just with a metronome ? What are the pros & cons of each method ?
By recording I also include recording through a software like GuitarPro or Sibelius, which allow to change the tempo at will, like a metronome.
Context : I'm a guitar player trying to improve my global sense of rhythm, not just practice a song to play it correctly. I've always preferred playing along with a recording—it is easier than the metronome to me.
Comment: Best way to improve your sense of rhythm and tempo is to take up dancing.  There are so many kinds.  Contra, English, salsa, bachata, ballroom, country western, jazz, lyrical, ballet, hip hop, tap, etc.  Check out what's happening at the community centers and senior citizen centers.  (You don't need to be a senior citizen to attend their classes and get-togethers.)  You can also dance at home by yourself.
Comment: @aparente001 Interesting suggestion, even though it's kinda of the scope of the question, I gladly take it :)
Comment: What do you mean by "overall sense of rhythm"? This seems rather vague. Can you be more specific?
Comment: @BrianTHOMAS I guess the ability to feel the rhythm when playing alone or with someone or something. Ability to feel it and incorporate it in one's playing to make it rhythmically more accurate.
Comment: @BrianTHOMAS added the words "global" and "overall" to express that this skill is not linked to just one piece. It's not just playing one piece correctly rhythm-wise, but a sort sense that slowly carry on to anything else you play. Maybe there's a better choice of words to express this; I'm not a native english speaker.
Comment: Playing along with a recording sounds good.  How about also expanding your opportunities to play with other people?  Large, small ensembles, formal, informal opportunities, people of your same level and people of higher or lower levels, various genres -- keep yourself open to anything as you are getting started, to find out what works best for you.
Answer: IMHO i think both will be helpful to learn sense of rhythm. But there are differences of course.
Good thing about metronome is you can change it, double or half the speed of it. So you have more options there.
Also it's easier to hear you playing , if you don't have the whole recording sounding in the background.
And you can hear a metronome with headphones and still be able to hear yourself playing. I believe doing this might make the beat more inherent in you.
Good thing about playing along with the recording is you are actually hearing the song! That may give you a more musical sense than only hearing the beep of the metronome.
Also if you play later with real musicians it'll be more familiar to you because you are used to practice while hearing the rest of the band.
Whatever you prefer is alright. Both will serve you.
Answer: Since you only ask about metronome or recordings -
they both have their place, along with other options...
A metronome is useful, if not (very) boring. It can easily be changed tempo-wise, half, double, and everything in between. Also extremely useful to use in more advanced ways - set up and take each click as the & between the beats, for example. It will be relentless, and never vary whatever tempo you choose.
Recordings, if made with a click track, like most these days, will also be relentless, and will doubtless ingrain more than just tempo - number of bars for verse/chorus/etc.
Earlier recordings (50s, 60s, 70s) often vary in tempo - rather like a lot of live music does - not drastically, but the speeding up and slowing down reflect the mood of the piece at that moment, so not metronomic. It also means you have to play the approriate chords/riffs, so need to know the particular songs.
Playing with others is an option not mentioned, so I'll mention it! It's good and bad. You'll get more musical experience this way - good and bad! Playing with poor time keepers is an experience to be had. Trying to keep time either with them or against them will help you appreciate what timing is. Playing with excellent time keepers is also an experience, and certainly keep you on your toes.
For guitar there are many backing tracks available - 'music minus one' comes to mind, which one can play along to and they will inevitably be spot on time wise.
Answer: Riding on and syncing to a pulse and rhythmic feel or "groove" produced by others is of course an important skill. But you can't rely on that only, you have to be able to produce the pulse and provide it to others reliably. Playing to records only is not a good practicing method, because you may develop habits of listening to specific subtle sound cues, and then you're lost in a real situation when the cues are missing or when something unexpected happens. You want to listen and adapt, and if needed, be the reliable master clock youself.
Recording can be very important, namely recording your own playing, because you need to hear how much your timing sucks ! ;)
Playing with a metronome is essential, and to make yourself produce the rhythm pulse instead of hanging on to it can be practiced with a metronome click that's not on the "one" or not on beats at all. For example, make the metronome click on downbeats or only on the TWO of each bar. That way you'll have to play the ONE loud and clear on top of silence, and you'll get the feedback on rushing or dragging a bit later. You have to be able to play strong rhythm with good time, no dragging or rushing, no tempo drifting. This is a basic skill.
Answer: Musicians primarily fail with these two because they don't match the extent of their skills with the complexity of composition they chose to play. this will cause the sensation that performing accepts good rhythm is extremely hard.
The truth is, each bit may feel complex initially but becomes easier with practice. Let's check out some useful tips for a way you'll improve your rhythm and timing when playing music.
Where to start?
It's important to start out practice with appropriate compositions. the simplest melodies for practicing are usually within one octave, during a signature you're conversant in. Also, it's best if there aren't any sixteenth or thirty-second notes (a.k.a. semi-quavers or semi-demi-quavers), therefore the pattern isn't too complicated at the right tempo. Here are a few easy to know examples for you to undertake to play along with:
Whether you're an experienced musician or amateur your rhythm practice should start with a careful study of the piece, slowly playing each note. If there's some complex poetic rhythm ahead, don't attempt to play it the superbly the primary time you encounter it. Leave it then attempt to practice it in isolation. the primary time you play it you would like to form sure you hit the proper notes; leave the timing and rhythm as secondary priorities. That way you'll have your full attention ready for understanding the rhythm once you return thereto.
Techniques for Improving Your Rhythm and Timing
We're getting to check out four techniques you'll start using today to enhance your sense of rhythm and timing once you play music. attempt to incorporate one or more into your regular practice immediately then add the others over time.
and Musicians practice with metronomes to enhance their timing, especially the power to stay to a daily tempo. Metronome practice helps internalize a transparent sense of timing and tempo. Composers and conductors often use a metronome as a typical tempo reference—and may play, sing, or conduct to the metronome. The metronome is employed by composers to derive beats per minute if they need to point that during a composition. Conductors use a metronome to notice their preferred tempo in each section.
When interpreting emotion and other qualities in music, performers seldom play exactly on every beat; expressive, flexible rubato could also be used sometimes. Typically, every beat of a musically expressive performance doesn't align exactly with each click of a metronome. This has led some musicians to criticize the use of a metronome because metronome time is different from time. Some go as far on suggesting that musicians shouldn't use metronomes in the least, and have leveled criticism at metronome markings also.


Partial Orders on finite sets to which Zorn's lemma does not apply

Question: Zorn's lemma is stated in the text I'm reading as

If $(A, \leq)$ is a poset such that every chain of elements in $A$ has an upper bound in $A$, then $A$ has at least one maximal element.

However, I can't think of any partial ordering (defined as a relation which is reflexive, anti-symmetric, and transitive) on which the condition

If $(A, \leq)$ is a poset such that every chain of elements in $A$ has an upper bound in $A$

would not hold if $A$ is a finite set. (I understand how an infinite set like $[0, 1)$ would fail to satisfy this requirement). My argument is that if $C$ is a chain in the poset $(A, \leq)$ then there will be an end to the chain which will be an element in the chain, and hence every set will satisfy this.
Then can we say that if $A$ is a finite set then any poset $(A, \leq)$ has at least one maximal element by Zorn's lemma? If not, is there a counter-example to help me understand?
Comment: You can say so, but it looks like Zorn's lemma is overkill. You can just compare all elements to each other, which is a finite process due to the finiteness of $A$. and does not use the Axiom of choice.
Comment: @max_zorn you mean zorn's lemma is useful in contexts other than the ones which deal with finite sets? Also, even though you say "you can just compare all elements to each other which is a finite process", you are assuming that there exists a maximal element in any poset on a finite $A$. Is this true?
Comment: 1) The big use of Zorn's lemma is exactly for infinite sets. You can prove things like every vector space has a Hamel basis, which is amazing since nobody knows one in, say, the space of all sequences. 2) I don't assume there is a maximal element, this is a consequence of just comparing all elements in the finite $A$.
Answer: Well, there is a counterexample, but it's not a very interesting one: if $A=\emptyset$, then the empty chain has no upper bound.  However, any nonempty finite poset satisfies the conditions of Zorn's lemma.  Indeed, any finite nonempty chain has a greatest element (this is easy to prove by induction on the size of the chain), which is then an upper bound.  (And as long as $A$ is nonempty, the empty chain also has an upper bound, namely any element of $A$.)
As others have mentioned, Zorn's lemma is kind of overkill for finite posets, because you can prove they have maximal elements without the axiom of choice.  However, I think they are actually an instructive example for understanding the proof of Zorn's lemma in general.  There is an obvious way to find a maximal element of a (nonempty) finite poset: start with one chosen element, and then compare it with all the elements of the poset one by one, changing your chosen element whenever you find another element that is greater than it.  This argument is in fact exactly how you prove Zorn's lemma in the general case as well, except that you need to choose a well-ordering of the poset and use it to go through the elements one-by-one by transfinite induction, and at limit steps you need to use the hypothesis that chains have upper bounds.
Answer: I actually wrote , many years ago , an example that may satisfy your curiosity:
https://coldoc.sns.it/UUID/EDB/02M/?lang=en_US
Indeed in this example there is a partial order that cannot satisfy Zorn's Lemma hypotheses, but it is not obvious at first sight.


Hiding derived class in WCF

Question: I want to hide derived class from the client in my WCF service.
Example -
<code>[DataContract]
public class Base
{
    public int Id {get; set;}
}

public class Derived : Base
{
    public string Name {get; set;}
}
</code>
Let's say I've operational contract like
<code>[OperationalContract]
Base GetData();
</code>
Implementation of operational contract
<code>public Base GetData()
{
    Derived = new Derived {Id = 1, Name = "Foo" };
    return derived;
}
</code>
The above example doesn't work. If I add [KnownType(typeof(Derived)] in Base class, and add DataContract attribute to Dervied class then everything seems to work fine. But if I do that the client will see the Derived class, that I want to hide. Is it possible to hide Derived class from the client? Thanks
Comment: Does it work if you cast to Base before returning?  Or you could map it to base (make a new Base and copy over the data, either manually or automatically).
Comment: It throws "There was an error while trying to serialize parameter http://tempuri.org/:DerivedResult". The second suggestion is hack that I would like to avoid.
Comment: Technically, if you're separating your data contracts and your entities, allowing you to decouple and also to turn WCF into an implementation detail, this is not only **not** a hack but it is also given to you for free.  You'd be mapping between multiple entity types and one data contract type.
Answer: I think you'll get the behavior you want hacking equivalence using named DataContracts instead of adding the KnownType attribute, like so:
<code>[DataContract(Name="Reply")]
public class Base
{
    [DataMember]
    public virtual int IntValue { get; set; }

}

[DataContract(Name = "Reply")]
public class Derived : Base
{

    public String StringProperty { get; set; }
}

Derived blah = new Derived { IntValue = 3, StringProperty = "blah" };
public Base SomeOperation()
{
     return blah;
}
</code>
Does this do what you want?  Also have a look at DataContractSurrogates (http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/14/wcf-extensibility-serialization-surrogates.aspx), which is all told a fancy way for WCF to support what zimdanen said - creating a type for your API, and converting your internal type into this API type in a less "hacky" way.
Comment: Wish I could +1 twice, once for each answer. :)

Hiding derived class in WCF


Let 4 linearly dependent vectors such that any 3 of them is independence

Question: Kinda stuck at this question and confused.
Let 4 Linearly dependent vectors exist in the F field.            Such that any 3 of them are linearly independent.
Let the 4 vectors be {${u,v,w,x}$}.
Let L=Span{${u,u-2v,u+3v+w,w+x}$}.
Find the dimL.
In my opinion the dim is 3 but it's a wild guess.
I found it with examples like (1,0,0),(0,1,0),(0,0,1),(1,1,1). And because (1,1,1) is linearly dependent the vector is also dependent in L.
How can I know what is the dim of L without similar inputs - only by the definition of the span.
Thank you very much in advance.
Answer: Notice that $u \in L$. Then since $u \in L$ and $u-2v \in L$ we also have $v \in L$ (we can write $v = \frac{1}{2}u - \frac{1}{2}(u-2v)$). Now since $u+3v+w \in L$, we conclude that $w \in L$ as well (since $w = (u+3v+w)-u-3v$). And so finally from the fact that $w+x \in L$ we have $x \in L$ (since $x = (w+x)-w$). Therefore $\text{span}(u,v,w,x) \subseteq L$.
Conversely, we also have $L \subseteq \text{span}(u,v,w,x)$ since the vectors used to define $L$ are all in $\text{span}(u,v,w,x)$.
Hence $L=\text{span}(u,v,w,x)$, so all that remains is to show that the dimension of $\text{span}(u,v,w,x)$ is $3$.
Comment: Got it , makes sense. Thank you very much!


Converter for em while

Question: #include <stdio.h>
#include <stdlib.h>

int main(void) {

   int X[10], cont;
   cont=0;
   while(cont<10){
        printf("Digite um numero inteiro: ");
        scanf("%d",&X[cont]);
        if(X[cont] %2 == 0){
            X[cont]=0;
        }else{
            X[cont]=1;

        }
        cont++;
    }

   while(cont<10){
        printf(" %d ", X[cont]);
        cont++;
   }

}

Esse código não está funcionando, porém quando faço com for dá certo:
#include <stdio.h>
#include <stdlib.h>

int main(void) {

   int X[10], cont;
   for(cont=0;cont<10;cont++){
        printf("Digite um numero inteiro: ");
        scanf("%d",&X[cont]);
        if(X[cont] %2 == 0){
            X[cont]=0;
        }else{
            X[cont]=1;

        }
    }

   for(cont=0;cont<10;cont++){
        printf(" %d ", X[cont]);
   }

}

Comment: Note que ao final do primeiro while a variável `cont` estará com o valor 10 e portanto não entrará no segundo loop. Reinicie a variável antes de entrar no segundo loop.
Comment: Ok, obrigada. Deu certo!
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: O principal problema é que não está zerando o contador quando vai fazer o segundo laço, como a variável estava valando 10 na saída do primeiro ele vai pegar posições erradas da memória na sequência. Aproveitei para organizar e simplificar o código.
Note que o resultado da conta para descobrir se é par ou ímpar já dá exatamente o número necessário, então não tem porque fazer um if.
#include <stdio.h>

int main(void) {
   int X[10];
   int cont = 0;
   while (cont < 10) {
        printf("Digite um numero inteiro: ");
        scanf("%d", &X[cont]);
        X[cont] = X[cont] % 2;
        cont++;
    }
    cont = 0;
    while (cont < 10) printf(" %d ", X[cont++]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Deu certo! Obrigada!!
Comment: Como eu faço para verificar a posição de um vetor?
Comment: Teste fazer, se tiver algum problema faça uma nova pergunta com todos detalhes necessários.
Comment: Veja o [tour] a melhor forma de dizer obrigado.

Converter for em while


How do you derive the formula $d= \frac {|a \times b| }{|a|}$ to find the shortest distance between 2 vectors?

Question: Distance from point $P$ (not on $L$) to line $L$ (that passes through $Q$ and $R$) is $$d=\frac{|\vec{a}\times \vec{b}|}{|\vec{a}|}$$
where $\vec{a}=\vec{QR}$ and $\vec{b}=\vec{QP}$
Find the distance from the given point to the given line:
(a) $(4, 1, −2); x = 1 + t, y = 3 − 2t, z = 4 − 3t$
How do you derive the above formula to find the shortest distance between the point and the vector?
Answer:
Geometrically, the formula is saying $PH$ equals the area of the parallelogram divided by $QR$.
Comment: How about vector projection method? Is vector projection method applicable to this scenario as well?
Comment: Yes, you can actually do the following as well: (1) first cross $PQ$ and $QR$, let it be $V$, then cross $QR$ and $V$ to get the direction of $PH$. Then dot product $PQ$ with the normalized direction vector of $PH$. However this method is much slower as it looks..
Answer: $d= \frac{|a \times b|}{|a|}=|bsin(\alpha)| $ where $\alpha$ is the angle between the vectors $a$ and $b$.


XML string array deserialize as different type name

Question: I have the following C# class property:
private List<string>  _accountTypes;

[XmlArray(ElementName = "accountTypes")]
public List<string> AccountTypes
{
   get { return _accountTypes; }
   set { _accountTypes = value; }
}

which is initialized like this in the class constructor:
_accountTypes       = new List<string>( new string[] { "OHGEE", "OHMY", "GOLLY", "GOLLYGEE" });

When deserialized I get this:
<accountTypes>
   <string>OHGEE</string>
   <string>OHMY</string>
   <string>GOLLY</string>
   <string>GOLLYGEE</string>
</accountTypes>

I should like it if I could get this:
<accountTypes>
   <accountType>OHGEE</accountType>
   <accountType>OHMY</accountType>
   <accountType>GOLLY</accountType>
   <accountType>GOLLYGEE</accountType>
</accountTypes>

Without creating a subclass of type "accountType", how can this be done? Are there any XML attribute properties that can be used to get what I need?
Answer: I think you are searching for the [XmlArrayItem] Attribute.
Try this:
[XmlArray(ElementName = "accountTypes")]
[XmlArrayItem("accountType")]
public List<string> AccountTypes
{
   get { return _accountTypes; }
   set { _accountTypes = value; }
}


Instance where echelon form of a matrix conceals the solution to a system?

Question: Say I have two equations:
$$y^3+x-y=0$$
$$x^3-x+y=0$$
These are both partial derivatives of some function, and the condition that they're equal to $0$ implies the values of $x,y,z$ are bound are stationary points. I thought I might try and put these values into a matrix to compute the solution to the system. I think I did something wrong here, because it ended up with a case where my matrix not being in echelon form actually made it easier to solve.
$$\begin{bmatrix}
        1 & 0 & 1 & -1 \\
        0 & 1 & -1 & 1\\
        \end{bmatrix}$$
Where it is a matrix of coefficients with each row vector with the form $(y^3,x^3,x,y)$. This matrix here, is actually in reduced echelon form, which tells me that there are two free parameters and that the system can be solved as is by back substitution, but if one does..
$$R2 \to R2 + R1$$
One then has (forming the augmented matrix):
$$\begin{bmatrix}
        1 & 0 & 1 & -1 &| & 0\\
        1 & 1 & 0 & 0 & | & 0\\
        \end{bmatrix}$$
And thus it is shown an implication of the system has  been rendered useful to us:
$$x^3 + y^3 = 0$$
$$y^3 +x -y = 0$$
Which is very straightforward to solve as it gives us the insight that $x=-y$. Why, though, did it make sense that doing a row operation after my matrix was in $rref$ helped simply the system further? Also, did what I do make sense? Or is the matrix I made not valid? Just tried applying some linear algebra to a calculus exercise. My hunch is that my matrix is invalid because usually our matrix of coefficients belong to $x,y,z$ terms and for mine, $y^3$ is not independent to $y$ like $z$ is to $y$. But, the vector space of all polynomials with degree at most $2$ have $(a,x,x^2)$ terms which seems to contradict my hypothesis.
Comment: You can't solve for the solutions of this system of equations using row reduction because these are not linear equations.
Comment: Applying RRE on a non-linear equation just doesn't make any sense. First of all, the variables $x,x^3$ are not independent. Second of all, the span of solutions to these equations do not form a vector space, so the transformation you are dealing with is non-linear.
Comment: @bat_of_doom Then why does $\mathcal P_2$ form a vector space (the set of all polynomials with degree at most $2$)? Its variables $x,x^2$ are not independent, and the polynomials are non-linear equations.
Comment: @sangstar There, you are not dealing with roots of a particular polynomial, but instead with the functions themselves. If $x^2-2x+1, x^2-3x+2$, are polynomials, any linear combination is a polynomial. But, if $(x-1)(x-2)$ is a polynomial, then, $1+1.2$, which is a linear combination of 1 and 2, is not a root.
Comment: So, in $\mathcal P_2$ the vector space consists of vectors with components of coefficients for the general polynomial of degree at most $2$, and here I'm attempting to form a vector space of roots of polynomials? Where is it given that my vector space is of roots here, and not of a general polynomial like for $\mathcal P_2$?
Comment: @sangstar When you solve a linear equation in variables, x1,x2,...xn, you essentially use the fact that the set of homogenous equations is a vector space. Here, it is not necessary that the sum of 2 solutions be a solution, as pointed out by my earlier comment. If you don't understand the theory, just take it for granted you can't do the same stuff with non-linear equations for solving them.
Comment: @sangstar Please, if you are ok, you can set as solved. Thanks!
Answer: adding both equations we get
$$x^3+y^3=0$$ and this is equal to $$(x+y)(x^2-xy+y^2)=0$$
can you solve this equation?
Comment: Since &y$ is not constant, no. Good point.
Answer: assuming $$x^3, y^3, x, y$$ as variables, the method is valid to reduce the first system to the second (finding the rref is equivalent to manipulate the starting equations)
Comment: by matrix analysis you find a new set of equation in the 4 variables by linear combination, in this sense the method is valid to symplify the system
Comment: Yes, of course they can be used to simplify the equation. But my point was that you can't use the RRE form directly for a solution, as the variables are not independent. I.e, to say that you can't declare variables free, because of the rank of matrix being less. I think the OP is confused about this. +1 from me if you can clarify this point in your answer, because as the answer stands, it suggests that you can find the solution by RRE.
Comment: Yes, but the given solution will be wrong, because the variables are not independant, and hence no variables are actually 'free'.


Combinations and permutations when separating into groups

Question:
If I have 30 people and I want to form them into 3 groups. One of size 10, one of size 5 and one of size 15. How many ways can I do this?
Similarly what if I have 15 boys and 15 girls and the 10 person group has to have 5 of each?

For part 1, I thought I would do 30C10 + 20C5 + 15C15 and that it would equal if I arranged it any other way, like 30C5 + 25C10 + 15C15, but I get different answers! Help?
Comment: For 1), multiply instead of adding. This is because for **every way** of choosing the $10$-person group, there are $\binom{20}{5}$ ways to choose the $5$-person group.  For 2) deal with the $10$-person group first.
Comment: Thank you! then for part 2, does that mean I multiply 15C5*15C5*20C15*5C5?
Comment: You are welcome. Sure. Of course the $\binom{5}{5}$ at the end is just there for decoration.
Answer: One way to think of the first part is to have the people numbered 1 to 30, and they do not move, now count the number of arrangements of labels which assign them into one of the three groups.
111111111122222333333333333333
this is arranging 30 labels with repetitions of 10, 5, and 15 so the total number off arrangements (and the total number of assignments of the 30 people into the 3 groups) is given by 30!/(10!5!15!)
Answer:

If I have 30 people and I want to form them into 3 groups. One of size 10, one of size 5 and one of size 15. How many ways can I do this?
Similarly what if I have 15 boys and 15 girls and the 10 person group has to have 5 of each?

1.
It's a straight multiset selection:
$${30 \choose 15, 10, 5} = {30\choose 15}{15\choose 10}{5\choose 5} = {^{30}C_{15}}\cdot{^{15}C_{10}}\cdot{^{5}C_{5}} = \frac{30!}{15!\,10!\,5!}$$
This counts the ways to select a teams of 15 from 30, times the ways to select a team of 10 from the remaining 15, and times the ways* to select at team of 5 from the remaining 5.
2.
Choose the boys and girls for the balanced team; then choose the two other teams from the remaining students.
$${15\choose 5}^2{20\choose 15}{5\choose 5} = {^{15}C_{5}}^2\cdot{^{20}C_{15}}\cdot{^{5}C_{5}} = \frac{15!\, 20!}{5!^3\, 10!^2}$$
This counts the ways to select a half-team of 5 boys from 15 boys, times the ways to select the other half-team of 5 girls from 15 girls, times the ways to select a team of 10 from the remaining 15 people, and times the ways* to select at team of 5 from the remaining 5 people.

(Note: * Counting the ways to select 5 from 5 is included for completeness, though it is obviously just 1.)


Can't start Plaid quickstart app in development mode

Question: I've just started using Plaid.  I've set up the quickstart app locally and it runs fine in sandbox mode.  The Link panel loads fine, and I can log into an institution using the sandbox creds.
My .env file looks like this:
PLAID_CLIENT_ID=xxxxxxxx
PLAID_SECRET=xxxxxxxx
PLAID_ENV=sandbox
PLAID_PRODUCTS=transactions
PLAID_COUNTRY_CODES=US,CA
PLAID_REDIRECT_URI=http://localhost:3000

I'd now like to check that Plaid will work with a few particular real/live institutions, so I'm attempting to update my quickstart app to work in development mode.  To do this I am simply updating PLAID_SECRET to be my development secret key, and PLAID_ENV to be 'development'.
When I now start the app, the start page no longer shows the 'Launch Link' button, but instead shows:

The logs suggest the issue is happening on the POST /api/create_link_token call.  If I remove the error handling from that route function the logs show me the issue:
Traceback (most recent call last):
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "server.py", line 196, in create_link_token
    response = client.link_token_create(request)
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api_client.py", line 769, in __call__
    return self.callable(self, *args, **kwargs)
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api/plaid_api.py", line 5566, in __link_token_create
    return self.call_with_http_info(**kwargs)
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api_client.py", line 831, in call_with_http_info
    return self.api_client.call_api(
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api_client.py", line 406, in call_api
    return self.__call_api(resource_path, method,
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api_client.py", line 200, in __call_api
    raise e
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api_client.py", line 193, in __call_api
    response_data = self.request(
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/api_client.py", line 452, in request
    return self.rest_client.POST(url,
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/rest.py", line 264, in POST
    return self.request("POST", url,
  File "/Users/william/Personal/quickstart/python/venv/lib/python3.8/site-packages/plaid/rest.py", line 223, in request
    raise ApiException(http_resp=r)
plaid.exceptions.ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Server': 'nginx', 'Date': 'Sun, 16 May 2021 18:22:05 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '301', 'Connection': 'keep-alive'})
HTTP response body: {
  "display_message": null,
  "documentation_url": "https://plaid.com/docs/?ref=error#invalid-input-errors",
  "error_code": "INVALID_API_KEYS",
  "error_message": "invalid client_id or secret provided",
  "error_type": "INVALID_INPUT",
  "request_id": "EbCTgZkFdeYQQ8r",
  "suggested_action": null
}

So it's suggesting I'm using the wrong client id or secret, but I don't understand.  The client ID should be fine (it worked in sandbox mode), and the secret is definitely my secret for development mode (I've even tried generating a new one but no difference).  Am I missing something?
Finally, if I use Postman to POST to https://development.plaid.com/link/token/create to create a link token, using the same client ID and 'development' secret, it seems to work fine (i.e. I get a 200 response and brand new link token).
Any help is much appreciated!
Answer: This is due to the fact that Python is hardcoded to Sandbox.  This is being fixed and in the meantime, on line 84 of server.py, you can change it to:
"host=plaid.Environment.Development"
Answer: Oops, well this would do it:
https://github.com/plaid/quickstart/blob/master/python/server.py#L84
It looks like the python Quickstart is hardcoded to ignore the environment variable set in the .env file.  We'll get that fixed.  In the meantime, changing that line should fix your problem.


let the user choose role upon registration

Question: I'd like to let the front-end user to choose user role upon registration.
When the register form submit, I'd like it to redirect to the respective profile page concerning with their chosen role.
I use profile2 module and profile2 registration path module.
Is there any existing module for that ?
Thanks in advance!
Answer: If you love custom coding and if you already have a custom module, I would recommend to do this with a custom module rather than using Profile 2 and other related modules. I personally prefer to write custom modules because it will let you get exactly what you are looking for.
But you still need to use Auto Assign Role module to let user choose a user role on registration.
My solution is to show/hide the respective profile fields upon user role selection on the registration form. It would not redirect to the respective profile page.
You can create profile fields at admin/config/people/accounts/fields and you can export them to the registration form, but they cannot be created by role. What you would need to do is to show/hide each field by role from hook_form_alter and use #ajax attribute.
Here is an code snippet for this purpose. I did not test the code. Just for example.
function yourmodule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'user_register_form' || $form_id == 'user_profile_form'){

        $form['autoassignrole_user']['user_roles']['#ajax'] = array(
          // #ajax has two required keys: callback and wrapper.
          // 'callback' is a function that will be called when this element changes.
          'callback' => 'ajax_form_alter',
          // 'wrapper' is the HTML id of the page element that will be replaced.
          'wrapper' => 'replace_field_div',
          // Don't show any throbber...
          'progress' => array('type' => 'none'),
         );

        # This profile field will be shown or hidden when the respective "user_roles" is selected
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
        $form['field_first_name']['und'][0]['value']['#prefix']     = '
';
        $form['field_first_name']['und'][0]['value']['#suffix']     = '
';

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['autoassignrole_user']['user_roles']) && $form_state['values']['autoassignrole_user']['user_roles'] == {rid_here}){
            # when the respective user roles is selected, show this field and set required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'textfield';
            $form['field_first_name']['und'][0]['value']['#required']   = TRUE;
        }else{
            # when the respective user roles, hide this field and remove required.
            $form['field_first_name']['und'][0]['value']['#type']       = 'hidden';
            $form['field_first_name']['und'][0]['value']['#required']   = FALSE;
        }
    }
}
/**
 * Callback for user_roles
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['field_first_name'];
}

You may notice that you have to use ['und'][0]['value'] for the profile field to tweak its attributes. If you are not sure about this, you can print $form for debugging purpose:
dpm($form); // if Devel module is enabled
echo '
'; print_r($form); echo '
'; // if you don't have Devel module

If there is another better solution, please post it and it will be appreciated.
Comment: I adopt your solution as it suits my needs.  Thanks for the help.  However, I need to change a little.   For one thing, change `$form_state['values']['autoassignrole_user']['user_roles']` to `$form_state['values']['user_roles']`.  And instead of using fixed {rid_here}, I use user_role_load_by_name().
Answer: checkout the Auto Assign Role.

The Auto Assign Role serves three primary purposes. The first is to
  provide an automatic assignment of roles when a new account is
  created. The second is to allow the end user the option of choosing
  their own role or roles when they create their account. The third is
  to provide paths that will trigger a specific role when an account is
  created. The administrator has full control over these functions and
  can have them working together or independently of each other.


What does the notation "2/3BII" mean?

Question: What does the note "2/3BII" mean here? The notation below is a part of the piece "Canon in D", arranged in classical guitar.
Update
This piece is arranged by Allan Alexander. Here is his explanation.

That is two thirds of a bar (4 strings) on the second fret. sometimes it's notated 2/3 CII. B for Bar, II for second fret. 2/3 for 4 strings. It's better than doing a full bar all the time.
Answer: It's a two thirds (top 4 strings) barre on the second fret. There are a few different ways of indicating a barre in guitar sheet music:
ⁿ⁄ₘ B X

Symbol
Meaning
Examples

ⁿ⁄ₘ
how much of a barre you do
½ = half barre, 3 out of 6 strings  ⅔ = two thirds barre = ⁴⁄₆ = 4 out of 6 strings  ⅚ = 5 out of 6 strings  <code> </code> = full barre

B
Indicates a barre
B = Barre  ₵ = C = Cejillo / Capotasto (Spanish/Italian for capo).

X
fret of barre
I = 1st fret  II = 2nd fret  III = 3rd fret etc.

e.g.

Xⁿ

Symbol
Meaning
Examples

X
fret of barre

ⁿ
amount of strings barred
³ = top 3 strings  ⁵ = top 5 strings etc.

e.g.

Frederick Noad in his book Solo Guitar Playing lists a few more common forms:

Unfortunately editors differ in the ways they indicate the half bar, and you may find it written in any of the following ways:

a. The fingering indication shows that the 1st finger must cover all three notes.
b. The bracket line indicates the notes to be barred.
c. The letters MC are abbreviated from the Spanish medio capotasto, meaning "half bar."
d. d, e, and f are self-explanatory and used according to the nationality of the editor. This author prefers the use of f which gives the fullest information as briefly as possible.
While the 1st finger holds the halfbar, other fingers may play, and the duration of the half bar is usually indicated by a line or dotted line.
Answer: If we look at the score the guitar 6th string is lowered down a whole tone to D which brings the 6th string F# to the fourth fret.
Now lets go ahead and play the first measure which doesnt pose any reading challenges. So does the 2nd measure.. Playing wise it should not pose a problem at all BUT what is written above (2/3 B11) is not really a great way of writing music. Actually notation should be easy on the reader.  to move ahead Let play the Bminor arpeggio while barring the 2nd fret with the fingerings mentioned .. without moving the barre the 3rd finger moves to the F# on the 6th string as the 2nd finger is lifted to make way for the C# to give us a F# minor chord..
According to my understanding I think whatever is written is a guide to the left hand 2nd and 3rd finger movement while retaining the barre.
Answer: I think it means a partial barre at the second fret, where it's only important that strings 2 and 3 are held by the first-finger barre.
I don't recall seeing this notation before. It would more commonly be written as "1/2 CII" (half-barre at fret 2), where 'C' stands for the Italian word capotasto, usually abbreviated capo (/kay-po/). The chord being play is F♯-minor.
Answer: This could refer to blocking in a musical theatre composition. (Blocking is the act of placing and moving performers on stage so that the director achieves the desired look and feel of that scene.)
It would be more helpful if you could show some extra context to your note. You include "..." to which I'm assuming means there is more text.

Ah ha! It's a reference to a B11 Chord. As guitar is not one of my main instruments, I am going to propose a couple ideas. Likely, it means a slide - while playing the chord, slide your finger on the second fret to the third. It could also mean use fingers 2 and 3 (see this handy B11 Chord reference). A third possibility is to play the B11 chord using the second and third of the scale - C# and D#, though normally you would say "add 2" if you wanted to add the second, depending on the chord.
If another person who knows guitar better than myself could improve on this answer, I'm all ears. :)

What does the notation "2/3BII" mean?


Como fazer consultas dentro de uma matriz em Java?

Question: O problema pede a criação de um programa que leia o nome, cpf, e-mail e telefone de 10 pessoas. Em seguida, disponibilizar 4 opções de consulta (1-Por nome, 2-Por CPF, 3-Por e-mail e 4-Por telefone). Por exemplo, se o usuário escolher a opção 2, a consulta deverá solicitar um CPF e, com base nele, deverá imprimir os
dados do cliente que tenha este CPF. O programa deve informar caso não encontre nenhum cliente com o dado informado. Use uma matriz 10 x 4 para representar os dados.
O problema é que compila certo, pede as informações, informa o menu, mas quando insiro por exemplo um nome para consultar, não aparece nada. Qual é o problema?
import java.util.Scanner;

public class Exercicio10 {

    public static void main(String[] args) {

        Scanner ler = new Scanner(System.in); //leitura de dados da matriz
        Scanner lm = new Scanner(System.in); //leitura de dados do menu
        Scanner n = new Scanner(System.in); //leitura de nome
        Scanner c = new Scanner(System.in); //leitura de cpf
        Scanner e = new Scanner(System.in); //leitura de email
        Scanner t = new Scanner(System.in); //leitura de telefone

        String m[][] = new String [10][4];
        int i, j;

        for (i = 0; i < 10; i++) {
            System.out.println("Informe o nome, CPF, e-mail e telefone da " + (i+1) + "ª pessoa:");
            for (j = 0; j < 4; j++) {
                m[i][j] = ler.nextLine();
            }
        }

            System.out.println("Opções de consulta:");
            System.out.println("|1| - Consultar por nome");
            System.out.println("|2| - Consultar por CPF");
            System.out.println("|3| - Consultar por e-mail");
            System.out.println("|4| - Consultar por telefone");
            int menu = lm.nextInt();

            switch (menu) {
            case 1:
                System.out.println("Insira o nome:");
                String nome = n.nextLine();
                for (i = 0; i < 0; i++) {
                    if (nome == m[i][1]) {
                        System.out.println(m[i][1]);
                    }
                }
            break;
            case 2:
                System.out.println("Insira o CPF:");
                String cpf = c.next();
                for (i = 0; i < 0; i++) {
                    if (cpf == m[i][2]) {
                        System.out.println(m[i][2]);

                    }
                }
            break;
            case 3:
                System.out.println("Insira o e-mail:");
                String email = e.next();
                for (i = 0; i < 0; i++) {
                    if (email == m[i][3]) {
                        System.out.println(m[i][3]);
                    }
                }
            break;
            case 4:
                System.out.println("Insira o telefone:");
                String telefone = t.next();
                for (i = 0; i < 0; i++) {
                    if (telefone == m[i][4]) {
                        System.out.println(m[i][4]);
                    }
                }
            break;

            }

        }

}

Answer: 1) Comparação entre Strings;
O problema principal é que vc está fazendo a comparação com ==. A comparação entre Strings deve ser feita com .equals que faz a comparação por valor e não por referência.
Suas comparações dentro do if devem ficar assim: m[i][1].equals(nome)
2) Laço FOR
O seu laço for não tem um critério de parada praticamente: for (i = 0; i < 0; i++). Da forma que está escrita, ele só iria parar quando i for menor do que
0, mas i já começa em 0, portanto ele irá acrescentar uma unidade até o infinito ou estourar alguma exceção. Tome cuidado com isso.
O correto seguindo sua lógica seria: for (i = 0; i < 10; i++).
3) Index da Matriz
Em Java, as estruturas começam em 0. Ou seja, se vc tem uma matriz 2x2 as posições que vc poderá acessar são: 0x0, 0x1, 1x0 e 1x1. Portanto para que vc não receba um código de erro, coloque as posições corretas ao acessar as posições da sua matriz;
Com esses pontos, vamos englobar tudo isso no seu código. Coloquei como era antes comentado e como deveria ser para que vc possa comparar:
import java.util.Scanner;

public class Exercicio10 {

    public static void main(String[] args) {

        Scanner ler = new Scanner(System.in); //leitura de dados da matriz
        Scanner lm = new Scanner(System.in); //leitura de dados do menu
        Scanner n = new Scanner(System.in); //leitura de nome
        Scanner c = new Scanner(System.in); //leitura de cpf
        Scanner e = new Scanner(System.in); //leitura de email
        Scanner t = new Scanner(System.in); //leitura de telefone

        String m[][] = new String[10][4];
        int i, j;

        for (i = 0; i < 10; i++) {
            System.out.println("Informe o nome, CPF, e-mail e telefone da " + (i + 1) + "ª pessoa:");
            for (j = 0; j < 4; j++) {
                m[i][j] = ler.nextLine();
            }
        }

        System.out.println("Opções de consulta:");
        System.out.println("|1| - Consultar por nome");
        System.out.println("|2| - Consultar por CPF");
        System.out.println("|3| - Consultar por e-mail");
        System.out.println("|4| - Consultar por telefone");
        int menu = lm.nextInt();

        switch (menu) {
            case 1:
                System.out.println("Insira o nome:");
                String nome = n.nextLine();
//                for (i = 0; i < 0; i++) {
                for (i = 0; i < 10; i++) {
//                    if (nome == m[i][1]) {
                    if (m[i][0].equals(nome)) {
//                        System.out.println(m[i][1]);
                        System.out.println(m[i][0]);
                    }
                }
                break;
            case 2:
                System.out.println("Insira o CPF:");
                String cpf = c.next();
//                for (i = 0; i < 0; i++) {
                for (i = 0; i < 10; i++) {
//                    if (cpf == m[i][2]) {
                    if (m[i][1].equals(cpf)) {
//                        System.out.println(m[i][2]);
                        System.out.println(m[i][1]);

                    }
                }
                break;
            case 3:
                System.out.println("Insira o e-mail:");
                String email = e.next();
//                for (i = 0; i < 0; i++) {
                for (i = 0; i < 10; i++) {
//                    if (email == m[i][3]) {
                    if (m[i][2].equals(email)) {
//                        System.out.println(m[i][3]);
                        System.out.println(m[i][2]);
                    }
                }
                break;
            case 4:
                System.out.println("Insira o telefone:");
                String telefone = t.next();
//                for (i = 0; i < 0; i++) {
                for (i = 0; i < 10; i++) {
//                    if (telefone == m[i][4]) {
                    if (m[i][3].equals(telefone)) {
//                        System.out.println(m[i][4]);
                        System.out.println(m[i][3]);
                    }
                }
                break;

        }

    }

}

Sobre a parte "O programa deve informar caso não encontre nenhum cliente com o dado informado." não tem nada implementado, mas minha dica é usar uma lógica com flag.
Espero ter ajudado.
Comment: muito obrigada!!


Qual o problema nesta query? Not unique table/alias

Question: Me deparei com um problema:
1066 - Not unique table/alias: 'catalog_product_entity_decimal'
SELECT DISTINCT catalog_product_entity.entity_id, sku, price as preco, qty as quantidade, stock_status as estoque, catalog_product_entity_decimal.value as embutido_regra_promo, catalog_product_entity_decimal.value as embutido FROM catalog_product_entity
INNER JOIN cataloginventory_stock_status ON (cataloginventory_stock_status.product_id = entity_id)
INNER JOIN catalog_product_index_price ON (catalog_product_index_price.entity_id = catalog_product_entity.entity_id)
INNER JOIN catalog_product_entity_decimal ON (catalog_product_entity_decimal.entity_id = catalog_product_entity.entity_id AND catalog_product_entity_decimal.attribute_id=249)
INNER JOIN catalog_product_entity_decimal ON (catalog_product_entity_decimal.entity_id = catalog_product_entity.entity_id AND catalog_product_entity_decimal.attribute_id=251)

A questão é que os dois ultimos INNERS utilizam a mesma tabela e coluna, porém com atributos diferentes no select, um defini para trazer o resultado do attribute_id 251 e o outro 249.
Alguma solução?
RESOLUÇÃO:
SELECT DISTINCT c0.entity_id, sku, price as preco, qty as quantidade, stock_status as estoque, c3.value as embutido_regra_promo, c4.value as embutido FROM catalog_product_entity c0 INNER JOIN cataloginventory_stock_status c1 ON (c1.product_id = c0.entity_id) INNER JOIN catalog_product_index_price c2 ON (c2.entity_id = c0.entity_id) INNER JOIN catalog_product_entity_decimal c3 ON (c3.entity_id = c0.entity_id AND c3.attribute_id=249) INNER JOIN catalog_product_entity_decimal c4 ON (c4.entity_id = c0.entity_id AND c4.attribute_id=251)

Answer: O problema é que você não está usando aliás para os joins. Tente assim:
SELECT DISTINCT catalog_product_entity.entity_id, sku, price as preco, qty as quantidade, stock_status as estoque, catalog_product_entity_decimal.value as embutido_regra_promo, catalog_product_entity_decimal.value as embutido
FROM catalog_product_entity c0
INNER JOIN cataloginventory_stock_status c1 ON (c1.product_id = c0.entity_id)
INNER JOIN catalog_product_index_price c2 ON (c2.entity_id = c0.entity_id)
INNER JOIN catalog_product_entity_decimal c3 ON (c3.entity_id = c0.entity_id AND c3.attribute_id=249)
INNER JOIN catalog_product_entity_decimal c4 ON (c4.entity_id = c0.entity_id AND c4.attribute_id=251)

Após utilize o aliás antes de cada campo do select também.
Comment: Funcionou, apenas tive que adicionar o alias na parte do select. Obrigado, Emir.
Answer: Bom dia, alguem pode me dar uma luz
Tenho essa query abaixo:
SELECT bairro.ba_bairro AS ba_bairro, count(cadastro.ca_bairro) AS
count_ca_outro_bairro, sum(cadastro.ca_bairro) AS sum_ca_bairro FROM
(cadastro LEFT JOIN bairro ON bairro.ba_codigo=cadastro.ca_bairro) GROUP BY bairro.ba_bairro

E faço uma mysql_fetch_assoc() mostrando o nome do bairro x e o total de registro dele na tabela cadastro.
Sendo que o mesmo existe mas 10 campos chamados:
ca_outro_bairro_1,ca_outro_bairro_2,ca_outro_bairro_3,ca_outro_bairro_4,ca_outro_bairro_5,ca_outro_bairro_6,ca_outro_bairro_7,ca_outro_bairro_8,ca_outro_bairro_9,ca_outro_bairro_10

Eu queria somar todos pois um cadastro pode morar no bairro x mas tem conhecido no bairro y.
Quero ter um relatório aonde mostra o total por bairro que some o total de cadastro nessas colunas relacionadas acima
Exemplo:
O bairro : bairro "centro" existe 20 cadastro na coluna ca_bairro e na coluna ca_outro_bairro_1 tem 10 registro então no bairro centro vai mostra 30 registro e assim com as outras colunas.
Comment: Olá @Radio Itacity. Bem vindo ao **StackOverflow PT**. A sua resposta não fornece informação para solucionar o problema colocado. Aconselho a que remova a resposta e coloque a questão de forma adequada. Aproveite para fazer o [Tour](https://pt.stackoverflow.com/tour) para perceber melhor como funciona o site.


Updating in MongoDB without first having to pull a Mongoid object?

Question: When performing queries I can go through Mongoid:
product_obj = Product.where(
                            _id: "58f876f683c336eec88e9db5"
                           ).first # => #<Product _id: 58f876f683c336eec88e9db5, created_at: nil, updated_at: nil, sku: "123", name: "Some text", ...)

or I can circumvent it:
product_hsh = Product.collection.find( {
                                         _id: BSON::ObjectId.from_string("58f876f683c336eec88e9db5")
                                       }, {
                                         projection: {
                                          _id: 1,
                                          name: 1
                                        }
                                      } ).first # => {"_id"=>BSON::ObjectId('58f876f683c336eec88e9db5'), "name"=>"Some text"}

I prefer to circumvent, because it performs better; I can limit which fields to get in the response.
My problem, however, is how to further work with the returned product. The response is a hash, not an object, so if I have to update it I need to pull it through Mongoid anyway, and thereby the performance gains are gone:
Product.find(product_hsh["_id"]).update_attribute(:name, "Some other text")

My question is: how do I update without first having to pull a Mongoid object?
Comment: can you format the first code block differently? The horizontal bar is covering the code for me.
Comment: @Tiramisu done.
Comment: the update command lets you specify the filter document and the update document. If you know the documents that you need to update then you can do so in a single statement. Look at the .update or the $set documentation.
Answer: You don't need to pull/fetch at all. You can just send the $set commands directly:
Product.where(id: product_hsh["_id"]).update_all(name: "Some other text")


How to properly vocalise and sing

Question: I am a bass. I can go down to E2 on any day and my voice sound rich and deep on F2-B2. I can somewhat vocalise up to E4, but I cannot sing anything from E3.
I think I know what my problem is. I squeeze my throat to make any note beyond G3 when I vocalise and C3 when I sing. My voice sounds tired/strained/like-singing-karaoke-for-hours-and-voice-is-gone after 10 minutes of practice. I also get a muscle pain in my jaw and neck.
My teacher suggested to sing as if I am projecting sound from my face or sometimes singing a very nasal voice, but my vocal cord still feels strained.
Can anyone help me out here?
Comment: I am in pretty much exactly the same situation. Very interested if you found anything that works for you!
Answer: I'm sure others will have more detail to give, but the answer seems pretty clear to me:
breath support.
Unfortunately, the way to develop stronger breath support is with all the non-musical exercises your teachers have given you over the years. Here are a few:

Hiss like a snake. Sssssssssssssssssssssssssssssssssss. Until you run out of breath. You want to be able to give a constant sound output using constant muscular pressure.
That riff from Paul Simon's Graceland. "Somebody say: Ih - Hih-Ih - Hih-Ih (Somebody cry Why Why Why?)".
Long, slow notes. Similar to hissing like a snake, but a little closer to music. Same deal though: you want a steady tone at an even volume, provided by the slow contraction of the muscles of the torso.

It is important to be aware of the difference between diaphragmatic breathing and chest breathing. But be wary of overly-zealous advice to use only diaphragmatic breathing. All the muscles of the abdomen, chest, and even the shoulders, too, contribute to the shape and pressures in the lung. There's an exercise called the Full Yogi Breath, which works all of the breathing muscles together.
Projecting can also help. Put a picture of your girlfriend on the wall across the room, and sing so the picture can "hear" you.
Comment: Agreed -- breath support. "Throat squeezing" sounds like a raised larynx, which is a way to get a higher note out when there's a lack of breath support. So the thing I would add here is that the larynx needs to be relaxed. Breath support is a prerequisite.
Comment: Could you add your answer to this question: http://music.stackexchange.com/questions/17/improving-breath-support
Answer: I had the same confusion but i later learn that its all about being original. Sing you voice with certainty and expect good of you . Listen to you self as as you break the air during your practice. Finaly believe in you today so that you tomorrow will be great.
Comment: While this is generally good advice, the OP is experiencing *strain* and *fatigue* which should be remedied by a stronger technique.

How to properly vocalise and sing


Jquery não monta data corretamente

Question: Fiz isso e a msg é: Data Inválida. Acho que é porque tudo virou string. Como eu faço para trazer somente a parte numérica na data? Aliás, falo isso, porque não consigo retornar uma data no nosso formato dentro do jQuery. No alert() dá Data Inválida.
var dtCadastro = data.agendamento.DataCadastro.substring(6, data.agendamento.DataCadastro.length - 2);
var dtAgendanmento = data.agendamento.DataAgendamento.substring(6, data.agendamento.DataAgendamento.length - 2);
var dtVisita = data.agendamento.DataVisita.substring(6, data.agendamento.DataVisita.length - 2);

var dt = new Date(dtCadastro);

alert(dt);

var dtCadastro = (Date)(data.agendamento.DataCadastro.substring(6, data.agendamento.DataCadastro.length - 2));

Este foi o cast que fiz, mas a data vem tipo:
Mon Jun 16 2014 14:24:45 GMT....

Gostaria de apenas um: 16/06/2014, sem a parte hora
Comment: Fiz um cast pada Date, aí consigo trazer a data, mas vem num formato quase que extenso e gostaria que fosse assim: dd/MM/yyyy somente. Vou editar o post para mostrar o cast
Comment: É mais fácil você formatar a data no C#. Tem o trecho de código C# que retorna o valor para que eu possa ajudar?
Answer: Use:
var x = "/Date(1402369200000)/";
var re = /-?\d+/;
var m = re.exec(x);
var d = new Date(parseInt(m[0], 10));
console.log(d);

// output: Tue Jun 10 2014 00:00:00 GMT-0300 (Hora oficial do Brasil)

Explicação

x recebe a data no formato string (DateTime do C# serializado em json, por exemplo);
re é o padrão em expressão regular para separar os números em um grupo (no caso o grupo na posição 0 do vetor m);
m é o vetor com o resultado do reconhecimento do padrão re (o que o regex reconhece);
m[0] é o valor, em epoch da data;
parseInt converte para inteiro na base 10;
d é a sua nova data.

Em 1 linha
var d = new Date(parseInt(/-?\d+/.exec("/Date(1402369200000)/")[0], 10));
console.log(d);

Para formatar

d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear() -> "10/6/2014"
d.toDateString() -> "Tue Jun 10 2014"
d.toLocaleDateString() -> "10/6/2014"

Exemplo com DataCadastro
function getFormattedDate(date){
 var re = /-?\d+/;
 var m = re.exec(date);
 var d = new Date(parseInt(m[0], 10));
 return d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear();
}

var dCad = getFormattedDate(data.agendamento.DataCadastro);
console.log(dCad);

Comment: Para formatar você pode utilizar: d.toLocaleDateString(). Vai retornar: '10/6/2014'. Para adicionar hora, você usa: d.toLocaleString(). Ou você pode formatar do jeito que precisar com: d.getDate() + "/" + d.getMonth() + "/" + d.getFullYear()
Comment: Veja só, conforme eu disse no C# está ok, as datas são as válidas que existem no BD. Quando serializo e pego no jquery e faço essas formatações é zoa tudo.
Comment: Fiz assim, Maia e formatou. Mas agora os três campos datas estão vindo com a mesma data todos(16/05/2014) e essa data nem existe em meu BD. Quando dou um break point no controller e vejo a data que está vindo, vem três datas diferentes e são as datas corretas, mas depois que eu pego no jquery via json, aí vem essa data incorreta e preenche todas as datas com esse valor(incorreto).
Comment: O melhor seria você enviar a data já formatada em C# (como o Joao Paulo sugeriu). Para os casos onde as datas estão erradas, pode ser que algumas variáveis esteja sendo aplicadas de forma errada. Preciso ver mais código para saber o que está acontecendo.
Comment: Veja o exemplo com DataCadastro que coloquei. Talvez ajude você.
Comment: Resolveu maia de acordo com a sua última resposta. Valeu
Answer: É mais fácil você formatar a data no C#.
Exemplo: String.Format("{0:MM/dd/yyyy}", VariavelDaData);
Comment: No C# ela está correta. A questão é na serelização para o json e pegar no jquery. Mas resolvi com o exemplo do maia, criando uma função para limpar a "data suja" e depois pegá-la na função principal.

Jquery não monta data corretamente


CSS para SASS converter ou não?

Question: Tenho vários arquivos em css, estou na duvida se reescrevo ele em sass para poder dar uma manutenção melhor no futuro ou não, será que é realmente vantajoso?
Comment: Não vale a pena. Primeiro que vejo como trabalho desnecessário, depois que na verdade pode dificultar a manutenção, afinal nem todo dev trabalha com SASS, SCSS etc... então vc limita muito as pessoas que mexem no código, além do mais vc tem que ter um compilador, e a pessoa pode não ter esse compilado de forma ágil. Eu não sei não, só vejo desvantagens... Mas cada um cada um. Achei sua pergunta basada em opiniões...
Comment: Amigo sempre é bom utilizar sass por questões de alterações futuras e agilidade, mas você tem que colocar na balança e analisar se vale a pena o trabalho.
Comment: Entendi, vou analisar, são muitos arquivos mais talvez seja vantagem no futuro.
Comment: Eu uso gulp para copilar e fazer outras automações de qualquer forma o dev tem que ter uma experiencia a mais para dar manutenção, o sass só seria mais uma tarefa para o gulp fazer.
Answer: É um bocado relativo e vai gerar muitas opiniões contraditórias, até porque um dos apetos positivos sobre o SASS é que não precisas converter CSS em SASS, uma vez que o SASS é uma extensão do CSS. Por outro lado, o SASS, dá-te coisas diferentes.
De seguida, apresento alguns benefícios na utilização do SASS:
- Compatível com o CSS:
Se tens bases de CSS, perceber e desenvolver SASS será pacífico. O SASS apresenta duas sintaxes diferentes, o SASS em si e o SCSS, que é o mais utilizado. A sintaxe SCSS é compatível com CSS, isso implica que se renomeares o ficheiro .css em .scss, terás o ficheiro em SCSS sem qualquer problema.
- Uso de variáveis:
Um dos grandes benefícios de usar o SASS é a capacidade de usar variáveis. Por exemplo:
$blue: #004BB4;

Depois de criar a variável, pode usá-la onde quiser:
h1 {
  color: $blue;
}

- Nested Syntax:
Por outras palavras, permite "aninhar" elementos HTML utilizando selectores CSS. Por exemplo:
.navbar {
  color: $blue;
}

- Uso de Mixins:
O uso de Mixins entra em ação quando tens blocos de código repetidos. Por exemplo:
@mixin set-font( $family: 'Ubuntu' , $weight: 400 , $style: normal ) {
  font-family: $family , 'Arial', 'Helvetica', sans-serif;
  font-style: $style;
  font-weight: $weight;
}

Depois de ter definido o Mixin, podes utilizá-lo onde quiser, usando o @include:
h1 {
  @include set-font;
  color: $blue;
}

Se precisares fazer alguma atualização ao Mixin, basta passar os parâmetros dentro da chamada @include.
h1.callout {
  @include set-font('Nunito',600);
  color: $azul;
}

- Maior comunidade e boa documentção:
Uma das grandes vantagens é sem dúvida a Documentção oficial e Comunidades.

Em suma, há muitos mais benefícios no uso dos pré-processadores CSS como o SASS, porque são sempre uma mais valia, visto que ampliam os recursos básicos de CSS, fornecendo um conjunto de funcionalidades poderosas que elevarão sua produtividade. Para além dos benefícios mencionados acima, o SASS permite-te fazer uso de herança, funções, diretivas de controlo e expressões como if (), for () ou while (), tipos de dados, interpolação, etc.
Se estas a procurar de fazer o refactoring do CSS em SASS bem estruturado, basta utilizar algumas ferramentas de conversão, como por exemplo este aqui.

CSS para SASS converter ou não?


How to make nonstandard scales on Finale?

Question: I'm trying to use the scale:

A,C,F#,A

And then:

A,B,C#,D#,F,G,A

But I'll need to input a nonstandard key signature. How can I do that?
Answer: From MakeMusic Support, after Googling 'finale non standard key signature':

Non-Standard Key Signatures allow you to create keys that are not part of the normal group of key signatures. This article will show an example of a linear key signature that mixes flats and sharps, in this case Bb and C#:

Choose the Key Signature Tool, and double-click the first measure to set the new key.
Choose Nonstandard Key.
Select Linear key, and click Next until it's Linear Key Format 2 (0 is predefined as major, 1 as minor).
Use the scrollbar above until the key signature there has the same number of symbols that you want for your piece (2 in this example). For the sake of example, we're clicking up to add two sharps.
Click on Accidental Order and Amount (AOrdAmt). Unit 1 is your first symbol, and in this example, change it to step 6 (step 0 is C, step 1 is D, etc.), and the amount to -1 (-1 is flat, 0 is natural, 1 is sharp).
Click Next to change Unit 2 (the second symbol). This is unnecessary for this example, as it's already C#.
Your Bb will be in the wrong octave; to adjust the octave placement for a Unit, click on Accidental Octave Placement (ClefOrd) and change Unit 1's octave from 1 to 0 (-1 would put it beneath the staff, etc.). Unit 2 is already correct.
Click OK, and OK again. Try entering a scale passage from D4 to D5, and click play. It should display the proper notation and play back correctly as well.


Generating data for one-class dataset

Question: In case I have a dataset that have only one class unlabeled (benign), could you please list some algorithms/papers that are used to generate complementary data (malignant) based on benign data only? I know SMOTE is there, but it's used in to generate data that is already labeled.
Comment: So you have data for only one category and you want to use it for generating data for the missing category?
Comment: @Tim. Yeah exactly. I just have one category. So I would like to generate data that is not like the one category that I have. The dataset is not labelled and has only data for one category. I would like to treat the problem as anomaly detection where anything that is not like my dataset is abnormal. But I am not sure yet what papers algorithms I can use to generate data for the other category (abnormal for example).
Answer:
I just have one category. So I would like to generate data that is not
like the one category that I have. The dataset is not labelled and has
only data for one category. I would like to treat the problem as
anomaly detection where anything that is not like my dataset is
abnormal. But I am not sure yet what papers algorithms I can use to
generate data for the other category (abnormal for example).

Imagine that your known category is pictures of humans and you want to generate pictures of non-humans. So you have to generate pictures of chimpanzees, dogs, cats, airplanes, tractors, atomic bombs, trees, planets, hamburgers, dinosaurs, screenshots of SlackOverflow.com page, hammers, hamsters, rivers, chairs, ... and an infinite number of every other thing that is not-human. Even worse if you want to generate those images from your data consisting of images of humans, how would you generate an image of an atomic bomb knowing only how humans look like? This simply cannot be done.
Comment: Thank you Tim. I forgot to add that dataset is timeseries.
Comment: @Abraheem this doesn't change much.
Comment: Thank you. So how does one-class algorithms work like OneSVM that creates a decision surface for one class and treat anything that is not within this boundary as outlier? I just want to know please if I can find similar models if you know any.
Comment: @Abraheem anomaly detection algorithms learn the distribution of the known class and classify everything that does not "look" like the known class as an anomaly. So they use the data that you have, rather than the data that you don't have.
Comment: You mean they have more than one class in their dataset not only one category that is unlabeled as in my case?
Comment: @Abraheem no, they have only one class.
Comment: Thank you. You mean, it's not possible to data that I don't have based on data that I have? What if I just want to create anything that does not look like what I have? Are there models of this kind please or the answer is still know even though we restrained what we want to generate?
Comment: @Abraheem you can. You can, for example, generate a uniformly distributed random noise and train a classifier to distinguish between your time-series and the random noise, but then if you apply the classifier to *whatever else* then your data or uniformly distributed random noise, it would be a lottery on what it predicts, because it only knows the two categories of data.

Generating data for one-class dataset


Estou tentando carregar a sessão na página principal com as diretivas do Blade, mas não carrega, por que?

Question: principal.blade.php
<!doctype html>

    Hello, world!

<code>@yield('conteudo')

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://firstname.lastname@example.com/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</code>
home.blade.php
@extends('template.principal')
@section('conteudo')
teste
@endsection[
Answer: Experimente
<code>@extends('conteudo')

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://firstname.lastname@example.com/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</code>


Lustre OST physical volume failure

Question: What happens when the physical volume of an OST is irrecoverably lost? What data is lost? Only the data stored on this OST, or everything? And, if the first is true, how can one control what data is stored on which OST? Assuming that clients see a single combined filesystem.
Answer: You lose any files which were striped onto that OST.
Lustre lets you control striping independently for each directory or file, using the lfs setstripe and lfs getstripe commands to control and view that configuration. You can configure the stripe size, stripe count, which OST to start striping on, etc.
By default Lustre has a default stripe count of 1 for each file (so that only one OST will contain that file), and subsequent files are assigned to different stripes in a round-robin fashion. However, most sites I've worked with set a default stripe of multiple OSTs for better performance. The Lustre manual has a lot more information on configuring striping.
Ideally each of your OSTs should be a RAID volume, not a single disk, so that you can guard against single-disk failures. AFAIK, Lustre doesn't provide any redundancy on its own.

Lustre OST physical volume failure


Transformation of Uniform(0,1) random variable

Question: Let $X \sim U[0,1]$. Find the pdf of $Y=4\sqrt{X}(1-\sqrt{X})$.
I have been studying transformation of random variables and came across this exercise.
Can anyone provide me a hint on how to proceed? Thanks.
Comment: [Draw the graph of $(X,Y).$](https://stats.stackexchange.com/a/138922/919)
Answer: One possible way is to compute the CDF and hen differentiate with respect to $y$.
Here's a start, try to complete it.
Let $y \in (0,1)$,
\begin{align}Pr(Y \le y)&= Pr(-4X+4\sqrt{X}-y \le 0)\\
&=Pr\left(\sqrt{X} \le \frac{1-\sqrt{1-y}}{2}\right) + Pr\left(\sqrt{X} \ge \frac{1+\sqrt{1-y}}{2}\right)\\
&=\left( \frac{1-\sqrt{1-y}}{2}\right)^2 +1- \left( \frac{1+\sqrt{1-y}}{2}\right)^2
\end{align}


How to find URLs in HTML using Java

Question: I have the following... I wouldn't say problem, but situation.
I have some HTML with tags and everything. I want to search the HTML for every URL. I'm doing it now by checking where it says 'h' then 't' then 't' then 'p', but I don't think is a great solution
Any good ideas?

Added: I'm looking for some kind of pseudocode but, just in case, I'm using Java for this project in particular
Answer: Try using a HTML parsing library then search for  tags in the HTML document.
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
Elements links = doc.select("a[href]"); // a with href

not all url are in tags, some are text
  and some are in links or other tags

You shouldn't scan the HTML source to achieve this.
You will end up with link elements that are not necessarily in the 'text' of the page, i.e you could end up with 'links' of JS scripts in the page for example.
Best way is still that you use a tool made for the job.
You should grab HTML tags and cover the most likely ones to have 'links' inside them (say:
,
,
 etc) . HTML parsers provide regex-like functionalities to filter through the content of the tags, something similar to your logic of "starts with HTTP".

[attr^=value], [attr$=value],
  [attr*=value]: elements with
  attributes that start with, end with,
  or contain the value, e.g.
  select("[href*=/path/]")

See: jSoup.
Comment: not all url are in tags, some are text and some are in links or other tags :S

by the way, I add it to my bookmarks the jSoup page for future reference, but I can't use it in this project :( I need all the urls
Answer: You may want to have a look at XPath or Regular Expressions.
Comment: Hi I'm using java, but anyway like I told to the other guys I'm trying to get all the urls on the string text, a, link, etc. Thanks to everybody that answer ;)
Answer: Use a DOM parser to extract all  tags, and, if desired, additionally scan the source for http:// outside of those tags.
Comment: not all url are in tags, some are text and some are in links or other tags :S
Comment: @Saikios : That's what I said.  The part about scanning for other links outside the tags.  The second half of my single-sentence answer.  Was it too long?
Comment: Hey, no it wasn't but if I do that what beneffit i'm going to have ... just a few href? :( my Idea was trying to do something like the str_replace using indexes or a reg_exp but i have it flying over my head
Comment: Take a look at [this](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)
Comment: I can't parse html with regex but I can eliminate everything that isn't between . .edu . .com . .gov, etc but is a really complex regex, :S
Answer: The best way should be to google for regexes. One example is this one:
    /^(https?):\/\/((?:[a-z0-9.\-]|%[0-9A-F]{2}){3,})(?::(\d+))?((?:\/(?:[a-z0-9\-._~!$&'()+,;=:@]|%[0-9A-F]{2})))(?:\?((?:[a-z0-9\-._~!$&'()+,;=:\/?@]|%[0-9A-F]{2})))?(?:#((?:[a-z0-9\-._~!$&'()+,;=:\/?@]|%[0-9A-F]{2})*))?$/i

found in a hacker news article. As far as I can follow it, it looks good. But there is, as far as I know, no formal regex for this problem.  So the best solution is to google for some and try which one matches most of what you want.
Comment: coolregex but is for something else, this is for checking if the url is a correct url but not to obtain the url's from a big string the one that I was thinking is probably bigger :P

How to find URLs in HTML using Java


ExtJS REST configuration gives Model name to ID

Question: I am working with ExtJS 5.1.1 and getting an error during POST process to Java server. Inside the DB there are several fields and ID is keyfield and generate automatically by server. I need only 3 fields to display and create/update/delete; firstName, lastName, email. I can't configure the ExtJS for POST to not touch ID, only pass those three fields via Form Panel.
Here is Request Payload of one sample record. As you will notice it gave name of Model to ID:
{"firstName":"New","lastName":"Record","email":"email@example.com","id":"Employee.model.EmployeeMdl-2"}

Therefore Java-Spring server response this message:
"Could not read document: Can not deserialize value of type int from String "Employee.model.EmployeeMdl-1": not a valid Integer value↵ at [Source: java.io.PushbackInputStream@ae6769; line: 1, column: 74]

The PUT process works very well! Could you please give any idea for POST?
Here is Model snippet:
Ext.define('Employee.model.EmployeeMdl', {
        extend: 'Ext.data.Model',
    fields: [
        {name: 'firstName', type: 'string'},
        {name: 'lastName', type: 'string'},
        {name: 'email', type: 'string'}
    ],
    idProperty: 'id',
    proxy: {
        type: 'ajax',
        headers: {
            'Content-Type': 'application/json'
        },
        api: {
            read: 'http://ip:port/orest/employee',
            create: 'http://ip:port/orest/employee',
            update: 'http://ip:port/orest/employee'
        },
        reader: {
            type: 'json'
        },
        writer: {
            type: 'json',
            allowSingle: true,
            encode: false,
            writeAllFields: true
        }
    }
});

Answer: You can provide to the model a specific way to generate the ID.
What I can recommend if integers are required is Ext.data.identifier.Negative. You would put the full class name into the requires section of the model and then just add the config identifier: 'negative' in the model.
Of course this means that you would have to tell the backend that negative ids indicate new entries.
Comment: Dear @Alexander, I have configure the Model as you told; included to requires and then defined identifier. So now `POST` and `PUT` both works well. I have checked successful `POST` record's id on DB and it saved with **ID: -1**. Here we use Java-Spring server, do you have any idea for backend to  recognize this id as provisionally generated and convert it.
Comment: I don't know how the Spring framework works, you would have to ask that in a new question with spring framework tag. It is not possible to have multiple records with the same id in ExtJS, e.g. an undefined id or zero.
Comment: Ok! dear @Alexander. That configuration works very well. Again thank you kindly for your time.
Comment: Hi again @Alexander! I will have another question, just noticed that this configuration keeps reset ID generator for each time when i close the window and open again. Therefore it keeps always 'post' with the ID: -1 and of course thats getting problem. Is there anyway to set it to increase ID?
Comment: I just tried [Sequential identifier](http://docs-devel.sencha.com/extjs/6.2.1/modern/Ext.data.identifier.Sequential.html) and set `increment` config but when its reloading the browser, it gets back to number that i defined. :(
Comment: You should use the -1, -2, ... only for the transmission of new records. They should be saved in the backend using positive ids, and the saved records returned to the client with the new ids, so that the frontend can update the ids in the store.


Radon-Nykodym approach to classic result: Left-cont. nondecreasing f on $ [a,b] \Rightarrow$ exists pos. Borel measure s.t. $ f(x)-f(a)=u([a,x))$

Question: EDIT!!!  The problem has been reduced to confirming that if for g strictly increasing left continuous and V open then g(V) is open.  The proposition is to decompose g into a continuous and singular part, but then I'm unsure of the set manipulations to confirm that for an open interval, $(g_c+g_s)(I)$ is a potentially countable union of disjoint potentially degenerate intervals.  See answer and comments, below.!!!
Struggling with exercise 7.12 part b in Rudin's Real & Complex Analysis.
$I = [a,b]$
f:I$\to\Bbb{R}$ is left continuous nondecreasing.  Show that there is a positive Borel measure s.t. $f(x)-f(a)=\mu[a,x)$.
The hint is to imitate the proof of theorem 7.18:
$g:I\to\Bbb{R}$ is continuous nondecreasing.  The following are equivalent.

$ g$ is AC on I.
$g $ maps sets of Lebesgue measure zero to sets of Lebesgue measure zero.
$f $ is differentiable; $f'\in L^1; f(x) - f(a) = \int_a^xf'd\mu$.

$1 \rightarrow 2$ by approximating the Lebesgue measure zero set by an open set (hence a disjoint union of open segments) and applying abs. cont..
$2 \rightarrow 3$

A) by defining $h(x) = x + g(x) $-- $h $ is injective; decompose any Lebesgue measurable set E to a Borel union of compact sets and a set of Lebesgue measure zero to show $m(g(E))$ is a measure;
B)  the Radon-Nikodym theorem gives the integral representation.

$3 \rightarrow 1$ is obvious.
I want to proceed analogously to the proof of $ii \rightarrow iii$ A).  But, I am struggling to show that m((f+x)(E)) is a measure.  It is clear that there are countably many points of discontinuity D by the monotonicity of f.  I'm not sure how to show that f+x sends Borel sets to Lebesgue measureable sets.
Thanks for your help!
Comment: Please stop removing the probability-theory tag:  problem 7.12 provides a nonstandard approach to a fundamental existence theorem from probability theory; search of similar questions on the exchange suggest this tag will likely attract the attention of responders most familiar with things of this sort.
Answer: I'm going to assume that $g$ is a continuous and strictly increasing function on $[a,b]$, and denote the set of Lebesgue measurable subsets of $[g(a), g(b)]$ by $\mathfrak{M}$. Put
$$
\Omega = \{E\subset [a,b]: g(E) \in \mathfrak{M}\}.
$$
It is clear that $\Omega$ is a $\sigma$-algebra. For any open subset $V$ of $[a,b]$, $g(V)$ is also open. Hence $\Omega$ contains all open subsets of $[a,b]$. By definition, $\Omega$ contains all Borel subsets of $[a,b]$. That is, for any Borel set $E$, $g(E)$ is Lebesgue measurable.
I believe you know how to proceed from here.
Comment: @entprise You can write an increasing function as the sum of a continuous one and a series of jump functions. See Stein's real analysis for the treatment (or figure it out yourself). That's probably the only part I like about Stein's treatment of differentiability.
Comment: Thanks!  I totally missed that it was an open map!  I'll try it tomorrow and upvote if it works out!
Comment: Sorry!  Late in getting back to this.  But, by assuming g is continuous it kind of makes the problem trivial.  The problem is that the discontinuities might not be isolated??
Comment: Ah.  So.  It's not the case that knowing it's left continuous allows you to directly show it sends intervals to elementary sets??  (And.  You're absolutely right that separating the jumps makes it easy.  I'm just apprehensive because the rest of the question doesn't head in "that direction")
Comment: @entprise You may find a cleaner treatment. I haven't attempted much.
Comment: So were clear (sorry, I'm on phone and cant tex):  left cont injective inc g = gc + gs where gs is the cumulation of the jumps;  g(open v) = disj union g(open interval I) = gc(I) + gs(I) where the result is perhaps countably many disjoint perhaps degenerate intervals, hence borel?
Comment: Now I can tex:

left cont inj inc $g = g_c+g_s; g_s = \sum_{y<=x}{g(y) - g(y-)}$.  So if V is open:  $V=\cup{I_i}; g(V) = \cup{g(I_i)}; (g_c+g_s)(I_i)$ is a perhaps countable union of disjoint perhaps degenerate intervals, hence borel?


React Native & Keyboard : How do I toggle the keyboard in useEffect without using TextInput?

Question: I'm writing react native using functional components.
I want to toggle and render the keyboard value without using TextInput.
<code>useEffect(() => {
    // Keyboard.addListener('handleKeyPress', handleKeyPress)
  }, []);
</code>
How do I do that? Please show me a sample code.
Comment: i usually match the style of TextInput with background
Comment: you can use an Text input and set it style is invisible
Comment: Well, is it the right way tho? It looks like we are trying to go around it.
Comment: it's the easiest way to implement. BTW, i dont see any built-in functions of Keyboard for openning it manually without using text input
Comment: I see. I will think about it. Thank you guys so much for your inputs ^^
Answer: You can match the style of TextInput with background!


How to run commands as "NT AUTHORITY\SYSTEM" under Windows Server 2008?

Question: I want to execute some commands with SYSTEM privileges on Windows Server 2008. I have Administrator privileges, of course. On the good old version of Windows without all the UAC BS this was as simple as:
at 15:48 /interactive cmd

And after a minute a command prompt would pop up, running as NT AUTHORITY\SYSTEM. But if I do this on Windows 2008 it tells me:

Warning: Due to security enhancements,
  this task will run at the time
  expected but not interactively. Use
  schtasks.exe utility if interactive
  task is required ('schtasks /?' for
  details).

I checked schtasks and it looks like that only gives you the ability to run a task interactively as the logged on user, which is not what I want. Of course, I could code and install a service that runs as SYSTEM, but what a hassle! Could anyone suggest an easier way?
I'm so sick of these hoops Microsoft is making me jump through just to do what I want to do on my system.
Answer: psexec /s [command]
Comment: To get psexec: (1) download PSTools from http://sysinternals.com (which will redirect into MS), (2) extract contents of ZIP into folder in PATH (or add the folder you use to the PATH).
Answer: If you just want to run a command prompt (or any app) as SYSTEM then use psexec as vu1tur suggests. As for running scheduled tasks interactively, this is surely a matter of opinion, but I've always thought that Windows should not allow scheduled tasks to run interactively as it's such a big security risk. Microsoft have changed the behaviour in W2k8, and I'm on their side this time.


"O melhor método sobrecarregado compatível tem alguns argumentos inválidos"

Question: Estou criando um serviço com um método que tem um argumento do tipo List<OrdemPais>(), e passando um objeto desse tipo para o método, porém na hora compilar aparece o erro:
O melhor método sobrecarregado compatível com 'Mahikari.Business.Domain.OrdemPaisVigencia.SetOrdensPaises(System.Collections.Generic.List<Mahikari.Business.Domain.OrdemPais>)' tem alguns argumentos inválidos

Essa é a parte do código que o método é chamado:
protected void salvar_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        SalvarEstadoOrdem();

        List<OrdemPais> OrdemPaisList = new List<OrdemPais>();

        OrdemPaisVigencia.Vigencia = dteVigencia.SelectedDate.Value;

        List<OrdemPais> ordemPaises = new List<OrdemPais>();
        foreach (KeyValuePair<int, int> ordem in ordens)
        {
            var o = new OrdemPais(ordem.Key, ordem.Value);
            ordemPaises.Add(o);
        }

        try
        {
            OrdemPaisVigencia.SetOrdensPaises(ordemPaises);

            paisService.SaveOrdemPais(OrdemPaisVigencia);
        }
        catch (Exception ex)
        {

        }

        Response.Redirect("OrdemPais.aspx", true);
    }

O método em si:
public void SetOrdensPaises(List<OrdemPais> ordemPaises)
    {
        if (ordemPaises.Any())
            this.Validation.Errors.Add(MainResource.Mensagem_ListaNaoPodeEstarVazia);

        this.OrdemPaises = ordemPaises.OrderBy(or => or.Ordem).ToList();
    }

Comment: @EricWu  Era exatamente isso, a classe(que está em outra DLL) tinha o mesmo nome de uma página, por isso dava o erro. Se quiser pode responder a pergunta para eu marcar como resposta!
Comment: O erro é na compilação ou na execução?
Comment: Compilação, e o mais estranho é que não sinaliza com o sublinhado vermelho embaixo(que normalmente fica no visual studio quando está errado).
Comment: Não consigo identificar nenhum problema vendo só isso. Pode estar me escapando algo. Mas esse código tem várias coisas esquisitas. Sei lá se o problema pode estar sendo causado por alguma outra coisa. Se conseguir fazer um [mcve] pode ser mais fácil ajudar.
Comment: Vou colocar o método inteiro desse trecho de código, o que tem esquisito @bigown ?
Comment: É estranho porque tanto a chamada quanto a assinatura _aparentemente_ tem o mesmo tipo. Certifica de que o `OrdemPais` em  `List ordemPaises = new List();` é exatamente o mesmo em `SetOrdensPaises(List ordemPaises)`.
Quero dizer, se não estão sendo referenciados de DLLs separadas apesar de terem o mesmo nome.
Answer: Certifique-se de que o OrdemPais em
List<OrdemPais> ordemPaises = new List<OrdemPais>();

é exatamente o mesmo OrdemPais em
SetOrdensPaises(List<OrdemPais> ordemPaises);

Se eles têm o mesmo nome, mas estão em namespaces diferentes, eles são essencialmente tipos diferentes.


Call internal pages with drupal_http_request

Question: I'm writing a little module, and I need to call several pages of my site using drupal_http_request(), which accepts only absolute URLs.
I don't want to add a variable to store the domain of the site, also because on my company we have proxy etc.
Which is the best way to add the domain of the site?
Comment: I'm not quite sure what you mean exactly, but have you looked at [`global $base_url`](http://api.drupal.org/api/drupal/developer!globals.php/global/base_url/7) ?
Comment: Hello, and welcome to Drupal Answers. I guess you want the absolute URL of the web server from which you call `drupal_http_request()`. Is  there any reason why you cannot use `url('', array('absolute' => TRUE))`? Did you try it?
Comment: If my page is "page" and I try to run
`$url = url('page', array('absolute' => TRUE))`, `$url` seems to be `http://default/page`.
Comment: I can use $_SERVER['HTTP_HOST'] but I don't know if works always..
Answer: Here is what I'm using in a similar situation, with $base_url as Baysaa mentioned above.
$path_to_file = '/path/to/feed.xml';
$base_url = $GLOBALS['base_url']; // Not sure if this line is necessary.
$file_over_http = $base_url . $path_to_file;
$http_result = drupal_http_request($file_over_http);

Comment: I think you can use `GLOBAL $base_url` as well.


Calculate norm of a polynomial knowing inner product but not the polynomials themselves

Question: In $\mathbb R[t]_2$ (vector space of all polynomials of up to a second degree), I need to compute the norm $||t^2 - 2t + 1||$, knowing only that:
$$\langle p(t),q(t)\rangle = p(-2)q(-2) + p(-1)q(-1) + p(0)q(0) + p(1)q(1)$$
I have absolutely no clue on how to compute it as I don't have the polynomials $p(t)$ and $q(t)$.
Do I need to assume $p(t)$ and $q(t)$ generic polynomials, such as $p(t) = a + bt + ct^2$ and $q(t) = d + et + ft^2$, where $a,b,c,d,e,f$ would be scalars in $\mathbb R$?
Comment: Yes, you have to assume that. In this way your inner product will be given as an expression in $a,b,c,d,e,f$ uniquely.
Comment: So when I compute the inner product using the generic polynomials I mentioned, I get:

-2ea+4ad+6af+6eb-8ec-2bd+6cd-8bf+18cf

How does this relate to the norm I need to compute?
Comment: Take $a=d=1,b=e=-2,c=f=1$
Answer: Just plug into your formula:
\begin{align}
\|t^2-2t+1\|^2 &= \|(t-1)^2\|^2\\
&= \langle (t-1)^2, (t-1)^2\rangle\\
&= (-2-1)^2(-2-1)^2 + (-1-1)^2(-1-1)^2 + (0-1)^2(0-1)^2 + (1-1)^2(1-1)^2\\
&= 81+16+1\\
&= 98
\end{align}
so $\|t^2-2t+1\|=\sqrt{98}$.
Answer: As you have computed once for all the expression
$$\langle p,q \rangle=-2ea+4ad+6af+6eb-8ec-2bd+6cd-8bf+18cf,$$
said otherwise
$$(a \ \ b \ \  c)\underbrace{\left(\begin{array}{rrr}2&-1&3\\-1&3&-4\\3&-4&9\end{array}\right)}_A\begin{pmatrix}d\\e\\f\end{pmatrix},$$
it is not lost time if you are asked to calculate other norms.
Moreover, and this is the most important, due to the fact that the eigenvalues of symmetric matrix $A$ are positive ($0.5815,$$1.4351,$ $11.9834$) it proves that this inner product is associated with a "true" norm, which isn't a priori evident (triangular inequality is lengthy by direct means).