given java class name and a pair of jar files, find the parent classname in each jarfile

Question: I'm writing a tool which is supposed to determine what classes have changed when a system is upgraded. What i have as input are:
1 - the jar file used with the pre-upgraded system
2 - the jar file used with the post-upgraded system
3 - a list of classes and their purpose that I care about
      asset init package1.myasset.class
      asset terminate package1.assetterminate.class
      etc.
What I want to do is be able to load the jar that comes with the new system and the jar that came with the old system and determine if a given class has the same parent after the change that it did before the change. i.e. if in the new system asset init
1 - is still package1.myasset.class and
2 - is still an extension of package0.generalasset.class
I assume I can use reflection but I'm not sure how to determine what a given classes parent is in each jar to see if it changed.
The jars are not necessarily used directly (runtime) by my tool - in fact they shouldn't really be used except as an input to the analysis of the system change.
Comment: if I was in your shoes, since you don't actually have to use these jars, I'd extract the classes (or list the jar contents), sort and diff both using unix tools.
Comment: but, if you still want to use reflection, I suggest you to take a look at http://code.google.com/p/reflections/
Answer:
You need two URLClassLoaders, one for each JAR file.
Process your list of classes and load each one in turn via both classloaders.
Do not attempt to cast them, they are just Class<?> at this stage.
Call Class.getSuperClass() on each, and then getName() on each parent class.
Compare.
Comment: Hi and thank you. I ended up using a snippet I found on this site which adds the jar file(s) to the system class loader. This is very close to what I ended up finding useful... it was the "flawlessly" answer here to another question: http://stackoverflow.com/a/60766/339274
Answer: Although there are many possibly important changes to a class other than its (single) parent, if that's really all you need I wouldn't bother with code, I'd just put both jars on a system with JDK and do:
javap -classpath jar1 aclassname |grep extends
javap -classpath jar2 aclassname |grep extends
# or substitute findstr on unimproved Windows
# repeat for multiple classes as desired

If you want to look for any change in the "public API", the full javap output is a good start.


How to use subquery in views where clause

Question: In my project user can created by profile2 module. When user is created i am assigning some role,initially user is block state. I have another user role ie.user app rover  who can approved these user and send activation link for active user.
I am using Mail Logger module for saving sending mail
Now i have created a view for user unapprove list
    SELECT users.name AS users_name, users.uid AS uid, users.mail AS users_mail,
    profile_users.pid AS profile_users_pid, users.created AS users_created, 'profile2' AS
    field_data_field_cc_first_name_profile2_entity_type, 'profile2' AS
    field_data_field_cc_address_office_profile2_entity_type, 'profile2' AS
    field_data_field_cc_designation_profile2_entity_type
         FROM
         {users} users
         LEFT JOIN {profile} profile_users ON users.uid = profile_users.uid AND
         profile_users.type IN ( 'company', 'goverment_profile' )
         WHERE (( (users.status = '0') AND (users.login = 0) AND (profile_users.type IN
            ('company', 'goverment_profile')) ))
            ORDER BY users_created DESC
            LIMIT 10 OFFSET 0

Hear i want to add sub-query in where condition
user those already send activation link who will not list in view.
My other table is mail_logger.
Is there any module by which i can use sub-query in where condition?
Answer: Just ran into the same question, here is what I found:
You can add a sub query to your view using the hook_views_query_alter hook in a custom module (documentation). Inside the module you should add something like the following:
function your_module_views_query_alter(&$view, &$query) {
  if ( $view->current_display == '[display in question]'){
    $query->add_where_expression([group], [sub query]);
  }
}

documentation for $query->add_where_expression.  You can add whatever where clause you need using this function.
hook_views_query_alter should go in your_module.views.inc.  Make sure you declare hook_views_api in your_module.module, otherwise views wont know to look for the file. For example:
function your_module_views_api() { // declare your views api # here
  return array(
    'api' => 3,
  );
}


Critical points of a matrix equation

Question: The question I am trying to solve is: how to find the critical points of a matrix equation
$$X^{2}-BX-C=0?$$
And then if I  follow the method of http://www2.math.umd.edu/~jmr/241/crits.html, first I should find the Jacobian, and there is where i find a doubt: How is it the differentiation of a matrix with respect to a matrix, I mean: I have a function depending on $X$,
$$f(X)=X^{2}-BX-C,$$
where $X$ is the variable and is a square matrix; $B$, $C$ are constant square matrices.
How should be the Jacobian? Is that correct to find the critical points in that way for matrix equation?.
Answer: Yes, to find the zeros of the derivative is the right way to find the critical points. Note that for your function $f \colon \def\Mat{\mathop{\rm Mat}\nolimits}\def\R{\mathbb R}\Mat_n(\R)\to \Mat_n(\R)$ we have for $X, H \in \Mat_n(\R)$ (I think it is easier to compute the derivative here using the definition):
\begin{align*}
  f(X+H) &= A(X+H)^2 - B(X +H) - C\\
         &= AX^2 - BX - C + AXH + AHX - BH + AH^2\\
         &= f(X) + AXH + AHX-BH + o(\|H\|).
\end{align*}
So $f'(X)H = AXH + AHX-BH$. To compute the zeros, it may be helpful to vectorize, we have $\def\vec{\mathop{\rm vec}\nolimits}\def\Id{\mathop{\rm Id}\nolimits}$
$$ \vec(f'(X)H) = \vec(AXH) + \vec(AHX)-\vec(BH) = (\Id \otimes (AX-B))\vec(H) + (X^t \otimes A)\vec(H) $$
So $f'(X) = 0$ iff $\Id \otimes (AX-B) = -X^t \otimes A$.
Comment: Should I find the solution of $$Id⊗(AX−B)=−X^t⊗A$$ and that would be a critical point, right?
Comment: @GinaTorres Yes, it would.
Comment: If A is a identity, what should I do? because when I vectorize I find that $(Id⊗(X−B))vec(H)+(Id⊗H)vec(X)$ it looks bad to solve it.
Comment: Should I choose H as any invertible matrix right? If it is not it doesn't work.
Answer: Consider the mapping $f \, : \, \mathcal{M}_{n}(\mathbb{R}) \, \rightarrow \, \mathcal{M}_{n}(\mathbb{R})$ defined by :
$$\forall X \in \mathcal{M}_{n}(\mathbb{R}), \; f(X) = AX^{2}-BX-C$$
Let $X$ be a matrix in $\mathcal{M}_{n}(\mathbb{R})$, you can determine the differential of $f$ at $X$ (it is a linear mapping from $\mathcal{M}_{n}(\mathbb{R})$ to itself whose matrix is the Jacobian matrix). To do so : take some matrix $H$ and consider $f(X+H)$.
We have:
$$
\begin{eqnarray*}
f(X+H) & = & A(X+H)^{2} - B(X+H) - C \\
       & = & A\big( X^{2} + XH + HX + H^{2} \big) - BX - BH - C \\
       & = & f(X) + AXH + AHX - BH + H^{2} \\
\end{eqnarray*}
$$
It proves that :
$$ \mathrm{D}_{X} f \cdot H = AXH + AHX - BH $$
The critical points of $f$ are such that :
$$ \forall H, \; (AX-B)H = - AHX $$
However, I don't know it these critical points can be determined in closed form. This article http://imajna.oxfordjournals.org/content/20/4/499.full.pdf+html presents numerical methods which can be used to solve quadratic matrix equations such as $AX^{2}-BX-C$.
Comment: If $A$ is the identity matrix, you have to find $X$ such that :

$$ (X-B)H=-HX $$

holds for any $H$, not just the identity matrix.
Comment: Which is the relationship between the critical points and the solutions found for $AX^2−BX−C=0$?
Comment: I don't think there exists a particular relationship between matrices $X$ such that $AX^{2}-BX-C=0$ (the zeros of $f$) and the critical points of $f$. For example, if $A$ is invertible, $f$ has $1$ critical point which is $X = \frac{1}{2}A^{-1}B$. At this point, $f(X) = -\frac{1}{4} BA^{-1}B - C$. There is no reason for $f(X)$ to be zero. Conversely, if you take a matrix $X$ such that $AX^{2}-BX-C = 0$, I don't see why it would be a critical point of $f$.
Comment: Ok I understood and yes A is invertible, Thanks. And last point: Should X as a critical point make $Id⊗(AX−B)=−X^t⊗A$ in @martini 's equation, because I have proved it numerically and both sides of the equation are different I don't know why.
Comment: I don't know what $\mathrm{Id} \otimes (AX-B)$ means. $X$ is a critical point of $f$ if, for all matrix $H$, we have :

$$ AXH+AHX-BH = 0 $$

which is equivalent to ask that

$$ (AX-B)H = -AHX $$

for all $H$. I guess it means the same thing.
Comment: In martini's answer appears after vectorizing  $f′(X)H=AXH+AHX−BH$, he says that $f′(X)=0 iff Id⊗(AX−B)=−X^t⊗A$, $⊗$ is the kronecker product. So what I did was to test if the X critical point found with your equation demonstrate his equation. But doesn't. However, I understand your point and I guess maybe i am commiting a mistake somewhere.
Comment: No, you're right. If I take $X = \frac{1}{2}A^{-1}B$, then we don't have $(AX-B)H=-AHX$ for all $H$. I'll edit my post.
Comment: But how are the critical points, then?. Does $X=1/2 A^{−1}B$ continue being a critical point in the way you have recommended?
Comment: I don't know if the critical points of $f$ can be determined in closed form. I think it can't. Have a look at http://imajna.oxfordjournals.org/content/20/4/499.full.pdf+html (I will edit my post). If that doesn't answer your question, try asking about it on Math.SE!
Comment: I have written equation as AX^2-BX-C=0 but A is a identity matrix, so if it is the identity $(X−B)H=−HX$ is as well correct, right? And in thi case how should I consider H? identity for example?
Comment: But is that possible, because here I have one more matrix variable H? one equation and 2 variables (X,H), so infinite solutions, isn't it?

Critical points of a matrix equation


How does support vector regression work intuitively?

Question: All the examples of SVMs are related to classification. I don't understand how an SVM for regression (support vector regressor) could be used in regression.
From my understanding, A SVM maximizes the margin between two classes to finds the optimal hyperplane. How would this possibly work in a regression problem?
Answer: In short: Maximising the margin can more generally be seen as regularising the solution by minimising $w$ (which is essentially minimising model complexity) this is done both in the classification and regression. But in the case of classification this minimisation is done under the condition that all examples are classified correctly and in the case of regression under the condition that the value $y$ of all examples deviates less than the required accuracy $\epsilon$ from $f(x)$ for regression.

In order to understand how you go from classification to regression it helps to see how both cases one applies the same SVM theory to formulate the problem as a convex optimisation problem. I'll try putting both side by side.
(I'll ignore slack variables that allow for misclassifications and deviations above accuracy $\epsilon$)
Classification
In this case the goal is to find a function $f(x)= wx +b$ where $f(x) \geq 1$ for positive examples and $f(x) \leq -1$ for negative examples. Under these conditions we want to maximise the margin (distance between the 2 red bars) which is nothing more than minimising the derivative of $f'=w$.
The intuition behind maximising the margin is that this will give us a unique solution to the problem of finding $f(x)$ (i.e. we discard for example the blue line) and also that this solution is the most general under these conditions, i.e. it acts as a regularisation. This can be seen as, around the decision boundary (where red and black lines cross) the classification uncertainty is the biggest and choosing the lowest value for $f(x)$ in this region will yield the most general solution.

The data points at the 2 red bars are the support vectors in this case, they correspond to the non-zero Lagrange multipliers of the equality part of the inequality conditions $f(x) \geq 1$ and $f(x) \leq -1$
Regression
In this case the goal is to find a function $f(x)= wx +b$ (red line) under the condition that $f(x)$ is within a required accuracy $\epsilon$ from the value value $y(x)$ (black bars) of every data point, i.e.  $|y(x) -f(x)|\leq \epsilon$ where $epsilon$ is the distance between the red and the grey line. Under this condition we again want to minimise $f'(x)=w$, again for the reason of regularisation and to obtain a unique solution as the result of the convex optimisation problem. One can see how minimising $w$ results in a more general case as the extreme value of $w=0$ would mean no functional relation at all which is the most general result one can obtain from the data.

The data points at the 2 red bars are the support vectors in this case, they correspond to the non-zero Lagrange multipliers of the equality part of the inequality condition $|y -f(x)|\leq \epsilon$.
Conclusion
Both cases result in the following problem:
$$ \text{min} \frac{1}{2}w^2 $$
Under the condition that:

All examples are classified correctly (Classification)
The value $y$ of all examples deviates less than $\epsilon$ from $f(x)$. (Regression)
Answer: In SVM for classification problem we actually try to separate the class as far as possible from the separating line (Hyperplane) and unlike logistic regression, we create a safety boundary from both sides of the hyperplane (different between logistic regression and SVM classification is in their loss function).
Eventually, having a separated different data points as far as possible from hyperplane.
In SVM for regression problem, We want to fit a model to predict a quantity for future. Therefore, we want the data point(observation) to be as close as possible to the hyperplane unlike SVM for classification.
The SVM regression inherited from Simple Regression like (Ordinary Least Square) by this difference that we define an epsilon range from both sides of hyperplane to make the regression function insensitive to the error unlike SVM for classification that we define a boundary to be safe for making the future decision(prediction).
Eventually, SVM in Regression has a boundary like SVM in classification but the boundary for Regression is for making the regression function insensitive respect to the error but the boundary for classification is only to be way far from hyperplane(decision boundary) to distinguish between class for future (that is why we call it safety margin).


How to create a 5x5 matrix with increasing numbers in java?

Question: i am trying to create a 5x5 matrix using for loops but i can not do it, i've been looking for it for a day but still i could not figure it out, so i gave up and asking for a help now.
 I need a matrix like;
 1  0  0  0  0
 2  3  0  0  0
 4  5  6  0  0
 7  8  9 10  0
11 12 13 14 15

I did the matrix full of zeros;
 public class ExampleClass{
 public static void main(String args[]) {

    int[][] Example =    new int [5][5];

        for(int i=0;i<Example.length;i++){
            for(int k=0;k<Example.length;k++)
            System.out.print(Example[i][k]+" ");
            System.out.println();

       }
    }
}
output:
           0  0  0  0  0
           0  0  0  0  0
           0  0  0  0  0
           0  0  0  0  0
           0  0  0  0  0

Answer: I would do this with another variable, let's say it's called c:
int c = 1;
for(int i=0;i<Example.length;i++){
  for(int k=0;k<Example.length;k++)
    if (k <= i) {
      System.out.print(c++ +" ");
     } else {
       System.out.print(0 +" ");
     }
  System.out.println();
}

Or if you want also the proper spacing:
int c = 1;
for (int i = 0; i < Example.length; i++) {
    for (int k = 0; k < Example.length; k++) {
        if (k <= i) {
            if (c < 10) System.out.print(" ");
            System.out.print(" " + c++);
        } else {
            System.out.print("  " + 0);
        }

    }
    System.out.println();
}

This outputs:
  1  0  0  0  0
  2  3  0  0  0
  4  5  6  0  0
  7  8  9 10  0
 11 12 13 14 15

Comment: thank you so much for the answer. this example made me crazy, you just saved my mental health haha.
Comment: This will only print the pattern but it will not initialize `Example[][]`.
Comment: Just add `int[][] Example =    new int [5][5];` before as it was in the question :)
Comment: @Balastrong - You are still not there. The statement, `int[][] Example = new int [5][5];` will initialize the array with default values which are `0`; not with the values which you have printed. If you want to use the array later in the program, all the indices will have `0` instead of the values which you have printed.
Answer: The values are below the main diagonal, including it. All these values are on the positions which i is less or equal to j, where i is the line index and j is the column index in the example below.
public static void main( String[] args ) {

    int[][] m = new int[5][5];
    int count = 1;

    for ( int i = 0; i < m.length; i++ ) {
        for ( int j = 0; j < m.length; j++ ) {
            if ( j <= i ) {
                m[i][j] = count++;
            } else {
                m[i][j] = 0;
            }
        }
    }

    for ( int i = 0; i < m.length; i++ ) {
        for ( int j = 0; j < m.length; j++ ) {
            System.out.printf( "%2d ", m[i][j] );
        }
        System.out.println();
    }

}

If you just need to print the values, you can do something like:
public static void main( String[] args ) {

    int size = 5;
    int count = 1;

    for ( int i = 0; i < size; i++ ) {
        for ( int j = 0; j < size; j++ ) {
            if ( j <= i ) {
                System.out.printf( "%2d ", count++ );
            } else {
                System.out.printf( "%2d ", 0 );
            }
        }
        System.out.println();
    }

}

Answer: Do it as follows:
public class Main {
    public static void main(String[] args) {
        int[][] example = new int[5][5];
        int x = 1;

        // Initialize
        for (int i = 0; i < example.length; i++) {
            for (int k = 0; k <= i && k < example[i].length; k++) {
                example[i][k] = x++;
            }
        }

        // Display
        for (int i = 0; i < example.length; i++) {
            for (int k = 0; k < example[i].length; k++) {
                System.out.printf("%3d", example[i][k]);
            }
            System.out.println();
        }
    }
}

Output:
  1  0  0  0  0
  2  3  0  0  0
  4  5  6  0  0
  7  8  9 10  0
 11 12 13 14 15

Also, always follow Java naming conventions e.g. the variable, Example should be named as example.


How to parse Firebase DataSnapshot value correctly

Question: I have to receive a username that has a fullName equal to "Bobby". So I'm trying to get data from Firebase Database using the following syntax:
ref.orderByChild("fullName").equalTo("Bobby").addListenerForSingleValueEvent(new ValueEventListener() {...}

What I get from dataSnapshot.getValue() is this:
{id3={username=bob, score=150, fullName=Bobby}}

I would like to know what is the best or correct way to get the username if I do not know which id number was returned?
Currently I'm achieving it this way:
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("Scores");

    ref.orderByChild("fullName").equalTo("Bobby").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG, "dataSnapshot value = "+dataSnapshot.getValue());
            if(dataSnapshot.hasChildren()){
                Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
                DataSnapshot snap = iter.next();
                if(snap.hasChildren() && snap.getValue() instanceof HashMap) {
                    HashMap map = (HashMap) snap.getValue();
                    if(map.containsKey("username")) {
                        Log.i(TAG, "onDataChange: username = " + map.get("username"));
                    }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

EDIT:
The Database structure is looking like this:
     {
      "Scores" : {
        "id1" : {
          "fullName" : "Robert",
          "score" : 96,
          "username" : "rob"
        },
        "id2" : {
          "fullName" : "Michael",
          "score" : 87,
          "username" : "mike"
        },
        "id3" : {
          "fullName" : "Bobby",
          "score" : 150,
          "username" : "bob"
        }
      }
    }

Thanks in advance.
SUMMARY:
Using wilkas' answer I came to the following code snippet to get the wanted result:
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("Scores");

    ref.orderByChild("fullName").equalTo("Bobby").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.i(TAG, "dataSnapshot value = "+dataSnapshot.getValue());
            if(dataSnapshot.hasChildren()){
                Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
                while (iter.hasNext()){
                    DataSnapshot snap = iter.next();
                    String nodId = snap.getKey();
                    String username = (String) snap.child("username").getValue();

                    //received results
                    Log.i(TAG, username + " on nod " + nodId);
                }

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

It works well when several entries have a fullName equal to 'Bobby'.
Comment: Post your entire json structure
Comment: Please post a representative snippet of your JSON (as text, not as a screenshot). You can easily get this by clicking the Export JSON link in [your Firebase Database console](https://console.firebase.google.com/project/_/database/data/). Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do.
Answer: Since you add listener under Scores, your childs are id1, id2 and id3. By adding query .orderByChild("fullName").equalTo("Bobby") you filter by subchild and get one result id3. So your first datasnapshot refers to one child id3 (though there could be more children if they would have same name of "Bobby").
In order to get the username, you need to iterate each received child (as you correctly do) - in this case only one child is iterated - and then get child username of that iterated child.
Since you know that every idX contains these children: username, score, fullName. You can easily extract username as follows (in your case snap is  reference to child id3):
String username = (String) snap.child("username").getValue();
String fullName = (String) snap.child("fullName").getValue();
long score = (long) snap.child("score").getValue();

Furthermore you can retrieve id too as follows:
String recordId = snap.getKey();

Within the inner iteration you could also get username as follows:
String recordId = snap.getKey();
String username = (String) dataSnapshot.child(recordId).child("username").getValue();


Visual Studio 2012 - Automatically Get Latest Version

Question: I've been bumping into an issue lately where developers on our team (mostly me) have a tendency to open a project and forget to Get Latest Version before coding and we end up making new changes to old code.
It'd be nice if Visual Studio would know that I'm about to make new changes on old code and either warn me or automatically grab the latest version for me.
Is this possible?
EDIT: I forgot to mention I'm using TFS
Comment: I'm using TFS. Sorry, I forgot to mention in the question.
Comment: If using Team Foundation Server see this [post](http://stackoverflow.com/questions/4722366/automatically-get-latest-version-when-you-open-solution-project).
Comment: You didn't mention what version control you are using. I don't think that there is anything Visual Studio can do to detect if your code is out of date. If you used something like Git, you could just make sure to initiate a Pull before writing any new code (in fact if you used Git, it requires you to Pull before being able to Push if your local repository is not current with the remote repository).
Comment: Thanks. Looks like @JayMee has your answer.
Comment: It's mentioned that that particular solution is considered bad practice and was removed from the 2015 version of VS. Why is it considered bad practice?
Answer: Good question, and fortunately for you the answer is 'yes' (since you're using TFS as specified in your comment).
Go to Tools > Options > Source Control (on the left) > Environment and ensure 'Get everything when a solution or project is opened' is checked.
I must add, though, settings like this shouldn't really be used as a substitute for good habits and best practices. You and your team should be aware of the importance of 'get latest' to the point whereby you want to get latest and don't want to work without it (if you're at that stage in the project).
Potential 'downsides' to this:
On the odd occasion, you'll hear our team members say "don't get latest yet". Because of a bad check-in they've made. If they break the build - you'll get that broken build. Not an ideal scenario, it should never happen, but the reality is that it does. You lose an element of that control if it does it automatically.
Not to mention the fact that if your team are forgetting to get latest, there's an even bigger chance of them forgetting to check the changeset for potential issues. The 'resolve conflict' dialog doesn't always highlight every issue you need to be aware of.
I suppose a really minor downside could also be the start-up time of the project (one of the reasons Microsoft more recently got rid of this feature as you mentioned). You're not just opening a solution anymore, you're opening it and waiting for a get latest. Which could, then, require further attention (conflict resolution).
I'm possibly rambling now - but what about when you take on juniors that might not be familiar with source control concepts such as get latest? If it's always been taken care of, they might miss a trick. For example, hypothetically, VS opens but fails to connect to the TFS server as it's temporarily down. Could this cause an already forgetful team to explicitly get latest at a later date?
Comment: Well, I definitely WANT to Get Latest Version... I just forget every once in a blue moon. My fault, for sure. You mention best practices, is there a downside to using 'Get everything when a solution or project is opened'?
Comment: Thanks for the clarification. To summarize then, best practice is to do it manually and force yourself to remember. The automatic option is convenient but can cause the user to be too reliant on it and cause problems if another dev checks in bad code or VS can't connect to the TFS server?
Comment: It's up to you to be honest mate. We're now venturing into the territory of opinion and whether it suits individual teams or not. Try both approaches, and choose what works for you.
Comment: Thanks for your help!


How to iterate through non-zeros values of an image ? - Python

Question: I have fond online a function to extract and display the dominant colors of an image. To save time, I want to iterate only on the non-zeros pixels instead of the whole image. However the way I changed the function raises an error :
   if row != [0,0,0]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Here is the modified code :
def dominantColor(image) :
    from matplotlib.pyplot import imshow, show
    from scipy.cluster.vq import whiten
    from scipy.cluster.vq import kmeans
    import pandas as pd

r = []
g = []
b = []
for row in image :
    if row != [0,0,0]: #the part I added to the original code
        print(row)
        for temp_r, temp_g, temp_b in row:
            r.append(temp_r)
            g.append(temp_g)
            b.append(temp_b)

image_df = pd.DataFrame({'red': r, 'green': g, 'blue': b})
image_df['scaled_color_red'] = whiten(image_df['red'])
image_df['scaled_color_blue'] = whiten(image_df['blue'])
image_df['scaled_color_green'] = whiten(image_df['green'])

cluster_centers, _ = kmeans(image_df[['scaled_color_red','scaled_color_blue','scaled_color_green']], 3)
dominant_colors = []
red_std, green_std, blue_std = image_df[['red','green','blue']].std()
for cluster_center in cluster_centers:
    red_scaled, green_scaled, blue_scaled = cluster_center
    dominant_colors.append((
        red_scaled * red_std / 255,
        green_scaled * green_std / 255,
        blue_scaled * blue_std / 255
    ))
imshow([dominant_colors])
show()

return dominant_colors

How should I correct my iteration loop to remove the error and have only the non-zeros values of my image ? (NB : the image is actually mask * original_image)
Answer: You need to add .all() method after that comparison if you want co compare arrays element wise. So if (row == [0,0,0]).all().
import numpy as np

image = np.array([
    [0, 0, 0],
    [1, 0, 0],
    [0, 0, 1],
])

for row in image:
    if not (row == [0, 0, 0]).all():
        print(row)

Result:
[1 0 0]
[0 0 1]

Comment: Thank you for your help ! I tried both .all() and .any() method copy pasting your syntax, however it seems the zero values are still taken into account. The `print(row)` line I added right after the `if` loop prints stuff like this :
 `[[0 0 0]
 [0 0 0]
 [0 0 0]
 ...
 [0 0 0]
 [0 0 0]
 [0 0 0]]`
while the code is running. How is that possible ?...
Comment: `if (row == [0,0,0]).all()` what is that supposed to mean? are you call `all` on a `bool`?
Comment: Not a bool, but array of booleans. `print(np.array([0, 0, 1]) == [0, 0, 0])` => `[ True  True False]`.
Comment: Thank you for your help ! I don't get why I still have `[[0 0 0]  [0 0 0]  [0 0 0]  ...  [0 0 0]  [0 0 0]  [0 0 0]]` and only zeros printed in my terminal but I guess it works anyway and is faster ! Thank you !
Answer: If I understand your code correctly, the answer is in the error log that you posted:

if row != [0,0,0]:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

So, the any function check if any of the elements in the row are evaluated as true:
for row in image :
    if any(row): #enter the if block if any element is not 0
        print(row)
        for temp_r, temp_g, temp_b in row:
            r.append(temp_r)
            g.append(temp_g)
            b.append(temp_b)

Comment: Thank you for your answer ! Is it normal that after correcting as you suggested, I still have arrays of 0 printed in my terminal ? should'nt they be ignored if the zeros values led to not entering the ìf` loop ?
Comment: I did an edit, can you try now?


infinite sequence of graphs

Question: For which natural $k$ this statement is correct:
Let $G_1 , G_2, G_3 ... $ be an infinite sequence of graphs. In each of them there are simple paths no longer than $k$. Then it exists $i \neq j$ such that $G_i$ is isomorphic with some subgraph of $G_j$.
I can prove this statement for $k = 1$.
Comment: Proceed by induction on k?
Comment: Do you know that the statement is false for some $k$?
Comment: @Math_QED Wow, you have found a solution already? What is it? What's the least $k$ for which the statement is false, or is it true for every $k$?
Comment: Adrian Gąsiorowski: Are you sure you've stated the problem correctly? Unless I'm missing something, the claim is false, for all $k$, even for $k=1$, Can you show your work for the case $k=1$?
Comment: I didn't find a solution. I suggested using induction if you already had proved it for k = 1. If the statement fails for some k, you should see where in your attempt at a proof. This is how mathematics is done.
Comment: @quasi look at my answer below
Comment: @Math_QED I have tried to find an example and counterexample of $G_i$s for $k = 2$, but I couldn't
Answer: I proved it for $k=1$ like this:
Let think how graphs with $k = 1$ look like. Every graph like that consists of some "pairs" of vertices connected by single edge and some "lonely" vertices.
If there exists $M$ such that every of $G_i$ has no more than $M$ vertices, then there exists identical graphs $G_k$ and $G_l$, because there is only finite number of nonisomorphic graphs with maximum $M$ vertices.
Suppose that for every $M$ exists some $G_i$ such that it has more than $M$ vertices. Let $G_k$ be a graph with minimum number of edges from all $G_i$s (or any of graphs with minimum number of edges, if there are more than one). Then we can take some $G_j$ such that it has more vertices than $G_k$ and at least the same number of edges as $G_k$. Remove some edges from $G_j$ until it will have the same number of edges as $G_k$. Then remove some vertices until it will have the same number of vertices as $G_k$. So $G_j$ and $G_k$ meet the requierments of the statement.
Comment: Based on your above proof, I think you need to edit the statement of the problem. I think the intended statement is this: For which nonnegative integers $k$ is the following statement true: If $G_1,G_2,G_3,...$ is an infinite sequence of finite simple graphs such that, in each graph, all paths have length at most $k$ (i.e., each graph has diameter at most $k$), then there exists a pair $G_i,G_j$ with $i \neq j$ such that $G_i$ is isomorphic with some subgraph of $G_j$.
Comment: Using my suggested edit, the statement is trivially true for the case $k=0$, and the proof you posted shows that it's also true for $k=1$. It's a nice problem, and the answer is not immediately obvious (at least not to me). I think it's true for all $k$, but I'm not sure. My suggestion: Play with the case $k=2$. And then perhaps try $k=3$. If the claim holds for both of those cases, try for a proof by induction.

infinite sequence of graphs


How to pass content type filter to taxonomy

Question: I created a classified ad website with different content type like vehicle, clothing, mobile phone, computers, etc. Within this content type has a field called location. A location field is an address of the item posted on my website like cities.
My question is on how can I filter location plus the content type. Currently, when I click the location, all of the content type article shows.
Here's an example of what I want:
Select article about vehicle, within the vehicle article is a field called location. When I click the location of the item, the result should include only items related to the previous content type, that is, vehicle content type. Location field is connected to Location taxonomy I created.
BTW, I already installed views and it is working fine.
Answer: I think you need to edit the location links to include a second "parameter" so it could look like:
yoursite.com/yourview?location=yourLocation&articletype=yourArticle

For this you would need to implement some hooks. Maybe you can start with hook_preprocess_node.
What I would do is to:

Use the said hook
Get the location terms available for the current viewed node
Construct the URL based on the term data and content type the way I want it to look.

Then in your view, you need to add just two contextual filters that would be those fields. The location term reference field and the content type.
EDITED
Node view and term link update

Created a new content type name Article 2 (Machine name: article_2) to follow your structure of content types having Vehicle, Clothing and etc. So mine is just Article and Article 2. My content types have the Term reference field of the Tags vocabulary w/c in your setup is the Location.
Added terms into the Tags vocabulary: Term 1 and Term 2.
Created a simple custom module using hook_preprocess_node() w/c looks like:

function yourmodulename_preprocess_node(&$vars) {
  // Check if your term field is being rendered in the node view
  if (isset($vars['content']['field_tags']['#items'])) {
    // Loop through all terms present in the node
    foreach ($vars['content']['field_tags']['#items'] as $index => $info) {
      $node_type = '/' . $vars['type'];
      // We append the node type to the URL of a term so that
      // it can be used as a contextual filter in the term view.
      $vars['content']['field_tags'][$index]['#href'] .= $node_type;
    }
  }
}

Remember to do a Flush Cache since were adding a new hook function into the system. Now when you view a node, check the term link(s) listed and you will see that the URL structure is not like http://yoursite.com/taxonomy/term/2/article
Term View

Clone the Taxonomy Term view (So that we wont be changing the original)
Add a second wild card argument in the Path w/c looked like taxonomy/term/% to taxonomy/term/%/%. The second argument would be for the content type.
Under contextual filter add the Content: Type field following the settings in the image.

And then place the Content: Type contextual filter at the second row to match the URL structure w/c would look like:

And that's it. A simple sample result based on this URL http://localhost/drupal/taxonomy/term/2/article would look like:

So it's filtering the right node that has Term 2 as its Tag(my setup)/Location(your setup) and only the Article content type.
My test data are:

Article content type: Article 1, Term 1
Article content type: Article 2, Term 2 (This is the result in the latest screenshot)
Article 2 content type: Article 3, Term 1
Article 2 content type: Article 4, Term 2

Issue
So far I haven't figured out how to use this style with Pathauto so the URL would look better for example, www.mysite.com/illinois/chicago/article.
Comment: Thanks for the suggestion. But I'm still cracking my head on how to do this. In my template file, I have the following code to display the value of location field ``. I don't know what to do next. The value of that field will output something like `www.mysite.com/illinois/chicago`. So are you suggesting I will add the value of the node type to something like `www.mysite.com/vehicle/illinois/chicago`? Where vehicle is the name of the content type.
Comment: Oh! If i may ask, what is the type you're using for the location field? Is is just taxonomies? For the link, yes, it could also be just a parameter though like using the "?field=value" but your structure may do also.
Comment: It's a Location field connected with from a Location taxonomy. Can you give me an idea on how to do this? How can I add a parameter like `?type=vehicle` and pass it to Views contextual filter?
Comment: I updated my answer of the rough work I did.
Comment: Thank you very much. I created the module and it works perfectly except for the simple hierarchy module. If I use "simple hierarchy" under the manage display >> format, the module does not work. But if I don't use it, it works great. Without simple hierarchy format the url turns into http://mysite/taxonomy/term/1181/vehicle. But if I use simple hierarchy format, the url output to something like www.mysite.com/illinois/chicago. And it doesn't turn to www.mysite.com/illinois/chicago/vehicle. Any idea?
Comment: You're very welcome. Yeah, I think the Simple Hierarchy module has a different way of dealing with it's data. Also for that, I have researched that its hard to append a new URL argument when its aliased because it matched the original URL to the one saved in URL Aliases. This was my first approach but was unsuccessful.


Which regression type should i use?

Question: I want to use logistic regression on spss to examine the factors associated with bottled water use.
A survey was distributed with these questions:
1.enter your gender (m, f), faculty (8 faculties to choose from), academic year (5 options)
 2.your poinion (yes or no):
- do you think bottled water is cleaner than tap water
- do you think bottled water is safer than tap water
- do you think bottled water is tastier than tap water
- do you think bottled water has an impact on human
- do you think bottled water has an impact on the environment
Can someone show me the steps to get these outcome: the adjusted odd ratio, confidence interval and p-value.
I really appreciate your help. Thnx
Answer: What you have in your hands looks like a classification problem rather than a regression one. Fortunatelly, you already know a classification technique (confusingly enough: logistic regression)
You may also want to tree different classifiers such as decision trees, which work great with categorical data

Which regression type should i use?


Finding the basis of $\mathbb{R}^n$ given a set of non-spanning, linearly independent vectors

Question: Let $S = \{ v_1, \dotsc, v_k \}$ be a set of non-spanning, linearly independent vectors in $\mathbb{R}^n$. From my lecture in LA, the instructor said that we can form a basis with $S$ given that we solve for the row-echelon form of $[v_1 \dotsc v_k \ e_1 \dotsc e_n]$ (where $\{ e_1, \dotsc, e_n \}$ is the natural basis of $\mathbb{R}^n$), and the vector whose column in the $\text{ref}([v_1 \dotsc v_k \ e_1 \dotsc e_n])$ has a leading one, then its a member of the desired basis.
For example, to find the basis in $\mathbb{R}^2$ which includes the vector in $S = \left\{
\begin{bmatrix}
1 \\ 5
\end{bmatrix}
\right\}$ (which is, by default, a linearly independent vector), we solve for the ref of S adjoint the natural basis of $\mathbb{R}^2$:
$$
\begin{bmatrix}
1 & 0 & 1 \\
5 & 1 & 0
\end{bmatrix}
\sim
\begin{bmatrix}
1 & 0 & 1 \\
0 & 1 & -5
\end{bmatrix} \ .
$$
Since the first and second column of the ref had the leading one, then the first and second column of the initial matrix can form a basis which includes the vector $[1 \ 5]^T$, i.e. $\left\{
\begin{bmatrix}
1 \\ 5
\end{bmatrix},
\begin{bmatrix}
0 \\ 1
\end{bmatrix}
\right\}$ is a basis of $\mathbb{R}^2$
Why is that?
Answer: This is because row operation does not change linear dependence relations between the columns. This is a consequence of the fact that row operations do not change the solution set of a system of linear equations.
You can actually get away with solving this problem and reducing a smaller matrix at the cost of having to reverse the row operations. You would do as follows:

Bring the matrix $[v_1 \quad \cdots \quad v_k ]$ to reduced row echelon form, keeping track of your operations. For each row missing a pivot, you add a column providing the missing pivot, until you have an invertible matrix $[v_1 \quad \cdots \quad v_k \, u_{k+1} \quad \cdots \quad u_{n}]$.

You reverse the row operations you did in step 1 on the matrix augmented with extra columns and the columns of the resultant matrix form a basis of $\mathbb{R}^n$ containing the original linearly independent, non-spanning set.
Answer: This question relates to the row-space and column-space of a matrix.
Theorem 2: Let $B$ be any matrix that is row equivalent to a matrix $A$, then row-space$(A)=$row-space$(B)$
Proof: This is mainly because row-equivalent matrices $A\cong B$ are attained by elementary row-operations, which implies that the rows of $B$ are linear combinations of the rows of $A$, and row$(B)\subseteq$row$(A)$. The reverse inclusion is had by noting that the same row operations used to get from $A$ to $B$ can be used in reverse from $B$ to get to $A$, thus the rows of $A$ are linear combinations of the rows of $B$, row$(A)\subseteq$row$(B)$.
Now comes the question of finding a basis for the row-space of a matrix $A$, well since row$(A)=$row$($rref$(A))$, we can look at the reduced row echelon form of $A$ to find a basis for row$(A)$.
It turns out that the if $R$ is a matrix in row echelon form, then a basis for row$(R)$ consists of the nonzero rows of $R$.
For example if
$A=\begin{pmatrix} 1&1&3&1&6 \\ 2&-1&0&1&-1 \\-3&2&1&-2&1 \\ 4&1&6&1&3 \end{pmatrix}$
then $R=rref(A)=\begin{pmatrix}1&0&1&0&-1\\0&1&2&0&3\\0&0&0&1&4\\0&0&0&0&0 \end{pmatrix}$
and a basis for row$(A)$ is $\left\{\begin{bmatrix}1&0&1&0&-1\end{bmatrix}, \begin{bmatrix}0&1&2&0&3\end{bmatrix}, \begin{bmatrix}0&0&0&1&4\end{bmatrix} \right\}$
What about the column-space of $A$? Recall that $A\vec{x}$ is a linear combination of the columns of $A$:
$A_{3\times 3}\vec{x}=\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\end{pmatrix}\begin{pmatrix}x_1\\x_2\\x_3\end{pmatrix}=x_1\begin{pmatrix} a_{11}\\a_{21}\\a_{31}\end{pmatrix}+x_2\begin{pmatrix}a_{12}\\a_{22}\\a_{32}\end{pmatrix}+ x_3\begin{pmatrix}a_{13}\\a_{23}\\a_{33}\end{pmatrix}$
Since elementary row operations do not affect the nontrivial solution set of the dependence relation $A\vec{x}=\vec{0}$, the columns of $A$ have the same dependence relationships as the columns of $R=$ref$(A)$.
Given our matrix $R$ it is obvious that $\vec{r_3}=\vec{r_1}+2\vec{r_2}$ and $\vec{r_5}=-\vec{r_1}+3\vec{r_2}+4\vec{r_4}$ where $\vec{r_1},...,\vec{r_5}$ are the column vectors of $R$, you can also note that these same relationships hold amongst the column vectors of $A$.
For example:
$\begin{pmatrix}3\\0\\1\\6\end{pmatrix}=\begin{pmatrix}1\\2\\-3\\4\end{pmatrix}+2\cdot\begin{pmatrix}1\\-1\\2\\1\end{pmatrix}$.
Thus the column vectors of $A$ that have a nontrivial dependence relation correspond to the non-leading-one column vectors of $R$. Therefore the linearly independent column vectors of $A$ correspond to the leading-one column vectors of $R$.
In your case you are given that $\{v_1,...,v_k\}$ is linearly independent, then $\{v_1,...,v_k,e_1,...,e_n\}$ has $k+n$ vectors but $\mathbb{R}^n$ has dimension $n$, thus there has to be a nontrivial dependence relationship amongst some of the vectors as we're forming a basis for $\mathbb{R}^n$. In the RREF of your matrix you would have the first $k$ column vectors be leading-ones because the first $k$ vectors are linearly independent, the remaining columns would either display a nontrivial dependence relation, or not. Those that do are not necessary in the basis, therefore the basis would consist of all the vectors that correspond to the leading ones in the RREF of $[v_1\;\;\;\;\;v_k\;e_1\;\;\;\;\;e_n]$. Don't believe me? The Fundamental Theorem of Invertible Matrices can help in this case. Note that if you eliminated all the columns of $A$ that didn't correspond to leading-ones in the RREF of $A$, then you would have an $n\times n$ matrix $A'$ whose RREF is $I_n$, and therefore the column vectors of the new matrix $A'$ are linearly independent. Also note that your professor assures that you have $n$ leadings ones by placing all desired vectors he wants in the basis as the first $k$ columns and then adding a basis for $\mathbb{R}^n$ to the matrix, if the vectors $e_1,...,e_n$ would of been placed first then we would of gotten $n$ leading ones for the first $n$ columns(by definition of the standard basis) and would of been done before even starting.
Note that in your example $\vec{r_3}=\begin{pmatrix}1\\0\end{pmatrix}=\vec{r_1}-5\vec{r_2}=\begin{pmatrix} 1\\5\end{pmatrix}-5\begin{pmatrix}0\\1\end{pmatrix}$ thus every linear combination of $\vec{r_1},\vec{r_2},\vec{r_3}$ is really just a linear combination of $\vec{r_1},\vec{r_2}$, and $\vec{r_1},\vec{r_2}$ are not multiples of one another and thus must be linearly independent.
Most of this explanation was taken from Linear Algebra: A Modern Introduction by David Poole between pages(approximately) 180-200.


How to keep children divs from growing bigger than their parent div

Question: I want to be able to add text to a child div, but never have it get bigger than its parent, but rather get scrollbars on the child.  Currently I have:

This is a title

<textarea rows="2"></textarea>

You can see the entire page with the css at this fiddle.  click on the 'add line' button a few times and you will see the problem.
What happens is as text is added to the #helplog div, eventually it pushes everything past the border of the #chatwindow div.  So you get: .
Notice that the text, e.g., line 7 and 8, and the msgbox (which is outlined in red) have moved out of the black borders which surround their parent, #chatwindow.
I have tried adding wrappers with position:absolute, but either this collapses the entire box or it has no effect.  The goal if for the #chatwindow div to remain the same size and for the text in #helplog to scroll.
How can I avoid this?
Comment: What do you want to happen when more text is added? Have the parent box grow, have the new content hidden, or have a scrollbar appear?
Comment: Have a scrollbar appear
Comment: You need to define a height on the helplog div
Comment: But I always want the helplog to fill the space between the `#dragtitle` and the `#msgline` and I want `#msgline` to be at the bottom.
Answer: If you want it to scroll instead of overflow you can add overflow-y: scroll as a CSS property to #chatwindow. This will cause it to become a scrollable area when it gets too big.

#foo {
  height: 100px;
  width: 100px;
  border: 1px solid red;

  overflow-y: scroll;
}

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Comment: But then the ENTIRE `#chatwindow` div will have a scrollbar.  I only want the `#helplog` div to scroll.


mouseenter mouseleave within contents of iframe

Question: I'm trying to highlight elements within a iframe with no success. I've tried using mouseenter/mouseleave with no success. It does not fire.
$('#iframe').contents().mouseenter(function (e) {
    //var element = $(e.target);
    var element = $(this);

    $(element).addClass("highlight");
}).mouseleave(function (e) {
    $(element).removeClass("highlight");
});

I've had better success with mousemove however it highlights the parents as well which I don't want.
var prevElement;
$('#iframe').contents().find('html').on('mousedown', function (e) {
    e.stoppropagation()
    //e.preventDefault - did not work either
    var element = $(e.target);

    if (prevElement == null) {
        prevElement = element;
        element.addClass("edit-element-selector");
    }
    else {
        if (prevElement != element) {
            prevElement.removeClass("highlight");
            //prevElement.parents().removeClass("highlight"); did not work
            element.addClass("highlight");
        }
    }
});

HTML

Comment: got your html please?
Comment: @DomAdams Added html. Don't have much. It's literally just a iframe.
Answer: The css rule for .hover is not visible in the context of the iframe.
Either use .css() to set style directly, add the css links or clone all styles in the main document into the iframe with jQuery.
Here is a working jfiddle which you should easily be able to copy.
http://jsfiddle.net/danmana/pMBw2/
Comment: Thanks but I still can't get it to work. Tt doesn't have anything to do css. Hovering only fires on the html element of the contents in the iframe but not any other element within.
Answer: My problem had 2 issues.

My css was wrong.

Wrong
.highlight :hover {
  outline:4px solid #f00;
}

Right
.highlight {
  outline:4px solid #f00;
}

Hover was bubbling up to the parents. Mouseenter and mouseleave worked however.
var $iframe = $("#iframe").contents();

$iframe.find('*').mouseover(function (e) {
    $(e.target).addClass('highlight');
}).mouseout(function (e) {
    $(e.target).removeClass('highlight');
});

Answer: Try jQuery Hover
    $(function () {
        var iContent = $('#iframe').contents();
        iContent.find('#id_username').val("New Value!");
        iContent.find('#id_username').hover(function () {
            $(this).css("border", "1px solid red");
        }, function () {
            $(this).css("border", "1px solid #c4c7cb");
        });
        console.log(iContent.find('#id_username'));
    });

jsFiddle
Sorry I guess I misunderstood the question.  Here is an updated fiddle changing the value of a text input and changing border color on hover.
Comment: Unfortunately it did not work. It tells me I'm hovering over the iframe but doesn't get the elements within.
Comment: I can't use find() because it is not restricted to an element.

I did try `$iframe.find('*').hover(function () {...` and it changes the border for the element but also the parents with I don't want.


Regular tetrahedron

Question: Calculate the distance between the slanted wall heights of the regular tetrahedron with edge lengths $a$.
I have problem with visualization where the distance is.
Let's say we have such situation($MC$ is height) and draw yet height $DP(BC)$, so the quested length is between $P$ and projected point $P$ on $MC$ ?
Comment: No, the length would be between the closest pair of points, one on $MC$ and one on $DP$.
Comment: can you give me hint how to determine these point?
Comment: Mm... Jessica, unfortunately, I don't know what kind of tools you are expected to use in the homework. If it were up to me, I would solve the problem using linear algebra. Most likely I wouldn't even find these two points explicitly, but rather find the required distance using an "indirect" method. Could you tell us what kind of course this is? Otherwise, it may be hard to give an answer at the appropriate level.
Comment: I don't have imposed method to solve this problem but I'd prefer the high school level solution. Could you explain how looks the "indirect" method?
Comment: I'm making calculations to give you an answer, but while I'm doing it, here is a note: I think the answer depends on which pair of heights you choose. The pair $(CM, DP)$ that we're talking about is one thing. But you could also consider point $Q$ which is the middle of $CD$ and look at the pair of heights $(CM, BQ)$. These two are situated differently than the two before, and the answer may be different. So it would be good to know which distance you need.
Comment: maybe first the pair $(CM,DP)$ and later we see what happen for $(CM,BQ)$
Answer: I am trying to answer your question (with my own interpretation). Several lines have been added to your picture. See below.
First of all, because MC is on the base (according to your picture), it should not be used as 'slant height'. To certain extend, you are allowed to do so because the figure is regular.
I found two of the slant heights, one is DM on face DAB and the other is DP on face DBC. The 'P' that you are using is not very clear because it was not shown in your picture.
To find the required distance is impossible because there are too many answers (ranging from 0 to MP). I guess what you are looking for is the MAXIMUM distance between these two slant heights. If this is true, then the answer is MP, which is eventually equal to 0.5a  because triangle BMP (was mistakenly written as DMP) is equilateral.
Comment: your heights are not oblique, because they are included in one plane
Comment: There are only 3 lines can be classified as 'slant heights' including the 2 that I have mentioned plus the one on the face DAC (which is the same as face DBC, geometrically speaking). Any two of them will definitely lie on a plane. There is no such thing as the two slant heights are oblique to each other. One altitude on one plane may be oblique to another altitude of another plane. In that case, one of these altitudes cannot be qualified as 'slant height'.
Comment: Triangle $DMP$ is not equilateral!
Comment: Should be triangle BMP. My mistake. Thanks for pointing that out.
Answer: Let $M$ be the middle point of $AB$ (as in the picture), and $P$ be the middle point of $BC$. We shall find the distance between segments $CM$ and $DP$.
First, it is clear that the answer is proportional to $a$, so I will just assume that $a=1$ to make formulas shorter.
The plan is very simple. I will calculate lots of vectors, and for my calculations I will use vectors $\overline{BA}, \overline{BC}, \overline{BD}$ as a basis. In the calculations to come I will use dot products of these vectors, which I denote by $(,)$. Their lengths are all equal to $1$, so their products by themselves are $1$:
$$
(\overline{BA}, \overline{BA}) =
(\overline{BC}, \overline{BC}) =
(\overline{BD}, \overline{BD}) = 1.
$$
The pairwise dot products are equal to $1/2$, because the angle between each two of these vectors is 60 degrees, and its cosine is $1/2$. So we have
$$
(\overline{BA}, \overline{BC}) =
(\overline{BC}, \overline{BD}) =
(\overline{BD}, \overline{BA}) = 1/2.
$$
Now, let $Q$ be a point on line $MC$ and $R$ be a point on line $PD$ such that the distance between $Q$ and $R$ is the smallest possible. We will see later that in fact $Q$ is on segment $MC$ and $R$ is on segment $PD$, so the length of $QR$ is the answer to our problem.
To find where $Q$ and $R$ are situated, let's use the parametric line equations in vector form:
$$
\begin{align}
\overline{BQ} &= \overline{BC} + \alpha\left(\overline{BC} - \frac{1}{2} \overline{BA}\right) \\
\overline{BR} &= \overline{BD} + \beta\left(\overline{BD} - \frac{1}{2} \overline{BC}\right)
\end{align}
$$
Here $\alpha$ and $\beta$ are some constants that we have to find. First, let's subtract these equations to get vector $\overline{QR}$:
$$
\overline{QR} = \overline{BR} - \overline{BQ} =
\frac{1}{2}\alpha\overline{BA} + \left(-1 - \alpha - \frac{1}{2}\beta\right)\overline{BC} + (1 + \beta)\overline{BD}.
$$
It should be clear that vector $\overline{QR}$ must be orthogonal to both lines $MC$ and $PD$. In terms of dot products this can be written as a system of two equations:
$$
\begin{align}
\left(\overline{QR}, \overline{BC} - \frac{1}{2}\overline{BA}\right) &= 0; \\
\left(\overline{QR}, \overline{BD} - \frac{1}{2}\overline{BC}\right) &= 0.
\end{align}
$$
Now, using our formula for $QR$ and the known dot products of our basis vectors, we can boil these equations down to the following:
$$
\begin{align}
6\alpha + \beta &= -4; \\
\alpha + 6\beta &= -6.
\end{align}
$$
Solving the system, we get $\alpha = -\frac{18}{35}$ and $\beta = -\frac{32}{35}$. The fact that both numbers are between $-1$ and $0$ shows that both points $Q$ and $R$ lie on their respective heights, not on their continuations.
And now the deed is almost done. We know $\alpha$ and $\beta$, so we can find
$$
\overline{QR} = -\frac{9}{35}\overline{BA} -\frac{1}{35}\overline{BC} + \frac{3}{35}\overline{BD}.
$$
To find its length, we find its dot product with itself (using the known dot products of the basis vectors). The result of this calculation is that $(\overline{QR}, \overline{QR}) = \frac{70}{35^2}$, therefore $|QR| = \frac{\sqrt{70}}{35}$. And that is our answer.
If we come back to an arbitrary value of $a$ instead of $1$, it is clear that the answer will be $\frac{\sqrt{70}}{35}a$.
I am really, really not in the mood to do the same amount of calculations for pair $(CM, BQ)$. Also, there surely is a shorter way to do this. Maybe calculations will be easier if you choose your basis better. I picked one at random and stuck with it. There should also be a solution without linear algebra, but somehow I don't feel like looking for it now. Maybe someone will provide one in another answer.
UPDATE: note that this method may look like an overkill, but there is an upside. It gives you some extra information as a bonus. We know not only the distance between heights, but the actual two points where they come closest to each other. The $\alpha$ and $\beta$ that we found tell us that point $Q$ divides $CM$ with ratio $18:17$ (almost in the middle), and point $R$ divides $DP$ with ratio $32:3$ (very close to point $P$).
Comment: You're welcome. I decided not to go with the "indirect" approach. With that approach you just find the vector product $[CM, DP]$, and then the resulting distance is $|([CM, DP], CD)| / |[CM, DP]|$ (I'm omitting vector bars). The drawback is this finds the distance between *lines*, not segments. The answers happen to be the same in our case because the points in the closest pair lie on the segments, not outside of them.
Comment: @Jessica If you have problems in any step, feel free to ask. I can always fill in the details.
Comment: well I need to admit that your solution is too hard for me, becouse I haven't learnt parametric line equation yet, but do you think it is possible to solve this problem using more elementary method for example by similar triangles  ?
Comment: @Jessica I'm certain that it's possible, I just took the easy way out by using algebra and avoiding the need to really think. On another note, parametric line equations are very easy. In this case they just say $\overline{CQ}=\alpha\overline{MC}$ and $\overline{DR}=\beta\overline{PD}$. It just says that $CQ$ is parallel to $CM$ (herce $Q$ is on line $CM$), and $DR$ is parallel to $DP$ (hence $R$ is on line $DP$).
Comment: I would like to calculate the second distance (with the same method as you) $(CM,BP)$ where $P$ is middle of $DC$, but I encounter a problem when I need to determine my basis. Let $QR$ be searched distance where Q lie at $MC$ and $R$ at $BP$. Then I have $\vec{QR}=\vec{AR}-\vec{AQ}$ and here I have problem with which vectors take for basis, could you help me? You don't need to calculate it, just help me to pick the proper vectors. Thanks in advance!
Comment: @Jessica It's not really that important which basis you choose. It should work out fine if you use vectors $\overline{AB}, \overline{AC}, \overline{AD}$.
Comment: ok if I choose those basis then I have $\displaystyle \vec{AQ}=\vec{AC}+\alpha(\vec{AC}-\frac{1}{2}\vec{AB})$ and I don't know how to determine $\vec{AR}$ in terms of $\vec{AB}$, $\vec{AC}$, $\vec{AD}$. Could you help me with it?
Comment: Sure. $P$ is the middle of $DC$, therefore $\overline{AP} = \frac{1}{2}(\overline{AC} + \overline{AD})$, and therefore $\overline{BP} = \overline{AP} - \overline{AB} = -\overline{AB} + \frac{1}{2}(\overline{AC} + \overline{AD})$. Then $\overline{AR} = \overline{AB} + \overline{BR} = \overline{AB} + \beta \overline{BP} = \overline{AB} + \beta(-\overline{AB} + \frac{1}{2}(\overline{AC} + \overline{AD}))$. Maybe you'll want to flip the sign of $\beta$ to make it more like the other equation, it's a matter of taste.
Comment: By the way, if we talk about little details, maybe it would be better to flip the sign of $\alpha$, not $\beta$. That is more natural. My choice of signs in the answer above wasn't the best. It doesn't affect the final answer, but it looks kinda bad.
Comment: @Jessica it looks correct. The difference of signs is because of what I said. If you'd started with $\overline{AR} = \overline{AB} -\beta\overline{BP}$, then the resulting $\beta$ would be $-\frac{3}{5}$. Since you started with $\overline{AR} = \overline{AB} + \beta\overline{BP}$, you got $+\frac{3}{5}$. If you'd used the equation $\overline{AR} = \overline{AB} + 100\beta\overline{BP}$, then you would've got $\beta = \frac{3}{500}$. The crux of it is: the $\beta$ you get depends on how you write the equation for point $R$. But the actual point $R$ you get is always the same.
Comment: OK, thanks a lot

Regular tetrahedron


como clicar no link e obter reposta sem sair da pagina

Question: entro no meu localhost e quando clico no link que criei ele vai para outra pagina....gostaria que quando eu clicasse no link ele obtivesse a resposta desse link na mesma pagina, sem sair dela..
irei mostra meu html...não sei o que estou errando!!

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercícios Html</title>

        Exercícios HTML

        00 -Teste|
        TEMPPPP

        Curso Web Moderno

Answer: Seu erro foi usar o query selector, que seleciona a partir de classe, para selecionar um hyperLink que no caso foi o "", caso esse código esteja retornando resposta, então crie uma div e coloque uma classe qualquer, só pra testar, exemplo:

Answer: Opa amigo, beleza? Então, você esta tentando fazer uma requisição assincrona? nesse caso, você precisa entender o processo, vou tentar resumi-lo pra você
obs.  Para facilitar o processo, use o jquery, ele faz a requisição pra você, e você só se procupa em posicionar o dado na pagina, mas caso queira fazer ocm js puro, de uma pesquisada sobre requisições XML.
Passo 1 - Verifique com o console log se a pagina que você esta chamando, esta realmente retornando um resultado, se não você só esta tentando imprimir dados vazios
Passo 2 - Após ver oque a pagina esta retornando, tente idenficar oque ela retorna (array, string, object e etc), isso vai facilitar na definição do método de impressão
Passo 3 - Pesquise sobre o metodo de impressão que vai usar para imprimir esses dados na tela.
Esse é o passo a passo mais básico possivel para requisições assincronas;


textarea didn't convert into tiny MCE while called in javascript

Question: i have problem while called text area that should be convert into tiny MCE from insert.php into manage.php. please help.thx
here my code
insert.php

    <?php
        echo '';
        echo '<textarea id=texta></textarea>';
        echo '	';
    ?>

manage.php

when i click #add its load insert.php but the textarea inside insert.php won't change into tiny MCE editor.
Answer: You need to make sure that tinymce.init gets executed after the phph is fully loaded (you may use $(document).ready for this).


Chord confusion

Question: Total music theory noob here, taking my first steps to try and figure some of this stuff out. I have some sheet music for Wonderwall (for guitar), and I'm a little confused on one of the chords (see image below)
So I've figured out from the key signature we're in the key of F#minor. I'm trying to figure out the notes in the B7sus chord, but the notes on the stave (B, D, A) aren't the notes showing in the tab above (B, F#, A, E, F#).
I'm sure it's just a case of me not really knowing how to read this stuff. I'd really appreciate being pointed in the right direction.
Thanks!
Comment: Just so you know, this music doesn't at all reflect the way the members of Oasis actually played this song on guitar.
Comment: The sheet music in SMN looks like it is meant for piano, and the box diagrams above are for a guitarist to accompany.  A lot of song books are written this way and you need wor things out using the text as a guide.  It may be intentional, no reason for the guitar and piano to match exactly as long as they do not conflict.  Or it could be an error.
Answer: Well spotted! The chords shown in the dots aren't exactly the same as those in the guitar chord windows. B7sus4 shouldn't have a D♮, there should be an E note instead.
That's a mistake. (By the way, that's not tab!). There is no obligation for either the guitar chord window or the music stave to show all the notes from a chord. But the chord name should be the correct one for that point. And the dots should reflect that.
As a keyboard and guitar player, I find this happening all too often.It's poor writing, and often I have to listen to what the rest of the players play, before deciding which is better to follow - chord name, chord window or actual dots.
Comment: @chasly-supportsMonica - edited accordingly! Sometimes I just have to prove I'm human - by erring... Thanks for spotting a schoolboy error. Possibly I was fixated by D#, as B7sus more often resolves to B(7), rather than Bm(7), if that makes sense.
Comment: Thank you - that's really helpful! Looks like it's something I'll have to watch out for (because it's not difficult enough already... :/ )

Just one more quick question. You mentioned the D# there, but I thought it was a D (it's not 'sharpened' in the key signature or on the actual note). I can see that in the key of B the 3rd is a D#  - is it something to do with that?
Comment: Well spotted again. I assumed (right or wrong) that since the chord mentioned was B.. not Bm.. that the D would be sharp. In B7sus, there wouldn't even be a D *or* a D#. There's a faint possibility that the chord could really be Bm11, which would just about cover all that's printed in that bar - but I doubt it... Don't think the Gallaghers were that advanced! Reckon they pressed a few strings down, liked the sound, and someone else had to transcribe it.  Lesson of the day - for me - pay more attention; for you - don't believe everything that's in print!
Comment: Thank you so much for your help - really appreciate you taking the time here!
Comment: You say, *"B7sus4 shouldn't have a D♯, there should be an E note instead."*  But it is an E, look closer!  As the OP correctly said, the notes from the chord symbol  are B, F#, A, E, F#
Comment: @chasly-supportsMonica - in the chord window, yes, but not on the stave.
Comment: @Tim - I don't get what you're saying. There isn't a D# anywhere on the page.
Comment: @chasly-supportsMonica - I've caused confusion - sorry. In the chord window there's an E, but on the stave there's a D (natural). That shouldn't be there if the chord is going to be a sus chord. That's what I meant.
Comment: Ummm ... Now I am confused. In the first sentence of your answer you mention D sharp. Did you mean to write D natural there?  You say, "B7sus4 shouldn't have a D♯" but who is saying that it should? Why have you mentioned D sharp at all? Am I missing something obvious?
Comment: IMO there's no _rule_ that the grand staff has to represent the same chords. It could just as well be a combination where the piano plays something a bit different. For example, a piano part could have voices going up and down and chords changing faster than is practical to write for guitar players. If the grand staff is a piano part. Chord symbols are an approximation, and it isn't _wrong_ to play something different. :)
Comment: @Tim Well, as far as how 'advanced' or otherwise it is to press some strings down and decide whether you like the sound, this is a tried-and-true compositional technique which I would imagine is responsible for a great deal of music, including some of great sophistication! Not least as the principle works as well on piano as on guitar, i.e. playing part "standard" major or minor chords and adding "extra notes". I'd say the piano part is a mistake though, as neither a determinate minor nor major tonality for that chord really seems to fit with the song. I would however say it's entirely
Comment: possible to alight on a m11 chord via the "pressing down some strings" process; in the original guitar part for Wonderwall the E and A at the top (frets 5 on B and E strings) are held throughout all four chords and the guitar is capo'd at the 2nd fret. Change the E to the D natural below and play the (capo'd) open strings from the 5th string onwards and you get a neat Bm11 voicing ;)

Chord confusion


On the opposite group

Question: When the group $G$ acts on the set $S$, e.g. $G \colon= {\mathrm{GL}}_2({\Bbb C})$, $S \colon= {\Bbb C}^{\oplus 2}$, $G$ have the right to act on the left or on the right. Both actions can be naturally identified as follows$\colon$
$\sigma \circ \tau (s) = (s)\tau \circ \sigma$,
where both sides means $\tau$ acts on $s \in S$ first and then $\sigma$ acts on $\tau(s) ~(= \!(s)\tau)$ next.
That is, the equality
\begin{equation*}
\sigma \circ \tau = \tau \circ \sigma \quad \cdots\cdots \quad (\lozenge)
\end{equation*}
automatically makes sense under the sequence of actions (or time).
Or when one starts from the left action, the set in the R.H.S. in $(\lozenge)$ can be put, by the more sophisticated terminology, the opposite group $G^{\mathrm{op}}$, for which the unique isomorphism $G \cong G^{\mathrm{op}}$ is given by $g \mapsto g^{-1}$.
However, the identification in $(\lozenge)$ is accomplished by switching the multiplication between two elements $\sigma$ and $\tau$ according to the sequence of actions on the left or right (on $S$).
Q. Is it correct that I never care about $G^{\mathrm{op}}$ but always automatically identify $G$ and $G^{\mathrm{op}}$ as in $(\lozenge)$ ignoring the group isomorphism between $G$ and $G^{\mathrm{op}}$?
Comment: I don't understand your question.
Comment: A quibble: the map $g\mapsto g^{-1}$ is **not** in general the only isomorphism between $G$ and $G^{op}$ (suppose $G$ is a non-rigid abelian group).
Comment: Sorry. I was mistaken. Pierre
Answer: It sounds like you are saying if you start with a left action of $G$ on $S$ (with $g$ acting on $s$ written "$gs$"), that you want to define a "right action" by just declaring that "$sg$" is an alternate notation for $gs$. This is what I assumed when you said $\sigma \tau (s) = (s) \tau \sigma$ both mean do $\tau$ first, then $\sigma$.
Here is the problem with this: the right-hand side, $s \tau \sigma$ is not really consistent. You get different results depending on if you intepret it as meaning $(s\tau)\sigma$ or $s(\tau\sigma)$ (but they need to agree to be a right action).
I will show by example. Consider the example you give, of $G = \mathrm{GL}_2(\Bbb{C})$ acting on $S=\Bbb{C}^2$. Consider
$$ g = \begin{pmatrix} 0&1\\1&0 \end{pmatrix} \hspace{0.5cm} \text{and} \hspace{0.5cm} v=\begin{pmatrix}x\\y\end{pmatrix}$$
Then of course $gv = \begin{pmatrix}y\\x\end{pmatrix}$. So if we define our right action like you suggest, then $vg = \begin{pmatrix}y\\x\end{pmatrix}$.
But $g$ can be factored as $g=g_2g_1$, where
$$ g_2 = \begin{pmatrix}0&-1\\1&0\end{pmatrix} \hspace{0.5cm} \text{and} \hspace{0.5cm} g_1 = \begin{pmatrix} 1&0\\0&-1 \end{pmatrix} $$
So in the usual left action, multiplication by $g$ is the same as first multiplying by $g_1$, and then by $g_2$. So your suggestion is that if we write things on the right, we should have $g_2g_1v = vg_1g_2$.
This is where the problem occurs: do we interpret the expression $vg_1g_2$ as meaning $(vg_1)g_2$ or as $v(g_1g_2)$? To be a valid right action, it shouldn't matter and both should be the same. The first interpretation is $(vg_1)g_2$, meaning act first by $g_1$, and then by $g_2$. This agrees with the calculation above (and the left action), and we get $\begin{pmatrix}y\\x\end{pmatrix}$. The other intrepretation is $v(g_1g_2)$, which means first multiply $g_1g_2$ in the group, and then act by that element. But $g_1g_2 = \begin{pmatrix}0&-1\\-1&0\end{pmatrix}$, which is not the same as $g$, and we get $\begin{pmatrix}-y\\-x\end{pmatrix}$ as the result.
Comment: Great Thanks! Very clear. Pierre Matsumi

On the opposite group


How can I change the circle size of pie chart with jqplot?

Question: I have no idea how I can change the circle size.
In my chart, the circle is very small.
I want a bigger circle than it is currently.
 code ex :
 plot2 = jQuery.jqplot('PieChart',[ ticks ,rs_money],
{
     grid: {
            drawBorder: false,
            drawGridlines: false,
            background: 'transparent',

            shadow:false
        },
        axesDefaults: {

        },
        seriesDefaults:{
            renderer:$.jqplot.PieRenderer,
            rendererOptions: {
                showDataLabels: true,
                startAngle: 180,
                sliceMargin: 2

            }
        },

  legend: {  fontSize:'11px',show:true,location: 's', labels:ticks}
}

Comment: I have the same question - have you reached any solution yet?
Answer: I alter the size of the circle via CSS. The pie itself is set up to shrink or grow with the div, as long as it isn't too small. Try styling the div with width and height to see if that is what you're looking for.

You can also go into the jqplot.pieRenderer.js and look for
this.diameter=null;this.padding=20;

The null value can be changed to any number you like to make the circle bigger. If you make it bigger than your div though, it will stretch out of the div's bounds. You can also change the padding to have the circle take up more space in the div.
Answer: Check out their documentation:
http://www.jqplot.com/docs/files/jqPlotOptions-txt.html
seriesDefaults: {
        rendererOptions: {
            diameter: <your value>, // diameter of pie, auto computed by default.

Answer:     table.jqplot-table-legend {
    table-layout: fixed;
}

td.jqplot-table-legend-label
{
   max-width:100px;
}

Answer:     seriesDefaults: {
            renderer: jQuery.jqplot.PieRenderer,
            rendererOptions: {
              padding: 10
            }
    }

You can reduce the space by using padding option.By changing padding you can change the size of pie chart.


Related date fields

Question: I have made this 2 fields using the Date module and CCK.

Field Date 1 I use to choose the date so I put a popup widget
Field Date 2 which I need to be related to the first date field, and to which I have to add 6 months

Is it possible? Does somebody know how to do it?
I've tried to put some token in the "Date 2" field options Default date and Relative, but I've just had problems.
I've searched everywhere without finding a solution.
Comment: explain you question clearly
Comment: You mean Date2 field's value must be restricted starting 6 months ahead of Date1?
Answer: I think you have to use the Date Restrictions module and get the date from the first date field as relative for the 2nd one.
From the module's page:

Date Restrictions Min/Max
Restricts valid minimum and maximum values to a fixed date, or relative interval. Dates or intervals may be provided statically in the field instance settings, or obtained from other fields attached to the host entity. Some examples:

Reservation dates starting today, or three days ahead.
+18 years old.
Dates after, or before, 01/01/2000.

Date Restrictions Allowed Values
Restrict allowed values based on a multivalued date field, or the results of a view (not yet implemented).
Date Restrictions Host Entity
Allow restrictions based on fields in the same entity, within the add/edit form. Restrictions are performed live with ajax.

Related date fields


integrating m/s with a double integral

Question: If I double integrate $f(x,y)$ with unit $m/s$, will the units become $m, m^2/s$ or $m/s^2$? I know the derivative of $m/s$ is just $m$.
Comment: You're integrating over a cross-sectional area. What do you think your units would be given that?
Comment: Are you integrating with respect to length twice, length then time, or time twice?
Comment: The problem is let $f(x,y)$ be the flow through a particular point on an aqueduct. What are the units of integrated over a particular slice of $\int\int f(x,y)dxdy$ the aqueduct, as pictured? What does this quantity represent?
Comment: its $m^3/s$ and it represents the volume flow rate i think, To find the units of $\int\int f(x,y)dydx$ then just multiply the units of f(x,y),dy and dx
Comment: this is the question I am givin: https://imgur.com/6LQ80SX
Comment: @pranavb23 I don't see how you've done $m/s \cdot m \cdot m = m^2/s$, are you sure that power is right?
Comment: oh sorry it should be $m^3$,thank you for pointing it out, ill delete and re comment
Comment: Discharge is defined as $ Q = v \cdot Area$  making dimension $m/s \cdot m^2 = m^3/s$
Answer: If I well understand you have a function $f(x,y)$ the has the dimension of a velocity $(m/s)$. The dimension of the integral depends from the dimensions of $x$ and $y$.  ù
As example, if $x$ has the dimension of  space $(m)$ and $y$ has dimension of time $(s)$, when you integrate the terms in the integral is the product of the function and two differential, and this product gives the dimension of the integrated quantity, as in the case:
$
f(x,y)dxdy
$
but, if $x,y$ are length $(m)$ than $f(x,y)dxdy$ has dimension $(m/s)(m)(m)$
that has dimension $(m/s)(m)(s)=(m^2)= (m^3/s)$
Comment: @Jam:  I modified my answer so that it can give correct hint  ( I hope).
Comment: I don't think $y$ is specified to be time, or a spatial dimension, so the question's missing relevant details.
Comment: The illustration does that there poster is integrating over a cross-sectional area.
Comment: @MichaelMcGovern I think you're probably right that $(x,y)$ are the spatial co-ordinates of the "point" they're talking about. But as far as I can see, they haven't made that explicitly clear

integrating m/s with a double integral


Delphi Multi-Threading Message Loop

Question: My application has several threads:
1) Main Thread
2) 2 Sub-Main Threads (each with Message Loop, as shown below), used by TFQM
3) n Worker Threads (simple loop, containing Sleep())
My problem is, when I close my application, the Worker Threads manage to exit properly, but 1 of the 2 Sub-Main Threads hangs (never exits) when I issue WM_QUIT to close them.

procedure ThreadProcFQM(P: Integer); stdcall;
var
  Msg: TMsg;
 _FQM: TFQM;
begin
  _FQM := Ptr(P);
  try
    _FQM.fHandle := AllocateHwnd(_FQM.WndProc);

    while GetMessage(Msg, 0, 0, 0) do
    begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;

  finally
    DeallocateHWnd(_FQM.fHandle);
    SetEvent(_FQM.hTerminated);
  end;
end;

procedure TFQM.Stop;
begin
  PostMessage(fHandle, WM_QUIT, 0, 0);

  WaitForSingleObject(hTerminated, INFINITE);
  if hThread <> INVALID_HANDLE_VALUE then
  begin
    CloseHandle(hThread);
    hThread := INVALID_HANDLE_VALUE;
  end;
end;

Answer: If I may point to few problems in your code ...
1) You're not checking output of AllocateHwnd. Yes, most probably it will never fail, but still ...
2) AllocateHwnd belogs OUT of try..finally! If it fails, DeallocateHwnd should not be called.
3) AllocateHwnd is not threadsafe. If you call it from multiple threads at the same time, you can run into poblems. Read more.
As Davy said, use MsgWaitForMultipleObjects instead of creating hidden message window. Then use PostThreadMessage to send messages to thread.
If I may put a plug for a totally free product here - use my OmniThreadLibrary instead. Much simpler than messing directly with Windows messaging.
Comment: D2007+, actually. Time to upgrade, then :)
Comment: Gabr, your threading library looks fantastic - thanks for pointing it out.  Oh, and I'd say your site is "spartan", not ugly.
Answer: I've had the same problem, and I found out I shouldn't create a hidden window just to recieve messages. Threads already have a message system.
I think that you're creating your windows handle and store it in fHandle, but GetMessage checks your thread's message loop. Therefore the message PostMessage(fHandle, WM_QUIT, 0, 0); is never recieved by the getmesssage.
You can post messages to your thread using PostThreadMessage, and in the thread you use GetMessage(CurrentMessage, 0, 0, 0). The only important difference is that you have to start the message loop from your thread by calling
PeekMessage(CurrentMessage, 0, WM_USER, WM_USER, PM_NOREMOVE);

You should start with this, than do your setup and than start your loop.
The reason why you should start with the peek message is to make sure messages which are sent during the initialization of your threadprocedure are not lost.
The weird thing is, at the moment I can't find the reference where I learned this, but my guess is the newsgroup community.
Comment: Ooops, sorry my first time here. Didn't know about comments.... I'll give it a try. Thanks.
Comment: Davy is right: PeekMessage should be used to create the Message Queue
Comment: You read it on the [MSDN page for `PostThreadMessage`](http://msdn.microsoft.com/en-us/library/ms644946(VS.85).aspx). They even recommend having the main thread wait on an event which the thread sets once it's message has been created.
Answer: 1) You don't need in AllocateHwnd within your thread. First call to GetMessage will create a separate message queue for this thread. But in order to send message to the thread you should use PostThreadMessage function.
Be aware that at the moment of calling PostThreadMessage the queue still could not be created. I usually use construction:
while not PostThreadMessage(ThreadID, idStartMessage, 0, 0) do
  Sleep(1);

to ensure that message queue created.
2) For terminating thread loop I define my own message:
  idExitMessage = WM_USER + 777; // you are free to use your own constant here

3) There is no need for separate event, because you can pass thread handle to
WaitForSingleObject function. So, your code could look like:
  PostThreadMessage(ThreadID, idExitMessage, 0, 0);
  WaitForSingleObject(ThreadHandle, INFINITE);

Take into consideration that ThreadID and ThreadHandle are different values.
4) So, your ThreadProc will look like:
procedure ThreadProcFQM; stdcall;
var
  Msg: TMsg;
begin
  while GetMessage(Msg, 0, 0, 0)
    and (Msg.Message <> idExitMessage) do
  begin
    TranslateMessage(Msg);
    DispatchMessage(Msg);
  end;
end;

Comment: As pointed out below, you should create the Message Queue with PeekMessage:

  // Force Message Queue Creation
  PeekMessage(Msg, 0, WM_USER, WM_USER, PM_NOREMOVE);

Delphi Multi-Threading Message Loop


Hiding scrollbar on Mozilla with margin-right messes up the content

Question: So I've hidden my scrollbar on Chrome with this piece of code:
 ::-webkit-scrollbar {
    width: 0px;
    background: transparent;
  }

And I found that the best way to hide it in Firefox is to set margin-right: -16px on the parent div. And in Firefox, that looks great. However, the issue is now in Chrome because it moves the entire content inside the parent div to right. If I try to fix it by adding margin-right: 16px to the container inside the parent div, then it messes things up in Firefox.
I'm sure you've encountered this before, but is there anything I can do to fix this? Any known solutions?
Thanks!
Comment: First of all, do you want to hide your scrollbar but still scroll into your page?
Comment: If you just want to visually hide the scrollbar and still allow user to scroll with mouse or keyboard, you can try the following css: `html {overflow: -moz-scrollbars-none;}`
Comment: @brian17han that worked! I can't believe I couldn't find that anywhere. Everywhere I looked, they just advised to hide it with margin-right. Can you please post is as an answer so I can accept it as a correct one?
Answer: If you just want to visually hide the scrollbar and still allow user to scroll with mouse or keyboard, you can try the following css:
html {
    overflow: -moz-scrollbars-none;
}

Answer: You can just give padding only for chrome
::-webkit-scrollbar {
    width: 0px;
    background: transparent;
    -webkit-padding-end: 16px;
  }

Or just set -webkit-padding-end: 16px; on the parent div .
And you can use the same idea on Firefox also , Just setup this
@-moz-document url-prefix() {
    parent div {
        margin-right: -16px;
    }
}

So the margin get only Firefox and you don't anything to change .
@-moz-scrollbars-none If you go to https://developer.mozilla.org/en-US/docs/Web/CSS/overflow and look at the Mozilla Extensions section, it says that "-moz-scrollbars-none" is "an obsolete API and is no longer guaranteed to work."  Better to go with an approach that is more stable.


In Active Admin index page how to display two table data like tab.?

Question: I have two different models. I want to display that both table data in Active Admin Index Page like tab. In one tab one table data display and in other tab 2nd table data display
Answer:
Consider a custom page with table_for components
Consider not using ActiveAdmin.  It wasn't designed to do this, perhaps it is the wrong tool to use.


Can music be written using scale degree numbers instead of note letters in LilyPond?

Question: Is it possible to refer to notes by scale degree rather than their name in LilyPond? For example instead of c d e, set the key to c and use 1 2 3. Or using movable-do solfege syllables (do, ro, re, me, mi...)? Or can those syllables be defined as variables/macros? I'm completely new to LilyPond, and I'm finding it hard to answer this question on my own. I don't think I would use LilyPond if it only works with note letters.
Comment: I do not believe that you'll be able to get the note names as numerals (1,2 etc) -- lilypond syntax requires the note names be be comprised of letters; but you do have complete flexibility in what names get mapped to which notes.
Answer: You can both load definitions that change the input name of notes (e.g. the German style definition changes the input syntax for a 'b' to 'h') and apply automatic transpositions (\transpose c e {...}). Between those two features, you should be able to notate anything in any way you want.
Comment: It would be interesting if you would post your custom language or a link to it here!
Comment: Thanks a lot. I edited the `define-note-names.scm` file and defined a custom `movabledo` language. Works like a charm!


Is there a notification api module?

Question: I like to have a general api for sending notification. I am not sure if there is out there somewhere for Drupal.
For instance, is should be possible to provide a node id and some criterias for which users to send notifications to. The options could be something like "not to the node author", "all who has commented on the node except specific ones (perhaps a comments that has just been written), true/false on sending notification to user who already got a notification about new comments, etc.
There are probably other notification scenarios that could be supported. It would be nice with a general notification framework for Drupal. It seems to be lacking right now (I have looked at subscription and notification). However, I am new to Drupal and might have missed something.
Answer: There is a Notifications module for Drupal that creates a framework for sending out notifications. There are already many modules using the framework. There's a development version of an extension module called Notifications Rules for integrating this with the Rules module if needed.
Answer: If you want to build an automated notification system, you can tap into the Rules module integrated with Notifications.
It has a simple, friendly and flexible UI that enables you to build complex workflows. There's several useful tutorials and use cases in http://dev.nodeone.se/node/634.
Answer: Have a look at the Message Stack (available for both D7 and D8), these are the basic components and dependencies of it:

Some more details about the Message-related modules (=quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

Quite a few popular Drupal distributions already adopted to this Message Stack, Open Atrium is one of them.
If you'd rather look at an existing module as an example, then checkout the 7.x-4.x version of the Answers module (disclosure: I'm a co-maintainer) and its Answers Notification sub-module. This sub-module allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.
Since your question is asking for an "API", you should also have a look at the Message_example module (a submodule of Message). The prezentation "Message Stack in Drupal" may help to get you going with it also.

Is there a notification api module?


Little oh notation question: $x^{o(1)}$

Question: I'm having a bit of trouble with a little oh notation question. If I have $x^{o(1)}$, am I right in thinking that as $x \rightarrow \infty$ that the exponent goes to 0 (and the base goes to 0). I have to show that $x^{o(1)} = O(\log x)$ but I'm a bit stuck. I'm erroneously stuck thinking that $x^{o(1)} - 1 = O(1)$ for some reason and can't see any other way to get the result. Any hints?
Comment: It all depends on how quickly the exponent goes to $0$. For example, if the exponent is $1/\log\log x$, then $x^{o(1)}\to\infty$.
Comment: If $x$ is the base, then it obviously goes to $\infty$. The base of the log stays the same.
Answer: What you want to prove is incorrect in general, that means there are functions $r(x) \in o(1)$ such that
$$\lim_{x\to\infty} \frac{x^{r(x)}}{\log x} = \infty,$$
which contradicts $x^{r(x)} \in O (\log x)$.
An example would be
$$r(x)=\frac{2\log(\log x)}{\log x}.$$
To see this, consider
$$\log (x^{r(x)})=r(x)\log x = 2\log(\log x) = \log \left((\log x)^2\right)$$
which implies
$$x^{r(x)} = (\log x)^2$$
and finally
$$\lim_{x\to\infty} \frac{x^{r(x)}}{\log x} = \lim_{x\to\infty}\log x = \infty.$$
OTOH,
$$\lim_{x\to\infty} r(x) = \lim_{x\to\infty} \frac{2\log(\log x)}{\log x} = \lim_{y\to\infty} \frac{2\log y}{y}$$
if we substitute $y=\log x$ and observe that with $x\to\infty$ also $y\to \infty$. The last limit is clearly $0$ (if you don't know this directly, apply the rule of l'Hospital).
That means we finally get
$$\lim_{x\to\infty} r(x) = \lim_{y\to\infty} \frac{2\log y}{y} = 0,$$
which implies $r(x) \in o(1)$.
So depending on where this problem comes from, you will need to get more knowledge about what I called $r(x)$. Just knowing $r(x) \in o(1)$ is not enough to get the conclusion you want.
Comment: This is helpful! What I'm trying to show is that if I have $O(x^{1/2 + o(1)}) = O(x^{1/2} \log x)$ and I'm not sure if I need more information to get to this. It's a bit baffling for me honestly.
Comment: This is equivalent to the problem here. When you create the qotient, the $x^{1\over 2}$ from both terms will cancel, and you get this problem. So you 'need' more info about the $o(1)$, as I wrote.

Little oh notation question: $x^{o(1)}$


How do I get the bar lines in successive staves to align?

Question: In the following, lines 2-6 have the same notes, yet the bar lines in the middle are not aligned. Is there a way to get them to align? Also, is there a way to extend the bar lines to the lyrics (here generated automatically using NoteNames context)

        \version "2.18.2"

    musicA = {c d e f g a b c c b a g f e d c
                        c d e f c d e f c d e f g a b c
                        c b a g c b a g c b a g f e d c}
    fooBar = { s1 \bar "!" s2 \bar "!" s2 \bar "||" }

    \score {
      \new Staff
      {

        \compoundMeter #'((4 4) (2 4) (2 4))
        \set Timing.beatStructure = #'(4 2 2 )
        <<
          \new Voice
          {
           \relative c' {\easyHeadsOn \musicA \musicA}

          }
          \context NoteNames  {
          \musicA }

          \new Voice = "theBarLines" { \repeat unfold 6 {\repeat unfold 2 \fooBar \bar "|." }}
          \new Voice = "breaks" {\repeat unfold 5 {s2*8 \break}}

        >>
    }}
Comment: Aligning bar lines is *not* a good idea. It's too easy to skip a line when they are.
Comment: This is not true in all contexts.  For example, in jazz lead sheets it's very common practice to deliberately align bars vertically, especially for the majority of tunes which are constructed in multiples of 4 or 8 bars.  For example a typical 32-bar AABA structure would have 2 lines of 4 bars for each section, and it's easier to read and learn the tune when it's laid out in this more regular geometric fashion.
Comment: Definitely agreed, unaligned staves is a feature not a bug. Good engraving practice is to *force* at least a slight misalignment, even when the two lines are identical.
Comment: Bagpipe music is often written with aligned bars with four bars per line.
Answer: I agree with the comment from Édouard.  Of course, one can tell LilyPond to leave all optical corrections that are put in for a more even optical appearance of the music flow (like kernings are in a font).  Your question is like asking how to tell your typesetter to have "rivers" in your text line up better.
LilyPond is flexible: you can tell it to stop doing what it is good at.

\version "2.18.2"

musicA = {c d e f g a b c c b a g f e d c
                    c d e f c d e f c d e f g a b c
                    c b a g c b a g c b a g f e d c}
fooBar = { s1 \bar "!" s2 \bar "!" s2 \bar "||" }

\score {
  \new Staff
  {

    \compoundMeter #'((4 4) (2 4) (2 4))
    \set Timing.beatStructure = #'(4 2 2 )
    <<
      \new Voice
      {
       \relative c' {\easyHeadsOn \musicA \musicA}
      }
      \context NoteNames  { \musicA }
      \new Voice = "theBarLines" { \repeat unfold 6 {\repeat unfold 2 \fooBar \bar "|." }}
      \new Voice = "breaks" {\repeat unfold 5 {s2*8 \break}}
    >>
  }
  \layout {
    \context {
      \Score
      proportionalNotationDuration = #(ly:make-moment 1/4)
      \override NoteSpacing.stem-spacing-correction = #0
      \override NoteSpacing.same-direction-correction = #0
      \override NoteSpacing.knee-spacing-correction = #0
  }}
}
Comment: Would someone please explain how this works?  I'm trying to apply it to something of my own and the bars remain unaligned.
Comment: same here, this doesn't work for me