How can I use a recent version of GCC in GitHub CI?

Question: I have a C++ project on GitHub with which I use GitHub CI. My workflow is configured to run on Linux and Windows through the strategy property:
runs-on: ${{ matrix.os }}
strategy:
  matrix:
    os: [ubuntu-latest, windows-latest]

This has worked well for me so far, with Cmake identifying the compiler as GNU 9.3.0. However, I would now like to use an experimental feature added in GCC 10 in my project, and so my build fails due to the old compiler version.
How can I use a more recent version of GCC from my GitHub CI workflow?
Answer: For the linux build you can use the following build step to switch the default gcc to gcc-10.
- name: switch to gcc-10 on linux
  if: matrix.configurations.os == "ubuntu-latest"
  run: |
    sudo apt install gcc-10 g++-10
    sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 100 --slave /usr/bin/g++ g++ /usr/bin/g++-10 --slave /usr/bin/gcov gcov /usr/bin/gcov-10
    sudo update-alternatives --set gcc /usr/bin/gcc-10

The first 2 lines in the script should be optional, as gcc-10 is already installed in ubuntu-latest. But it doesn't hurt much to have them there and it might help to make clear what is happening and how to reproduce the build locally.
You can check the manpage for update-alternatives if you are interested how this works.
windows-latest uses visual-studio as it's default compiler, but since you only asked about gcc I suppose that it already supports the c++ features you are using?
Comment: I see, thank you. This answer works and addresses the question well, so I'll accept it. I ended up going in a slightly different direction, because it turns out gcc-10 and gcc-11 had bugs in the feature I needed :)
Answer: @wirew0rm posted an excellent answer, which works very well generically. It's useful to note that one is allowed to use sudo on the GitHub CI runners, and so one simply needs to install the desired packages:
sudo apt install gcc-10 g++-10

# or
sudo apt install gcc-11 g++-11

# or, for very recent Clang:
wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh
sudo ./llvm.sh 12
sudo apt-get install libc++-12-dev libc++abi-12-dev

Then, because I was using CMake, I could set the CXX environment variable instead of using sudo update-alternatives:
echo "CXX=g++-10" >> $GITHUB_ENV

The subsequent CMake configure step would then select g++-10 as the C++ compiler.


Django extend common variable or block in child templates

Question: I have a common variable or block in base template that i want to extend in child templates, how can i achieve that? I have following code.
base.html

        <title>
            {% block page_title %} {% endblock %}
        </title>
        <meta property="og:title" content="{% block page_title %} {% endblock %}" />
        ...

 {% block page_title %} {% endblock %}

...

my_page.html
{% extends 'base.html' %}

{% block page_title %}
    Page title goes here
{% endblock %}

When i run this code i get the following error
'block' tag with name 'page_title' appears more than once
Comment: in each `view`, set a context variable with the value of page title in it.
Comment: AFAIK, blocks have to be unique. Your block `page_title` appears twice.
Comment: How can i achieve the solution?
Comment: As @SachinKukreja states, use the same context variable in all those places and make sure your views provide it properly. You might provide a default value in the template not to ever leave it empty.
Answer: Whenever you find yourself wanting for a value to appear twice in a template it smells like that data should be provided in your rendering context.
There are many options for that, but the simplest is just to provide a page_title context parameter when rendering the template:
def my_view(request):
    # View code here...
    return render(request, 'myapp/index.html', {
        'page_title': 'Your Page Title',
    })

And then use it in your template as any other template variable: {{ page_title }}


When is it "appropriate" to prove a statement using induction?

Question: I know the question is broad, but I am just starting to get my hands dirty with mathematical proofs. I understand that in some cases, a "direct" proof may be appropriate if we are simply going step-by-step in a definition-type question.
In other cases, I've found that that proofs by contradiction may be the "easiest" way to go, such as in some linear algebra proofs I've seen.
However, I'm now looking at combinatorial proofs, and notice that something relatively simple such as the proof that $1+2+3+...+n=\frac{(n)(n+1)}{2}$ uses induction - where if we show that it holds when $n=1$, and we assume that it holds when $n=k$, we can reach the desired result.
My question is as follows - is this considered a "weak" argument by any means because of the fact that we are assuming some fact to be true? I still have in my mind the old adage "You know what happens when you assume.." Does this same concern generally hold for mathematical proofs?
Comment: It's not considered weaker because something is "assumed".  You're conflating the colloquial and mathematical usages of the word.  It's a matter of style.  The $1+2+\dots+n = n(n+1)/2$ statement can be proven many ways, and induction is arguably the hardest to follow.
Comment: There is nothing "weak" about "weak induction" in terms of mathematical rigor.  It is particularly useful to prove that something is true for all natural numbers.  However, it is frequently the case that a proof by induction provides less insight than a direct proof.
Comment: Simply put - A proof is a proof, there's no two ways about it. You could write a 100 page proof on something or a simple 1 line proof and both get to the $\textit{exact}$ end result. From my experience induction isn't used very often - but nevertheless very helpful for certain examples.
Answer: Three points:

As Matthew L. says, there is no such thing as "the" proof of your equation -- it is provable in many ways. Here's a non-inductive one: consider
$$\ 1\ \ \ +\ \  2 \ \ \ +\ \ \  3\  \quad+ \ldots + n$$
$$n + (n-1) + (n-2) + \ldots + 1$$
Add those two vertically and we get
$$(n +1) + (n +1) + (n +1) + \ldots + (n +1)$$
So twice the sum of the first $n$ numbers is, trivially, $n(n + 1)$. QED
Suppose you want to prove by induction that (C) for all $n$, $Pn$ (for some numerical property $P$). This involves proving that (A) $P1$ (usually trivial) and proving that (B), for any $j$, if $Pj$ then $P(j + 1)$
(or, if you like, proving that if we assume $Pj$ we can deduce $P(j + 1)$). There are no undischarged mere assumptions here!
For more on induction and why (A) and (B) give you a proof of (C) -- and for much more on how to start getting your hands dirty with mathematical proofs -- it is difficult to recommend the following too highly, which you should find in any library:

Daniel J. Velleman How to Prove It (CUP)
Comment: Are you sure that 1. is not a proof by induction? I'm not. `;-)`
Comment: Isn't it a proof of the form "Take any $n$ you like.  Stuff-about-$n$. $n$ was arbitrary. So for all $n$, stuff-about-$n$." Looks like a universal generalization step at the end, rather than induction.
Comment: How do you prove that $1+2+\dots+n=n+\dots+2+1$ without induction?
Comment: Distinguish: "If we are to prove the arithmetical generalization $P$ from the axioms of first-order PA, will induction be needed somewhere along the way?" vs "If we are giving an informal proof of $P$ from assumptions that can, in the classroom context, be taken for granted, do we need to invoke induction?" The answer to the first is almost always "yes", of course. The answer to the second, as in this case, can be "no".


Probabilistic interpretation. Prove that $\sum_{k=0}^{n}\binom{n+k}{k}\frac{1}{2^k}=2^n$

Question:
Prove that $\sum_{k=0}^{n} \binom{n+k}{k} \frac{1}{2^k} = 2^n$

Well, the solution given on the book is as follows:

We will solve this counting problem by a powerful and elegant interpretation of the result.  First we divide the identity by $2^n$, getting
$$ \sum_{k=0}^{n} \binom{n+k}{k} \frac{1}{2^{n+k}} = \sum_{k=0}^{n} p_k = 1. $$
This is the sum of probabilities $p_k = \binom{n+k}{k} \frac{1}{2^{n+k}}$. Now,
$$ p_k = \frac{1}{2}\binom{n+k}{k} \frac{1}{2^{n+k}} + \frac{1}{2}\binom{n+k}{k} \frac{1}{2^{n+k}} = \mathbb{P}(A_k) + \mathbb{P}(B_k),$$
with the events
\begin{align*}
A_k &= \{\text{$(n+1)$ times head and $k$ times tail}\}, \\
B_k &= \{\text{$(n+1)$ times tail and $k$ times head}\}.
\end{align*}

However, I am not getting the way to calculate the probabilities of $A_k$ and $B_k$. I mean, how did we arrive at the conclusion that $\mathbb{P}(A_k) = \frac{1}{2}\binom{n+k}{k} \frac{1}{2^{n+k}}$ and $\mathbb{P}(B_k) = \frac{1}{2}\binom{n+k}{k} \frac{1}{2^{n+k}}$. I mean, how to calculate those probabilities?
Comment: @angryavian $1 + \frac{3}{2} + \frac{6}{4} = 1 + 1.5 + 1.5 = 4 = 2^2$
Comment: @PTrivedi Thanks for catching my error
Answer: In fact, it's necessary to split it into two events.
I reference the original solution in page97 https://mathematicalolympiads.files.wordpress.com/2012/08/75427434-problem-books-in-mathematics-problem-solving-strategies.pdf

What inspired me is Fig.5.12 in the original solution.

See Fig. 5.12, which shows the corresponding $2n + 2$ paths starting in O and
ending up in one of the $2n+2$ endpoints, $n+1$ vertical and $n+1$ horizontal ones.
Here, we used the standard interpretation:
heads → one step upward, tails → one step to the right.

Imaging we start from $(0,0)$, and end up in one of the $2n+2$ points.
The key is: the sum of probability of end up in the $2n+2$ points is pbviously $1$.
In fact $A_k$=we finally reach the k-th(from left to right) points in the top of the image.
And similarly $B_k$=we finally reach the k-th(from down to up) points in the right of the image.
Now I explain why $P(A_k)=\frac{1}{2}\tbinom{n+k}{k}\frac{1}{2^{n+k}}$
How can we get $A_k$? It needs two steps.
Step1: we must reach point$(k,n)$.
Step2: the last move must be upward.
the probability of step1 is $\tbinom{n+k}{k}\frac{1}{2^{n+k}}$, and the probability of step2 is $\frac{1}{2}$
Thus $P(A_k)=\frac{1}{2}\tbinom{n+k}{k}\frac{1}{2^{n+k}}$
The similar analysis for $B_k$.
So I think the defination of $A_k$ and$B_k$ should be changed into:
$A_k$={$n$  times head and $k$ times tail and the last flip must be head.}
$B_k$={$k$  times head and $n$ times tail and the last flip must be tail.}
Answer: We toss a fair coin until we get a total of $n+1$ heads or $n+1$ tails, whichever comes first. Say we get $n+1$ heads first, but along the way we also get $k$ tails ($k\leq n$) so the total number of tosses is $n+k+1$. The last toss must be head since we stop tossing after the $n+1$-th head. So we only need to figure out the number of possibility to get $k$ tails from the first $n+k$ tosses, which is $\binom{n+k}{k}$. Divide by the number of all possible outcomes from $n+k+1$ tosses, which is $2^{n+k+1}$ to obtain the probability $\frac{1}{2^{n+k+1}}\binom{n+k}{k}$
Answer: I'm not sure why splitting this into two events is necessary. One can say $p_k = P(A_k)$ where $A_k$ is the event of flipping a fair coin $n+k$ times and getting exactly $k$ tails. Then if we imagine a sequence of $H$s and $T$s as the outcomes of the flips then we want $k$ spots of the $n+k$ spots as $T$. This occurs in $\binom{n+k}{k}$ ways. And each outcome has probability $1/2$ so $p_k = \binom{n+k}{k}(1/2^{n+k})$.
This also tells us that the $A_k$ and $B_k$ defined in the solution have probability $\binom{n+k+1}{k}(1/2^{n+k+1})$ which is off by a factor of $n+k+1$ from what we need.
Comment: if the probability for each of them is $1/2 $ then for $ k$  different places in that sequence how is the probability ${n+k\choose k }\frac{1}{2^{n+k}} $ inspite of only $1/2^{n+k}$
Comment: So there is 1/2 probability for heads and 1/2 probability for tails so $1/2^{n+k}$ of a particular sequence of $k$ tails and $n$ heads. Now you have to add this probability for all sequences of $k$ tails and $n$ heads of which there are $\binom{n+k}{k}$.


How many different 13-digit numbers can you get if you write down all the numbers from 1 to 11 , one behind the other in all possible orders?

Question:
How many different 13-digit numbers can you get if you write down
  all the numbers from 1 to 11, one behind the other in all possible
  orders ?

This is one of the questions in final exam when everybody has hard time. Thank you for answers.
Answer: You can arrange $11$ numbers in $11!$ ways. You have to subtract the half the cases of $1$ beside $11$ because, both ways it is $111$. That is, subtract $\frac {10!}2$
The answer - $$11! - \frac {10!}2$$
Comment: @Ivan Everytime 0 comes, The $1$ before it will always be $10$. So, there is no problem. There can't be $ 1$ $10$ or $11$ $0$ . Like in the case of $11$ $1$ or $1$ $11$
Comment: @Ivan It is beacuse I am grouping $11$ and $1$ together. When I group, I now have only $10$ elements- $9$ numbers and $1$ group.
Comment: thank you, kind sir. but what about "0" from "10"?
Comment: Oh, i see now. One last question, about this 10!, why is there 10!, but not 11!?


Custom iOS Tweet Sheet

Question: I am looking to have a custom looking tweet sheet to use in my application.
Obviously I can build my own and use the twitter API for posting; however, this would SEEM (Maybe its not THAT MUCH work, I can't say) to take a lot of work to build, especially in features like autocomplete for user twitter followers etc.
Is there anyway to customize the tweet sheet used by Apple's frameworks? It just looks god awful, especially compared to the design of my app.
If not, where can I look to implement the displaying friend results while typing in @user?
Any thoughts, idea's, links, suggestions would be great. Thanks in advance!
Answer: You can use Social.framework for signing your requests with data from accounts, which is in system.
Second step - make your own view for tweeting.
Third - get ACAccount.
Like this:
<code>ACAccountStore *store = [[ACAccountStore alloc] init];
    ACAccountType *accountTypeTwitter = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    [store requestAccessToAccountsWithType:accountTypeTwitter options:nil completion:^(BOOL granted, NSError *error) {
                                     if(granted) {
                                         dispatch_sync(dispatch_get_main_queue(), ^{
                                             NSArray *accounts = [store accountsWithAccountType:accountTypeTwitter];

                                             //All twitter accounts are in array, show sheet to select one of them.
                                         });
                                     }
                                 }];
</code>
Fourth - send SLRequest to twitter for post.
Example of SLRequest (to get information about user):
<code> NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/1.1/users/show.json?screen_name=%@",account.username]];

        SLRequest *req = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:nil];
        [req setAccount:account];
        [req performRequestWithHandler:^(NSData *respData, NSHTTPURLResponse *resp, NSError *err){
//Req finished
        }];
</code>
Answer: Here's a head start for your own custom tweet sheet:
https://github.com/doubleencore/DETweetComposeViewController

Custom iOS Tweet Sheet


How to use Easy breadcrumb module so that breadcrumb reflects the URL path segments?

Question: For example, if URL ends with /test/flower , breadcrumb should be Home/test/flower.
First time working with this module,and it's not clear to me how to do this.
Could you please help me?
Thanks in advance
Answer: Easy Breadcrumb works on the principle that every segment in your path is actually a reachable page (more on this later) and it builds the page's breadcrumb based on that path sequence. This works best when used with Pathauto to define aliases.
For example, let's take an example URL of https://example.com/blogs/space/how-to-reach-mars. The expectation is that the breadcrumb would be Home / Blogs / Space / How To Reach Mars. To make this work:

https://example.com/ must be a working page (it should, it's your home page)
https://example.com/blogs could be a Views page listing all Article nodes.
https://example.com/blogs/space could be a Views page with a contextual filter, filtering all Article nodes by a topic field containing "space".
https://example.com/blogs/space/how-to-reach-mars an Article node whose alias is constructed with pattern /blogs/[node:field_topic]/[node:title]

Now Easy Breadcrumb does allow you to set unreachable pages on the in-between segments (e.g. the pages might be permissioned away or just non-existent), there is a configuration for this. In the example above, you can totally leave out the Views pages (/blogs and /blogs/[topic]) and still have the Node's path be /blogs/space/how-to-reach-mars. The breadcrumb on the page is still Home / Blogs / Space / How To Reach Mars but "Blog" and "Space" are unclickable.


How to deal with small degrees of freedom in an independent variable when testing for effects on continuous dependent variables?

Question: I have a dataset of roughly 1000 measurements of body size in an invertebrate species collected from 15 different sites, with substantially variying sample size per site. Now I want to test how the concentration of three amino acids in the substrate collected at each site affects body size, so the concentration of each amino acid can only take 15 different values.
Thinking of the types of analysis I want to do using these continuous data (regression and bayesian type): Does it matter that my independent variable is not as continuous as my dependent variable? i.e., one can take 1000 values, the other only 15
The distributions just look so different:
Comment: It should not be a problem if the assumptions of your model are fulfilled. For example, if you apply the linear regression approach, it won't be a problem if the assumptions of homoscedasticity, no autocorrelation, normality of errors etc. are fulfilled. Alternatively, you could also try to standardize the variables to change their scaling.
Answer: You have ~1000 measurements taken from 15 sites, so naturally there is more variability in body size (between specimen) than variability in amino acid concentration (between sites). This is not an issue for the validity of a model for body size as a function of amino acid concentration. (Aside: Assuming that you observe the same species at multiple sites, your data is crossed: species by sites. You have to account for this structure in the model to estimate the residual error correctly.)
However, it does have implications for the statistical power of your analysis. For the purpose of studying the relationship between amino acid concentration and body size, the sample size is 15. In other words, you would have been able to learn more about how amino acids affect length from more sites with fewer samples from each site.
Finally, it may be more informative to plot body size (length) against each amino acid concentration (trp, glu, his), optionally using shape and color of points to indicate site. This should give a better visual representation of the variability of body size across concentration and, qualitatively, about power.


How to show that every point of this set is an isolated point

Question: If we define a non-empty set $S := \{ x \in [a,b] \ | \ f(x) = 0, f'(x) >0 \}$ , $f$ having a continuous first derivative, then every point of $S$ is an isolated point.
I truly don't know where to begin. I am assuming the key is in $f \equiv 0$ yet having a positive derivative. Is this a special case? Since $S$ is non-empty, I am assuming such set exists. So far I can only think of such functions that have this behavior at specific points, like trig. functions.
Comment: *Hint*: Take $x \in S$. Then, being $f'$ continuous and $f'(x)>0$, there is a neighborhood of $x$ in which $f'$ is positive. Think about why $f$ can't be $0$ in that neighborhood.
Comment: Kernel of $f$? Why $S$ is non-empty?
Comment: That is how it was defined. If it is non-empty, then it must have isolated points only.
Comment: If what you are trying to prove is the first statement, I've posted an answer. If you are trying to find a function $f$ such that $S_{f,a,b}$ is non-empty, let $(a,b)=(-1,1)$ and $f(x)=x$.
Answer: Let $x\in S$ and $\varepsilon=f'(x).$ There exists $\delta>0$ such that
$$\forall h\in(-\delta,\delta)\quad\left|\frac{f(x+h)-f(x)}h-f'(x)\right|<\varepsilon,$$
i.e.
$$\forall h\in(-\delta,\delta)\quad\left|\frac{f(x+h)}h-\varepsilon\right|<\varepsilon,$$
therefore
$$\forall h\in(-\delta,\delta)\quad f(x+h)\ne0,$$
which proves that $x$ is the only point of $(x-\delta,x+\delta)\cap S.$
Note that the continuity of $f'$ is useless.
Answer: Let $x\in S$. By contradiction, assume it is not an isolated point. Then, for every natural $n>0$, $((x-1/n,x+1/n)\setminus \{x\})\cap S\neq \emptyset$. For all $n>0$
choose $\varphi(n)\in((x-1/n,x+1/n)\setminus \{x\})\cap S$. We then have that $\varphi(n)\to x$ so
$$f'(x)=\lim_{n\to \infty}\frac{f(x)-f(\varphi(n))}{x-\varphi(n)}$$
But, since $\varphi(n)\in S$, we must have $f'(x)=0$, a contradiction $\rightarrow\leftarrow$.
We conclude that every element in $S$ ought be isolated.


How to broadcast to other controllers when load with module.config or .run in Angularjs

Question: I have a checking when reading the web page,then using the result to refresh sidebar by ng-repeat,but I have errors  :
Uncaught Error: Unknown provider: $scope from myModule   or
Uncaught Error: Unknown provider: $scope from sharedService
How can I resolve it?
Here is my code
module:
var myModule = angular.module('myModule', []);

service for broadcast:
myModule.factory('mySharedService', function($rootScope) { //service
    var sharedService = {};

    sharedService.keyHistory = [];
    sharedService.linkHistory = [];
    sharedService.prepForBroadcast = function(key,link) {
        this.keyHistory = key;
        this.linkHistory = link;
        this.broadcastItem();
    };

    sharedService.prepForBroadcastAdd =function(key){
        console.log(this.keyHistory.push(key));
        //this.linkHistory = linkHistory+link;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

config to do Checking:
myModule.config(function($scope,sharedService){

        $.ajax({
            url:"/fly/AJAX",
            type:"POST",
            contentType:'application/x-www-form-urlencoded; charset=UTF-8',
            datatype:"json",
            success:function(data){
                if(data!=null){
                var loginResult = $.parseJSON(data);

                if (loginResult.success == true){
                    console.log("login success");
                    $("#userLable").html(loginResult.userName+'('+loginResult.loginID+')');//
                    if (loginResult.hasHistory==true) {
                        sharedService.prepForBroadcast(loginResult.searchHistory,[]);
                        console.log("broadcast");
                    }
                    };
                }
            }
    });

});

SideCtrl:
function SideCtrl($scope,sharedService) {
    $scope.$on('handleBroadcast', function() {

    $scope.keyHistory =sharedService.keyHistory;
    $scope.linkHistory = sharedService.linkHistory;
    });

}

SideCtrl.$inject = ['$scope', 'mySharedService'];

THX !
Comment: Config blocks don't have a scope.
Comment: Thx for your reply sir!
Can you tell me how to modify my code?
Comment: To be honest, I'm not entirely sure what you're trying to do here. That's why I gave such a short answer. :-) Why are you using `$.ajax` instead of `$http`? Other than broadcast an event, what do you want your service to do?
Comment: In fact,I have 3 controllers,I hope they can communicate to each other by service .
This is my reference http://jsfiddle.net/VxafF/ and it do work.                     Now I am trying add an checking when this web page loaded,so I use config to try this ,this is my fiddle  http://jsfiddle.net/deltaguita/YnACF/  :)
Comment: Using a service to communicate with multiple controllers is the right approach, but I don't think using `broadcast` is. Before I post an answer - will the data be fetched only that once, initially? Or will it be requested again later?
Comment: I hope the data can be used many times later because user may update it  :)
Comment: I meant does the AJAX request need to occur more than once?
Comment: Check do ajax once when initially webpage.
If user user Login another ID,it will do another AJAX check
Answer: The error is due to trying to request a $scope in a config block, which you can't do. If I understand what you're trying to do, then I also think you're over-complicating it. I'd solve the problem a little differently. The details would depend on your requirements and use case, but based on the information you gave...
I'd have a service responsible for communication with the server and storing the state:
app.factory( 'loginService', function ( $http ) {
  var result;

  function doRequest( data ) {
    // just flesh out this post request to suit your needs...
    return $http.post( '/fly/ajax', data, {} )
    .then( function ( response ) {
      // assuming you don't care about the headers, etc.
      return response.data;
    });
  }

  // Do it once initially
  if ( ! angular.isDefined( result ) ) {
    result = doRequest();
  }

  // return the service's public API
  return {
    getStatus: function () { return result; },
    login: doRequest
  };
});

Now the first time this service is requested, the $http request will be made. If you're accessing this from multiple controllers, the post will only occur once because of the isDefined statement. You can then use this in your controllers:
app.controller( 'MainCtrl', function( $scope, loginService ) {
  loginService.getStatus().then( function ( data ) {
    // do whatever you need to with your data.
    // it is only guaranteed to exist as of now, because $http returns a promise
  });
});

Every controller accesses it the same way, but it was still only called once! You can set values against the scope and access it from your views, if you want:
app.controller( 'MainCtrl', function( $scope, loginService ) {
  loginService.getStatus().then( function ( data ) {
    $scope.loginId = data.loginID;
  });
});

And in your view:

Welcome, {{loginId || 'guest'}}!

And if you need to, you call the function again:
app.controller( 'MainCtrl', function( $scope, loginService ) {
  // ...
  loginService.login( $scope.user ).then( function ( data ) {
    $scope.loginId = data.loginID;
  });
  // ...
});

As you can see, broadcasting an event is totally unnecessary.
Comment: Thank you sir!
It do work very well in my project.Could I have another question? Why the ng-repeat dose not show data as  {{loginId || 'guest'}} When init? They show data when I change or click the table only, this is my fiddle  http://jsfiddle.net/deltaguita/YcyQU/
Comment: It's hard to tell without seeing it run. Can you send me a working fiddle?
Comment: Well,server works on localhost,I don't know how to deploy it on fiddle...   XD
Answer: I would do it differently. I would create some sort of more top-level controller, like function MainController($rootScope, $scope, sharedService) and wire it up with body: <body ng-controller='mainController' ng-init='init()'. After that you should create init() method in MainController.
Inside this initialization method I would call sharedService which should make AJAX request (via $http! that's the best practice, and it's very similar to jQuery) and broadcast proper event when required.
That way you make sure to call initialization just once (when MainController is initializing), you stick to the angular's best practices and avoid dodgy looking code.


How to perform inference on stratified sampling data

Question: Let's say I'm studying a population of generic emergency calls to over the course of several months, and keeping track of the following independent variables:

month (when the call happened)
country (where the call originated)
typology (what the call was about: robbery, murder, fire, health issues, natural disasters, etc)

My target variable is whether or not the call was a false alarm, i.e., something that wasn't really an emergency. I know as a fact that the vast majority of calls (~90%) are false alarms.
I'm working with a statistical study where the samples are stratified by month and country, essentially sampling a number of calls separately in each country and each month, but across all typologies at random. In this way, I think the most frequent typologies are better represented.
In theory, if the sample is large enough, I can draw meaningful conclusions on what happened in a certain country on a certain month, because that's the population subset where I have a random sample -- by definition of stratified sampling.
Unfortunately, I know that the monthly sample for each country is not large enough, say on average 80 samples over 800 calls. I can't really draw any conclusion on how many calls are false alarms in a given country/month with a satisfactory margin of error and interval of confidence. Let alone doing so by typology, because I didn't even stratify the sampling for that variable. Hence, I'm looking for ways to aggregate my stratified monthly/country samples to derive some statistically valid conclusion on false alarms in countries, and possibly by call typology.
Can I assess how many calls are false alarms in each country if I consider the samples for a large enough number of months all together, and assume there are no month-dependent factors in whether or not a call is a false alarm? In this way, say for a year, I'd have in a country a sample of $80*12 = 960$ calls over a population of $800*12 = 9600$, which at least size-wise looks better representative than a sample of 80 over 800. I'm afraid that since the 960 samples aren't random anymore (they are equally split by month) this could lead to a fundamentally study-invalidating bias even if I assume time-independence.
Let's assume I can do that -- Can I assess how many calls are false alarms for each typology if I consider the samples for a large enough number of months and countries all together, and assume there are no month- and country-dependent factors in whether or not a call is a false alarm? This case is similar to the previous one, but the original sampling didn't stratify by typology -- only by country and month. Can that be an issue, or since the sample has been taken at random across all typologies it's representative enough at least for the most common call typologies?
Comment: Mixed midels (hierarchical models) are perfect for the scenario you are talking about, are you familiar with these methods? ie lme4 package in R?
Comment: No, not really. As you can read from the text, I'm attacking the problem from the "traditional" theory for sampling, intervals of confidence and margin of errors. I.e., I have a population of N individuals, I sample n of those (with/without replacement), hence I have a MOE and CI which I can calculate with critical values based on the normal distribution, and possibly finite populations corrections if sampling without replacement. I'd love an answer on how to tackle this problem with mixed models though, but I'll start reading right away.
Answer: Okay, so here is what I recommend:
What not do to:

Collapsing by ignoring certain level (for example month) could either be fine but more probably not, as it will have some effect and confounds your inference since you did not control for it.
Assuming things and not really testing that assumptions hold. I'm not saying you should actually perform statistical test for the assumptions (even though you often can), but simply evaluating the effect of changing the assumptions on the result of your inference.

Enough of things not do to, let's talk about more interesting stuff, what you can do:

Assume you have no idea how to tackle this and start learning how people often attack this sort of problems which is through using mixed/random/hierarchical models.
Read Wikipedia pages for terms like hierarchical models, partial pooling and random effects.
Download the magnificent book of Statistical Rethinking (version 2, freely available) from Richard McElreath. The pdf is available here. It is password protected (hint: info about where to find the password is provided in the latest course's webpage).
Read the book and also go through the lectures (latest version) for example here
Now you will have a very good understanding of how to tackle this.
You could either go through the lme4 docs and try to get things done in a frequentist way, or you might want to use a fully Bayesian way, it all depends on you.
There are literally tons of documents, article, books on how to do these things, but the most important thing is to learn what these models are and what they can do for you and this is exactly what McElreath has done, in an outstanding way, IMHO.

Here are some other books I recommend reading (after that book) if you are into this:
1 - Data Analysis Using Regression and Multilevel/Hierarchical Models
2 - Mixed Models: Theory and Applications with R
Good luck!


Why are samples always taken from iid random variables?

Question: In most mathematical statistic textbook problems, a question always ask: Given you have $X_1, X_2, \ldots, X_n$ iid from a random sample with pdf:(some pdf). My question is why can't the sample come from one random variable such as $X_1$ since $X_1$ itself is a random variable. Why do you need the sample to come from multiple iid random variables?
Comment: The samples _do_ come from the same random variable, but the different samples need different names, that is, it makes no sense to say something like "Let $X_1$, $X_1$,$\ldots,$ $X_1$ denote a random sample with pdf $f_X(x)$".
Comment: @Henning: that sure looks like an answer to me... :)
Answer: A random variable is something that has one definite value each time you do the experiment (whatever you define "the experiment" to be), but possibly a different value each time you do it. If you collect a sample of several random values, the production of all those random values must -- in order to fit the structure of the theory -- be counted as part of one single experiment. Therefore, if you had only one variable, there couldn't be any different values in your sample.
Answer: Suppose the sample came from a single random variable $X$, say a dice with sample $[3,5,1,3]$. To compute the probability of observing this sample, you'd start by writing down something like
$$\text{Pr}\,(X=3\wedge X=5 \wedge X=1 \wedge X=3).$$ But this is zero, since the events $X=3$, $X=5$ and $X=2$ are mutually exclusive.
Taking the math seriously you might even come to the conclusion that the philosophical underpinnings of frequentism make no sense. There is no such thing as a single random variable, which can be repeatedly sampled and produce different outcomes.
Not sure if this argument is what Henning Makholm meant by "in order to fit the structure of the theory".


ImportError: when I use quandl module in python

Question: ImportError: when I use quandl module in python
Traceback (most recent call last):
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:\workspace\python\stock-lab\agent\quandl.py", line 1, in <module>
    import quandl
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\__init__.py", line 7, in <module>
    from .model.database import Database
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\model\database.py", line 5, in <module>
    import quandl.model.dataset
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\model\dataset.py", line 5, in <module>
    from .data import Data
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\model\data.py", line 1, in <module>
    from quandl.operations.data_list import DataListOperation
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\operations\data_list.py", line 1, in <module>
    from quandl.model.data_list import DataList
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\model\data_list.py", line 2, in <module>
    from .data_mixin import DataMixin
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\quandl\model\data_mixin.py", line 1, in <module>
    import pandas as pd
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\__init__.py", line 55, in <module>
    from pandas.core.api import (
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\api.py", line 29, in <module>
    from pandas.core.groupby import Grouper, NamedAgg
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\groupby\__init__.py", line 1, in <module>
    from pandas.core.groupby.generic import DataFrameGroupBy, NamedAgg, SeriesGroupBy
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\groupby\generic.py", line 60, in <module>
    from pandas.core.frame import DataFrame
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\frame.py", line 124, in <module>
    from pandas.core.series import Series
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\series.py", line 4572, in <module>
    Series._add_series_or_dataframe_operations()
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\generic.py", line 10349, in _add_series_or_dataframe_operations
    from pandas.core.window import EWM, Expanding, Rolling, Window
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\window\__init__.py", line 1, in <module>
    from pandas.core.window.ewm import EWM  # noqa:F401
  File "C:\Users\vopl1\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\window\ewm.py", line 5, in <module>
    import pandas._libs.window.aggregations as window_aggregations
ImportError: DLL load failed: 지정된 모듈을 찾을 수 없습니다.

I did several things, but I don't know why the module was not available

I installed quandl
as followed :

pip install quandl

I made my under python code

import quandl

quandl.ApiConfig.api_key = '@@@@@@@@@@@@@@'
data = quandl.get('BCHARTS/BITFLYERUSD', start_date='2019-03-07', end_date='2020-05-02')

print(data)

I call my pthon code

python -m myPythonCode

and then, I saw the error.
So I deleted and installed, but failed.
So I installed as followed :
pip3 install quandl

this is still failed.
if uninstall quandl and then call my python code, I can see error :
ModuleNotFoundError: No module named 'quandl'

Plz, Help me.
Comment: Does this answer your question? [Unable to import pandas (pandas.\_libs.window.aggregations)](https://stackoverflow.com/questions/60763529/unable-to-import-pandas-pandas-libs-window-aggregations)
Answer: When the error is DLL related, many times it can be resolved by installing the Microsoft Visual C++ Redistributable that is most likely missing.
Microsoft Visual C++
Comment: Thank you for your help. I install Microsoft Visual C++ Redistributable 2019. This is available. Thank you!!


How to Create a custom tab layout that mimics the default tab text

Question: I need to create a custom tab layout, but I want the text to mimic the style used in the normal TabLayout.TabView.
To do that, I've set my text appearance to TextAppearance.Design.Tab.
If you take a look at TabLayout itself, you can see that's what TabView's text uses:
mTabTextAppearance = a.getResourceId(R.styleable.TabLayout_tabTextAppearance, R.style.TextAppearance_Design_Tab);

...
TextViewCompat.setTextAppearance(mTextView, mTabTextAppearance);
However, when my tabs display, I can clearly see the text is not the same.  It's very similar, but the default tab looks to be more bold.
What am I doing incorrectly?
Answer: The answer was to set the text appearance programmatically.  Setting android:textAppearance on the TextView in the XML file doesn't seem to do anything.  Setting the text appearance programmatically (like TabLayout.TabView) works.


Erro - string C# para o Crystal Report

Question: Ao tentar passar a string do c# Windows Forms para o Crystal Report seguindo o procedimento da segunda imagem e do código abaixo o crystal report mostra o seguinte erro! Visual Studio Community 2017, Mysql free e Crystal Report Sap.
Erro:

Código:
private void Form2_Load(object sender, EventArgs e)
{
    ReportDocument cryRpt = new ReportDocument();
    cryRpt.Load("C:\\Users\\Rafael\\Desktop\\ProG\\Gold Business - Another\\Gold Business\\CrystalReport1.rpt");

    ParameterFieldDefinitions crParameterFieldDefinitions;
    ParameterFieldDefinition crParameterFieldDefinition;
    ParameterValues crParameterValues = new ParameterValues();
    ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

    crParameterDiscreteValue.Value = usuario;
    crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
    crParameterFieldDefinition = crParameterFieldDefinitions["usuario"];
    crParameterValues = crParameterFieldDefinition.CurrentValues;

    crParameterValues.Clear();
    crParameterValues.Add(crParameterDiscreteValue);
    crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

    crystalReportViewer1.ReportSource = cryRpt;
    crystalReportViewer1.Refresh();
}

Ligando no Crystal Report:
Comment: que linha está estourando a exceção? é em "crParameterFieldDefinition = crParameterFieldDefinitions["usuario"]; "  ?
Comment: crParameterFieldDefinition = crParameterFieldDefinitions["usuario"];    // aponta esta linha
Comment: O mais provável é que você não esteja passando o nome, no caso "usuario", correto, se eu fosse você colocaria um breakpoint aí e daria uma olhada na collection de crParameterFieldDefinitions pra ver se encontra o nome de fato do seu campo
Comment: desculpe eu sou novato com o Crystal Report, como devo passar no parâmetro a "string" usuario para fazer conexão com o código escrito acima deve ser aí o erro, está passando no parâmetro, no crystal report, na segunda imagem abaixo.
Comment: cara, sinceramente é mais fácil fazer o que eu falei, se você abrir a collection lá vai dar pra ver o nome dos seus parâmetros corretamente, mas se não me engano acho que precisa por uma @ antes do nome do parâmetro, talvez seja só isso
Answer: Acho que pode substituir todo esse código de atribuição de um parâmetro por isto:
cryRpt.SetParameterValue("usuario", "Eu!");

Após essa substituição pode inclusive deixar de lhe dar erro, isto se o parâmetro realmente existir no report.
Comment: Dá o mesmo erro! e aponta para esta linha cryRpt.SetParameterValue("usuario", "Eu!")  no caso só tem no Crystal Report o parâmeto "usuario" no caso como eu deveria passar o parâmeto está como na segunda imagem acima.

Erro - string C# para o Crystal Report


About GCM implementation Android application after April 11, 2019(GCM is abolished)

Question: I would like to migrate a GCM Client App for Android to Firebase Cloud Messaging.
In the Firebase console, I selected my GCM project from the list of existing Google Cloud projects, and add Firebase,
and now, even if I update my server code to use new FCM endpoints for sending messages,  Push notification will be sent to the existing GCM version Android application It has arrived.
Will Push notifications be sent to GCM version applications after April 11, 2019(GCM APIs will be removed)?
It seems that such meaning is written in GoogleDeveloper (※ https: //firebase.googleblog.com/2018/04/time-to-upgrade-from-gcm-to-fcm.html).
But my android app does not use "GcmListenerService" which appears in Google official migration guide.
my android app is an old implementation just after migrating a C2DM Client for GCM Client,
is the old implementation right after moving from C2DM to GCM, is my android app OK?
Current implementation

Start Service with the intent of
com.google.android.c2dm.intent.REGISTER specified, and register
registration ID
Receive BroadCast of com.google.android.c2dm.intent.REGISTRATION,
obtain registrationId and send it to business server
Receive BroadCast of com.google.android.c2dm.intent.RECEIVE,
receive push notification from the server.

For business reasons,
It is difficult to forcibly update the current user's Android application from the GCM version to the FCM version.
Thank you.
Answer: From the same blog post (emphasis mine):

If you have projects that are still using the GCM APIs, you will need to update your client and server code to use FCM before April 11, 2019.

With that, it seems you need to update the client app as well. There isn't any documentation that says that app versions that are still using GCM code would cease to receive messages, but the behavior to receive will no longer be guaranteed after the said date.
Business wise, you may not force the update, but make it so that users are encouraged to update by saying something along the lines of "An update is necessary to use the full potential of the app."
Answer: I came to the following conclusion, based on this (from further down the same blog post):

What happens to my users who don't update their apps?
As long as users have GCM logic in their apps, they will still receive messages. FCM is backwards compatible with GCM, so even if you don't update your server endpoint now, you can still update your app's logic, and vice versa.

And from the FAQ:

Note that client SDKs and GCM tokens will continue to work indefinitely. However, you won't be able to target the latest version of Google Play Services in your Android app unless you migrate to FCM.

So I'm going to play it safe and have both my server and app updated with FCM before the deadline.
But to answer your question, users who have not upgraded to the FCM version of the app should still continue to receive push notifications after the April 2019 deadline.


How to play and read scales when the treble clef appears with the bass?

Question: In the ABRSM scales, eg. Level 3 E Major, the treble clef appears on the bass clef. Do I read as treble but play with my left hand?
Thank you in anticipation
Comment: Do you mean the treble clef appears on the bottom staff where the bass clef usually is?
Comment: Can you post an image of the notation?
Answer: Pretty straightforward. You're playing two hands together, so follow r.h. all the way up on treble clef. L.h. starts on bass clef - that's basically what the bass clef is for - and goes for one octave. After that, the notes go too high for the bass clef, and would have to be all on ledger lines, so they're shown as the lower notes on the treble clef, going up the second octave. You didn't think they all had to be played with r.h., did you?! This is only grade III...
Don't understand 'the treble clef appears on the bass clef'.
Scales will follow the pattern of playing each note sequentially ascending, then return descending, so it's pretty logical.
Comment: Hello Tim, thanks for your reply. In my ignorance I thought you had to play right handed when notated (if that's the correct phrase) that way
Answer: I think you are mixing up clef with stave.
A stave or staff is the group of lines, five is modern, four is very old, and there are sometimes other unusual numbers of lines. Clefs are the symbols used to assign pitches to the staff.

...the treble clef appears on the bass clef.

It appears on the lower stave of the system.
It's not a bass clef unless the stave has a bass clef.

...Do I read as treble but play with my left hand?

Yes, unless for some reason the part is marked in the score with something like R.H. to mean play this lower stave with the right hand.
Comment: Thank you Michael, yes I did mix stave with clef, I now understand the reason for the notation and how to play the scale
Comment: @the-baby-is-you - being even more pedantic - staff and stave are interchangeable - in music either is used in the singular. Plural is staves. Staffs is a county in England...
Comment: Have a look at ABRSM grade III scales. It will make more sense to you, as this doesn't answer the question, I think.
Comment: I don't have those books. I assumed it was a piano grand staff. Is this a single stave, starting with an F clef and then switching to G clef? If a single stave didn't give a hand indication you could use either one.
Comment: It's Googleable. Comes up with the page of clearly written scales .
Comment: Then how about a link or update the OP? I only get links to _buy_ it.
Comment: Put in 'abrsm grade 3 scales' and it should come up with options to see.
Comment: https://us.abrsm.org/en/our-exams/piano-exams/piano-grade-3/ is the first of Google results, that page has a PDF link https://us.abrsm.org/media/62100/grade_3_piano_syllabus_2019___2020.pdf and a link to buy. I don't see a scale, ...a simple screen shot updating the OP would clear it up
Comment: Didn't realise abrsm operated in US too. Try UK.
Comment: gb.abrsm.org has the exact same content. Is there a point @Tim to not simply update the OP if you already have the scale?
Comment: Sadly, I am too old to transfer that information - or possibly it can't be transferred anyway. It's in the OP's interest to do that, surely? My answer covers it in any case.
Comment: @Tim, oh I see now. You might want to check out Greenshot for easy screen shot capture. Not necessarily for this question, but you might find it useful for lots of things. https://getgreenshot.org/
Comment: "Staves" is the plural of "staff." There's no such thing as one stave. I'm sorry, I know the usage is widespread, I just have to be pedantic about it.
Comment: that's why they celebrate independence day!
I've understood that **staff** is one system of 5 note lines and the term for both systems (l. & r. h. keyboard) is **grand staff**, is this correct?  ... while in a full score would be several staves?
Comment: @the-baby-is-you, https://doi.org/10.1093/gmo/9781561592630.article.26519
Answer:
Do I read as treble but play with my left hand?

Yes, of course. Obviously  you know how to read both clefs (bass and treble) you're just wondering why in the left hand the treble clef appears. you're practicing scales: they go from the lowest key up to the highest key of the piano. Imagine this notes were written in the bass clef: You had to decipher so many ledger lines that you always had to count them first with your fingers.
There's no difference between the treble clef in the l.h. and the r.h. - only that the l.h. (respectively your brain) is not used to read treble clef for the l.h. and give the command to the l.h. So you can play this passage first with the r.h. and then let the l.h. follow what the r.h. was doing. It will take you only a short time to get adapted to it.
N.B You will encounter the opposite "problem" when the r.h. will play lower than the middle C, the bass clef will appear in the staff for the r.h.

I've just encountered this original handwriting by Bach: In bar 5 you can see how the l.h. is playing in the c-clef staff of the r.h. but here it is quite clear that the lower part is played by the l.h.
Comment: My thanks to you all for taking the time to educate me


VHDL - Phase Accumulator with feedback

Question: I am trying to create a phase accumulator using VHDL that has the following characteristics.
Inputs:

D (Input signal)
RESET
CE
CLK

Outputs:

Q (output signal - feedback)

Source code:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;
entity Phase_accu is
port (
    D       : in std_logic_vector(3 downto 0);
    CE      : in std_logic;
    CLK     : in std_logic;
    RESET   : in std_logic;
    Q       : out std_logic_vector(15 downto 0)
);
end Phase_accu;

architecture Behavioral of Phase_accu is
begin

process(D, CE, CLK, RESET)
    begin
        if RESET = '1' then
            Q <= "0000000000000000";
        elsif rising_edge(CLK) then
            if CE = '1' then
                Q <= ("000000000000" & D) + Q;
            end if;
        end if;
end process;

end Behavioral;

I get an error with the line trying to merge together the 2 signals for feedback...
Q <= ("000000000000" & D) + Q;

Cannot read output "Q".
Comment: Removing the superfluous `use` before `library` on the first line of your code and using VHDL revision -2008 your code analyzes and elaborates (evaluating a port of mode out is possible in -2008). Please provide a [mcve] including complete error message and identifying the operation your tool was performing, the problem isn't guaranteed reproducible from your question as is.
Answer: You can't read the value of an out in VHDL revisions prior to VHDL-2008. The usual way to get around this is to have an internal copy of your output, and use that internal copy when you need to get its value:
[...]
Q : out std_logic_vector(15 downto 0);
[...]
signal Q_reg : std_logic_vector(15 downto 0);

process(D, CE, CLK, RES)
    begin

        if RES = '1' then
            Q_reg <= "0000000000000000";
        elsif rising_edge(CLK) then
            if CE = '1' then
                Q_reg <= ("000000000000" & D) + Q_reg;
            end if;
        end if;
end process;

Q <= Q_reg;

Comment: I understand now. Thankyou very much for your help. :)
Answer: I suggest to use numeric_std library instead of STD_LOGIC_ARITH and STD_LOGIC_UNSIGNED. I also suggest to make some minor optimizations regarding the vector size specification.
Also the sensitivity list has two many entries. You have to remove D and CE to describe a valid clocked process with asynchronous reset. See your Synthesis tool manual for details.
This makes the code above to
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity Phase_accu is
port (
    D       : in std_logic_vector(3 downto 0);
    CE      : in std_logic;
    CLK     : in std_logic;
    RESET   : in std_logic;
    Q       : out std_logic_vector(15 downto 0)
);
end Phase_accu;

architecture Behavioral of Phase_accu is
    signal Q_reg : unsigned(Q'range);
begin

process(CLK, RES)
begin

        if RES = '1' then
            Q_reg <= (others => '0');
        elsif rising_edge(CLK) then
            if CE = '1' then
                Q_reg <= resize(unsigned(D), Q_reg'length) + Q_reg;
            end if;
        end if;

end process;

Q <= std_logic_vector(Q_reg);

end Behavioral;

VHDL - Phase Accumulator with feedback


packager for iphone XML

Question: I am trying to build my iphone app from a swf in windows using pfi but i run into this error:

C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(117): error 105: application.icon.image29x29 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(117): error 105: application.icon.image29x29 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(118): error 105: application.icon.image57x57 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(118): error 105: application.icon.image57x57 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(119): error 105: application.icon.image72x72 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(119): error 105: application.icon.image72x72 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(120): error 105: application.icon.image512x512 contains an invalid value
C:\Users\tkazak\Adobe Flash Builder 4\iphoneTest\bin-debug\iphoneTest-app.xml(120): error 105: application.icon.image512x512 contains an invalid value

My xml looks like this:
<code> <icon>
        <image29x29>icons\icon29.png</image29x29>
        <image57x57>icons\icon57.png</image57x57>
        <image72x72>icons\icon72.png</image72x72>
        <image512x512>icons\icon512.png</image512x512>

 </icon>
</code>
Does the packager regard my xml values as invalid because of the backslashes?
Comment: Maybe. Try with the regular-style-backslashes?
Comment: Interesting... using flash. Probably this way will start getting some popularity now AppStore rules are changed.
Answer: Turns out the forward slashes are fine. The issue was in my cmd line arguments. I used the refresher example where only a file name is specified for the icon http://blogs.adobe.com/cantrell/archives/2010/09/packager-for-iphone-refresher.html
So all I needed to do was change the last pfi argument to "icons" for the icons folder.

packager for iphone XML


shared files or folders being locked by administrator

Question: I have a user who uses a share folder. the folders are in 2003 windows server.
she started to complain about files and folders which she cannot rename or move.
I checked the open files under Shared Folders in computer management and the folders and files she uses at the time are opened by administrator not by her. but only she uses those files no one else using the files or folders.
She has windows 7.
I have to close those files from computer management in server 2003 all the time for her to rename or move the files.
why do you think this is happening?
Comment: real-time AV scanning in use on the server, like McAfee?  I've seen it cause these types of situations.
Comment: As well as AV scanning, this can also be caused by the explorer.exe process on a client trying to index files or trying to build a `thumbs.db` file, it often happens if the directory contains images, pdf files etc. Does the computer management open files give any clues as to what files / directories are locked?
Comment: Possibly a AV service running or some other type of indexer?
Answer: Download and install Process Explorer. And run it on the server
<code>1. Click Find menu
2. "Find Handle or DLL"
3. Enter file name or path
</code>
You will get a list of processes that have the file or folder(s) open. This can help you to determine what happens.
Answer: An app like PA File Sight would let you track access to those files and find out what IP address the administrator account is accessing them from.  And if access is coming from the server itself, it would tell you what process was the source of the access.


eu estou tendo problemas ao iniciar o React

Question: ao tentar iniciar o react ele diz que "package.json" não esta sendo encontrado em "C:\Users\admin\Downloads\Projeto-QUIS-main"; irei colocar imagens abaixo para ajudar a identificar, irei colocar um print tentando iniciar com "yarn start" e a outra com "npm start"
npm start
yarn start
Comment: Você rodou npm install antes?
Comment: Obs: "quiz" é um termo em inglês, e se escreve  com Z
Answer: Perceba que você tem duas pastas com o mesmo nome: "Projeto-QUIS-main". O seu package.json existe, mas ele está na segunda pasta "Projeto-QUIS-main". Você atualmente está na primeira pasta. Então a solução é você mover para a segunda pasta e executar novamente npm start ou yarn start.


Why does Type II/III ANOVA on cumulative link model (R-package ordinal) give different results depending on factor order?

Question: From what I understand, type II and type III ANOVA should give the same result irrespective of the order of the factors in the formula because they calculate:
Type II:
    SS(A | B) for factor A.
    SS(B | A) for factor B.
    SS(A:B|A,B) for the interaction.
Type III:
    SS(A | B, A:B) for factor A.
    SS(B | A, A:B) for factor B.
    SS(A:B|A,B) for the interaction.

But when I run clm from the ordinal R-package on my data and then perform type II (or type III) ANOVA using the Anova function from the car R-package, I obtain completely different results depending on the order of my factors.
Edit 2:
After a little bit of trial and error, I managed to make better example data for my issue:
dat<-data.frame(Treatment=c("Control","TreatmentA","TreatmentB","Control","TreatmentA","TreatmentB"),
Judge=c("C","C","C","E","E","E"),
VeryLow=c(2,3,2,2,3,2),
Low=c(1,3,6,1,3,6),
High=c(3,3,5,3,3,5),
VeryHigh=c(68,76,72,68,76,72))

# Some code to make the count data compatible with the clm package
orderedLevels<-c("VeryLow","Low","High","VeryHigh")
longDat<-reshape(dat, varying=orderedLevels, v.names="rating_count",timevar="rating",times=orderedLevels,direction="long")
indivDat<-longDat[rep(seq(1, nrow(longDat)), longDat$rating_count),]
indivDat$rating<-ordered(indivDat$rating, levels=orderedLevels)
summary(indivDat)

# The clm models without interactions
library(ordinal);library(car)
fm1 <- clm(rating ~ Treatment + Judge, data=indivDat)
fm2 <- clm(rating ~ Judge + Treatment, data=indivDat)
Anova(fm1, type="II"); Anova(fm2, type="II")

# The lm equivalent models without interactions
indivDat$rating_num<- as.numeric(indivDat$rating)
fm3 <- lm(rating_num ~ Treatment + Judge, data=indivDat)
fm4 <- lm(rating_num ~ Judge + Treatment, data=indivDat)
Anova(fm3, type="II"); Anova(fm4, type="II")

The results for this new example are:
> Anova(fm1, type="II")
Analysis of Deviance Table (Type II tests)

Response: rating
          Df  Chisq Pr(>Chisq)
Treatment  2 92.725    < 2e-16 ***
Judge      1 53.275    2.9e-13 ***
---

> Anova(fm2, type="II")
Analysis of Deviance Table (Type II tests)

Response: rating
          Df  Chisq Pr(>Chisq)
Judge      1 92.426  < 2.2e-16 ***
Treatment  2 76.882  < 2.2e-16 ***
---

> Anova(fm3, type="II")
Anova Table (Type II tests)

Response: rating_num
           Sum Sq  Df F value Pr(>F)
Treatment   1.177   2  1.3917 0.2497
Judge       0.000   1  0.0000 1.0000
Residuals 204.659 484

> Anova(fm4, type="II")
Anova Table (Type II tests)

Response: rating_num
           Sum Sq  Df F value Pr(>F)
Judge       0.000   1  0.0000 1.0000
Treatment   1.177   2  1.3917 0.2497
Residuals 204.659 484

How can the Judge effect be significant with the clm package when the data for each judge is just a copy of each other? And why does the order of the factor in the cum link model matters?
What is going on here? Did I misunderstood the type II/III Anova? And what is the best course of action when analyzing such a data set?
Original example (without results):
Here is a reproducible example for Type II using the wine dataset:
library(ordinal)
fm1 <- clm(rating ~ contact * bottle, data=wine)
fm2 <- clm(rating ~ bottle * contact, data=wine)

library(car)
Anova(fm1, type="II"); Anova(fm2, type="II")

Edit 1: Same model without interactions.
> fm1 <- clm(rating ~ contact + bottle, data=wine)
> Anova(fm1, type="II")
Analysis of Deviance Table (Type II tests)

Response: rating
        Df   Chisq Pr(>Chisq)
contact  1  1.8182     0.1775
bottle   7 53.1100  3.526e-09 ***

> fm2 <- clm(rating ~ bottle + contact, data=wine)
> Anova(fm2, type="II")
Analysis of Deviance Table (Type II tests)

Response: rating
        Df  Chisq Pr(>Chisq)
bottle   7 71.534  7.231e-13 ***
contact  1  6.847   0.008879 **

Comment: That is the problem. Contact is fully determined by bottle. As such, this data is not appropriate for a two-way ANOVA. With data in all 16 cells (8 bottles, 2 contacts) then the order of the factors would not matter. Also note that this is not a standard ANOVA model (I didn't notice this initially) given that the DV is coded as ordinal and not scaled (hence the analysis of deviance with a chisq rather than analysis of variance with an F). I'm not sure how the latter would be affected by the Type II/III distinction.
Comment: In your example, bottles are nested within contacts. Correcting what I said above, you can do a two-way anova but the interaction between these two doesn't make sense: it is not possible for the effect of bottle to differ between contacts=0 and contacts=1.
Comment: You've got a problem with your data. The df for the interaction should be 7. Given that it is 3 indicates that you have cells with no data.
Comment: `wine` is the example data from the `ordinal` package. It does not contain any missing data. @dbwilson You are right that the interaction doesn't make sense here because bottles 1,2,5 and 6 always have "no" contact and the rest of the bottles (3,4,7 and 8) always have a "yes" for contact. But (1) removing the interaction term does not solve the problem. (2) Shouldn't Anova type II and III results be independent of the order of the factor even if the data is unbalanced?
Comment: @dbwilson (1) If the data was perfectly balanced, not only would both order give the same results but ANOVA type I, II and III would also give the same results. So that would completely defeat the purpose of this question. Of course this is an extreme example, but I get the same with less unbalanced data. (2) Indeed, I only get this issue with `clm` models for `ordinal` response. But shouldn't the Chi-square test be symmetrical just like the F-test? Otherwise, what does Type II and III mean in for this test?
Comment: Having data in each cell of the design is not the same thing as a balanced design. The latter is the same sample size in each cell. You are correct that with a truly balanced design, Type I, II, and III SS give the same results. That said, it appears that you've identified the issue as the clm model. I don't have any experience with these so can't answer why the chi-square test in this situation would be different, but clearly it is.
Comment: @dbwilson Indeed, empty cells and unbalanced is not the same. I answered a bit to hastily, sorry. But I had difficulties making a small reproducible example that made sense. In any case, I observe the same issue without interactions and without empty cells in my data. I think there is an issue with the way ANOVA is performed on `clm` objects because if I have the exact same data for the 2 levels of a factor, the factor still appears significant! And if I do the Chi-square test by dropping or adding terms manually the results look much more consistent!
Comment: @dbwilson explained what the problem is with that particular data.  For an example without issue, try the following. `library(ordinal); library(car); fm1 <- clm(rating ~ contact * temp, data=wine); fm2 <- clm(rating ~ temp * contact, data=wine); Anova(fm1, type="II"); Anova(fm2, type="II")`
Comment: Also note that you get useless results if you use lm rather than clm for the contact / bottle data.  `library(car); wine$rating.num = as.numeric(wine$rating); fm3 <- lm(rating.num ~ contact * bottle, data=wine); fm4 <- lm(rating.num ~ bottle * contact, data=wine); Anova(fm3, type="II"); Anova(fm4, type="II")`
Comment: I made a new example data set to show that even on a data set with all possible combinations of parameters, ANOVA on clm can have a similar unexpected behavior.
Comment: @SalMangiafico Indeed, I get useless results with the `lm` too but at least the absence of results and 0 Df for the interaction term shows clearly where the issue lies in that case! Similarly, in the new example data set, the `lm` Anova results are consistent with the data and independent of the term order whereas the `clm` Anova results are not.
Answer: The documentation for car::Anova does not indicate that it works with clm or clmm objects. From your examples, it appears it can have some unusual behavior.
My solution is to use RVAideMemoire::Anova.clm.
So, for your EDIT 2 example:
if(!require(RVAideMemoire)){install.packages("RVAideMemoire")}
if(!require(car)){install.packages("car")}

library(car)

library(RVAideMemoire)

Anova(fm1, type="II")

### Analysis of Deviance Table (Type II tests)

### Response: rating
###           LR Chisq Df Pr(>Chisq)
### Treatment   4.0507  2     0.1319
### Judge       0.0000  1     1.0000

Anova(fm2, type="II")

### Analysis of Deviance Table (Type II tests)

### Response: rating
###           LR Chisq Df Pr(>Chisq)
### Judge       0.0000  1     1.0000
### Treatment   4.0507  2     0.1319

Note that this produces the same p-values as the anova function.
fm1 <- clm(rating ~ Treatment + Judge, data=indivDat)
fmx <- clm(rating ~ Treatment, data=indivDat)
fmy <- clm(rating ~ Judge, data=indivDat)

anova(fm1, fmx)

### Likelihood ratio tests of cumulative link models:

###     formula:                   link: threshold:
### fmx rating ~ Treatment         logit flexible
### fm1 rating ~ Treatment + Judge logit flexible

###     no.par    AIC  logLik LR.stat df Pr(>Chisq)
### fmx      5 474.85 -232.42
### fm1      6 476.85 -232.42       0  1

anova(fm1, fmy)

### Likelihood ratio tests of cumulative link models:

###     formula:                   link: threshold:
### fmy rating ~ Judge             logit flexible
### fm1 rating ~ Treatment + Judge logit flexible

###     no.par    AIC  logLik LR.stat df Pr(>Chisq)
### fmy      4 476.90 -234.45
### fm1      6 476.85 -232.42  4.0507  2     0.1319

Comment: UPDATE:  a generic `anova` function has been added to the `ordinal` package, so that you can use `anova(model)` directly from the `ordinal` package.  At the time of writing, by default, it reports Wald chi-square tests, whereas `anova(model1, model2)` will report likelihood ratio tests.  `Anova.clm` from `RVAideMemoire` reports LR tests by default.   Also, at the time of writing, `anova(model)` in the `ordinal` package doesn't work with clmm objects.
Comment: Thank you a lot! These results make much more sense, and it is a bit simpler to use than the "manual" comparison of models with `anova`, especially for models with more predictors! It would be nice if `car::Anova` would give an error or a warning of some sort for 'clm' objects...
Comment: If I type `if(!require(RVAideMemoire)){install.packages("RVAideMemoire")}; library(RVAideMemoire); Anova(fm1, type="II")`, I get `Error in Anova(fm1, type = "II") : could not find function "Anova"`! Would you know what is going on?
Comment: You need a `library(car)` before the `library(RVAideMemoire)`.  Let me change that in my answer.


Number of solutions of equation

Question: Consider the set $A = [a,b,c,d,e,f,g,h] = [1,2,3,4,5,6,7,8]$.
Find the number of permutations of $A$ that satisfy the equation:
$$a + 2b + 3c + 4d + 5e + 6f+ 7g + 8h = 160$$
No computer allowed.
Note:
The question is based on the (unsolved) n. 344 problem - recreational math contest corner - "Sapere" magazine - Hoepli editions - year 1938 - printed in Italy.
Nowadays,if we want the result,a computer instantly gives correctly 1066 permutations.
A math value or interest of the question, I think, is to find an elementary way to enumerate the permutations that solve the equation, only
using permutations's properties or combinatoric techniques. Early days' matter?
Comment: You may not be aware, but the custom on this site is to phrase questions as questions ("How many permutations satisfy..." or "How can we count the number of permutations that..."). Many users find it impolite to ask questions in the imperative mood ("Find the number of..."). Moreover, it gives the impression that the problem here has merely been transcribed from somewhere else.
Comment: Whoever voted to close this question because "it does not appear to be about math" should be ashamed of themselves.
Comment: Could you explain how you asked this question without a computer? :P  (Seriously, though--we like to see questions where the questioner has documented their effort in the question statement.  Please edit your post to include your own work.)
Comment: You don't need a computer to check every case.
Comment: Are all a,b... distinct?
Comment: @Awesome The question says that $a,b,\ldots h$ are a permutation of $1,2,\ldots 8$.
Comment: I have amended my answer to add some additional material. You might like to add some of the context which you sent me to your question which would help people to understand why it is interesting. You will see from my notes that a by hand direct solution looks to be possible, but rather tedious. I would be interested in any efficiencies people notice.
Comment: I have corrected an error in one of my sub-examples
Answer: For the record I would like to point out that this problem has a solution using multiset cycle indices. Suppose we have $q$ distinct positive integer values $\{v_k\}_{k=1}^q$ and a set of multiplicities $\{b_k\}_{k=1}^q$ and we want to know how many permutations $\pi$ solve the equation
$$\sum_{k=1}^q v_{\pi(k)} b_k = n$$
then the answer is given by the coefficient of a subsituted multiset cycle index
$$[z^n] \mathfrak{M}_{b_1, b_2, \ldots b_k} \left(\sum_{k=1}^q z^{v_k}\right).$$
In your particular case you want the value
$$[z^{160}] \mathfrak{M}_{1,2,3,\ldots 8}(z+z^2+z^3+\cdots+z^8).$$
These cycle indices can be calculated at a lower cost complexity (considerably lower) than iterating over all $q!$ permutations. Learn more at this link introducing multiset cycle indices.
Addendum Thu May  1 21:24:10 CEST 2014. I am adding material to this question on request (personal communication).
A conjecture (I). The sequence of the number of terms in the substituted cycle index for the problem where the multiplicities are $1,2,\ldots q$ before coefficient extraction is
$$1, 2, 4, 11, 21, 36, 57, 85, 121,\ldots$$
which is OEIS A126972
and has closed form $$1+{q+1\choose 3}$$
This is extremely good news since the count is polynomial in $q$ (cubic) as opposed to $q!.$ Actually thinking about it we see that this formula represents the fact that
$$\sum_{k=1}^q k^2 - \sum_{k=1}^q k (q+1-k) = {q+1\choose 3}.$$
A conjecture (II). On the other hand the number of terms in the cycle index for the operator $\mathfrak{M}_{1,2,\ldots, q}$ gives the sequence
$$1, 2, 5, 13, 36,\ldots$$
which does not have enough terms to be identified (there is a challenge for the reader!). The number of terms in the cycle index being bound by the partition function we can nonetheless affirm that its growth is asymptotically strictly less than $q!.$ (Remark, added later: this number does not require the actual cycle index coefficients to be calculated, but only a count of partition shapes derivable from $[1,2,3,\ldots,q]$, which is easy, consult the OEIS hit below.)
Example. We do the case $q=4$ in order to make it easier to understand what is going on. The cycle index of the multiset operator $\mathfrak{M}_{1,2,3,4}$ is given by
$$a_{{1}}a_{{2}}a_{{3}}a_{{4}}-a_{{1}}a_{{2}}a_{{7}}-a_{{1}}a_{{3}}a_{{6}}-a_
{{1}}a_{{4}}a_{{5}}-a_{{2}}a_{{3}}a_{{5}}-a_{{2}}{a_{{4}}}^{2}-{a_{{3}}}^{2
}a_{{4}}+2\,a_{{1}}a_{{9}}\\+2\,a_{{2}}a_{{8}}+3\,a_{{3}}a_{{7}}+3\,a_{{4}}a_
{{6}}+{a_{{5}}}^{2}-6\,a_{{10}}.$$
Substituting $z+z^2+z^3+z^4$ into this cycle index we obtain
$$ \left( {z}^{4}+{z}^{3}+{z}^{2}+z \right)  \left( {z}^{8}+{z}^{6}+{z}^{4}+{
z}^{2} \right)  \left( {z}^{12}+{z}^{9}+{z}^{6}+{z}^{3} \right)  \left( {z}
^{16}+{z}^{12}+{z}^{8}+{z}^{4} \right) \\- \left( {z}^{4}+{z}^{3}+{z}^{2}+z
 \right)  \left( {z}^{8}+{z}^{6}+{z}^{4}+{z}^{2} \right)  \left( {z}^{28}+{
z}^{21}+{z}^{14}+{z}^{7} \right) \\- \left( {z}^{4}+{z}^{3}+{z}^{2}+z
 \right)  \left( {z}^{12}+{z}^{9}+{z}^{6}+{z}^{3} \right)  \left( {z}^{24}+
{z}^{18}+{z}^{12}+{z}^{6} \right) \\- \left( {z}^{4}+{z}^{3}+{z}^{2}+z
 \right)  \left( {z}^{16}+{z}^{12}+{z}^{8}+{z}^{4} \right)  \left( {z}^{20}
+{z}^{15}+{z}^{10}+{z}^{5} \right) \\- \left( {z}^{8}+{z}^{6}+{z}^{4}+{z}^{2}
 \right)  \left( {z}^{12}+{z}^{9}+{z}^{6}+{z}^{3} \right)  \left( {z}^{20}+
{z}^{15}+{z}^{10}+{z}^{5} \right) \\- \left( {z}^{8}+{z}^{6}+{z}^{4}+{z}^{2}
 \right)  \left( {z}^{16}+{z}^{12}+{z}^{8}+{z}^{4} \right) ^{2}\\- \left( {z}
^{12}+{z}^{9}+{z}^{6}+{z}^{3} \right) ^{2} \left( {z}^{16}+{z}^{12}+{z}^{8}
+{z}^{4} \right) \\+2\, \left( {z}^{4}+{z}^{3}+{z}^{2}+z \right)  \left( {z}^
{36}+{z}^{27}+{z}^{18}+{z}^{9} \right) \\+2\, \left( {z}^{8}+{z}^{6}+{z}^{4}+
{z}^{2} \right)  \left( {z}^{32}+{z}^{24}+{z}^{16}+{z}^{8} \right) \\+3\,
 \left( {z}^{12}+{z}^{9}+{z}^{6}+{z}^{3} \right)  \left( {z}^{28}+{z}^{21}+
{z}^{14}+{z}^{7} \right)\\ +3\, \left( {z}^{16}+{z}^{12}+{z}^{8}+{z}^{4}
 \right)  \left( {z}^{24}+{z}^{18}+{z}^{12}+{z}^{6} \right) \\+ \left( {z}^{
20}+{z}^{15}+{z}^{10}+{z}^{5} \right) ^{2}\\
-6\left(z^{40}+z^{30}+z^{20}+z^{10}\right).$$
Expanding this cycle index we obtain the generating function
$${z}^{30}+3\,{z}^{29}+{z}^{28}+4\,{z}^{27}+2\,{z}^{26}+2\,{z}^{25}+2\,{z}^{
24}+4\,{z}^{23}+{z}^{22}+3\,{z}^{21}+{z}^{20}$$
where $dz^p$ represents the fact that the value $p$ was obtained as a solution $d$ times.
Addendum, part II. Re-writing some software of mine I was able to compute the multiset cycle index for the operator $\mathfrak{M}_{1,2,3,4,5,6}$ and get another value for the sequence of terms in the cycle index, obtaining
$$ 1, 2, 5, 13, 36, 109,\ldots$$
This gave a perfect match with OEIS A066723. The OEIS entry just repeats the definition from our problem above and does not give asymptotics which we leave to the reader (looks like an interesting challenge). This multiset cycle index gives the generating function for $q=6$ which is
$${z}^{91}+5\,{z}^{90}+6\,{z}^{89}+9\,{z}^{88}+16\,{z}^{87}+12\,{z}^{86}+14\,{z}^
{85}+24\,{z}^{84}+20\,{z}^{83}+21\,{z}^{82}\\+23\,{z}^{81}+28\,{z}^{80}+24\,{z}^{
79}+34\,{z}^{78}+20\,{z}^{77}+32\,{z}^{76}+42\,{z}^{75}+29\,{z}^{74}+29\,{z}^{
73}\\+42\,{z}^{72}+32\,{z}^{71}+20\,{z}^{70}+34\,{z}^{69}+24\,{z}^{68}+28\,{z}^{
67}+23\,{z}^{66}+21\,{z}^{65}\\+20\,{z}^{64}+24\,{z}^{63}+14\,{z}^{62}+12\,{z}^{
61}+16\,{z}^{60}+9\,{z}^{59}+6\,{z}^{58}+5\,{z}^{57}+{z}^{56}.$$
Answer: Here is another way of going about the task.
The maximum value of the sum is $$1^2+2^2+3^2+4^2+5^2+6^2+7^2+8^2=204$$ and the target value is $44$ less than this.
A transposition switching $a$ and $b$ reduces the total by $$a^2+b^2-ab-ba=\frac 12\left((a-b)^2+(b-a)^2\right)[=(a-b)^2]$$
Note we want the first form here and not the simplest, as will appear later.
The $3$-cycle $(abc)$ reduces the total by $$a^2+b^2+c^2-ab-bc-ca=\frac 12\left((a-b)^2+(b-c)^2+(c-a)^2\right)$$ and $(abcd)$ by $$\frac 12\left((a-b)^2+(b-c)^2+(c-d)^2+(d-a)^2\right)$$and now the pattern is clear.
So we are first looking for decompositions of $2\cdot 44=88$ into sums of up to eight squares, the greatest of which is $\leq49$, and then converting the sum of squares into a cycle decomposition, if possible.
So, for example $88=5\cdot 4^2+2\cdot 2^2$, giving us $7$ squares, which in theory allows a decomposition as a $2$-cycle and a $5$-cycle - but we can't have a $5$-cycle where all the elements have the same parity. The other alternatives are $3,4$ and $2,2,3$. The $3$-cycle is constrained to have differences $2,2,4$ and is all odd or all even - i.e. $(1,3,5), (2,4,6), (3,5,7), (4,6,8)$. The remaining part has to provide four differences equal to $4$ and this is only possible with two transpositions $(1,5)(3,7)$ if the $3$-cycle contains even numbers and $(2,6)(4,8)$ otherwise. [correction] Note that the inverses of the four three cycles also work. So this decomposition gives us eight possible permutations.
It is now a question of being systematic, as there are only a few possibilities.

Looking at a simpler example $$a+2b+3c+4d=27$$ the greatest possible sum is $1+4+9+16=30$ the difference is $3$ so we are looking at up to four squares which sum to $2\cdot 3=6$. The only possibility is $1+1+4$ representing differences of $1,1,2$.
We now need to divide this into two subsets with the same sum - $1+1=2$. This is because we start on one number, have some ups and downs and end back where we started. So the ups have to equal the downs. Three squares means a $3$-cycle. The $2$ is either $|3-1|$ or $|4-2|$. So we have the cycles $(312), (132), (423), (243)$. It depends which way you are used to reading cycles, but the solutions are then $(2,3,1,4), (3,1,2,4), (1,3,4,2), (1,4,2,3)$
__
Note also that the number of cases for the original problem is intermediate for doing this by hand. The number of odd squares is a multiple of four. I get (to illustrate some of the complexities - care is required):
$7,6,1,1,1$ with $7+1=6+1+1$ representing a $5$-cycle and $7=6+1; 1=1$ representing a $3$-cycle and a transposition. The first of these requires differences of $6$ and $7$ so $8\to 1\to 7$ or $1\to 8\to 2$ or the reverse, and the differences of $1$ don't fit in to make a cycle, so you need the transposition e.g. $(34)$
$7,5,3,2,1$ with $7+2=5+3+1$ ($5$-cycle e.g. $(18354)$ - others are possible)
$7,5,3,1,1,1,1,1$ with $7+3=5+1+1+1+1+1$: $7+1+1+1=5+3+1+1$: $7+1+1=5+3+1;1=1$: $7+1=5+3;1=1;1=1$ (this is a four-cycle and two transpositions of adjacent numbers e.g. $(1856)(??)(??)$ but nothing goes with $7$ or $(1834)(??)(??)$ and nothing goes with $2$ so no solution)
$7,5,2,2,2,1,1$ with $7+2+1=5+2+2+1$: $7+2=5+2+2; 1=1$: $7+1=5+2+1; 2=2$: $7=5+2;2+1=2+1$: $7=5+2; 2=2; 1=1$
Taking $7=5+2; 2+1=2+1$ we have a 3-cycle and a 4-cycle. $7=|8-1|$ is the only possibility, so we have $(186), (183), (813), (816)$ and taking the first of these we need to realise the $1+2=1+2$ note that $7$ can't fit into this pattern , so $2$ has to go somewhere (+1 or +2) and so we get $(2354)$ or $(2453)$, and similarly for the others.
$7,4,4,2,1,1,1$ gives $7+2+1=4+4+1+1$ (from which $2=1+1$ or $1=1$ can be extracted) and $7+1+1+1=4+4+2$ e.g. for this last $(1867345)$ or $(1845673)$ (not exhaustive)
My full list is (copying screwed the spacing) - I'm adding [n] to show the number I've found of each type (corrections welcome):
$$
\begin{array}{ccccccccl}
7 & 6 & 1 & 1 & 1 &   &   &   & \text{[16]} \\
7 & 5 & 3 & 2 & 1 &   &   &   & \text{[10]} \\
7 & 5 & 3 & 1 & 1 & 1 & 1 & 1 & \text{[4]} \\[2ex]
7 & 5 & 2 & 2 & 2 & 1 & 1 &   & \text{[28]} \\[2ex]
7 & 4 & 4 & 2 & 1 & 1 & 1 &   & \text{[32]} \\
7 & 4 & 3 & 3 & 2 & 1 &   &   &  \\
7 & 4 & 3 & 2 & 2 & 2 & 1 & 1 &  \\[2ex]
7 & 3 & 3 & 3 & 3 & 1 & 1 & 1 &  \\[2ex]
7 & 3 & 3 & 3 & 2 & 2 & 2 &   &  \\
6 & 6 & 4 &   &   &   &   &   & \text{(impossible)} \\
6 & 6 & 3 & 2 & 1 & 1 & 1 &   &  \\
6 & 6 & 2 & 2 & 2 & 2 &   &   & \text{[8]} \\
6 & 5 & 5 & 1 & 1 &   &   &   & \text{(impossible)} \\
6 & 5 & 4 & 3 & 1 & 1 &   &   &  \\
6 & 5 & 4 & 2 & 2 & 1 & 1 & 1 &  \\[2ex]
6 & 5 & 3 & 3 & 3 &   &   &   & \text{(clearly impossible mod $3$)} \\
6 & 5 & 3 & 3 & 2 & 2 & 1 &   &  \\
6 & 4 & 4 & 4 & 2 &   &   &   & \text{[16]} \\
6 & 4 & 4 & 4 & 1 & 1 & 1 & 1 &  \\[2ex]
6 & 4 & 4 & 3 & 3 & 1 & 1 &   &  \\
6 & 4 & 4 & 2 & 2 & 2 & 2 & 2 &  \\[2ex]
6 & 4 & 3 & 3 & 3 & 3 &   &   & \text{(impossible)} \\
6 & 4 & 3 & 3 & 3 & 2 & 2 & 1 &  \\[2ex]
5 & 5 & 5 & 3 & 2 &   &   &   & \text{[20]} \\
5 & 5 & 5 & 3 & 1 & 1 & 1 & 1 &  \\[2ex]
5 & 5 & 4 & 4 & 2 & 1 & 1 &   &  \\
5 & 5 & 4 & 3 & 3 & 2 &   &   &  \\[2ex]
5 & 5 & 4 & 3 & 2 & 2 & 2 & 1 &  \\[2ex]
5 & 5 & 3 & 3 & 3 & 3 & 1 & 1 &  \\[2ex]
5 & 4 & 4 & 4 & 3 & 2 & 1 & 1 &  \\[2ex]
5 & 4 & 4 & 3 & 3 & 3 & 2 &   &  \\
5 & 3 & 3 & 3 & 3 & 3 & 3 & 3 &  \\[2ex]
4 & 4 & 4 & 4 & 4 & 2 & 2 &   & \text{[8]} \\[2ex]
\end{array}
$$
Comment: I have tried formatting your table.  Please give it a quick check for obvious errors.
Comment: @MJD Thanks. If I spot anything I'll correct it.
Answer: What is the coefficient of $x^{160}$ in $(\sum_{i=1}^{8}x^i)^{36}$?
Note that $36=\sum_{i=1}^{8} i$
Further hints: hover to see.

 Use formula for $GP$ and taylor expansion of denominator.
Comment: Are you sure this doesn't overcount? AFAICT this might include terms corresponding to such solutions where one of the variables is zero, or $>8$, or some are equal?

Number of solutions of equation


8 less than triple a number is equal to -5 (I'm trying to find the unknown number)

Question: It's a hard question... for my thinking! I've tried many solutions but haven't figured it out.
(Let $M$ be the unknown number)
I've tried:
$M^3-8=-5$
Then
$M^3-8+8=5+8$
Then I think the answer is
$M^3=13$
Comment: Triple a number is not the same as the number squared. Instead your equation should be $3M-8=-5$.
Comment: @ René B. Christensen: I think "cubed" is the word you are looking for.
Comment: @abstract Yes, of course. I might have written that comment a bit too  fast.
Answer: Hint: A number is tripled if it is multiplied by $3$, not put to the third power. For example, tripling the number $5$ gives $15$.


Android Studio gradle compilation error

Question: I wonder if you can help, I'm not a very exerienced developer but trying my had at Android Development. I'm using Android Studio which uses gradle. I'm getting the following compilation error:

Gradle: A problem occurred configuring project ':HelloWorld'.

Failed to notify project evaluation listener.
    Configuration with name 'default' not found.

My folder structure is:
HelloWorldProject
.HelloWorld
.libraries
..facebook
..build.gradle
.src
..main
..build.gradle
...java
....com.helloworld
.....firstPage
.gradle
..wrapper
...gradle-wrapper.jar
...gradle-wrapper.properties
.build.gradle
.settings.gradle
.gradle.properties

my ./build.gradle in the root is empty
my ./setting.gradle file contains:
include ':libraries:facebook', ':HelloWorld'

my ./HelloWorld/build.gradle is:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
    dependencies {
        compile project(':libraries:facebook')
    }
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 16
    }
}

my ./HelloWorld/src/build.gradle contains:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
    dependencies {
        compile project(':libraries:facebook')
    }
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 16
    }
}

Comment: I've been getting crazy in the last days with gradle related problems. I think that, if your project is not so big, you shall create a new project from the scratch, add your components throug the File -> new component menu, and have a running project in a few minutes. You will not understand wich is the problem, but in this early days of gradle an of android studio there are so many bugs and changes that is not worth to spend much time on such problems.
Answer: The problem here, in most cases, is a library doesn't have a build.gradle file.  In this case, it would be the facebook library.

Android Studio gradle compilation error


String bending pain doesn't go away

Question: I have been playing the guitar since 2006, so I'm not new to the activity, and I have caluses.
I started playing Flamenco on a nylon strings and in 2013 moved to play Surf on a stratocaster.
A couple of years ago, I began playing Blues and Rock (some Eric Clapton and mainly Mark Knopfler stuff), which required a technique I never used before - string bending. I have been doing it for some years now, but the pain at my fingertips still isn't going away (I'm using the right technique - bending with all 3 fingers, use rotating motion, etc, etc).
Currently I'm playting on a Les Paul, a short scaled guitar, with 9 gauge strings (the lightest set available in my area), with a low action and wrap arround tail (some claim it makes the strings more slinky. . . ) - this should be the easiest setup for string bending, but not in my case.
I watched many tutorials how to bend strigns the right way. It looks to be a casual and effortless act, but it doesn't come effortless to me. In fact, after about a dozen of bends, I can't play any longer, for my fingertips heart much. I feel as if my flash is moving away from the bone, and the sore feeling keeps for hours after - I feel like I'm playing a cheese grater rathar than a guitar
Again, I'm not a new player to experience such pain, and it hasn't improved with the years. I wonder if the issues is with the way my fingers are.
Have anyone encountered such a thing before? I found none in the common guitar forums.
I do a bit of dish washing on a daily bases as well as using hand moisturizer. Obviously not going to stop doing both.
(By the way, when playing Surf, which doesn't require bending, I used 11 and 12 gauge strings on a Stratocastr, without any issues)
Comment: Use a whammy bar?  I realize it doesn't provide the same expressiveness as bending on the neck, but it does have the virtue of saving your hands.
Answer: No idea which videos you've seen, but if you're using one finger for a bend, it's going to be hard work. Whenever possible, use as many as you can - obviously those behind the fretted note are the extras!
Consider whether you're going to bend the string towards your head, or towards the floor. Both work, but on top string, it's more common to bend upwards.
You should be using the rotation movement of your whole hand to bend, not fingers. fret a note, and rotate your hand either way, depending on up or down movement. The rotation comes from the elbow! Your hand cannot rotate from your wrist.
Another consideration - with a good action and thin strings would be to drop the tuning. It's what used to happen back in the day when there was only one set of strings available - heavy(ish).
Go down a semitone or a tone, or try to get some thinner strings - I use .008, .010, .012 for my top three, but my guitars aren't as short scale as LPs. By going down exact semitones, you'll still be able to play along to backing tracks, albeit in a different key.
Comment: @Riddle-Master Laborious, but is there any chance you could post a short gif or video of your current technique? Unfortunately, there are just too many variables in play to know exactly what's going wrong without seeing it. It could have to do with your sitting/standing posture, strap height, neck size, scale length....
Comment: What's lowered tuning to do with heavy metal?! It's very difficult to help you without knowing what you actually do. No info. in the question! Your best bet, if possible is to see a teacher for at least one lesson.
Comment: Hendrix and countless others were doing just that back in the '60s. Many blues players are doing the same now.
Comment: Yes! The bend starts at the elbow. Another thing the OP might consider is putting their thumb above the neck to get more leverage.
Comment: @Max - or consider *not* putting the thumb on at all...
Comment: Please leave a comment with your downvote - we need to know what your problem is!
Comment: Technique wise I do all you wrote above. I bend with 3 figners, using rotating motion etc etc. . . . I watched tutorial by Justin Guitar, Paul Gilbert and many other people who knows what they are talking about. But it doesn't work for me. Also, as I wrote above, 9's are the smallest set I can get. I don't play heavy metal to lower the tuning.
Comment: I wrote in the question that I play blues and rock. Can't see it being played with low tuning.
Comment: @Riddle-Master SRV played 1 semitone low. His guitar was tuned in Eb
Comment: @Riddle-Master, lots of blues players drop tuning down.  It's not at all a "metal" thing.  But I would like to "see" your technique too.  I bend with single fingers on 11s and I don't have this problem.  Of course it could be experience too.  Don't know.
Answer: Too little information to really answer.  Several things can cause finger tip pain in an experienced player.  As someone else said, having them in water for a long time then playing.  A couple other issues to consider are...

Does the pain or tenderness (I am assuming this is what you mean and not for example joint pain) ever get better?  Do you have some periods of time where it seems fine then it flares up?  I ask because this could correlate to periods of over practicing, learning a new song, etc.
Are you bending more than a whole step?  The greater the interval the more stress you will put on the finger.  It should adjust but if you stop for a while and start again you won't be used to it.
Is it the finger tip or under the nail?  I used to get this a lot when I was younger.  Things would be going fine then for some reason (usually right after clipping my left hand nails) the skin would tear from under the nail and that would burn for quite a while.
Could it be the brand of string?  9s are not that heavy.  I bend up to a major 3rd, sometimes a 4th on 11s and I DON'T use 3 or 4 fingers.  I do not like that technique as it takes freedom away from playing harmonies while bending.  For many years (decades) I used GHS boomers because it just seemed like what everyone had and there didn't seem to be a lot of variety.  More recently a tech who sets up my guitars recommended another brand, even said that GHS was not great for bending.  I don't recall if he put on D'Adario, or Ernie Ball.  Whatever it was it just felt loose and had both more "spring" to it and was easier to bend.  It could be the material too.
High action might contribute to this.  Make sure you have your guitar well adjusted.  If the action is too high that will affect both the feel of just playing notes and bending.
Does the amount of pain or tenderness depend on where you are playing.  It might be easier to play at the 12th fret than the 3rd or 5th.

Ironically, even though people say don't play right after you bath, I prefer to play when my hands are still soft right out of the shower.  Perhaps this helps keep the callus developing.  I find that my hand goes through phases and no surprise these depend on what I'm practicing and playing.  If I keep up with the Zep, and Blues in general I don't suffer the problem you are having.  But if I move on to other styles that don't use bending a lot and neglect to play a little blues every day I will notice when I do it again that I experience a little tenderness as part of the adjustment.  These are perishable skills and your hand will acclimate to whatever input you give it.  If you take a break for too long I'd expect that you will feel pain again as you get used to it.  For mr this does not last long (and rarely happens).
Comment: I wondered when callouses were going to get mentioned! Surprised no-one's said OP needs to develop them...
Comment: Tim, I wonder if you actually read my question. I have been playing guitar since 2006, and have caluses for almost a decade and a half to the level that I have no feeling at all in my left hand fingertips, even when I haven't played for long periods.
Comment: ggcg, 1. My pain lasts for about 4 to 6 hours 2. No, whole step at most 3. Fingertip. I don't touch that part of the skin anyhow. 4. I use D'addario. The usual type, no coating 5. The action is low. I had a luthier done the set up 6. I usually bend the 7th and 8th fret.
Comment: @Riddle-Masterm I really don't know what to say.  What about the bridge?  Did you say it was a fender strat?  Sometimes spring tension in the bridge can make it feel harder to bend.  I play a Gibson 335 and have never gone lower than 11s on it, used to play 13 flat wounds.  Perhaps you are pinching a nerve, and the callus can make that worse if it develops incorrectly.
Comment: No, I play a les paul with 9s. I used to have a strat with 11 when I played Surf. I switched to gibson to have a shorter scale, but that didn't help. I guess the problem is in me then.
Comment: @Riddle-Master - only just picked up comment - you didn't use '@'. You have no feeling in your figertips, yet the pain lasts several hours. Sorry, I don't understand how both conditions can exist. Callouses - I really don't believe they need to exist. I've played for 60+ yrs, and not had them for 55+ - originals due to naff guitar. Play guitars with .008s, and basses with up to .130s. Maybe those callouses are the cause of the problem. A shorter scale guitar means the strings will have less tension, so it could have helped. What is the problem with trying lighter strings, as in my suggestion?
Comment: @Riddle-Master - a teacher and a doctor would both be on my list. Have you considered either? Gloves for dishwashing helps. And, yes, I read each question before answering, and that did include yours. We are here to help, please be aware of that. It could be as simple as you are pressing too hard - we all do that - some more than others.
Comment: @Tim - I don't feel on the surface, when I touch objects, but I feel pain deeper, at the flash of the fingertip rathar than the skin.
Comment: I'm guessing a pinched nerve
Answer: My personal experience is that when my hands stay in the water for some time, the fingertips are definitely affected when it comes to playing.
And so I would definitely try a couple of things. For at least one week:

Always wear rubber gloves when washing stuff, avoid soaking your hands as much as possible.
Use moisturizer on the hands, but not on the fingertips, try to keep the last inch of your fingers completely dry.

If you can do this for at least a week, it's quite possible that you may start to notice significant changes. The bigger the changes you'll notice, the more you can draw the conclusion that the root of the problem is too much contact with water, rather than anything else.
Answer: Try distributing the force of your bend onto the strings with all 3 fingers. If you just use the ring finger to push the strings up and the index and middle are left hanging below that might cause an issue.
Answer: I found my problem. It consisted of 2 things:

The Guitar in question had its frets leveled but not crowned (for they became too low for that - old guitar). While it never bothered my playing, apparently it affects bending, for I compared it with the exact same guitar but newer which belongs to a friend of mine. He also said that string bending is painful on my guitar.

Unlike what is told in all the string bending tutorials - put 2 to 3 fingers in each fret and bend together, I starte bending only with 2 fingers, but always on the same fret. Even on the 10th fret and beyong. To me, that is a way more easy bending, and the strings doesn't move much under my finger as it did when deviding fingers to each fret.
Comment: so, essentially, the guitar was your problem?
Answer: think of your fingers as you do about any muscle; you need to properly stretch it before and after you use them, bendings  are one of the most demanding movements fingers do when playing guitar.
You should alse be properly warmed up.
on the other hand, you can use finger combinations to acomplish bendings; like using two fingers to lower the stress put into individual member.
Comment: What hurts are my fingertips - it has nothing to do with stretching or muscle strength.
Comment: Yeah, it sounds like bruising rather than muscle pain.
Comment: Well, there are no muscles in the fingers other than your thumb, all the finger movements are actuated by tendons from muscles located in your forearm - so if there's pain caused by tired, overexerted or rapidly stretched muscles, then it won't be felt in fingers (as the OP describes) but in the forearm.
Comment: Fingers don't have muscles!

String bending pain doesn't go away