Link button's Click Function is not being call

Question: I am generating dynamic link buttons in c#.At click of any of them,a other function will be call that will show which link button was clicked.But it is not being call at click of any link button.
This is how i am generating it.
 Int32 i; //create a integer variable
 for (i = 1; i <= 10; i++) // will generate 10 LinkButton
 {
LinkButton lb = new LinkButton(); //create instance of LinkButton
lb.Text = Convert.ToString(i) + ""; //LinkButton Text
lb.ID = Convert.ToString(i); // LinkButton ID's
lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
lb.CommandName = Convert.ToString(i); // LinkButton CommanName
lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
//type lb.Command += and press double time Tab Key it will generat the lb_Command() code
 PlaceHolder1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
 }

This is function code.
void  lb_Command(object sender, CommandEventArgs e)
{
Label1.Text = e.CommandName; // will display the which Linkbutton clicked
Label1.Text = "aaaa";
//  Response.Redirect("LnkBtn.aspx?val=" + Label1.Text); // you can also use as QueryString to send values to another page
}

please provide help.
Thanks.
Comment: It's not mentioned anywhere below but make sure you are creating recreating those buttons during the OnInit() phase of every post back ofr your events won't be wired up early enough in the page lifecycle to work anyway.
Comment: i am generating it inside page_load's if (!IsPostBack) event.
Moreover when i click on link button,all the links buttons gets disappears why?
Comment: @user1627138 You're not creating the buttons early enough in the page lifecycle.  They aren't being saved to the view state, so when you post back the server doesn't remember that it had any buttons.  As Eoin has said, you need to add the controls in the `OnInit` event, and you need to do it on every single page load, not just on `!IsPostBack`.
Comment: @OP. I've posted some info in an answer below.
Answer: You are using the wrong event :
ClientClick is just a client side event triggered in javascript.
What you want is the Click Event
[...]
lb.Click += new CommandEventHandler(lb_Command); //Create Handler for it.

If you still aren't catching the event, then chances are you are declaring your LinkButton dynamically at the wrong time in the Page Lifecycle (as mentionned by Eoin Campbell in his comments and in his answer).
He links to an article that's really good on the subject, you should read it to understand why you aren't catching the event.
Judging by your comments on your question and on different answers, you are declaring the button in your Page_Load function. That will not work because Page_Load occurs too late in the page lifecycle.
From what I understand, right now you have :
void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
          Int32 i; //create a integer variable
          for (i = 1; i <= 10; i++) // will generate 10 LinkButton
          {
              LinkButton lb = new LinkButton(); //create instance of LinkButton
              lb.Text = Convert.ToString(i) + ""; //LinkButton Text
              lb.ID = Convert.ToString(i); // LinkButton ID's
              lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
              lb.CommandName = Convert.ToString(i); // LinkButton CommanName
              lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
              PlaceHolder1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
        }
    }
}

You need to get rid of that. Instead, use :
void Page_Init(object sender, EventArgs e)
{
    Int32 i; //create a integer variable
    for (i = 1; i <= 10; i++) // will generate 10 LinkButton
    {
         LinkButton lb = new LinkButton(); //create instance of LinkButton
         lb.Text = Convert.ToString(i) + ""; //LinkButton Text
         lb.ID = Convert.ToString(i); // LinkButton ID's
         lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
         lb.CommandName = Convert.ToString(i); // LinkButton CommanName
         lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
         PlaceHolder1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
    }
}

The article linked above will explain why that is. It's a hard concept to grasp but a very important one.
Comment: The OnClientClick is only part of the problem. Even with OnClick as you stated, his code will only work if he's generating those buttons early enough in the page life cycle.
Comment: well he wasn't getting compile errors in the first place. but he'll continue to get "odd" run time behaviour where clicking on his buttons doesn't "appear" to do anything. And given that he was making the OnClick vs. OnClientClick mistake and misunderstanding the page lifecycle is pretty common when working with dynamic controls... yeah... i think it's worth mentioning.
Comment: using onclick gives the error:-
Error 2 'System.Web.UI.WebControls.LinkButton.OnClick(System.EventArgs)' is inaccessible due to its protection level
Comment: The event handler doesn't need to be `protected`.  It can be `private` and it will work just fine.  In fact, it really *should* be private.  The accessibility error is because the name of the event he needs to attach to is `Click`.  That's the public event.  `OnClick` is a protected *method* (not event) that triggers the `Click` event.  Since this class can't access protected members of `LinkButton` he's getting an error.
Comment: @Hugo turns out page Life cycle is an issue for OP. See my response below.
Comment: onclick is not a valid method for linkbuttons.it real method is OnClientClick.
i made a protection level to protected but use OnClientClick but it still didn't give any effect.
:(
Comment: @user1627138 The event handler that you're attacking does not need to be protected, it can and should be private.  The *event* (not method) that you need to attach the event handler to is neither `OnClick` (which isn't an event at all) nor is it `OnClientClick`; you need to attach it to `Click`.
Comment: I just updated my answer with the solution to both initial problems. I think you should be fine with that.
Answer: You are mixing client and server side code.  OnClientClick is method for attaching client side code.  lb_Command runs on the server side.
Use Click instead.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
versus
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click.aspx
Comment: lb.command still didn't work.it didn't get a hit when i click any link button
Answer: Ok. two things. as others have pointed out you should be using the LinkButton Command or Click handlers.
But your second problem is that you are running into Page Life Cycle issues by attempting to only generate your controls

on if(!Postback)
in the Page_Load.

Read this: It's a very good article on the subject that dates all the way back to .net 1
https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
In a nutshell, you should be creating your controls every single time (not just on the initial post) and you need to wire up your event handler (the += part) early enough in the page lifecycle such that the events are wired, by the time the PageLifeCycle attempts to trigger them.
Override the page's OnInit method and move your code there, without the if(!Postback) check
Comment: The event isn't `OnClick`, it's `Click`.
Answer: Instead of the below code
lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.

use the following
lb.Command+= new CommandEventHandler(lb_Command); //Create Handler for it.

Here is the full code. It running at my end.
    protected void Page_Load(object sender, EventArgs e)
    {
        Int32 i; //create a integer variable
        for (i = 1; i <= 10; i++) // will generate 10 LinkButton
        {
            LinkButton lb = new LinkButton(); //create instance of LinkButton
            lb.Text = Convert.ToString(i) + " "; //LinkButton Text
            lb.ID = Convert.ToString(i); // LinkButton ID's
            lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
            lb.CommandName = Convert.ToString(i); // LinkButton CommanName
            //lb.Click += lb_Click; //Create Handler for it.
            lb.Command += lb_Command;
            //type lb.Command += and press double time Tab Key it will generat the lb_Command() code
            form1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
        }

    }

    void lb_Command(object sender, CommandEventArgs e)
    {
        Label1.Text = e.CommandName; // will display the which Linkbutton clicked
    }

Thanks.
Comment: lb_command function is not getting still a hit after clicking on the any link button,even all the link button get invisible when i click on any button.
Strange Behaviour.
Comment: @user1627138 That's because you're creating and adding the LinkButtons too late in the page lifecycle.
Comment: i am creating it inside page load.
So whats the solution?
Answer: If link button is inheriting from Button class then you should attach to the OnClick event. ?
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.buttonbase.click(v=vs.100)
or
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onclick.aspx
Comment: This isn't windows forms, it's ASP.NET


How are the values of residuals (white noise) calculated in ARMA model?

Question: I am trying to implement ARMA model in Java. I have trouble with calculating residuals (white noise) in Moving average part of the model. From the answer on this question (Fitted values of ARMA model) I see that they can be calculated by certain expression:  $e_t=X_t-Ar*X_{t-1}-Ma*e_{t-1}$, where $Ar$ and $Ma$ are parameters which you set in program $R$.
My question is how can I calculate or estimate residuals without having parameters $Ar$ and $Ma$? Because the goal of my application is actually to calculate these parameters and use the model for predicting.
Generally I understand residuals as the differences between real and predicted (estimated) values. So how can I estimate residuals if I don't have constructed model yet?
p.s.
I looked up to some books and theory, but didn't find any example or exact explanation of what are the values of these residuals.
Thank you in advance.
Answer: You need to identify the appropriate model using methods that are robust to outliers/step shifts  (i.e. not simple AIC computation premising no outlers/step shifts) and  then estimate the parameters which will yield the errors you are looking for..
Answer: For your ARMA(1,1) example, you need to assume you know the first $e_{t-1} $(you can fix it to zero). Then you run the model (starting from $X_{2}$ if you first data point is $X_{1}$) with different AR and MA coefficients , you'll obtain several errors series. For each error serie you compute the associated likelihood function. And finally the parameters (AR and MA) which gives you the highest Likelihood are the estimated parameters.  Obviously you need to assume a distribution for the errors.
So in short you obtain the AR and MA parameters by testing different values trough a maximization algorithm using the MLE Method.


End process error code -1 if acess to string field of structure

Question: #include <cstdlib>
#include <string>
#include <iostream>
#define S 10

using namespace std;
struct List
{
    string name;
    bool male;
    int year;
    string addr;
    string diag;
    bool hosp;
};

main()
{
    struct List *l=NULL;
    int n=0;
    for(int i=0;i<10000;i++)
    {
        if(!(n%S))
        {
            l=(List*)realloc(l,(n/S+1)*S*sizeof(struct List));
            cout<<"realloc ok\n";
        };
        l[n].male=rand()%2;
        l[n].year=1900+rand()%100;
        l[n].hosp=rand()%2;
        //!l[n].name="abc";
        n++;
        cout<<l[rand()%n].male<<" "<<l[rand()%n].year<<" "<<l[rand()%n].hosp<<endl;
    }
}

If l[n].name="abc" remarked then program works fine.
If i try put string value to this field the programm compiled without warnings nay, but crash with error code -1 after first realloc.
Any way to solve it?
Comment: Step through the code in your debugger to see what's going on.
Answer: Since your structure is non-trivial - it contains members of class type, std::string, which need to be initialised by calling their constructors - you can't simply allocate raw memory and pretend that contains a valid object.
The simplest solution is to use a type-aware dynamic array
std::vector<List> l;

which can be resized, perserving its contents, with
l.resize((n/S+1)*S);

Answer: Tip! Using "new" operator to allocate this structure will automatically create string object for each field.
List *l=new struct List[S];

It fix this issue, l[n].name="abc" will works, but it not implements reallocation functional.


php create two separate sentences from one sentence

Question: I want to separate two sentences from one sentence in php.
For ex. Mr. ABC is good in math and science.
Will be

Mr. ABC is good in math
Mr. ABC is good in science

Thanks in advance
EDIT:
May be regular expression. I am trying convert paragraph to speret statement. Then single statement convert two sub statement. using following regular expression.
<code>$str = "Mr. ABC is good in math and science. but he is poor in sport";
$sentences = preg_split('/(?<=[.?!;,])\s+(?=[a-z])/i', $str);
</code>
I want to calculate sentiment of text. that's why i need to split these statement. (How many percentage of positive statement is?)
Comment: What is the logic behind your separation?
Comment: Show us your tries. Why you want to do it?
Comment: May be regular expression. I am trying convert paragraph to speret statement. Then single statement convert two sub statement. using following regular expression.

$str = "Mr. ABC is good in math and science. but he is poor in sport";
$sentences = preg_split('/(?<=[.?!;,])\s+(?=[a-z])/i', $str);
Comment: @RuchishParikh I want to calculate sentiment of text. that's why i need to split these statement. (How many percentage of positive statement is?)
Answer: Your question is incomplete. However you may consider using substring.
and finally do concatenation. example, in the two sentences:
<code>$str1 = "Mr. ABC is good in math";
$str2 = "Mr. ABC is good in science";
$mainstr = substr($str1, 0, 15)." and ".substr($str2, 19, 7);
</code>
Check out that and see if it helps. Otherwise, who us what you have done first


Webscraping Symfony/Panther: Can't get HTML

Question: I want to scrape a site with the symfony panther package within a Laravel application. According to the documentation https://github.com/symfony/panther#a-polymorphic-feline I cannot use the HttpBrowser nor the HttpClient classes because they do not support JS.
Therefore I try to use the ChromClient which uses a local chrome executable and a chromedriver binary shipped with the panther package.
$client = Client::createChromeClient();
$crawler = $client->request('GET', 'http://example.com');
dd($crawler->html());

Unfortunately, I only receive the empty default chrome page as HTML:

Every approach to do something else with the $client or the $crawler-instance leads to an error "no nodes available".
Additionally, I tried the basic example from the documentation https://github.com/symfony/panther#basic-usage  --> same result.
I'm using ubuntu 18.04 Server under WSL on Windows and installed the google-chrome-stable deb-package. This seemed to work because after the installation the error "the binary was not found" does not longer occur.
I also tried to manually use the executable of the Windows host system but this only opens an empty CMD window always reopened when closing. I have to kill the process via TaskManager.
Is this because the Ubuntu server does not have any x-server available?
What can I do to receive any HTML?
Comment: Did you check this: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md#chrome-headless-doesnt-launch-on-unix ?
According to the documentation it is possible to run it in headless mode. You can see the required packages.
Comment: I have the same issue. When I look for a locally hosted website it returns the html but when I try an external webpage I get the same result. Did you find a solution?
Comment: it has nothing to do with solving this problem, but try to investigate this one https://github.com/spatie/crawler
Answer: $client = Client::createChromeClient();
$crawler = $client->request('GET', 'http://example.com');

/**
* Get all Html code of page
*/

$client->getCrawler()->html();

/**
* For example to filter field by ID = AuthenticationBlock and get text
*/

$loginUsername = $client->getCrawler()->filter('#AuthenticationBlock')->text();

Comment: I had the same problem and try to find answer, but no one share this solution. Readme file do not describe how to use Panther at all. Answer is simple when you know how it works.
Comment: The more explanation you give the better. In this case, I believe your comments should be enough, but for future I recommend to explain your solutions so that they are more easily understandable.
Comment: I was commented code, it is not enough? Please give me advise
Answer: So, I'm probably late, but I got the same problem with a pretty easy solution: Just open a simple crawler with the response content.
This one differs from the Panther DomCrawler especially in methods, but it is is safer to evaluate HTML structures.
$client = Client::createChromeClient();
$client->request('GET', 'http://example.com');

$html = $client->getInternalResponse()->getContent();
$crawler = new Symfony\Component\DomCrawler\Crawler($html);

// you can use following to get the whole HTML
$crawler->outerHtml();

// or specific parts
$crawler->filter('.some-class')->outerHtml();


Use ansible.builtin.version outside of assert

Question: I have following working tasks:
- name: Get Package infos
  ansible.builtin.package_facts:
    manager: auto

- name: Test redis-server version
  ansible.builtin.assert:
    that:
      - ansible_facts.packages['redis-server'][0].version is version('4.0', '>=')

I have wondered if I am able to combine those tasks into a single one:
- name: Get Package infos
  tags: redis
  ansible.builtin.package_facts:
    manager: auto
  failed_when: ansible_facts.packages['redis-server'][0].version is version('4.0', '<')

But if I do so I got quite long error message which ends with:
The error was: error while evaluating conditional
(ansible_facts.packages['redis-server'][0].version is version('4.0', '<')):
'dict object' has no attribute 'packages'. 'dict object' has no attribute 'packages'"}

It seems that the field packages does not exists at that moment. What may fix this approach?
Comment: It's a bad idea to combine these tasks. You will miss potential `package_facts` failures.
Comment: In addition to this, it's an overkill to run `package_facts` to get status of one package only.
Answer: A minimalistic option would be
    - command: redis-cli --version
      register: out
      failed_when: out.stdout|split|last is version(7.0, '<')

Optionally, test also rc
    - command: redis-cli --version
      register: out
      failed_when:
        out.rc != 0 or
        out.stdout|split|last is version(7.0, '<')

This task doesn't change anything. Suppress the reporting of the changed status
    - command: redis-cli --version
      register: out
      failed_when:
        out.rc != 0 or
        out.stdout|split|last is version(7.0, '<')
      changed_when: false

Notes

It's possible to use the ansible_facts.packages from the registered variable. But, the module package_facts is not practical in checking the version of redis because it is OS dependent and slow. For example,

    - package_facts:
      register: out
    - debug:
        msg: |
          {{ out.ansible_facts.packages['redis-server'] |
             map(attribute='version') }}"
          {{ out.failed }}

gives on Ubuntu
  msg: |-
    ['5:7.0.12-1']
    False

The equivalent to the above command task would be
    - package_facts:
      register: out
      failed_when:
        out.failed or
        ver is version(7.0, '<')
      vars:
        ver: "{{ out.ansible_facts.packages['redis-server'] |
                 map(attribute='version') |
                 first |
                 split(':') |
                 last }}"
      changed_when: false

An elegant option is custom facts. On the remote hosts where you want to check the version of redis create the below script

shell> cat /etc/ansible/facts.d/redis.fact
#!/usr/bin/sh
ver=`(redis-cli --version | cut -d ' ' -f 2)`
echo {\"redis_version\": \"$ver\"}

Test it
shell> /etc/ansible/facts.d/redis.fact
{"redis_version": "7.0.12"}

Then, the below play
- hosts: localhost

  tasks:

    - setup:
        gather_subset: facter
    - debug:
        var: ansible_local

gives (abridged)
  ansible_local:
    redis:
      redis_version: 7.0.12

Answer: Correct, ansible_facts is not updated between when a task completes and when that same task evaluates its failed_when.
Use your first attempt as is, package_facts followed by assert. Perfectly understandable what it is doing.
package_facts checks the system package manager, which is a good choice for centralizing how software gets installed. (If your OS distro is supported by this module.) You could install some other way, but that requires other methods to maintain and patch it.
Collecting facts about all packages in a standard format, abstracted across a half dozen package managers, is worth the small performance cost of a package manager query. Similar to doing an rpm -qa when -all is not strictly necessary. Although in rpm's case it is using Python bindings rather than the program.
assert is an action plugin, and so does not need to remote anywhere or run external commands. As a result not much run time would be saved combining the tasks.
Tasks that only collect data, and so increase the tasks count in a play summary but never change things, are acceptable style to me. Doing many non-trivial things in Ansible calls for set up, and those tasks don't always change anything.
Minor suggestion, consider making the version string a variable. Major version requirements of applications might not change often. However when testing your role would be nice to see what the failure condition looks like.


Can someone provide intuition for Alfsen's proof of the existence and uniqueness of the Haar measure on locally compact groups?

Question: I am trying to understand Alfsen's proof of the existence and uniqueness of the Haar measure on locally compact groups:
Alfsen, Erik M., A simplified constructive proof of the existence and uniqueness of Haar measure, Math. Scand. 12 (1963), 106-116 (1964). ZBL0274.43001.
I am not entirely sure what the underlying idea is behind this proof. My thoughts on this are as follows:

The identify measures with linear functionals, so the proof reduces to constructing a particular linear functional on the space $L^{+}$ of compactly supported positive functions defined on $G$.
In particular, we need to find an admissible functional. The existence and uniqueness of this then implies the  existence and uniqueness of the Haar measure.
We associate to the class of admissible functionals a pre-ordering, denoted in words by 'are comparable', which allows us to 'compare' two functionals.
Proposition 2.1: We show that two admissible functionals that have comparable pre-orderings are unique up to a multiplicative positive scalar.
Our problem now reduces to finding one admissible that is comparable with any other.
We define a coarser pre-ordering on $L^{+}$, known as relative size (equation 2.5)
We show that this particular pre-ordering is itself a pre-ordering associated to some admissible.
We deduce this problem to proving that equation 2.6 holds. We prove this using the separation property for functions in $L_{V}^{+}$. see prop. 2.3, whose proof ends before the remark on page 111.
The remainder of the paper is dedicated to proving that the separation theorem property actually holds.
"QED"

There is very little material explaining this paper other than the paper itself, so any further information about it would be much appreciated. Thanks.
Answer: It seems that you more or less have a decent understanding of the proof, so I'm not sure if I can add much of value.
The first important step is that he defines an admissible functional on $L^+$ in a way so as to make existence and uniqueness, modlulo some positive multiple, of an admissible functional equivalent to existence and uniqueness of a Haar measure (via the Riesz representation theorem). Next he introduces a pre-ordering on $L^+$ associated to an admissible functional and deduces that any two functionals giving a comparable pre-order differ only by a positive multiplicative constant.
This leads to the realization that it would be nice to find a pre-order which is comparable with any pre-order induced by an admissible functional. For if this were the case and this pre-order were associated with an admissible functional, then this would give existence and uniqueness (once more modulo multiplication by a positive constant) of an admissible functional. He shows that the first part is indeed the case in Prop. 2.2.
Now all that is left is showing that the pre-order is associated wit an admissible functional. This boils down to proving (2.6). He shows that (2.6) is equivalent to a separation property (S) and then, as you mentioned, spends the rest of the paper proving (S).
I feel like I've mostly repeated what you wrote, but as I said you pretty much get the gist of it. Did you have any specific questions/issues?
Edit: The idea is the following: We know that $\mathrm{supp}(f)$ is contained in some compact subset $C$ of $G$. This implies that $\mathrm{supp}(f)$ can be covered by a finite number of left translates of $\{\varphi > \frac{1}{2}\|\varphi\|_\infty\}$, where $\|\cdot\|_\infty$ denotes the sup norm.
Edit 2: Generally, the notation $u^+$ denotes the positive part of $u$; that is, $u^+ := \max(u,0)$. In this context, that would mean $\left(f - \frac{1}{n}\right)^+ = \max\left(f-\frac{1}{n},0\right)$. That would seem to make sense in this context, so I would assume that is what he means.
Comment: Thank you so much for your answer. I doubted my understanding of this proof, so I am relieved to hear that my thinking is more or less correct. The only thing I am not quite sure about still is how we get Equation 1.1 -  I'm not familiar with this property and not sure how to go about proving it. Do you know if it is referenced in a textbook somewhere?
Comment: I'm also not sure about some notation, do you know what is meant by the + in $(f-1/n)^{+}$ at the bottom of page 110? Thanks


Optimal measure

Question: I am studying conditional expectations and I have a doubt that if it is possible to maximise over a family of measures. It means, let $X$ be a random variable, $A$ be a set and $\mathcal{P}$ be a family of probability measures is it possible  to compute
\begin{equation}
Y=\sup_{\mathbb{P}\in \mathcal{P}} \mathbb{E}^{\mathbb{P}}\left[X|A\right]
\end{equation}
I mean, for instance to compute the maximum of a function $f$ we can compute the first derivative $f'$. Does it exist a similar way to find Y?. Maybe in the case when each $\mathbb{P}$ has density function $f_\mathbb{P}$ is it possible to obtain using something like
\begin{equation}
\frac{d Y}{df_\mathbb{P}}
\end{equation}
I would like to know if there exist some similar result or theory about it. Any help or advice is welcome. Thank you!.
Answer: This answer assumes that $\ \mathcal{P}\ $  is the set of all probability measures on some $\ \sigma$-algebra $\ \mathscr{A}\ $ for which $\ A\in\mathscr{A}\ $ and with respect to which $\ X\ $ is a random variable (i.e. measurable). I made this assumption because I initially misread the description of  $\ \mathcal{P}\ $ as being the family of probability measures rather than a family of probability measures. I don't believe the question is answerable for an arbitrary family of probability measures about which no further information is available.
$\def\ed{\stackrel{\text{def}}{=}}$
If $\ a\in A\ $ and
$$
\mathbb{P}_a(B)\ed\cases{1&if $\ X(a)\in B$\\
0&if $\ X(a)\not\in B$}\ ,
$$
then
$$
\mathbb{E}^{\mathbb{P}_a}(X\,|\,A\,)=X(a)\ ,
$$
and since $\ \mathbb{E}^{\mathbb{P}}(X\,|\,A\,)\le\sup_\limits{a\in A}X(a)\ $ for any probability measure $\ \mathbb{P}\ ,$ it follows from this that
$$
\sup_{\mathbb{P}\in\mathcal{P}}\mathbb{E}^{\mathbb{P}}(X\,|\,A\,)=\sup_{a\in A}X(a)\ .\label{e1}\tag{1}
$$
Also, $\ \mathbb{E}^{\mathbb{P}}(X\,|\,A\,)\ $ attains the supremum in (\ref{e1}) at some $\ \mathbb{P}^*\in\mathcal{P}\ $ if and only if $\ X(a)\ $ attains it at some $\ a^*\in A\ .$
If $\ a^*\in A\ $ satisfies
$$
X\big(a^*\big)=\sup_{a\in A}X(a)
$$
then
\begin{align}
\mathbb{E}^{\mathbb{P}_{a^*}}(X\,|\,A\,)&=X\big(a^*\big)\\
&=\sup_{a\in A}X(a)\\
&=\sup_{\mathbb{P}\in\mathcal{P}}\mathbb{E}^{\mathbb{P}}(X\,|\,A\,)\ .
\end{align}
On the other hand, if $\ X(a)<\sup_\limits{a\in A}X(a)\ $ for all $\ a\in A\ ,$ and $\ \mathbb{P}\in\mathcal{P}\ ,$ then
$$
A=\bigcup_{j=1}^\infty\left\{a\in A\,\left|\,X(a)\le\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{j}\,\right.\right\}\ .
$$
Therefore,
\begin{align}
1&=\mathbb{P}(A\,|\,A\,)\\
&=\mathbb{P}\left(\bigcup_{j=1}^\infty\left\{a\in A\,\left|\,X(a)\le\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{j}\,\right\}\right|A\right)\\
&=\lim_{n\rightarrow\infty}\mathbb{P}\left(\bigcup_{j=1}^n\left\{a\in A\,\left|\,X(a)\le\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{j}\,\right\}\right|A\right)\\
&=\lim_{n\rightarrow\infty}\mathbb{P}\left(\left\{a\in A\,\left|\,X(a)\le\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{n}\,\right\}\right|A\right)\ ,
\end{align}
from which it follow that there exist a positive integer $\ N\ $ such that
\begin{align}
\mathfrak{p}&\ed\mathbb{P}\left(\left\{a\in A\,\left|\,X(a)\le\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{N}\,\right\}\right|A\right)\\
&\ge\frac{1}{2}\ .
\end{align}
Let
$$
B\ed\left\{a\in A\,\left|\,X(a)\le\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{N}\,\right\}\right.\ .
$$
Then
\begin{align}
\mathbb{E}^{\mathbb{P}}(X\,|\,A\,)&=\mathbb{E}^{\mathbb{P}}\big(I_BX+I_{A\setminus B}X\,\big|\,A\,\big)\\
&=\mathbb{E}^{\mathbb{P}}\big(I_BX\,\big|\,A\,\big)+\mathbb{E}^{\mathbb{P}}\big(I_{A\setminus B}X\,\big|\,A\,\big)\\
&\le\mathfrak{p}\left(\sup_\limits{\alpha\in A}X(\alpha)-\frac{1}{N}\right)+(1-\mathfrak{p})\sup_\limits{\alpha\in A}X(\alpha)\\
&=\sup_\limits{\alpha\in A}X(\alpha)-\frac{\mathfrak{p}}{N}\\
&<\sup_\limits{\alpha\in A}X(\alpha)\ .
\end{align}
Thus, if $\ X(a)\ $ doesn't attain the supremum in (\ref{e1}) for any $\ a\in A\ ,$ then neither does
$\ \mathbb{E}^{\mathbb{P}}(X\,|\,A\,)\ $ attain it for any $\ \mathbb{P}\in\mathcal{P}\ .$

Optimal measure


Como atualizo uma linha do datatable com jquery?

Question: Tenho o seguinte código funcionando para adicionar uma linha na tabela dinamicamente
var NovaLinha = [usuario,email,senha,ativo,acao];
NovaLinha.id = retorno;
$('#tabela').DataTable().row.add(NovaLinha).draw();

agora quero alterar ela também com jquery e o código abaixo não está funcionando. O que estou fazendo de errado abaixo?
var NovaLinha = [usuario,email,senha,ativo,acao];
$('#tabela').DataTable().row('#'+id).data(NovaLinha).draw();

Answer: Utilize o método fnUpdate para isso.

Atualiza uma célula ou linha da tabela - este método irá aceitar um
  valor único para atualizar a célula, um array de valores com um
  elemento para cada coluna ou um objeto no mesmo formato que a fonte de
  dados original.

Exemplo:
var tbl = $('#tabela').dataTable({ ... })
tbl.fnUpdate(['Baz', 'email@example.com', 'pass', 'no'], 1);

Demonstração no JSFiddle


Parsing font info and converting it to System.Drawing.Font

Question: i have a text file that contains font information like this:
Arial, 12.5
...and I need to read that info into label.Font like this:
label.Font = new Font(fontNameFields[0], Single.Parse(fontNameFields[1]));
... but I always get the following error:
Index was outside the bounds of the Array.
Can somebody please help me with this?
Thanks
jason.
Code I have:
    MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)");
    foreach (Match match in lines)
    {
        string control = match.Groups[1].Value;
        string text = match.Groups[2].Value;
        int x = Int32.Parse(match.Groups[3].Value);
        int y = Int32.Parse(match.Groups[4].Value);
        String cfont = match.Groups[5].Value;

            String fontName = cfont;
            String[] fontNameFields = fontName.Split(',');

            label.Font = new Font(fontNameFields[0], Single.Parse(fontNameFields[1]));
}

Stacktrace

   at Tabbed.Form1.FillCanvas() in C:\Documents and Settings\jay\My Documents\Visual Studio 2008\Projects\MYPROGGY\ MYPROGGY\Form1.cs:line 574
   at Tabbed.Form1.openbtn_Click(Object sender, EventArgs e) in C:\Documents and Settings\jay\My Documents\Visual Studio 2008\Projects\ MYPROGGY\ MYPROGGY\Form1.cs:line 802
   at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
   at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
   at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
   at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
   at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
   at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
   at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.ToolStrip.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at Tabbed.Program.Main(String[] args) in C:\Documents and Settings\jay\My Documents\Visual Studio 2008\Projects\ MYPROGGY\ MYPROGGY\Program.cs:line 27
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Comment: You could have added this as a comment to http://stackoverflow.com/questions/1518304/convert-string-to-font, it's the same question.
Comment: You've now changed the question significantly - what line does the stack trace point at?
Comment: thank you again, it seems to be pointing at a few lines :(... i've added the stacktrace text to the bottom of the question
Comment: Those line numbers don't help us much until you identify which line is 574.
Comment: line 574 is:

label.Font = new Font(fontNameFields[0], Single.Parse(fontNameFields[1]));
Answer: I suspect you're running into a line which doesn't contain a comma. Your sample data work okay:
using System;

class Test
{
    static void Main(string[] args)
    {
        String fontName = "Arial, 12.5";
        String[] fontNameFields = fontName.Split(',');
        String name = fontNameFields[0];
        float size = float.Parse(fontNameFields[1]);
        Console.WriteLine("{0}: {1}", name, size);
    }
}

Log (or pop up in a dialog box) fontName just before you try to create the font, and I'm sure that'll show you what's going on.
Comment: thank you mr. skeet, i showed a messagebox with the code you provided, but before i even get to display it the messagebox, and returns an error "Index wasoutside the bounds of the array" on line4 of that code.
Comment: "That code"? Which code? My code won't throw an error, and you've now edited your code.
Comment: oh no, i didnt mean that your code was causing the error, all i meant was that i still get the error, even after i tried your code (suggesting that the problem may be somewhere else?)
Answer: At first glance the code looks OK.
Have you checked that fontName is what you expect it to be (i.e. "Arial, 12.5") and what fontNameFields contains after the call to fontName.Split?
fontNameFields[0] -> "Arial"
fontNameFields[1] -> "12.5"

Without seeing the actual values I wouldn't like to suggest anything else.
EDIT
From your updated code I'd suggest that it's your regex that's failing. Try printing out the contents of the match.Groups array to check that you're parsing the input correctly.
Comment: @baeltazor - that's your problem then. The split will then fail and return an empty array which is the exception being raised. Can you post the code that defines and sets `cfont`
Comment: thank you ChrisF. The actual values that I am trying to convert? they are in the question up the top, but ill write them here:

Arial,12.5
Comment: @baeltazor - I meant have you double checked that `fontName` is actually the value you expect it to be. If it is then check that `fontNameFields` is what you expect it to be.
Comment: I added this line of code to see what was goingn on:
MessageBox.Show(fontName);   ...and it doesn't display anything in the messagebox. it just pops up an empty messagebox
Comment: @chrisf - i have just updated my question with the requested info
Comment: thank you very much chrisf - i just did that and when it prints out the cfont line of the regex (the Groups[5] one) it's plain empty. so i can't see anything. i'm not very good with regex, so i am not too sure where the  mistake is
Comment: @baeltazor - it might be best to ask a new question with the string you want to parse and the regex you have and ask why it's not returning anything. Refer to this question for the history.
Comment: i was just thinking that. i think i may have unintentionally caused alot of confusion for everybody here
Answer: Could it be your format contains a strange comma, or none at all?
Also could you provide code on the label as if it were a System.Web.UI.WebControls then Font has not got a setter.
Skeet's code above works fine for the given input.  You're problem lies elsewhere.
Comment: thanks for the answer, but no i've been checking over and over again and the font info in the file is:

Arial,12.5
Comment: the code for the label is: label.Font = new Font(name, size);
Comment: @baeltazor that is still setting. what type of label is it?  also i'd merely suggest you break up the code and maybe write some tests for the separate tasks you are trying to accomplish, i'd always hone in on checking the regex first.


Show taxonomy field in View

Question: I have taxonomy called Hardware Type and it has field Short Code. Now content-type Hardware's has this taxonomy and I have a page which lists all Hardware. I want to show Hardware type's short code field but option is not available under fields.
What are the possible solutions to this?
Answer: NVM, I figured it out that relations can be added from Advanced menu, like below screenshot.

Show taxonomy field in View


Vue.js: como alterar um $state do Vuex que está em um v-model?

Question: Estou com a seguinte dúvida, eu tenho alguns inputs atrelados a estados do Vuex:
<input class="form-control" type="search" placeholder="Filtre sua pesquisa" v-model="$store.state.controlAccessModule.filters.search" v-on:keyup.enter="loadEmployees()" />

Porém por padrões do Vuex, não devo alterar o $state diretamente pelo v-model, como devo fazer isso? Utilizar um $state no v-model é uma "anti pattern"?
Answer: Você precisa criar uma mutation na sua store, uma mutation é utilizada para atualizar um valor no state:
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    username: ""
  },
  mutations: {
    setName(state, username) {
      state.username = username;
    }
  }
});

export default store;

Feito isso, você pode usar uma computed com getter e setter para atualizar o valor:
export default {
  computed: {
    username: {
      get() {
        return this.$store.state.username;
      },
      set(value) {
        this.$store.commit("setName", value);
      }
    }
  }
};

Exemplo:
https://codesandbox.io/s/loving-swirles-twkw0?fontsize=14&hidenavigation=1&theme=dark


$a_{n+1} = f(a_n)$, then $|a_{n+2} - a_{n+1}| \leq M|a_{n+1} - a_n|$

Question: If f is differential such that $|f'(x)| \leq M < 1$, $\forall x \in \mathbb{R}$
Let $a_1$ be any real number and define $(a_n)$ by $a_{n+1} = f(a_n)$
Then $|a_{n+2} - a_{n+1}| \leq M|a_{n+1} - a_n|$.
Is it directly from the Mean Value Theorem?
Comment: Yes. $ $ $ $ $ $
Answer: Yes. Because
$$a_{n+2}-a_{n+1}=f(a_{n+1})-f(a_n)=f'(x_0)(a_{n+1}-a_n)$$
for $n \in \mathbb{N}$. You can bound this by $M|a_{n+1}-a_n|$.
Answer: Yes! That's directly from the MVT, as @M.Van explained.
Moreover, you can conclude that this sequence converges, because $M < 1$!
Comment: How would you like to prove this? Because if $(a_n)$ is a sequence, $|a_{n+2}-a_{n+1}|<|a_{n+1}-a_n|$ for all $n$ does not imply $(a_n)$ converges. Consider the famous counterexample:
$$a_n = \sum_{k=1}^{n} \frac{1}{k}.$$
Now we know $(a_n)$ does not converge, while
$$|a_{n+2}-a_{n+1}| = |\sum_{k=1}^{n+2}\frac{1}{k}-\sum_{k=1}^{n+1}\frac{1}{k}|=\frac{1}{n+2}< \frac{1}{n+1} =|a_{n+1}-a_n|.$$
Comment: @M.Van ,  Luísa is rigth. If $M<1$, the sequence converges.  Note that, from  $$|a_{n+2} - a_{n+1}| \leq M|a_{n+1} - a_n|$$ it is easy to prove, for all $n\in \mathbb{N}$,
$$|a_{n+2} - a_{n+1}| \leq M^n|a_2 - a_1|$$
So for all $p\in \mathbb{N}$, $p \geqslant 1$,
$$|a_{n+p+1} - a_{n+1}| \leqslant \sum_{k=1}^p|a_{n+k+1} - a_{n+k}|\leqslant \left(\sum_{k=1}^p M^{n+k-1} \right)|a_2 - a_1|\leqslant \frac{M^{n}}{1-M}|a_2 - a_1|$$
So, since $M<1$,  the sequence is a Cauchy sequence.
Comment: I see! very nice


Iterating through a specified registry subkey

Question: I'm developing a Windows Registry editor in Python 3.
At the moment my function to query the SOFTWARE key in the CURRENT_USER hive is outputting what I want, I am looking to have a user specify which subkey they want to query for example the Python subkey, and iterate through that but cannot work this out.
My code so far:
def query_registry():
    registry_path = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    registry_key = winreg.OpenKey(registry_path, r"SOFTWARE\\", 0, winreg.KEY_READ)

    for i in range(200):
        try:
            subkey_name = winreg.EnumKey(registry_key, i)
            print(i, "-", subkey_name)
        except:
            print("Number of Directories --> %s" %i + "\n")
            break

The output:

Any suggestions will be appreciated.
Answer: Make the query_registry() function more universal to call itself recursively e.g. as follows (sorry for too little pythonish code):
def query_registry( sargpath, sargxst):
    print(sargpath)
    iargxst = int( sargxst)
    registry_path = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    registry_key  = winreg.OpenKey(registry_path, sargpath, 0, winreg.KEY_READ)
    info_key      = winreg.QueryInfoKey(registry_key)
    if ( iargxst < 0 ):
        for i in range(info_key[0]):
            subkey_name = winreg.EnumKey(registry_key, i)
            print(i, "-", subkey_name)
        print("Number of Directories --> %s\n" %(info_key[0]))
        ###
        if ( info_key[0] > 0 ):
            x = input('Enter subkey number (-1 to end): ')
            if ( int(x) in range(info_key[0]) ):
                subkey_name = winreg.EnumKey(registry_key, int(x))
                query_registry( sargpath + '\\' + subkey_name , -1 )
            else:
                exit()
    else:
        subkey_name = winreg.EnumKey(registry_key, iargxst)
        query_registry( sargpath + '\\' + subkey_name ,-1 )

### main ###
import sys
import winreg
query_registry(sys.argv[1],sys.argv[2])

Result example:
==> D:\bat\SO\53808855.py "software" 19
software
software\Google
0 - Chrome
1 - Common
2 - Software Removal Tool
3 - Update
Number of Directories --> 4

Enter subkey number (-1 to end): 0
software\Google\Chrome
0 - BLBeacon
1 - BLFinchList
2 - BrowserCrashDumpAttempts
3 - BrowserExitCodes
4 - Extensions
5 - NativeMessagingHosts
6 - PreferenceMACs
7 - StabilityMetrics
8 - ThirdParty
Number of Directories --> 9

Enter subkey number (-1 to end): 6
software\Google\Chrome\PreferenceMACs
0 - Default
1 - Guest Profile
2 - Profile 2
3 - Profile 3
4 - System Profile
Number of Directories --> 5

Enter subkey number (-1 to end): -1

==>

Comment: Thank you for your answer Josef, I just wanted to ask, sargpath, sargxst, iargxst these variable names are confusing to me. What exactly are they representing? I see one is for a path and another for argument?, I just wanted to clarify this for context.
Comment: I am getting invalid syntax errors because of the line 26, query_registry( sargpath + '\\' + subkey_name , -1 ), im guessing because we are calling the function within itself we have to use the self?
Comment: @Atreyu about naming e.g. `sargpath` you can read as **s**tring**arg**ument**path**, `sargxst` as **s**tring**arg**ument**xst** where **xst** is my faulty abbreviation for a subkey _sequence number_ (should be rather **xth**?). As you can see I don't get any syntax error using `Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32`.


What can not be done by the Panels module without using the Panelizer module?

Question: Is there anything that can not be done by the Panels module without the Panelizer module?
I'm just starting to learn Panels module and I faced Panelizer.
Note: I installed and applied this module but the Edit in-place that was selected has gone. Is there any conflict?
Comment: watch this tutorial it will helps you.. "https://www.youtube.com/watch?v=0l9QsmbPtrw" by daily dose drupal.
Answer: To answer your question, as in the 'title' of your question, consider reviewing the article about Creating Specialized Layouts with Panelizer. Here is part of what is written in it, and which I think are key features of Panelizer that you can't do with only the Panels module:

Many users of Panels have taken advantage of the Panel Nodes sub-module to create customized layouts for nodes. Panelizer does that and takes things a giant step further; by integrating with Drupal 7's entity system, it can create custom layouts for any entity item.
Panelizer was initially created to allow for one node to be displayed differently than any other node on the system. This allows content creators to be just about as creative with the look and feel of each unique piece of content as they would like.

Some more suggestions about tutorials that you may want to checkout:

Manage Drupal Content Layout with Panelizer.
Architecting Landing pages using Panelizer.

Regarding the Edit-In-Place (IPE, or In-Place-Editor), refer to what's mentioned also in Working with Panelizer combining panels and node displays, i.e.:

Panelizer fully supports the IPE (In Place Editor) meaning that panelized nodes can enable the alternative directly editable panel.

The question about "Enabled Panels In-Place Editor module but cant see the edit icon" may contain other interesting information about IPE, with topics related to:

Clearing the cache.
Renderer mode.
Permissions.
Comment: I installed and applied this module but the `Edit in-place` that was selected has gone. Is there any conflict?


Does there exist a function $f: \Bbb{R} \to \Bbb{R}$ with $\lim_{x \to x_0}|f(x)|=\infty$ for every $x_0 \in \Bbb{R}$?

Question: A function  $f: \Bbb{R} \to \Bbb{R}$ is said to be anti-continuous at $x_0$ if $\lim_{x \to x_0}|f(x)|=\infty$. This is equivalent to taking the epsilon-delta definition for a function being continuous, but requiring that $|f(x) - f(x_0)| > \epsilon$ for $x$ sufficiently close to $x_0$.
Does there exist a function that is anti-continuous at all real values? Or even just a dense set of real values?
I have noticed that if we restrict the domain to $\Bbb{Q}$ then we can simply take the denominator of the fractions in simplest form.
Comment: Note that $f(x)$ can only take a value $c$ at a discrete set, since if $f^{-1}(c)$ accumulates at some point then at that point the limit wouldn't be $\infty$. If the range of $f$ were uncountable, then there would be uncountable number of those values inside some bounded set $A$. Then $f^{-1}(A)$ would be uncountable and therefore, it accumulates at at least some real point. At that point the limit wouldn't be $\infty$. Therefore, the range of $f$ would have to be countable. But then $f^{-1}(f(\mathbb{R}))=\mathbb{R}$ would be countable. Contradiction.
Answer: The answer is NO. We prove by contradiction. Suppose that there exists
a function $f:\mathbb{R}\rightarrow\mathbb{R}$ such that for each
$x_{0}\in\mathbb{R}$, $\lim_{x\rightarrow x_{0}}|f(x)|=\infty$.
For each $n\in\mathbb{N}$, define $A_{n}=\{x\in\mathbb{R}\mid|f(x)|\leq n\}$.
Note that $A_{n}$ does not have any accumulation point (If $A\subseteq\mathbb{R}$,
we say that $x\in\mathbb{R}$ is an accumulation point of $A$ if
there exists a sequence $(x_{n})$ in $A$ such that $x\neq x_{n}$
and $x_{n}\rightarrow x$.) because if $x_{0}$ is an accumulation
of $A_{n}$, we can choose a sequence $(x_{k})$ in $A_{n}$, with
$x_{k}\neq x_{0}$ and $x_{k}\rightarrow x_{0}$. Then $|f(x_{k})|\leq n$
for each $k$, contradicting to $|f(x)|\rightarrow\infty$ as $x\rightarrow x_{0}$.
By Bolzano-Weierstrass Theorem, $A_{n}$ is at most countable. (For,
if $A_{n}$ is uncountable, then $A_{n}=\cup_{k\in\mathbb{Z}}\left(A_{n}\cap[k,k+1]\right)$
which implies that $A_{n}\cap[k,k+1]$ is uncountable for some $k\in\mathbb{Z}$.
$A_{n}\cap[k,k+1]$ is a bounded, infinite subset of $\mathbb{R}$,
so it must has accumulation points. A contradiction!). Finally, $\mathbb{R}=\cup_{n}A_{n}$,
contradicting to the fact that $\mathbb{R}$ is uncountable.


Redirect users to an external URL

Question: Is it possible to redirect users from a controller?
I tried using the following code, but it doesn't work.
<code>public function hello() {
  $query = $db->select('coop.oad','x');
  $query->fields('x', ['oad_url']);
  $query->condition('x.oad_soc', $column_name,'=');
  $result = $query->execute()->fetchField();

  return new TrustedRedirectResponse($result);
}
</code>
Comment: Possible duplicate of [How we replace goto with http status in drupal 8](https://drupal.stackexchange.com/questions/138697/how-we-replace-goto-with-http-status-in-drupal-8)
Comment: Thanks but not working for me :/
Answer: This should do it:
<code>$redirect = new TrustedRedirectResponse($url);
return $redirect->send();
</code>

Redirect users to an external URL


Is there any simple set of properties that uniquely characterizes differentiation in the space of complex functions?

Question: The transformation of differentiation is a linear operator over the vector space of entire functions (call this space $\mathbb{C}^E.$) Is there any simple set of properties that uniquely determines this linear operator that uses only the field structure of the complex numbers and the vector space structure of $\mathbb{C}^E$ and how they "interact" with each other, rather than using an "absolute value" that cannot be defined in terms of the field structure alone?
Comment: @mathlander  No, since $h(z)d/dz$ is also a derivation on entire functions, when $h$ is an entire function: so $3\ d/dz$, $e^z\ d/dz$ and so on.  But $d/dz$ is the only derivation sending $z$ to $1$.
Comment: If you want it short and from the standpoint of a linear operator then it is: "Differentiation is a derivation."
Comment: Basically the same question but with the real numbers: https://math.stackexchange.com/questions/4587371/is-there-any-simple-set-of-properties-that-uniquely-characterizes-differentiatio
Comment: The proof given in that question adapts to this case, I think.
Comment: The proof uses Taylor's theorem. Apart from that, I'm pretty sure everything adapts to this case too.
Comment: Ah, I didn't notice the square. I haven't checked but I suspect that step can be replaced with writing $f(x) = f(a) + (x - a) f'(a) + (x - a)^2 h(x)$ which still works for analytic functions.
Comment: Would Peetre's theorem be something helpful?  In the simplest case, that a linear operator, without continuity assumptions, on test functions, that does not increase supports, must be a differential operator. ... ?
Comment: Yes, but is is the **unique** derivation that can be applied on all of $\mathbb{C}^A$ to get another function in that space?
Comment: If you have a simple proof of the second statement, you can write that as an answer.
Answer: Let $D$ be a derivation on $\mathbb C^E$ such that $Dz = 1$.  Since $Df = D(f \cdot 1) = Df + f D1$ for every $f$, we must have $D1 = 0$.  Moreover $Dz^2 = D(z \cdot z) = 2 z Dz = 2 z$.
Now for any entire function $f(z)$ and $a \in \mathbb C$ we have $f(z) = f(a) + f'(a) (z-a) + (z-a)^2 h(z)$ where $h(z)$ is an entire function.  Then $Df(z) = f'(a) + 2 (z-a) h(z) + (z-a)^2 Dh(z)$; substitute $z=a$ and this says $Df(a) = f'(a)$.  But that is true for all $a\in C$, so $Df = f'$.
Of course this would also work for analytic functions in any open subset of $\mathbb C$.


Selecting maximum number value from a range and autofill down

Question: I want VBA to select the maximum value from range (U2:VN2) and paste the value into range VO2
Then to autofill down column VO, so column VO would display the maximum value for each row down to last row with values.
I tried the following
Sub MaxValueAutofill()

Dim r As Excel.Range
Dim rX As Excel.Range
Dim lastRow As Long
Dim lngMax As Double

Set r = Range("U2:VN2")
lngMax = Application.Max(r)
Set rX = r.Find(What:=lngMax, After:=Range("U2"), LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows,
SearchDirection:=xlNext, MatchCase:=False)

If Not rX Is Nothing Then
    Application.Goto rX, Scroll:=True
End If
Selection.Copy
Range("VO2").Select
ActiveSheet.Paste
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Range("VO2").AutoFill Destination:=Range("VO2:VO" & lastRow)

End Sub

Any help will be greatly appreciated.
Comment: Welcome to SO, I could not find a clear question, can you modify your post and define a question to solve? Please read> [How to Ask](https://stackoverflow.com/help/how-to-ask)
Answer: This should suffice:
Sub Test()

For i = 2 To ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
    Range("VO" & i).Value = Application.WorksheetFunction.Max(Range("U2:VN2"))
Next i

End Sub

Answer: Based on the question stating "maximum value for each row", it doesn't sound like you want to just copy the maximum from row 2 into every row of column VO, so autofilling a value all the way down the column is not appropriate.  You actually need to autofill the "Max" formula all the way down and then convert to values.
Sub MaxValueAutofill()
    With ActiveSheet
        With .Range("VO2:VO" & .Range("A" & .Rows.Count).End(xlUp).Row)
             .Formula = "=MAX(U2:VN2)"
             .Value = .Value
        End With
    End With
End Sub

Comment: Simple and yet efficient. Good job!


React day picker doesn't update class name after simulating click event through enzyme

Question: I'm using React day picker and trying to write some tests for it. One of the tests includes simulating click on a particular day and then checking the class name of that day whether it has added the selected class to it or not. But the problem is, the class name doesn't change at all even after simulating click through enzyme's method simulate('click'). The on click handler does get called though, and I can see in the console output which day was clicked.
Comment: Which version of React day picker are you using?
Comment: Its v7.1.9. Should that matter?
Answer: Figured out! The problem was I was checking the resultant html for the updated class name using the debug() method. But I realised that by using html() I could get the latest updated result. However, for actually checking the existence of the selected class, I couldn't simply use hasClass(<className>), instead I had to use .render().hasClass(<className>).
In short, the click event was working as expected, but just that the checking out output had to be done differently.


Estou iniciando em java e estou tendo o erro java.lang.NullPointerException

Question: ERRO:
Exception in thread "main" java.lang.NullPointerException
    at br.com.drogaria.dao.FabricanteDAO.excluir(FabricanteDAO.java:33)
    at br.com.drogaria.dao.FabricanteDAO.main(FabricanteDAO.java:64)

Embora apareça esse erro ele esta excluindo os dados no BD.  Estou usando a ide eclipse
CÓDIGO:
package br.com.drogaria.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import br.com.drogaria.domanin.Fabricante;
import br.com.drogaria.factory.ConexaoFactory;

public class FabricanteDAO {
    public void salvar(Fabricante f) throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO fabricante ");
        sql.append("(descricao) ");
        sql.append("VALUES (?)");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());
        comando.setString(1, f.getDescrição());

        comando.executeUpdate();
    }

    public void excluir(Fabricante f) throws SQLException {
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM fabricante ");
        sql.append("WHERE codigo = ? ");

        Connection conexao = ConexaoFactory.conectar();

        PreparedStatement comando = conexao.prepareStatement(sql.toString());
        comando.setLong(1, f.getCodigo());

        comando.executeUpdate();

    }

    public static void main(String[] args) {

        /*
         * Fabricante f1 = new Fabricante(); f1.setDescrição("DESCRICAO 1");
         *
         * Fabricante f2 = new Fabricante(); f2.setDescrição("DESCRICAO 2");
         *
         * FabricanteDAO fdao = new FabricanteDAO();
         *
         * try { fdao.salvar(f1); fdao.salvar(f2);
         * System.out.println("Os fabricantes foram salvos com sucesso"); } catch
         * (SQLException e) { System.out.println("Erro ao salvar um dos fabricantes");
         * e.printStackTrace(); }
         */

        Fabricante f1 = new Fabricante();
        f1.setCodigo(1L);

        Fabricante f2 = new Fabricante();
        f1.setCodigo(5L);

        FabricanteDAO fdao = new FabricanteDAO();

        try {
            fdao.excluir(f1);
            fdao.excluir(f2);
            System.out.println("Os fabricantes foram removidos com sucesso!");

        } catch (SQLException e) {
            System.out.println("Ocorreu um erro ao cadastrar um dos fabricantes!");
            e.printStackTrace();

        }

    }
}

Comment: Ola @initJavaWeb, Bem vindo ao SOpt, vale apena você adicionar um comentário ao lado das linhas **33** e **64** indicadas no erro informado, isso vai ajudar a comunidade a identificar o erro, para isso clique em [Edit] abaixo de sua pergunta -- também vale apena você dar uma olhada no nosso [Tour] =D
Comment: Possível duplicata de [O que é a NullPointerException e quais são suas principais causas?](https://pt.stackoverflow.com/questions/63617/o-que-%c3%a9-a-nullpointerexception-e-quais-s%c3%a3o-suas-principais-causas)
Comment: Leia isso: https://pt.stackoverflow.com/q/172909/132
Answer:
at br.com.drogaria.dao.FabricanteDAO.excluir(FabricanteDAO.java:33)

Essa linha é a seguinte:
    comando.setLong(1, f.getCodigo());

Sabemos que comando não é null e que f também não é null. Logo, o suspeito é que o resultado de f.getCodigo() seja null.
De acordo com o javadoc, o segundo parâmetro é do tipo long. Assim sendo, se você passar null no lugar deste parâmetro, o resultado será um NullPointerException de autounboxing. Veja mais sobre isso no terceiro caso dessa resposta.
Considerando que você chamou o método setCodigo(Long) no seu objeto Fabricante, mas mesmo assim o método getCodigo() retornou null, então a origem do seu NullPointerException não está em sua classe FabricanteDAO, e sim em sua classe Fabricante.
Apesar disso, a sua classe FabricanteDAO tem ainda assim um monte de problemas. Recomendo fortemente que você utilize o try-with-resources. Veja nessa outra pergunta o porquê de fazer isso e como fazer.
Ah, finalmente isso daqui:
    StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO fabricante ");
    sql.append("(descricao) ");
    sql.append("VALUES (?)");

É algo desnecessário. Você está montando e remontando sempre a mesma SQL pedaço por pedaço todas as vezes que o método salvar executa. O melhor seria fazer assim:
private static final String INSERT_SQL = "INSERT INTO fabricante (descricao) VALUES (?)";

Pois dessa forma, você constrói a SQL apenas um única vez quando a classe é inicializada e o custo de construí-la é praticamente zero, uma vez que ela já vai estar disponibilizada pronta e inteira dentro do bytecode. O mesmo pode ser dito da sua SQL do método excluir.


MahApps - Alterar ícones para um formato PNG desejado

Question: Encontrei um projeto WPF na web muito bacana. Ele utiliza um framework chamado MahApps. No menu Hamburger há alguns ícones que utilizam imagens de uma pacote do próprio Mahapps. Gostaria de saber se há a possibilidade de eu alterar o bloco e configurar de maneira que eu consiga informar uma imagem png em vez de usar uma do pacote do mahapps. Alguém saberia como?
using System;
using MahApps.Metro.IconPacks;

namespace MahAppsMetroHamburgerMenuNavigation.ViewModels
{
    internal class ShellViewModel : ViewModelBase
    {
        public ShellViewModel()
        {
            // Build the menus
            this.Menu.Add(new MenuItem() { Icon = new PackIconFontAwesome() { Kind = PackIconFontAwesomeKind.Bug }, Text = "Bugs", NavigationDestination = new Uri("Views/BugsPage.xaml", UriKind.RelativeOrAbsolute)});
            this.Menu.Add(new MenuItem() {Icon = new PackIconFontAwesome() {Kind = PackIconFontAwesomeKind.UserOutline}, Text = "User", NavigationDestination = new Uri("Views/UserPage.xaml", UriKind.RelativeOrAbsolute)});
            this.Menu.Add(new MenuItem() {Icon = new PackIconFontAwesome() {Kind = PackIconFontAwesomeKind.Coffee}, Text = "Break", NavigationDestination = new Uri("Views/BreakPage.xaml", UriKind.RelativeOrAbsolute)});
            this.Menu.Add(new MenuItem() {Icon = new PackIconFontAwesome() {Kind = PackIconFontAwesomeKind.FontAwesome}, Text = "Awesome", NavigationDestination = new Uri("Views/AwesomePage.xaml", UriKind.RelativeOrAbsolute)});

            this.OptionsMenu.Add(new MenuItem() {Icon = new PackIconFontAwesome() {Kind = PackIconFontAwesomeKind.Cogs}, Text = "Settings", NavigationDestination = new Uri("Views/SettingsPage.xaml", UriKind.RelativeOrAbsolute)});
            this.OptionsMenu.Add(new MenuItem() {Icon = new PackIconFontAwesome() {Kind = PackIconFontAwesomeKind.InfoCircle}, Text = "About", NavigationDestination = new Uri("Views/AboutPage.xaml", UriKind.RelativeOrAbsolute)});
        }
    }
}

Answer: Esse PackIconFontAwesomeKind, podes adicionar essa tua imagem lá nele, mas deve ter algum outro lugar ligando o que tu cria no PackIconFontAwesomeKind com o local físico da imagem, podes criar por exemplo: PackIconFontAwesomeKind.MinhaImagem
Comment: Obrigado pela dica Rafael :)


Is Fantaisie Impromptu actually in G# Phrygian?

Question: I'm new to music theory and the definition of key I've learned seems to contradict established fact. I've been told that the tonic of a piece is the key where the melody comes to rest, where it feels resolved. And then from there the notes used determine the mode. But, for example, in Chopin's Fantaisie Impromptu, isn't the tonic of the first section G#, not C#? Especially in the main melody, where it clearly resolves (and begins!) on G#:

And, given that the piece uses the notes of the E major/C# minor scale, wouldn't this make the key of the piece G# Phrygian, not C# minor? If the justification for listing the key as C# minor is that the harmony/bass uses C# minor chords, can it be said that the melody is in G# Phrygian while the harmony is in C# minor? Is this a coherent statement?
EDIT: This is the passage that led me to believe G# was the tonic:

I understand now that the harmony is more important for establishing the tonic than the melody, but if we just consider the melody in isolation here, can it be said to have a tonic of G#? If not, why? It starts and resolves on a G# and it certainly does not resolve on C# the one time it encounters that note. So what is the justification for considering C# the tonic if it doesn't act as such? Isn't this being biased towards traditional tonality over a modal explanation? This is the problem I have here.
Comment: Baroque, classical, and romantic music is rarely strictly in one key with no chromatic alterations. In particular, a piece or movement in a major key will very often explore the major key that is a fifth higher, and a piece in a minor key will often explore the major key a third higher and/or the minor or major key a fifth higher. For there to be material leading to a cadence in G# in a piece that is mostly in C# minor would not be unusual at all. It doesn't change the key of the piece and it's very rarely helpful to interpret any key areas modally.
Comment: The entire section you added in an edit has its tonic be E, not G#. Again, music and melodies can strongly emphasize scale degrees other than the tonic. (I am reminded again of one of the second final boss's themes in _Kirby Star Allies_, "La follia d'amore", and how strongly it emphasizes the 5th scale degree in the melody.)
Comment: I'm having trouble with explanations of the tonality which are based on the harmony because to me this melody has an existence separate from the chords in the left hand. If I play the melody on its own without the embellishments, just the first note of each bar, it still sounds the same. The addition of the harmony doesn't radically change my perception of the melody. So I find it difficult to believe the harmony is establishing the tonic. It seems like the melody has its own tonic, which may not be the same as the harmony's.
Comment: I strongly believe the tonic of the first section is still C# - the music comes to rest on a C# into a C# minor arpeggio in Bar 3, and the previous Bars 1-2 are on G#s that we later find were unresolved. Music and melodies can strongly emphasize the 5th scale degree instead of the tonic - even Chopin's "Ocean" etude (in C minor) ends with the 5th scale degree in the melody!
Comment: Your recent edit should be asked as a new question so as not to invalidate the current answers. The analysis of a melody alone is potentially quite different than one that is embedded in a harmony.
Comment: @Dekkadeci but if we consider the melody in isolation, without the harmony, what reason at all is there to consider C# the tonic? The melody begins and resolves on G#, and if you play an additional C# at the end, or replace the final G# with a C#, it doesn't sound right. How do you draw the line between the melody merely emphasising the 5th scale degree and the 5th scale degree actually being the tonic? This is what I'm asking.
Comment: I'm repeating myself, but you really should open a separate question for this. The question and answers here are clearly focused on the Chopin piece. But since your question is really about how to analyze a melody in isolation, you would get the most understandable answers if you create a new question, write out only the melody line absent any of the rest of the piece, and ask how one would go about analyzing that melody.
Answer: Where are you talking about the G# in the melody? In your mm.21-24 example, I see only one place with G# in the melody (treble part) and that is m.24, beat 4. I highlight that in yellow here...

...that G# is harmonized as a G# dominant seventh chord, and it next moves to a C# minor triad, highlighted in blue.

If the justification for listing the key as C# minor is that the harmony/bass uses C# minor chords, can it be said that the melody is in G# Phrygian while the harmony is in C# minor? Is this a coherent statement?

That is not a coherent statement.
Key is determined by tonality, and that is largely a harmonic matter. Even if some music were a single voice melody only, tonal melody often implies harmony in various ways. Harmony is not a justification, it's what makes tonality and key perceptible.

I've been told that the tonic of a piece is the key where the melody comes to rest, where it feels resolved.

Kind of. But that description sounds like a lot of non-technical, non-music theory explanations.
You want to make a distinction between a rest in the interior of a piece of music versus the start/end of the music along with the understanding that music often modulates to different keys as the music progresses. When a piece is said to be "in the key of..." the convention is referring to the starting and ending key. All the interior parts of the work may modulate to other keys.
The thing you really want to look for is dominant/tonic harmonic relationships. Cadences are the typical points to look at to find those dominant/tonic relationships. In fact a cadence is the standard musical device used to define when establishment of a key is confirmed.
The opening of this piece has a tonic of C#. It plays a G#, then a C# minor chord, eventually moves through II V I cadential harmony.
It ends with a V I cadential harmony movement, which connects to a coda, so the V I happens quit a bit before the actual end. Also, the very last chord changes in quality from minor to major. That doesn't change the overall mode of the piece. It's more of a chromatic "coloring" at the very end. That device is called a Picardy Third.
Ironically, the section of your excerpt also has a dominant seventh chord in C# minor, but you need to include m. 25 to see it move to I.
It seems pretty clearly in C# minor.
Just a note. I used plain, upper case Roman numerals for the chord analysis to avoid the complications of chord quality and inversions. We don't need the distraction of those details to figure out the key. The II V I progression at mm.7-9, all diatonic, except for the conventional raised leading tone, the B#, and a little auxiliary motion to Fx, only requires identifying the chord roots to understand the cadential harmony establishing the key.
Comment: Thank you for the very detailed answer. I edited the question to show where I considered G# to be the tonic. Can you have a look and tell me what you think? Thanks.
Answer: Michael Curtis is basically right, as usual, but I'd like to make a couple of points.
First, it's absolutely possible to identify a key for most melodies independent of any harmony.  The terms "tonic" and "dominant," after all, predate the development of harmony.  They are originally melodic concepts.
Most composers harmonize most melodies in the melody's key, but not always.  Harmony is much more powerful at establishing a key than is melody, though.  As Michael Curtis says, it's largely a harmonic matter, but mot exclusively.
It is in fact possible to take a melody in the Phrygian mode and harmonize it in the relative major key, or the relative minor key for that matter.  Bach and his contemporaries did this fairly frequently.  But it's nonetheless somewhat unusual, and it doesn't make much sense to analyze a piece that way unless the melody has some independent existence as a Phrygian melody.  In most cases, a melody that ends on the third or the fifth of the tonic chord is nothing more than a melody that ends on the third or fifth of the tonic chord.
So, it's not always the case that "the tonic of a piece is the key where the melody comes to rest."  For tonal classical music (and much other music) the better way to find the key of a piece is to identify the root of the last chord.
But even there, there will be exceptions.  for example, Bach's harmonizations of Phrygian chorale melodies are often best analyzed as being in the relative minor key but ending on the dominant chord, so, for example, the piece is in A minor but the melody ends on E and the harmony ends on E major as the dominant of A minor.
Comment: Thanks, I'm interested in what you say about harmonising a melody with a different tonic. I edited the question to show another section. Do you think this is an example of this or not?
Answer: Based on a later edit and comment on this question:
Considering only the accented melody notes in Bars 13-16, it's actually easier to argue the melody is in F sharp minor than G sharp anything:

E sharps are plentiful and are always immediately followed by F sharps, strongly implying that the E sharps are leading tones and therefore F sharp is the tonic
The melody can be plausibly harmonized as C♯-F♯m-C♯-F♯m / C♯m-G♯-C♯m-C♯m / C♯-F♯m-C♯-F♯m / C♯- F♯m-A-C♯ (this obviously isn't what Chopin actually used, though)
Taken alone, the melody notes used are F♯-G♯-A-C♯-D♯-E-E♯; this collection cannot be G sharp Phrygian because it contains E sharp

Zoom out and consider all melody notes in Bars 13-16 and a G sharp tonic becomes even more implausible:

The melody notes used are G♯-A-B-B♯-C♯-D♯-E-E♯-F♯, already implying great chromaticism and a lack of modal flavour due to the presence of 3 notes in a row separated by a semitone each
Especially given that minor-key music often uses a sharpened leading tone instead of a flattened subtonic for the 7th scale degree, taking the voice leading of the full melody into consideration, tonics of F sharp, C sharp, and E are more plausible than G sharp, which is only ever preceded by E, A (accented melody notes edition), E, and B (full melody edition) - never F double sharp or even F sharp like we likely expect for a G sharp tonic
With 9 G sharps and 12 F sharps in the full melody, F sharp is more common than G sharp in the full melody, further harming the case for G sharp as the tonic
The full melody can be plausibly harmonized as C♯-F♯m-C♯-F♯m / F♯m-D♯°-E-E / C♯-F♯m-C♯-F♯m / E♯ half-diminished 7th-B-Esus4-E, actually making the case that E is the tonic instead as the music rests on E major chords the longest and all E major and E major-like chords are immediately preceded by dominant-function chords in E major or just more E major(-like) chords

Overall, the requested melody of Chopin's Fantaisie-Impromptu contains too many notes not in G sharp Phrygian to be in G sharp Phrygian, the melody notes do not undergo voice leading consistent with G sharp Phrygian, and analyzing the harmony of the requested melody alone reveals that it is in E major instead with heavy tonicization of F sharp minor and C sharp.
Comment: Thanks, your answer is very interesting and well thought out. I assumed the E sharp/F natural was an example of chromaticism so never considered a possible F# tonic. I'm not completely convinced though because of the occurrence of the D# which doesn't appear in F# minor. I wonder if the melody is passing through multiple modes/keys, as you point out it appears to end in E major. Or perhaps it is just ambiguous. I'm very curious now to see whether it could be harmonised in G# Phrygian. Perhaps I'll try to rewrite the left hand if I have some spare time.
Comment: I don't really consider the non-accented notes part of the melody but rather an ornamentation and part of the harmony. If I were to modify the harmony I would modify these notes as well.
Comment: @chopinliszt - I'm guilty of also singing just the accented melody notes in Bars 13-16 whenever I sing Fantaisie-Impromptu (this does contrast awkwardly with my need to sing all the right-hand notes in measures beforehand, though). However, D# does indeed appear in F# minor - D# is in the F# melodic minor scale, which means that D# does get used in F# minor music.
Answer: the tonic of a piece is the key where the melody comes to rest, where it feels resolved is of course something that is taught to students to give a basic understanding of what a tonic is, but it absolutely fails to achieve its purpose in this case. The reason is that Chopin intends to create motion, and he does so by not remaining on the tonic, but by modulating, exploring different intermediate tonics, until resolving back to the original one. In this piece in particular it makes sense to study the left hand, as that gives us the harmonic framework this is build upon. We can then try to find cadences and characteristic chords (dominant 7, semidiminished 7) to analyse what our tonic center is at which point. This then gives us something like this:

(done till measure 27 where we return to the first motive in C# minor). We thus see that the piece starts in C# minor, then shortly changes to G# minor (which is the part you had in mind), but quickly changes again to E major, until we resolve back to C# minor.
This concept of leaving the tonic and employing intermediate tonics is what gives the piece tension and what makes it interesting. But the main, big, final tonic of the piece everything eventually resolves to is still C# minor.
Comment: I don't have the score or an instrument in front of me but I think there's something off with your harmonic rhythm at bar 13, I follow along until there then lose it. That, or I'm just really bad at counting
Comment: oh, reading through again paying attention to the harmonic movement, I think it's just that the 4 4 5 1 should be 2 beats each over 2 bars, but you have the B7 and E as whole bars not minims.  Should be Ax4 Bx2 E4 (in beats) not Ax4 Bx4 Ex4.  Good overall analysis though, just a little error :)
Answer: I was just looking through the sheet music for a pop song when I saw something that reminded me of this question. The song was in G major but there was a section where for a few bars the G was sharp and the melody alternated between F# and G# and it was clear that the purpose of this sharp on G was to make the melody avoid hitting the tonic and continue the motion of the piece without letting it terminate on the tonic. This made me think of this question and I suddenly realised that this is very likely what's happening here.
Take a look at similar melodies that start on G#, such as G#-F#-E-F#-E-F#-C#-E or even just G#-F#-E-F#-E-F#-E, which both clearly resolve to E. It seems like going from G# to F# and then one or two semitones lower creates a strong tendency towards E as the tonic. Additionally, when considered with the harmony which as Lazy pointed out progresses A6-B7-E the evidence for an E major tonic in this section seems pretty overwhelming. Also I have since seen quite a few pop songs including the aforementioned one in G major ending on the 3rd degree of the key without sounding unresolved, so it seems plausible for the melody to end on G# while the tonic remains E. So I would say this section is in E major and the purpose of the E sharp is to continue the melody where it would otherwise encounter the tonic and tend to end soon after.


Spring Boot session configuration questions

Question: I have a Spring Boot application and I can't seem to get my login session to last very long. I'm setting the following in application.properties:
spring.session.timeout = 180d
server.servlet.session.timeout = 180d

I have a couple of questions:
• What duration suffixes are allowed when specifying spring.session.timeout and server.servlet.session.timeout? I can't find this documented anywhere, just a note in these docs saying "If a duration suffix is not specified, seconds are used," implying other durations are possible.
• Do I need to include spring-session in my POM? I don't care about session clustering or the stateful REST API support, and I want to avoid more startup time and configuration. I certainly don't want to configure more persistence.
My primary concern is keeping me logged in to the website (ideally indefinitely).
I'm using Spring Boot 2.3.0-RELEASE.
Comment: Which version of Spring Boot are you using?
Answer: If your are not using Spring Session, you should use the property server.servlet.session.timeout.
When specifying the timeout you have 3 options.

You can use the standard ISO-8601 format used by java.time.Duratio, for example P180D for 180 days.
You can use a simple format where the value and the unit are coupled, for example 180d for 180 days. You can find the supported units in this section of the Spring Boot reference docs.
Finally, you can use a long representation and the specified number will be interpreted as second, for example 200 for 200 seconds.

You do not need to include spring-session in your POM.
Answer: In Spring boot 2.4+. It might work in the below version but I did not test it.
I am using the below configuration. max-age sets the max-age in the cookie on the browser side and timeout sets the timeout in the MAX_INACTIVE_INTERVAL column in spring_session which I store in JDBC.
When I use only max-age, my cookie gets deleted from the backend database in 30 minutes.
When I use the only timeout, the cookie gets deleted from the browser on the browser restart.
Therefore, I have set max age to 30 days to persist the session in browser and timeout to 30 days to persist the session in db.
server:
  servlet:
    session:
      cookie:
        max-age: 30d
      timeout: 30d

My build.gradle for oauth looks like
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'

    // for oauth
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // to store session in jdbc
    implementation "org.springframework.session:spring-session-jdbc"

Helpful link


Is python capable of doing MATLAB equivalent matrix operations?

Question: I have implemented codes in MATLAB that operates on 216x216 matrices that contain numeric data and sometime strings. The operations that I do on these matrices are mostly like filter matrices above a certain threshold, find all the matrix indexes that are above some value, Find a list of values above say X and then find consecutive differences between them, some string replace manipulations. Do matrix dot products etc. I need to access thousands of files to generate these matrices(dlmread I use in MATLAB).
Now I am in need to implement the above project in any other language that are usually bundled with an OS say Perl, c or python or opensource language.
I did a brief search and found out that python is a good tool for research. Does python has some of these MATLAB equivalents for matrix operations ( like read a file directly into an array, find, dlmwrite etc )
Because my codes already have a lot of loops without these MATLAB functions the codes would get much messier and difficult to maintain.
Or could you point out any other alternatives. I am familiar with little Perl but not python or R.
Comment: I did complete my project using scipy/numpy. Awesome experience !
Answer: Start with this page comparing NumPy and Matlab.
Here are some examples regarding your post:
<code>In [5]: import scipy

In [6]: X = scipy.randn(3,3)

In [7]: X
Out[7]:
array([[-1.16525755,  0.04875437, -0.91006082],
       [ 0.00703527,  0.21585977,  0.75102583],
       [ 1.12739755,  1.12907917, -2.02611163]])

In [8]: X>0
Out[8]:
array([[False,  True, False],
       [ True,  True,  True],
       [ True,  True, False]], dtype=bool)

In [9]: scipy.where(X>0)
Out[9]: (array([0, 1, 1, 1, 2, 2]), array([1, 0, 1, 2, 0, 1]))

In [10]: X[X>0] = 99

In [11]: X
Out[11]:
array([[ -1.16525755,  99.        ,  -0.91006082],
       [ 99.        ,  99.        ,  99.        ],
       [ 99.        ,  99.        ,  -2.02611163]])

In [12]: Y = scipy.randn(3,2)

In [13]: scipy.dot(X, Y)
Out[13]:
array([[-124.41803568,  118.42995937],
       [-368.08354405,  199.67131528],
       [-190.13730231,  161.54715769]])
</code>
(Shameless plug: a comparison I once made between Python and Matlab.)
Comment: `scipy.nonzero(X>0)` can be replaced by `numpy.where(X>0)` which I think is easier to read.
Comment: Agree. `where` implies that locations ought to be returned. Edited.
Comment: Yes, sci/numpy looks likes the solution !
Answer: You may want to take a look at NumPy / SciPy, they may help you do what you want. Plus there are a sizable number of users which will make it easier to get help when needed. General Intro to both libraries here


ExtJS 4.1 - Drag and Drop with RowExpander Issues

Question: Update 9/11/13 - Here is a fully working jsFiddle demonstrating the issue... to experience the issue, expand the grid and attempt to drag the nested row over to the TreePanel. The drag element will be obfuscated by the TreePanel, as if it is behind it. Link here: http://jsfiddle.net/ZGxf5/
Here's a bit of a unique roadblock I've run into... I figured it would be best illustrated with an image:

As you can see in the picture, I am attempting to drag a div, generated via the rowBodyTpl property of the RowExpander plugin utilized in the grid shown in the bottom left of the image. I am able to "grab" the element and move it about, however it is seemingly constrained to the RowExpander generated div. I cannot drag the div any further left, nor upwards from where its original position. Attempting to move it into the panel to the right results in the dragging div being obfuscated, as shown in the picture.
I have attempted to completely eliminate all constraints in the startDrag method as you will see in the code below, but to no avail. I am basically just using the code provided in Sencha's 5 Steps to Understanding Drag and Drop with ExtJS Blog Post, but it obviously needs some tweaking for my implementation.
Below is my code for initializing the Drag on the target div..
 /**
   * NOTE: The following code is executed whenever
   * the contents of the grid's store change
   */

    var me = this, // ENTIRE left panel, including the TreePanel and lower GridPanel
        divs = Ext.select('div[name=storage-item-div]', false, me.getEl().dom),
        dragOverrides = {}; // provided separately, see below

    Ext.each(divs.elements, function(el){
        console.warn("mkaing new dd", el);
        var dd = new Ext.dd.DD(el, 'storageItemDDGroup',{
            isTarget: false
        });

        Ext.apply(dd, dragOverrides);
    });

The dragOverrides object is defined as follows (note my debugging for Constrain)
        dragOverrides =  {
            b4StartDrag : function() {

                // Cache the drag element
                if (!this.el) {
                    this.el = Ext.get(this.getEl());
                }

                //Cache the original XY Coordinates of the element, we'll use this later.
                this.originalXY = this.el.getXY();

            },
            startDrag: function(){
                /** DEBUGGING */
                _t = this;
                this.resetConstraints();
                this.setXConstraint(1000,1000);
                this.setYConstraint(1000,1000);
            },
            // Called when element is dropped not anything other than a dropzone with the same ddgroup
            onInvalidDrop : function() {
                // Set a flag to invoke the animated repair
                this.invalidDrop = true;
            },
            // Called when the drag operation completes
            endDrag : function() {
                // Invoke the animation if the invalidDrop flag is set to true
                if (this.invalidDrop === true) {
                    // Remove the drop invitation
                    this.el.removeCls('dropOK');

                    // Create the animation configuration object
                    var animCfgObj = {
                        easing   : 'elasticOut',
                        duration : 1,
                        scope    : this,
                        callback : function() {
                            // Remove the position attribute
                            this.el.dom.style.position = '';
                        }
                    };

                    // Apply the repair animation
                    this.el.moveTo(this.originalXY[0], this.originalXY[1], animCfgObj);
                    delete this.invalidDrop;
                }

            }

Finally, I think the rowBodyTpl portion of the lower grid's configuration may be useful in solving the issue, so here is the source for that!
    rowBodyTpl :  ['
'+
                   '<tpl for="order_data">'+
                        '<tpl for=".">' +
                          '
' +
                            '{quantity} from Purchase Order {purchase_order_num} @ ${purchase_cost}' +
                            '<input type="button" style="margin-left: 10px;" name="storageViewOrderButton" orderid="{purchase_order_id}" value="View Order"/>' +
                          '
' +
                        '</tpl>' +
                    '</tpl>'+
                    '
']

Comment: Added jsFiddle example: http://jsfiddle.net/ZGxf5/
Answer: I was able to get this working in a Fiddle, but I had to switch my RowExpander template to instead render an Ext.view.View rather than the div which I was previously using. Using an Ext.view.View allowed me to basically just follow the Sencha demo for using DragZone and DropZone.. kinda wish it wasn't so complicated but hey, that's just how it is sometimes, I guess.
See the very messy jsFiddle source here for a working demo using DragZone and DropZone, feel free to tweak for your own needs: http://jsfiddle.net/knppJ/
Again, the issue here was dragging a nested div from inside a RowExpander generated row inside a gridpanel to a separate adjacent panel. The issue I was encountering is thoroughly described in my question above. I was not able to get a regular div working the way I wanted it to, so I ended up using an Ext.view.View in place of the grid. This required adding a bit of extra logic in the onbodyexpand event fired by the RowExpander plugin, basically just rendering an Ext.view.View to the div generated by the RowExpander.


How can I show that Uniform($0,A$) ,as $A \to \infty$, is an improper denisty?

Question: I am very new to Bayesian statistics and I wanted to know how could I show that Uniform($0,A$) ,as $A \to \infty$, is an improper density?
I mean the Uniform($0,A$) ,as $A \to \infty$ density is given by
$ \lim_{A \to \infty}f(x)=\frac{1}{A} \mathbb{1}_{[0,A]}=0$ and hence it doesnt integrate to 1 and therefore improper based on the definition I found here
Does "improper" posterior or prior refer to a density function that does not integrate to 1 or to one that does not integrate to a finite value?
Am I wrong?
Answer: Basically, yes.
More formally, what you want to know is: what is the value of
$$ \int_{-∞}^∞ \lim_{A \to ∞} \tfrac{1}{A}1_{[0, A]}(x) \; dx \;\;\; ?$$
For all $x$, the limit converges to 0. To see this, notice that for any $x$ and $A$, $\tfrac{1}{A}1_{[0, A]}(x)$ is either $0$ or $\frac{1}{A}$, the latter of which is less than any $ε > 0$ for all $A > \frac{1}{ε}$. Then we have just $\int_{-∞}^∞ 0 \; dx$, which is $0$.
Because the function's integral is $0$, it isn't a proper density.
Comment: If the density approaches 0 everywhere it can't integrate to 1.  That is why it is improper.
Comment: Hi if you read from  the link I attached , I see that any finite number is considered to be proper but somehow i gather that this finite number should be non zero for it to be proper since we can scale it to make it equal to 1 . Right ?
Comment: @user3503589 That's right. There can't be a normalizing constant when the integral is 0.
Comment: @Kodiologist But does it even make sense for a density to be zero everywhere? I was reading a paper by Prior distribution for variance parameter in hierarchical models by Andrew Gelman, where they talk about approximating the improper distribution $U(0, \infty)$ as a limit of proper distributions i.e $U(0,A), A \to \infty$
Comment: @user3503589 No, it does not make sense, because it means that the function has integral 0. The improper prior $U(0, ∞)$ indeed has no corresponding random variable or probability density function.
Comment: @Kodiologist Then why do we even do this approximating argument ?
Comment: @user3503589 Why, because $U(0, A)$ for finite $A$ is an actual distribution, so we can come up with proper priors that resemble the desired improper prior.


Is it possible to set Brotli compression level dynamically based on the request headers in Nginx?

Question: I'm using Brotli for response compression, and doing this in Nginx using nginx-brotli module.
I would like to set the value for brotli_comp_level dynamically based on the request headers, so that clients on slow networks could request higher compression. How can I achieve this?
I tried to no avail:
http {
  ...

  brotli on;
  brotli_comp_level 6;
  brotli_types *;

  if ($http_x_brotli_high_quality) {
    brotli_comp_level 11;
  }
}

Answer: It is not possible with the stock/packaged Brotli module from NGINX Plus.
You can, however, custom compile (not recommended for production) with the following pull request integrated.
Or, if the budget allows, use the nginx-module-brotli module package from NGINX Extras, which has the aforementioned pull request integrated into the packages. This option requires a CentOS/RHEL machine and maintaining a paid subscription with GetPageSpeed.


Views REST Export and Multi-Value Fields

Question: I'm having trouble getting the Views REST export to work nicely with multi-value fields.
I have an image field that can have multiple images. I have added the field to my REST export View, however all values are being output on the same line. Like this:
[
    {
        "nid": "11",
        "image": "http://example.com/sites/default/files/2016-02/mobile-1.jpg\n,   http://example.com/sites/default/files/2016-02/mobile-2.jpg\n"
    }
]

What I would like to achieve is something like this:
[
   {
      "nid":"11",
      "image":{
         "0":"http://example.com/sites/default/files/2016-02/mobile-1.jpg\n",
         "1":"http://example.com/sites/default/files/2016-02/mobile-2.jpg\n"
      }
   }
]

Is this possible?
Perhaps using HOOK_views_pre_render() to change the returned value?
Comment: I think this happens because it's displaying in the same row for that field. Unfortunately when you uncheck this, it will make each image its own row so you'd end up with multiple items for each node. However if you use entity display styling, then you should be able to use display modes to control what fields you want. Of course then you lose the ability to add field aliases.
Comment: @mradcliffe I guess this still isn't possible?
Comment: See below answer if it was reported as a bug.
Answer: This looks like it's a plain bug. Please report it to the views.module issue queue in Drupal core: https://drupal.org/project/issues/drupal?component=views.module.
Comment: For reference, there is this issue: https://www.drupal.org/project/drupal/issues/2782909
Answer: This happens even in 8.4, so I had to use the Views Field View plugin to create a view for just the list items (in your case, a list of image URLs) and add that view as a field to the main view. This works conceptually, but the output of the child view is littered with HTML which I can't seem to figure out a way to get rid of.