Rewrite content of view field based on value

Question: On a business review page, I have a views block which shows each individual review submitted for the business. In the review form available to the user, I am using integer fields to allow the user to select their choices and to store the submitted information in the database. For instance, if a user selected in their review that the staff was "Very Helpful," then a 5 is stored in the database. This allows me to show the average value on the main business page and change the output based on php (using computed field). However, because of the way that the data is stored, the view block displays a "5" in the field for Staff Helpfulness instead of "Very Helpful."
So, the topic of the question, how can I rewrite text in a view field based on its value (i.e. replace the displayed "5" with "very helpful")?
Answer: you can rewrite the output of a field using "Rewrite the output" option in views.
In your case, you might also need php code:
ex:
   $selectedValue=5; // this you can get from the replacement tokens easily

   // this array can be populated using some db query too.
   $selectedText=array('1'=>'satisfactory','5'=>'Very helpful');

   $selectedDisplayTitle=$selectedText[$selectedValue];
   return $selectedDisplayTitle;

Hope this helps.
Let us know if you come across a better solution.
Comment: See the other suggested answer for a better explanation.
Answer: You need to create a template for your field. Field templates are extremely simple. Their content is:
<?php print $output; ?>

So you should go and change the template to something like this:
<?php
 if($output == 5) {
    print "very helpful";
  }
  else if($output == 4){...}
?>

and so on.
In the advanced section of your view hit "Theme" to see a list of available templates you can create.
If you want to do all this through drupal interface you can do it using Rewrite the output but you will need to enable another module to be able to write php code inside the box. Take a look at Views PHP, Views Custom Field. I suggest you choose the template way. Your template is fairly simple.
Comment: That's the ticket. I had already installed Views Custom Field to try and solve something else, but I haven't quite gotten it to work correctly. This was much easier.


Do they ever pull the goalkeeper in football?

Question: In ice hockey, teams that are losing will sometimes pull their goalkeeper late in the game and bring in an extra attacker to increase their chances of scoring and tying the game.
Do teams ever pull their goalie in football and bring in an extra attacker when they are losing?  Is this even allowed?
Comment: @gbianchi - this is true, but you can put an outfield player in a different shirt, and technically that's enough to make them the goalkeeper.
Comment: I'm trying to look at the rule, but you are enforce to have a goalie all the time in the field...
Comment: I've seen the Mexican national team have their goalie move forward into the attack for the final corner kick in extra-time. Unlike hockey, where the goal-tending equipment is so cumbersome, it's just easier to use the goalie, him/herself as the extra attacker, since there are no rules preventing it.  In water polo, only a goaltender may substitute for a goaltender, and the goaltender can't cross into the offensive half of the pool, but I'm not aware of similar restrictions in football/soccer.
Answer: It would certainly be allowed, but it would likely be a failed strategy in soccer.

In professional soccer, you only get 3 substitutes per game. If you burn one on pulling out your keeper, then if you accomplish your goal and tie the score, if you go to overtime, you're stuck with no keeper on the field.

So subbing in a field player for a keeper is probably a loser as it's a poor use of resources and leaves you in a bind if you succeed.
However, most keepers are capable players and can play the field in a pinch. Thus it's not hugely uncommon for you to see the keeper pushed way up in a situation where his team must score.
However, there are some good reasons to not do this in normal play:

Most soccer league regular season games aren't hugely meaningful, but it can be a lot better to lose 1-0 than it would be to lose 2-0. Which means risking a greater loss to try to tie the game is not beneficial.
Keepers aren't usually good field players. While they may be capable, and they usually have a solid kick, they aren't strikers, and at best, a keeper playing high frees up a mid or back to go up and play a striking role.
It's a long run from the defending third to the attacking one. Most of the time it doesn't make much of a difference to have an extra player on the attack (see how often a team of 10 can play even with a team of 11), so it doesn't make a lot of sense for the keeper to come forward and play a role he's relatively unfamiliar with.

Overall, this strategy can pay, especially on very late set piece opportunities, but in general, it just doesn't seem worth it.
Comment: "most keepers are capable players" -- we can thank the passback rule for that. It used to be said that the keeper is keeper because he *can't* play football. In practice though, the role of the keeper upfield might just be to have your corner-taker try to score in-off his head ;-)
Comment: in this situation, there is a complication with the offside rule that catches people out. two players are required to play an attacker onside (usually the goalkeeper and one defender). if the goalkeeper is way out of goal, two defenders are required to play an attacker onside.
Comment: @Bachrach44 many tournaments take into account goal difference, so a 2-0 loss is more damaging than a 1-0 loss.
Comment: This is probably a stupid question, but why is a 2-0 loss worse than a 1-0 loss? A loss is a loss is a loss right? Your won-loss record is still the same. Does goal differential really come into play on tiebreakers that often?
Comment: There are numerous instances of goalkeepers scoring in both domestic and international fixtures, most notably Peter Schmeichel http://en.wikipedia.org/wiki/Peter_Schmeichel
Comment: @waxeagle Ahh - tournaments. Actually makes a lot of sense there due to the small number of games. Thanks.
Answer: As has been noted, keepers do sometimes come up to act as an attacker during the game, though they are never really subbed out for another attacking player. A couple things to keep in mind from The Laws of the Game.
Players
Page 15: "A match is played by two teams, each consisting of not more than eleven
players, one of whom is the goalkeeper"
Page 16: "Any of the other players may change places with the goalkeeper, provided that:
• the referee is informed before the change is made
• the change is made during a stoppage in the match"
Equipment
Page 19: "• Each goalkeeper must wear colours that distinguish him from the other
players, the referee and the assistant referees"
So if you did substitute off a goalkeeper, the sub would have to have a different shirt, or if you swapped a field player with the goalkeeper, they would have to change jerseys. I have seen this happen when the goalkeeper is injured and the team has no more substitutes left - they'll put a midfielder or attacker (sometimes, but rarely, a defender) into goal, but the midfielder will play as a goalkeeper, not as an attacking player.
That being said, the goalkeeper is almost never subbed out except for another goalkeeper. The cost is too high.
EDIT: More often I've seen this happen when the goalkeeper gets a red card and the team has no more subs left. If the goalkeeper interferes with a player trying to score, he can get a red card and if the team has no more subs, they'll have to put a player already on the field into the goal, in which case he'll have to get a different shirt.
Comment: BTW if you want to get your bullet points on a new line (for example in your quote from page 16, where you have two of them), you can use `` or end the line with two spaces; see [here](http://sports.stackexchange.com/editing-help#linebreaks). Or you can create bulleted list using markdown, see [here](http://sports.stackexchange.com/editing-help#simple-lists). (Editor also has a button for such lists and also a shortcut Ctrl+U.)
Comment: This is the correct answer, although for all intents and purposes the goalkeeper could play outfield you need to have one player designated as goalkeeper (in a different coloured shirt to the rest of the team) on the pitch at all time.
Comment: Thanks Martin - I know about addressing bullet points. Since there were only two I figured I'd just leave 'em.
Comment: +1 for references. NB: the more common scenario is not when GK is injured, but when he's sent off.
Answer: You don't see this in soccer. If a team is desperate to score a goal, the goalie comes out of his net and plays in the middle or front. For example when there is a corner kick, the goalie could go all the way to the opposite box to score.
However, this happens often in indoor soccer. The goalie comes out at the end of the game replaced by an attacker. But this extra attacker should still be wearing a goalie's uniform, since team are required to have designated jersey for goalies and each team must have a goalie.
Answer: Yes, it does happen, although not very often. Goal difference can be important at the end of the season, so if your team was losing in a regular game, there's no point going all out to tie when the risk of conceding a goal is very high without a goalie in the net. On the other hand, during cup matches where a team is about to be put out unless they score a goal, you would often see the goalkeeper advance to the other half of the pitch for corner kicks. Two that come to mind:

Peter Schmeichel scoring for Manchester United from a corner kick
Joe Hart sprinting back to his goal when the opposition get the ball back
Comment: .. or Neuer in practically every game he plays, seriously I think he gets bored in the goal :)
Comment: Arguably the most famous example is [Jimmy Glass](https://www.youtube.com/watch?v=KejwqhLDeOs) scoring from a last-minute corner to keep Carlisle United in the Football League.
Answer: A point that hasn't been made in the other answers is that this tactic would be numerically much less effective in football than in ice hockey because of the larger teams. In ice hockey, pulling the goalie gives you six outfield players against five, which is a 20% increase over your opponent. In football, it would only give you eleven against ten, a 10% increase of manpower. So, not only is it very expensive (three substitutions in football, versus unlimited in ice hockey), it's also likely to be much less effective.
Answer: In soccer the goalkeeper can act just as another player. He can also use his hands in the penalty area, but he can play anywhere.
It is relatively usual in play-out matches that the goalkeeper goes to attack, when there is a corner kick in the last minute and they lose by just one goal. This way the goalkeeper can try to score with a header.
For instance, this is how Seville beated Shakhtar Donetsk in UEFA Cup 2007, with a goal of the goalkeeper in the last minute. You can google "palop goal" to watch it.
It is permitted to pull out the goalkeeper and put any other player in his place, if you have not made all the changes. In this case the team must decide which one is the goalkeeper. But this is not a good idea. You lose more time like this, and it will not make a big difference. You'd better change a defender.
Answer: While rare, it does happen. Generally speaking, after an intensive match players are exhausted, but that probably won't apply to the goalkeeper, so if he were a fairly good field player it may be worth for him to leave the box.
I've seen it happen (without an official role switch) during the just finished World Championship in the last minutes of one match, but I'm not sure which that was. Maybe Honduras? (see  below)
Honduras captain and championship keeper Noel Valladares said in a german interview he actually scored, albeit after officcially switching role, in their national professional league games. He says his total score is five goals!
The interview in german.
Comment: The question is about taking the goalkeeper off the pitch and replacing them with a dedicated outfield player, not just having the goalkeeper move up the field.
Answer: They don't pull their goalie, but goalies can go anywhere they want on the field, so if they need an extra attacker on a free kick or something they may bring the goalie up to take the free kick so that they can have everybody else attacking, or they may just get the goalie to participate in the attack. This strategy is only applied if the team needs to score at the end of the match, because if they lose the ball they won't have anybody back so the opposing team can just lob the ball and try to score.
tl;dr the goalie is just another player but one that has special privileges (i.e. can pick up the ball in his/her box), so they don't pull the goalie they send the goalie up onto the attack.


Como acessar o DrawerMenu no flutter de várias telas?

Question: Estou Começando um aplicação em Flutter, adicionei na minha HomePage um DrawerMenu, Funciona bem, porém quando acesso outra página, queria que o menu pudesse ser aberto de qualquer uma.
Vi alguns exemplos criando o Drawer em arquivos separados, mas não consegui por em meu projeto.
Meu Drawer:
        drawer: Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(

            child:  Image.asset("assets/quadro.jpg"),
            decoration: BoxDecoration(
              color: Colors.white24,
            ),
          ),
          ListTile(
            leading: Icon(Icons.home),
              title: Text('Home'),
              onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => HomePage(),
                ),
              );
            }),
          ListTile(
            title: Text('Item 2'),
            onTap: () {},
          ),
        ],
      ),
    )

Answer: Crie um arquivo novo chamado "CustomDrawer" e insira nele um novo Widget (pode ser o StateLess mesmo). Coloque no "return" desse widget o código do seu Drawer.
Drawer(
  child: ListView(
    padding: EdgeInsets.zero,
    children: <Widget>[
      DrawerHeader(

        child:  Image.asset("assets/quadro.jpg"),
        decoration: BoxDecoration(
          color: Colors.white24,
        ),
      ),
      ListTile(
        leading: Icon(Icons.home),
          title: Text('Home'),
          onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HomePage(),
            ),
          );
        }),
      ListTile(
        title: Text('Item 2'),
        onTap: () {},
      ),
    ],
  ),
)

Após fazer isso tudo que precisará fazer é chamar esse CustomDrawer em cada componente AppBar que inserir nas telas da sua aplicação.
É necessário porém tomar cuidado e pensar direitinho no comportamento do empilhamento das telas. Aconselho realizar diversos testes acionando elas e utilizando o BackButtom do aparelho para verificar se a pilha está na ordem que deseja. Em alguns casos precisará fazer a substituição dela ao invés de apenas o empilhamento normal.
Comment: Ótimo Leonardo, funcionou muito bem isso, a parte de empilhamento irei repensar mais além, por enquanto tendo o menu acessado de qualquer tela já me ajuda muito. Obrigado.


Create Batch file to execute multiple batch files and VBS files

Question: I have multiple batch files and vbs files , when i try to create a batch to call them it stop after the last batch file and dont execute the vbs.
without giving any error
if i put the vbs at the start it execute it alone.
any advice ?
<code>@echo off
call batch1.bat
call batch2.bat
cscript //nologo test.vbs
</code>
Comment: Try to post your batch file (the one that calls) all of the others
Comment: @echo off
call batch1.bat
call batch2.bat
cscript //nologo test.vbs
Answer: Try dropping the call commands and moving the //nologo to after the test.vbs so it will look like this. That is mostly a personal taste change but I have a couple of Batch files that call multiple batch and vbs files and have never had an issue. If that doesn't work, my only guess is that something is wrong with the environment.
<code>@echo off

batch1.bat

batch2.bat

cscript test.vbs  //nologo
</code>


Sentença while - not true... entendimento da lógica

Question: Estou com muito problema para entender porque o programa para quando digito n=0.
quando digito 0 o terminou vira True, e a lógica do while é justamente esta, não?
Já rodei o programa e está correto, eu que não estou conseguindo entender. Realmente o not me confunde um pouco rs.
terminou = False
p = i = 0
while (not terminou):
    n = int(input("Digite um número, ou zero para terminar: "))
    if n == 0:
        terminou = True
    else:
        if n % 2 == 0:
            p = p + 1
        else:
            i = i + 1

print ("P = ", p)
print ("I = ", i)

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: O programa para porque o seu código determinou isso. Um primeiro lugar ele para porque ele concluiu o que tinha que fazer. Ele só consegue concluir depois que sai do laço e a condição do while é que determina isso.
Para entrar nele está esperando que o valor de terminou seja False. E por que tem que ser esse valor? Porque tem um operador de negação na condição, o not, então ele inverte o valor da variável. Se o valor é False ele passe ser True ali naquela expressão. Como o while espera que algo seja True para executar é isso que acontece, ele entra no laço.
Daí para sair só quando a passar de novo pelo o while e nesse momento a expressão der False, portanto como tem um not o valor de terminou deve ser True.
Qualquer valor que digite vai cair no else do if e lá o valor de terminou não muda. Apenas quando digitar 0 é que cai no if mesmo. E nesse bloco o que está mandando fazer é justamente a variável ter o valor True, que invertido é o que faz o laço encerrar.
Portanto é só seguir o fluxo do código que ele determina o que acontece.
Na verdade esse código ser simplificado:
p = i = 0
while (True):
    n = int(input("Digite um número, ou zero para terminar: "))
    if n == 0:
        break;
    else:
        if n % 2 == 0:
            p = p + 1
        else:
            i = i + 1
print ("P = ", p)
print ("I = ", i)

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Desta forma não precisa de variável controlando a saída e tem um comando que manda sair na hora que quiser, de forma mais explícita que quer sair, sem enrolações.
Comment: obrigada, mas o que me deu nó é que no início é determinado que a variável terminou = false. portanto se na while está como not terminou, significa que para entrar no loop espera que terminou = true ... certo?
obrigada pelo código simplificado! :)
Comment: Não, a resposta diz que é o oposto disso.


How to use Dense Rank for Date Field in BusinessObjects

Question: I am trying to filter for only latest 4 weeks of data in BusinessObjects. In the below example I want to retrieve data for below dates (latest weeks). Week Date is a field which is every Monday date of the week.

10/9/2017
10/2/2017
9/25/2017
9/18/2017

Week Date   Sales
8/28/2017   100
8/28/2017   101
9/4/2017    102
9/4/2017    103
9/11/2017   104
9/11/2017   105
9/18/2017   106
9/18/2017   107
9/25/2017   108
9/25/2017   109
10/2/2017   110
10/2/2017   111
10/9/2017   112

I tried with Rank Function and spent hours finding solution but had no luck. I hope Dense Rank would help, later I can filter for 1 to 4.
Answer: You could do this in one variable and a filter on that variable, but I like to break things down to understand exactly what is happening. You can always combine variables later.
First, create a variable to represent the cutoff date...
[CutOff Date] = RelativeDate(CurrentDate(); -4; WeekPeriod)

Second, create another variable to determine if a particular week should be included...
[Last Four Weeks] = If([Week Date] > [CutOff Date]; 1; 0)

Finally, create filter on to only show the last four weeks...
[Last Four Weeks] = 1

You may need to adjust the values depending on the timing of when you are running your report, but that is the general idea.
As I mentioned earlier, you could combine [CutOff Date] and [Last Four Weeks] into one variable...
[Last Four Weeks] = If([Week Date] > RelativeDate(CurrentDate(); -4; WeekPeriod)
; 1; 0)

Noel
Comment: Thanks for your response, I used the same but in other way `[DateFilter] = IF(Max[Week Date] >= RelativeDate(CurrentDate();-27;"Yes";"No")`


Adobe AIR for Android sound effects not playing

Question: I'm making a simple game in Flash CC using Adobe Air and publishing for Android. The movie compiles correctly and the sound plays fine on the desktop, but when publishing to Android nothing plays from my phone. I've tried using a different phone as well, and there's no sound coming out of it. My code is below:
<code>package  {

import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.media.Sound;
import flash.net.URLRequest;

public class MainGame extends MovieClip {

    public var sndBoop:Boop = new Boop();

    public function MainGame() {

        gameTimer = new Timer(1500);
        gameTimer.addEventListener(TimerEvent.TIMER, createNewCircle);
        gameTimer.start();
    }

    public function createNewCircle(event:TimerEvent):void {

        sndBoop.play();
    }

}

}
</code>
The sound I have is a .wav file that's linked to the Boop class in the library. I've tried using a .mp3 file, adding in the sound file during the packaging settings, using the URLRequest method of grabbing an external sound file, or internal sound file. None of these methods work. It's still just playing on the desktop or emulator, but not on my actual phone. I've used three phones so far, and they all aren't playing the sound.
Is there something I've overlooked?
Comment: gameTimer is not declared so it should produce an error right away. Is this a pseudo code?
Comment: I have public var newCircle:Circle; public var newHeader:Header; public var gameTimer:Timer; added in above the call to the Boop class, I just removed them for the sake of length.
Comment: Premissions maybe? Check the manifest.
Comment: What's the phone you're testing on? The sound might be too low (has more bass) in frequency, so the speakers on the phone might not be able to play it. I used to have the same issue on a game and in the end opted to buy other sounds. You should also check if the sound is exported in frame 1.
Comment: HTC One, Galaxy S4 and Galaxy S3. I believe the sound is being exported in Frame 1. Should it not be?
Comment: @Travis what permissions should there be for audio? I have internet permissions enabled.
Comment: You are not reporting any error which means the sound is playing correctly so look for other problems. If the sound was not available you would get errors. use trace and figure out what's running and what's not.
Comment: @aschmelyun It's good that the sound is exported. You could try putting the sound on the device and see if you can hear it with a media player.
Answer: It appears that the problem was being caused by the compression method in Flash. Changing it from MP3 to RAW now makes the sound play on all devices. I don't know why this is the case, but it's a workaround for now.


Element not allowed in content model

Question: there.
I'm trying to validate a xml document with a schema made by myself and I keep getting this error:
Validation stopped at line 40, column 12: element 'article' is not allowed for content model '(book*|article*|mastersthesis*|inproceedings*)'
My xsd file is well-formed, so as my xml file. The line 40 is just the end of my xml document (</bibEntry> ).
This is part of my xsd file:
<xs:element name="bibEntry" type="entryType"/>
 <xs:complexType name="entryType">
  <xs:choice>
    <xs:element ref="book" minOccurs="0" maxOccurs="unbounded"/>
    <xs:element ref="article" minOccurs="0" maxOccurs="unbounded"/>
    <xs:element ref="mastersthesis" minOccurs="0" maxOccurs="unbounded"/>
    <xs:element ref="inproceedings" minOccurs="0" maxOccurs="unbounded"/>
  </xs:choice>
 </xs:complexType>

<xs:element name="author" type="xs:string"/>
<xs:element name="title" type="xs:string"/>
<xs:element name="publisher" type="xs:string"/>
<xs:element name="year" type="xs:string"/>
<xs:element name="edition" type="xs:string"/>
<xs:element name="ISBN" type="xs:string"/>
<xs:element name="journal" type="xs:string"/>
<xs:element name="volume" type="xs:positiveInteger"/>
<xs:element name="number" type="xs:positiveInteger"/>
<xs:element name="pages" type="xs:string"/>
<xs:element name="school" type="xs:string"/>
<xs:element name="booktitle" type="xs:string"/>

<xs:element name="book" type="bookType"/>
 <xs:complexType name="bookType">
  <xs:sequence>
    <xs:element ref="author"/>
    <xs:element ref="title"/>
    <xs:element ref="publisher"/>
    <xs:element ref="year"/>
    <xs:element ref="edition"/>
    <xs:element ref="ISBN"/>
   </xs:sequence>
  <xs:attribute name="id" type="xs:NMTOKEN"/>
 </xs:complexType>

 <xs:element name="article" type="articleType"/>
  <xs:complexType name="articleType" mixed="true">
   <xs:sequence>
    <xs:element ref="author"/>
    <xs:element ref="title"/>
    <xs:element ref="year"/>
    <xs:element ref="journal"/>
    <xs:element ref="volume"/>
    <xs:element ref="number"/>
    <xs:element ref="pages"/>
   </xs:sequence>
   <xs:attribute name="id" type="xs:NMTOKEN"/>
 </xs:complexType>

And this is my xml:

<bibEntry xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com bibEntry.xsd">

  <book>
    <author>José Saramago</author>
    <title>Ensaio Sobre a Cegueira</title>
    <publisher>Caminho</publisher>
    <year>1995</year>
    <edition>1ª</edition>
    <ISBN>9722110217</ISBN>
  </book>

    <author>Regev, Oded</author>
    <title>On Lattices, learning with errors, random linear codes and cryptography</title>
    <year>2009</year>
    <journal>Journal of the ACM</journal>
    <volume>56</volume>
    <number>13</number>
    <pages>34</pages>

  <mastersthesis>
    <author>Menno den Hollander</author>
    <title>Automatic Unit Test Generation</title>
    <school>Delft University of Technology</school>
    <year>2010</year>
  </mastersthesis>

  <inproceedings>
    <author>Thomas Tilley</author>
    <title>Tool Support for FCA</title>
    <booktitle>ICFCA</booktitle>
    <year>2004</year>
    <pages>104-111</pages>
  </inproceedings>

</bibEntry>

Can you see what I'm doing wrong?
Comment: The error suggests that your XML is violating the rules that you established in the schema, so I think we need to see the XML.
Comment: Your schema may be well-formed, but it's still not valid.  You're missing element declarations for 'mastersthesis' and 'inproceedings'.
Answer: It seems like you close your element tags too soon.
Instead of
<xs:element name="article" type="articleType"/>

try
<xs:element name="article" type="articleType">
 (....)
</xs:element>

Element not allowed in content model


Finding the basis and dimension of a subspace of the vector space of 2 by 2 matrices

Question: I am trying to find the dimension and basis for the subspace spanned by:
$$
\begin{bmatrix}
1&-5\\
-4&2
\end{bmatrix},
\begin{bmatrix}
1&1\\
-1&5
\end{bmatrix},
\begin{bmatrix}
2&-4\\
-5&7
\end{bmatrix},
\begin{bmatrix}
1&-7\\
-5&1
\end{bmatrix}
$$
in the vector space $M_{2,2}$. I don't really care about the answer, I am just hoping for an efficient algorithm for solving problems like this for matrices.
I am not sure how to account for interdependence within the matrices. My instinct as of now is to find the maximum restriction imposed by the matrices. It is clear that the $1$ in position $a_{1,1}$ in each matrix will allow me to get any number in that position, so one vector in the basis will be:
$$
\begin{bmatrix}
1&0\\
0&0
\end{bmatrix}
$$
But depending on which of the matrices I scale, I have restrictions on the other entries. So I don't think I can include that matrix in my basis.
It just occurred as I was writing this that I could maybe just think about these as $4$ by $1$ vectors and proceed as usual. Is there any danger in doing so?
Comment: No danger. Just wanted to suggest so.
Comment: $M_{2,2}(\mathbb{F})$ is isomorphic to $\mathbb{F}^4$, where $\mathbb{F}$ is the underlying field of the vector space. You can just think of these matrices as 4-tuples, as you suggested.
Comment: ah ok, welp, hopefully the question will help people who have the same question in the future.
Comment: Write these matrices as *row* vectors, and use row -reduction to find the rank and a basis.
Answer: Inputs
$$
\alpha =
\left(
\begin{array}{rr}
 1 & -5 \\ -4 & 2
\end{array}
\right),
\qquad
\beta =
\left(
\begin{array}{rr}
 1 & 1 \\ -1 & 5
\end{array}
\right),
\qquad
\gamma =
\left(
\begin{array}{rr}
 2 & -4 \\ -5 & 7
\end{array}
\right),
\qquad
\delta =
\left(
\begin{array}{rr}
 1 & -7 \\ -5 & 1
\end{array}
\right)
$$
Find the basis for these matrices.
Matrix of row vectors
As noted by @Bernard, compose a matrix of row vectors. Flatten the matrices in this manner
$$
\left(
\begin{array}{rr}
 1 & -5 \\ -4 & 2
\end{array}
\right)
\quad \Rightarrow \quad
\left(
\begin{array}{crrc}
 1 & -5 & -4 & 2
\end{array}
\right)
$$
Compose the matrix
$$
\mathbf{A} =
\left(
\begin{array}{crrr}
 1 & -5 & -4 & 2 \\\hline
 1 &  1 & -1 & 5 \\\hline
 2 & -4 & -5 & 7 \\\hline
 1 & -7 & -5 & 1
\end{array}
\right)
$$
Row reduction
Column 1
$$
\left(
\begin{array}{rccc}
 1 & 0 & 0 & 0 \\
 -1 & 1 & 0 & 0 \\
 -2 & 0 & 1 & 0 \\
 -1 & 0 & 0 & 1 \\
\end{array}
\right)
%
\left(
\begin{array}{crrc}
 1 & -5 & -4 & 2 \\
 1 & 1 & -1 & 5 \\
 2 & -4 & -5 & 7 \\
 1 & -7 & -5 & 1 \\
\end{array}
\right)
%
=
%
\left(
\begin{array}{crrr}
 \boxed{1} & -5 & -4 & 2 \\
 0 & 6 & 3 & 3 \\
 0 & 6 & 3 & 3 \\
 0 & -2 & -1 & -1 \\
\end{array}
\right)
%
$$
Column 2
$$
\left(
\begin{array}{rccc}
 1 & 0 & 0 & 0 \\
 -1 & 1 & 0 & 0 \\
 -2 & 0 & 1 & 0 \\
 -1 & 0 & 0 & 1 \\
\end{array}
\right)
%
\left(
\begin{array}{crrr}
 \boxed{1} & -5 & -4 & 2 \\
 0 & 6 & 3 & 3 \\
 0 & 6 & 3 & 3 \\
 0 & -2 & -1 & -1 \\
\end{array}
\right)
%
=
%
\left(
\begin{array}{cccc}
 \boxed{1} & 0 & -\frac{3}{2} & \frac{9}{2} \\
 0 & \boxed{1} & \frac{1}{2} & \frac{1}{2} \\
 0 & 0 & 0 & 0 \\
 0 & 0 & 0 & 0 \\
\end{array}
\right)
%
$$
The fundamental rows are marked by the unit pivots.
Solution
The basis is
$$
\mathcal{B} = \left\{
\alpha, \, \beta \right\}
= \left\{
\left(
\begin{array}{rr}
 1 & -5 \\ -4 & 2
\end{array}
\right),
\
\left(
\begin{array}{rr}
 1 & 1 \\ -1 & 5
\end{array}
\right)
\right\}
$$


Relation between path components of two topological spaces with path components of their product.

Question: Let $X_1$ and $X_2$ be topological spaces. Let's denote by $\pi_0(X)$ the set of path components of $X$. I would like to know if there is a relation between $\pi_0(X_1)$, $\pi_0(X_2)$, and $\pi_0(X_1\times X_2)$.
I have already showed that $\pi_0(X_1)\times \pi_0(X_2)\subset \pi_0(X_1\times X_2)$. Is the other inclusion true?
Thanks!
Answer: First thing to note is that this isn't technically a set  inclusion, rather a natural inclusion $(X_i,Y_j) \mapsto X_i \times Y_j$, since the product of path connected spaces is path connected. If $X=A \cup B$, with $A \cap B = \emptyset$, then for any set $Y$, $X \times Y = A \times Y \cup B \times Y$ with this being disoint component. So if $Y = \bigcup_i Y_i$ and $X=\bigcup_j X_j$, where $X_j,Y_i$ are the path components (which are disjoint!), we have that $X \times Y = \bigcup_{ij} X_j \times Y_i$. These are  clearly the path components of $X \times Y$, since if theres is path linking points in different ones there would be a path connecting $Y_i$ to $Y_i'$ or $X_j$ to $X_j'$. So we get a natural bijection (the inclusion is surjective) $\pi_0(X)\times \pi_0(Y) \rightarrow \pi_0(X \times Y)$ where $(X_j,Y_i) \mapsto X_j \times Y_i$.
Comment: Thanks a lot! the relation is more clear now.


Why do american commentators call the ball "the football"?

Question: Listening to commentators on NFL games, it seems that all of them systematically call the ball "the football", and not just "the ball".
Why is that the case? In Rugby or Soccer (at least in my country) I've never heard commentators call the ball "the rugby ball" or "the soccer ball". There doesn't seem to be any advantage to calling it "the football", which is longer and not really more descriptive.
"Football" is the name of the sport. Why do comentators insist on calling the ball it is played with the same name as the sport itself?
Comment: Football is the name of the sport, but the ball they play with is also called a football, so I'm not understanding the last sentence.
Comment: Well in that case why is the ball even called a football? Why not just a ball? But the main focus of the question is the insitence of commentators, I've never heard one call it just "the ball". In tennis for example sometimes they call it "the tennis ball" but usually just "the ball", why not the same in American Football?
Answer: First, the object is a "football". See Definition 9:

The ball used in any game called "football".

Second, your premise is mistaken. Commentators do call it the "ball".
From http://www.pbs.org/wgbh/pages/frontline/sports/league-of-denial/transcript-50/

He fumbled the ball! And let's see— Minnesota has it! Jeff Seamon on it.

Joe Starkey's call of "The Play":

the ball is still loose, as they get it to Rodgers!

Searching in Google for "comes down with the" NFL yields many examples of "comes down with the ball".
I will try to get a better estimate, but I believe it is called "the ball" more often than it is called "the football" during broadcast.


How to tell if a Rubik's cube is solvable?

Question: How can I determine if a certain Rubik's cube, that is in a certain state, is solveable? By "certain state" it could mean that the cube has been dismantled and put together again. And in my experience if you don't put it together the right way, the cube might not be solvable.
A way to check for a $3 \times 3 \times 3$ cube would be great. For any size cube, awesome!
Comment: Well the literature on the subject tells us that there are twelve different sets of configurations, and you can't get from one to the other without taking the cube apart. They are shown by parity considerations - so twisting a single corner cube creates an unsolvable cube (there are three orientations to a corner cube). The edge cubes give a similar factor 2, and the parity consideration that each move of the cube gives an even permutation (the basic move is a product of two 4-cycles on edges and corners respectively). So you need to measure these parity changes against a base case.
Comment: A very simple way would be to apply a well-known algorithm for solving it until you reach a point where it is "obvious" that you cannot proceed.
Comment: Have a look at http://www.emba.uvm.edu/~snapp/teaching/cs32/lectures/rubik.pdf, starting on page 38. It may answer your question.
Comment: @Gerry: That text gives one way each of defining orientational invariants (without mentioning that this is only one of many ways to define them) but is vague if not to say wrong on the positional invariant. It says: "Each sequence of operations always moves a multiple of 4 pieces. It is thus
impossible to interchange just two corners, or just two edges." But the number of pieces moved $\bmod 4$ is not an invariant; successive rotations of adjacent sides can move exactly one piece back into position and thus lead to an odd number of pieces moved.
Comment: Or more elementarily (relative to @joriki's argument), there are well-known combinations that cyclically permute exactly 3 pieces and leave the rest of the cube unchanged.
Comment: Funny story: I once got my brother a Rubik's cube for his birthday. Before I gave it to him, I popped a corner off, rotated it 120°, snapped it back in and scrambled the cube. This would've been useful to him.
Comment: @joriki, thanks - I hadn't read it closely enough to detect the problems you point out.
Answer: For a 3×3×3 cube there are three different conditions to check, usually decomposed as "permutation parity", "edge parity", and "corner parity".
(Mathematically, the group that the describes all ways to take apart and reassemble the cube has the group of legal movements as a normal subgroup, and the quotient group is $C_2\times C_2\times C_3$, so it is natural to group the check into three parts. In principle there ought to be equivalent ways to deal with the $C_2\times C_2$ factor, but the overall and edge parities are so natural that looking for the other decompositions doesn't seem worth the trouble).
We imagine that the spindle axes (and therefore the center cubies) stay fixed in space -- turning the entire cube is trivial and ignorable.
Permutation parity: This rejects 1/2 of all configurations. In this step, ignore which way each of the little cubies is turned and just look at where it has ended up. In this way each way to assemble the cube corresponds to some particular permutation of the 20 non-center cubies. Each legal permutation is an even permutation (because each quarter turn is a product of two 4-cycles and therefore itself even). On the other hand it is well known that any even permutation can be achieved, as long as it doesn't try to interchange edges with corners.
To check whether a given permutation is even, just write down the permutation (i.e. the function from "where the cubie is" to "where it ought to be") and compute its sign by any standard methods -- e.g., by counting inversions or unraveling its cycle structure.
For edge and corner parity, we temporarily forget the difference between opposing colors on the cube -- say, we call both of white and yellow $X$, both of green and blue $Y$ and both of red and orange $Z$.
Corner parity: This rejects 2/3 of all configurations, and can be defined in the following way: Since we have unified opposing colors, each corner has the colors $X$, $Y$ and $Z$. Let's say that a corner is "oriented correctly" for its instant position if its $X$ side is next to an $X$ center. (This treats the $X$ color pair specially; the $Y$ and $Z$ sides may or may not line up with matching centers). Now for any way to assemble the cube, consider how many clockwise 120° twists of a corner-in-place it would take to orient all of the corners "correctly" without moving them. If this number is a multiple of $3$, the configuration passes the corner parity test. (It is easy to see that a quarter turn of an $X$ face keeps this number unchanged, and only slightly more complex that a quarter turn of $Y$ or $Z$ changes it by a multiple of $3$).
Edge parity: This rejects 1/2 of all configurations. It can be computed much in the same way as the corner parity, except that the definition of "correct orientation" for an edge is a bit more involved. One may take, for example:

An edge with a $X$ side is oriented correctly if the $X$ side is next to an $X$ center or if the edge is in the middle layer and would become correctly oriented by a quarter turn of the $Y$ (but not $Z$) face it is in.
A $YZ$ edge is oriented correctly either if it sits between a $Y$ and a $Z$ center in the obviously matching way, or if its $Z$ side is next to an $X$ center.

One may now check that a quarter turn of an $X$ or $Y$ face doesn't change whether any edge is oriented correctly or not, whereas a $Z$ quarter-turn changes each of the four edges it moves from correct to non-correct or vice versa. Thus, every legal move changes the number of correctly oriented edges by an even amount. So we must reject any way to assemble the cube that ends up with an odd number of incorrectly oriented edges.
Though not immediately obvious, these three tests will reject any configuration that cannot be solved.

The corner-parity check carries over to larger cubes unchanged, but the two other tests cannot always be directly applied to larger cubes. For a 4×4×4 cube with indistinguishable center pieces, the corner parity check is the only check; anything that satisfies it can be solved. For a 5×5×5 cube, the virtual 3×3×3 formed by corners, middle centers and middle edges must be solvable according to the 3×3×3 rules, and it turns out that the remaining pieces can always be solved, again assuming that centers are indistinguishable. I think that larger-yet cubes continue the pattern from 4×4×4 and 5×5×5.
There are special parity checks to apply for supercubes (where the orientation and/or permutation of center pieces of the same main color matters); I don't remember offhand how they work.
Comment: @Mel: When speaking about permutations, "even" is a technical term that is not equivalent to "divisible by 2" -- see [parity of a permutation](http://en.wikipedia.org/wiki/Parity_of_a_permutation) on Wikipedia. Swapping just two pieces is simplest example of an _odd_ permutation. You're supposed (in one of the many equivalent ways to think about it) to be counting the number of _swaps_, not the number of pieces affected. The permutation is even if it can be created using an even number of swaps.
Comment: +1 Well done, Henning. AFAICT I used exactly the same method to describe corner parity on my Rubik's cube page (in Finnish only, so I'm not gonna bother with the link - the page is old anyway :-). The word *parity* suggests to me that the check is two-valued, whereas here it is 3-valued. Doesn't matter! Interesting stuff about 4x4x4 and higher!!! I didn't know that these were the only checks (though I once had a working 4x4x4 and a 5x5x5, but they were not very durable).
Comment: The regularity in the assignments you describe is useful for a computer evaluation but not required mathematically; any assignments from $\mathbb Z_2$ to edge pieces and edge slots and any consistently oriented assignments from $\mathbb Z_3$ to corner pieces and corner slots will do.
Comment: I didn't know that, but did notice it in your answer (somehow I didn't get a new-answers alert while typing, or I would have been considerably less verbose here).
Comment: @Jyriki: Agree about parity but couldn't think of a better word. Triplity? The 4×4×4 and 5×5×5 properties follow because I can transpose two edge cubies (outer edges on the 5×5×5) without disturbing centers or corners, which together with conjugation generates the entire $S_{24}$ of edge pieces. The centers themselves are easily solved from any starting point because the pieces are interchangeable in groups of 4.
Comment: Thank you for explaining in plain english! I'm just a little confused with the permutation/positional parity. I am supposed to compute for the sum and it should be divisible by four right? (not just even). If I swap 2 adjacent edges or corners, that would be an even permutation right? but the cube wont be solvable.
Comment: @HenningMakholm Sorry to disturb.....I had not read the word *dismantled cube*....
Comment: There may be a problem with your "Permutation parity" method. To demonstrate, swap YR and WR such that edge parity is maintained. As this is 1 swap (odd # of swaps), it should fail the permutation parity test. Yet using your hints, since the distance is 2 for 2 out-of-place cubies, it cannot fail.  Your hint of "we temporarily forget the difference between opposing colors" implies similar confusion as opposing face swaps DO matter. I tried this on several online cube solver and not one of them has detected this properly, so it seems messing this up is common. Any tips?
Comment: @VoidStar - Henning never said anything about counting "out-of-place" cubies for Permutation parity. The "standard method" of computing the sign of a permutation referenced is to count how many swaps of two items in the permutation it would take to completely undo it. If that count is odd, it is an odd permutation, if it is even it is an even permutation.
Comment: For Edge Parity, I think a better way of defining the "correct orientation" is that a cubie is correctly oriented if either both of its sides agree with the adjacent centers, or neither side agrees with the adjacent face. It is wrongly oriented when only one side agrees with the adjacent center. The advantage of this definition is that in all cases, a quarter turn of a face will flip all four edges, making it easy to see that the count of correctly oriented faces must always be even.
Answer: As explained at Wikipedia, the operations you can perform without disassembling the cube lead to $12$ different equivalence classes; you want to know whether the current state of the cube is in the same class as the solved state. One way to do that is to use invariants that characterize the classes.
As discussed in comments under example's answer (now deleted), the invariants decompose into a $\mathbb Z_2$ edge orientation invariant, a $\mathbb Z_3$  corner orientation invariant and a $\mathbb Z_2$ positional invariant.
For the edge orientation invariant, arbitrarily assign the elements of $\mathbb Z_2$ to the two faces of each edge slot and to the two faces of each edge piece; then the invariant is the parity of the number of matches between the assignments of the edge pieces and the assignments of the edge slots they're in. If you take out an edge piece and insert it the other way around, you change the invariant. On the other hand, if you turn a side (the only operation you can perform without disassembling the cube), the sum of the four changes you induce is the change you'd get for one piece being turned around by $2\pi$, so this operation doesn't change the invariant. Of course you'll want to choose an assignment that's easy to handle systematically on a computer, but any assignment will do.
Likewise, for the corner orientation invariant, arbitrarily assign the elements of $\mathbb Z_3$, say, clockwise, to the three faces of each corner slot and to the three faces of each corner piece; then the invariant is the element of $\mathbb Z_3$ that you get by adding up all the differences (in $\mathbb Z_3$) between the assignments of the corner pieces and the assignments of the corner slots they're in. For analogous reasons as above, this invariant changes if you take out a corner piece and insert it with another orientation, but doesn't change if you turn a side.
The positional invariant is just the parity of the permutation of all the pieces, edge pieces and corner pieces together, disregarding orientation. If you swap any two corner pieces or any two edge pieces, you change the parity; on the other hand, if you turn a side, you apply a $4$-cycle to the edge pieces and a $4$-cycle to the corner pieces, so the parity of the overall permutation doesn't change.


Is it possible to change the field type in a node form afterwards?

Question: I have an instance here where an existing textfield in a node form should be limited to enter only three possible values. I though it might be possible to alter the field to #type => 'select' and attach my '#options' as well. So I altered the form to:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD']['#type'] = 'select';
    $form['field_MYFIELD']['#title'] = 'Enter a value';
    $form['field_MYFIELD']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
  }
}

But when I now try to create a form like that, all I get is this error:
Fatal error: Cannot create references to/from string offsets nor overloaded objects in /Users/Shared/www/drupal.dev/includes/common.inc on line 6606

Is it even possible to change an existing field type like I want with a small custom module? Do I have to alter the submit function then as well? Please help!
Comment: Have a read through [this](http://drupal.stackexchange.com/questions/27767/why-is-hook-form-alter-so-messy-in-d7/), it's likely you need something more like `$form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#type'] = 'select'];`, etc
Comment: @Clive - Thank you a thousand times! I still was in the container ... Should I delete this question or attach the correct code in an answer?
Comment: I think an answer with the code you used would be useful :)
Answer: The answer is: Yes! It is possible. All I did wrong when altering the form is that I changed the '#type' of the container instead of changing the type of the textfield itself. I had to go one level deeper:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#type'] = 'select';
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
    // #select doesn't need #size and #maxlength
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#size']);
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#maxlength']);
  }
}

Comment: Ah, that pesky `value`; I am always perplexed when I work with Form API as to which level attributes and other options should be changed on, even after a decade of Drupal development :P
Comment: I used you sample but in setting default_value, I have problem. although I set #default_value but there is no item selected in rendered field.
Comment: @leymannx Is this the same goes to drupal8 as well? I'm trying to convert select type field to 'textfield' by using $form['field_control_number'][LANGUAGE_NONE][0]['value']['#type'] = 'textfield'; but not working. Any idea on what is missing here?
Answer: You can write a field formatter that will render select box for this field. It's very simple and didn't take many time to use it. API here: https://api.drupal.org/api/drupal/modules!field!field.api.php/group/field_formatter/7
I can help with this if you need.


why does recursion do this?

Question: class Java_code {
public static void main(String args[]){

    mymethod(5);
}
static void  mymethod(int counter){
    if(counter==0){
    System.out.println("");
    }
    else {
    System.out.println("Hello" + counter);
    mymethod(--counter);
    System.out.println("" +counter);
    }
}
}

Suppose we have above program , when i give argument 5 it prints
Hello5

Hello4

Hello3

Hello2

Hello1

after that it prints

0
1
2
3
4

, but why does it prints numbers , how does it happen ? I don't understand how that happens can you help me out on this?
Comment: See this answer http://stackoverflow.com/questions/21474297/trouble-understanding-recursion
Comment: There is a line `System.out.println("" +counter);` after the recursive function call `mymethod(--counter);` , this is exactly why it happens !
Comment: Paper and pen is also useful for small programs.
Answer: Remember that these three lines will be executed as long as counter != 0
System.out.println("Hello" + counter);
mymethod(--counter);
System.out.println("" +counter);
mymethod() is being called initially with counter = 5. So it prints "Hello5" and before it returns, it calls itself recursively with the counter = 4 so prints "Hello4" and before it returns, it calls itself recursively with the counter = 3 so prints "Hello3" and before it returns, it calls itself recursively with the counter = 2 so prints "Hello2" and before it returns, it calls itself recursively with the counter = 1 so prints "Hello1" and before it returns, it calls itself recursively with the counter = 0 at which point it prints nothing but returns to the caller which will execute the rest of the code
System.out.println("" +counter)
in each of the ongoing previous executions so on its' way back to the initial caller function it prints the values 0, 1, 2, 3, 4 respectfully.
Answer: If you look carefully you can see this line
mymethod(--counter);
This is decreasing the value of counter and then passing it as a parameter to mymethod
This will be called for as long as counter > 0, then the method will return all the way up.
After each method returns System.out.println("" +counter); will be executed.
The value of counter is being remembered in each call of mymethod
Answer:   why does it prints numbers , how does it happen ?
I don't understand how that happens can you help me out on this?

Because you have this line in your code
mymethod(--counter);-> recursive call so upto this line it continuously print (Hello world 1 to 5.)
After that only it executes this line
 System.out.println("" +counter);

This is called stack buffer overflow
Comment: I know that but what exactly happens in code when that line is executed ? how does it increment ?
Answer: System.out.println("" +counter);

prints those numbers. Because of stack unwinding  (whenever a method call happens the current state is pushed into the stack) And since stack is LIFO (Last In first out) so it is printing in the reverse order
Answer: It will help you better understand what is happening if you draw the steps along with the current values of variables any time you use recursion because it can get confusing in the beginning until you get more familiar with it.

why does recursion do this?


How to get event of changing current keyboard layout in Unix?

Question: I searched simple solution, but could not find.
I need getting event of changing system keyboard layout for setting this in my application.
QApplication::keyboardInputLocale() is not suitable, because I need to catch system layout, not the application.
Xkblib also is not suitable, because I use Qt project and this library can lead to crashes (QEvent, QTimer).
Comment: Try catching `XkbStateNotify` events.
Comment: Thanks, but using xkblib is very very difficult for me. I searching a simple solution. And I use the qt project. Therefore, this library can lead to crashes (QEvent, QTimer).
Answer: X sends a MapNotifyEvent (not to be confused with KeymapNotify) when the key mapping is changed (tested with xmodmap, but should work for other methods as well). I don't know if you can get at raw X events under Qt, but if you can, I think that's the event to look for.


HTML form post or Ajax post

Question: I have a form which has many inputs and will need to be broken up and sent to different databases. What would be the more efficient way to do this, with a regular HTML post to a PHP function or posting to an AJAX(or JQUERY?) function. I don't know much of all the options available for posting and processing data, but if clarification is needed please ask.(If it matters, my project is written in PHP)
Answer: If your HTML contains inputs such that the values are independent to each other then sending a separate request is good else AJAX is good option.
Answer: If you have a big comprehensive form the better way is divide it on small parts and code step-by-step form submission. In this case you can store data with simple PHP request but validate form fields input with AJAX verification.
Comment: The form isn't large per-say, it has 4 fields that go to one table, and a variable amount of fields go to another table(which is linked to the first table)

HTML form post or Ajax post


Proof for minimal polynomial $\mathbb{F}_q$

Question: Show that each monic irreducible polynomial of $\mathbb{F}_q[x]$ of degree $m$ is the minimal polynomial of some element of $\mathbb{F}_{q^m}$ with respect to $\mathbb{F}_q$ .
Using theorem, find all the irreducible polynomials of degree 4 over F2. (Let α be a root of 1 + x^3 + x^4 ∈ F2[x].)
Comment: The part after "I messed it up" is not clear. What theorem do you mean? Where is the connection to the first part?
Comment: To prove that a quartic is irreducible you need to check that it doesn't have linear or irreducible quadratic divisors. A polynomial has a linear factor, iff it has a zero in the base field (here $\Bbb{F}_2$). There is only one irreducible quadratic polynomial in $\Bbb{F}_2[x]$. If you are asked to prove the irreducibility of $x^4+x^3+1$, then you have surely been given that irreducible quadratic in class :-) Hint: it is the only quadratic that does not have zeros in $\Bbb{F}_2$.
Comment: I second azimut's query. His +1 answer takes care of the  question in the first paragraph.
Comment: i know what you say. but i must show this using the current theorem. so i did not get, exactly.
Comment: to azimut with respects =) Using theorem, find all the irreducible polynomials of degree 4 over F2. (Let α be a root of 1 + x^3 + x^4 ∈ F2[x].)
Answer: Let $f$ be a monic irreducible polynomial over $\mathbb F_q$ of degree $m$ and $F$ be an algebraic closure of $\mathbb F_q$.
$f$ has a zero $\alpha$ in $F$.
So $f$ is the minimal polynomial of $\alpha$ over $\mathbb F_q$ and
$$[\mathbb F_q(\alpha) : \mathbb F_q] = \deg(f) = m,$$ so $\lvert \mathbb F_q(\alpha)\rvert = q^m$. Since all finite fields of the same order are isomorphic, $\mathbb F_q(\alpha) \cong \mathbb F_{q^m}$.
Thus, there is an element $a\in \mathbb F_{q^m}$ such that $f$ is its minimal polynomial.
For the subtle point why it is possible to find $a$ such that the minimal polynomial $f$ is not "twisted" by the isomorphism $\mathbb F_q(\alpha) \to \mathbb F_{q^m}$, see the discussion below and in particular the explanation of Marc van Leeuven.
Comment: I answered the first part of your question: "Show that each monic irreducible polynomial of $\mathbb F_q[x]$ of degree $m$ is the minimal polynomial of some element of $\mathbb F_{q^m}$ with respect to $\mathbb F_q$.
Comment: I think this still does not solve it (say you have $\mathbb{R}\subseteq \mathbb{C}$ and an automorphism of $\mathbb{C}$ which sends an element $\alpha \in \mathbb{C}\setminus \mathbb{R}$ to something other than its conjugate. Then the minimal polynomial of the element changes).
Comment: so α^4=α^3+1 is my primitive element. so 1+x^3+x^4 is irreducible over F2 am i right?
Comment: I am not sure that the reasoning is correct (or, at least, complete): Say you have the isomorphism $\varphi:\mathbb{F}_q(\alpha)\rightarrow \mathbb{F}_{q^m}$. Then it is clear that $\varphi(\alpha)$ is a root of $\overline{\varphi}(f),$ where $\overline{\varphi}$ is the isomorphism $\varphi$ extended to the ring $\mathbb{F}_q[x]$ in the obvious way. But how would you ensure that it is a root of $f$ as well? For this to work, you need $\varphi$ to be $\mathbb{F}_q$-isomorphism.
Comment: @PavelC: In the moment where you define $\alpha$, you know that $f$ is its minimal polynomial over $\mathbb F_q$. I've changed the order of the arguments in my answer to make this clear.
Comment: azimut: I think @PavelC has a point, and I extended my answer to deal with it. In your current answer, the point is that you need the isomorphism $\def\F{\Bbb F}\F_q(\alpha)\cong\F_{q^m}$ to fix the subfield $\F_q$; it is not obvious that the mere fact that all fields of a given order are isomorphic gives you enough to ensure this.
Comment: @PavelC: No, if $\Bbb F_q$ is not the prime field, it is _possible_ to choose an isomorphism that is not an $\Bbb F_q$-isomorphism (it will always fix $\Bbb F_q$ globally, but you need to fix it point-wise). However it is also always possible to do it right.
Comment: @Marc van Leeuven: You are right, I realized it as well, hence the deleted last comment. : )
Comment: @PavelC: I agree that there is a subtle point that I never realized before. I've added a note on it.
Answer: This question is a bit strange, since the real work is in showing that all fields of order $q^m$ are isomorphic. If $\def\F{\Bbb F}P\in\F_q[X]$ is irreducible with $\deg P=m$, then $K=\F_q[X]/(P)$ is a field with $q^m$ elements in which the image $\bar X$ of $X$ has minimal polynomial$~P$ over$~\F_q$. If you know that necessarily $K\cong\F_{q^m}$, just choose an isomorphism and let $\alpha\in\F_{q^m}$ be the element corresponding to$~\bar X$ under the isomorphism.
There is a slight subtlety in that here you view $\F_q$ as a subfield of $\F_{q_m}$ by restriction (from $K$ to $\F_q$) of the chosen isomorphism. If you had already an embedding $\F_q\hookrightarrow\F_{q_m}$ when $\F_{q^m}$ was first given to you, then you must make sure to match that embedding, which plays a vital role when you talk about minimal polynomials over $\F_q$ of elements of $\F_{q^m}$. Fortunately this can always be done: every finite field is normal over the prime field $\F_p$, so there is a surjective morphism $\def\Gal{\operatorname{Gal}}\Gal(\F_{q^m}/\F_p)\to\Gal(\F_q/\F_p)$ that can be used to adjust the embedding to what is needed by applying an automorphism of $\F_{q^m}$.
Answer: Adding my bit with a view of covering the possibility (somewhat implied by OP's comments) that the task really is to find all the irreducible quartic polynomials over $\Bbb{F}_2$ using the theorem that they must all be factors of $p(x)=x^{16}-x$.
The given minimal polynomial of $\alpha$, $f_1(x)=x^4+x^3+1$ is obviously one of those. A useful trick for finding another one is to go to the so called reciprocal polynomial, i.e.
$$
f_2(x)=x^4f_1(\frac1x)=x^4(\frac1{x^4}+\frac1{x^3}+1)=1+x+x^4.
$$
We immediately see that
$$
f_2(\frac1\alpha)=\alpha^4f_1(\alpha)=0,
$$
so $f_2(x)$ is a multiple of the minimal polynomial of $1/\alpha$. As the elements $\alpha$ and $1/\alpha$ generate the same extension field, their respective minimal polynomials must be of the same degree. Therefore $f_2(x)$ is
the minimal polynomial of $1/\alpha$ and is, thus also irreducible.
Let's take stock. We know that in addition to $f_1(x)$ and $f_2(x)$ the polynomial $p(x)$ is divisible by $q(x)=x^4-x$ (if you don't know how to deduce this from properties of finite fields, then you can just calculate that
$q(x)^4+q(x)=p(x)$. Thus we know that $p(x)$ factors like
$$
p(x)=q(x) f_1(x) f_2(x) r(x),
$$
where $r(x)$ is some yet unknown factor. We can partially factor $p(x)$ directly as follows:
$$
p(x)=x(x^{15}-1)=x(x^5-1)(x^{10}+x^5+1)=x(x-1)(x^4+x^3+x^2+x+1)(x^{10}+x^5+1),
$$
and $q(x)$ as follows:
$$
q(x)=x(x^3-1)=x(x-1)(x^2+x+1),
$$
where that last quadratic factor is irreducible.
I leave it as an exercise for you to check that
$$
(x^2+x+1)f_1(x)f_2(x)=x^{10}+x^5+1.
$$
Putting all this together gives us that the mystery factor $r(x)=f_3(x)=x^4+x^3+x^2+x+1$.
I next claim that $f_3(x)$ is irreducible. As it has no zeros in
$\Bbb{F}_2$ it has no linear factors in $\Bbb{F}_2[x]$. It cannot be a product of two distinct quadratics, because then it should be a factor of $q(x)$.
It cannot be the square of a quadratic, because then its zeros would not be simple, but $f_3(x)$ is a factor of $p(x)$ that has 16 distinct zeros.
Thus the list $f_1(x), f_2(x), f_3(x)$ is a complete list of irreducible quartics in $\Bbb{F}_2[x].$

Yet another way of deducing the irreducibility of $f_3(x)$ is to observe that
$f_3(x)\mid x^5-1$, so its zeros are fifth roots of unity. If you are familiar with the cyclicity of the multiplicative groups of finite fields, then you can immediately check that $\Bbb{F}_{16}$ has no proper subfields containing primitive fifth roots of unity. Therefore the minimal polynomial of a fifth root of unity over $\Bbb{F}_2$ must have degree four, i.e. equal to $f_3(x)$.
Observe that $f_3(x)$ is its own reciprocal polynomial. Polynomials with this property are called palindromic because you can equally well read their sequence of coefficients backwards. Therefore our first trick won't give us a fourth irreducible quartic.
Comment: Thank you very much. really I appreciate you Jyrki Lahtonen .


How to Add a quertystring to a link using jquery

Question: I have a set of links on my page and some of them start with /mypath, like this
I need to add a querystring to the links that start this way, so the result is something like  with the '1234' being the node id of the node we're currently viewing.
I've sucessfully passed the nid into my js file using drupal settings.  The only part of this I can't get to work is putting the original link in where you see the second attr('href').
My code is as follows:
    $('a[href^="/mypath/"]').attr('href', attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid);

Instead of that second attr('href') I've tried a number of things and can't figure out what it should be.
Comment: Is the problem with the selector or with the href value? Is it changing the href at all with what you've got here?
Comment: If I put a static url (ie. 'http://google.com') in there instead of the attr('href') it works as expected.   Right now, due to it just erroring, it returns the original url)
Answer: You've got nothing to hook onto for that second attr() as you're not storing the result of the jQuery call in a variable.
I'd advise using a loop instead:
$('a[href^="/mypath/"]').each(function(index, element) {
  var newAttr = $(element).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(element).attr('href', newAttr);
});

That will catch any link on the page that matches the path selector.
Comment: Awesome, thanks! I figured it had something to do with the href not being defined.  The only thing I don't get about this is what's the 'index, element' part?
Comment: No worries :) Those variables are provided by the [`each()`](http://api.jquery.com/each/) function, I think the docs page can do a better job of explaining than I can


Logistic Regression with Unbalanced Data

Question: I have a binary dataset which is 99% in one class and 1% in the other class. I MUST create a logistic regression. I have read literature that says both using this dataset as is, or over/undersampling will do a better job.
Given this conflicting information, does anyone have any experience in this area? Would I be better off first balancing the classes (maybe not to the extent of 50:50), or would it not matter for logistic regression.
There are around 15000 data points - 200 of which belong to the minority class.
Comment: Logistic regression will work just fine. It doesn't care about the balance. What do you want to do with your analysis?
Comment: As a general principle of statistics, any method that requires discarding data to work should be avoided.  Logistic regression handles extreme imbalances fine.
Comment: How much data do you have?
Comment: Just want to build a model for prediction. I thought I ma need to resample my calibration dataset to overcome the unbalance.
Answer: You could simply try both approaches and see if re-balancing helps. Adjusting the cutoff is probably a good idea as well.
It would be better to completely reshuffle your training and test set every time you change something to the algorithm. Also, if you want to have statistically significant comparisons, you need an experimental setup that produces multiple sample points.
On the other hand, logistic regression with its hyperplane separation doesn't have a high risk of overfitting. It can't come up with non-linear separation surfaces. So this rigorous approach is less crucial here than with neural nets for example.


Unable to understand useCapture parameter in addEventListener

Question: I have read article at https://developer.mozilla.org/en/DOM/element.addEventListener but unable to understand useCapture attribute. Definition there is:

If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTargets beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture.

In this code parent event triggers before child,so I am not able to understand its
behavior.Document object has usecapture true and child div has usecapture set false and document usecapture is followed.So why document property is preferred over child.

function load() {
  document.addEventListener("click", function() {
    alert("parent event");
  }, true);

  document.getElementById("div1").addEventListener("click", function() {
    alert("child event");
  }, false);
}

click me

Comment: Another good answer can be found here https://stackoverflow.com/a/25591239/14824067
Answer: Events can be activated at two occasions: At the beginning ("capture"), and at the end ("bubble").

Events are executed in the order of how they're defined. Say, you define 4 event listeners:

window.addEventListener("click", function(){console.log(1)}, false);
window.addEventListener("click", function(){console.log(2)}, true);
window.addEventListener("click", function(){console.log(3)}, false);
window.addEventListener("click", function(){console.log(4)}, true);

The log messages will appear in this order:

2 (defined first, using capture=true)
4 (defined second using capture=true)
1 (first defined event with capture=false)
3 (second defined event with capture=false)
Comment: @tjameson The order of execution *is* guaranteed in the successor to the DOM2 spec, [DOM3 events](http://www.w3.org/TR/DOM-Level-3-Events/#h2_dom-event-architecture): "the implementation must determine the current target's [candidate event listeners](http://www.w3.org/TR/DOM-Level-3-Events/#glossary-candidate-event-handlers). This must be the list of all event listeners that have been registered on the current target in their order of registration."
Comment: Order of execution is [not guaranteed](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-basic): `no specification is made as to the order in which they will receive the event with regards to the other EventListeners on the EventTarget`. I haven't tested all browsers, so they may all just happen to implement it the same way. Capture events will, however, be done before non-capturing events.
Comment: No idea why this is the accepted answer since afaik, capturing and bubbling talks about propagation behavior and not about dictating the order of execution for multiple, adjacent event handlers
Comment: so this is basically got to do with event order i guess
Comment: @slier, yes, the order in which multiple handlers for the same event are executed.
Comment: Can anyone suggest a general guiding principle as to when we should use `useCapture === true`? It seems that in many cases it will be quite irrelevant.
Answer: I find this diagram is very useful for understanding the capture/target/bubble phases:
http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-phases
Below, content extracted from the link.
Phases
The event is dispatched following a path from the root of the tree to this target node. It can then be handled locally at the target node level or from any target's ancestors higher in the tree. The event dispatching (also called event propagation) occurs in three phases and the following order:

The capture phase: the event is dispatched to the target's ancestors
from the root of the tree to the direct parent of the target node.
The target phase: the event is dispatched to the target node.
The bubbling phase: the event is dispatched to the target's
ancestors from the direct parent of the target node to the root of
the tree.

The target's ancestors are determined before the initial dispatch of the event. If the target node is removed during the dispatching, or a target's ancestor is added or removed, the event propagation will always be based on the target node and the target's ancestors determined before the dispatch.
Some events may not necessarily accomplish the three phases of the DOM event flow, e.g. the event could only be defined for one or two phases. As an example, events defined in this specification will always accomplish the capture and target phases but some will not accomplish the bubbling phase ("bubbling events" versus "non-bubbling events", see also the Event.bubbles attribute).
Comment: I just wish all the resources that explained the "what" included a "why".  Off to more googling as usual.
Comment: How about the children of the target node? When do they get the event?
Comment: @Aurimas they don't, it wouldn't make sense. The target is the inner-most element that should receive the event. If you i.e. click on  element (an empty place), all elements inside  (= all elements of page) should obviously not receive the click event.
Comment: Is the root of the tree actually `Window`, instead of `document`, because `document` is a child of `Window`?
Comment: The diagram comes from the W3C. https://www.w3.org/TR/2000/CR-DOM-Level-2-20000307/introduction.html
Answer: Capture Event (useCapture = true) vs Bubble Event (useCapture = false)
MDN Reference

Capture Event will be dispatch before Bubble Event
Event propagation order is

Parent Capture
Children Capture
Target Capture and Target Bubble

In the order they were registered
When the element is the target of the event, useCapture parameter doesn't matter (Thanks @bam and @legend80s)

Children Bubble
Parent Bubble

stopPropagation() will stop the flow

Demo
Result:

Parent Capture

Target Bubble 1
(Because Capture and Bubble of Target will trigger in the order they were registered, so this is trigger first)

Target Capture

Target Bubble 2

Parent Bubble

var parent = document.getElementById('parent');
var target = document.getElementById('target');

// "target" will trigger in the order of register (addEventListener()), capture / bubble don't affect the order
// #2
target.addEventListener('click', function (e) {
console.log('Target Bubble 1');
// e.stopPropagation();
}, false);

// #3
target.addEventListener('click', function (e) {
console.log('Target Capture');
// e.stopPropagation();
}, true);

// #4
target.addEventListener('click', function (e) {
console.log('Target Bubble 2');
// e.stopPropagation();
}, false);

// #1 : "parent capture" first
parent.addEventListener('click', function (e) {
console.log('Parent Capture');
// e.stopPropagation();
}, true);

// #5 : "parent bubble" last
parent.addEventListener('click', function (e) {
console.log('Parent Bubble');
// e.stopPropagation();
}, false);

    <button id="target" style="padding: 1em 0.8em;">
        Trigger event
    </button>

Comment: There is a mistake in example: you declared child events in the order:
1. child capture
2. child bubble
It matters! Just because if the Child will be the target of the event, listeners will be called in the same order. See the note at MDN: when the element is the target of the event 'useCapture' parameter doesn't matter. (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
Comment: **Note**: For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. `Events in the target phase will trigger all listeners on an element in the order they were registered, regardless of the useCapture parameter.` From https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener. So there exists no phase of "Children Capture" and "Children Bubble".
Comment: And that explains why running the example produces "Children bubble 1" before "Children capture", when the diagram suggests that "capture" should always occur first for any element!
Answer: When you say useCapture = true the Events execute top to down in the capture phase when false it does a bubble bottom to top.
Answer: Summary:
The DOM spec described in:
https://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-phases
works the following manner:
An event is dispatched following a path from the root (document) of the tree to the target node. The target node is the most deep HTML element, i.e. the event.target. The event dispatching (also called event propagation) occurs in three phases and the following order:

The capture phase: the event is dispatched to the target's ancestors from the root of the tree (document) to the direct parent of the target node.
The target phase: the event is dispatched to the target node. Target phase is always on the deepest html element on which the event was dispachted.
The bubbling phase: the event is dispatched to the target's ancestors from the direct parent of the target node to the root of the tree.

Example:

// bubbling handlers, third argument (useCapture) false (default)
document.getElementById('outerBubble').addEventListener('click', () => {
  console.log('outerBubble');
}, false)

document.getElementById('innerBubble').addEventListener('click', () => {
  console.log('innerBubble');
}, false)

// capturing handlers, third argument (useCapture)  true
document.getElementById('outerCapture').addEventListener('click', () => {
  console.log('outerCapture');
}, true)

document.getElementById('innerCapture').addEventListener('click', () => {
  console.log('innerCapture');
}, true)
div:hover{
  color: red;
  cursor: pointer;
}

click me to see Bubbling

click me to see Capturing

The above example really illustrates the difference between event bubbling and event capturing. When adding the event listeners with addEventListener, there is a third element called useCapture. This a boolean which when set to true allows the event listener to use event capturing instead of event bubbling.
In our example when we set the useCapture argument to false we see that event bubbling takes place. First the event at the target phase is fired (logs innerBubble), and then via event bubbling the event in the parent element is fired (logs outerBubble).
When we set the useCapture argument to true we see that the event in the outer
 is fired first. This is because the event is now fired in the capturing phase and not the bubbling phase.
Answer: It's all about event models: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow
You can catch event in bubbling phase or in capturing phase. Your choice.
Take a look at http://www.quirksmode.org/js/events_order.html - you'll find it very useful.
Comment: links to w3 are as or even less useful than google search i cant understand anything there.
Comment: Yeah, that w3 link is just a huge bunch of words, but opposite to it, that second link to _quirksmode_ site explains the topic very well and briefly.
Answer: Code example:

  Outer Div

    Inner Div

Javascript code:
d1 = document.getElementById("div1");
d2 = document.getElementById("div2");

if both are set to false
d1.addEventListener('click',function(){alert("Div 1")},false);
d2.addEventListener('click',function(){alert("Div 2")},false);

Executes: Onclicking Inner Div, alerts are displayed as:
 Div 2 > Div 1
Here the script is executed from the inner element: Event Bubbling (useCapture has been set to false)
div 1 is set to true and div 2 set to false
d1.addEventListener('click',function(){alert("Div 1")},true);
d2.addEventListener('click',function(){alert("Div 2")},false);

Executes: Onclicking Inner Div, alerts are displayed as:
 Div 1 > Div 2
Here the script is executed from the ancestor / outer element: Event Capturing (useCapture has been set to true)
div 1 is set to false and div 2 set to true
d1.addEventListener('click',function(){alert("Div 1")},false);
d2.addEventListener('click',function(){alert("Div 2")},true);

Executes: Onclicking Inner Div, alerts are displayed as:
 Div 2 > Div 1
Here the script is executed from the inner element: Event Bubbling (useCapture has been set to false)
div 1 is set to true and div 2 set to true
d1.addEventListener('click',function(){alert("Div 1")},true);
d2.addEventListener('click',function(){alert("Div 2")},true);

Executes: Onclicking Inner Div, alerts are displayed as:
 Div 1 > Div 2
Here the script is executed from the ancestor / outer element: Event Capturing since useCapture has been set to true
Comment: What's the meaning of the "greater than" chevrons in this context?
Comment: It is just an arrow indicating execution order, as in "Div 1 first, Div 2 second"
Answer: Given the three phases of event travel:

The capture phase: the event is dispatched to the target's ancestors from the root of the tree to the direct parent of the target
  node.
The target phase: the event is dispatched to the target node.
The bubbling phase: the event is dispatched to the target's ancestors from the direct parent of the target node to the root of the
  tree.

useCapture indicates for which phases the event travel will be on:

If true, useCapture indicates that the user wishes to add the event
  listener for the capture phase only, i.e. this event listener will not
  be triggered during the target and bubbling phases. If false, the
  event listener will only be triggered during the target and bubbling
  phases

Source is the same as the second best answer: https://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-phases
Answer: The order of definition only matters if the items are at the same level.  If you reverse the order of definition in your code you will get the same results.
However, if you reverse the useCapture setting on the two event handlers, the child event handler responds before that of the parent.  The reason for this is that the child event handler will now be triggered in the capture phase which is prior to the bubbling phase in which the parent event handler will be triggered.
If you set useCapture to true for both event handlers--regardless of order of definition--the parent event handler will be triggered first because it comes before the child in the capturing phase.
Conversely, if you set useCapture to false for both event handlers--again regardless of order of definition--the child event handler will be triggered first because it comes before the parent in the bubbling phase.


Random effects ANOVA: what happened to the assumption of independence?

Question: It's often stated that regular (fixed effects) ANOVA assumes independence of observations, but that in random effects ANOVA there is no such assumption.
I think the following represents a standard way to represent the two ANOVAs with formulae:

$Y_{ij} = \beta_{0} + \beta_{j} + \epsilon_{ij}$ (fixed effects ANOVA)
$Y_{ij} = \gamma_{00} + u_{j} + \epsilon_{ij}$  (random effects ANOVA)

I think I understand the basics of the difference between the two, inasmuch as in the fixed effects ANOVA the null hypothesis is that the $\beta_{j}$s is equal to zero, whereas in random effects ANOVA the null hypothesis is that $u_{j}$ has zero variance.
However, those two null hypotheses seem fundamentally similar to me, and I don't see how they license the relaxation of the assumption of independence.
Answer: In the random effects ANOVA the observations $Y_{ij}$ with common $j$ are not independent, because they share the common random effect $u_j$.  But the independence assumption in this models are not about the observations, it is about the error terms $\epsilon_{ij}$.  Both models contain this terms.
For the fixed effects ANOVA this details does not matter much, since in fact also the $Y_{ij}$ are independent. But when entering into random effects models, this detail matters!


Finding the Units Digit to 7 to the 2945

Question: How would I go about finding the Units Digit to 7^(2945)?
I know that:
7^0 = 1
7^1 = 7
7^2 = 49
7^3 = 343
7^4 = 2401
...
7^9 = 40353607
Comment: What pattern do you see in the units digits of that sequence?
Answer: when u are interested only in the unit digit you can multiply step by step like u did in your post but you can forget the other digits.
So you have $$7^2 = 49$$ however you forget what was it exactly and u only remember that $$7^2 = x\cdot 10 + 9 $$
you multiply again
$$7^3=7^2 \cdot 7 = 70x+63 = (7x+6) \cdot 10+3$$
yet again you only remembering that it looked like
$$7^3=x_3 \cdot 10 +3$$
as you can see you dont have to remember $7^9 = 40353607$, $7^9 =x_9 \cdot 10 +7$ will be enougth
so now we can repeat you what u did but make it simpler. We can note that

if the $7^n$ ends with $1$ then $7^{n+1}$ ends with 7
if the $7^n$ ends with $7$ then $7^{n+1}$ ends with 9
if the $7^n$ ends with $1$ then $7^{n+1}$ ends with 3
if the $7^n$ ends with $1$ then $7^{n+1}$ ends with 1

so the sequence of units digits will be $(1,7,9,3,1,7,3,9,\ldots)$
now you want 2945th element of that sequence. The value repeats itself evey 4 steps.$$a_n=a_{n-4}$$
and also
$$a_n=a_{n-20}$$
$$a_n=a_{n-100}$$
so u can say that:
$$a_{2945}=a_{45}=a_5=a_1=7^1=7$$
Answer: as you know $7^4$ is a number whose units digit is 1. You can write $7^{2945}$ as $7^{(736\times 4+1)}$ or alternately as $(7^4)^{736}7^1$ as the first factor when simplified  will be a number whose units digit is 1 so the answer is a number ending with "7" as its unit digit...
Comment: Guide to the MathJax formula (and much else) formatting tool: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: It is easy to verify that$$7^{4n+k}\equiv 7,9,3,1\pmod{10}\text{  when }k=1,2,3,4 \text{ respectively}$$ Hence
$$7^{2945}=7^{4\cdot736+1}=(7^{736})^4\cdot 7\equiv 7\pmod{10}$$


How can I check using javascript or vbscript that a url has loaded completely or not?

Question: I have a set of url.I need to check whether those url have loaded completely or not and record the time taken to for the page to load completely.I can take care of the time if somehow I know how can I know if that url is loaded completely using java script or vbscript
Answer: You can use javascript to control iframe event Like:

var beforeLoad;
function newSite() {
   beforeLoad = (new Date()).getTime();
   $("#res").html('loading...');
   //loadURL(document.getElementById('urltext').value);//to deal with The X-Frame-Options response header
   document.getElementById('myframe').setAttribute('src', document.getElementById('urltext').value) ;
}
$('#myframe').load(function(){
 $("#res").html('This request took '+(new Date().getTime() - beforeLoad)+' ms');

});

<input type="text" value="https://en.wikipedia.org" id="urltext" />
<input type="button" value="Go" onClick="newSite()" />

And it can deal with The X-Frame-Options response header use:

<input type="text" value="" id="urltext" />
<input type="button" value="Change site" onClick="newSite()" />


Why the factorial in this analytical form of Dirichlet function?

Question: On Mathworld I found that the Dirichlet function can be written as
$D(x)=\lim_{m\to\infty}\lim_{n\to\infty}\cos^{2n}(m!\pi x)$
Is the exclamation mark a factorial and why do you need it there? Why can't you absorb this monotonic function into the limit?
Answer: The factorial is necessary because otherwise the outer limit may not exist. Say $x=\frac{1}{2}$. Then the inner limit (if $m!$ is replaced by $m$) would fluctuate depending on $m$, sometimes being $1$ and other times being $0$, depending on whether $m$ is a multiple of $2$.
With the current form with $m!$, once $xM!$ is an integer for some $M$, for all $m\ge M$, $xm!$ is also an integer. That's why this works.
To answer your question about why this can't be absorbed into the limit, note that this limit is the limit of a sequence, not that of a function. $m$ can only take integral values. While it's impossible for the limit of a subsequence $(a_{n_k})$ to be distinct from the limit of the sequence $(a_n)$, this only applies if $(a_n)$ actually converges. It's possible for $(a_{n_k})$ to converge and not $(a_n)$, which is what happens here.


Json_encode in While Loop

Question: I need to get data from the database with ajax and put that data in the 'select' tag. I need to have every name in a different 'option'... View the code:
Index.php:
Select:
<select id="users"></select>

JS:
$(document).ready(function() {
setInterval(function() {
    $.get("frombase.php", function(data) {
        data = JSON.parse(data);
        for (var id in data) {
            $("#users").empty();
            $("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
        }
    });
}, 1000);

});
And frombase.php:
$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);

$name = array();

while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));

mysqli_close($db);

Look at the result (I do not need this)

(My english is not good, because I use Google Translate)
Comment: Just do `echo json_encode($name);`. There's no need to put it in another array. Or if you want to keep it as is, then in your JS, do: `for (var id in data.name])` and then `+ data.name[id] + `.
Comment: You should probably also call `$("#users").empty()` _before_ the loop. If it's in the loop as it is now, it will empty the select box on each iteration and you'll only end up with the last name.
Comment: Or change JS loop to `for (var id in data.name) {`. Note however is not good practice to is `for in` loops on arrays
Answer: I would do in this way...
JS:
        $(document).ready(function() {
            $.ajax({
                url :'frombase.php',
                type: "POST",
                dataType: "json",
                success : function(data){
                    $("#users").empty();
                    $(data['options']).each(function(k,v){
                        $("#users").append("<option value='"+ v['id'] +"'>"+ v['name'] +"</option>");
                    });
                },
                error:function(){
                    alert('Error of server comunication');
                }
            });
        });

PHP:
    $db = 'YOUR CONNECTION';
    $query = $db->prepare("SELECT id,name FROM users");
    $query->execute();
    $query->bind_result($id,$name);

    while ($query->fetch()) {
        $result[] = array('id'=>$id,'name'=>$name);
    }
    $root['options'] = $result;
    $root = json_encode($root);
    $db->close();
    echo $root;

Json_encode in While Loop


SQLite invalid conversion from 'char' to 'const char*' [-fpermissive] in CPP

Question: Need to update database by new value (Name and Address) provided by the user.The error in query is that:

error: invalid conversion from 'char' to 'const char*' [-fpermissive]   sqlite3_bind_text(res, 2, *c2)

error: too few arguments to function 'int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void ()(void))'
     sqlite3_bind_text(res, 2, *c2)

my code is:
        const char *c1 = updatedName.c_str();
        const char *c2 = updatedAdd.c_str();

char *sql = ("UPDATE RECORDS SET NAME = ? AND ADDRESS = ? WHERE ACCOUNT_No = ?");
        rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
        sqlite3_bind_text(res, 1, *c1);
        sqlite3_bind_text(res, 2, *c2);
        sqlite3_bind_int(res, 3, acc);
        rc = sqlite3_step(res);
        sqlite3_finalize(res);

Comment: sorry, a function must be passed as last arg. Check the documentation... some example: http://stackoverflow.com/questions/19927188/sqlite3-bind-text-on-select-different-result-on-prepared-vs-string-sql-statemen
Comment: 1. This is perhaps because of argument mis-match, when not enough arguments were supplied. As Jean-François said, please read the man pages.
Comment: also, `*c1` and `*c2` are of type `const char` and the function ask for `const char*`.
Comment: 2. The compiler is telling you that `sqlite3_bind_text` takes 5 arguments but you only provide 3, so 2 arguments are missing.
Comment: @Jean-FrançoisFabre it is throwing too few arguments to function 'int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void (*)(void*))'
             sqlite3_bind_text(res, 1, c1, 0); this error
Answer: sqlite3_bind_text() wants a pointer to the entire string, not only the first character. (You need to understand how C pointers and strings (character arrays) work.)
And the sqlite3_bind_text() documentation tells you to use five parameters:
sqlite3_bind_text(res, 1, updatedName.c_str(), -1, SQLITE_TRANSIENT);

SQLite invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] in CPP


How to create hosted app that allows clients to extend it as they like

Question: I have an application in heavy development status that I would like to allow my users/clients to extend as their needs (with limitations in plan and etc.) What approach could I use to enable the deployment of own code in to the application?
The options which I was able to think of are:

Mapper file in the root of a PHAR archive which says what is what. (Kinda like in java :D)
Manual Deployment, clients upload their code, which we review and put it where it is supposed to go (Which will result in many unhappy customers, b`cuz it will take time to review the code...)

I was thinking in every aspect I could though of, the DB is separated for each app so not much of a concern, but the code could expose many many things which could destroy the business.
What I am looking is a good approach, fresh point of view, possible bumps along the way and fresh ideas.
Thanks!
Answer: Have you considered using a scripting language such as Lua? You can choose what functions are exposed to your clients and so there is little risk because clients will lack the functionality to severely screw up your infrastructure.


Is there any notable difference between studying the Riemann integral over open intervals and studying it over closed intervals?

Question: (1) A function $f:[a,b]\to\mathbb{R}$ is said to be Riemann integrable on $[a,b]$ . . .
(2) A function $f:(a,b)\to\mathbb{R}$ is said to be Riemann integrable on $(a,b)$ . . .
Suppose a book started the exposition like (1) and other started like (2). My question is: Has every theorem that is valid for first definition, a analogue for the second?
I think most of the books (at least my calculus books and analysis books) uses closed intervals, but I started to study Lebesgue Integral and in the first chapter of book the author presents a review about Riemann integral and considers functions defined on open intervals.
Maybe it's trivial, but I would like know if there is a reason for choose to work with open intervals instead of closed intervals.
Thanks.
Comment: You should look up this question, [http://math.stackexchange.com/questions/201566/why-does-the-definition-of-an-integral-specify-a-closed-interval]
Comment: See also this [question](http://math.stackexchange.com/questions/99753/why-is-the-riemann-integral-only-defined-on-compact-sets).
Answer: There is no such thing as a "Riemann integral defined over the open interval $\ ]a,b[\ $".
The definition of the Riemann integral deals with bounded functions defined on a compact ($=$ finite closed) interval $[a,b]$.
It turns out that when you take  a function which is Riemann-integrable on $[a,b]$ and change its values on a very small set, e.g., on a finite set, then the value of the integral does not change. It follows that when you have a function on the open interval $\ ]a,b[\ $ which is Riemann-integrable on $[a,b]$ for any values you might choose at $a$ and $b$ then the Riemann integral of $f$ over $[a,b]$ is well defined.
It is a completely different matter when you are forced to consider integrals of the form
$$\int_{a+\epsilon}^{b-\epsilon'} f(x)\ dx$$
with $\epsilon$, $\epsilon'>0$ in order to get hold of the "integral" you actually want, e.g., when you want to consider the integral
$$\int_0^1{1\over\sqrt{x(1-x)}}\ dx\ .$$ In this case one would speak of an improper Riemann integral.


Diagonalize the matrix using simultaneous row and column operations?

Question: I need to diagonalize the matrix $$\left[\matrix{1 & -1\\-1 &3}\right]$$ using simultaneous row and column operations.
My attempt is to do $R2+R1 \to R2$ and $C2+C1\to C2$, and this brings the matrix to $\left[\matrix{1 & 0\\0 &-4}\right]$. Doing the same row operations to the identity matrix, I get $\left[\matrix{1 & 0\\1 &1}\right]$.
From what I understand, in the form $P^TAP = D$, is that $P^T=\left[\matrix{1 & 0\\1 &1}\right]$ and $D=\left[\matrix{1 & 0\\0 &-4}\right]$.
But I have plugged this into Wolfram Alpha and I know that my answer is incorrect. I'm not sure where to go from here.
Comment: You mean you want to diagonalize the matrix $A = \begin{bmatrix} 1 & - 1\\ -1 & 3\end{bmatrix}$?
Comment: Just a remark. You are never accepting people's answer (basically, the message is "I am nor happy with your explanation"), so it is quite hard to expect more help from them.
Comment: Yes that is the matrix that I want to diagonalize. And sorry A.G., I have gone through and accepted answers to all my questions.
Answer: When I calculate $R2+R1 \to R2$ and $C2+C1\to C2$, I get
$$
\left[\matrix{1 & 0\\0 &2}\right].
$$
Check out your calculations once again. Note $\color{green}{2}=\color{red}{+}3-1$, $\color{green}{-4}=\color{red}{-}3-1$.
Answer: That matrix does not have eigenvalues 1 and 2 for sure. Also if you want to preserve similarity it is necessary that the simultaneous column operation is the inverse of the raw operation just done. Which is not in your case. You do get a diagonal matrix, but is not similar to the one you started with.