How to prove that $AB$ is invertible if and only if $A$ is invertible?

Question: Let $A$ be a matrix and $B$ an invertible matrix. Show that $AB$ is invertible if and only if $A$ is invertible.
I know how to do this using determinants, but how else could you prove this?
Comment: If $AB$ is invertible, $B(AB)^{-1}=A^{-1}$ .
Answer: $A$ is invertible $\implies$ $AB$ is invertible: This is because $(AB)^{-1}=B^{-1}A^{-1}$.
$A$ is invertible $\impliedby$ $AB$ is invertible: use the proven implication ($\implies$) above, applied to the matrices $AB$ and $ABB^{-1}=A$, with the fact that, since $B$ is invertible, $B^{-1}$ is also invertible.
Answer: Let $A$ and $B$ be $n\times n$ matrices. $B$ is invertible, so its rank is $n$.
If $A$ is invertible, then its rank is $n$. Then the rank of $AB$ is also $n$. Therefore $AB$ is invertible.
If $AB$ is invertible, then its rank is $n$. The rank of $A=ABB^{-1}$ is therefore also $n$ (the identity matrix has full rank).
We use the fact that multiplying two $n\times n$ matrices that have full rank results in a full rank $n\times n$ matrix. That is so, because each matrix will map $n$ linearly independent vectors onto another set of $n$ linearly independent vectors.
Answer: Lets say that $A, B \in \mathbf F^{n \times n}$ for some field $\mathbf F$. If $A$ is not invertible then
$\operatorname{span}A = \{Ax : x \in \mathbf F^n\}$
is a proper subset of $\mathbf F^n$. That is, there exists a vector $v \in \mathbf F^n$ such that $Ax = v$ has no solution for any $x \in \mathbf F^n$.
If $AB$ were invertible, then for some $y \in  \mathbb F^n$, $ABy=v$; in particular, $y = (AB)^{-1}v$. But then $x=By$ would solve $Ax = v$. Hence $AB$ is not invertible.
Answer: If $A$ is invertible, $(AB)^{-1} = B^{-1}A^{-1}$.
If $A$ is not invertible, its rank is less than $n$ (the size of the matrices).  Therefore the rank of $AB$ is less than $n$.
Comment: I was very concerned to see affirmative answers thinking the title was the proposition
Comment: How can you say the first line without knowing B is investable?
Comment: OP states "Let A be a matrix and B an *invertible* matrix"
Comment: Oh, whoops. I only read the title.
Answer: For the converse, matrix multiplication is associative so that if C is the inverse of AB, then (AB)C= A(BC) = I.
Answer: A direct proof for $AB$ invertible $\implies  A$ invertible (knowing $B$ is):
If $AB$ is invertible, there exists a matrix $U$ such that
$(AB)U=I$. However, $(AB)U=A(BU)=I$, hence $BU$ is a right-inverse for $A$.
But also, $U(AB)=(UA)B=I$, so $UA=B^{-1}$, and, multiplying on the left by $B$:
$$B(UA)=(BU)A=BB^{-1}=I,$$  which shows $BU$ is also a left inverse for $A$.


Display elements of a String which are not found on the other

Question: We were told to do a program on stings and I wasn't able to attend class because I was sick. I am asking for your help on this task that was given to us.
Create a java program that will ask the user to input two Strings. Compare the two strings and display the letters that are found on the first string but are not found on the second string.
Here is what I have at the moment https://pastebin.com/7a4dHecR
I really have no Idea what to do so any help would be appreciated!
https://pastebin.com/7a4dHecR
import java.util.*;
public class filename{
    public static void main(String[] args){
        Scanner sc =new Scanner(System.in);

        System.out.print("Input first string: ");
        String one=sc.next();
        System.out.println();
        System.out.print("Input second string: ");
        String two=sc.next();

    }
}

Comment: Please read: [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) --- I recommend contacting your instructor/professor/teacher. --- Please read: [Open letter to students with homework problems](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) --- You forgot to ask an actual question. Please [edit] the post and add a focused question.
Comment: What have you tried till now? Try reading about the concepts that were taught in the class the day you were not able to attend and make your way forward from there.
Answer: There are many ways to do this. I'm going to give you some parts you can put together. They are not the shortest or simplest way to solve this particular problem, but they will be useful for other small programs you write.
Here are some hints:
First, figure out how to step through your code with a debugger.
Second, figure out how to find the Javadoc for Java library classes and their methods.
You need to do something for each character in a string. Use a for loop for that:
for (int i = 0; i < one.length(); i++) {
 // your code here
}

You need to get a particular character of a String.
String c = one.substring(i, i+1);

Read the Javadoc for String.substring to understand what the i and i+1 parameters do.
Now you need to find a way to check whether a String contains another String. Look at the Javadoc for the String class.
Then you can put all this together.
Answer: You could try the following:
String diff: StringUtils.difference(one, two);
System.out.println(diff);

Comment: Code-only answers are discouraged. We should rather explain the challenge and how our solution overcomes it. --- The code presented will not compile.
Comment: Oh, my bad. Sorry!


How to test if an R object is a named numeric vector?

Question: I'd like to know if there is a simple and robust way to test if an object is a named numeric vector. Here is an example:
data <- c(2.3, 3.5, 5.7)
typeof(data)
#[1] "double"
mode(data)
#[1] "numeric"
str(data)
# num [1:3] 2.3 3.5 5.7
is.vector(data)
#[1] TRUE
is.numeric(data)
#[1] TRUE

So as you can see from the above, I have created a numeric vector. Now I assign names to the elements.
named_vec <- structure(data, names = c('a', 'b', 'c'))
named_vec <- structure(data, names = c('a', 'b', 'c'))
str(named_vec)
# Named num [1:3] 2.3 3.5 5.7
# - attr(*, "names")= chr [1:3] "a" "b" "c"
names(named_vec)
#[1] "a" "b" "c"

I could use a few compound conditions such as:
if(is.vector(named_vec) & is.numeric(named_vec) & !is.null(names(named_vec)))           {
   "named_vec is a named numeric vector"
 } else {
   "named_vec is not a named numeric vector"
 }
#[1] "named_vec is a named numeric vector"

Or something like this, but it feels like it could fall prey to corner cases:
length(names(named_vec)) == length(named_vec)
#[1] TRUE
names(data)
#NULL

I'm looking for something that is concise and robust.
Comment: If you want a `vector` which is `numeric` and has `names`, then there is nothing wrong in testing each of the above separately. Your first solution looks fine to me.
Comment: Just create a function with your solution and give it a nice concise name, something like `is.named.numeric = function(x) ...`
Comment: `length(names(named_vec)[(names(named_vec) != "")]) == length(named_vec)` for named vectors with missing names
Answer: The only problem I see in your firt solution (the if clause) is that the names of the vector could be incomplete, and I do not know if thats acceptable in your case.
In the second solution, a non-numeric named vector would pass the verification, right? And it seems to me that this is not what you desire.
If you could provide more details about what you want exactly to do with this verification, I could help you a little more.
It is also easier to do
is.vector(f, mode = "numeric")

Thus you verifie both conditions (vector and numeric). Read is.vector help.
Comment: @ursus, I am still not able to post comments in other answers than mine. But I think you got it. Justo to be more clear and concise if you write you write your function like this:  `IsNamedVector <- function(VECTOR) is.vector(VECTOR, mode = "numeric") &  !any(is.na(names(VECTOR)))`. With less tests and an inline function you are gonna have the same results!
Answer: My answer simply combines the comments of @nicola and @Gregor along with the answer provided by @droubi:
Create a new function IsNamedVector. Below is example:
Create Example Data Set
> data <- c(2.3, 3.5, 5.7)
> typeof(data)
[1] "double"
> mode(data)
[1] "numeric"
> str(data)
 num [1:3] 2.3 3.5 5.7
> is.numeric(data)
[1] TRUE
> is.vector(data)
[1] TRUE
> named_vec <- structure(data, names = c('a', 'b', 'c'))
> str(named_vec)
 Named num [1:3] 2.3 3.5 5.7
 - attr(*, "names")= chr [1:3] "a" "b" "c"
> names(named_vec)
[1] "a" "b" "c"

Create Custom Function
> IsNamedVector <- function(VECTOR) {
+   is.vector(VECTOR) & is.numeric(VECTOR) & !is.null(names(VECTOR)) &
+      !any(is.na(names(VECTOR)))
+ }

Test Function
> length(names(named_vec)) == length(named_vec)
[1] TRUE
> names(data)
NULL
> !all(is.na(names(named_vec)))
[1] TRUE
> missing_names_vec <- structure(data, names = c('a', 'b'))
> str(missing_names_vec)
 Named num [1:3] 2.3 3.5 5.7
 - attr(*, "names")= chr [1:3] "a" "b" NA
> IsNamedVector(named_vec)
[1] TRUE
> IsNamedVector(missing_names_vec)
[1] FALSE

Thanks for the help.
Answer: For this kind of tests, I use package checkmate. It is fast and easy to use.
For named numeric vectors, check functions test_numeric(), check_numeric(), and assert_numeric() with parameter names = "named" (for other options, see type under "Arguments" section). The functions differ in output so you should decide, which is the most suitable for you.
Returns logical:
checkmate::test_numeric(1, names = "named")
#> [1] FALSE
checkmate::test_numeric(c(a = 1), names = "named")
#> [1] TRUE
checkmate::test_numeric(c(a = "A"), names = "named")
#> [1] FALSE

Returns string:
checkmate::check_numeric("1", names = "named")
#> [1] "Must be of type 'numeric', not 'character'"
checkmate::check_numeric(1, names = "named")
#> [1] "Vector must be named"

Returns error message:
checkmate::assert_numeric(1, names = "named")
#> Error in withCallingHandlers({: Assertion on '1' failed: Vector must be named.


Linux Traffic Shaping with "tc": QoS filter for requests directly on the host not applied?

Question: I'm trying to reduce the interface thoughput to debug my application on slower network speed.
I've remembered a tc statement to do this on a interface which was working in the past. I used it on a dedicated (remote) development machine.
This is the statement
 tc qdisc add dev wlan0 root tbf rate 250kbit latency 300ms burst 125kbit

It works well when trying to access the local socket from another host, but when accessing a socket on that interface from my local machine, the filter is not being applied.
Interface:
# ifconfig wlan0
wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet XXX.XXX.XXX:XXX netmask 255.255.255.0  broadcast XXX.XXX.0.255
        inet6 xxxx::xxxx:xxxx:xxxx:xxxx  prefixlen 64  scopeid 0x20<link>
        ether XX:XX:XX:XX:XX:XX  txqueuelen 1000  (Ethernet)
        RX packets 31438  bytes 28025182 (26.7 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 27035  bytes 7482740 (7.1 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

Socket (any):
# netstat -lntp | grep 8080
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN      5990/nginx: master

Socket (lo/wlan0):
# netstat -lntp | grep 8080
tcp        0      0 127.0.0.1:8080          0.0.0.0:*               LISTEN      7432/nginx: master
tcp        0      0 XXX.XXX.XXX.XXX:8080      0.0.0.0:*               LISTEN      7432/nginx: master

In the browser I try to access http://XXX.XXX.XXX.XXX:8080/path and the page (>1 MB content + assests) shows immediately (cache cleared before).
On another host that has access to my system all content is loading (visibly) slow.
I looked into other resources of course, but non of them is working for me:

Port based bandwidth shaping
Traffic shaping on Linux with HTB: weird results
http://www.cyberciti.biz/faq/linux-traffic-shaping-using-tc-to-control-http-traffic/
https://coderwall.com/p/zpckbg

I also tried creating a class using tc and mangling packets using iptables (as shown in the 3rd link) was not possbile on Fedora 19. The rule is ignored (no error when adding the rule, but it does not appear when issuing iptabls -n -L).
So, I suspect the filtering is only applied for packages arriving on a interface or local requests do not pass the filtering layer.
Envrionment:

Fedora Linux 19
Kernel 3.11.10-100.fc18.x86_64
tc utility, iproute2-ss121001
Nginx is the serving HTTPD

How can I get traffic shaping working for local requests?
(Tips for alternative solutions also welcome. Next I'll try out squid as reverse proxy with delay classes.)

It should be solved directly on the host
Additional hardware should not be required
I prefer solutions not limited to HTTP (to test Websockets or other protocols too)
Comment: I've tried using Squid, but even though the `delay pools` do work, limiting the throughput, I does not show the same loading behaviour compared to rate limiting using `tc`. Meanwhile I found [another workaround using lighthttpd](http://stackoverflow.com/questions/13654663/how-can-i-serve-http-slowly).
Comment: The filter is not applied because the traffic passes through the loopback interface (**lo**), not **wlan0**.
Answer: Packets destined for the local machine will not pass through the network interface. For example, you can flood the IP address of your eth0 interface (lets say 100Mbit link) with 1GBit of traffic while not passing any data through it. Hence the scheduler will not be used.
FWIW, it's much easier to use the netem scheduler for what you're testing instead of tbf. netem is meant to do exactly what you're trying to do. Yet it'll still not work in your case.
There's a very dirty hack that I used to do for tests that involved two interfaces. Let's say you have eth0 and eth1:

You connect them with each other with a cable
You assign IP address 10.0.0.1/24 on eth0 and and 10.0.1.2/24 on eth1
You add NAT rules on both interfaces saying:

Traffic exiting eth0 with DST IP 10.0.0.2 is DNATed to 10.0.1.2
Traffic exiting eth1 with DST IP 10.0.1.1 is DNATed to 10.0.0.1

You add static ARP entries saying that:

10.0.0.2 maps to the MAC address of eth1, but associated with interface eth0
10.0.1.1 maps to the MAC address of eth0, but associated with interfaces eth1

Then you may ping 10.0.0.2 and this will exit eth0 and enter back eth1. After that you can add your desired qdisc on the appropriate interface and run your tests.
Comment: Thanks for confirming that the filtering mechnism is not used for local access to a socket. The 2nd part of your answer is not applicable as I'm looking for a solution that's working without external hardware (I'll update my question).


In what ways does (late) Romantic-era orchestration practice differ from contemporary film orchestration?

Question: By contemporary film orchestration I mean, broadly speaking, the orchestration style of popular mainstream film composers like John Williams and James Horner. It seems to me that these 'Hollywood' composers derive a lot of inspiration from historic Romanticism (especially the latter half of that era); but at the same time the orchestral 'sound' of a Horner score seems totally different from the sound of, say, a Wagner or a Bruckner or even a Mahler score. I would like to pinpoint wherein this difference consists, apart from the harmonic and contrapuntal language per se.
I do realize this is a rather vague and broad question, about something that must in all likelihood be very difficult to put into words. But it nonetheless seems sufficiently interesting to me to ask. (If the mods disagree, I can respect that.)
Comment: This is potentially a big question. While I agree Williams is heavily influenced by romantic music from 1850-1950, Horner has his own style which is different from Williams and Zimmer even more so. In other words, I don't think we can reasonably discuss "contemporary film music orchestration" because there is too much variation in style among film composers of the last 40 years.
Comment: I can't make a full answer out of this, but consider everybody learns from what went before, just like pop, & then listen to Holst's Planet Suite. It has the building blocks of just about everything in orchestral film scoring since the 70's.
Comment: @musicamante I feel like only comparing James Horner to a single Romantic composer is an entire answer separate from comparing Williams to that same composer. To me Williams and Horner are too different between them for the phrase "like Williams and Horner" to be meaningful. Compare *Thunderheart* with *Jaws* - it's like two completely different genres.
Comment: @ToddWilcox I'd say even 60 years at least, but OP did specify (even if in a vague way) "composers like John Williams and James Horner", which would probably exclude composers with a more "modern approach" that still use a "classical" orchestra such as Zimmer or even Giacchino (who normally has a bit more "classical" style than the former), but probably include others like Alex North, Jerry Goldsmith or even Howard Shore.
Comment: @ToddWilcox well, those are indeed different, but we could say the same even for the same author: for instance, while there are some obvious typical similarities in orchestration and treatment of instruments, Williams' scores for "Catch Me If You Can" and "Harry Potter and the Chamber of Secrets" are *very* different, despite having been composed in the same year. I believe the OP is referring to a broader sense of the "usual" composer style, for which Horner can certainly be more affine to Williams than, for example, Hans Zimmer or Randy Newman, even when they use a more symphonical approach.
Answer: As already noted by the OP, the question is indeed very broad, and this answer obviously takes a very subjective approach to what is being asked, so I'm mostly going to address music about the cited composers (Williams, Horner) and those that could be considered affine to their "classical" style.
Conceptually speaking, they do not differ a lot.
There are obvious differences, and what you point out as a "different sound" between Horner and Wagner, is the difference in "sound" of each composer.
For instance, despite belonging to the same era, using a very specific musical style and almost always identical instrumentation, you can usually recognize if a composition is written by Bach or Händel even if you have never listened to it.
"Classical"[1] film music also tends to use much more distinct characters for any given piece (except for longer "suites"), and that's because they usually have a single composition for a very specific scene, which has to portray what the director wants to highlight. While they do have "developments" of themes, their forms rarely use classical layout forms, as what happens on the screen is what actually creates those layouts, sometimes leading to section repetition, abrupt changes in character, etc. Another important aspect is that some scenes require some time for their development, forcing the composer to extend sections that are sometimes not really "musically important", and that's because the music shouldn't distract the viewers from what's happening, possibly leading them to beliving that something is happening while it's not (yet).[2]
Orchestral film music is also often "stereotyped", with very large string sections for moody and melodic passages, powerful brass groups for heroic and thrilling scenarios and, most importantly, a much larger percussion palette (remember that most instruments now commonly used in modern orchestral compositions were rarely considered for classical compositions, and some were not even invented yet).
Note that many composers that could still be considered "classical" in a broader sense, have a very different approach, sometimes radically. For instance, Jerry Goldsmith is usually closer to the mentioned composers, and a bit more than Alan Silvestri could be, but still somehow more modern (including a larger usage of electronic instruments or a sound that resembles them). And while Hans Zimmer adopted a more symphonical approach in his maturity, his style is clearly very different. Other composers chose to follow an even more different attitude, while mostly keeping a typical orchestral sound, like Elliot Goldenthal. It's also worth noticing that sometimes even normally-classical composers take a different path that is closer to their formation: Williams is known to write interesting jazzy music (see the score for Catch Me If You Can, or "Banning Back Home" from Hook) as much as Danny Elfman often goes back to his pop/rock roots.
That said, consider that those "classical" composers also explicitly borrow from previous musical styles (sometimes for personal choice, others, obviously, due to film requirements) which is something that happened much less often in the past, and while doing that they also "modernize" those styles with instrumentation and orchestration methods that are not typical of those styles.
Take for instance the suite "The Forest Battle" from Star Wars: Episode VI - Return of the Jedi:

You can clearly hear elements from Prokofiev and Shostakovich, but with orchestration choices and instrumentation that were not exactly from those eras (even considering their rather modern approaches). Lots of winds, fast and bright themes, but also strings used much more as a sound palette, a more "romantic" approach for more broad/heroic themes and, obviously, a lot more of colorful percussions.
It's also worth noticing an interesting aspect about Horner, since you mentioned him: he has been known (even in his life) as a nasty borrower, sometimes taking exact excerpts of other earlier composers and with very little adaptation.
Take for instance "Death of Tybalt" from Prokofiev's Romeo and Juliet (note the section starting at 1:18):

Then listen to the soundtrack version of "Stealing the Enterprise" by James Horner, for the score of Star Trek III:

The initial theme of the violins is not only the exact copy, but it's also in the same key. The orchestration is a bit different though, including harp arpeggios and a glockenspiel (or crotales), which make it a bit lighter in tone, considering that the scene has some elements of comedy.
The violin part at the beginning didn't survive the film score, some say that the producers asked him for less "movement" at the beginning in order to provide a better effect in the development of the scene, but considering that in some cases his "borrowings" also led to litigation (see the link above), it's also possible that they required him to remove it for copyright reasons: the film was made in 1984, but Prokofiev died in 1953, so Romeo and Juliet wasn't public domain yet.
[1] with "classical" I mean music that uses a symphonic orchestra with compositions that stylistically resemble late 19th-early 20th century music; also consider composers of the Hollywood's Golden Age, like Max Steiner, Alfred Newman and Erich Korngold (the latter of which is known as the most influential composer in "modern" film music, and also a known inspiration for John Williams himself).
[2] there are some rare exceptions, and the most known is that from the final chase scene of E.T. the Extra-terrestrial, as Spielberg loved so much the music Williams wrote that he actually re-edited the scene to match the whole suite in order to leave it almost unchanged.
Comment: That was an enjoyable read, ty for the effort.
Comment: Thank you very much for your extensive answer. Really helpful!


Criar função para fazer cálculos com um determinado operador utilizando JavaScript

Question: Não sei se daria certo, ou se seria a melhor opção, mas eu tenho um código que consiste no seguinte:
Situando que o valor operacao venha com o argumento +, e eu queira usar ele para somar dois valores. Como eu deveria fazer?
Exemplo:
function calcular(operacao){

    var num1 = 6, num2 = 2;

    var resultado = num1 + operacao + num2;
    mostrarVisor(resultado);
}

function mostrarVisor(result){

    document.getElementById('visor').innerHTML = result;
    // aqui eu escrevo o resultado na tela!
}

Answer: Para não usar o eval, que pode trazer alguns riscos, você pode criar uma função que faz uso do switch para determinar a operação.
Algo assim:

function operate(x, y, op) {
  switch (op) {
    case '+':
      return x + y;
    case '-':
      return x - y;
    case '*':
      return x * y;
    case '/':
      return x / y;
    default:
      throw new Error('Invalid operator.');
  }
}

console.log(operate(4, 3, '+')); // 7
console.log(operate(6, 4, '-')); // 2
console.log(operate(3, 3, '*')); // 9
console.log(operate(8, 2, '/')); // 4

Mas você ainda pode utilizar o eval, se desejar. Sugiro apenas que crie uma série de validações para se assegurar que nenhum código arbitrário será executado:

const isNumber = (val) => typeof val === 'number';

function operate(x, y, op) {
  const validOperators = ['+', '-', '*', '/'];

  if (!isNumber(x) || !isNumber(y) || !validOperators.includes(op)) {
    throw new Error('Invalid arguments.');
  }

  return eval(`${x} ${op} ${y}`);
}

console.log(operate(4, 3, '+')); // 7
console.log(operate(6, 4, '-')); // 2
console.log(operate(3, 3, '*')); // 9
console.log(operate(8, 2, '/')); // 4
Answer: Amgio, acredito que o que você esteja procurando seja o método eval(), ele recebe uma String, e se ela for uma expressão o eval irá calcular o resultado:
eval("1 + 1");

A saída do comando a cima será 2


Why some users are getting FC at database.close?

Question: I have the following code:
public class DbAdapter {
...
    public DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }
...

This close method is called at onDestroy of MainActivity:
@Override
protected void onDestroy() {
  super.onDestroy();

  mDbHelper.close();
}

I've got the following error log from my user:
device_model:bravo
build_version:1.6.17
condition:1
processName:spb.bridges
pid:23493
uid:10057
tag:null
shortMsg:android.database.sqlite.SQLiteException
longMsg:android.database.sqlite.SQLiteException: unable to close due to unfinalised statements
stackTrace:java.lang.RuntimeException: Unable to destroy activity {my.package/my.package.MainActivity}: android.database.sqlite.SQLiteException: unable to close due to unfinalised statements
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:2680)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:2698)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:2814)
at android.app.ActivityThread.access$1600(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3694)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: unable to close due to unfinalised statements
at android.database.sqlite.SQLiteDatabase.dbclose(Native Method)
at android.database.sqlite.SQLiteDatabase.onAllReferencesReleased(SQLiteDatabase.java:323)
at android.database.sqlite.SQLiteDatabase.close(SQLiteDatabase.java:884)
at android.database.sqlite.SQLiteOpenHelper.close(SQLiteOpenHelper.java:220)
at spb.bridges.DbAdapter.close(DbAdapter.java:177)
at spb.bridges.MainActivity.onDestroy(MainActivity.java:159)

What is wrong with my code?
Answer: It's possible that they try to close the app while the app is performing a database operation.  The easiest thing to do would be to put a try/catch/log around that mDbHelper.close(); statement.
Comment: what kind of Exception should I catch?
Comment: `SQLiteException` or `Exception` itself.  It's bad practice, but it is better than throwing out the Force Close.  The underlying cause may be that it's trying to perform a database operation when you `.close()` it.  Do you have long-running DB operations?
Answer: OnDestroy() is not guaranteed to run.  If say a user is using a task killer, it may sudo kill -9 the thing, and not run.  Other people on SO have also said there are situations where even Android won't call it.  It's supposed to be called right before android kills it to free up memory.
It would probably be best if you put that logic to close in OnPause() and then again initialized in OnResume().


Too much time taking for the copy the data

Question: I have a some problem with for loop copies' time I don't why for loop is taking much time for the copy small data size.
I am using PIC24FJ256GL406 MCU and everything is fine but when operate the UART micro-controller is running slow because some delay is occurring while copy the buffer data.
Let me explain you with code and debug log.
Here I am posting the function for the UART transmission. this function is generally transfer only FIRST character and Rest of the byte will be transfer in the Interrupt routine service.
My clock Frequency is 32Mhz So peripheral will be 16 Mhz.
I did not understand why for loop is taking Almost 20 MS for the copy the 16 byte data only. So This time will be increase if data is more.
unsigned int UART1_WriteBuffer(const uint8_t *buffer, const unsigned int bufLen)
{
    //transmit first char

    U1TXREG = buffer[0];

    while (!U1STAbits.TRMT);

    numBytesWritten = bufLen - 1;

    totalByte = 0;

    //get the current time stamp
    WSTimestamp currentTimeStamp = WSGetCurrTimestamp();

    WMLogInfo(GEN_LOG, "current time stamp %ld", currentTimeStamp);

    uint16_t i = 0;

    //memset
    memset(&uart1_txByteQ, 0x00, sizeof(uart1_txByteQ));

    for (i = 0; i < numBytesWritten; i++)
    {
        uart1_txByteQ = buffer[i + 1]; //copy the data
    }

    _U1TXIE = 1;

    //get last time stamp
    WSTimestamp lastTimeStamp = WSGetCurrTimestamp();

    WMLogInfo(GEN_LOG, "last time stamp %ld ", lastTimeStamp);

    ///print the debug
    WMLogInfo(GEN_LOG, "total = %ld MS time taken fo copy the = %d byte", lastTimeStamp - currentTimeStamp, numBytesWritten);

    return bufLen;

}

My Interrupt Routine service.

void __attribute__((interrupt, no_auto_psv)) _U1TXInterrupt(void)
{
    if (totalByte < numBytesWritten)
    {
        U1TXREG = uart1_txByteQ[totalByte++];

        while (!U1STAbits.TRMT);
    }
    else
    {
        _U1TXIE = 0;
        _U1TXIE = 0;
    }

}

Console Log.
This is function log. please note.

GEN:main loop current time stamp 6503<\r><\n>
GEN:current time stamp 6506<\r><\n>
GEN:last time stamp 6526 <\r><\n>
GEN:total = 20 MS time taken fo copy the = 16 byte<\r><\n>
GEN:command "AT+QREFUSECS=1,1<\r>" send with len [17]

Comment: It's a transmit interrupt.  When it happens, load the tx register.  Do not pass 'Go', do not collect any delays by pointless polling.  When there is no more to send in the handler, disable the interrupt.  When there is a buffer to send, check if the interrupt is disabled and, if it is, enable it and load the first char into the tx register.
Comment: What *is* `uart1_txByteQ`? Is it an array? Then an assignment like `uart1_txByteQ = buffer[i + 1];` doesn't make sense, and shouldn't even build. Please try to create a [mcve] to show us.
Comment: And if you want to copy, why don't you use `memcpy`?
Comment: @Someprogrammerdude Yes uart1_txByteQ Is an array. As you can see the function there only buf[0] character is transmitting and rest of the character will be transfer in Interrupt Routine So uart1_txByteQ Is global Array So i Copy buffer[i+1] to the uart1_txByteQ because 1 Char already Transferred.
Comment: You are waiting in the interrupt for transmitting the byte `while (!U1STAbits.TRMT);` and wasting time.
Perhaps and if possible, you should do some `ready-test` before `U1TXREG = xx`
Comment: Why don't you:   1-prepare the buffer 2-enable interrupts 3-write first char? At the moment, I would await the first interrupt, you haven't enabled interrupts and the buffer is not prepared?
Comment: @Holger Can I Use while (!(U1STAbits.UTXBF == 1)) in interrupt for the transmission. I thing Loading character to the interrupt without check TRMT and UTBF is not working
Comment: @MartinJames Thank you for you suggestion. It now fine. I fix the problem.
Comment: @KetanVadodariya then you should either answer your own question, accept and/or upvote the answer given, or delete this question since you say you fixed the problem but didn't explain how.
Answer: The long delays are caused by busy-waiting for flags in combination with some use-case bug. Why are you using Tx interrupt in the first place in case you intend to busy-wait poll for a flag anyhow? The ISR doesn't make sense - it would seem that you should simply drop Tx interrupts entirely.
In addition, you have a naive implementation of buffer copies. It's a very common embedded systems beginner bug to hard copy RAM buffers needlessly. There's very few cases where you actually need to do hard copies and this isn't one. Instead you should use a system with double buffers and simply swap a pointer between them:
static uint8_t buf1 [n];
static uint8_t buf2 [n];
static uint8_t* rx_buf = buf1;   // buffer used by rx ISR
static uint8_t* app_buf = buf2;  // buffer used by the application

...

if(rx_done)
{ // swap buffers
  uint8_t* tmp = rx_buf;
  rx_buf = app_buf;
  app_buf = tmp;
}

This also solves the double-buffering problem where an UART rx interrupt needs to store it's incoming data somewhere at the same time as the main program uses data. You'll need to protect against race conditions somehow - with a semaphore etc. And you'll need to declare variables shared with ISRs volatile to protect against bad compiler optimizers.
Comment: Here There is not problem with buffer. Here problem Is I have an 1024 Byte data which I have to transfer to the UART Interrupt So I wrote the function Who Transfer the first character Only And rest of it it would be transfer via Interrupt service. Because of while on in Transfer function so it was holding process. To Avoid I did this.


Fourier transform of $\frac{1}{f(t)}$

Question: Suppose we know Fourier transform of $f(t)$ is $F(\omega)$.
Can we find Fourier transform of $\frac{1}{f(t)}$.
I was thinking we can write $\frac{1}{f(t)}=( f(t))^{-{1}}$. So I guess a more general question is can we find Fourier transform of $(f(t))^k$ for any k?
Comment: For positive, integral $k$, use the convolution theorem.
Comment: Yes you are right. what about negative k?
Comment: If I knew something about negative $k$, I would have said it.
Answer: For $ k \geq 1$, the answer is as above. For $k < 0$, in general $F(\omega) = \int_{-\infty}^\infty \frac{1}{f(x)}e^{-2\pi i \omega x} dx$ need not be even defined. For instance, if
$$f = x^{-2}\chi_{|x| > 1} + \chi_{|\chi| \leq 1},\quad \chi_A(x) = \begin{cases} 1 & x \in A \\ 0 & x \notin A\end{cases}$$
then $F(\omega)$ is defined since the integrand is finite, but $1/f$ is not even integrable and I do not know if one can make sense of this without using tempered distributions. I do not know if one can salvage anything useful without using properties specific to the function $f$.
Answer: In general, $1/f$ may not have a Fourier transform, even in the sense of tempered distributions.  Here's one case where it does.
Suppose $f(t) = p(t)/q(t)$ where $p$ and $q$ are polynomials with no real roots.
The Fourier transform of $f$ can be obtained by expanding $f$ in partial fractions: if
$$ f(t) = r(t) + \sum_{j=1}^m \dfrac{a_j t + b_j}{(t - c_j)^2 + d_j^2}$$
where $r$ is a polynomial of degree $m$ and $a_j, b_j, c_j, d_j$ are real, $d_j > 0$, then $F(\omega)$ is
a linear combination of the Dirac $\delta$ and its derivatives up to the $m$'th derivative, $e^{-\omega(ic_j + d_j)} H(\omega)$ and $e^{\omega(-ic_j + d_j)} H(-\omega)$ ($H$ = Heaviside).  And similarly for $1/f(t)$ where we use the partial fraction expansion of $1/f$.

Fourier transform of $\frac{1}{f(t)}$


Skip items with empty values in View

Question: I've a view filled with events. Some events carry a date, some don't.
How can I leave out those without a date? There should be somewhere a empty($date) ? hide($view) : break;. But I don't know how to do this with a view. Any suggestions?
Answer: Add a filter to the View, and filter out all events where date is NULL.

Skip items with empty values in View


Trouble installing Ruby with RVM on Cygwin

Question: I'm on Windows and I currently have Ruby v2.1.5 as that is what came with RailsInstaller. However, I need to downgrade to 2.1.1 for another project and I'm not sure how to.
I have installed rvm on Cygwin and I'm getting these problems when trying to execute rvm install 2.1.1
Searching for binary rubies, this might take some time.
No binary rubies available for: cygwin/unknown/x86_64/ruby-2.1.1.
Continuing with compilation. Please read 'rvm help mount' to get more
information on binary rubies.

and
Checking requirements for cygwin.
Installing requirements for cygwin.
Updating system.
Installing required packages: mingw64-i686-gcc, mingw64-x86_64-gcc.
Requirements installation successful.
Installing Ruby from source to: /home/K/.rvm/rubies/ruby-2.1.1, this may take a while depending on your cpu(s)...
ruby-2.1.1 - #downloading ruby-2.1.1, this may take a while depending on your connection...
ruby-2.1.1 - #extracting ruby-2.1.1 to /home/K/.rvm/src/ruby-2.1.1....
ruby-2.1.1 - #applying patch /home/K/.rvm/patches/ruby/2.1.1/libyaml.patch.
ruby-2.1.1 - #applying patch /home/K/.rvm/patches/ruby/changeset_r45225.diff.
ruby-2.1.1 - #applying patch /home/K/.rvm/patches/ruby/changeset_r45240.diff.
ruby-2.1.1 - #configuring....................................................
ruby-2.1.1 - #post-configuration..
ruby-2.1.1 - #compiling....................................................
Error running '__rvm_make -j4',
showing last 15 lines of /home/K/.rvm/log/1433355357_ruby-2.1.1/make.log
make[2]: Leaving directory '/home/K/.rvm/src/ruby-2.1.1/ext/-test-/printf'
exts.mk:109: recipe for target 'ext/-test-/printf/all' failed
make[1]: *** [ext/-test-/printf/all] Error 2
make[1]: *** Waiting for unfinished jobs....
installing default rational libraries
installing default recursion libraries
make[2]: Leaving directory '/home/K/.rvm/src/ruby-2.1.1/ext/-test-/postponed_job'
linking shared-object -test-/rational.so
linking shared-object -test-/recursion.so
make[2]: Leaving directory '/home/K/.rvm/src/ruby-2.1.1/ext/-test-/recursion'
make[2]: Leaving directory '/home/K/.rvm/src/ruby-2.1.1/ext/-test-/rational'
make[1]: Leaving directory '/home/K/.rvm/src/ruby-2.1.1'
uncommon.mk:180: recipe for target 'build-ext' failed
make: *** [build-ext] Error 2
++ return 2
There has been an error while running make. Halting the installation.

Any help would be appreciated. Thanks
Answer: You need to patch ruby soure code so it would compile on cygwin. Thankfully rvm supports patches out of the box!
Create a file called cygwin.patch with the following content:
--- /ext/-test-/printf/printf.c 2014-06-29 10:17:20.000000000 -0700
+++ /ext/-test-/printf/printf.c 2015-07-08 16:58:15.882479100 -0700
@@ -1,3 +1,4 @@
+#define __STRICT_ANSI__ /* avoid conflicting utoa */
#include <ruby.h>
#include <ruby/encoding.h>

And now simply execute rvm with a --patch parameter like shown below:
rvm install 2.2-head --patch cygwin.patch


If $\alpha(s)$ is an oval, prove that $\mathbf{t}$'' is parallel to $\mathbf{t}$ at at least four points.

Question: If $\alpha(s)$ is an oval, prove that $\mathbf{t}$'' is parallel to $\mathbf{t}$ at at least four points.
Attempt:
Using the Four Vertex Theorem we know the oval has at least four vertexes, so at these four points curvature has a relative maximum or minimum. Let k be the curvature.
Since  k(s) = $<\mathbf{t}′(s),\mathbf{n}(s)>$ then k'(s) = $<\mathbf{t}′′(s),\mathbf{n}(s)> + <\mathbf{t}′(s),\mathbf{n}′(s)>$.
Since k'(s) = 0 at the four vertex $<\mathbf{t}''(s), \mathbf{n}(s)> + <\mathbf{t}'(s), \mathbf{n}'(s)>$ = 0 at these four points.
Now since $\mathbf{t}'(s)$ = k(s)$\mathbf{n}(s) \rightarrow$ k'(s) = $<\mathbf{t}''(s), \mathbf{n}(s)> + <k(s)\mathbf{n}(s), \mathbf{n}'(s)>$
I can write that $<k(s)\mathbf{n}(s), \mathbf{n}'(s)>$ = 0 at the four vertex because k(s) is just a constant and $\mathbf{n}(s)$ and $\mathbf{n}'(s)$ are perpendicular?
Then $<\mathbf{t}''(s), \mathbf{n}(s)>$ = 0, and from this I know that $\mathbf{t}''(s)$ is perpendicular to $\mathbf{n}(s)$.
Also I know that $\mathbf{n}(s)$ is perpendicular to $\mathbf{t}(s) \rightarrow \mathbf{t}(s)$ is parallel to $\mathbf{t}''(s)$ at these four points.
Does this proof work?
Comment: Oops. So if $k'=|\mathbf t''|$, then it would follow that since $|\mathbf t|=1$, then $|\mathbf t'|=0$? You need to differentiate $|\mathbf f|$ more carefully. (Hint: Write this in terms of dot product.)
Comment: @Ted Shifrin k(s) = $<\mathbf{t}'(s), \mathbf{n}(s)>$ then k'(s) = $<\mathbf{t}''(s), \mathbf{n}(s)> + <\mathbf{t}'(s), \mathbf{n}'(s)>$. Thank you for your help I'm still new to this, is this heading in the right direction?
Comment: Yes, this is fine. Or use $k(s)^2 = \langle \mathbf t'(s),\mathbf t'(s)\rangle = 2\langle \mathbf t''(s),\mathbf t'(s)\rangle$.
Comment: @TedShifrin Thank you so much for your help in this problem! I edited my post correcting my previous mistakes, and I think I was able to finish the proof. If you get a chance could you let me know if this looks correct. Thanks.
Comment: Well done. I've made a few minor suggestions in the answer, so you can accept it and your question will no longer appear unanswered :)
Comment: @TedShifrin Thanks for all the help!
Comment: You're most welcome. Enjoy learning some differential geometry :)
Answer: Yes, you have it, basically.  More seriously,  $\langle\mathbf t'(s),\mathbf n'(s)\rangle = 0$ for all $s$, not just at the vertices, as $\mathbf t'(s)$ is a multiple of $\mathbf n(s)$ and $\mathbf n'(s)$ is a multiple of $\mathbf t(s)$. Perhaps you should emphasize at the end that since you're working in $\Bbb R^2$, any vector orthogonal to $\mathbf n(s)$ must be a scalar multiple of (parallel to) $\mathbf t(s)$.


In reduxjs/toolkit on first dispatch() action.payload is undefined, second dispatch() passes correct data

Question: I cannot figure out why on first dispatch() call data passed as prop which it then read by reducer is undefined, but when I instantly call dispatch() again it then passes proper value.
this is how store.ts is defined
import addEditLuxmedBenefitSystemsSlice from 'pages/edit-blind/redux/add-edit-benefits-slice';
import { PreloadedState } from 'redux';

export const reducer = combineReducers({
  addEditLuxmedBenefitSystemsSlice: addEditLuxmedBenefitSystemsSlice,
});
export type RootState = ReturnType<typeof reducer>;

export function setupStore(preloadedState?: PreloadedState<RootState>) {
  return configureStore({
    reducer,
    preloadedState,
  });
}

this is my slice:
import { createSlice } from '@reduxjs/toolkit';
import { LuxmedBenefitUserType, BenefitSystemsUserType } from '../types';

export const addEditLuxmedBenefitSystemsSlice = createSlice({
  name: 'addEditLuxmedSlice',
  initialState: [] as LuxmedBenefitUserType[],
  reducers: {
    addEditBenefits: (state, action) => {
      const { id } = action.payload;
      console.log(id);
      if (!state.length) {
        state.push(action.payload);
      }
    },
  },
});

export default addEditLuxmedBenefitSystemsSlice.reducer;

export const addEditLuxmedBenefitSystemsActions = addEditLuxmedBenefitSystemsSlice.actions;

And here how dispatch() is called in onSubmit funtion:
export const LuxmedBenefitComponent = () => {
  const { currentEditBlind } = useSelector((state: RootState) => state.editBlind);
  const { id, name, lastName, profileName } = currentEditBlind!;
  const userProps = { id, name, lastName, profileName };
  const [luxmedBenefitUser, setLuxmedBenefitUser] = useState<UserLuxmedBenefitType>();
  const [isFormSubmitted, setIsFormSubmitted] = useState<boolean>(false);

  const dispatch = useDispatch();

  const displayParagraphHandler = () => {
    setIsFormSubmitted(true);
    setTimeout(() => {
      setIsFormSubmitted(false);
    }, 4000);
  };

  const { values, handleChange, handleSubmit, resetForm } = useFormik({
    initialValues: {
      contractForm: '',
      userRelation: '',
      offerType: '',
      totalPrice: '',
      employerCost: '',
      employeeCost: '',
      comments: '',
    },
    onSubmit: (values) => {
      setLuxmedBenefitUser({ ...userProps, ...values });
      resetForm();
      displayParagraphHandler();
      dispatch(addEditLuxmedBenefitSystemsActions.addEditBenefits(luxmedBenefitUser));
    },
  });

Answer: useState hooks are asynchronous.
Inside of onSubmit, you call setLuxmedBenefitUser and then try to use the newly updated luxmedBenefitUser. But, being asynchronous, it hasn't been updated yet.
Simply store the new value as it's own variable so that you can use it in both contexts:
    onSubmit: (values) => {
      const updatedLuxmedBenefitUser = {...userProps, ...values};
      setLuxmedBenefitUser(updatedLuxmedBenefitUser);
      resetForm();
      displayParagraphHandler();
      dispatch(addEditLuxmedBenefitSystemsActions.addEditBenefits(updatedLuxmedBenefitUser));
    },


Change form title for a custom entity

Question: I'm just trying to clone a d7 site in 8.  My first step was to use drupal console to generate a custom entity.  Everything is working fine but I want to change the title of the form to "Create project" instead of the default "Add project".
I don't see "Add " anywhere except for module.links.action.yml, but that is just the local action - it doesn't change the name of the form.
The root of the directory looks like:
config
  schema
    project_entity_type.schema.yml
src
  Entity
    ...several classes
  Form
    ...several classes
  templates
    ...couple template files
  Tests
    LoadTest.php
module.page.inc
module.links.action.yml
module.links.menu.yml
module.links.tasks.yml
module.module
module.permissions.yml

Comment: Did you find a solution?
Comment: @Saulius This was just a play-around project so it never made it past a demo phase; however, I posted my solution below - not sure if it's the best way or not.
Answer: The answer comes from here: https://www.drupal.org/node/2187643.
Note: change "module" in the below code to the name of your module.
The first step is to register an event subscriber service. In module.services.yml:
services:
  module.route_subscriber:
    class: Drupal\module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Next, create your class RouteSubscriber and extend RouteSubscriberBase:
  namespace Drupal\module\Routing;

  use Drupal\Core\Routing\RouteSubscriberBase;
  use Symfony\Component\Routing\RouteCollection;

  /**
   * Subscribe to the Route to change page titles.
   */
  class RouteSubscriber extends RouteSubscriberBase {

    private function alterRoutes(RouteCollection $collection) {
      if ($route = $collection->get('entity.project_entity.add_form')) {
        // set the title (or override '_title_callback' below)
        $route->setDefault('_title', 'Create Project Request');
        // unset the _title_callback; alternatively you could override it here
        $route->setDefault('_title_callback', '');
      }
    }
  }

Note that you receive a RouteCollection in alterRoutes and then using the $collection-get() will return an instance of Route.  The documentation for Route can be found here: http://api.symfony.com/2.7/Symfony/Component/Routing/Route.html
If you're having trouble figuring out what your routes are, the excellent drupal console drupal route:debug tool will help you.
Comment: To bad this doesn't seems to work on the html ``, works great for the page title 'tho. :)

Change form title for a custom entity


Radius of convergence for complex power series

Question: I am supposed to find the radius of convergence for the complex power series $$\sum_{n=0}^{\infty}(-1)^n2^nz^{2n+2}$$
I know that the radius of convergence is calculated by $\frac{1}{R}=\limsup_{n\to\infty}|a_n|^{1/n}$, which in this case means
$$\frac{1}{R}=\limsup_{n\to\infty}|(-2)^n|^{1/n}=2$$
$$\Rightarrow R=\frac{1}{2}$$
but the answer is supposed to be $R=\frac{1}{\sqrt{2}}$. Where did I go wrong? Is it because of the $z^{2n}$ in the series?
Comment: That formula for $R$ is for $\sum a_n z^n$ not $\sum a_n z^{2n+2}$.
Comment: How do I calculate the radius for $\sum a_nz^{2n+2}$? Is there a formula, or do I have to manually find where it converges?
Answer: Yes, you went wrong because of the $z^{2n}$. You're assuming that $a_n=(-1)^n2^n$. That's not so. In fact $a_{2n+2}=(-1)^n2^n$, while $a_k=0$ if $k$ is not of the form $k=2n+2$.
The best way to look at these things, in my opinion, is to forget that $|a_n|^{1/n}$ and know this: The radius of convergence is the supremum of the $r$ such that $|a_n|r^n$ is bounded.
So here you'd ask yourself when $2^nr^{2n+2}$ is bounded. Since $2^nr^{2n+2}=(2r^2)^nr^2$, it's bounded if and only if $2r^2\le1$. Which is if and only if $r<1/\sqrt 2$. So the radius of convergence is $1/\sqrt 2$.
Answer: If you insist on using the Hadamard formula, here's how it can be done.
$$\sum_{n=0}^\infty (-1)^n 2^n z^{2n+2} = z^2 - 2z^4 + 4z^6 - 8z^8 + 16z^{10} - \dotsb := \sum_{n=2}^\infty b_n z^n$$
where $b_n = 0$ if $n$ is odd and $(-2)^{n/2-1}$ if $n$ is even.
Then the sequence $|b_n|^{1/n}$ alternates between $0$ and $2^{1/2-1/n}$ according to the parity of $n$, so the sequence of suprema converges to $\sqrt{2}$.
The calculation is simpler if one factors out $z^2$ initially, because then the series is equal to $$z^2\sum_{n=0}^\infty c_n z^n$$ where $c_n = (-2)^{n/2}$ for even $n$, and 0 otherwise.


Comparing multigroup CFAs: Improved fit with more restrictions

Question: I have conducted a CFA for a one-factor measurement model and then proceeded to do multigroup CFAs to test for measurement variance for gender and age (binary variable, median split). Testing for measurement invariance proceeds as would be expected for gender, but I am getting some strange results when testing for scalar invariance on age. Specifically, the fit indices all show improved fit from the less restrictive model to the more restrictive model. What might be the issue?
Details
CFA is done with the cfa() function in lavaan version 0.6-13 and the fit objects are compared with the compareFit() function in semTools version 0.5-6.
The lavaan model syntax:
ghmodel <- 'harm =~ Q5_col + Q6_col + Q7_col + Q8_col + Q9_col + Q10_col + Q11_col'

The Qx_col variables have 5 ordinal response alternatives coded with the levels 0, 1, 2, 3, 4 in the data frame "gh".
The general CFA model:
ghfit <- cfa(ghmodel, data = gh, ordered = TRUE)

The binary age variable is coded like this:
gh <- gh %>%
  mutate(ageBinary = case_when(Age < 38 ~ 0,
                               Age >= 38 ~ 1))

Now for the two multigroup models for age and the comparison:
ghfitAge2 <- cfa(ghmodel, ordered = TRUE, data = gh, group = "ageBinary",
          group.equal = "loadings")
ghfitAge3 <- cfa(ghmodel, ordered = TRUE, data = gh, group = "ageBinary",
          group.equal = c("loadings", "intercepts"))
comp <- compareFit(ghfitAge2, ghfitAge3)
summary(comp)

At the compareFit() stage I get the following warning message:

Warning message:
In (function (object, ..., method = "default", A.method = "delta",  :
lavaan WARNING:
Some restricted models fit better than less restricted models;
either these models are not nested, or the less restricted model
failed to reach a global optimum. Smallest difference =
-25.2639971395378

Now the models are nested as can be seen from the code and the less restricted model did converge.
Here is some of the output which shows reduced chi-square and higher CFI in the more restrictive ghfitAge3:

Model
Df
Chisq
Chisq diff
Df diff
Pr(>Chisq)
cfi
cfi diff

ghfitAge2
34
192.61

0.9988652

ghfitAge3
54
167.35
-39.497
20
1
0.9991890
0.0003238

PS: I am aware of the similar post MultiGroup Factor Analysis CFI gets better as model gets more restricted
The poster has experienced improved CFI like here but makes no mention of the chi-square. The accepted answer explains that the increase in CFI could be because the chi-square statistic may increase at a slower rate than the degrees of freedom earned by imposing constraints. However, the chi-square is decreasing in my case so I don't see how that can be the answer here.
Might it be due to some downstream effect of using the "ordered = true" specification in the cfa() function? I have attempted to rerun these model with regular ML and then the more restrictive model experiences reduced fit as expected. However, I do not want to go with ML because the fit for the overall model becomes much worse.
Answer: Read this:
Wu, H., Estabrook, R. (2016). Identification of Confirmatory Factor Analysis Models of Different Levels of Invariance for Ordered Categorical Outcomes. Psychometrika, 81, 1014–1045. https://doi.org/10.1007/s11336-016-9506-0
You can use this to help with correct specification:
?semTools::measEq.syntax
Comment: Thank you, this worked. For info to others: It appears the weird results with improved fit are a consequence of how the handling as ordinal variable (ordinal = TRUE) affects model comparisons in multi-group CFA. The reason for this is described in the Wu & Estabrook reference. By using the measEq.syntax function for invariance testing which incorporates Wu & Estabrook's solution you will avoid it.


Given a unit disk (regular hexagon), how to tell the formula of the norm to show that it is not derived from a scalar product?

Question: In $\mathbb{R}^2$ there is a norm $\left\|\cdot\right\|$; the unit disk in this norm, $B = \{(x, y) \in \mathbb{R}^2 :\left\|(x,y)\right\| \leq 1\}$, has the shape of a regular hexagon with side length $1$ and one vertex at $(1, 0)$.
Show that the norm is not derived from a scalar product.
Now, I would like to demonstrate the failure of the parallelogram law holding. That is how I usually did such exercises. However here I am not given any formula for $\left\|\cdot\right\|$ , just the shape of unit circle.
So here comes my question: how to tell the formula of the norm if I'm given a unit disk
Comment: The norm of a point $p$ is the unique $\lambda$ such that $p \in \lambda S$, where $S$ is the unit circle: $\{v \mid \| v \| = 1\}$. The only requirements on the shape of the unit disc $D$ of a norm are that it is convex and symmetric about the origin, i.e., $-D =D$.
Comment: You mean unit *disk*, not circle. :) ... What is the *geometric* interpretation of the parallelogram law? Can't you apply this geometrically here?
Comment: The disk* must be a parallelogram. Hexagon is not a parallelogram. However, if I was to determine the value of $\left\|(3, \sqrt{3})\right\|$, I would still need the formula. Or can that be done also with geometry (by calculating the distance between a given point and the center of hexagon?
Comment: @RobArthan, ohhh so to find the value of $\left\|(3, \sqrt{3})\right\|$ I just need to fint the $\lambda$ that would bring the point on my circle (which is a hexagon)?
Comment: Where did you get $(3,\sqrt3)$? Are you starting with obvious unit vectors for $x$ and $y$?
Comment: As my comment about the requirements on the unit disc weren't quite comprehensive, I've written up the full details in an answer. As you will see you don't need to do much algebra.
Answer: Given any closed, bounded and convex subset $D$ of $\Bbb{R}^2$ that is symmetric about the origin, i.e., for all $v$, $v \in D$ implies $-v \in D$, we can define a norm $\|\cdot\|$ whose unit disc, i.e., the set $\{v \in \Bbb{R}^2\mid \|v\| \le 1\}$, is $D$. $\|\cdot\|$ can be defined by:
$$
\| v \| = \inf \{\lambda \in \Bbb{R_{\ge0}} \mid v \in \lambda D\}
$$
Equivalently $\|v\|$ is the unique $\lambda \ge 0$ such that $v \in \lambda S$, where $S$ is the boundary of $D$. As the unit disc of any norm is closed, bounded, convex and symmetric about the origin, all norms on $\Bbb{R}^2$ arise in this way. (This all generalises easily to highher dimensions.)
The points lying on and inside a regular hexagon centred on the origin meet the above criteria to be the unit disc of a norm. To see that the paralelogram identity is not satisfied, let the vertices of the hexagon be $v_1, v_2, \ldots v_6$, and consider any parallelogram $P$ with vertices $w_1 = (0, 0)$ $w_2 = v_1 + v_2$, $w_3$ and $w_4$ where $w_3$ and $w_4$ lie on the edge $[v_1, v_2]$.  Then each side of $P$ has length $1$ and the long diagonal $[w_1, w_2]$ has length $2$, but different choices of $w_3$ and $w_4$ let us vary the length of the short diagonal $[w_3, w_4]$ from $0$ to $1/2$. So the parallelogram identify cannot hold.
Norms that are induced by a scalar product are called Euclidean. The unit disc in a Euclidean norm is strictly convex, which mean that its boundary contains no line segments. Norms with a strictly convex unit disc are called strict. Another way of seeing that the norm with a hexagon as its unit circle is not Euclidean is to note that it is not strict. This approach applies to lots of interesting norms, although there are strict norms that are not Euclidean.


Warning: count(): must be an array or object that implements Countable

Question: I have migrated to a new server which is using PHP v7 (from my PHP v5.4) and am now being displayed errors on my website.
This is the lines of code which is returning the error:
// The value of $ip at this point would look something like: "220.127.116.11"
$ip = ip2long($ip);
// The $ip would now look something like: 1073732954
if(!count($ip) > 0 || !preg_match('/^\d+$/', $ip) || empty($ip)) {
    $ip="0000000000";
}

How can I resolve this?
Comment: Looks like it might be new behavior with 7.2, https://github.com/processwire/processwire-issues/issues/408 Checking the type before usage seems to be the solution.
Comment: Those who are facing problem as: `if ( count($articles)){..}` in **CodeIgniter**, they should use: `if ( count((array)$articles)){..}` as [here](https://github.com/processwire/processwire-issues/issues/408#issuecomment-337931543)
Answer: ip2long never returned an array. I think you can safely remove !count($ip) > 0 || from your condition.
Comment: You could also just do `if ($ip === false)` since `ip2long` returns `false` on error, or a long integer on success. No need for regexes.


Need help with GetShortPathName

Question: I have used GetShortPathName frequently with no problem.  However, now I'm having a problem.
In the past I have done, for example, @"C:\LongFoldername\LonfolderName\"
Now I'm using UNC like this @"\\MyServerName\TheLongFolderName"
But it does not get shortened.  It stays the same.
I have tried @"\\?\MyServerName\TheLongFolderName"
But that returns "".
I have read GetShortPathName Function But it did not help.
What am I missing?
Thanks!
Answer: I doubt very much that GetShortPathName will work on network names because they wouldn't be unique anymore and who would manage the mappings.
In a filesystem the short path name in guaranteed unique on the whole file system and it is created when the file with the long name is created or renamed. You cannot make ensure this in a network.
But even on a file system it is not guaranteed that a given file has a short file name, this may depend on system settings.
Answer: THe share name is too long - it must be under 11 chars for compability with GetShortPathName.  I think you may be warned of this when creating long share names in some instances.
http://groups.google.co.uk/group/microsoft.public.win32.programmer.kernel/msg/88454e39076262ab

Need help with GetShortPathName


How to calculate perceptiles in a discute r.v?

Question:
The problem said:
Suppose the random variable $X$ has  pmf
$Pr(n)=\frac{1}{3}  (\frac{2}{3})^n , n=0,1,2,···$
Find the median and the $70$th percentile.

My work,
MEDIAN:
$0.5=(1/3) \cdot (2/3)^n$
then $n=0.608$
and for $70$th perceptile.
$0.7=(1/3) \cdot (2/3)^n$
then $n=1.11$

The solution said: median=$1$ and $70$th percentile=$2$.
My question, is my procedure fine? or I missing something?
Thanks.
Answer: The random variable $X$ is the number of failures until the first success, where the probability of success on any trial is $1/3$.
The random variable $X$ is $\ge n$ if there are $n$ failures in a row. Thus $\Pr(X\ge n)=(2/3)^n$.
As is the case for many discrete distributions (and even some continuous ones) the median is not completely determined. But $\Pr(X\ge 2)=(2/3)^2=4/9\lt 1/2$, so $\Pr(X\lt 2)=5/9$, and $\Pr(X\lt 1)=1/3$. By one of the conventions for median in this kind of situation, one would average and say the median is $(1+2)/2$.
For the $70$-th percentile, we want to find the $n$ such that $(2/3)^n\approx 0.30$. Note that $n=3$ brings us under $0.30$, while $n=2$ leaves us over $0.30$.  One of the conventional answers for median is $(2+3)/2$.


T-SQL GROUP BY a nvarchar error

Question: I was wondering if anyone could help me with a request kindly:
Here is the data:
Table 1: EMPLOYEE
    FK: DID
    PK: Name
    UserName

Table 2: DEPARTMENT
    PK: DID
    TerminationDate

I'm looking to find the number of terminated employees in the quarter.  Here is the T-SQL so far:
SELECT
    DEPARTMENT.name AS Name,
    COUNT(e.userName)
FROM
    EMPLOYEE AS e
JOIN
    DEPARTMENT ON e.department = DEPARTMENT.DID

UNION

SELECT
    u.eu, u.name
FROM
    (SELECT
         dd.name, COUNT(ee.userName) AS eu
     FROM
         DEPARTMENT AS dd
     JOIN
         EMPLOYEE AS ee ON dd.DID = ee.department
                        AND ee.terminationDate IS NOT NULL
     WHERE
         ee.terminationDate IS NOT NULL
         AND ee.terminationDate BETWEEN '2015-04-01' AND '2015-06-30'
     GROUP BY
         dd.name, ee.userName) AS u
GROUP BY
    u.eu, u.name, Name
ORDER BY
    Name

The error is:

Msg 8120, Level 16, State 1, Line 1
  Column 'DEPARTMENT.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Comment: GROUP BY dd.name, ee.userName make it as GROUP BY dd.name in 2nd query and remove u.eu
Comment: With t-sql all non-aggregated columns in the select statement must be included in the group by clause, so in the first query you need to add a group by clause for _department.name_
Comment: Also, you switch places between the count and name in the second query; the union must have the same data types for all columns so you need to change the order too.
Comment: If you just want the count of employees terminated in the specific period then your query can be simplified a lot. What is the actual output you want?
Comment: What is the actual output you want? Thanks, the output I'm looking for is the number of terminated employees in the quarter.
Answer: The number of problems with this query are bewildering.  To start with... The table definitions you have listed do not match your query.  You have the TerminationDate as an attribute of the DEPARTMENT table, where as in the query it looks like you are accessing it though the EMPLOYEE table, which makes sense to be there.  So I'm going to assume that your table structure really is:
Table 1: EMPLOYEE
FK: DID
PK: Name
UserName
TerminationDate

Table 2: DEPARTMENT
PK: DID
Name

The way you have used a UNION in this query leads me to believe that you have a misunderstanding of what a UNION statement does.  UNION is used to join two sets into one. So in set theory {1,2,3} union {3, 4} is {1,2,3,3,4}.  In SQL Server, you have to make sure that the types and number of columns in the first select statement match all the selects that are unioned with it.  So for example:
 Select 1 A, 2 B
 Union
 Select 3 B

Will give this error because the first select has two columns and the second has only one:

Msg 205, Level 16, State 1, Line 3 All queries combined using a UNION,
  INTERSECT or EXCEPT operator must have an equal number of expressions
  in their target lists.

And this query:
 Select 1 A
 Union
 Select 'Bob' A

Will give this error because the column types do not match:

Msg 245, Level 16, State 1, Line 2 Conversion failed when converting
  the varchar value 'Bob' to data type int.

If all you are looking for is the number of employees terminated between two dates, then there really isn't really anything you need to union.  All the employees are already together in one set (the Employee table)... and you just need to filter the dates you want and count the record total.  You don't even need the DEPARTMENT table to calculate this.
I could write the query for you... but I'll leave the rest to you.
Comment: Thanks Brian, I forgot to include that I'm also looking for the department name and department employee count: Table 1: EMPLOYEE PK: ID, Name, username, FK: DepartmentID. Table 2: DEPARTMENT PK DepartmentId, DepartmentName so overall I'm looking for the number of employees in a department and the number of employees that have been fired within the quarter in one result set. So if there were 20 departments with 5 employees per department and a total of 2 employees were terminated during the last quarter the result set would be 20 rows with something like this as a row: | Accounting | 20 | 0 |
Comment: We've found a solution - thank you. A common table expression was needed:
Answer: In the first part of your query, you list the department name in your select clause but don't include it in a group by clause (because it is missing)
select DEPARTMENT.name as Name, COUNT(e.userName)
from EMPLOYEE as e
join DEPARTMENT on e.department = DEPARTMENT.DID
group by DEPARTMENT.Name --add this line

T-SQL GROUP BY a nvarchar error


Why Bootstrap's creators not using the normal classes in the new themes site?

Question: The Bootstrap creator just annonuce a new site http://themes.getbootstrap.com/ which using bootstrap and need to be a "stunning real world examples" of using bootstrap (http://blog.getbootstrap.com/2015/08/19/bootstrap-4-alpha/)
so when looking at the source code I was excepting to see some "rows" "span-12" and all the known classes names excpet what I see is this classes names:
dv alm dz
k
di

and so on
any good reason why not just using the normal names? and how they do it? like if they not using all the rows and span how they using the grid than?
Comment: My wild guess is that they don't want newbies copy/pasting right from their demo site.
Comment: @Darth_Vader html is public.. I did not meant to "steal" their design, just  understand the reason
Answer: They "are using" the normal bootstrap classes. Although I do not know the exact process, it looks as if they're "mangling" the CSS selectors of Bootstrap much like what happens you minify and uglify your JavaScript source. When you mangle your JS local variables and functions will get renamed from something like isRightClick() to d().
Why do you do this?
To reduce the footprint of your static resources. Instead of using .col-md-12 or .col-md-6 .some-class multiple times in their CSS file it's reduced to .a and .a .b. Which is a lot smaller.
There could be other reasons like a preventative measure of some sort.
How do they know which classes to use then?
More than likely they are using something like Grunt, Gulp or some other process that runs in the background when they make updates or are ready to deploy the project. Whatever they use, it is likely performing some sort of replacement, whether that be variables or a find-n-replace approach I have no clue. But they probably write something like this:

Which at some point is converted to:


Join future dates to table which only has dates until current day

Question: I have these two tables:
table1: name (string), actual (double), yyyy_mm_dd (date)
table2: name (string), expected(double), yyyy_mm_dd (string)

table1 contains data from 2018-01-01 up until the current day, table2 contains predicted data for the year of 2020. My problem is that table1 doesn't have any date values past the present date, so I get duplicate data when joining like below:
SELECT
    kpi.yyyy_mm_dd,
    kpi.name,
    kpi.actual as actual,
    pre.predicted as predicted
FROM
    schema1.table1 kpi
LEFT JOIN
    schema1.table2 pre
    ON name = kpi.name --AND pre.yyyy_mm_dd = kpi.yyyy_mm_dd
WHERE
     kpi.yyyy_mm_dd >= '2019-12-09'

Output:
+----------+------------+----------+-------------+
|yyyy_mm_dd|  name      |actual    |predicted    |
+----------+------------+----------+-------------+
|2019-12-10|  Company   | 100000   | 925,180     |
|2019-12-10|  Company   | 100000   | 1,145,723   |
|2019-12-10|  Company   | 100000   | 456,359     |
--------------------------------------------------

If I uncomment the AND condition in my join clause, I won't get the predicted values as my first table has no 2020 data. How can I join these tables together without duplicating actual values? actual should be null for days which haven't happened yet.
Answer: I think you want UNION ALL and not a JOIN:
SELECT
    yyyy_mm_dd,
    name,
    actual as actual,
    NULL as predicted
FROM schema1.table1
WHERE yyyy_mm_dd >= '2019-12-09'
UNION ALL
SELECT
    yyyy_mm_dd,
    name,
    NULL as actual,
    predicted as predicted
FROM schema1.table2

Comment: This is why I use NULL. The columns that do not exist in each table can be replaced with NULL at the other table.
Comment: I think a `union all` would work here, however in reality `table1` contains many metrics (`actual` is just one of them). `table2` only contains three columns. How could I union these since one schema would be larger than the other?
Answer: Hive supports full join:
SELECT COALESCE(kpi.yyyy_mm_dd, pre.yyyy_mm_dd) as yyyy_mm_dd,
       COALESCE(kpi.name, pre.name) as name,
       kpi.actual as actual,
       pre.predicted as predicted
FROM (SELECT kpi.*
      FROM schema1.table1 kpi
      WHERE kpi.yyyy_mm_dd >= '2019-12-09'
     ) kpi FULL JOIN
     schema1.table2 pre
     ON kpi.name = pre.name AND
        kpi.yyyy_mm_dd = pre.yyyy_mm_dd

Answer: Try using
group by

clause in your query, below might solve your problem
SELECT
    kpi.yyyy_mm_dd,
    kpi.name,
    kpi.actual as actual,
    pre.predicted as predicted
FROM
    schema1.table1 kpi
LEFT JOIN
    schema1.table2 pre
    ON name = kpi.name
group by kpi.yyyy_mm_dd,kpi.name,kpi.actual


Como apagar de todos os commits um arquivo?

Question: No meu primeiro commit enviei um arquivo binario que não tem motivo de ficar.
E enviei um arquivo de configuração com senhas verdadeiras.
Eu alterei a senha pra uma falsa, apaguei o binário, mas se voltar a um commit antigo os dados ainda estão lá.
Não queria apagar o repositório e iniciar um novo perdendo o meu histórico de meses trabalhados pra esconder esse pequeno deslise. Mas preciso que realmente esses 2 arquivos fiquem irrecuperáveis.
Answer: Você pode usar o filter-branch para isto.
Primeiro, precisa rastrear os commits que contém este arquivo:
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch CAMINHO-PARA-SEU-ARQUIVO-COM-SENHAS' \
--prune-empty --tag-name-filter cat -- --all

Adicione o arquivo no .gitignore (se desejar manter este arquivo de senhas apenas localmente):
echo "SEU-ARQUIVO-COM-SENHAS" >> .gitignore
git add .gitignore
git commit -m "Add SEU-ARQUIVO-COM-SENHAS to .gitignore"

Se estiver tudo certo e seu repositório estiver disponível remotamente (exemplo, no Github), faça um push para sobrescrever no repositório todas as alterações:
git push origin --force --all

Faça o mesmo com as tags, se tiver usado alguma tag no período que o arquivo com senhas estava disponível:
git push origin --force --tags

Recomendo fazer um backup do repositório antes de proceder com as dicas acima.
Comment: Nossa parece que entendi muito bem o que ele queria não, +1!


In france not getting result for Place API

Question: I am using place API to serch Hospital, Doctors.
with types=pharmacy&keyword=pharmacy
https://maps.googleapis.com/maps/api/place/search/json?location=50.468869,2.909696&radius=50000.0&types=pharmacy&keyword=pharmacy&language=&sensor=false&key=value
But not getting result in france ?
Is there any thing that we can improve in search API to get accurate result ?
Thanks
Answer: API behaviour is strange between category keywords and searched word. As you can see here, if you search for "pharmacy" in France you don't get the same results as if you search for "pharmacie" :

https://maps.google.fr/maps?q=pharmacy&sugexp=chrome,mod%3D6&um=1&ie=UTF-8&hl=fr&sa=N&tab=wl
https://maps.google.fr/maps?q=pharmacie&sugexp=chrome,mod%3D6&um=1&ie=UTF-8&hl=fr&sa=N&tab=wl

Notice that for the first one you can see "category : Pharmacy" on the left results list. And not for the other request.
Comment: No, the above url does not contain value for key.
To check you need to put key value against key parameter in above URL.
Comment: Thanks for quick response.

Actaully my app is live on google play store :
https://play.google.com/store/apps/details?id=com.matrix.emergency

But few clients from France and Germany are complaining about getting wrong results for doctor and dentist at there location.

It will be great if you can suggest me any changes that we can do in above API request to get more accurate results.
Comment: Ok I think I understand your problem. This is because you do a research about the word "pharmacy" that doesn't exist in french. What you are really looking for is a "pharmacie" and here, you will get much more results (and "real" and accurate results). Because if you search for "pharmacy" you only get places that are categorized in pharmacy type.
Try this (for Toulouse, France) : https://maps.googleapis.com/maps/api/place/search/json?location=43.607245,1.443964&radius=50000.0&types=pharmacy&keyword=pharmacie&language=&sensor=false&key=theAPIKey
Comment: Thanks Grsmto !
But this is not specified in Google place API, keyword should be in place local language.
I am still confused that using this will make any difference.
Comment: Yes this is strange...I don't understand well how the places API works for this because when you search for "pharmacy" you've got the places that are categorized as pharmacy. But when you type "pharmacie" you've got every places that have the keyword in their name but they are also categorized as "pharmacy"...So why they don't appear for "pharmacy" ? I don't know...May be the API make a difference for places that are categorized by the owner of the place and places that "auto-categorized".


What does a major-7 chord resolve/lead to?

Question: I reckon the major-7 chord is my favourite guitar chord.
I was strumming Amaj7 chord and got a lovely first line to a song, but I am not musical enough to figure out what chords fit the melody I was singing. What would be some obvious chords to directly follow such a chord? And in normal (not jazz) music, which chords in a key would lend themselves well to being substituted with the major-7 alternative - i.e. is it more likely Amaj7 is Imaj7, Vmaj7, etc?
Comment: Damnit how do I get a chord fingering to appear? I did it by mistake the other day, now I can't get it to display a typical Amaj7 voicing.
Comment: Indent by four spaces (like a code block).
Comment: Is it documented what chord types it recognises and the namings one has to use?
Comment: In A major, Amaj7 would possibly resolve to Dmaj7 (Imaj7 to IVmaj7)
Comment: @Mr.Boy Documentation is here: http://jtab.tardate.com
Answer: To understand how chords with 7ths work, you need to know the scale you are using. The chords most commonly used are built on thirds, so if you choose a scale and then a note from that scale, you'll see what chords are maj7 chords, by ascending thirds from the note you chose. *
In the major scale, only the I and IV are major chords and have a major 7th.
So, let's say you want to use the Amaj7 chord. One way to look at this chord would be to consider it the Imaj7 from the A major scale. The chord is built on thirds -- A,C#,E,G# (G# is a major 7th). After the Amaj7 chord, you can use any chord from the scale, like you would use if you simply had a A (without the maj7).
Pretty much the same would work if you considered it as a IVmaj7. It would be the IV from the E major scale. So, you can create a chord progression in the E major scale and instead of a simple A chord, to play a nice Amaj7.
What I like to do sometimes is to play the chord as it is, without the 7th and then add the 7th.
Also, I've never seen a Vmaj7 chord. The V usually is dominant (V7); that means it has a minor 7th instead of a major one; one semitone lower.
*The V doesn't have a major seventh. Let's assume we are in the A major scale. The notes in the A major scale are A,B,C#,D,E,F#,G#. The V chord has E as a root. Let's ascend thirds from E and see what kind of chord we have:

E (root)
G# (major third)
B (perfect fifth); so far we have a major chord
D (minor 7th).

So the V is a 7 chord, not a maj7 one.
Comment: "In the major scale, only the I and IV are major chords and have a major 7th." - I didn't understand that, could you reword or clarify in your answer? e.g. why doesn't V "have a major 7th"?
Comment: @Mr.Boy I added more info at the end of my answer
Comment: After your edits I think it all makes sense, especially why Vmaj7 isn't a thing :) So in summary, a maj7 can be directly substituted for the same degree plain major chord in that key?
Comment: @Mr.Boy Yup; Also, keep in mind that the 'maj' goes to the 7th, not the chord. Another similar chord is Aminmaj7 which is a Aminor chord with a major 7th (the I from the harmonic minor scale). It's a weird sounding chord; try it out.
Comment: And this makes sense... I could see Bm, C#m and D would fit nicely with Amaj7 and now I checked those are chords from the key of A mjor (not a key I know off-hand, but Amaj7 is the easiest maj7 chord I know on guitar!)
Comment: @Mr.Boy doesn't matter that you don't know they off-hand. If you can't figure them out at the moment, try writing down the notes from the A major scale, take each note as a root and ascend thirds. This way you'll be able to see what chords are in the A major scale.
Comment: Oh yeah, I can work out chords to any key but I meant I didn't recognise those chords as being in A. Whereas if I noticed Am, F and G were working against Cmaj7 I'd have thought "huh, those are all chords from C major" :)


Execução de script(js) externo em pagina online

Question: Desejo executar um script(JS) especifico para a exclusão de alguns elementos da pagina que considero poluição visual; e atrapalham minha navegabilidade em especifico. ( É o site da universidade, então não tenho escolha se não usa-lo )
O script está pronto, faz tudo que desejo e funciona. Porem toda vez que entro na pagina ou atualizo tenho que: abrir o console, colar o script e então executar para ter o resultado que desejo.
Existe alguma forma de automatizar esse processo para toda vez que eu acessar "x-URL" ele executar automaticamente ?
Se sim, qual o termo correto que eu deveria utilizar nas pesquisas do Google para encontrar ?
Onde teria mais informações a respeito ? ( Vi sobre o Selenium, porem até o momento ele não se encaixa )
Answer: você pode usar o plugin do chrome Tampermonkey
https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=pt-BR
com ele você pode criar scripts próprios e programa-los para executar automaticamente quando uma url específica for lançada no browser
Comment: Obrigado! Irei aplicar essa ferramenta aqui. A  possível solução é melhor do que eu imaginei que seria, é sempre um misto de sensações conhecer alguma coisa nova que pode vir a ser utilizável. =)
Comment: @AlexSandro caso esta resposta tenha resolvido seu problema é recomendável marcá-la como solução.


QTableWidget's cell widget not displaying correctly when last row deleted

Question: I have a QTableWidget that has QPushButtons as cell widgets. I use these push buttons as a means to delete a row from the table. I'm having a problem where the QPushButtons can be accidentally shifted from being centered in their cell. The image below shows what is happening.

This occurs in the specific case where the user has 1) made selected a cell in the last row of the table, 2) that cell contains a delete button, and 3) the vertical scroll bar is moved such that the last row is partially visible.
Below is a very minimal example that will create this problem. The user needs to use the scrollbar and scroll up by one tick, then press the last delete button.
mainwindow.h:
#pragma once

#include <QMainWindow>

class QSignalMapper;
class QTableWidget;
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

public slots:
    void DeletePressed(int row);

private:
    QSignalMapper* signalMapper_;
    QTableWidget* table_;
};

mainwindow.cpp:
#include "mainwindow.h"

#include <QGridLayout>
#include <QSignalMapper>
#include <QTableWidget>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    signalMapper_(new QSignalMapper(this)),
    table_(new QTableWidget())
{
    setCentralWidget( new QWidget );
    this->setFixedSize(200,300);

    QGridLayout *layout = new QGridLayout(centralWidget());
    layout->addWidget(table_);

    table_->setRowCount(0);
    table_->setColumnCount(1);

    // if you comment out the following line then the problem is not present
    table_->setSelectionMode(QAbstractItemView::SingleSelection);

    for (int i = 0; i < 20; i++) {
        table_->insertRow(i);
        QPushButton *button = new QPushButton("Delete");
        connect(button, SIGNAL(clicked(bool)), signalMapper_, SLOT(map()));
        signalMapper_->setMapping(button, i);
        table_->setCellWidget(i, 0, button);
    }
    connect(signalMapper_, SIGNAL(mapped(int)), this, SLOT(DeletePressed(int)));

    table_->setCurrentCell(19,0);
}

MainWindow::~MainWindow()
{
}

void MainWindow::DeletePressed(int row)
{
    table_->clearSelection(); // <- added clear selection before remove row
    table_->removeRow(row);
}

main.cpp:
#include <QApplication>
#include "mainwindow.h"

int main( int argc, char* argv[] )
{
    QApplication app(argc, argv);
    MainWindow wnd;
    wnd.show();
    return app.exec();
}

I think the problem stems from the QTableWidget trying to keep the selected cell visible when a new selection is made. I have tried both of the answers posted here but neither solved my problem.
If anyone could tell me how to solve this problem I would appreciate the help.
Answer: I had a similar problem a long time ago with a QtreeWidget and I solved it by callig protected method updateGeometries().
If you did not specialize QTableView, you can't simply call this function (as it is protected), so here's a trick to simply do it:
class MyQTableView : public QTableView
{
public:
    inline void publicUpdateGeometries() { updateGeometries(); }
};

void MainWindow::DeletePressed(int row)
{
    table_->clearSelection(); // <- added clear selection before remove row
    table_->removeRow(row);

    // call the protected method QTableView::updateGeometries()
    ((MyQTableView*) table_)->publicUpdateGeometries();
}

Hope this will solve your problem.
Comment: Worked like a charm. Thanks.
Comment: You are welcome. By the way, I just reported a Qt bug for that, then hopefully this can be fixed in later versions of Qt. https://bugreports.qt.io/browse/QTBUG-49548
Comment: @Stanton: Note that the bug was fixed! Next Qt version should work better.
Answer: Try ui->tableWidget->clearSelection();
Comment: Where should I place this in my code? I made a slot called `DeletePressed(int row)` which I connected to the signalMapper. In the slot I added your `clearSelection()` followed by the `removeRow(row)` call, but that didn't solve the problem.
Comment: I think you should call `clearSelection` before `removeRow(row)`
Comment: I've made the change as you suggested, but this didn't solve my problem. Please see the edited code above to see that I did this as you intended.
Answer: This happen only when scroll bar is added.to solve this you need to setvrticalscrollbarpolicy to scroll bar off then delete the row and add the scroll as needed by setverticalbarpolicy.
It will solve your problem.
I did the same way.


printing of integers mips

Question: I try to add numbers to a array and then I try to print those numbers, but when I add mine numbers and I try to print and then I got different numbers. How is that possible?
My code is:
#----------------------------------- Array Vullen  -----------------------------------------------------
.data
    question1_msg: .asciiz "How much integer do you want to give?\n"
    question2_msg: .asciiz "give a number?\n"
.text

question_numbers:
    la $a0, question1_msg #load the question in $a0
    li $v0, 4
    syscall

answer_numbers:
    li $v0, 5  #read the answer of previous question
    syscall
    move $t0, $v0
    move $t9, $t0
    move $t8, $t0

generate_array:
    sll $t0, $t0, 2 #create array
    move $a0, $t0
    li $v0, 9
    syscall
    move $t3, $v0 #put the stack pointer in a temperay register
    move $t4, $v0

add_numbers_array:
    bge $t1, $t9, Call_procedure # if $t1 >= $t0 then exit

    #ask questions
    la $a0, question2_msg #load the question in $a0
    li $v0, 4
    syscall

    #read numbers
    li $v0, 5
    syscall
    move $t2, $a0

    #add number en go to the next array point
    sw $t2, ($t3)
    add $t3, $t3, 4
    add $t1, $t1, 1

    #get back to the begin of the loop
    b add_numbers_array

#-------------------------------------Array Printen------------------------------------------------

Call_procedure:
    li $t1, 0
    la $a1, ($t8)    # load the couple of numbers
    la $a2, ($t4)    # load the starting adress of the array
    jal Print
    b exit

Print:
    bge $t1, $a1, return  # if $t1 >= $t0 then exit
    lw $t2, ($a2)  #load integer and print
    move $a0, $t2
    li $v0, 1      # print the number in the array
    syscall

    addu $a2, $a2, 4  #increase the sp
    addi $t1, $t1, 1    #increase the number printed

    b Print

return:
    jr $ra

exit:
li $v0 , 10 # let the code end
syscall

Comment: Unfortunately, I can't help you. Just wanted to thank you for your nice, clean code. Keep it up.
Answer: I see 2 errors:
1.
#read numbers
    li $v0, 5
    syscall
    move $t2, $v0

This should be $v0, not $a0
2.
move $a1, $t8
move $a2, $t4

instead of
la $a1, ($t8)    # load the couple of numbers
la $a2, ($t4)    # load the starting adress of the array

printing of integers mips


Finite fiber of scheme morphism is zero-dimensional?

Question: Let $X$ and $Y$ be locally Noetherian schemes and $f:X\rightarrow Y$ be an étale morphism of finite type. Let $x\in X$ and $y=f(x)$. I would like to know why the fiber $X_y$ is a zero-dimensional scheme. This is statement without justification in Liu's Algebraic Geometry. By a prior result, we know that $X_y$ is finite and reduced when the hypothesis above hold. This seems to intuitively be enough to insure it is zero-dimensional (compare to manifolds consisting of a finite number of points, for example), but I don't know how to prove it using material in Liu.
I've pieced together a proof of this using theorems in the Stacks project that I haven't seen in Liu, but Liu passes over it in a sentence without explanation. Is there an easy way to see it is true?
Comment: What's your definition of étale morphism? In any case, one can show that the fibre $X_y$ is _discrete_ as a topological space, and so must be zero-dimensional (because there are no interesting irreducible sets!).
Comment: @ZhenLin Unramified and flat. Is there an easy way to see $X_y$ is discrete?
Answer: Let $f : X \to Y$ be a morphism locally of finite presentation.

$f : X \to Y$ is unramified if and only if all its fibres are unramified, so we may assume $Y = \operatorname{Spec} k$.
$f : X \to \operatorname{Spec} k$ is unramified if and only if $X$ is a disjoint union of affine schemes of the form $\operatorname{Spec} K$ where $K$ is a finite separable field extension of $k$.
So if $f : X \to \operatorname{Spec} k$ is unramified, then $X$ is discrete as a topological space.

To see (2), one may also assume $X$ is affine. Then the problem is reduced to commutative algebra – more precisely, to the structure theorem for artinian rings.
Comment: This is essentially what I found via the Stacks project. Liu requires the stronger hypothesis that the map be of finite type (and étale), which leads me to believe a simpler argument may work. Do you know if the proof can be simplified using these stronger hypotheses?
Comment: The question is local on the domain and the codomain, and both are locally noetherian, so there's no practical difference between "locally of finite presentation" and "of finite type".


Google Chrome Application using Google Fonts

Question: I am trying to include the link stylesheet to use a font from Google fonts. I've tried the Web Font Loader and the actual link stylesheet and yet I keep getting the CSP error.
Refused to load the stylesheet 'http://fonts.googleapis.com/css?family=Open+Sans:400,300,600'
because it violates the following Content Security Policy directive:
"style-src 'self' data: chrome-extension-resource: 'unsafe-inline'".

This is my CSP in my manifest.json
"content_security_policy": "default-src 'self'; style-src 'unsafe-inline'; script-src 'self';",

Now since I haven't read the entire Documentation on CSP's because it seems to get left and right when I'm trying to read this maybe someone could enlighten me how this works, what I need to get my stylesheet to work.
Another Method I've tried:
 load({
    method:"GET",
    url:"http://fonts.googleapis.com/css?family=Open+Sans:400,300,600"
 },function(data){
   var style = document.createElement('style');
   var head = document.head;
   style.innerHTML = data.responseText;
   head.insertBefore(style, head.firstChild);
 });

Answer: For security reason even the load won't work, so I did some more research and to use a Google Fonts in a Chrome App use the import method instead of standard or javascript.
EX:
stylesheet
@import url(http://fonts.googleapis.com/css?family=Open+Sans);
body {
  font-family: 'Open Sans', sans-serif;
}

And everything works A Ok just like that!


Binding a Label's content to a property in code-behind file

Question: I'm making a bingo card generator to try and learn more about WPF, and having trouble figuring out how to set a labels content property to be set from a Property in my code-behind file.
I thought that I could use
<Setter Property="Content" Value="{Binding BNumber}">
for the content property to set the content of the label to a random element of my List<String>?
I have in my MainWindow.xaml
<Window x:Class="Bingo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="600" Width="800"
        WindowStartupLocation="CenterScreen">
  <Grid>
    <Grid Width="350" Height="420" ShowGridLines="True">
      <Grid.RowDefinitions>
        <RowDefinition Height="70"/>
        <RowDefinition Height="70"/>
        <RowDefinition Height="70"/>
        <RowDefinition Height="70"/>
        <RowDefinition Height="70"/>
        <RowDefinition Height="70"/>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="70" />
        <ColumnDefinition Width="70" />
        <ColumnDefinition Width="70" />
        <ColumnDefinition Width="70" />
        <ColumnDefinition Width="70" />
      </Grid.ColumnDefinitions>

    </Grid>
  </Grid>
</Window>

My App.xaml code
<Application x:Class="Bingo.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
  <Application.Resources>

  </Application.Resources>
</Application>

In my MainWindow.xaml.cs I have this List<String> BNumbers object and a Property that returns a random element of the BNumbers List
public MainWindow() {
  InitializeComponent();
  BNumbers.Add("1");
  BNumbers.Add("2");
  BNumbers.Add("3");
  BNumbers.Add("4");
  BNumbers.Add("5");
  BNumbers.Add("6");
  BNumbers.Add("7");
  BNumbers.Add("8");
  BNumbers.Add("9");
  BNumbers.Add("10");
  BNumbers.Add("11");
  BNumbers.Add("12");
  BNumbers.Add("13");
  BNumbers.Add("14");
  BNumbers.Add("15");
}
public string RandomBNumber {
  get { return randomB(); }
}
public string randomB() {
  Random rand = new Random();
  int randomBNumber = rand.Next(0, 15);
  return BNumbers[randomBNumber];
}
public List<String> BNumbers = new List<string>();

Answer: It maybe easier to randomize the list itself then each number as this will stop duplicates.
Aslo using a Uniform grid may be easier han adding a bunch of labels.
Example:
Xaml:
<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="346" Width="300" Name="UI">

    <Grid DataContext="{Binding ElementName=UI}">
        <ItemsControl ItemsSource="{Binding BNumbers}" Margin="0,29,0,0">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border Margin="1" BorderBrush="Black" BorderThickness="1" CornerRadius="2">

                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <UniformGrid Columns="5" Rows="5"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
        <Button Content="New" Height="23" HorizontalAlignment="Left" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
 </Window>

Code:
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public List<string> AllNumbers { get; set; }
    private List<string> _bnumbers = new List<string>();

    public MainWindow()
    {
        InitializeComponent();
        AllNumbers = new List<string>();
        // Bingo game 75 numbers, 5x5 grid
        for (int i = 0; i < 75; i++)
        {
            AllNumbers.Add(i.ToString());
        }
    }

    public List<string> BNumbers
    {
        get { return _bnumbers; }
        set { _bnumbers = value; NotifyPropertyChanged("BNumbers"); }
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        RandomizeList(AllNumbers);
        BNumbers = AllNumbers.Take(25).ToList();
    }

    private void RandomizeList<T>(IList<T> list)
    {
        Random rng = new Random();
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

Result ("New" will generate a new game)
Comment: Thank you very much for spending time on helping me learn! I've never heard of the uniform grid before, but it sounds like it would work perfect, and be less mess than what I was trying to create.
Comment: I have [another question](http://stackoverflow.com/q/14282440/1804496) if you are up to it?
Answer: In the constructor, you need to set the DataContext:
this.DataContext = this;

You'll also need to change your setter to match the property name RandomBNumber :
<Setter Property="Content" Value="{Binding RandomBNumber }">

Comment: That's right :)  You would usually set the DataContext to a ViewModel object, but using the Window is fine for the sake of learning/experimenting with binding.
Comment: Thank you for your quick response O_O If I understand this right, `this.DataContext = this;` is setting the Window object's DataContext property to.. itself?
Comment: I followed ssdam's suggestion and used UniformGrid's to display numbers selected at random inside an ItemsControl, I have [another question](http://stackoverflow.com/q/14282440/1804496) about accessing the items themselves if you have a moment


N-th child selector with class names not being considered?

Question: I have a list of photos as such:

Corresponding CSS as follows:
.gallery {
    list-style-type: none;
    li {
        float: left;
    }
    .red {
        width: 100%;
        margin-bottom: 2%;
    }
    .blue {
        width: 49%;
        margin-right: 2%;
    }
    .green {
        width: 32%;
        margin-right: 2%;
    }
    .blue:nth-child(2n) {
        margin-right: 0;
    }
    .green:nth-of-type(3n) {
        margin-right: 0;
    }
}

Here is a picture to illustrate this:

Every second blue element do not need a margin-right to fit the grid properly. Similarly, every third green element doesn't need a margin-right.
I tried to target them using the n-th child selector above which doesn't seem to do the trick. The second element in the list is actually the first .red element which is being set to margin-right: 0;
It seems like the class name is being overriden by the selector. Maybe the class names aren't considered and I know I can group the red items in a div and target them but that's not a solution as the list is being generated dynamically and I would like to keep its structure.
Basically, the user will be able to upload as much photos as he like in the grid with a structure as follows:

If he decides to upload a blue picture, the next picture has to be blue as well to fit the grid.
If he uploads a green picture, the next two pictures have to be green as well to fit the grid.

Any ideas on how to solve this?
Comment: It is working fine here. http://jsfiddle.net/sureshponnukalai/dzobxgk4/. Just format to normal CSS instead of SCSS.
Comment: Thanks for you reply @SureshPonnukalai but unfortunately, it's not. If you check your fiddle (http://jsfiddle.net/sureshponnukalai/dzobxgk4/) against the photo above http://imgur.com/Bp1cyrH, it's not working right.

What I want is exactly like the photo above. The second blue element in the list should have a margin-right of 0. Not the first one like in your case.
Answer: nth-child(2) will select every other element in your ul, and nth-of-type(2) will select every other li element in your ul. Unfortunately, what you are trying to do is impossible using CSS only, you can't select every other element with a specific class.
You need to change your HTML, for example - when you generate your list, count the number of blues and give every other "no-margin" class, and do the same for every third green.