How does appeal against sending off work in football?

Question: Taking a recent example of two unsuccessful appeals by Real Madrid:
1. Sergio Ramos being sent off against Deportivo.
2. Cristiano Ronaldo being sent off against Barcelona.
So my question is, when teams appeal for a review of a sending off, do the reviewing bodies just look at the particular instance leading to the send off or the whole match behavior before deciding if the bans should be upheld or not?
Comment: I'm really confused by the premise of this question. If a player is sent-off or otherwise cited for committing an offence, and can prove that they did not commit that offence, why would other unrelated incidents in the match have any impact on whether they committed that offence? No sport or legal jurisdiction works like that, as it's a nonsensical proposition.
Comment: @studro My question arose due to more or less same confusion. I had mentioned this in the question earlier, but in my opininion, the exact instances in both the mentioned cases when the red was shown did not warrant a sending-off.
In Ramos's case particularly, there was an earlier incident in which if he was sent off that would be justified. He got away at that point but was nonetheless shown a red at last.

That got me questioning if the previous incident was in minds of the reviewing body for rejecting the appeal against the ban.
Comment: They both received a second caution in the same match. That's why the appeal failed - the only way to prove that the send-off was invalid is to prove that they didn't receive two cautions. As a general rule, appeals panels / committees don't deal with cautionable offences - only sending-off offences. Allowing the post-match review of cautions would make the workload of appeals committees unmanageable.
Answer: Reviewing bodies, in case of Spanish League, Spanish football federation's (RFEF) compeetition committee and appeals committee, will only look at the particular instance leading to the sending off or the incident club is appealing against, and the club has to provide written report with video evidences to that particular incident. Consequences will only be overridden in case of obvious mistake.
From RFEF Disciplinary code:

Article 130. Review of arbitration decisions.(google translation)
2. The disciplinary consequences of such expulsion may be overridden by the disciplinary body only in the event of manifest material error.

(As OP was interested in incident involving Sergio Ramos and Ronaldo)
1.For incident involving Ramos ESPN: Madrid appealed the second yellow shown by referee Jose Luis Gonzalez Gonzalez, but the Spanish federation's competition committee said the video evidence presented by the club's legal team had failed to establish that the official had made a mistake. Adding, this appeal may be lodged against the Appeal Committee within a maximum period of ten working days.
2.For incident involving Ronaldo DailyMail: The Spanish football federation's (RFEF) appeals committee "dismissed the appeal presented by Real Madrid", the RFEF said in a statement.
While the RFEF compeetition committee stated Madrid have 10 days to lodge an appeal with its appeals committee, while adding in its report that the club attempted to get the offence downgraded from a push to a minor "disregard" for the referee.
The official match report sent to the RFEF from the Camp Nou included Ronaldo's push in the "other incidents" section.

Other incidents: (Player: Cristiano Ronaldo Dos Santos Aveiro) Once the red card was shown, the player pushed me slightly in a sign of disagreement.

From efe.com:

The sole judge on the RFEF's Competition Committee, after reviewing Real Madrid's defense statements, first of all made clear that the referee was the only sportive authority during the match and his decisions were irrevocable.
The judge also considered that the player violated article 96 of the disciplinary code, which forbids pushing the referee and imposes bans ranging between 4-12 matches for that action.
The judge dismissed the argument that the shove had been an instinctive response from Ronaldo, as Real Madrid claimed, and instead called it an "unjustified and disproportionate reaction."

Other Articles: mls soccer, theguardian, playtheadvantage 1 2, theguardian 2, espn, telegraph, bleacherreport


Javascript callback functions differences

Question: I would like to know the difference between 2 implementations of callback functions.
This:
$("#button").on('click', function () {
            //do something
});

Versus having the function already defined.
$("#button").on('click', btnFunction);
function btnFunction() {
    //do something
}

Are there any implications with one compared to another? Performance-wise is one faster?
Comment: There's no functional difference, and no noticeable performance difference either
Answer: The first uses an anonymous function and the second does not. There's no difference in both.
See:
Why do you need to invoke an anonymous function on the same line?
Answer: Some folks prefer the second form because it gives a function name when using the debugger and tracing, but there are ways to get the same functionality in the first form.
If you are attaching and removing the event handler based on changing conditions, the second form is much easier to maintain, however.
Answer: There's no difference at all, and there's no performance issue with neither one of them. The only difference is that in one of them you're defining the callback function as an anonymous function, this way you cannot reuse it.
The other way, where you define it else where and named it and then pass it as a callback, you're defining a function that you can later reuse in another part of your code.
For example: if you want to do something when the document is ready, and then do se exact same thing when some one press a button you can use something like this:
function getData() {
    //do something
}

$(function() {
    // Call the function once the DOM is ready
    getData();
});

// Call the same function when the button is clicked
$("#refresh_button").on('click', getData);

Answer: In most cases the first one will be used, called Anonymous Functions
The second one will be used when the function is not only used inlined here, but also needs to be reused somewhere else.
But anyway it could be a personal preference.
Answer: The only real difference you could see is that stack trace (if an exception is thrown for example) will be better, i.e. easier to debug, when using the second one.
Answer: Just reuse-ability.
In the second case, you could call btnFunction() somewhere else if need be.


Proving something is the basis of a quotient space

Question: Let $k$ be a field which does not have characteristic 2. Let $M$ be the free $k$-vector space generated by two elements $\{ c, x \}$. Let $T(M)$ be the tensor algebra of $M$ and let $I$ be the ideal generated by the elements $$\{c^2 -1, x^2, cx + xc \}.$$
I am trying to show that $B = \{ 1, c, x, cx\}$ forms a basis of the quotient space $T(M) / I$. I can see why it spans the space but I cannot show that it is linearly independent. Any help would be appreciated.
Answer: As you probably know, this is an example of a Clifford algebra attached to the quadratic form which gives two orthogonal basis elements $c,x$ respective "norms" $1$ and $0$, and $c,x$ anti-commute, etc.
The standard trick to show that the dimension is as large as possible begins with the case of the Clifford algebra of a one-dimensional vector space with bilinear form, and in that case we know that $k[x]/(x^2-a)$ is two-dimensional, in any case, because we have simpler control in the commutative case.
It is perhaps over-kill for the two-dimensional vectorspace case, but the induction step in proving that a Clifford algebra on an $n$-dimensional v.s. $V$ has dimension $2^n$ (rather than accidentally smaller) is to express $V$ as an orthogonal sum $V_1\oplus V_2$ where $V_1$ is one-dimensional. There is the parity grading into odd and even elements, inherited from the universal associative (tensor) algebra, and for monomials define a twisted multiplication $(x\otimes y)\cdot (x'\otimes y') = xx'\otimes yy' \cdot (-1)^{\deg x'\cdot \deg y}$ on $Cl(V_1)\otimes CL(V_2)$. One checks directly that this gives the Clifford multiplication, and we know the dimension of a tensor product (whether or not the multiplication is defined with $-1$'s in it).
(So this is not as serious a result as Poincare-Birkhoff-Witt for universal enveloping algebras, but it's not completely trivial.)
Edit: Actually, knowing the above, one can pretend to have the epiphany that this algebra is inside the $4\times 4$ matrix algebra over the ground-field (it has some degeneracy) so prove the four-dimensionality by mapping this (universal) object surjectively to a four-dimensional subalgebra of the matrix algebra. But this is a bit of a prank... :)
Comment: Thanks for you answer. I wasn't aware it was a Clifford algebra, but I will look into this!
Comment: You're welcome. This smallish case is also some sort of "quaternion algebra", which indeed is the smallest non-commutative Clifford algebra.


How To Enter Data Into A Custom Drupal Entity?

Question: I have a question regarding entering data into custom entities
I have a usage case I believe is better for Drupal Entities than Content Types and Nodes.  I have installed Entity Construction Kit and used it to set up the structure for my entity.
What is not clear to me is how I go about getting data into my entity.  I assume we could do a mass CSV import via Feeds.  But what about making individual entries?  I'm looking for a way to enter the data through the Drupal Administration forms (i.e. Add Content > Entity Name) but that does not appear to be the case.
Are there additional modules out there that would give me the ability to do this?
Thank you for your time and assistance.
-- Chris
Answer: I think everyone suffers the same bewilderment on first meeting ECK. Its workflow is bonkers.
You begin by creating an entity type and optionally renaming the default bundle (which otherwise will have the same name as your entity). I recommend giving the bundle a unique name to avoid confusion in this rabbit warren interface.
Then from the list of entities, click into that entity and then into the bundle. From here you can manage fields - and add your data from the 'entity list' tab. There, the link to add new instances of your entity type will be at the top of the interface - "+ add [name of your bundle]" and the list there will effectively serve as a rudimentary content list for that entity until you can whip something up in views.
If you want to cut through the labyrinth and use a simple link to add your data, it'll be structured like this:
admin/structure/entity-type/[your entity name]/[your bundle name]/add
Comment: Yes. Have a look at this I stumbled on earlier. [http://www.trellon.com/content/blog/creating-own-entities-entity-api] It seems to cover much of what your looking for.
Comment: Thank you Peter, for your response.  I did find that actually.  What I'm struggling with in my head is how I eventually give my users access to this form so they can enter content.  It did kind of throw me after I found it under Structure.  This concerns me since my users wouldn't have access to the Structure menu.

You mentioned its possible to build an edit form through a view?  How is that accomplished?  I've never done that before.  I've only built views to display content.

Thanks again!
Comment: I think our wires are crossed! I was referring to the list of entity content under the entity list tab - it's eck's equivalent of admin/content and that you would probably want to make a custom display for it using Views and VBO. For a custom form I assume you'd need to use the form API.
Comment: Exactly, yes.  But is the Entity List tab not only accessible through the Structure Tab?
Answer: Answering your original question I would like to propose Model Entity module for your consideration. It is less known than ECK, but in a few projects it gave enough support for my goals.
Out of the box you will have entity editing forms not under Structure but for a bit more appropriate place - Content, so URL will look as /admin/content/models/add .
Hope this helps!
Answer: I use Inline Entity Form on my Drupal site. Although it is not entirely clear from the linked page, this module has options that allow you to create new entities (of a specified type & bundle), and then remove them from the form, but leave them in the database, you may then select to add the entities for display in other forms. You can enable and disable entity creation on each instance of a form.
The rest of my setup includes:-

several custom entity types made with ECK, add fields using the usual UI.
On a node[*] add an entity reference field for your custom entity, you should have two new choices for the widget - either a single entity form, or a multi-entity form.
The entity creation form is now shown as part of the node creation page - and so will be accessible to those who have the usual permissions.
Be sure to review the permissions for creation of the appropriate entity as well, otherwise the form will not function.

[*]this does not have to be a node, I also use this setup on my User account page.
Answer: I'm new to Drupal, but had the same question.  After poking around, it seems that the https://www.drupal.org/project/entityform module is useful for entering data into custom entity data fields in Drupal 7.  In 8 this will be Eform.
I've installed Entityforms and it seems to work.  I have not had enough time to run into problems yet, though.  Good luck.


Don't think I am interpreting JQuery post() response correctly

Question: Writing a jquery function to check whether password user enters is already in use.
Using a blur event to send via post() value to a coldfusion page that returns 'ok' or false.
Using firebug, looks like am sending and receiving the expected data.
I'm guessing that perhaps my problem is in the return function. My first alert for resp gives correct. However, regardless the resp value (whether it is 'ok' or 'notok', I get the "else" option in the test.
Appreciate any thougts as what I wrong. (This is my first stackoverflow post, so hope I am doing this correctly!) Here is function that is called on the "ready". As I said, the jquery blur and the post seem to be correctly functioning. (I also used get() with same result.)
function setAjaxCk() {
$('#password').blur(function(){
    var myVal = $('#password').val();
    if (myVal.length < 1){
        return false;
    }
    $.post("ajxTest.cfm",{myWord: myVal, myType: 'pw'},
          function(resp) {
              alert(resp);
              if(resp == 'ok'){
                alert('things are alright');
              } else {
                alert('a problem here');
              }
    });
    return false;
});
}

Comment: in the jquery `post` doc.
dataTypeThe type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). You should log your result in the console instead of alert so you can better see what is being returned.
Comment: @TimJoyce agreed, default doesn't go to JSON, so add json to your jQuery.post and then retry as in my answer below.
Comment: what does the server returns to you ?
Comment: Are myWord and myType already defined? Otherwise you have to put them in quotes.
Answer: put the code
 alert( Object.prototype.toString.apply(resp)  );

after it returns from the server and see its type.
also
try  if(resp.toString() == 'ok'){
Comment: did not seem to help. Same results
Comment: is the same as without the toString: ok or notok
Comment: @KeithDodd the alert is "ok" ?
Comment: @KeithDodd please upload a print screen of fiddler response
Answer: What is the dataType of the post ? JSON i assume, can you try adding datatype = JSON in your jQuery.post and then re run your code ?
Comment: I must be missing something. Not sure about your datatype suggestion. Just sending 2 value params. my CF page expecting two text values and returning a text value.
Comment: to add datatype you do this: $.post("ajxTest.cfm",{myWord: myVal, myType: 'pw'},datatype: 'json',
          function(resp) {
              alert(resp);
              if(resp == 'ok'){
                alert('things are alright');
              } else {
                alert('a problem here');
              }
    });
    return false;
});
Comment: He is referring to the data being sent back from CF, not what you are sending. try `console.log(resp);` instead of `alert();` and tell us what you get
Comment: I get a js error if do the datatype as you have it (outside the curly braces). If add it as a third param (along with myVal, myType, etc), does not change any results.
Comment: my fault i gave you the incorrect format try this : $.post("ajxTest.cfm",{myWord: myVal, myType: 'pw'},"json", function(resp) { alert(resp); if(resp == 'ok'){ alert('things are alright'); } else { alert('a problem here'); } }); return false; });
Comment: Think I'm getting confused trying a number of things :-) Using dataType. My data returning is just text. Should I use that instead of 'json'?
Comment: :) okay lets do this one by one, 1 - > change datatype to dataType as figured by @TimJoyce then re run your code see what happens, and let us know
Comment: 1. should my dataType be 'json' or 'text'? 2. Where does the dataType param go? If after my curleys as noted, get js syntax error
Comment: according to sytax i saw for post, the dataType should be after the function: (if do that with 'json', seems to bypass function. With 'text', get same result)

    $.post("ajxTest.cfm",{myWord: myVal, myType: 'pw'},
     function(resp) {
     // alert(resp);
     console.log(resp);
      if(resp == 'ok'){
     alert('things are alright');
      } else {
     alert('a problem here');
      }
  },'json');
Comment: remove json and in your original code change your if like : if(resp.toString() == 'ok') { console.log('Got it working');}else {console.log('Nope not yet');}
Comment: @mprabhat : still get same inaccurate response. Regardless whether the post response is 'ok' or 'notok', I get the "Nope, not yet choice"
Comment: below are the supported format that returned data can be dataType   From the docs [at](http://api.jquery.com/jQuery.post/) The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html), if you change your code to json then your server should also return json which I think is the correct way of handling this type of data
Comment: @mprabhat: cannot get my syntax correct for doing the json thing.

However: using resp.length, I find that the length is always 2 more than the actual length (or what it should be). ie: ok shows , and notok shows 7. Problem not seem to be in my CF plate, as get same result whether I do as a ColdFusion variable or just hardcode it.
Comment: if(jQuery.trim(resp.toString()) == 'ok') { console.log('Trailing space was the problem');} else { console.log('Nopes some other issue');} for json try this syntax $.post("ajxTest.cfm",{myWord: myVal, myType: 'pw'}, function(resp) { alert(resp); if(resp == 'ok'){ alert('things are alright'); } else { alert('a problem here'); } }); return false; }, "JSON");
Comment: @mprabhat : "WOW"; the jq trim thing seemed to take care of it! Gives the right length. Wonder what is being returned? I think doing all possible on the CF end to ensure only the text.

Did not go ahead and try the JSON addition. The trim alone seems to take care of things. Did try the JSON, but either that doesn't do anything or I am not getting it in right place for syntax.

Placing it at:
    },'JSON');
  return false;

seems only place not to cause JS error. (See my orig. code). But if use JSON there, seems to bypass my if/else check. 'text' works ok but still need the trim.
Comment: Glad it worked for you finally :), if you use JSON at both places client and server then you would be sending your response say in a variable named 'clientResponse' so in order to access that your if code should be if(resp.clientResponse == 'ok'), you can try this if you have time :).
Comment: @mprabhat
haven't used this forum before. Where mark your response about trim as answer?

Only place I see is the "1" at top of this comment series.
Answer: I know this sounds elementary, but have you tried to trim your response to make sure there are no leading or trailing whitespace characters?
Comment: did a cfenableoutputonly setting and a trim. No help


Quantify the proportion of data not explained by explanatory variables in linear regression

Question: Say I'm in a classic linear regression situation:
$Y = \beta_0X_0 + \beta_1X_1 + \dots + \beta_NX_N + \epsilon$
And that I know that my explanatory variables $X$ only explain some part of my regressand $Y$, what sort of metrics could I use to estimate the proportion of this unexplained part? I know about the fraction of variance unexplained (FVU) that can be calculated with the coefficient of determination, but after a quick search on the internet I get the feeling that it's not used that often?
I may be wrong but I'm looking for potential alternative ways of quantifying this unexplained proportion in my system.
Comment: $R^2$ is the "explained variance", and $1-R^2$ is the "unexplained variance", roughly speaking.
Answer: $R^2$ is the proportion of variance explained, at least under particular conditions, which you have.
Consequently, $1-R^2$ would be the proportion of variance left unexplained. While this metric is not as common as $R^2$ (I'd never thought of it before I saw this question), it should not cause controversy.


Uniqueness of the matrix representation of tensors

Question: Note that both maps below satisfy the universal property of the tensor product.
\begin{align*}
\mathbb{R}^2 \times \mathbb{R}^2 &\rightarrow \mathbb{R}^{2 \times 2} &\mathbb{R}^2 \times \mathbb{R}^2 &\rightarrow \mathbb{R}^{2 \times 2} \\
   \begin{bmatrix}
    a_1 \\
    a_2 \\
   \end{bmatrix} \times
   \begin{bmatrix}
    b_ 1 \\
    b_2 \\
   \end{bmatrix}
&\mapsto
   \begin{bmatrix}
    a_1 b_ 1 & a_1 b_2 \\
    a_2 b_1 & a_2 b_2 \\
   \end{bmatrix}
&\begin{bmatrix}
    a_1 \\
    a_2 \\
   \end{bmatrix} \times
   \begin{bmatrix}
    b_ 1 \\
    b_2 \\
   \end{bmatrix}
&\mapsto
   \begin{bmatrix}
    a_1 b_ 2 & a_1 b_1 \\
    a_2 b_2 & a_2 b_1 \\
   \end{bmatrix} \\
(a_i) \times (b_i) &\mapsto (c_{ij} = a_i b_j) &(a_i) \times (b_i) &\mapsto (c_{ij} = a_i b_{\tau(j)}) \text{ where $\tau = (12) \in S_2$}
\end{align*}
Similarly, for $(\sigma_1, \sigma_2, \dots, \sigma_d) \in S_{n_1} \times S_{n_2} \times \dots S_{n_d}$, the map
\begin{gather*}
K^{n_1} \times K^{n_2} \times \dots \times K^{n_d} \  \xrightarrow{\Gamma_{(\sigma_1, \sigma_2, \dots, \sigma_d)}} \ K^{n_1 \times n_2 \times \dots \times n_d} \\
(x_i^1) \times (x_i^2) \times \dots \times (x_i^d) \ \mapsto \ (c_{{i_1}{i_2}\dots{i_d}} = x^1_{\sigma_1(i_1)} x^2_{\sigma_2(i_2)} \dots x^d_{\sigma_d(i_d)})
\end{gather*} satisfies the universal property.
Are these the only maps that satisfy the universal property? Formally, is it true that:
if $K^{n_1} \times K^{n_2} \times \dots \times K^{n_d} \  \xrightarrow{\Gamma} \ K^{n_1 \times n_2 \times \dots \times n_d}$ satisfies the universal property of the tensor product, then $\Gamma = \Gamma_{(\sigma_1, \sigma_2, \dots, \sigma_d)}$ for some $(\sigma_1, \sigma_2, \dots, \sigma_d) \in S_{n_1} \times S_{n_2} \times \dots S_{n_d}$.
I asked a similar question here
Proof of unique coordinatization of tensor space once bases are chosen
but I think I confused people in how the question was stated, so I am writing it in a different way here. Thank you for any help you can offer.
Answer: No, there are many more such "tensor maps". For instance, (I think, as you didn't specify exactly which tensor product property you wanted) you can compose with any automorphism of $\mathbb{R}^{2 \times 2}$ to create a different tensor map.
For instance, for any invertible matrix $P$, $(a,b) \longmapsto P^{-1}\Gamma_{\operatorname{id},\operatorname{id}}(a,b)P$ should satisfy the property.
For a concrete example, take $P=\begin{bmatrix}0 & 1\\-1 & 0\end{bmatrix}$ and consider the map $$\begin{bmatrix}a_1\\ a_2\end{bmatrix} \times \begin{bmatrix}b_1\\ b_2\end{bmatrix} \longmapsto \begin{bmatrix} a_2b_2 & -a_2b_1 \\-a_1b_2 & a_1b_1\end{bmatrix}.$$
Comment: Thank, your map is indeed another tensor map. But not every automorphism of $R^{2 \times 2}$ will work. Do you know of a characterization of such tensor maps?


Apache2 virtual hosts order (00- before 000-)

Question: I need to load three virtual hosts in an exact order to make my configuration scheme work as expected.

default (Apache default virtualhost)
phpmyadmin (a virtualhost that serves phpMyAdmin to all pma.* subdomains)
mysite.com (my website's virtualhost)

When Apache loads the default virtualhost from /etc/apache2/sites-available, it becomes 000-default in /etc/apache2/sites-enabled so it is the first (default) virtual host that Apache tries when a request is received.
Thus, I renamed my virtualhost from phpmyadmin to 00-phpmyadmin so Apache would try, in order:
000-default
00-phpmyadmin
mysite.com

To my surprise, 00-phpmyadmin comes BEFORE 000-default!
See the output of apache2ctl -S:
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:80                   is a NameVirtualHost
     default server MY_SERVER_HOSTNAME (/etc/apache2/sites-enabled/00-phpmyadmin:1)
     port 80 namevhost MY_SERVER_HOSTNAME (/etc/apache2/sites-enabled/00-phpmyadmin:1)
     port 80 namevhost MY_SERVER_HOSTNAME (/etc/apache2/sites-enabled/000-default:1)
     port 80 namevhost mysite.com (/etc/apache2/sites-enabled/mysite.com:1)
Syntax OK

I had to rename 00-phpmyadmin to 0phpmyadmin to make it work as expected:
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:80                   is a NameVirtualHost
     default server MY_SERVER_HOSTNAME (/etc/apache2/sites-enabled/000-default:1)
     port 80 namevhost MY_SERVER_HOSTNAME (/etc/apache2/sites-enabled/000-default:1)
     port 80 namevhost MY_SERVER_HOSTNAME (/etc/apache2/sites-enabled/0phpmyadmin:1)
     port 80 namevhost mysite.com (/etc/apache2/sites-enabled/mysite.com:1)
Syntax OK

Do you know why Apache behaves this way?
Answer: ASCII code for the hyphen character is 0x2d. ASCII code for the digit zero is 0x30. Hyphen comes first.
If you ever see a file listing which appears to be sorted but has 000- before 00- your locale is probably "helping" you by skipping punctuation in its string comparison routine.
Comment: Of course... I should have thought of this! Thank you.


How should I carry out simple oracle queries from C#?

Question: I have the need to carry out a few thousand inserts into an oracle database from a C# program. What would be the best way to carry this out? I need the ability to control transactions and run queries and stored procedures. I don't have a need for a full blown ORM and guess I really just want a simple, stable DAL to run queries. Can anyone suggest such a framework?
Answer: Look at following oracle data provider for .NET
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
or else, you can look at OLEDB for Oracle.
Comment: Thanks, extra info on why to use Oracle's provider from another SO question .."Oracle has it's own ADO.NET provider for .NET now, and you should use that one instead of System.Data.OracleClient, because MS is not maintaining the System.Data.OracleClient code anymore."


How to modify the timezone options list?

Question: I have a date range field in a paragraph which is set to allow setting the timezone. Can someone suggest how I can alter the list of options used to select the TZ?
For the user profile form a simple form_alter exposes the timezone field options but when trying to alter the paragraph form I only see the timezone value already set as #date_timezone.
Possibly I can override the class used to build this list?
I could do this with JS without too much effort; but not the correct approach.
Comment: I need to check my list, but I am nearly positive there is an open issue to add an alter hook for this.
Comment: I couldn't find anything to help this but certainly could use a little helper function to do this globally. I have 2 places it shows up: 1. user profile (was easy to set with a form alter), 2: on date field in a paragraph - no answer yet. Ideally could do one alter to globally change this so was thinking override class; but can't even tell where that it.
Answer: You can do that by using HOOK_form_alter and altering the widget of the field:
<code>HOOK_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Check for your target entity form.
  // Replace 'your_entity_type' and 'your_entity_bundle' with your entity type and bundle.
  if (strpos($form_id, 'your_entity_type_your_entity_bundle') !== FALSE) {

    // Define the custom timezone options.
    $customTimezones = [
      'America/New_York' => 'America/New_York',
      'America/Los_Angeles' => 'America/Los_Angeles',
      'Europe/London' => 'Europe/London',
    ];

    foreach (array_keys($form['your_paragraph_field']['widget']) as $index) {

      // Check if the index is numeric, which indicates a paragraph item.
      if (is_numeric($index)) {

        // Alter the timezone options of the date range field.
        $form['PARAGRAPH_FIELD']['widget'][$index]['subform']['DATE_RANGE_FIELD']['timezone']['#options'] = $custom_timezones;
      }
    }
  }
}
</code>
Comment: This does not work. Possibly it is a function of the paragraph widget which is used? I am using Paragraphs (stable) and there is no paragraph IEF on the node form when the form is first loaded as it gets added later with ajax. So the node form alter is run multiple times but in none of them is there a timezone #options.
Comment: No luck finding a right way to do this so thought i would be smart and hack the system.module to add an alter to allow modifying the $zones (as should be there in the first place). All i do in my alter is remove all the non-America optgroups. It works perfectly but form submit complains it is not a valid option. This isn't standard Drupal form processing is it? I should be able to remove items from a select list without issue.
Comment: Sorry this is not working for you. How are you requesting the timezone field with the date range in the paragraphs you're using? What modules are you using?
Comment: Modules? Core plus paragraphs. This is just a basic core daterange field with timezone collection enabled. But, less specifically, this is every field in/out of a paragraph (such as the core user entity) that uses a TZ selection. Yes, on simple entity forms, it is possible to form alter; but ideally there would be an alter to just globally change this list everywhere it is used. Which i added, but for some reason throws an "illegal option" error when form is submitted.
Comment: Adding an alter in system_time_zones() does work as long as not when submitting the form. Not the proper way to do this but suggest this is due to a bug in core which might be being worked on for D10.


Why does my simple application stop

Question: I am new to learning android development and I am following this tutorial to make a small application. I just changed a bit of code. and when I click the send button, i get a prompt saying "Unfortunately this My First App has stopped." Can somebody please tell me whatever is the matter.
I replaced the code given in the tutorial (here shown as a block comment in the code of second class), and replaced by the code which is here made prominent with comments containing *.
FIRST ACTIVITY: -
package com.practice.firstapp1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import com.practice.firstapp1.R;

public class MainActivity extends Activity {

    public final static String EXTRA_MESSAGE= "com.practice.fristapp1.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /** Called when the user clicks the Send button */
    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.id1);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

}

LAYOUT OF FIRST ACTIVITY: -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/id1"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="sendMessage" />
</LinearLayout>

CODE OF 2ND ACTIVITY: -
    package com.practice.firstapp1;

    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.NavUtils;
    import android.view.MenuItem;
    import android.widget.TextView;

    public class DisplayMessageActivity extends Activity {

        @SuppressLint("NewApi")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_display_message);

            // Make sure we're running on Honeycomb or higher to use ActionBar APIs
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                // Show the Up button in the action bar.
                getActionBar().setDisplayHomeAsUpEnabled(true);
            }

            //Get the intent which invoked this activity and read its extra's data into the string named message.
            Intent intent = getIntent();
            String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

            TextView textView = (TextView) findViewById(R.id.text_view_2); //************
            textView.setText(message);//***********

            setContentView(textView);//***********
//The above three statements along with statements from its layout (which have been given *s in comments have been placed instead of the statements in the following block comment. Because I wanted to create the TextView in layout.xml and handle its work in code.

/*
    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);
*/

        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

LAYOUT OF 2ND ACTIVITY: -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".DisplayMessageActivity" >

    <TextView
        android:id="@+id/text_view_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp" />

</RelativeLayout>

ANDROID MANIFEST FILE : -
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.practice.firstapp1"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.practice.firstapp1.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.practice.firstapp1.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.practice.firstapp1.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.practice.firstapp1.MainActivity" />
        </activity>
    </application>

</manifest>

Comment: Could you post the error from the logcat please ?
Comment: have you declared the activities in manifest file? post manifest file
Comment: and you don't need this `setContentView(textView);`
Comment: @Raghunandan: I havn't done anything in the manifest file. I think it is done automatically when we are using eclipse. See here [link](http://developer.android.com/training/basics/firstapp/starting-activity.html)
**When you use the Eclipse tools to create the activity, it creates a default entry.**
Comment: @ZouZou: I don't even know what logcat is. If you can say how to, then I will.
Comment: Without seeing the logcat error result, how can we determine where the problem is?
Comment: @user2882662 you need to make an entry of the second activity is manifest which eclipse does not do for you. so i suggest you post the manifest file
Comment: @user2882662 your forget to look at the add it to manifest topic in the same link
Comment: @user2882662 post the manifest file to confirm
Comment: @user2882662 in eclipse goto windows  open perspective open other choose ddms click logcat you should see a caused by part. select and save the log to some text file. there is black button that says export log to text file at the top right. now copy paste the same here.
Comment: @user2882662 i can't seem to find anything wrong with the code  can you pls post the manifest file or confirm if you have an entry of the second activity
Answer: From your comments
I havn't done anything in the manifest file. I think it is done automatically when we are using eclipse.

Yes eclipse does add the activity to manifest if you create a new Android Activity.
Your manifest looks fine. Remove the below line
Edit 1 :
setContentView(textView);

activity_display_message.xml already has a textview and in your code you initialize your textView and set text. TextView already has a parent.
No need for setContentView(textView)
Comment: @user2882662 ok post the logcat. In Eclipse goto windows-->open perspective-->open other-->choose ddms click logcat you should see an exception post the same here and there is no harm is posting manifest file just for confirmation
Comment: Please see my two answers below for the log cat and manifest. I didnot know how to add an image in a comment.
Comment: @user2882662 run the app again select com.example.firstapp in devices top left of the screen shot posted. now check the log cat. in the logcat you see at the right a black button select the exception lines and save it to text file to a location of your choice . now copy paste the same here. and remember to edit your post not answer your question with another question
Comment: @user2882662 and remove `setContentView(textView)` and try. don't need that. i think this is your cause for as the child textview already has a parent.
Comment: @user2882662 what happens now did you remove this line `setContentView(textView)` and try? it should work
Comment: There is no com.example.firstapp in devices. Can you please try the code on your computer. It is not even runnng properly. I am getting this warning.

"[2013-11-04 01:00:40 - MyFirstApp1] ActivityManager: Warning: Activity not started, its current task has been brought to the front"
Comment: To my surprise, I have only removed the extra setContentView() and restarted the emulator, it has run properly
Comment: "@user2882662 run the app again select com.example.firstapp in devices top left of the screen shot posted. now check the log cat. in the logcat you see at the right a black button select the exception lines and save it to text file to a location of your choice . now copy paste the same here. and remember to edit your post not answer your question with another question – Raghunandan"
I didnt do any of this. I couldn't even find com.example.firstapp in devices, but it has worked properly. So it is cool now? or am I supposed to get into any logcat matters?

Why does my simple application stop


getting linking Error while creating a flyweight_pattern

Question: #include <iostream>
#include <map>
#include <string>
#include <cstdlib>

using namespace std;

class Shape
{
public :
    virtual void draw()=0;
    virtual ~Shape(){}
};

class Circle : public Shape
{
   string color;
   int x;
   int y;
   int radius;
public:
  Circle(string color){
      color = color;
   }

    void setX(int x) {
       x = x;
   }

    void setY(int y) {
      y = y;
   }

    void setRadius(int radius) {
      radius = radius;
   }
    void draw() {
     cout << "color :" << color << x << y ;
   }
};

class ShapeFactory {
public:
    static map<string, Shape*> circlemap;
    static Shape* getcircle(string color)
    {
        Shape *mcircle;
        mcircle = circlemap.find(color)->second;
        if(mcircle == nullptr) {
         mcircle = new Circle(color);
         circlemap[color] = mcircle;
        // circlemap.insert(std::make_pair(color,mcircle));
        }
        return mcircle;
    }

};

class Flyweightpattern
{
public:

    static string getRandomColor(string colors[]) {
      int m_rand = rand() % 5;
      return colors[m_rand];
   }
    static int getRandomX() {
      return (int)(rand() % 100);
   }
    static int getRandomY() {
      return (int)(rand() % 100);
   }

};

int main()
{
    string colors[] = { "Red", "Green", "Blue", "White", "Black" };

      for(int i=0; i < 20; ++i) {
         Circle *circle = dynamic_cast<Circle *>(ShapeFactory::getcircle(Flyweightpattern::getRandomColor(colors)));
         circle->setX(Flyweightpattern::getRandomX());
         circle->setY(Flyweightpattern::getRandomY());
         circle->setRadius(100);
         circle->draw();
      }

      getchar();
      return 0;
   }

I am getting the linking error during run is below :

flyweight_pattern.obj : error LNK2001: unresolved external symbol
  "public: static class std::map,class std::allocator >,class Circle
  *,struct std::less,class std::allocator > >,class
  std::allocator,class std::allocator > const ,class
  Circle *> > > ShapeFactory::circlemap"
  (?circlemap@ShapeFactory@@2V?$map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVCircle@@U?$less@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PAVCircle@@@std@@@2@@std@@A)

I have a map in the ShapeFactory class and tried to creating filling the map in the class itself but still not able to resolve the problem.
Comment: Just define the static member [example](http://cpp.sh/4cznb)
Answer: You didn't defined circlemap, it's a static member, so you should define it (and initialize) in global scope:
map<string, Shape*> ShapeFactory::circlemap = {};

Integral nonvolatile static members can be initialized in class.
Oh, and it  is not recommended to do using namespace std; in global scope, that leads to side effects.
You can write something like
using std::map;

to target selected id (map in this case), and you can write using in namespace that contains usage.
Comment: oops ,yeah i forgot to initialise it ,initialising solved the issue ,Thanks !!


Display all pages on one page in wordpress

Question: How to display all pages (different page templates) on one page
for ex : About , portfolio , resume , contact etc in one page
i want to display each page in a div in index.php
Answer: this is really simple implementation, add the below code in your index.php
Modify ID for page destiny.
you have create div´s in HTML
       <?php $page_id = XXX;  //Page ID
       $page_data = get_page( $page_id );
       //Guardar variáveis
       $title = $page_data->post_title;
       $content = apply_filters('get_the_content', $page_data->post_content);?>

      <?php echo $title; //Show title ?>

     <?php echo $content; //Show content ?>

Good Luck.
EDIT
I have not tried, but it would be something like this
     <?php
     $mypages = get_pages( array( 'child_of' => $post->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc' ) );

    foreach( $mypages as $page ) {
    $content = $page->post_content;
    if ( ! $content ) // Check for empty page
        continue;

    $content = apply_filters( 'the_content', $content );
?>

<a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo $page->post_title; ?>

<?php echo $content; ?>

    <?php
    }
    ?>

Comment: tnx for your answer , but i want to load all pages dynamiclly without using page id and display it into divs


Removing Duplicates with hook_views_prerender

Question: I have a view (filtering on content) that is returning duplicates. I am trying to used hook_view_prerender to remove those duplicates... but even after running this, I still get duplicates... Any ideas? Here's my function (and yes I know the function is running):
<code>
function customedm_views_pre_render(&$view) {
  $used_nids = array();
  if ($view->name == 'new_resources'){
    echo ('hi');
    foreach ($view->result as $row){
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
      }
    $view->result = $new_view_result;
    }
  }
</code>
Answer: This is an old question, but someone might end up here (as I did) because distinct or even aggregation does not always remove all duplicates.
In the specific example above, the $new_view_result array should have been declared outside of the loop(foreach).
Here's code that would work in Drupal 8 / 9 / 10:
<code>/**
 * Implements hook_views_pre_render().
 */
function customedm_views_pre_render(&$view) {
  if (
    $view->storage->id() == 'new_resources' &&
    $view->current_display == 'block_1'
  ) {
    $used_nids = [];
    $new_view_result = [];
    foreach ($view->result as $row) {
      if (!in_array($row->nid, $used_nids)) {
        $new_view_result[] = $row;
        $used_nids[] = $row->nid;
      }
    }
    $view->result = $new_view_result;
  }
}
</code>
Answer: You do not need to do this - simply use Distinct.
Edit the View, open the Advanced section -> Query Settings -> check the "Distinct" checkbox and save the view.
Edit:
In case you do use Distinct already, there are some cases where this can occur. Here is an issue discussing this - https://www.drupal.org/node/1765730, and this one has a code example that manipulates the result similarly to what you are trying to do - https://www.drupal.org/node/1223448#comment-4757898
Comment: I suppose I should have mentioned that the distinct box is checked, and I am still returning duplicates on my filter...
Comment: I edited my answer accordingly.
Answer: This might help https://www.drupal.org/project/views_distinct
The views distinct module has removed all duplicates from my views.


Enable auto (self)-closing tags for JSX in MDX file

Question: I am moving a website to Gatsby. For article posts, the original source was written as HTML files. I want to take advantage of using MDX for those content. However, copy-paste tons of articles from HTML to MDX produce much pain. Particularly, MDX parser usually complains about Expected corresponding JSX closing tag for ...
I wonder if prettier or any formatter can help with auto adding self-closing tags for MDX files.
Example:

Expected formatted output

// or

Answer: The Prettier MDX parser fails at parsing tags that are not self-closing, like the img in your example (playground). However, if you use the HTML parser, Prettier will add the closing / (playground).
Use the --parser option to format using the HTML parser (note that you need to do it before adding your MDX frontmatter, otherwise the HTML parser won't be able to parse the files either):
prettier --parser html --write ./my-html-files-from-wordpress

Once the elements are all (self-)closing, you can switch back to using Prettier's inferred parser (MDX for .mdx files):
prettier --write ./my-formatted-mdx-files


Simplify boolean expression, so close but yet so far

Question:
$$F(w,x,y,z) = w'y' + w'z + x' + yz + y'z'$$

The simplest form is apparently $w'y' + x' + yz + y'z'$, but for the life of me, I cannot figure out how, no matter what trick I use.
Comment: If w' and z are true, then one of w'y' or yz will be true in the second.
Comment: Consensus theorems applied to $w'y'$ and $yz$.
Comment: @Eugenebaba do you know Karnaugh's maps? This tool gives as result $w'y' + x' + yz + y'z'$ or alternatively $w'z + x' + yz + y'z'.$
Comment: @frabala it *is* true.
Comment: @frabala so I invite you to delete your comments and I will delete the mine :)
Answer: Given $$F(w,x,y,z) = w'y' + \color{red}{w'z} + x' + yz + y'z',\quad\quad (*)$$ we want to show that $F(w,x,y,z)$ reduces to  $\;w'y' +  x' + yz + y'z'.$
For this, it suffices to prove that $\color{red}{w'z}$ is covered by other terms in $(*).$
Rewrite
 $$\color{red}{w'z}=w'zxy+w'zx'y+w'zxy'+w'zx'y'.$$
Note that $w'zxy$ is covered by $yz,$ and similarly find in $(*)$ a covering term  for each of $w'zx'y,\; w'zxy',\; w'zx'y'.$
Answer: The $yz+y'z'$ terms take care of all cases where $y$ and $z$ have the same truth value, so the other terms only matter if $y$ and $z$ have different truth values. In that case we have $z=y'$, so $w'y'=w'z$ and you only need one of those equivalent (in context) terms.


user_access( ) - Printing list 'variables' you can plug into?

Question: Something I have seen many times, but never fully understood is what exactly to plug into user_access() (Want to get the correct terminology here too, do you just call them variables?). I have seen some basic ones like user_access('manager access'), manager being a made user? Another using user_access('access nodes links'), which I assume is just seeing if they can see/access the tab links on a node.
If there an easy way to get a common list of what you can plug into user_access()?
Thanks in advance
Answer: You can see all the permissions on the /admin/people/permissions page.


Show that the value is, indeed, the MLE

Question: Let $ X_1, ... X_n$ i.i.d with pdf
$$f(x;\theta)=\frac{x+1}{\theta(\theta+1)}\exp(-x/\theta), x>0, \theta >0$$
It is asked to find the MLE estimator for $\theta.$
The likelihood function is given by
$$L(\theta;x)=[\theta(1-\theta)]^{-n}\exp\left(\frac{\sum_i x_i}{\theta}\right)\prod_i (x_i+1)I_{(0,\infty)}(x_i)$$
Then, the derivative of log-likelihood will be
$$\frac{dlogL(\theta;x)}{d\theta}=\frac{-(2\theta+1)n}{\theta(1+\theta)} + \frac{\sum X_i}{\theta^2}$$
I've obtained my candidate to MLE. But, doing the second derivative of the log-likelihood, I could not conclude that it is negative so that the candidate is, indeed, the point of maximum. What should I do, in this case?
Comment: That's the *entire* point: the sign of the second derivative is relevant only at $\hat\theta$; for determining whether $\hat\theta$ is a (local) maximum, the sign is not relevant anywhere else.  I don't know what you mean by "not have a good form", but I believe that if you work through the algebra, you will find it's a particularly simple rational function of a minimal sufficient statistic $\sum X_i/n$ and the parameter $\theta$ and it can be expressed in a way that is obviously negative.
Comment: Ok, forget about the form. You are right, I was having a problem with calculus here. Thank you very much for your attention.
Comment: How did a factor of $(1-\theta)^{-n}$ appear in the likelihood when $(1+\theta)^{-1}$ appears in $f$ (as it must, to normalize it)?  Why did the sign change?  Why is the negative sign missing in the exponential? (Those look like typos; your final equation seems correct.)
Comment: Hint: You don't have to show that the second derivative is negative everywhere; you only want to evaluate it at the optimum value of $\theta$.
Comment: What do you mean by "optimum value" of theta ?
Comment: The one that maximizes the likelihood.
Comment: Ok, but it does not have a good form. And whst is the point of evaluating it at the point that I think is the MLE?
Comment: You are welcome.  Does this resolution also help you with [your other question](http://stats.stackexchange.com/questions/115987/mle-for-standard-deviation-of-n0-sigma2)?  You should be able to solve it in the same way.
Comment: Yes, I deleted it after find my huge calculus mistake
Comment: Giiovanna - it looks like you have solved this question; could you write a brief answer?
Answer: You actually don't have to show that it is a maximum in this case.
The root of the first derivative of the log-likelihood, that is the MLE, can be shown to be unique if the iid observation are considered from a random variable of the exponential family. That is, a r.v. for which the density has the form:
$f(x;\theta) = h(x)\,\exp{(s\,\theta - K(\theta) )}$
Where $h$ is a function only of the observations $x_i$, $\theta$ is called the natural parameter, $s$ is called the natural statistics and $K$ is a function only of the natural parameter.
In this case, given $X_1,..X_n$ iid with the density you have, we have
$\prod_{i=1}^n \frac{(x_i+1)}{\theta\,(1+\theta)} \exp(-x_i/\theta) \longrightarrow \prod_i (x_i+1) exp\big(-\frac{n\overline{X}}{\theta} - \log(\theta(1+\theta)) \big)$
As this random variable belongs to the exponential family the MLE is unique.
In general, for exponential families the MLE always exists, is unique, is consistent and is asymptotically normal.
EDIT: http://www.stat.purdue.edu/~dasgupta/ml.pdf is a good explanation of this, maybe a bit too mathematical, but it depends from your academic background. Otherwise, V.S.Huzurbazar, in his "The likelihood equation, consistency and the maxima of the likelihood function" (1947) explains this theory in an easier way.
Comment: These are useful observations, thank you. But: (1) You will need to generalize your definition of exponential family slightly in order to make your point--or else change the parameter from $\theta$ to $1/\theta$--because the density in question is not exactly in the characteristic form you give. It would also be of great help to any reader new to these concepts to be clear at the outset that $s$ is a function of $x$ alone. (2) The OP has found the derivative but observes the second derivative is not everywhere negative. It doesn't look like your observation directly addresses that confusion.
Answer: (The likelihood function in the question is written mistakenly, the derivative of the log-likelihood is correct).
To address the specific issue raised by the OP, we need, as mentioned in the comments, to determine whether the second derivative is negative evaluated at the MLE. The tip here is that checking this does not necessarily require to obtain a closed-form expression for the MLE -in fact, sometimes, even if we have a closed-form expression, it is advisable not to use it, but rather, exploit the first-order conditions in a different way.
And this is exactly the case here. The first-order condition eventually leads to a second-degree polynomial in $\theta$ (including the sample mean of the data as a parameter), with a single admissible root, So we have a closed-form expression for the MLE. Denoting the sample mean by $\bar x$, this expression here is
$$\hat \theta = \frac {\bar x-1 + \sqrt{\bar x^2 +6\bar x +1}}{4} >0 \tag{1}$$
Let's turn now to the issue of the sign of the 2nd derivative. The second derivative is
$$\frac{d^2logL(\theta;x)}{d\theta^2}=-n\left(\frac{2\theta+2\theta^2-(2\theta+1)^2}{\theta^2(1+\theta)^2}\right) - 2\frac{\sum X_i}{\theta^3}$$
$$\Rightarrow \frac 1n \frac{d^2logL(\theta;x)}{d\theta^2}=-\frac 1{\theta^2}\left[\frac{-2\theta^2-2\theta-1}{(1+\theta)^2} + 2\frac{\bar x}{\theta}\right] \tag{2}$$
We want the term inside the brackets in $(2)$ to be positive. Now imagine inserting $(1)$, the closed-form expression for the MLE, into $(2)$, and try to determine the sign of the exrpession...
...Instead, it is more efficient to go back to the first-order condition and eliminate the sample mean, since the MLE must satisfy:
$$\bar x = \frac{(2\hat \theta+1)\hat \theta}{(1+\hat \theta)} \tag{3}$$
Inserting $(3)$ into the bracketed expression in $(2)$ we obtain
$$[\;] = \frac{-2\hat \theta^2-2\hat \theta-1}{(1+\hat \theta)^2} + 2\frac{1}{\hat \theta}\frac{(2\hat \theta+1)\hat \theta}{(1+\hat \theta)} $$
which for sign purposes is equivalent to
$$\frac{-2\hat \theta^2-2\hat \theta-1}{(1+\hat \theta)} + 2(2\hat \theta+1) >0$$
$$\Rightarrow (4\hat \theta+2)(1+\hat \theta) > 2\hat \theta^2+2\hat \theta+1$$
which holds, since $\hat \theta >0$.
Answer: Removing the multiplicative constants that do not depend on $\theta$, the likelihood function in this case is:
$$\begin{equation} \begin{aligned}
L_\mathbf{x}(\theta)
&= \prod_{i=1}^n \frac{1}{\theta (\theta+1)} \cdot \exp \Big( - \frac{x_i}{\theta} \Big) \\[6pt]
&= \frac{1}{\theta^n (\theta+1)^n} \cdot \exp \Big( - \frac{n \bar{x}}{\theta} \Big). \\[6pt]
\end{aligned} \end{equation}$$
Thus, the log-likelihood function is:
$$\ell_\mathbf{x}(\theta) \equiv \ln L_\mathbf{x}(\theta) = -n \Bigg[ \ln(\theta) + \ln(\theta+1) + \frac{\bar{x}}{\theta} \Bigg] \quad \quad \quad \text{for all } \theta >0.$$
I will write the derivatives of this function out in a form that is useful for finding the critical points and then finding the second derivative at those critical points:
$$\begin{equation} \begin{aligned}
\frac{d \ell_\mathbf{x}}{d \theta}(\theta)
&= -n \Bigg[ \frac{1}{\theta} + \frac{1}{\theta+1} - \frac{\bar{x}}{\theta^2} \Bigg] \\[6pt]
&= -n \Bigg[  \frac{2\theta + 1}{\theta(\theta+1)} - \frac{\bar{x}}{\theta^2} \Bigg] \\[6pt]
&= - \frac{n}{\theta^2} \Bigg[ \frac{(2\theta + 1)\theta}{\theta+1} - \bar{x} \Bigg], \\[6pt]
\frac{d^2 \ell_\mathbf{x}}{d \theta^2}(\theta)
&= -n \Bigg[ - \frac{1}{\theta^2} - \frac{1}{(\theta+1)^2} + \frac{2\bar{x}}{\theta^3} \Bigg] \\[6pt]
&= -n \Bigg[ - \frac{(\theta+1)^2 + \theta^2}{\theta^2 (\theta+1)^2} + \frac{2\bar{x}}{\theta^3} \Bigg] \\[6pt]
&= -n \Bigg[ - \frac{2 \theta^2 + 2 \theta + 1}{\theta^2 (\theta+1)^2} + \frac{2\bar{x}}{\theta^3} \Bigg] \\[6pt]
&= -n \Bigg[ \frac{(2\theta+1)(\theta+1) - \theta}{\theta^2 (\theta+1)^2} - \frac{2\bar{x}}{\theta^3} \Bigg] \\[6pt]
&= \frac{n}{\theta^3} \Bigg[ \frac{[(2\theta+1) - \theta]\theta}{\theta+1} - 2\bar{x} \Bigg] \\[6pt]
&= \frac{n}{\theta^3} \Bigg[ \frac{(2\theta+1) \theta}{\theta+1} - \bar{x} - \frac{\theta^2}{\theta+1} - \bar{x} \Bigg] \\[6pt]
&= - \frac{1}{\theta} \frac{d \ell_\mathbf{x}}{d \theta}(\theta) - \frac{n}{\theta^3} \Bigg( \frac{\theta^2}{\theta+1} + \bar{x} \Bigg). \\[6pt]
\end{aligned} \end{equation}$$
From this form, we see that at any critical point we must have:
$$\begin{equation} \begin{aligned}
\frac{d^2 \ell_\mathbf{x}}{d \theta^2}(\theta)
&= - \frac{n}{\theta^3} \Bigg( \frac{\theta^2}{\theta+1} + \bar{x} \Bigg) < 0. \\[6pt]
\end{aligned} \end{equation}$$
Since every critical point is a local maximum, this means that there is a unique critical point that is the MLE of the function.  Thus, the MLE is obtained by solving the equation:
$$\bar{x} = \frac{(2 \hat{\theta} + 1) \hat{\theta}}{\hat{\theta} + 1}
\quad \quad \quad \implies \quad \quad \quad
2 \hat{\theta}^2 + \hat{\theta} (1-\bar{x}) - \bar{x} = 0.$$
This is a quadratic equation with explicit solution:
$$\hat{\theta} = \frac{1}{4} \Bigg[ \bar{x} - 1 + \sqrt{\bar{x}^2 + 6 \bar{x} + 1} \Bigg].$$

Show that the value is, indeed, the MLE


how to find the first negative term in an AP

Question: If $a$ is the first term and $-d$ is common difference then $n^{\textrm{th}}$ term is $a+(n-1)(-d)$.
Now if in this AP if we are asked what will be the first negative term then how does $a+(n-1)(-d)<0$ give the answer?
I mean why is it giving the first negative term why not any other negative term?
Comment: Arithmetic progressions are monotonic, meaning they are either always increasing or always decreasing. Your common difference is negative, so this sequence is always decreasing. Solving for $n$ in your inequality will give an inequality bound on $n$ where all $n$ satisfying that will give negative terms. Then the smallest $n$ satisfying that inequality should give the first negative term.
Comment: Is there any reason why we are getting the smallest value of 'n'?
Comment: Solving this sort of linear inequality always produces a solution set which is a half-line $(c,\infty)$. Every integer larger than $c$ is in the solution set, and there is a smallest integer in the set (the first integer to the right of $c$).
Answer: It doesn't give the first negative term. It gives all values of $n$ which produce negative terms. If you continue, you have
$$a + (n-1)(-d)< 0$$
$$(n-1)(-d)< -a$$
$$n-1 > \frac{-a}{-d}=\frac ad\tag{assuming $d>0$, so $-d<0$}$$
$$n > 1 + \frac ad$$
Every positive integer greater than $1+\frac ad$ will produce a negative term. The first such integer will produce the first negative term, and all terms thereafter will also be negative.
For example, if $a=1$ and $d=2$, then you get $n>1+1/2=1.5$, so the positive integers satisfying $n>1.5$ are $2,3,4,5,\cdots$ and the first of these is $2$; so the second term is the first negative term.
You can verify this by observing that the corresponding progression is
$$1, \underbrace{-1}_{2^{\textrm{nd}}\textrm{ term}}, -3, -5, -7, \ldots$$
Comment: oh i got it thanks man :)


Getting AAD App access token to call Azure App service with client secret

Question: I am writing a Nodejs CLI to Deploy AAD-Auth Protected Web API via Azure ARM template. Facing issues in getting Access-Token to invoke the Web API.
I have used adal-node library to generate access token using AAD-App clientID and secret, but the generated token doesn't have valid objectId.
I also tried to get device_code and then tried to acquire access-token with same, but failed with error "needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it."..
However, if I go to the browser and enter https://app-service-name.azurewebsites.net/.auth/me, i am prompted to enter my azure login credentials and consent to let AAD-App access the resources, I am getting Access-token on the browser. And this access-token has all the properties (audience, issuer, objectId) i need. I am struggling to acquire similar access-token from nodejs CLI.
<code>const context = new AuthenticationContext('https://login.microsoftonline.com/my-tenant-id');
context.acquireTokenWithClientCredentials(
    aadAppIdUri, aadAppId, aadClientSecret, (err: Error, result: any) => {
        if (err) {
            reject(err);
        } else {
            resolve(result.accessToken);
        }
    });
</code>
I want to invoke the AAD-Protected web api from my Node CLI with valid Access-Token. Kindly help me generate the Access-Token for this.
Answer: The way you get the access token via client credentials need application permission.
The way you get the access token via login credentials need delegated permission.
Make sure you have the needed application permission for your app.

Also, remember to click grant admin consent button.


Observed and estimated proportions differ with binomial GLM - which to present?

Question: Using the predict() command in R, I have been able to calculate estimates (av2) and se-intervals (upper, lower)for my data below. The calculated proportion (av2) is different from the observed proportion (av1) - so 1. I'm not sure why this is? When writing up the experiment which should I quote and graph? Data and working are below.
A<-c(10,10,10,10,10,10,19,19,19,19,19,19)
B<-c("0","1","2","0","1","2","0","1","2","0","1","2")
C<-c("-ve","-ve","-ve","+ve","+ve","+ve","-ve","-ve","-ve","+ve","+ve","+ve")
Dead<-c(1,1,27,0,6,18,2,10,23,0,14,21)
Alive<-c(29,32,2,22,19,4,28,22,3,20,11,0)
Total<-Dead+Alive
gaf<-data.frame(A,B,C,Dead,Alive,Total)

mod2<-glm(cbind(Dead,Alive)~A+B+C, family=binomial)

p<-predict(mod2,newdata=gaf,se.fit=TRUE)
up<-with(p,fit+se.fit)
low<-with(p,fit-se.fit)
invLink<-family(mod2)$linkinv
av2<-with(p,invLink(fit))
upr<-invLink(up)
lwr<-invLink(low)
av1<-Dead/Total

round(av1, digits=2)
# 0.03 0.03 0.93 0.00 0.24 0.82 0.07 0.31 0.88 0.00 0.56 1.00 # observed

round(av2, digits=2)
# 0.01 0.11 0.83 0.02 0.19 0.90 0.03 0.33 0.95 0.07 0.49 0.97 # estimate

round(upr, digits=2)
# 0.02 0.15 0.88 0.03 0.26 0.94 0.06 0.40 0.97 0.12 0.57 0.98 # upper and lower se

round(lwr, digits=2)
# 0.00 0.08 0.76 0.01 0.14 0.86 0.02 0.26 0.92 0.04 0.41 0.96

Answer: Of course the predicted values differ from the observed ones: you fitted a model that imposes all kinds of restrictions, which the original data does not have to follow. Specifically, your model assumes that there is no interaction between the predictors: the effect of variable A is the same regardless of the value of B and C, and similarly of the other variables.
If you do want a perfect fit, you have to fit a saturated model with all interaction terms:
mod3 <- glm(cbind(Dead,Alive)~A*B*C, family=binomial, data=gaf)
round(predict(mod3, type="response"), 2)
 #0.03 0.03 0.93 0.00 0.24 0.82 0.07 0.31 0.88 0.00 0.56 1.00

On the other hand, doing this completely obliterates the whole point of modeling - you could have calculated the standard error for each row separately. Try running the model on, say, the first row (glm(cbind(Dead,Alive)~1, family=binomial,data=gaf[1,])) - you will get exactly the same predicted value and standard error as with the saturated model.
Edit
In a paper, we often report observed proportion and the fitted proportion with confidence intervals. If the observed proportion is nowhere near the fitted proportion, then you have a bad model, which you should not be reporting.
Comment: OK thanks, but which would you include in a paper? It seems the norm to present observed data, but is this the correct thing to do if your model is testing something else? Also, when i produce the mod3, as you suggested, the standard errors for the estimates where there are 0% or 100% deaths are very large (they pretty much span from 0%-100%) - this seems odd to me, and is there any way around this? Finally, when I try running a model with 1 row I just get an error
Comment: I made edits to clarify how to run the model with only one row (you can't have any predictors), and added a comment about reporting.


apache restricting bandwidth

Question: Ive been looking around the web without much success.
I am running a local xampp (1.7.0) installation and a web app that i have developed that backups up my file and send them to an FTP server. The problem is that apache seem to be using only a limited amount of my bandwidth and i am unsure why this is happening.
It usually doesn't get above 64KB/s but i know that my current broadband will allow over 1MB/s which is a massive difference. Also if i use my FTP program to login to the server it will let me download in excess of 500KB/s. Does anyone know how i can get around this cos my backups are very big files and take hours to copy at 64KB/s?
Thanks Mic
Answer: You seem to be confusing download and upload speeds: "if i use my FTP program to login to the server it will let me download in excess of 500KB/s."
Are you perhaps on a 1Mb/64Kb ADSL or cable connection?
Comment: no im not don't worry... i am on broadband cable 100Mb/10Mb,
i did word that poorly though. If i can download and upload from that server at 500KB/s then why can apache not do the same?

apache restricting bandwidth


How to show pop up dialog only for first visit?

Question: I have created one pop-up div on my web page. I wanted to show it only on the first load, but not for any other page load.
Below is the JS code and the HTML.  I tried many ways like localstorage and cookies, but failed.

$(document).ready(function() {
  var id = '#dialog';
  var maskHeight = $(document).height();
  var maskWidth = $(window).width();
  $('#mask').css({
    'width': maskWidth,
    'height': maskHeight
  });
  $('#mask').fadeIn(500);
  $('#mask').fadeTo("fast", 0.9);
  var winH = $(window).height();
  var winW = $(window).width();
  $(id).css('top', winH / 2 - $(id).height() / 2);
  $(id).css('left', winW / 2 - $(id).width() / 2);
  $(id).fadeIn(1000);
  $('.window #close').click(function(e) {
    e.preventDefault();
    $('#mask').hide();
    $('.window').hide();
  });
  $('#mask').click(function() {
    $(this).hide();
    $('.window').hide();
  });
});

<img src="<?=base_url()?>front/images/mobile_pop_bg.png"   alt="get ealaniah mobile app" title="get mobile app" >

Comment: The problem with doing saving anything on client side, is that the user can  reset that information. So your pop-up will show up more than once. If you truly want to only show the popup once you will need server side persistence storage to say if it has showed for the user or not.
Comment: Thank you GH9 & Rino Raj the answers from you both are working for me.I opted one method form it.
Answer: jQuery(window).load(function() {
  if (sessionStorage.getItem('dontLoad') == null))
    // code to show popup
    sessionStorage.setItem('dontLoad', 'true');
  }
});

The sessionStorage property allows you to access a session Storage object. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.
FIDDLE DEMO
Answer: var Foo = function(){

     var hasShownLocalStorageName = 'bob';
     this.HasShown = function() {
          localStorage.getItem(hasShownLocalStorageName) || false
     };
     this.SetShown = functioN(){
          localStorage.setItem(hasShownLocalStorageName ,true);
     };

}

usage
if (Foo.HasShown())
{
//do popuplogic
Foo.SetShown()
}

With the caveat that the user can reset your localstorage anytime. But the same basic principle applies if you use a cookie.
Comment: Thank you for the helping answer.Your method is working for me.


Formatar texto de JLabel com cores diferentes

Question: Como eu poderia formatar com "propriedades" diferentes um JLabel e o seu conteúdo?
Por exemplo, eu queria poder setar uma cor pro texto do meu JLabel, e outra pra string que esta concatenada com ele. É possível?
No meu caso, ele ficou de um "jeito" só, e o html que eu tentei usar, também não deu certo.
O que eu tentei:
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Teste extends JFrame {

    public static void main(String[] args) {
        new Teste().setVisible(true);
    }

    private JPanel painel = new JPanel();

    private Font fonte = new Font("SansSerif", Font.BOLD, 15);
    private JLabel label = new JLabel();

    private String string = "string";

    public Teste() {

        setSize(500, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        painel.add(label);
        add(painel);

        label.setText("Label + " + " " + string + " ");
        label.setFont(fonte);
        label.setForeground(Color.red);

    }
}

Answer: Para o efeito que você quer funcionar. Todo o texto do JLabel tem que estar dentro do .... Qualquer coisa que você coloque fora disso vai dar errado.
Por exemplo:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TesteCor {

    public static void main(String[] args) {
        EventQueue.invokeLater(TesteCor::executar);
    }

    public static void executar() {
        JFrame frame = new JFrame();
        JPanel painel = new JPanel();

        Font fonte = new Font("SansSerif", Font.BOLD, 15);
        JLabel label = new JLabel();

        frame.setSize(500, 200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        painel.add(label);
        frame.add(painel);

        label.setText(""
                + ""
                + "Cor padrão "
                + "Vermelho "
                + "Azul "
                + "Verde "
                + "Amarelo "
                + "");
        label.setFont(fonte);
        label.setForeground(Color.pink);
        frame.setVisible(true);
    }
}

Observe que coloquei o Color.pink como o foreground do label.
Quanto ao EventQueue.invokeLater, veja essa minha outra resposta que o explica.
Eis o resultado:
Answer: Não é possível fazer isso usando JLabel, esse componente é para texto puro. Claro que ele aceita tags HTML para formatação de texto, mas além de "emporcalhar" o código, vai tornar bem difícil a manutenção depois.
Felizmente existem alternativas de componentes para este fim, que é o caso do JTextPane ou JEditorPane, que aceitam estilização de texto, mesmo que fragmentados, como você precisa.
Veja este exemplo:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;

public class JTextPaneExample {

    public void createAndShowGUI() {
        JFrame f = new JFrame("JTextPaneExample");

        // cria um StyleContext e um Document para o jtextpane
        StyleContext sc = new StyleContext();
        final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
        JTextPane pane = new JTextPane(doc);
        pane.setEditable(false);

        // cria um estilo e adiciona atributos personalizados nele
        final Style redStyle = sc.addStyle("RED", null);
        redStyle.addAttribute(StyleConstants.Foreground, Color.red);
        redStyle.addAttribute(StyleConstants.FontSize, new Integer(16));

        final Style blueStyle = sc.addStyle("BLUE", null);
        blueStyle.addAttribute(StyleConstants.Foreground, Color.blue);
        blueStyle.addAttribute(StyleConstants.FontSize, new Integer(14));
        blueStyle.addAttribute(StyleConstants.Bold, new Boolean(true));

        try {
            // insere um texto inicial com uma style
            doc.insertString(0, "Texto inicial ", redStyle);
            // insere texto concatenado com outra style
            doc.insertString(pane.getText().length(), "texto concatenado", blueStyle);
        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }

        f.getContentPane().add(new JScrollPane(pane));
        f.setSize(400, 300);
        f.setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            new JTextPaneExample().createAndShowGUI();;
        });
    }
}

Que resulta em:

Um StyleContext é nada mais que um pool de estilos, onde adicionaremos os estilos que usaremos no componente. O DefaultStyledDocument é a classe que interpretará estes estilos e aplicará ao texto, conforme concatenamos e passamos os estilos para os fragmentos de textos. A interface Style é o estilo em si, onde configuramos detalhes como cor, tamanho e tipo de fonte que queremos do texto.

Referências:

JTextPane Styles Example 1 : TextPane « Swing JFC « Java
Different font color in a JTextField
How to Use Editor Panes and Text Panes


Simple WordPress Membership - PHP login button - how do I redirect to a specific page

Question: I am really new to PHP and am currently trying to add a redirect to a specific page to a login button.
The code currently looks like the below:

<form id="swpm-login-form" name="swpm-login-form" method="post" action="">

            <?php echo SwpmUtils::_('Username') ?>

            <input type="text" class="swpm-text-field swpm-username-field" id="swpm_user_name" value="" size="25" name="swpm_user_name" />

            <?php echo SwpmUtils::_('Password') ?>

            <input type="password" class="swpm-text-field swpm-password-field" id="swpm_password" value="" size="25" name="swpm_password" />

            <input type="checkbox" name="rememberme" value="checked='checked'">
             <?php echo SwpmUtils::_('Remember Me') ?>

            <input type="submit" class="swpm-login-form-submit" name="swpm-login" value="<?php echo SwpmUtils::_('Login') ?>"/>

            <a id="forgot_pass" class="swpm-login-form-pw-reset-link"  href="<?php echo $password_reset_url; ?>"><?php echo SwpmUtils::_('Forgot Password') ?>?

            <a id="register" class="swpm-login-form-register-link" href="<?php echo $join_url; ?>"><?php echo SwpmUtils::_('Register to submit your listing.') ?>

            <?php echo $auth->get_message(); ?>

</form>

Looking at some other files I think I need to add something like  somewhere, but I don't know where this is supposed to go (and I may be completely wrong).
Many thanks in advance!
Kat
Comment: submit buttons don't "redirect" anything. they submit a form to whatever url is specified in the parent `` tag's `action` attribute.
Comment: Thank you, Marc!

I have this bit of code at the beginning of my file:

Does this mean I have to add something to the "action" bit to get taken to the correct page after the form was submitted?
Answer: According to your comment, your action is set to "", meaning form is calling the same file it's located in. Your provided form action does not really help since it's not the source we should be looking for.
To redirect to your desired page, you need to find a part where if ($_POST[]) is. Check if if statement is true (by checking if form's field name(s) match(es) if conditional like this $_POST['fieldNameHere']. You can also use exit() to see if that's the correct part of file.
After that, add at the end (or edit already existing one) header("Location: yourNewPage.php");. This will redirect user to your specified file but note that it is most likely already been defined through method or another function.


Xcode Error signing Failed to create provisioning profile and No profiles for 'com.photo.appwall' were found

Question: I am having issues signing my application.

Failed to create provisioning profile.
No profiles for 'com.photo.appwall' were found.
Comment: Do you have access to an iOS device?  If so, plug one into your Mac and build the app to it.  Xcode will add the device to your development provisioning profile.  If you don't have any iOS devices, it is a bit more complicated.  Is this a paid Apple developer account?
Comment: it can be helpful to you. https://stackoverflow.com/questions/64133060/xcode-signing-failed-to-create-provisioning-profile
Answer: The error message seems self explanatory: you need to register your test device on the Apple's developer portal.

Log in Apple's Developer portal
Click Certificates, IDs & Profiles
Click Devices | All
Click the + button and add your device UDID

Xcode should be able to do this for you if you plug your device with your computer then select it in menu:

(Xcode 8) Window | Devices
(Xcode 9) Window | Devices and Simulators


irreducible representations of $GL_2$ over $p$-adic field

Question: Let $E$ be a finite extension of $\mathbf{Q}_p$. In class we stated the following fact :
Every irreducible algebraic representation of $GL_2(E)$ is of the form
$$
\mathrm{Sym}^{k-2}(E^2) \otimes_E {\det}^m
$$
for $k \geq 2$ and $m \in \mathbf{Z}$
Questions :
1) What does algebraic mean here ?
2) do you know a reference ?
Comment: I would guess algebraic means that it needs to be a representation of this as an algebraic group (these are also called rational representations). As for a reference, it follows from the general results in Jantzen's book on algebraic groups, though that may well be overkill (and the exposition there is aimed at working in positive characteristic with an algebraically closed field, so there are almost certainly better sources more concerned with the $p$-adic case).
Comment: A word of warning: That book has some pretty heavy prerequisites.
Answer: To confirm what Tobias said, "algebraic" in this case means a homomorphism of algebraic groups $GL_2(E)\rightarrow GL_N(E)$ for some $N$, i.e. a group homomorphism defined via polynomial functions. A slight word of warning: in the earlier years of the subject, an "algebraic representation" of a $p$-adic group such as $GL_2(E)$ meant something very different to this (what's now usually called a smooth representation).
As for the most straightforward proof that I can think of, let me sketch out how you can do this by first considering $SL_2(E)$. Let me cover myself by saying that I haven't thought very carefully about the details, but I don't think that anything should go wrong; maybe some things will just be a bit harder than I'm claiming.
A fairly well-known result is the classification of the finite-dimensional irreducible complex representations of the Lie algebra $\frak{sl}_2(\Bbb{C})$, which is via looking at highest weights. This leads to the result that the irreducible representations are precisely the representations $Sym^{k-2}(\Bbb{C}^2)$. In fact, this holds more generally: one obtains the same classification of the $k$-representations of ${\frak{sl}}_2(k)$ for any field $k$ of characteristic $0$: see here, for example.
The algebraic group $SL_2(E)$ has a Lie algebra defined in a way reasonably analogous to the usual definition (the tangent space at the identity identifies with derivations and inherits a Lie bracket), which leads to the usual result that it's Lie algebra is ${\frak{sl}}_2(E)$ as above, namely the Lie algebra of 2x2 traceless matrices over $E$. Then by the usual argument of "differentiating" an irreducible algebraic representation of $SL_2(E)$, one obtains an irreducible representation of ${\frak{sl}}_2(E)$. So one needs only to classify the irreducible representations of ${\frak{sl}}_2(E)$, and then note that every such representation arises via "differentiation", in order to classify the irreducible algebraic representations of $SL_2(E)$.
It then remains to extend this classification to $GL_2(E)$ (in a general setting, this is fairly common: $GL_2$ is a reductive group with derived subgroup $SL_2$. The group $SL_2$ is semisimple, and so a bit easier to work with as one doesn't really have to worry about the centre, and the representation theories of the two groups are closely related). Let me write $V(k)$ for the representation $Sym^{k-2}(E^2)$ of $SL_2(E)$. Since the action of $SL_2(E)$ on $E^2$ clearly extends to an action of $GL_2(E)$ (which obviously remains algebraic), $V(k)$ extends to a representation of $GL_2(E)$ for any $k\geq 2$. This means that any irreducible representation of $GL_2(E)$ which contains $V(k)$ upon restriction to $SL_2(E)$ must be isomorphic to $V(k)\otimes\chi$, where $\chi$ is some irreducible representation of $GL_2(E)/SL_2(E)\simeq G_m(E)$, viewed as a representation of $GL_2(E)$ via inflation. It's easy to see that the only such $\chi$ are the powers of $\det$: use the classification of characters of $G_m(E)$ (it's a split torus of rank 1 so they are precisely the characters $x\mapsto x^m$ for $m\in\Bbb{Z}$) and then note that inflating to $GL_2(E)$ means pulling back through $\det$, so $\chi$ is of the form $x\mapsto\det(x^m)$, i.e. $\chi=\det^m$.
Comment: That is an absolutely fantastic answer. Thank you so very much !! (P.S. I can't upvote because i'm not a registered user)
Comment: You're welcome!
Comment: It is interesting to note that characteristic $0$ is also used in the step from the group to the Lie algebra (or rather, for the step back again), since this step fails in positive characteristic, where the Lie algebra can only "detect" the representations of the first Frobenius kernel (the fix is to consider the algebra of distributions instead, which coincides with the enveloping algebra of the Lie algebra in characteristic $0$).


GroupControl - BackColor não muda

Question: Estou utilizando um GroupControl da DevExpress 16.1, porém ao tentar mudar a cor de fundo (backcolor) o mesmo continua com a cor default, alguem sabe o motivo? ou se estou fazendo errado?
        //
        // groupControl2
        //
        this.groupControl2.Appearance.BackColor = System.Drawing.Color.DarkRed;
        this.groupControl2.Appearance.Options.UseBackColor = true;
        this.groupControl2.Location = new System.Drawing.Point(346, 314);
        this.groupControl2.Name = "groupControl2";
        this.groupControl2.Size = new System.Drawing.Size(308, 156);
        this.groupControl2.TabIndex = 60;
        this.groupControl2.Text = "Fiscal";

Answer: Seguinte, para usar o backcolor, é necessário definir a propriedade LookAndFeel.UseDefaultLookAndFeel como false e a propriedade LookAndFeel.Style para Flat.

GroupControl - BackColor não muda


Given a triangle's circumcenter, incenter, and foot of one inner bisector, construct its vertices

Question:
Wernick's list problem number 82: The goal is to construct, with a straightedge and compass only, vertexes of $\triangle ABC$ but we're only given:

its circumcenter, $O$

its incenter, $I$

its foot of the inner bisector of vertex $A$ on side $BC$, $T_a$.

I draw line $IT_a$ for this is the inner bisector. And that's kinda it. These points are very unrelated. I thought about finding the contact point of the incircle with side $BC$ but this point also has no relation with $O$.
$O$ and $H$ are isogonal conjugates but this doesn't help much
Answer: It seems that although this problem is solvable (i.e. constructable), there is no simple construction.
The paper Wernick's List: A Final Update, which is a survey whether the problems in Wernick's list are solvable or not explains:

[I]t is theoretically possible to extract a construction [$\dots$], but it
is very difficult to obtain and [$\dots$] is geometrically unappealing

In Example 2, this is explained for Problem 108:

Recall that it is possible to perform additions, multiplications,
divisions and root extract by using ruler and compass constructions.
This construction might not be elegant, but it is perfectly valid

So in theory, it is possible to construct Problem 82, but this would involve using a ruler and compass for arithmetic operations and square radicals, which seems out of the spirit of synthetic constructions.
They don't rule out the possibility of an elegant construction, but based on what they say I'd advise you to not spend a lot of time looking for one because even automated geometry solvers have come up empty handed so far.
There is a compendium of automatically generated constructions for Wernick's list at http://poincare.matf.bg.ac.rs/~vesnap/animations/compendiums.html. The construction for $O, T_a, I$ is notably non-existent.
Comment: Even I was thinking the same but assumed that I may be lacking knowledge regarding that. Also, thanks for the links.


pandas: unstack rows into new columns

Question: i have a df that looks like this:
     a        date    c
0  ABC  2020-06-01  0.1
1  ABC  2020-05-01  0.2
2  DEF  2020-07-01  0.3
3  DEF  2020-01-01  0.4
4  DEF  2020-02-01  0.5
5  DEF  2020-07-01  0.6

i would like to "unstack" column 'a' so my new df looks like this
     a       date1   c1        date2   c2        date3   c3        date4   c4
0  ABC  2020-06-01  0.1   2020-05-01  0.2          nan  nan          nan  nan
1  DEF  2020-07-01  0.3   2020-01-01  0.4   2020-02-01  0.5   2020-07-01  0.6

how can i do this?
Answer: Use GroupBy.cumcount for helper counter for MultiIndex and reshape by DataFrame.unstack, then for correct order is used DataFrame.sort_index with map for flatten MultiIndex:
df = (df.set_index(['a',df.groupby('a').cumcount().add(1)])
        .unstack()
        .sort_index(axis=1, level=[1, 0], ascending=[True, False]))
df.columns = df.columns.map(lambda x: f'{x[0]}{x[1]}')
df = df.reset_index()
print (df)
     a       date1   c1       date2   c2       date3   c3       date4   c4
0  ABC  2020-06-01  0.1  2020-05-01  0.2         NaN  NaN         NaN  NaN
1  DEF  2020-07-01  0.3  2020-01-01  0.4  2020-02-01  0.5  2020-07-01  0.6

Or if sorting is not possible because different columns names one idea is use DataFrame.reindex:
df1 = df.set_index(['a',df.groupby('a').cumcount().add(1)])
mux = pd.MultiIndex.from_product([df1.index.levels[1], ['date','c']])
df = df1.unstack().swaplevel(1,0, axis=1).reindex(mux, axis=1)
df.columns = df.columns.map(lambda x: f'{x[1]}{x[0]}')
df = df.reset_index()
print (df)
     a       date1   c1       date2   c2       date3   c3       date4   c4
0  ABC  2020-06-01  0.1  2020-05-01  0.2         NaN  NaN         NaN  NaN
1  DEF  2020-07-01  0.3  2020-01-01  0.4  2020-02-01  0.5  2020-07-01  0.6

Comment: thanks. what if i have another column which for each group in 'a' has only 1 unique value and i want to keep this column but not  "dupe" it?
Comment: @idt_tt then change `df.set_index(['a',df.groupby('a').cumcount().add(1)])` to `df.set_index(['a','col', df.groupby(['a', 'col1'] ).cumcount().add(1)])`

pandas: unstack rows into new columns


Recorders and Musical scores

Question: I'm new to recorders and I do not know much about it. I have a soprano recorder by Yamaha.
I really enjoyed a composition by handel, specifically the recorder sonata.
I would like to know whether the musical scores written for recorders are suitable for all types of recorders (like soprano, alto, etc.)?
In particular, is it possible to play handel's recorder sonata with a soprano recorder?
Any response is appreciated.
Thank you
Comment: Well, have you looked at a page or two of the sheet music?  I'm assuming you don't care whether you play in the original or transposed key or register.
Comment: Related: [Recorder type for Telemann's music piece](https://music.stackexchange.com/questions/4208/recorder-type-for-telemanns-music-piece/)
Answer: No, Handel wrote his recorder sonantas for alto (treble) recorder which has a range from F (first space in the treble clef) to the G 2 octaves and a tone above. Your soprano won't play that high, so you are out of luck playing the music as written.
You could transpose the notes down a fourth (i.e. A sonata in F becomes a sonata in C) which will bring it into range on the soprano, but because the soprano sounds an octave higher than written, the music will sound a fifth above what the composer intended. You will also need to transpose the continuo part if you plan to play with piano or harpsichord. The sonata won't sound as good as when played on the alto - a little high and screechy.
My recommendation is to move to the alto recorder as soon as practicable. The bulk of the Baroque repertoire is written for alto, and a lot of transverse flute music is also playable on the alto. You could try listening to Telemann and Marcello. They both wrote good stuff for the alto.
Comment: Also, the soprano is higher than the alto, its range is C5-D7, the alto is F4-G6. "Transposing" simply means using alto fingerings on the smaller instrument, pretending it is an alto. Since Eric doesn't know alto fingerings this is not an option for him however.
Comment: Yep.  I'd just point out that playing alto music on a soprano means transposing up a fifth, not down a fourth, no matter how you write it.
Answer: If you can't use the instrument/fingerings Handel thought you'd use, you won't have an easy time of it. I suggest buying an Yamaha alto recorder and start learning that instrument's fingerings. IMHO it's a better choice for adult beginners. There are many easier bits in those sonatas to help you practice.
Answer: It really depends, you might be. If there are no notes below the range of the soprano recorder, then go on and play it, it will sound approximately the same. I play alto sax and am able to play multiple tenor sax pieces on it since most of the notes overlap. If some of the notes are too low, you will have to transpose, though.
Comment: @Ira I.I. The weirdness I am referring to is the need to make octave jumps when the music goes above a written D6. For instance, a written interval of D6 to E6 (major 2nd) will become D6 to E5 (a seventh - with the soprano sounding all these notes up an octave). The composer certainly did not intend those sorts of jumps. A fully transposed version will not suffer from this - it will just sound a little high.
Comment: The other difficulty for new soprano recorder players is that the notation for soprano recorder lines are often just notated as treble clef, when really it's treble-8up. Alto, however ,is always straight treble, so its has many notes well above the staff with 2 and 3 ledger lines; unfamiliar territory for soprano players. So it's the highest notes on the page they can't finger as written although they could if re-written into the correct octave.
Comment: @Ira I.I.  There are lots of notes in Handel sonatas that are outside the soprano range. Recorders have a limited range of just two octaves and a tone. Handel and his contemporaries recognized this and wrote to fit the alto recorder range. It is not practical to transpose some notes down an octave. It would sound very weird. And it is not possible to transpose all notes down an octave, as this would exceed the low register. I suggest you reconsider your answer.
Comment: @kiwiron thank you! I didn't know all this, as I have zero experience whatsoever with recorders, I just answered using common sense. Also, why would the transposed version sound weird? The intervals stay the same, don't they?

Recorders and Musical scores


Convert GML file to adjacency matrix in matlab

Question: I have a GML file of a directed graph (Political blogs). I want to use this graph in Matlab as an adjacency matrix. How can I convert it?
Thanks.
Answer: There is a sample code here for this purpose:
%Extracting edges from gml file graph
fileName = 'dolphins.gml';
inputfile = fopen(fileName);
A=[];
l=0;
k=1;
while 1
      % Get a line from the input file
      tline = fgetl(inputfile);
      % Quit if end of file
      if ~ischar(tline)
          break
      end
      nums = regexp(tline,'\d+','match');
      if length(nums)
          if l==1
              l=0;
              A(k,2)=str2num(nums{1});
              k=k+1;
              continue;
          end
          A(k,1)=str2num(nums{1});
          l=1;
      else
          l=0;
          continue;
      end
end

A[], an [m x 2] matrix, contains the links between nodes.
Comment: Thanks again,I wanted to check it and compare the result because the number of edges was different from  the result of gephi graph software but I think there are some parallel links(https://gephi.org/) The Matlab code works.
Comment: Thanks to answer to newcomer :) .I check the code it seems to work.But Online converter loading till now and I don't see the result in it!!!
Comment: @Fatime, you're right. I tried the online converter myself and it stuck at something. But I think it's better to parse your graph inside MATLAB rather than relying on an online one.
Answer: With R you can use:
library("multiplex") ## >v1.5
read.gml(file, as="matrix")


Quartz Cron Expression for running a job every 5 hours from a given time

Question: I am using Quartz library for scheduling. I have to schedule a job every 5           (could be variable) hours from a given time.
I tried using the following expression -
0 0 12/5 1/1 * ? *
I checked the output of future runs at Cronmaker.
Schedule Start Time -> Tuesday, June 21, 2017 10:30 AM
Future runs -

Wednesday, June 21, 2017 12:00 PM
Wednesday, June 21, 2017 5:00 PM
Wednesday, June 21, 2017 10:00 PM
Thursday, June 22, 2017 12:00 PM

The expression does what it is asked but I was hoping that the 4th run would be 5 hours in addition to the 3rd run i.e something along these lines -

Wednesday, June 21, 2017 12:00 PM
Wednesday, June 21, 2017 5:00 PM
Wednesday, June 21, 2017 10:00 PM
Thursday, June 22, 2017 3:00 AM

The 4th run goes to next day's 12:00 PM trigger. I want it to be added to the last run's time.
Is there any way via which this can be achieved via the cron-expression?
Comment: The correct expression is `0 0 0/5 1/1 * ? *`
Answer: CronSchedule is not the best suited one for what you want to do.
Use SimpleSchedule instead:
trigger = newTrigger()
    .withIdentity("yourJobName", "yourJobGroup")
    .withSchedule(simpleSchedule()
        .withIntervalInHours(5) // every 5 hours
        .repeatForever()) // keep going in intervals of 5h
    .startAt(dateOf(12, 0, 0)) // start at 12:00 PM
    .build();

You can find more examples in the official documentation.