What factors give a "Home Advantage" and how big is it?

Question: Often you hear about the team whose ground the match is being played at having a "home advantage".
During a discussion with a friend they said teams go as far as to style the opposing teams changing room to play mind games; i.e. making the room layout hard for discussion, and the colour scheme being dull so as to lower any motivation.
Personally I thought this was a bit too far (sportsmanship anyone?), but I was curious as to what actually contributes to a home advantage?
Additionally, does anyone know of any studies/ statistics which can prove whether the home advantage is merely a myth, or is a real thing?
Comment: There is some evidence (presented in Freakonomics IIRC) that suggests that the home field team gets an officiating advantage in American football. No clue what the research for international football is, but it will be interesting to see if someone can look towards some studies here.
Comment: See also Wikipedia article: [Home advantage](http://en.wikipedia.org/wiki/Home_advantage).
Answer: I'm not posting this as an answer to rival the others as I feel they are excellent answers.
However, this is pertinent to the question, it's interesting and it is going to be longer than a comment.
Why it's better to be the home team
I've read a number of articles over the years about how playing an away game can be a considerable disadvantage above the obvious difference in supporter numbers.  Here are some that I recall.

Middlesbrough's Riverside Stadium's away team dressing room is 'L'-shaped.  Not only does this subconciously suggest "Lose" but it makes inter-team communication more difficult as the manager has to talk around a corner.
It was noted that some away dressing rooms had the tactics board in full view of the corridor.
During a Champion's league game between Chelsea and Barcelona it was suggested that the away team dressing room only had three working showers and one mirror.
Away teams have considerably less space to get prepared.  The home side often has adequate locker space for 4 or 5 pairs of boots and plenty of bench space to get ready whereas away dressing rooms are often smaller, more cramped affairs.
Simple luxuries.  Huge TV screens, ice baths, carpets, more treatment tables etc.
I recall Roy Keane ensuring that Sunderland's away dressing room had pictures of Sunderland winning all over it as a bit of a mind game.
The away team probably slept in a hotel the night before the match whereas the home players would have slept in their own beds.
The away team may have travelled a considerable distance/time and may be fatigued as a result.

Finally, a couple of interesting articles:
The Guardian
The Independent
And here's a BBC Magazine article on "The Science of Home Advantage".
Answer: There have been quite a few studies in football/soccer discussing home field advantage.
In blog post titled "Home Field Advantage: What You See Depends On Where You Look (And What You Make Of Draws)" (Wayback Machine), Chris Anderson writes about a book discussing home field advantage in football:

In these chapters, Moskowitz and Wertheim first document that the home
field advantage is ubiquitous across different team sports, as well as
across leagues and over time. They also argue that most of the
advantage home teams seem to have stems from referee decisions, rather
than things like travel, schedule, weather, or any other number of
factors that have been proposed over the years.

The abstract for "Home advantage in soccer: A retrospective analysis" (full article must be purchased) notes:

The existence of home advantage has been established for all major
professional team sports in England and North America. The advantage
was found to be greatest in soccer, with the home team currently
obtaining about 64% of all points gained in the English Football
League. Home advantage has changed very little since the formation of
the League in 1888 and there are only small variations between the
four Divisions of the League. The advantage is less marked in local
derbies, in the FA Cup and in non‐professional competitions. It is
greater in the European Cup and increases as the stages of the
competition progress. The allocation of three points, instead of two,
for a win in the Football League has not changed home advantage, but
its effect has been greatly reduced in the GM Vauxhall Conference
where an away win gains more points than a home win. The statistical
evidence suggests that crowd support and travel fatigue contribute
less to home advantage in soccer than do the less easily quantifiable
benefits of familiarity with conditions when playing at home.

From these two resources and information from this thread, it appears that the subconscious biases exhibited by referees and the familiarity of home conditions play the largest factors in home field advantage.
Comment: +1 for great sources. It's weird that in my head I had contributed crowd support as the main reason, and had disregarded a teams familiarity with conditions.. how wrong was I!
Comment: @matt, I was surprised too - I thought that crowd support and fatigue would've been larger factors than familiarity with the home conditions.
Answer: I can think of three key factors that are quite logical conjectures.

The crowd is more than likely cheering for them, and cheering against their opponent. It gets very loud on the pitch and very hard to concentrate. For example in American football, the guard often has to signal the center to snap because the center can't hear the quarterback because it's so loud. This causes great confusion and miscommunication. The morale aspect is important too.
The home team is more familiar with the field. Is this field easier to slip on than most? Is the grass longer? The environmental factors and familiarity will give you an edge over your opponent, as they need to consciously adjust their style to suit the field, while you, having practiced on this field and played on this field, have a much more natural attunement to it.
Lack of travel. Travel is very exhausting, even when you have professional clubs who spare no expense in keeping the players comfortable. You lose a day of preparation traveling as well, but the home team gets that extra day to stay loose and freshen up. If the away team is on the second or third consecutive travel, it can take a pretty heavy toll on their mental and physical state.

As for how big it is the advantage is, a study has indicated that for every 10,000 people in the stands, a home team in the English Premiership will score an additional 0.1 goals, on average. Wikipedia sums this up to 37% more goals, although how they reach that from the article presented is at present unclear. It is significant enough that they now track 'away goals' as a way to break ties.
Comment: not sure how common this is in other sports but in baseball the grounds crew will sometimes communicate with the home players about how they want the grass cut etc.
Answer: Being extremely interested in this myself, I used data taken from the English 2010-2011 season (Wayback Machine) in the Premier League, Championship and divisions 1 and 2, to compile the following statistics;
<code>Division       | # of Games | % Home Wins | % Away Wins | % Draws | # Home Wins | # Away Wins | # Draws |
Premier League | 380        | 47.1        | 23.7        | 29.2    | 179         | 90          | 111     |
Championship   | 552        | 44.6        | 28.6        | 26.8    | 246         | 158         | 148     |
League 1       | 552        | 45.1        | 30.1        | 24.8    | 249         | 166         | 137     |
League 2       | 552        | 40.8        | 28.8        | 30.4    | 225         | 159         | 168     |
TOTAL          | 2036       | 44.2        | 28.1        | 27.7    | 899         | 573         | 564     |
</code>
From this, it's easy to see that the team playing at home has a considerable advantage.
1 idea we could perhaps draw from this is that the environment provided by the spectators play a role in the size of the home advantage; the attendance at matches dwindle the further down the leagues we go, and we can also see that the %age of home wins drops as well.
Indeed, these provides the stats/data that was asked for in the question, but as for reasons why, I'll leave others to answer!
Comment: Your numbers for premier league do not add up to 100%. I suspect draws is the problem. You have a higher `away win %` than `draw %`, but you have more `draw #` than `away win #`.
Answer: I realize your question isn't about ice hockey, but there is one advantage in the rules that the home team gets in the NHL.
The home team gets "last change". This means that, on a faceoff, for instance, when both teams are changing, the visiting team has to make their line change before the home team does. This gives the home team the ability to tailor their players or pick a specific line to match whoever the visiting team has sent out. This tends to be something like putting out your top defensive pairing if the other team sends out their first line, or putting out your first line if the other team sends out their fourth.
Some coaches rely heavily on line-matching and it is much easier to do when you have "home ice advantage" due to the first change rule.
More Information

82.1 Line Change - Following the stoppage of play, the visiting team shall promptly place a line-up on the ice ready for play and no substitution shall be made from that time until play has been resumed. The home team may then make any desired substitution, except in cases following an icing, which does not result in the delay of the game.
Answer: Home advantage is a huge thing, a lot in  say a contact sport like football and rugby but its almost like having an extra player when we are talking about a sport like cricket.
In cricket basically if its a bilateral series, you get to decide your own pitch and the pitch determines what kind of match if could be, whether it would help the slow bowlers or pacers etc. So a team with better slow bowlers would go with a dusty pitch.
In terms of cricket just look at the number of bilateral series' that happen, I guess most of the time the home team ends up as winners.
If you were compare the performances of India since 2012 in test cricket against England, at home India has a 55% win record, 75% against the Aussies and 85% against South Africa. While the away record shows that India has a 20% win record in Eng and SA and 18% in Australia. So I guess home advantage matters a lot.
In terms of other sports like football and rugby I'd say the supporters shouting you're names will pump you up and kind of serves as a motivational factor during the game. Also they create a hostile environment for the opposing players which can make their in game thinking quite slow.
Comment: Welcome to Sports! While I don't disagree with this, are you able to provide any statistics to back up this answer?
Comment: In terms of cricket just look at the number of bilateral series' that happen,I guess most of the time the home team ends up as winners. If you were compare the performances of  India  since 2012 in test cricket against England,at home India has a 55% win record, 75% against the Aussies and 85% against South Africa. While the away record shows that India has a 20% win record in Eng and SA and 18% in Australia. So I guess home advantage matters a lot.
Comment: That's some good statistics for cricket - could you please [edit them into your answer](https://sports.stackexchange.com/posts/24831/edit)? Do you have similar statistics for the other sports you refer to?


Porque as bolas azuis não ficam posicionada ao centro da coluna?

Question: Estou a criar uma página com um Grid Bootstrap e coloquei quatro bolas azuis numa das colunas... O problema é que não consigo colocar as bolas azuis no centro da coluna (elas ficam sempre posicionadas no lado esquerdo quer na posição inicial e também quando se reduz a página). Como faço para que as 4 bolas azuis fiquem sempre no centro da coluna e responsivas?
https://www.clubesorte.org/e_tombolas/a_originais/lotarias-e-rifas_1x/t1_as_ca4.html
Posição ERRADA

Posição CORRECTA

`
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
    <link href="./css/lotti.css" rel="stylesheet" type="text/css">

    <title>Tombola Dinamica</title>

      <link href="http://clubesorte.org/b_styles/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

SUPER-PRÉMIO

Boa-sorte!

FORM

VER RESULTADOS
    PATROCINADOR

<audio id="audio" controls tabindex="0" style="width:220px; height:25px;">
    <source type="audio/mp3" src="https://www.clubesorte.org/c_elements/musicas/presentation/Quirky%20-%20AShamaluevMusic.mp3">
    Sorry, your browser does not support HTML5 audio.
</audio>

---

---

`

Answer: O problema está na linha 111 do lotti.css (Exclua ela e teste). Aqui funcionou pra mim!
d4w4 {/* width:164px; */}
Comment: Obrigado ao Pedro Paulo pela dica... mas se apagar o css de " d4w4 {/* width:164px;" também não funciona... porque se retira o tamanho das linhas e assim ao colocar mais bolas, por exemplo 10 bolas, ficam todas em linha e eu pretendo que cada linha tenha 4 bolas (4 na horizontal e 4 na vertical), tal como se mostra nos novos desenhos que coloquei na sua edição.


Notificações em tempo determinado e ao ligar celular

Question: Olá.
Estou fazendo um app android que me notifica quando tenho que entregar uma tarefa de escola e, caso seja o dia da tarefa ou um dia antes, quero ser notificado em certos horários.
A tela inicial é onde o service é iniciado, onde clico em "Tarefas" para ir pra Activity de tarefas.
public class DashboardActivity extends Activity {

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

    startService(new Intent(this, ShowNotificationService.class));
}
}

Mas eu gostaria que o serviço fosse iniciado quando o celular fosse ligado (como o Whatsapp mostra notificações de mensagens quando ligamos o celular).
Código do showNotificationService.class
public class ShowNotificationService extends Service {

private EducInDAO dao;
private DatabaseHelper helper;
private Context context;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    helper = new DatabaseHelper(this);
    try {
        tarefas();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

public void tarefas() throws ParseException {
    SQLiteDatabase db = helper.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM tarefas", null);

    if (cursor == null) {

    } else {
        while(cursor.moveToNext()) {

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date dataEntrega = new Date(cursor.getLong(2));
            Date dateNow = new Date();

            String dataEntregaFormatada = sdf.format(dataEntrega);
            String dateNowFormatada = sdf.format(dataEntrega);

            GregorianCalendar calendar = new GregorianCalendar();
            int hora = calendar.get(Calendar.HOUR_OF_DAY);

            if ((dateNowFormatada.compareTo(dataEntregaFormatada) == 0) || (dateNowFormatada.compareTo(dataEntregaFormatada) == 1)) {
                int id = cursor.getInt(0);
                String nomeMateria = cursor.getString(1);

                String title = "Eae, já fez?";

                if ((dateNowFormatada.compareTo(dataEntregaFormatada) == 0)) {
                    if ((hora == 0 || hora == 7 || hora == 12 || hora == 23)) {
                        if ((hora == 0 || hora == 7 || hora == 12)) {
                            String contentText = "Você tem tarefa de " + nomeMateria + " para hoje!";
                            Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
                            v.vibrate(1000);
                            showNotification(title, contentText, id, 1);
                        }
                    }
                } else if ((dateNowFormatada.compareTo(dataEntregaFormatada) == 1)) {
                    if ((hora == 15 || hora == 18 || hora == 22)) {
                        String contentText = "Você tem tarefa de " + nomeMateria + " para amanhã!";
                        Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
                        v.vibrate(1000);
                        showNotification(title, contentText, id, 1);
                    }
                }
            }
        }
    }

    cursor.close();
}

public void showNotification(String title, String content, int id, int tipoNotificacao) {

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(title)
            .setContentText(content)
            .setAutoCancel(true);;

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    if (tipoNotificacao == 1) {
        mBuilder.setSmallIcon(R.drawable.homework);

        Intent resultIntent = new Intent(this, TarefasActivity.class);
        resultIntent.putExtra(Constantes.TAREFA_ID, String.valueOf(id));

        stackBuilder.addParentStack(TarefasActivity.class);
        stackBuilder.addNextIntent(resultIntent);
    }

    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(id, mBuilder.build());
}

}

Mas o que acontece é que ele mostra as notificações, por exemplo, as 22h mas se eu tiro a notificaçao, ela aparece novamente! Então, é tirar que mostra novamente :/
Como resolver?
Answer: Para executar um serviço quando o celular for ligado tem que registar um BroadcastReceiver que responda à action android.intent.action.BOOT_COMPLETED.
No AndroidManifest.xml registe o seu BroadcastReceiver:
<receiver android:name="aSuaPackage.StartUpBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Adicione esta permissão:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Defina o BroadcastReceiver que irá lançar o seu serviço:
public class StartUpBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

            // Chame aqui o seu serviço
        }
    }
}

No serviço defina um método para registar as notificações.
Este método usa o AlarmManager para lançar um BroadcastReceiver que irá criar as notificações na data/hora especificada no paramêtro data.
Chame este método por cada notificação que desejar criar.
private void AgendarNotificacao(Date data) {

 // Obtém um novo calendário e define a data para a data da notificação
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(data);

 // Obtém um alarm manager
    AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);

 // O id a ser usado no pending intent
    int id = (int) System.currentTimeMillis();

 // Prepara o intent que deverá ser lançado na data definida
    Intent intent = new Intent(this, CriarNotificacao.class);

 // Obtém o pending intent
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

 // Regista o alerta no sistema.
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}

Como você tem mais de um tipo de notificação introduza os parâmetros que necessitar para construir a notificação. Passe essa informação ao Intent através de Intent.putExtra();
Defina o BroadcastReceiver que será lançado pelo AlarmManager registado pelo método anterior.
Este BroadcastReceiver é responsável por criar a notificação.
public class CriarNotificacao extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent paramIntent) {

    // Obtenha os 'Extra' que passou e crie aqui a notificação

}

Registe-o no AndroidManifest.xml.
<receiver android:name="aSuaPackage.CriarNotificação"/>

Notas:

É necessário executar a aplicação uma vez antes de ela poder responder à android.intent.action.BOOT_COMPLETED action. O mesmo se aplica caso a sua execução tenha sido parada usando Force Close.
A aplicação necessita de ser instalada na memória do celular.
Comment: Olá, obrigado pela resposta. Fiz o que me pediu, mas não funcionou. Segue o código modificado: http://pastebin.com/fgYui4W8
Comment: Você registou o CriarNotificação no AndroidManifest.xml.? Esqueci de colocar esse pormenor na resposta.
Comment: Estive a ver o seu código e julgo que não entendeu como usar o método AgendarNotificação. Você deve passar ao método a data e hora em que quer ser notificado. Suponha que tem uma tarefa para a data 16/04/2015 às 18h e quer ser notificado 3 horas antes, deverá subtrair à data da tarefa 3 horas e chamar o método com o resultado. Use a classe *Calendar* para construir a *data* a passar ao método. Não esqueça que ao dizer *data* não me estou apenas a referir ao dia, mês e ano mas sim também à hora, minuto e segundo a que quer que a notificação seja lançada.
Comment: Muito obrigado! Assim que possível irei tentar implementar a solução xD
Comment: Funcionou! Obrigado!


Read cookies from nodejs in angular side

Question: I am creating a project using angular and nodejs. I have a problem in my code. I am setting the cookies in nodejs and wants to read the angular side. I don't know how can I achieve this.
Here is setting the cookie
cookies = {expire : new Date(new Date().getTime()+20*60*1000), maxAge : 600000, httpOnly : true, secure : true};
res.cookie('cookiename', "cookievalue", cookies);

In angularjs:
console.log(document.cookie) //get blank value

Please help
Answer: You can use the AngularJS api for that:
https://docs.angularjs.org/api/ngCookies/service/$cookies
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieving a cookie
  var favoriteCookie = $cookies.get('myFavorite');
  // Setting a cookie
  $cookies.put('myFavorite', 'oatmeal');
}]);

Answer: Reading the values is a matter of using the $cookie.get(key) method:
console.log( $cookie.get('cookiename') ); // cookie value

In order to persist your cookies between requests to the server, use this config in Angular:
angular.config(function ($httpProvider) {
  $httpProvider.defaults.withCredentials = true;
})

This will send the cookie data back to the server on XHR calls to your nodejs server.


Is there an IIS log viewer integrated into IIS Manager?

Question: There are quite a few external IIS log analyzers but since IIS 7 has quite a nice administrative UI and new modules can be created for it, is there a module that would display / analyze log files directly from within IIS 7 Manager?
Answer: No, but there are several free and/or cheap options. One I would suggest is Log Analyzer, affordable, and there is a trial as well.
Comment: @petrus Looks good to me.  Q: Is there an IIS log viewer integrated into IIS manager?  A: No.  It's correct too.


Understanding the stack $B\mathbb{Z}$

Question: Here, let $\mathbb{Z}$ be the group scheme whose functor of points is the constant functor which takes a connected affine scheme to the group $\mathbb{Z}$.  I'm having a bit of trouble understanding the stack $B\mathbb{Z}$, in particular quasicoherent sheaves on it.
Here's how I want to approach $BG$ for $G$ say an affine algebraic group.  One can take a smooth atlas $f: * \rightarrow BG$ and apply Barr-Beck to find that the category of coalgebras over the comonad $f^* f_*$ is equivalent to the category of quasicoherent sheaves on $BG$.  One can use smooth base change ($f$ is smooth and thus flat, also separated and finite type, everything is noetherian I think) and see that this comonad is the same as $g_* g^*$ for $g: G \rightarrow *$.  Then a coalgebra is a vector space $V$ (let's say everything is over a field of char 0) which is a comodule for $\mathcal{O}_G$ (ring of global functions).  If $V^*$ is finite-dimensional then we can take symmetric powers and spectrum and get an algebraic action $G \times V^* \rightarrow V^*$ -- here we need that $G$ is affine.  Thus a coherent sheaf on $BG$ is a vector space with a rational action of $G$.  (Is the above correct?  I understand there's also some argument involving Hopf duals, but I'm not sure there's a good analogue for the group ring for $G$ not finite.)
For $G$ not affine (e.g. $G = \mathbb{Z}$, or maybe $G$ an ind-scheme like $\hat{\mathbb{G}}_a$), do we have a way to understand (coherent sheaves on) these objects?
Edit: Extra question.  In the above, I had to assume that $V$ as finite-dimensional, in order for a coaction $k[V] \rightarrow k[V] \otimes k[G]$ to give a rational/algebraic action.  If $V$ is infinite-dimensional (i.e. quasicoherent sheaf instead of coherent sheaf), I'm also not really sure how to proceed.
Comment: I would guess that quasicoherent sheaves on $B G$ for any _discrete_ group $G$ is just $G$-modules.
Answer: If $p : G \to S$ is any smooth group scheme over some base $S$, then $BG:=B(G/S)$ is an algebraic stack over $S$ with a presentation $S \to BG$ (corresponding to the trivial $G$-bundle). (Actually we only need $G \to S$ to be flat, then $BG$ will be an algebraic stack in the sense of Goerss-Naumann.) A quasi-coherent sheaf on $BG$ thus consists of a quasi-coherent sheaf $M$ on $S$ together with an isomorphism $p_1^* M \cong p_2^* M$ on $S \times_{BG} S$ which satisfies the cocycle condition. Using the isomorphism $S \times_{BG} S \cong G$, we get an isomorphism $p^* M \cong p^* M$. This is the same as a $G$-action on $M$, which is a natural family of group homomorphisms $G(T) \to \mathrm{Aut}_{\mathcal{O}_T}(M_T)$ for $S$-schemes $T$. So we get $\mathsf{Qcoh}(BG)=\mathsf{Rep}_S(G)$.
If $\Gamma$ is a discrete group, we may look at its corresponding group scheme $G=\coprod_{g \in \Gamma} S$. Its functor of points is the sheaf associated to the constant presheaf with value $\Gamma$. Therefore, an action of $G$ on a quasi-coherent module $M$ on $S$ is just an action of $\Gamma$ in the usual sense, i.e. a group homomorphism $\Gamma \to \mathrm{Aut}_{\mathcal{O}_S}(M)$. For $\Gamma=\mathbb{Z}$ this action is just an automorphism of $M$.
Hence, quasi-coherent sheaves on $B (\coprod_\mathbb{Z} S)$ are just quasi-coherent sheaves on $S$ equipped with an automorphism of $S$.
Comment: Some details are missing, I will try to include them later.
Comment: Ah, this makes sense.  What I was missing is how to think of a $G$-action by functor of points.  Thanks!
Comment: Perhaps someone can explain (I forgot how to do this) why the isomorphism $p_1^* M \cong p_2^* M$ corresponds to a $G$-action on $M$?
Comment: I'd guess you can do it by functor of points definition for quasicoherent sheaves, i.e. a quasicoherent sheaf on $G$ is a functorial assignment to each affine $T$ and $\eta \in G(T)$ a $T$-module (morally, the pullback to $T$, you can say this more cleanly but I forget the terminology). So a map in $G(T)$ gives you an isomorphism of the pullback of $M$ to $T$, i.e. a $T$-automorphism of $M_T$, which is a $G$-action on $M$
Comment: Yes, this is a very good explanation! And the cocycle condition will (hopefully) correspond to the property that $G(T) \to \mathrm{Aut}(M_T)$ is a group homomorphism.
Comment: Yeah, I guess if one wanted to nitpick, I think Barr-Beck only gives us a morphism $\sigma: p_1^* M \rightarrow p_2^* M$, so here a map $G(T) \rightarrow \End_T(M_T)$, and one of the things the cocycle conditions tells us is that it is in fact an isomorphism... I think I'll post this as a separate question, it's something else I haven't completely figured out.
Comment: 1) One doesn't need Barr-Beck. 2) Recall that the fiber product $X \times_S Y$ of stack morphisms $p:X \to S$, $q:Y \to S$ has as points $(X \times_S Y)(T) = \{(f,g,\sigma) : f \in X(T),g \in Y(T), \sigma : pf \cong qg\}$, and here $\sigma$ is an isomorphism. 3) In case you don't agree with 2: The cocycle condition tells us that $G(T) \to \mathrm{End}_T(M_T)$ is multiplicative. Hence, it has values in $\mathrm{Aut}_T(M_T)$.

Understanding the stack $B\mathbb{Z}$


Linear order and well-order

Question: The question is:
A linear(or total) order (L,=<) is a well-order if and only if (1) for every infinite decreasing sequence
x0 =< x1 =< x2 =< ...
in L, there is an n such that for all m>n, xn =xm.
My answer (sketch) so far:
Assume the linear order (L, =<) and (1).
For every infinite sequence, we have (1). This gives us an xn ( with n the smallest number such that for every m>n, xn =xm.)* for every infinite sequence. These 'xn' will give us another infinite sequence, and with (1) will give us an element xn (with n again the smallest like before) such that for every x in L: xn =< x .
*= I got the hint that I had to use the axiom of choice, but I dont think I need it when I can just pick the smallest n for which this is true?
Comment: @Jay: Tags should describe what the question is about, not what it contains. Just because the axiom of choice is used somewhere does not merit the tag's use. If it were, the tag should have been used a lot more. This tag is reserved for questions which specifically ask about the role of the axiom (or a related principle)  in the proof.
Answer: You have to use the axiom of choice in order to prove that well-ordered are exactly those linear ordered without infinite decreasing sequences.
The reason is that it is consistent to have linearly ordered sets, which are not well-ordered, that have no countably infinite subsets. In fact it is even consistent that such set is a subset of the real numbers.
Your proof seems somewhat unclear to me. If $(L,\leq)$ is a linear order without an infinite decreasing sequence, take $A\subseteq L$ which is non-empty. Pick some $a_0\in A$, if it is was minimal, you are done. Otherwise there is some $a_1\in A$ such that $a_1<a_0$. Continue by induction and define a sequence $a_n$, and show that it is strictly decreasing, which is a contradiction to the assumption that no such sequence exists.
We use the axiom of choice in order to generate the sequence. By induction we only chose one next element, but the axiom of choice assures us that we can make all these choices uniformly and put them into one sequence.
Comment: @Ryan: We can define arbitrarily long sequences by induction, but those are only finite sequences. We need some sort of "glue" to ensure that we can pass from finite sequences of every length to an infinite sequence. This is where the axiom of choice comes in. I think that this is probably one of the more delicate uses of the axiom of choice that I know of (this particular proof).
Comment: With some practice, we can recognize that we used AC, in this case a weak version of AC. Recognizing that it is *necessary* is far harder. We need to prove an independence result, or, more frequently, reduce the problem to someone else's independence result. To do this, we need a thorough knowledge of the various models of ZF that have unusual properties.
Comment: @Ryan: The axiom of induction is for the natural numbers which can be well-ordered to begin with. For general infinite sets you don't necessarily have that, and you need to have a choice function on *some* family of subsets in order to proceed. There is a model, which I mentioned in my answer, where there is a set of real numbers that have no infinite decreasing sequence, but every decreasing sequence can be extended by one more element.
Comment: Ah, so let me get this (and hopefully I will be repeating what you said):

You create a decreasing infinite sequence by picking an element a out of L.
If a is the smallest, we are done. If not, there is at least one element that is smaller than a.
To choose between those elements, we need the axiom of choice.
We can keep going on, but (1) will ensure that we will get a smallest element. Then we are done.

Is that ok?
Comment: Ryan, I am looking for a minimal element of $A$. If I find one, then I stop. But if I didn't find one, then the axiom of choice assures that the choices I made can be coherently put into a sequence which contradicts $(1)$.
Comment: It seems like I have to review the axiom of choice, because I understand the proof, but not why the axiom is necessary.
Comment: @AsafKaragila: Why can you only get finite sequences with induction? The axiom of induction states that we can prove things for all n in N with the usual conditions. Thus, in this example, whenever we have a sequence of n decreasing elements, we can find another, smaller element. With induction this gives a sequence of infinite (as in N) elements.

And: We are creating a sequence of decreasing elements. But (1) will ensure us that this sequence is finite! So why would we need the AC?
Comment: @AsafKaragila I think I get it now, thanks for your help!

This is more explicit: We can find finite sequences of decreasing sequences. Now let A be the set of those decreasing sequences ((x1),(x1,x2),..) and let B the set A with an added element # not in A. Then define f: A -> B with f(x1)=#, f(x1,..,xn+1)=(x1,..,xn). This function is surjective, thus AC gives us a function s:B->A with f(s(b))=b.

Now we can define our sequence, which is a function from N to L, as followed: g(0)=s(#), g(n+1)=s(g(0),..,g(n)).
This function is well defined and gives us the infinite seq. we need for the contr.
Comment: @Ryan, close, but not quite there (at least in the form you have summed the argument into here). Fix $f$ to be a choice function on subsets of $A$ (it is enough to have $f$ choosing from initial segments of the order restricted to $A$). Now define by recursion $F(0)=a$ some $a\in A$; and $F(n+1)=f(\{x\in A\mid x<F(n)\})$ if $F(n)$ is not minimal; and $F(n+1)=F(n)$ if it is minimal. From $(1)$ we know that $a_n=F(n)$ is a decreasing sequence and must therefore stabilize, so we must have found a minimal element, otherwise the sequence would be strictly decreasing in contradiction to $(1)$.

Linear order and well-order


Git Commit Author's Email changing according to the directory and/or project?

Question: I work with my own projects and every-now-and-then I do some work for third-parties where I need to use their contact-information etc in commits. I usually use just global commit names etc but now I need to specify commit names and emails according to the directory. How can I do that in Git?

Perhaps useful relating information

What is the difference between author and committer in Git?
Git commit with no email
Comment: Possible duplicate of [Can I specify multiple users for myself in .gitconfig?](https://stackoverflow.com/questions/4220416/can-i-specify-multiple-users-for-myself-in-gitconfig)
Answer: You can have a per-repository username and email address that supercedes your global settings. It will affect commits made in the current repository, but not in other repositories.
git config user.name "Foo Bar"
git config user.email "firstname.lastname@example.com"

You can confirm that your local information is overriding your global defaults with:
git config -l | fgrep user.

It may show multiple entries (e.g both a global and a local configuration setting), but whatever is shown last in the list takes precedence.
Answer: Use the following command to commit your changes
git commit -m "Commit message" --author "Your Name <email>"

Then you will be able to set the author, email explicitly for that commit.
Comment: ...no way to make this more implicit/automatic perhaps in some file? Perhaps something centralized like gitolite but just for managing commit credentials-and-contacts (not sure whether possible, well hence the q)?
Answer: If you need to specify different author/committer name/email according to folders. You can add a line like this in your .bashrc
PROMPT_COMMAND='[[ $PWD =~ ^path/to/dir.*$ ]] && { export GIT_COMMITTER_EMAIL=email && export GIT_COMMITTER_NAME=name && export GIT_AUTHOR_EMAIL=email && export GIT_AUTHOR_NAME=name; } || { unset GIT_COMMITTER_NAME && unset GIT_COMMITTER_EMAIL && unset GIT_AUTHOR_NAME && unset GIT_AUTHOR_EMAIL; }'


Alias / to /lang_code

Question: I got a multilanguage configuration with language detection based on URL(/en /fr). Drupal behavior redirects everything to so it would have those two prefixes or, if setup, it will ignore the prefix for a language while keeping for the other.
In my situation I need to keep the prefix for both language except for root page.
Ex:

example.com/en -> will load english homepage
example.com/fr -> will load french homepage
example.com/ -> has to load english homepage but without redirect to /en

So, how can this be achieved?
Answer: Drupal core doesn't redirect everything. Do you have the Redirect module installed? Then disable the route normalizer in the module settings, which is by default enabled:
/admin/config/search/redirect/settings

GLOBAL REDIRECTS
[x] Enforce clean and canonical URLs

If you want to keep the global redirect try this module specifically for the language prefix Disable Route Normalizer.
Comment: It's the module Redirect redirecting everything and not Drupal. You can disable this behavior in the module settings.
Comment: That would imply that I need to make my homepage language neutral which is not the case.
Comment: No, you don't need to do this. You have the module Redirect installed?
Comment: yes I have redirect, but still not sure what is your point

Alias / to /lang_code


how to add exposed drop-down filter with options in a view of custom table

Question: In a drupal 7 website, I have a view that is based on a custom table. I have a status column in that custom table, which is type of integer and has 0 or 1 value, and in a view I want to add exposed filter with dropdown, with values somehow like below
$options[0] = 'No';
$options[1] = 'Yes';

So that a user can choose a value from dropdown and filter out data.
So in my views.inc file I have implemented hook_views_data(), then I have added the following code to make that field accessible in a view
$data['custom_users']['status'] = array(
      'title' => t('User Status'),
      'help' => t('User Status'),
      'field' => array(
        'click sortable' => TRUE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric',
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
  );

Now when I am trying to add exposed filter using this field I am not able to make it available as dropdown. I am only getting a textfield as exposed filter for this field.
Any help will be appreciated.
Comment: Have you checked this article? https://atendesigngroup.com/articles/drupal-7-views-drop-down-exposed-filter-text-field
Comment: @PatrickScheffer Hello. Thanks for your response. Yes I have checked that article, and method mentioned in it somehow works with actual field table, in my case I have only one custom table that stores form submissions, some simple values like name and other details. So there I have a status column that holds either 0 or 1 value. In views I was expecting to have drop down option, like in case of node you can have filter with Published & Unpublished options in dropdown.
Comment: How does your views_handler_filter_numeric class look?
Answer: You can use hook_form_alter() for this.
simply change the field type to select and add your options.
here is my working code
// implements hook_form_alter
function project_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'views_exposed_form') {
    $view = $form_state['view'];
    // add your view name in 'view_name'.
    if ($view->name === 'view_name') {
      // Checking status field is exists or not.
      if (isset($form['status'])) {
        $form['status']['#type'] = 'select';
        $form['status']['#empty_value'] = '';
        $form['status']['#empty_option'] = 'All';
        $form['status']['#options'] = array('0' => 'No', '1' => 'Yes');
        $form['status']['#size'] = 1;
        $form['status']['#attributes'] = array('id' => 'status-list');
      }
    }
  }
}

hope this will work :).


uWSGI: running separate instances for each domain?

Question: basically I am following the guide from
https://gist.github.com/mplewis/6076082
and I am wondering what is the implication of running 3 domains on 3 separate uWSGI instances on the same server? Should I be using emperor mode instead? I gave that up because it was quite complicated to setup and it was taking too long.
Answer: Yes. Using Emperor is the cleanest way but not the only one.
I personally suggest to use it.
Setup is straight-forward. Just as nginx, you'll have an <code>/etc/uwsgi/apps-available</code> and `/etc/uwsgi/apps-enabled' symlink structure. Configuration of each domain is few lines. Look at some example configurations online.


window.open(...) with authorization

Question: We have a GWT app that accesses REST API. REST API is meant for other uses too, and is secured using JAAS basic authorization. GWT app uses RestyGWT dispatcher and filter, as shown here, to add Authorization: Basic to header, and, so far, this works fine.
However, our app also allows users to work with files, either download generated (such as pdf reports) or upload/download any kind files. We used servlets on server side for upload and download of these files, and Window.open() call to receive them in GWT. Without JAAS this worked fine.
Now I'm trying to secure that part of the API, too. Window.open(...) won't work because it doesn't allow for adding headers.
Is there some kind of workaround for this?
I've tried RequestBuilder, and I receive correct response, that contains the requested file. However, I'm not able to initiate the download of the file. Is it maybe possible to encode this (AJAX) response as data:... URL and display it using, for example, iframe, which will, in turn, initiate file download?
Answer: I always handled downloads by producing regular links. Wouldn't it be ok to check if a user session is valid and only then deliver the file?
By the way you could obtain an opened window's document and populate it:
public static native Document open(String url, String name, String features)/*-{
    return $wnd.open(url, name, features).document;
}-*/;

Comment: It is a requirement to secure both REST and servlets with JAAS basic. Therefore, I am not to use user session.

window.open(...) with authorization


thumbnail with some text to the right?

Question: I have a list like this:

      <link type="text/css" rel="stylesheet" href="testli.css">

Title, max two lines.

Some longish text, max two lines, causes problems when too long.

Title

Some longish text here which may wrap some and cause problems..

// testli.css
* {
  margin:0;
  padding:0;
}

#grok {
  list-style-type: none;
  width: 200px;
}

#grok li {
  background-color: lightgreen;
  margin: 5px;
  padding: 5px;
  text-align: left;
}

.cimg {
  width:70px;
  height:44px;
  float:left;
}

.cinner {
  float: left;
  margin: 0px;
  padding: 0px;
  margin-left: 10px;
  font:14px;
}

when the text in the p elements is short, the layout behaves as I want - the thumbnail and the text should appear as if they're in two separate columns. I'm basically looking to recreate the thumbnails youtube has for recommended items - thumbnail on the left, some text in another column to the right of it. Title and text each allowed two lines of text each.
If the text is too long, the cinner div gets placed below the thumbnail. What's the right way to force it to always be to the right?
Thanks
Comment: it'd be nice to include a link to your page, or a full test html page to plug in to a browser.
Comment: ok added full html / css for a test
Answer: Add max-width to .cinner (if I don't mistaken - max-width: 110px).
Answer: You could do it by setting a min-height on the
 and then absolutely positioning the image to the left of the title and description:
#grok {
   list-style-type: none;
   width: 200px;
}

#grok li {
   position: relative;
   margin: 5px;
   padding: 5px;
   min-height: 44px;

   /* min-height fix for IE6.  Ideally this would be in an IE6 only stylesheet */
   height: auto !important;
   height: 44px;

   background-color: lightgreen;
}

.cimg {
   position: absolute;
   left: 0;
   top: 0;
   width: 70px;
   height: 44px;
}

.cinner {
   padding: 0 0 0 80px; /* Makes room for the image so it doesn't overlap text */
   font: 14px;
}

thumbnail with some text to the right?


how to modify the path with hook_menu_local_actions_alter

Question: when I add the hook_local_actions_alter to my module, I can see that the node.add.page link shows up on certain pages as below.  how can I modify this so that this also show up on a different path in addition to the "admin/content" link it already shows up on ?  I want it to also show up on "admin/owncontent" .
[node.add_page] => Array
            (
                [id] => node.add_page
                [title] => Drupal\Core\StringTranslation\TranslatableMarkup Object
                    (
                        [string:protected] => Add content
                        [translatedMarkup:protected] =>
                        [options:protected] => Array
                            (
                            )
                    [stringTranslation:protected] =>
                    [arguments:protected] => Array
                        (
                        )

                )

            [weight] =>
            [route_name] => node.add_page
            [route_parameters] => Array
                (
                )

            [options] => Array
                (
                )

            [appears_on] => Array
                (
                    [0] => system.admin_content
                )

            [class] => Drupal\Core\Menu\LocalActionDefault
            [provider] => node
        )

Answer: Local actions and tasks (and menu links) don't apply to paths, they apply to routes.
For local actions to appear somewhere, you put them in the appears_on list, as you can see in your dump for the system.admin_content route. Just add your own route name there.
If you don't know your route name (e.g., because it is a view or otherwise dynamically defined page), you can look it up for example with the WebProfiler module that's part of Devel. Or you look in the router table.
Note that having hardcoded definitions on something like a view is a bit problematic, if the view is deleted or renamed, the route name will change and your code will break. That's probably OK for custom modules as you can assume that nobody will do that. One way to work around that is to specify a dummy route with the same path in a routing.yml file, views will see that and use the same route name.
Comment: can you explain how to specify a dummy route as you say here ?


Callback methods annotated in a listener bean class must return void and take one argument: javax.persistence.PreUpdate

Question: Estou tendo esse erro no meu console...
Caused by: javax.persistence.PersistenceException: Callback methods annotated in a listener bean class must return void and take one argument: javax.persistence.PreUpdate - public void digifred.model.aud.global.LogradourosEntityListener.preUpdate(digifred.model.global.Logradouros,java.util.Date)
    at org.hibernate.jpa.event.internal.jpa.CallbackBuilderLegacyImpl.resolveCallbacks(CallbackBuilderLegacyImpl.java:180) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.event.internal.jpa.CallbackBuilderLegacyImpl.buildCallbacksForEntity(CallbackBuilderLegacyImpl.java:69) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]

Não estou sabendo identificar o meu erro..
public class LogradourosEntityListener {

    @PrePersist
    public void prePersist(Logradouros target, Date modifiedDate) {
        perform(target,Acoes.INSERTED, modifiedDate);

    }

    @PreUpdate
    public void preUpdate(Logradouros target, Date modifiedDate) {
         perform(target, Acoes.UPDATED, modifiedDate);

    }

    @PreRemove
    public void preRemove(Logradouros target,Date modifiedDate) {
        perform(target, Acoes.DELETED, modifiedDate);

    }

    @Transactional()
    private void perform(Logradouros target, Acoes acao, Date modifiedDate) {
        EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
        entityManager.persist(new LogradourosHistorico(target, acao, modifiedDate));
    }
}

Answer: Caused by: javax.persistence.PersistenceException: Callback methods annotated in a listener bean class must return void and take one argument

É o que diz a mensagem. Os seus métodos anotados com @PrePersist, @PreUpdate e @PreRemove só podem ter um argumento. Em todos os seus métodos você colocou dois: Logradouros target e Date modifiedDate.
Ou você remove um deles, ou cria uma nova classe que tenha esses dois objetos como atributos e a utilize como argumento.


PHP redirect conditional statements

Question: I am attempting to modify the ID login system to work for admin and users but it dosnt work, any suggestions? Why wont my access level MySQL query not work please help. There is also a connection to the db and call to functions but these are nothing to do with it I need to make it work with this single form.
<?php
require_once('lib/connections/db.php');
include('lib/functions/functions.php');
If acces_level = 2 {
$returnURL = "users/index.php";
   } else {
If access_level = 1 {
   $returnURL = "secdirpostdata//aderr/auth/admin/index.php";

//For login

    // we check if everything is filled in and perform checks

    if(!$_POST['username'] || !$_POST['password'])
    {
        die(msg(0,"Username and / or password fields empty!"));
    }

    else
        {
            $res = login($_POST['username'],$_POST['password']);
                if ($res == 1){
                    die(msg(0,"Incorrect Username or Password"));
                }
                if ($res == 2){
                    die(msg(0,"Your account has been suspended, contact us to remove the suspension"));
                }
                if ($res == 3){
                    die(msg(0,"Your account has not been activated. Please check your email's inbox or spam folder for a link to activate your account. If you are having problems activating your account then contact us to resolve the issue."));
                }
                if ($res == 4){
                    die(msg(0,"Your account has been disconnected and is banned from using server, Contact Us to resolve this issue."));
                }
                if ($res == 99){
                    echo(msg(1,$returnURL));
                }
        }

    function msg($status,$txt)
    {
        return '{"status":'.$status.',"txt":"'.$txt.'"}';
    }

?>

Answer: You're doing an assignment with the equal sign =
If access_level = 1 {
If acces_level = 2 {

Instead of checking if it's equal to ==
Replace them both with:
If access_level == 1
If acces_level == 2 {

that's checking if it's equal to.
Edit
Considering what Jake put in for his answer, using the following would also make more sense.
(Credit to Jake Gould)
If $access_level == 1 {
If $acces_level == 2 {

N.B. You have acces_level with a (possible) missing s where as you have it correctly spelled in access_level = 1 do double-check everything. There is no other reference to access_level or acces_level or any other variable in your posted code.
Comment: Its querying a table in users where level access but im confuesed could you post the code, please and thanks &  MERRY CHRISTMAS
Comment: What does your DB code look like? @user3132932 It's not in your question.
Comment: My database has 5 tables and within the table users their is a collum called access_level this will give access to users meaning admins users will be give level 1 access where as users will be given level 2 access
Comment: You may be confusing the condition with a variable. What is the relation to `acces_level`? You may want to do something to the affect of `If $acces_level == 2` @user3132932 Depending on what that is related to and how you're bringing it into the whole picture.
Comment: I just tryed the code and it isnt working mabey Im not selecting the proper table etc. Please check out this script for the code im using...
Comment: Which script is that, I don't see a link. @user3132932 you may not have enough rep points to post links in comments. Please add your full code to your question.
Comment: Plus as I stated in my **EDIT**, you may have mispelled the word `acces_level` with a missing `s` which should read as `access_level` and possibly a `$` in front of it to make it as a variable. I.e.: `$access_level` @user3132932 that I need to know how it is being taken from, if it's coming from another file.
Comment: Yep, I had that impression just as soon as I saw the OP's first comment; another can of worms. @JakeGould
Answer: Your syntax for if and else if are wrong. Additionally your = check is an assignment when it should be ==. And when you have acces_level == 2 and acces_level == 1 those should be a variable so it should be $acces_level == 2 and $acces_level == 1. Finally, you need parenthesis around the conditions. Examples below.
Where you have this:
If acces_level = 2 {
$returnURL = "users/index.php";
   } else {
If access_level = 1 {
   $returnURL = "secdirpostdata//aderr/auth/admin/index.php";

It should be this:
if ($access_level == 2) {
  $returnURL = "users/index.php";
}
elseif ($access_level == 1) {
  $returnURL = "secdirpostdata//aderr/auth/admin/index.php";

Also, it is unclear if the variable is acces_level or access_level with two s's.  In general you need to provide more details. But your formatting is way off to say the least.
Comment: I'm starting to think that your answer makes more sense. It's really hard to know though, exactly why the OP set it up the way it is now, since there are other conditional statements elsewhere, resembling what you put in. I might end up deleting my answer, if I can't see the whole picture.
Comment: @Fred-ii- Can you and Jake please look at this script to see how I can implement this feature please http://www.venturehapa.biz/umscript/
Comment: I'm sorry, but I can't go through all those files. @user3132932 You took this from a demo, and I for one won't go through all of it. If Jake wants to do it, then that's up to him. I've done what I could with your initial question while pointing out the errors.
Comment: also the link is a link to the coding im using
Comment: The only thing I could tell is that the DB is using `level_access` and not `access_level` inside `functions.php` file. @user3132932
Answer: Also keep the format correct
if (acces_level == 2) {

not
If acces_level = 2 {

just better formatting doesnt mean you actually need the ()
Comment: I'm sorry its just what I could easily make out. Im not a pro just try to help with the little that I can.

PHP redirect conditional statements


Is it possible to hook to variable_set() event?

Question: I would like to track the system changes event, to make them revertable. When checking variable_set(), I see there is no hook provided for that event. Is there any way for me to do this?
I can alter to hook to settings forms, but there's a lot of settings form to track, if I can hook to variable_set() directly, code becomes much simpler.
I can also track the variable changes with features + strongarm modules, but it's better if Drupal admin can browse the variable history without code touching.
Comment: I opened a Feature Request ticket on Drupal.org to create hooks for intercepting the setting and deleting of system variables, and I submitted for review a core patch for this! Please see: https://www.drupal.org/project/drupal/issues/2934718
Answer: It seems that it's impossible using only Drupal, which means:
variable_set() itself doesn't invoke any hooks, but it uses db_merge(). That function is using the MergeQuery class. Now, it would be nice to hook with hook_query_alter(), but it only works for query classes that implements the QueryAlterableInterface interface. Sadly, this interface is now implemented only by the SelectQuery and the SelectQueryExtender classes, not by the MergeQuery class.
Note that even if you will find a way to create a child class of MergeQuery, that will implement QueryAlterableInterface, and make Drupal use it. hook_query_alter() only works on queries that have tags, and variable_set() doesn't tag its query, so the hook would not be used anyway, unless you are willing to hack core. But if you are, you don't need all that, you could simply hack in a hook call.
If you feel hardcore you can use a more indirect PHP approach: $conf is a global array of configuration variables; you can write a module that will replace it with object acting like an array, as described on Stack Overflow. To make it a good substitute you need to implement ArrayAccess. Pull all values from original $conf into your object. Then, in ArrayAccess::offsetSet() implement your logging logic.
Comment: I forgot about [this old answer of mine](http://drupal.stackexchange.com/a/76142/16495) and I already found how to do pretty much anything with `$conf` back then :D Hope my updated answer will help somebody.
Comment: I'm impressed! :D
Comment: @Letharion Thank you :) Once upon a time I liked "object acting as ..." magic in PHP, and I still remember a bit about it ;)
Answer: You could use a database trigger, which would be faster than code.
Here is the MySQL doc.

create a table to store old values
CREATE TABLE variable_backup
(
    name varchar(128) not null,
    value longblob,
    updated datetime not null,
    primary key (name, updated)
);

create your triggers, one for insert and one for update:
CREATE TRIGGER backup_variable_update BEFORE UPDATE ON variable
    FOR EACH ROW
        INSERT INTO variable_backup (name, value, type, updated) VALUES (OLD.name, OLD.value, "update", NOW());

CREATE TRIGGER backup_variable_insert BEFORE INSERT ON variable
    FOR EACH ROW
        INSERT INTO variable_backup (name, value, type, updated) VALUES (NEW.name, NEW.value, "insert", NOW());

Now all of your updates and inserts will record old values in variable_backup.
Comment: I like it, neat and simple. Probably faster than my method, too. More limited, but enough to do what OP needs, if he has sufficient MySQL access.
Comment: I like this way. But I think we need to track user agent information too
Comment: I doubt that information would be available to the database.
Comment: @AndyTruong that info will not be in the database, sorry. I tried to look around but it's impossible to guess it with data in session table, and only select queries are alterable so no way to add it. So my "hardcore" method is there for you. Hope you had success at implementing it, if not - ask new question linking to it, and comment that you did so.
Answer: As you can see in the source code, variable_set() makes no request for hooks or alterations, e.g no module_invoke_all() or drupal_alter() calls there.
function variable_set($name, $value) {
  global $conf;

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;
}

However, you might be able to listen to the db_merge() query with a specially placed hook_query_alter() and do some additional processing there but, as pointed out by Molot, hook_query_alter() looks unlikely to be able to target the db_merge() query.
Alternatively, you could perhaps cron snapshot the variable table to diff it against previous revisions of that table, or else implement some other form of variable revision storage to compare against.
Comment: If hook_query_alter can be used on this query, I would love to see how. In 8 `QueryAlterableInterface` is indeed implemented by `Query` itself. But in 8 configuration management is rebuilt anyway. And in 7 only tagged select queries are alterable as far as I see. But maybe I'm missing something?
Comment: No, you are correct, hook_query_alter was a guess, but not viable in D7 in this case, thanks.


How to find point on line closest to sphere?

Question: Given:

$r_0$ - Position vector of a point outside of the sphere in ${\rm I\!R^3}$.
$v$ - Line of sight vector from the point outside of the sphere in ${\rm I\!R^3}$.
$R$ - Radius of the sphere.

Calculate:

$r$ - Position vector of closest point on the sphere to the line created by extending the LOS vector from r_0, whose Frobenius norm is R.

My approach:
Assumption: Given that this is a sphere, the point on the sphere that is closest to the line created by extending the LOS vector must be on the perpendicular segment connecting the center of the sphere to said line.  I do not think this holds true for a spheroid, but that's a possible follow up question for later.

$p = r_0 \times v$ yields the vector tangent to the plane formed by $r_0$ and $v$ and is thus orthogonal to both $r_0$ and $v$.
$r' = p \times v$ yields the vector pointing from the center of the sphere to the line created by the vector $v$
$r'$ differs from $r$ by a scaling factor $C$, such that $||Cr'|| = R$.  We can solve for $C = R/||r'||$
Scale $r'$ to get $r$ by $r = Cr'$

I feel like I'm missing something however or that my assumption might not be correct.
Comment: This is a classic Lagrange multiplier problem: https://en.wikipedia.org/wiki/Lagrange_multiplier
Comment: Cool, so that sounds like a fun way to try it...if that's the case, then
my function to minimize would be the magnitude of the difference between the line and the sphere?  Subject to the constraint of the equation of the sphere.  I think the trouble I have with this part is coming up with the functional form of the line.  Using a parametric form of the line based off the origin of the line and the los vector gives me a t that makes this a little nasty.
Comment: Yes, its an ugly set of equations. The simplest way I can think of is posted below.
Answer:
The line has one parameter $t$ :  $(x_0+s_x t, y_0 + s_y t, z_0 + s_z t)$
The radius is perpendicular to the sphere.
The shortest distance will be perpendicular to the sphere and the line.
$$ d = \sqrt{(x_0+s_x t - x_c)^2 + (y_0 + s_y t - y_c)^2 + (z_0 + s_z t - z_c)^2 } - R$$
The distance is a function in one parameter $t$.
$$\frac{dd}{dt} = \frac{s_x (x_0+s_x t - x_c) + s_y (y_0 + s_y t - y_c) + s_z (z_0 + s_z t - z_c) }{\sqrt{(x_0+s_x t - x_c)^2 + (y_0 + s_y t - y_c)^2 + (z_0 + s_z t - z_c)^2 }}$$
The minimum occurs at $\displaystyle \frac{dd}{dt} = 0$
$$ s_x (x_0+s_x t - x_c) + s_y (y_0 + s_y t - y_c) + s_z (z_0 + s_z t - z_c) = 0 $$
$$ t = \frac{s_x(x_c-x_0) + s_y(y_c-y_0) + s_z(z_c-z_0)}{s_x^2 + s_y^2 + s_z^2}$$
Calculate $d$.
The point on the sphere can be taken as a ratio along the center to the point on the line:
$$ \left( x_c + \frac{(x_o + s_x t - x_c)R}{R+d} , y_c +  \frac{(y_o + s_y t - y_c)R}{R+d} , z_c + \frac{(z_o + s_z t - z_c)R}{R+d} \right)$$


How to change this geometric progression into a direct one

Question: We have the progression:
$$u_0 = 5$$
$$ u_{n+1} = 3- 0.5u_n \space ( n = 1,2,...)$$
I want to change this into a 'direct' progression, so I tried:
$$ 5 \cdot -0.5^n + 3$$ but this actually fails for $n=0$. How can I edit this so it also holds for $n=0$?
Comment: (1) Did you mean $\,u_{n+1}=3-0.5u_n\,$ ? Because if you did then this is **not** a geometric progression, and (2) what is a "direct progression"?
Comment: @DonAntonio For the one you need to know the previous term, for the other you can immediately plug in a number if you understand what I mean.
Comment: I honestly do not understand what you mean: a progression $\,u_1,u_2,...\,$ is geometric iff for all $\,n\in\Bbb N\,$ , we have that $$\frac{u_{n+1}}{u_n}=q=\;\text{a constant}$$ I can't see how yours fulfills this.
Answer: If I understand the problem correctly, we do not have a geometric progression. Instead, we have the recurrence
$$u_{n+1}=3-(0.5)u_n,$$
with $u_0=5$. We want an explicit formula for $u_n$.
There are many techniques for dealing with this sort of problem. We use one of the basic ones.  Let $u_n=c+y_n$, where we will choose $c$ to make the recurrence nicer. Then our recurrence can be rewritten as
$$c+y_{n+1}=3-(0.5)(c+y_n)$$
or equivalently
$$y_{n+1}=3-(0.5)c-c -(0.5)y_n.$$
To make the constant term in the recurrence disappear, we choose $c=2$.
We arrive at the recurrence
$$y_{n+1}=(-0.5)y_n,$$
with $y_0= 3$. This has the solution $y_n=3(-0.5)^n$, and therefore we get
$$u_n=2+3(-0.5)^n$$


I have two checkboxes, i need to show or hide one or the other based off my sql value

Question: If the checkbox ['transfer'] is checked which will be the default checkbox that displays on the page, after being saved and the page refreshes they should only have the option to view the checkbox ['reverse'].
If they select reverse  and save the option for the checkbox ['transfer'] should appear again.
I'm trying to wrap my head around it and it seems really simple but i'm having a block atm.
so i created a variable for my sql query:
$secular = sql::value("select * from ev.do.taskAU where event_id = $event_id and transfer = '1'");

essentially both checkboxes will have the same field name in the database.. that will be ['transfer'] and it should change based on the bit 0 or 1.
hope that makes sense and any help would be greatly appreciated.
This is what i'm trying:
<?php

$secular = sql::value("select * from event.dbo.taskAU where event_id = $event_id and transfer = '1'");
$checked = $secular['transfer'];

?>

     <?php if ($checked == 1) echo "Transfer	<?php if (in_array(login::$id, array('02O','04R','0A3','0BN','0BO','00D','0FR','0E1'))) { echo ". cbox_return('transfer') ."	"; ?>
     <?php if ($checked == 0) echo "Reverse	<?php if (in_array(login::$id, array('02O','04R','0A3','0BN','0BO','00D','0FR','0E1'))) { echo ". cbox_return('transfer') ."	"; ?>

Comment: Where are these checkboxes?
Comment: they are in the array, called cbox_return
Comment: And you just want to check them?
Comment: if one is checked and the page reloads they only have the option to use the reverse checkbox. if they check the reverse checkbox.. after it reloads they only have the option to transfer.
Answer: Once you get the value of whether or not the item was checked from the database, you would use this code:
   $checked = ('whatever value you got from the database');

$checkedValOne = (in_array(login::$id, array('02O','04R','0A3','0BN','0BO','00D','0FR','0E1'))) ? true : false;

$checkedValTwo = ($checked == 1 ? true : false;

    <input type="checkbox" value="<?php echo (($checkedValOne && $checkedValTwo) ? "checked" : ""));?>" />

The above code will only add checked to the checkbox if the value from the database was 1.
Comment: how do i concat my in array with my if statement above?


What's the difference between @ and * with python matrix multiplication?

Question: I know one does one kind of matrix multiplication and the other does another kind but can never remember the difference.
Doing
>>> import numpy as np
>>> a = np.matrix([[1, 2],[3,4]])

>>> print(a * a)
[[ 7 10]
 [15 22]]

>>> print(a @ a)
[[ 7 10]
 [15 22]]

appears to give the same answer which confuses me.
Comment: No built-in type supports `@`, IIRC. This should be documented in types that *do* support `@`, such as those provided by the `numpy` module.
Comment: What did you try?
Comment: @theEpsilon numpy.matrix is deprecated.  You can use numpy.array with @ instead.
Comment: Except for np.matrix (as opposed to np.array); np.matrix maps * to matrix multiplication as it is a special class that predates @ and was used to make it do 'natural' matrix multiplication.  This is presumably one of the reasons it is considered deprecated.
Comment: @YoanaG the question has been reopened. Feel free to submit an answer
Comment: @Max the question has been reopened. Feel free to submit an answer
Comment: `@` is equivalent of matrix mutiplication, at least for higher dimensions. And `*` is cellwise multiplication.
Answer: a * b is a multiplication operator - it will return elements in a multiplied by elements in b.
When a and b are both matrices (specifically defined by np.matrix) the result will be the same as the @ operator.
a @ b is matrix multiplication (dot product when used with vectors). If you haven't specified that a is a matrix and have used an array instead a * a would return every element in a squared.


Concrete Mathematics: Clarification about equation 2.20: intersection of set with its complement

Question: In Concrete Mathematics (Graham, Knuth, and Patashnik) equation 2.20 is
$$
\sum_{k\in K}a_k + \sum_{k \in K'}a_k = \sum_{k \in K \cap K'}a_k + \sum_{k \in K \cup K'}a_k
$$
Specifically $k \in K \cap K'$: I would have thought a set cannot interect with its complement? So the equation could just be
$$
\sum_{k\in K}a_k + \sum_{k \in K'} = \sum_{k \in K \cup K'}a_k
$$
I am sure the authors had a good reason to include the intersection RHS sum and I want to make sure I understand the point they're making.
Comment: The good reason is that $K'$ is not the complement of $K$, but just another set.
Comment: Oh I see! I shall read it again in a new light
Comment: To be more precise, $K$ and $K'$ are both subsets of some set $E$.
Comment: @J.-E.Pin: Specifically, '$K$ and $K'$ are any sets of integers' (from the sentence introducing the equation).
Answer: As J.-E. Pin and Brian M. Scott pointed out in the comments this was due to me not properly reading the part where they say

If $K$ and $K'$ are any sets of integers

Now it makes sense. I shall certainly endeavour to read more carefully in the future ☕


OpenVPN on OpenBSD 4.8: How do I set up a VPN for road warriors in bridged mode

Question: I'd like to set up an OpenVPN server on my OpenBSD router.
I'd like to run it in bridged mode, so the IPs given to the road warriors are from the local network subnet. I'd like to use the DNS server of OpenVPN for those clients.
I found some tutorials on how to do this, but most seem to be out of date, to the point that it's virtually impractical to use anything from it.
Do I have to compile it from ports, isn't installing with pkg_add sufficient?
Could someone please point me to a how-to that is somewhat up-to-date?
Answer: This is pretty easy using openvpn.  You will need to setup your server to use a specific tap interface.  Then just use ifconfig to bridge tapX to your LAN interface.  More info on bridge here:
http://www.openbsd.org/cgi-bin/man.cgi?query=bridge&sektion=4&arch=&apropos=0&manpath=OpenBSD+Current
As requested here is the how-to:
http://www.chrisk.de/blog/2010/03/how-to-openvpn-on-openbsd-as-layer2-vpn/


iPhone : How to change gradient color for negative values in Core Plot?

Question: How to change area gradient color for negative values in Gradient Scatter Plot in Core-Plot in iPhone?
I want gradient colors as below:

For positive values to be Green
For negative values to be Red.

How should I do that?
Comment: You'll likely need to normalize your values.  From what I can see, CPGradient only accepts `CGFloat 0 - 1`.  So if your values range from -1024 to +1024, you'll need to add an offset and divide by the total range.  That'll give you a number from 0-1.  I can't answer for certain, b/c I've never worked with CorePlot.
Comment: @Stephen Furlani: Thanks for the input. I am not clear about wat u said. Can you please explain it in bit of detail
Comment: You know, either ahead of time, or by looking at your data set, that all values `n` are such that `j ≤ n ≤ k`. Then, you can get the gradient value as `(n - j) / (k - j)`, which will be in the range `[0-1]`. This linearly interpolates between `j` and `k`.
Answer: Just implement the following method of the CPBarPlotDataSource is OK:
- (CPFill *)barFillForBarPlot:(CPBarPlot *)barPlot recordIndex:(NSUInteger)index
{
    if (barPlot.identifier == @"profit") {
        id item = [self.profits objectAtIndex:index];
        double profit = [[item objectForKey:@"profit"] doubleValue];

        if (profit < 0.0) {
            return [CPFill fillWithGradient:[CPGradient gradientWithBeginningColor:[CPColor redColor] endingColor:[CPColor blackColor]]];
        }
    }

    return nil;
}

Hope to help:)
Comment: I am unsure why this answer has been marked as accepted as question is about a scatter plot. When I implement `-barFillForBarPlot:recordIndex:` when using a scatter plot, the method is never called. How did this fix the issue?
Answer: Well, I don't know if it's too pretty, but I suppose you could do two separate plots with the same dataSource, let's say positivePlot and negativePlot.
CPScatterPlot *positivePlot = [[[CPScatterPlot alloc] init] autorelease];
positivePlot.identifier = @"PositivePlot";
positivePlot.dataSource = self;
[graph addPlot:positivePlot];

CPScatterPlot *negativevePlot = [[[CPScatterPlot alloc] init] autorelease];
negativevePlot.identifier = @"NegativePlot";
negativePlot.dataSource = self;
[graph addPlot:negativePlot];

Now, if you configure your plotSpaces properly, you can separate positive and negative values and configure each plot properly, including area gradient:
CPXYPlotSpace *positivePlotSpace = [graph newPlotSpace];
positivePlotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0)
                                             length:CPDecimalFromFloat(100)];
positivePlotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0)
                                             length:CPDecimalFromFloat(100)];

CPXYPlotSpace *negativevePlotSpace = [graph newPlotSpace];
negativePlotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-100)
                                             length:CPDecimalFromFloat(100)];
negativePlotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(0)
                                             length:CPDecimalFromFloat(100)];

// Plots configuration

//POSITIVE VALUES
positivePlot.plotSpace = positivePlotSpace;

// Green for positive
CPColor *areaColor = [CPColor colorWithComponentRed:0.0
                                            green:1.0
                                             blue:0.0
                                            alpha:1.0];
CPGradient *areaGradient = [CPGradient gradientWithBeginningColor:areaColor
                                                    endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0f;
CPFill *areaGradientFill = [CPFill fillWithGradient:areaGradient];
positivePlot.areaFill = areaGradientFill;

//NEGATIVE VALUES
negativePlot.plotSpace = negativePlotSpace;

// Red for negative
areaColor = [CPColor colorWithComponentRed:1.0
                                     green:0.0
                                      blue:0.0
                                     alpha:1.0];
areaGradient = [CPGradient gradientWithBeginningColor:areaColor
                                          endingColor:[CPColor clearColor]];
areaGradient.angle = -90.0f;
areaGradientFill = [CPFill fillWithGradient:areaGradient];
negativePlot.areaFill = areaGradientFill;

NOTE: This is off the top of my head, as I dont have Core-Plot docs here, or a working configuration to test this in, so the syntax or something might be off, but I think the general concept should work.
Cheers


Thinkenning a Renewal Process

Question: This problem is a dual question of  "Splitting a renewal process".

Assume we have a renewal process $P_1$ with inter-renewal distribution $p_1(x)$ and rate $\lambda_1 = \lim_{t \to \infty} \frac{N_1(t)}{t}$, where $N_1(t)$ is the total number of renewals of $P_1$ during $[0,t]$. We want to find another renewal process $P_2$ with rate $\lambda_2$ such that the super position of $P_1$ and $P_2$ is a renewal process.

If $P_1$ is Poisson, $P_2$ would be simply Poisson and the superposition of them is another Poisson and everything works. But here, $P_1$ is general, not only Poisson.
Also, if $P_1$ and $P_2$ are independent and $P_2$ is renewal, the superposition $P_1+P_2$ is renewal if and only if both $P_1$ and $P_2$ are Poisson, or have special distribution (discussed here).
The question remains for the general case. To solve that, I am thinking of considering building the superposition by as a renewal process with inter-renewal distribution $p_t(x)$ where $\frac{1}{\mathbb{E}[p_t(x)]}=\lambda_1+\lambda_2$. Now, we have $P_1(t)$ and $P_1(t)+P_2(t)$, I don't know how to find $P_2(t)$. Maybe we could take advantage of the fact that pdf of sum of two random variables is the convolution of their pdf. Any idea? or simpler method?
Comment: I suggest you consult some texts on renewal theory. In particular, *Renewal Theory* by Cox (1962) is a rather comprehensive treatment; *Stochastic Processes* by Ross (1996) and *Introduction to Stochastic Processes by Çinlar* (1975) are some more general texts that treat renewal theory, and *Stochastic Processes: Theory for Applications* by Gallagher (2013) is a more recent text that appears decent.
Comment: Thanks  a lot. I will do that. Meanwhile, I wait for a response.
Answer: Along the lines of my last comment in your previous question, you could do a reverse convolution type thingy:
Suppose we have a renewal process $N(t)$ with rate $\lambda>0$. Let $X$ be a random variable with the same distribution as the inter-arrival times of $N(t)$. Then $E[X]=1/\lambda$.   Fix $\epsilon>0$. We want to add another process $A(t)$ (not necessarily renewal, and not necessarily independent of $N(t)$) so that the sum process $N(t)+A(t)$ is a renewal process of rate $\lambda + \epsilon$.
Fix a probability $p \in (0,1]$. Suppose $X$ can be viewed as a geometric sum of positive iid random variables $Y$, so that $X = \sum_{i=1}^G Y_i$ where $G$ is independent and geometrically distributed with success probability $p$.  Thus, $E[X]=E[Y]/p$.  The process $N(t)$ can be viewed as having arrivals defined only at the end of the last $Y_i$ interval in every geometric sum.  Let $A(t)$ be the arrival process with arrivals at the end of all the other $Y_i$ intervals.  Then $N(t)+A(t)$ is a renewal process with rate $1/E[Y]$.  We can choose $p$ to make the rate difference equal to $\epsilon$:
$$ \epsilon = \frac{1}{E[Y]} - \frac{1}{E[X]} = \frac{1}{pE[X]} - \frac{1}{E[X]} = \frac{1/p-1}{E[X]}  $$
So choose $p = \frac{1}{\epsilon E[X] + 1}$.
Now it may not be possible to make such a decomposition of $X$.  We want $X=\sum_{i=1}^G Y_i$. The moment generating function for $X$ gives:
$$ E[s^X] = \sum_{i=1}^{\infty} (1-p)^{i-1}pE[s^X|G=i] = \sum_{i=1}^{\infty} (1-p)^{i-1}pE[s^Y]^i = \frac{pE[s^Y]}{1-(1-p)E[s^Y]} $$
where I am not worrying about region of convergence issues for simplicity. So this can be used to solve for the moment generating function $E[s^Y]$ in terms of the moment generating function $E[s^X]$.
Comment: That is a nice. If you are near a river and observing the boats on it ($P_1$) and you want to add some boats ($P_2$) in such a way that the super-position process is renewal, then how can you use the pdf of $Y$ to do that? I think we cannot, since we have the causality problem, that is when you see the first boat and want to put some boats on the river, you need to know the time that the second boat arrives.
Comment: @Susan , That can be done in the Poisson case by basic Poisson properties. I was arguing above that it can also be done for non-Poisson, provided that the inter-arrival time has a certain structure.
Comment: Thanks a lot. Your answer is correct actually. The problem I mentioned in my last comment is a bit different, it has the causality problem.

Thinkenning a Renewal Process


Css do Jquery-Ui.css esta bloqueando elementos da pagina

Question: Tenhos elementos dispostos na minha tela. Porém devido ao uso do plugin jquery.Tab o css esta bloqueando os elementos da página.

Codigo Index.php
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Detalhes

Mapas

Cadastrar Divices

Alerta

Código Mapas.php

    Tipo
    <select name="tipo">
        <option value="" >-------- </option>
    </select>

    Agendamento
    <select name="agendamento">
        <option value="" >-------- </option>
    </select>

    Online
    <select name="online">
        <option value="" > Todos </option>
    </select>

    Vinculados
    <select name="vinculados">
        <option value="" > Todos </option>
    </select>

    <form action="busca.php" method="post">
        <input type="text" class="search-query" placeholder="Busca">
    </form>

    <button class="btn">

    </button>

    <button class="btn">

    </button>

    <button class="btn">

    </button>

    <button class="btn">

    </button>

    <?php include "mapas/detalheMapa.php"; ?>

    <?php include "mapas/painelPonto.php"; ?>

    <?php //include "mapas/detalhePonto.php"; ?>

    <?php //include "mapas/rodape.php"; ?>

Aqui o codigo esta rodando: JSfidle
Comment: Tem como pelo menos detalhar melhor o que seria "CSS bloqueando elementos"? O ideal seria que você fizesse um [mcve].
Comment: Não consigo alinhar na mesma linha os elementos na imagem acima
Comment: por mais que use o CSS:display não funciona!
Comment: https://jsfiddle.net/alexjosesilva/kb56r3be/1/
Answer: Resolvido bastou apenas inserir a classe na tag  a partir dela que tinha a quebra do alinhamento.
.linha{
   display: inline;
}

codigo: JSFiddle


How do you dynamically load a javascript file from different domain?

Question: I find this excellent code, posted by aemkei as answers to this questions:

How do you dynamically load a javascript file? (Think C's #include)
Use javascript to inject script references as needed?

You may write dynamic script tags
  (using Prototype):
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});

The problem here is that we do not
  know when the external script file is
  fully loaded.
We often want our dependant code on
  the very next line and like to write
  something like:
if (iNeedSomeMore){
  Script.load("myBigCodeLibrary.js");  // includes code for myFancyMethod();
  myFancyMethod();                     // cool, no need for callbacks!
}

There is a smart way to inject script
  dependencies without the need of
  callbacks. You simply have to pull the
  script via a synchronous AJAX request
  and eval the script on global level.
If you use Prototype the Script.load
  method looks like this:
var Script = {
  _loadedScripts: [],
  include: function(script){
    // include script only once
    if (this._loadedScripts.include(script)){
      return false;
    }
    // request file synchronous
    var code = new Ajax.Request(script, {
      asynchronous: false, method: "GET",
      evalJS: false, evalJSON: false
    }).transport.responseText;
    // eval code on global level
    if (Prototype.Browser.IE) {
      window.execScript(code);
    } else if (Prototype.Browser.WebKit){
      $$("head").first().insert(Object.extend(
        new Element("script", {type: "text/javascript"}), {text: code}
      ));
    } else {
      window.eval(code);
    }
    // remember included script
    this._loadedScripts.push(script);
  }
};

I found that, the code does not work on IE if the all of them is executed in 'file://' protocol, however, it is not the problem since its use case involved real web application.
I tried it once to include http://www.google-analytics.com/urchin.js by google, but from one of web page, but it looks like it cannot request javascript file from different domain.
How we could dynamically add javascript, just like what above scripts does, but from another domain?
Answer: You can use the onload and onreadystatechange event to understand when the


How to restart a systemd service with salt?

Question: I am trying to build an .sls file which will always restart a service:
systemd-resolved:
  service.running:
    - restart: True

When deployed, this gives

      ID: systemd-resolved
Function: service.running
  Result: True
 Comment: The service systemd-resolved is already running
 Started: 23:46:49.999789
Duration: 53.068 ms
 Changes:

This is correct, the service is already running. What I was trying to convey with this command is to restart it. How to do that?
Note: I would like to avoid, if possible, an explicit command to be ran (as I feel it i snot very salt-like - this should rather be handled by the appropriate module):
'systemctl restart systemd-resolved':
  cmd.run

Answer: If you want your service to reload you need to set reload: True instead.
Beside, If you only want to restart the service if there is any change in any other state, you need to use watch instead.
for instance,
systemd-resolved:
  service.running:
    - enable: True
    - reload: True
    - watch:
      - pkg: <abc>

Answer: Unfortunately this does not work if the service does not have the execreload command defined in the service file.  The only way around this that I have found is to use cmd.run and systemctl restart service.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


visio event for layer name change, new layer and so on

Question: i am programming a little layer manager  as add-on (or add-in?) for visio in c#. Therefore i need an event after name change of a layer or after creating a new layer without my layer manager. The rest is already done. But, I do not have any idea how to start.
How to get the layer events (name change, new layer, deleted layer, rename layer, ...)?
Thanks
Heiko
Answer: The layer related events are cell-changed-events of the responding page. So you can set an event to the ActivePage.CellChanged.
When the event is active, you can check the cell that was changed to get only layer related events. I did it by checking cell.LocalName.StartsWith("Layer.").


How can I change Angular Material button background color on hover state?

Question: I have an Angular button:
<button md-button class="link-btn" >Cancel</button>

.link-btn {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

.link-btn:hover {
  background-color: transparent;
  background-repeat: no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
  outline:none;
  font-size: 0.8em;
  padding: 0px;
}

Normally it is setting transparent background, but in hover state, gray background is shown? How to remove that?
Comment: You can check my answer at: https://stackoverflow.com/a/72401579/3339907
Answer: As of Angular 6, the use of /deep/ or ng-deep in the chosen solution is marked for deprecation. The recommended way is to use global styles as stated in the docs.

Some Angular Material components, specifically overlay-based ones like
  MatDialog, MatSnackbar, etc., do not exist as children of your
  component. Often they are injected elsewhere in the DOM. This is
  important to keep in mind, since even using high specificity and
  shadow-piercing selectors will not target elements that are not direct
  children of your component. Global styles are recommended for
  targeting such components.

In the specific case of button hover background, I had to use the following code in my styles.css (global stylesheet included via angular-cli or directly linked in index.html). Note that you might have to replace primary with accent or warn depending on the palette type (color="primary" or color="accent" or color="warn") used in the button.
.mat-button.mat-primary .mat-button-focus-overlay {
  background-color: transparent;
}

If you don't want every button to be affected, it's better to have a specific class like no-hover-effect as shown below.
.no-hover-effect.mat-button.mat-primary .mat-button-focus-overlay,
.no-hover-effect.mat-button.mat-accent .mat-button-focus-overlay,
.no-hover-effect.mat-button.mat-warn .mat-button-focus-overlay
{
  background-color: transparent;
}

For every material button that doesn't need hover-effect, you'd do
  <button mat-button color="primary" class="no-hover-effect">
    No Hover Button
  </button>

Comment: I found that the trick for the template I was using was to follow the :hover style background-color with !important.   The background color change would not reflect on hover unless I used !important.
Comment: Just a small note, but if anyone uses mat-button but not the color property (e.g. primary, accent, warn), then you can achieve the same outcome with this in styles.scss:

`.no-hover-effect.mat-button .mat-button-focus-overlay { background-color: transparent; }`
Answer: The button styles are encapsulated, so you have to use /deep/ selector to change internal styles.
Try this:
.link-btn /deep/ .mat-button-focus-overlay {
    background-color:transparent;
}

Plnkr
Update:
As of Angular v4.3.0 the /deep/ selector is deprecated and will be replaced by the ::ng-deep selector. You can find more info in the documentation: Angular Documentation
Comment: deep AND ::ng-deep will be depricated and removed:

The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.

Source: https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep
Comment: how would you do this when /deep/ is removed?
Comment: As written in my answer, with `::ng-deep`
Answer: You can also use mat-flat-button instead of mat-button as the former doesn't have an overlay mechanic. You just need to override the background color in your component which is imho is a much cleaner mechanic than globally overriding dynamically created overlay components angular material creates.
Answer: Try adding the following to your css...
.mat-button-focus-overlay {
    background-color:transparent;
}

Or
.mat-menu-item:hover {
     background-color:transparent;
}

Answer: You can apply a global style to your application to all the buttons.
I did it using Angular theming for the mat-icon-buttons.
$background: map-get($my-theme, background);

// add hover for mat-icon butttons
.mat-icon-button:hover {
   background-color: mat-color($background, hover);
 }


Rolling Dice Repeatedly

Question: This question is from DEGROOT's PROBABILITY and STATISTICS.
Rolling Dice Repeatedly:
Suppose that two dice are to be rolled repeatedly and the
sum $T$ of the two numbers is to be observed for each roll. We shall determine the
probability $p$ that the value $T =7$will be observed before the value $T =8$ is observed.
Solution:
The desired probability $p$ could be calculated directly as follows: We could assume that the sample space $S$ contains all sequences of outcomes that terminate as
soon as either the sum $T = 7$ or the sum $T = 8$ is obtained. Then we could find the
sum of the probabilities of all the sequences that terminate when the value $T = 7$ is
obtained.
However,there is a simpler approach in this example. We can consider the simple
experiment in which two dice are rolled. If we repeat the experiment until either the
sum $T = 7$ or the sum $T = 8$ is obtained, the effect is to restrict the outcome of the
experiment to one of these two values. Hence,the problem can be restated as follows:
Given that the outcome of the experiment is either $T = 7$ or $T = 8$, determine the
probability $p$ that the outcome is actually $T = 7$.
If we let $A$ be the event that $T = 7$ and let $B$ be the event that the value of $T$ is
either $7$ or $8$, then $A ∩ B = A$ and
$p = Pr(A|B) =Pr(A ∩ B)/
Pr(B)
=Pr(A)/
Pr(B)$.
But $Pr(A) = 6/36$ and
$Pr(B) = (6/36) + (5/36) = 11/36$. Hence, $p = 6/11$.
Now,my doubts are
1.) Why the author says "We could assume that the sample space $S$ contains all sequences of outcomes that terminate as
soon as either the sum $T = 7$ or the sum $T = 8$ is obtained. Then we could find the
sum of the probabilities of all the sequences that terminate when the value $T = 7$ is
obtained." ?
2.)How can we go from lengthy sequences of outcomes that terminate as
soon as either the sum $T = 7$ or the sum $T = 8$ is obtained to just the outcome of the experiment for which either $T = 7$ or $T = 8$ ?
Please help.Thank you.
Answer: For 1, once you get either a $7$ or an $8$, you know the result of the run.  Any rolls we make subsequently will not affect the outcome, so we might as well ignore them.  As we roll $7$ or $8$ with probability $1$, to find the chance that a $7$ is last we just add them up.
2 is the more subtle point.  If you like thinking of Markov processes, we have one with just three states.  You have a start state and two ending states.  If you throw a $7$ you move to one end state.  If you throw $8$ you move to the other end state.  If you throw anything else, your return to start.  We are interested in the chance we end at $7$.  This is the chance of $7$ given that we threw either $7$ or $8$.  As the cycles back to start leave us in the same place, we can ignore them.
Comment: Sir, Marcov chains are explained in the book in later chapters, so how could the author use it before?(He has not presupposed it at all.)Will you please explain the second question with some other reasoning? Thanks.
Comment: Even so, the idea that if you throw something different from $7$ and $8$ you are back where you started should be clear.  You used to have to throw until you get one and you still have to throw until you get one.  All you care is the relative chance of $7$ and $8$
Comment: Thanks a lot. Will you please elaborate why any rolls we make after 7 or 8 will not affect the outcome?
Comment: Because you already have the answer.  Once you get one, that is the first one you see, so it comes before the other.

Rolling Dice Repeatedly


Is Kernel-Regression parametric or non-parametric?

Question: As the title says, is kernel regression a parametric or non-parametric method, and how can this be motivated/explained?
Comment: What is it you want explained?  The distinction between parametric and nonparametric models?  Kernel regression?
Comment: Thank you for the clarification.  You might find material on ["semi-parametric" methods](https://stats.stackexchange.com/search?q=semi*+parametr*+kernel+regres*+score%3A2) will illuminate some of the issues.
Comment: I want to know why Kernel Regression is considered a non-parametric regression method (Wikipedia)? I heard from someone that both the case of non-parametric and parametric can be argued for Kernel Regression, which made me curious. I am sorry if the question is not clear, maybe that is because of my own lack of understanding.
Answer: Kernel regression is considered non-parametric.
It is tempting to think of the amount of optimal smoothing as a "parameter", nevertheless on that aspect to quote from Shalizi's Advanced Data Analysis from an Elementary Point of View Chapt. 4 "Using Nonparametric Smoothing in Regression": "Strictly speaking, parameters are properties of the data-generating process
alone, so the optimal amount of smoothing is not really a parameter."
Our optimal amount of smoothing depends on our smoothing method, kernel choice, but also on how much data we have. As such as the number of data is our "parameters" in a kernel regression setting, kernel regression is non-parametric in itself. This fully aligns with the definition of a non-parametric model as a model "that cannot be parametrized by a finite sample of parameters" (from Wasserman's All of Statistics Chapt. 7 "Models, Statistical Inference and Learning").