ngFor gerando muitas chamadas

Question: Possuo um array que contém 40 posições. Ao fazer um ngFor utilizando esse array, crio uma série de componentes  dentro desse *ngFor. O problema é que está acabando com a performance. Debugando, e fazendo um contador dentro desse for, descobri que ele roda 600x, tendo somente 40 items.
Lendo sobre, descobri que se trata do Change detection, mas não consegui resolver. Alguém sabe como contornar esse comportamento? (não posso desligar o change detection).
No arquivo .ts

  cont: number = 0;
  array: number[] = [];

  ngOnInit() {
    let i = 0;

    while(i < 40) {
      this.array.push(i);
      i++;
    }
  }

  contador() {
    console.log(this.cont);
    this.cont++;
  }

No html

{{ contador() }}

Observando no console, verão que o contador vai até 400.
Se redimensionarem a tela, por exemplo, ele ainda continua gerando mais 400 chamadas :o
Comment: @LucasDuete, editei o post para melhor compreensão, agradeço pelas dicas do mínimo completo verificável.
Comment: Possível relacionado: https://pt.stackoverflow.com/questions/325996/angular-6-ngfor/326158#326158
Comment: Olá @weber bem vindo ao StackOverflow, por favor adicione alguns trechos de código para tornar a pergunta mais clara e para que possamos verificar se há algum problema no seu código, sugiro que leia https://pt.stackoverflow.com/help/mcve
Comment: Olá Pedro, tudo bem? Obrigado por tentar ajudar. É exatamente nesse post que sugeriu que eu descobri que o change detection que estava gerando os console.log a mais, porém não posso desativá-lo. Gostaria de saber se existe alguma técnica para contornar esse problema.
Answer: Isso acontece por causa do Change detection conforme já mencionado.
Cada vez que você adiciona no array, ele detecta e executa o ngFor* mais uma vez. É como se ele o código abaixo:
        let totalExecucao = 0;
        let array = [];

        for (int i = 0; i < 40; i++)
        {
            array.push(i);

            array.forEach(a => totalExecucao++);

            foreach (var item in array)
            {
                totalExecucao++;
            }
        }
        console.log(totalExecucao);

Se você executar esse código que coloquei, vai ver que o totalExecução será 820, que é o total de iterações que o ngFor* vai executar no código que você fez.
Solução:
Criar um Array temporário, incluir os objetos no array temporário, e depois atribuir o array temporário ao que está sendo utilizado pelo ngFor*.
cont: number = 0;
array: number[] = [];
arrayTemp: number[] = [];

ngOnInit() {
  let i = 0;

  while(i < 40) {
    this.arrayTemp.push(i);
    i++;
  }
  array = arrayTemp;
}

ngFor gerando muitas chamadas


Trying to call variable in C after if statement

Question: I'm making a calculator application, and I wanna see if I can call a variable I set in an if statement; after the if statement has ended. Can I do it? I've tried a couple of things but I just can't get it to work.
int main()
{
    // ...
    int finished;
    do{
        // ...
        if(operator == 1){
            int finished = number[1] + number[2];
            printf("\n\n%d \+ %d is: %d", number[1], number[2], finished);

        }
        if(operator == 2){
            int finished = number[1] - number[2];
            printf("\n\n%d \- %d is: %d", number[1], number[2], finished);

        }
        // ...
        printf("\ndebug %d\n: ", finished);
        // ...
    } while (doAgain == 1);
    return 0;
}

Comment: Which line are you referring to?
Comment: @Mihai Maruseac Your edit removed the initial declaration of `finished` so made substantial alterations to the question.  I've rolled it back.
Comment: @Austen Some suggestions: Transform your series of if in a [case switch](http://www.cprogramming.com/tutorial/lesson5.html). As default value (operator is no one of those handled) you will set a variable `resultComputed`, previously initialized at `true`, as `false`. You can also print a warning message in this case. You can put then printf *after* you have computed `finished`, so that you can put it only one time. And you call `printf` only if `resultComputed` is `true`.
Comment: Can you please elaborate?
Comment: Oooh I'm so sorry. at the very end of the code, the int variable finished. When it asks if you want to continue. I wanna reuse the contents of the finished variable as number[1].
Comment: @simonc: thanks, I overlooked that definition. I've updated the edit :)
Comment: @MihaiMaruseac Your edits removed the use of `finished` and thus obscured the point of the question.
Comment: The uses are there. The ones relevant to the question.
Comment: @MihaiMaruseac No, the whole point is the access of `finished` after the loop exits.
Comment: No, after the if branches. Which is there in the edit.
Comment: There is no `finished` access after the end of the `do` loop.
Comment: Before do-while() int finished is defined as integer; now there is no need to define the same variable "finished" again & again in the code.
Answer: No, the scope of a variable is up to the end of the nextmost { } pair.
If you need to access it here, you should define int finished; at the top (what you already do).
So just replace int finished = ... with finished = .... This just writes the pre-existing variable instead of defining a new one.
Answer: No, you cannot access a variable after it has fallen out of scope.
You'll need to add a new variable:
int fin;

if (...) {
    int finished;
    fin = finished;
}

fin; // still accessible. but finished no longer exists.

Or remove the declarations from the inner variable so the higher-scoped one is used:
int finished;

if (...) {
    finished = ...;
}

finished; // still accessible, of course.

Comment: What I meant was that you don't need to feel guilty about including in your answer things that you learned from other answers, and if it bothered you to duplicate other answers, then the logical thing is to just delete it.
Comment: Read the code again. The OP already has a `finished` variable outside the loop. s/he needs to get rid of the local declarations of `finished` that hide the outer one.
Comment: I learned that from the other answers. It seemed disingenuous (and unnecessary) to add it to mine.
Comment: SO isn't some sort of ego game, it's about good answers ... `fin` doesn't make for one. I suggest that you just delete your answer, since you have nothing to add.
Comment: I have edited. I really think I do not deserve the "ego" remark.
Comment: But's that's exactly what you're referring to with talk of "disingenuous" ... SO answers properly have nothing to do with such personal matters. If you were offended by it, you misunderstood what I was saying.
Answer: In C and almost all programming languages there are two things which are related to variables: the domain of visibility (scope) and the domain of life. Your question covers the first one.
In C, the rules are simple:

global variables are visible everywhere in the current compilation unit
local variables are visible only in the enclosing {..} scope

In your case, you must not redefine the finished in the if branches.


Determining the round of a match in a knock out tournament

Question: I have a knock-out tournament with $n$ players. The players are $P1$, $P2$, ... $Pn$.
In a tournament with 8 players there are the matches $M1$ (between $P1$ and $P2$), to $M4$ (between $P7$ and $P8$) in round 1. In round 2 the matches are $M5$ and $M6$ and in round 3 is the match $M7$.
Now I need a formula to calculate the round number for a given $M$. I think this should be pretty simple, but I have no idea what to look for.
Comment: Are you sure that there are $2^n$ players? If so, you cannot enumerate them from $P_1$ to $P_n$ for an integer number of players because $2^n=n$ does not have a real solution. (A solution to 2^n=n can be obtained with the analytic continuation of the product log-function. However this solution would not be a real number). My guess is that it's $n$ players and not $2^n$ players?
Comment: @YukiJ Yes, you are right, I changed that. I wanted to make clear that only powers of 2 are possible.
Comment: I understand how to calculate the number of matches in each round, but I would like to get _which_ round we are in when I only know $n$ and the match number.
Answer: Assuming that the number of players is $n$ and not $2^n$: In round 1 there are $n/2$ matches. In round 2 there are $n/4$ matches. In round $k$ there are $\frac{n}{2^k}$ matches. There are a total of $\log_2(n)$ rounds. The total number of matches is thus $$\sum_{i=1}^{\log_2(n)} \frac{n}{2^i}=n-1.$$
If you want to find out in which round match $j$, i.e. $M_j$, has taken place, you are looking for the minimal round $k$ ($k$ integer) such that $$\sum_{i=1}^{k} \frac{n}{2^i} \geq j.$$
In an optimization context one might write that the round number $R(j$) of match $j$ is given by
\begin{equation*}
\begin{aligned}
R(j)=& {\text{minimize}}
& & k \\
& \text{subject to}
& & \sum_{i=1}^{k} \frac{n}{2^i}\geq j,\\
&& &k \in \mathbb{Z}
\end{aligned}
\end{equation*}
Luckily, we don't have to use integer-programming methods to solve the problem. The number of matches up to round $k$ is given by  $$\sum_{i=1}^{k} \frac{n}{2^i} = n-2^{-k}n.$$ We thus need to solve $$j=n-2^{-k}n$$ for $k$. Since the $k$ obtained this way needs not to be an integer, we have to round it to the next higher integer. Thus, $R(j)=\lceil k \rceil$ with $k$ satisfying $j=n-2^{-k}n$.Solving the equation for $k$ yields $k=\frac{\log(\frac{n}{n-j})}{\log 2}$. This value then needs to be rounded to the next highest integer.
Comment: You are right with the variables. I added the precise calculation of $k$ in the answer. It is $k=\frac{\log(\frac{n}{n-j})}{\log 2}.$ Then round $k$ to the next highest integer.
Comment: So if I understand correctly, $j$ is the match number, $n$ is the number of players and $k$ is the round I am looking for, right? If so, how can I solve the formula for $k$?
Comment: Awesome! Thank you very much for your time!


read only error while reading data from excel in python

Question: I am new to python.
I have written a sample code to read data from excel in python.
from openpyxl import load_workbook
import logging

logging.basicConfig(level=logging.DEBUG)
wb = load_workbook(filename = 'names.xlsx', use_iterators = True)

for sheet in wb.get_sheet_names():
    worksheet = wb.get_sheet_by_name(name=sheet)
    print sheet

    if worksheet:
        index = 2
        append_brace = False

        while True:
            gender_index = 'B' + str(index)
            operator_index = 'C' + str(index)
            name_index = 'D' + str(index)
            lastname_index = 'E' + str(index)
            middlename_index = 'F' + str(index)

            print gender_index,"\n"
            print worksheet[gender_index]
            index = index+1;

when I run this file,the gender_index(cell) is getting printed properly but could not print the cell value.
Following is the error I have seen.
<openpyxl.cell.read_only.ReadOnlyCell object at 0x10faece30>

Comment: Whenever you report errors, you should include the whole traceback.
Answer: Use pandas to read excel files, your life will be much easier.
import pandas as pd
df = pd.read_excel('names.xlsx', sheetname=sheetname)

Then for printing columns you can do:
print df[column_name]

where column_name is the column name in Excel.


How to create pager in Yii2?

Question: I was searching how to create pager in Yii2 using LinkPage widget.
Is there any example? I am new in Yii, so any help would be good.
Answer: It is simple
$dataProvider = new ActiveDataProvider([
    'query' => User::find(),
    'pagination' => array('pageSize' => 50),
]);

echo \yii\widgets\LinkPager::widget([
    'pagination'=>$dataProvider->pagination,
]);

Or if you don't use dataProvider you should use this:
$query = User::find();
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>30]);

echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]);

Comment: @Alex shouldn't it be `'pagination' => $pagination` in the second example?
Comment: Just a hint: if you use GridView for listing entity rows it's enough to use the data provider code, the widget adds pager html on it's own.
Comment: Hi Alex - where do you provide the pageSize in your second example. Thanks.
Answer: In controller:
function actionIndex()
{
    $query = Article::find()->where(['status' => 1]);
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount' => $countQuery->count()]);
    $models = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

    return $this->render('index', [
         'models' => $models,
         'pages' => $pages,
    ]);
}

In view file:
foreach ($models as $model) {
    // display $model here
}

// display pagination
echo LinkPager::widget([
    'pagination' => $pages,
]);

Answer: Below is too simple for adding pagination,
We just need to add in controller,
$dataProvider = new ActiveDataProvider([
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
]);

Yii2 will bring pagination on index page,
https://yii2-framework.readthedocs.io/en/stable/guide/output-data-widgets/
Answer: In your controller
$searchModel = new CourseModuleMasterSearch();

$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

$dataProvider->pagination = ['pageSize' => 20];//add this line

How to create pager in Yii2?


Broadcasting message from ipcMain in electron

Question: I need to broadcast a message from main process of electron to all renderer processes. There is no send option for ipcMain, only an option to reply to the sender via event.sender.send().
Answer: You are looking for the webContents API. From the same page of documentation in your post:

It is also possible to send messages from the main process to the renderer process, see webContents.send for more information.

Here is the doc for webContents
Answer: You could make an array of windows, then iterate over them and send a message to each one:
var windowsArr = [];

windowsArr.push(new BrowserWindow({title: "Win 1"}));
windowsArr.push(new BrowserWindow({title: "Win 2"}));

function broadcast (message) {
    for (var i = 0; i < windowsArr.length; i++) {
        windowsArr[i].webContents.send('asynchronous-message', message);
    }
}

Answer: To elaborate on @Joshua's answers
in your main.js you can add something like that
const {BrowserWindow, ipcMain} = require("electron")

// list of active windows
const windows = []

// method to create windows in your app
const createWindow = (fileToLoad) => {
    const win = new BrowserWindow({
        webPreferences: {
            preload: path.join(__dirname, "preload.js"),
        },
    })
    // add new window to list of active windows
    windows.push(win)
    // automatically remove window from list when closed
    win.on("closed", () => {
        const winId = windows.indexOf(win)
        winId > -1 && windows.splice(winId,1)
    })
    fileToLoad && win.loadFile(fileToLoad)
    return win
}

// broadcast to all windows opened with createWindow
const broadcast = (eventType, ...params) => {
    windows.forEach(win => win.webContents.send("app:broadcastEvent", {eventType, eventData: [...params]}))
}

// later in your code
broadcast('customEvent', "parameter1", "parameter2")

in your preload.js you should expose a method to regiseter a listener for broadcasted events
const { contextBridge, ipcRenderer } = require("electron")

contextBridge.exposeInMainWorld('electronAPI', {
    onBroadCastedEvent: (callback) => {
        ipcRenderer.on("app:broadcastEvent", (evt, {eventType, eventData}) => callback(eventType, ...eventData))
    }
})

then in you renderer.js you can register a listener like this:
window.electronAPI.onBroadCastedEvent((eventType, ...eventParams) => {
    console.log(`received broadcast event ${eventType} with data: `, eventParams)
})


full-text catalog index CONTAINS() doesn't work with numbers

Question: I've just moved databases from one server to another, this query works fine on the old server but now it doesn't work on the new one when I use numbers only in the search:
<code>SELECT *
FROM Products
WHERE  CONTAINS(ProductTitle,'"sample*" AND "7*"')
</code>
When you remove the 7* it works fine on the new server but it doesn't return anything with it included.  Just tested the same exact query on the old server and it runs perfectly fine.
Comment: You should specify that you're trying to use a full-text catalog index, and verify that the fulltext index is properly built on the new server. Personally, I avoid full text catalogs in SQL Server, especially for something like just a Product Title.
Comment: Tell us about the old server and the new server: are they the same version of SQL Server? What configuration did you copy across?
Comment: I'm using full-text catalog index.  I don't have access to the old server anymore so I'm not sure what it had.  I can't use the LIKE because if user types "7 sample" and the ProductTitle is "sample 7 product", it won't come up which is why I use the CONTAINS.
Comment: What would you use @pmbAustin for something like this? I want it where if user searches for Sample 7, it'll show anything that contains the words 7 and Sample regardless of the order
Comment: You can still use LIKE. Just do a Split String on your search term (splitting on space), and generate a WHERE clause with a clause for each term. This gets into dynamic SQL, but it's a solution.
Answer: In case someone else ran into this... the new server I moved to had a "stoplist" which for the full-text catalog was for any single letter.  I removed it and everything worked.
Comment: Hey I am running into the same issue, what did you do to remove "stoplist" thanks in advance
Comment: Nevermind I found it under the properties of the FullText, I had stoplist on and toggled it off, re indexed, now all works too, thanks!
Answer: try to use 'like' instead 'CONTAINS'
Comment: I'm using full-text catalog index. I don't have access to the old server anymore so I'm not sure what it had. I can't use the LIKE because if user types "7 sample" and the ProductTitle is "sample 7 product", it won't come up which is why I use the CONTAINS.


Exim won't sign mail send by PHP through SMTP

Question: I've been struggling to get Exim to sign my mails i'm sending with Zend2 Mailer class. The class has the option to send through SMTP; this is awesome since i have everything configured at MTA level.
However. Sending mail from a client (Thunderbird) will get signed. The mail send with Zend2's Mailing class will not. Let's start with my version of Exim.
Exim version 4.76 #1 built 19-Jul-2011 02:56:59
Copyright (c) University of Cambridge, 1995 - 2007
Berkeley DB: Berkeley DB 4.7.25: (November 12, 2010)
Support for: crypteq IPv6 Perl OpenSSL move_frozen_messages Content_Scanning DKIM Old_Demime
Lookups (built-in): lsearch wildlsearch nwildlsearch iplsearch cdb dbm dbmnz
Authenticators: cram_md5 plaintext
Routers: accept dnslookup ipliteral manualroute queryprogram redirect
Transports: appendfile/maildir/mailstore/mbx autoreply lmtp pipe smtp
Size of off_t: 8
Configuration file is /etc/exim.conf

Then there is the configuration of DKIM. I tried looking up the domain with the method beneath instead of using the $sender_address_domain variable. I saw in another serverfault post that the DATA command can malform the envelope resulting in a wierd sender address. That however was not the case with me. Both resolve to the actual sender/from adres.
[rob@server ~]$ exim -bP transports | grep dkim
dkim_canon = relaxed
dkim_domain = ${lc:${domain:$h_from:}}
dkim_private_key = ${if exists{/etc/virtual/$sender_address_domain/dkim.private.key}{/etc/virtual/$sender_address_domain/dkim.private.key}{0}}
dkim_selector = x
dkim_sign_headers = MIME-Version:Date:Message-ID:Subject:From:To
dkim_strict = 0

The keys are there. The configuration works, as verified with mail send with Thunderbird.
Then i asked myself, do these mails actually pass through the SMTP server? The result; yes they do. I checked the /var/log/exim/mainlog. Now i also noted that the mails from Thunderbird don't get that "recieving the mail" logline. I don't know why? Can someone elaborate on that if they know why? PHP connects using SMTP login method with the exact same SMTP information that Thunderbird uses. Same ports, domain, username, password.

https://framework.zend.com/manual/2.4/en/modules/zend.mail.smtp.options.html#zend-mail-smtp-options

# This is the mail recieved from the PHP code.
2016-11-15 08:28:52 1c6YAm-000154-6p <= email@example.com H=mydomain.com [ipv4.addr] P=esmtpa A=login:email@example.com S=22098 firstname.lastname@example.com T="Another day at the office with DKIM..." from <firstname.lastname@example.com> for email@example.com

# Here it is outbound for its destination. Not signed to be noted.
2016-11-15 08:28:52 1c6YAm-000154-6p => email@example.com F=<firstname.lastname@example.com> R=lookuphost T=remote_smtp S=22157 H=gmail-smtp-in.l.google.com [ipv6.addr] X=UNKNOWN:ECDHE-RSA-AES128-GCM-SHA256:128 C="250 2.0.0 OK 1479194932 yr4si27147042wjc.210 - gsmtp"

# This is send with Thunderbird. This gets signed...
2016-11-15 08:31:47 1c6YDa-0001CM-UY => firstname.lastname@example.com F=<firstname.lastname@example.com> R=lookuphost T=remote_smtp S=762 H=gmail-smtp-in.l.google.com [ipv6.addr] X=UNKNOWN:ECDHE-RSA-AES128-GCM-SHA256:128 C="250 2.0.0 OK 1479195107 s17si1915514wme.47 - gsmtp"

These mails also don't get rejected nor can be found in the panic log. They both get recieved by my gmail account:
# This is the mail send from thunderbird. With DKIM signing.

Delivered-To: email@example.com
Received: by 10.80.186.18 with SMTP id g18csp1289759edc;
        Mon, 14 Nov 2016 23:31:47 -0800 (PST)
X-Received: by 10.194.248.5 with SMTP id yi5mr384988wjc.11.1479195107193;
        Mon, 14 Nov 2016 23:31:47 -0800 (PST)
Return-Path: <email@example.com>
Received: from myserver.com (myserver.com. [ipv6.addr])
        by mx.google.com with ESMTPS id s17si1915514wme.47.2016.11.14.23.31.47
        for <email@example.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Mon, 14 Nov 2016 23:31:47 -0800 (PST)
Received-SPF: pass (google.com: domain of email@example.com designates ipv6.addr as permitted sender) client-ip=ipv6.addr;
Authentication-Results: mx.google.com;
       dkim=pass firstname.lastname@example.com;
       spf=pass (google.com: domain of email@example.com designates ipv6.addr as permitted sender) email@example.com;
       dmarc=pass (p=NONE dis=NONE) header.from=mydomain.com
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=mydomain.com; s=x;
    h=Content-Transfer-Encoding:Content-Type:MIME-Version:Date:Message-ID:Subject:From:To; bh=zaNQl8a2eAEHfPVmKMA7RmtMqJ/6huDk4u6pr/tWrqQ=;
    b=xcDHIzzTWS8hPMxjqbZM0I6b/act/LlweTuNcnZJ9ttEF1dAm37Lzy8zOJz2E2aDTkcQOdCQuC+VyIaXTRzTMJXyzJTUXTgPUPOePsR5XYqqsE0iQRMkDl/Ah650kBHD5drqIrFJwCw5g0aL9OECqTyRO9kwL0DQJX/mKcTkLtiiIs7Z7G77ZwWhJpFm/duoQARtZZ1UZFu42/Vbl+V8vSoWbXoZBpg+WBGucWJoGq+hb5zILxwsMPcbrIu+avBjjoUdLVP9YMFiPC3nK+7zOGBWOO7x6QoHQmO8uo0P88E52Sm9ZJGgLQOCfFCMjCnv4IMemj/GSe25Sf8PKah/Xg==;
Received: from 159-032-128-083.dynamic.caiway.nl ([126.96.36.199] helo=[192.168.1.108])
    by myserver.com with esmtpsa (UNKNOWN:AES128-SHA:128)
    (Exim 4.76)
    (envelope-from <firstname.lastname@example.com>)
    id 1c6YDa-0001CM-UY
    for email@example.com; Tue, 15 Nov 2016 08:31:46 +0100
To: Rob van der Lee <email@example.com>
From: Rob van der Lee <email@example.com>
Subject: Dit is een verzonden mail via account
Message-ID: <email@example.com>
Date: Tue, 15 Nov 2016 08:31:46 +0100
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
 Thunderbird/45.4.0
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit

Dit is echt een test.

And here the mail that gets send from PHP that doesn't get signed.
Delivered-To: email@example.com
Received: by 10.80.186.18 with SMTP id g18csp1288906edc;
        Mon, 14 Nov 2016 23:28:52 -0800 (PST)
X-Received: by 10.28.170.134 with SMTP id t128mr2009669wme.29.1479194932632;
        Mon, 14 Nov 2016 23:28:52 -0800 (PST)
Return-Path: <email@example.com>
Received: from myserver.com (myserver.com. [ipv6.addr])
        by mx.google.com with ESMTPS id yr4si27147042wjc.210.2016.11.14.23.28.52
        for <email@example.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Mon, 14 Nov 2016 23:28:52 -0800 (PST)
Received-SPF: pass (google.com: domain of email@example.com designates ipv6.addr as permitted sender) client-ip=ipv6.addr;
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of firstname.lastname@example.com designates ipv6.addr as permitted sender) email@example.com;
       dmarc=pass (p=NONE dis=NONE) header.from=mydomain.com
Received: from mydomain.com ([220.127.116.11])
    by myserver.com with esmtpa (Exim 4.76)
    (envelope-from <email@example.com>)
    id 1c6YAm-000154-6p
    for firstname.lastname@example.com; Tue, 15 Nov 2016 08:28:52 +0100
Date: Tue, 15 Nov 2016 07:28:52 +0000
To: email@example.com
From: Rob van der Lee <email@example.com>
Sender: Rob van der Lee <firstname.lastname@example.com>
Subject: Another day at the office with DKIM...
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="=_7ebb8a8d12984c5cc3f5fbf995b1b4ad"
Message-ID: <email@example.com>

This is a message in Mime Format.  If you see this, your mail reader does not support this format.

--=_7ebb8a8d12984c5cc3f5fbf995b1b4ad
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

... content of mail in text and then html, left it out since not relevant.

It just doesn't make sense to me why Exim won't sign this mail. As seen in the log file both mails get send via T=remote_smtp and according to my MTA configuration all outbound mails that get send via remote_smtp should be signed.
Apart from the fact that the mail actually does get send and reaches the mailbox. Hopefully i can learn from this.
Update:
As per suggestion of Daniel i tried resolving the domain, handling the SMTP request, internally as opposed to letting my provider handle this for me. This does not help, the message is still sent unsigned.
The logs also look the same as mentioned above.
Dig Request of old situation:
;; QUESTION SECTION:
;mydomain.com.      IN  NS

;; ANSWER SECTION:
mydomain.com.   86400   IN  NS  ns1.transip.nl.
mydomain.com.   86400   IN  NS  ns2.transip.eu.
mydomain.com.   86400   IN  NS  ns0.transip.net.

Dig Request of new situation:
;; QUESTION SECTION:
;mydomain.com.      IN  NS

;; ANSWER SECTION:
mydomain.com.   14400   IN  NS  ns2.myserver.com.
mydomain.com.   14400   IN  NS  ns1.myserver.com.

Update to Answer:
I've also make a bug ticket over at the Exim Bug tracker. Thought to get some help over the experts; Jeremy Harris pointed me in the right direction.
Jeremy Harris 2016-11-15 14:58:55 GMT

First, if you're running Exim 4.76 - update it.

Then, assuming the problem still exists:  restart your daemon with a commandline
debug option, collecting output.  Feed it a test mail.  Examine the debug output,
which shows the processing flow for the message.  Compare with your config and
work out where it differs from what you expected.

I did what he told me. Updated, then found out the problem still persisted. Fed the debug modus 2 mails. One signed, the other unsigned.
I started closely comparing and noticed that the body on both mails started getting fed to PDKIM (the dkim lib for Exim). Then i noticed my unsigned mail didn't had closure after the body like the signed message did.
I figured it had to do with the content; so from the PHP side i send a mail with just a line of text. This was getting signed...
Solution? Wordwrapping! That i didn't thought of this earlier! I really don't feel all that smart now. This because i knew about this at forehand.  The RFC 2646 spec tells us all about it.
Hope this post will help somebody else. It was a good journey and stupid enough the problem was my implementation.
Comment: Just a shot in the dark, try this:  `dkim_sign_headers = MIME-Version:Date:Message-ID:Subject:From:To`   Maybe you hit some weird bug with Content-Type or Content-Transfer-Encoding.
Comment: Changed the config. Restarted Exim. Send mail, yet without being signed. I will leave that in nonetheless as it doesn't hurt. Thanks for the suggestion. Also updated the main post with this change.
Comment: check that the value of `$sender_domain` is as expected.  Perhaps you can use `headers_add` to do this,
Comment: `message-id` seems kind of long, but probably not related.
Comment: The message id in the PHP generated mail was added there by me. That is indeed long. How can i check what the sender domain at MTA level is? Can i add a print to log or debug?
Answer: (I can't comment, so this isn't meant as an answer, but I hope it helps)
A while back I worked on the same issue and it gave me a real headache, in my case I had two nameservers, one on the oustite at the hosting company, and one was also running on the server itself, to handle internal naming.
(As you seem Dutch; TransIP VPS with Cpanel and the domains where handled on the TransIP side.)
Now on the external DNS I had set the DKIM, so that worked for most of the situations, but not for my PHP mail function, therefor I needed to als set it on the internal (Cpanel) DNS to get it working for PHP.
(Also while I was searching for this issue there was something with 7bit and 8bit Content-Transfer-Encoding, but that didn't make a difference in my case)
Comment: Yes. I'm using TransIP's servers. I'm using the same setup it seems. I will try to handle the domain internally to see if it makes any difference. Thanks for the tip so far!

I will also try to set the encoding to 7bit to see if it makes a difference in my case.
Comment: Changing to 7bit didn't help. Thanks nonetheless for the suggestion. I will still try sending from an internal domain later today (when the dns is fully resolved)


"404 - Resource not found" when query OData v2 with empty key field

Question: I have an SAP CDS View exposed via Gateway and hosted on APIM.
This CDS has CRUD operations enabled using @ObjectModel annotations.
One of the key fields from the CDS (SAP table) can be empty as per business process, but when I try to query for this full key via APIM service (with the empty property) I receive 404 - Resource not found:

The same query works fine inside SAP Gateway:

What should I do in order to APIM understand that this key field can receive empty (or null?) values?
Comment: CDS has two types of keys: semantic and technical keys, and both cannot be empty. AFAIK. Give the definition of your CDS view, please
Comment: Sorry.. Didn't get it! Key fileds can be empty.. I mean on transparent table and also CDS.

The keys are the ones used to identify the resource on my request: zbudat, matnr, werks, lgort and charg.

Note that charg is a key and it's emtpy.
Answer: Thanks for the answers!
We have found out that it might be an APIM mapping issue because when we set an empty key on the path (charg='') we receive a 404 without even reaching SAP Gateway:

But when we set this same parameter with a blank / space (charg=' '), it works fine and it finds the entry on S4 table:

How do I know it didn't reach S4?
First, because the trace doesn't catch anything and second because the 404 message is differente when it comes from S4:

Thank you all!
Answer: It is interesting to see this from the APIM service and gateway query, the result is different given the same query parameter, the only explanation to me is that there is a conversion at ABAP side and this cause no result can be loaded. Can you enable gateway trace at ABAP side to check the exact request when ABAP tries to query data when you use APIM client? Use transaction /IWNFD/TRACES to see the traces for your user at ABAP side.
Regards,
Derek


Probability of flipping 12 coins 5 times all being heads

Question: If I had to flip 12 coins simultaneously, and did this 5 times in a row, what are the chances that all 60 coins got heads?
Comment: There is no essential difference between throwing simultaneously or in a row.
Answer: The probability is the same as if you just flipped a fair coin 60 times in a row, i.e., one in $2^{60} \approx 1.1529215 \times 10^{18} \approx 1.15$ quintillion.  The fact that you're dividing them into five batches of twelve does not affect the probability.
For comparison, the probability of winning the Powerball jackpot (a US lottery) is one in 292 million.  You are more than ten times more likely1 to win the Powerball jackpot twice in a row than you are to have a coin come up heads 60 times in a row.

1 To be precise:  $2^{60}/(292201338)^2 \approx 13.5$ times.


Magento configurable products and associated products

Question: I have an issue when I add a new configurable product, then try to add associated products
to this the associated products do not appear.
Also if I go into edit the product it prompts to Select Configurable Attributes
even though the type is already a configurable product.
The attribute set is applicable to all product types.
Seems like the JavaScript to add the simple products to the configurable is not firing
and when I save the product, because there are no options added to the attribute it prompts me
to choose an attribute set again.
Any help would be great
Comment: see what happens in the browser console - maybe U r right and some JS fails to load or sth - console is a good place to start investigation
Answer: Thankyou for the reply, it appears that the script folder was missing, i download the latest version and upload the files to the correct path and issue resolved, this link helped
http://www.magentocommerce.com/boards/prem../viewthread/914919/#t477173
thanks for your help.


How do I backup email messages in Dovecot? Where are they located in the file system?

Question: I run Postfix with Dovecot. Now I need to begin to backup email messages. What directories should I backup? Such that later, if a server breaks down, I'll be able to restore all the email message on a new server with Postfix and Dovecot.
Comment: Does this answer your question? [How to backup all the emails(content) of Postfix? What folders?](https://serverfault.com/questions/1033805/how-to-backup-all-the-emailscontent-of-postfix-what-folders)
Comment: please be so kind to inform us what distribution you are using, are you using native administration or some kind of administration panel?
Comment: Please don't repeatedly ask the same question, because the answer is the same: it depends on your configuration so start by checking that.
Comment: These questions actually are subtly different (albeit closely related) and I expect them to have different answers, so I've reopened the question.
Answer: As usual, there is more than one way to skin the cat. But dovecot-backup exists, so have a look, it might be just the ticket for you.
Some commenters advised you to check your configuration and that is good advice. In case you feel overwhelmed by where and what to check, I suggest you start with doveconf -n|less and check for the word 'location', in particular the variable mail_location.
You will have a learning curve ahead of you, either way. Good luck!
Comment: @MichaelHampton Maybe his other, implied question was "why do people keep being friendly and helpful even when I am presenting myself as lazy, not following house rules and rude?"  Dunno...
Comment: Question: How do I backup email messages in dovecot?
Answer: Use dovecot-backup.

Well, at least to me that very much does look like an answer.  Better luck with your questions next time, I guess.
Comment: There're 2 more questions as well in my topic
Comment: @karneliy He also answered how to find out what directory is being used. What other questions did you have?


Show custom video control bar in Firefox

Question: Have a hard problem here: my video controls bar isn't showing up in fullscreen mode in Firefox. In Chrome, Opera, Safari everything is "Gucci in the Louis store" (done by z-index: 2789034264 !important ) but in Firefox it ignores z-index. The main function names are exitHandler(), enterFullScreen() and exitFullScreen(). Full code here:

var vid, playPauseButton, seekSlider, currentTime, vidDuration, muteButton, volumeSlider, fullScreenToggler, loop, fullscreenHider;

function intializePlayer(){
"use strict";
// Set object references
vid = document.getElementById("vid");
playPauseButton = document.getElementById("playPauseButton");
seekSlider = document.getElementById("seekSlider");
currentTime = document.getElementById("done");
vidDuration = document.getElementById("duration");
muteButton = document.getElementById("muteUnmute");
volumeSlider = document.getElementById("volumeSlider");
fullScreenToggler = document.getElementById("toggleFullScreen");
loop = document.getElementById("loop");
fullscreenHider = document.getElementById("exitFullScreen");
// Add event listeners
playPauseButton.addEventListener("click",playPauseVideo,false);
seekSlider.addEventListener("input",timeSlider,false);
vid.addEventListener("timeupdate",videoTimeUpdate,false);
muteButton.addEventListener("click",muteUnmute,false);
volumeSlider.addEventListener("input",volumeChange,false);
volumeSlider.addEventListener("input",toggleIcon,false);
fullScreenToggler.addEventListener("click",enterFullScreen,false);
fullscreenHider.addEventListener("click",exitFullScreen,false);
document.addEventListener('webkitfullscreenchange', exitHandler, false);
document.addEventListener('mozfullscreenchange', exitHandler, false);
document.addEventListener('fullscreenchange', exitHandler, false);
document.addEventListener('MSFullscreenChange', exitHandler, false);
loop.addEventListener("click",loopVideo,false);
//Add some other settings
vid.controls = false;
vid.oncontextmenu = function(){return false;};
}

window.onload = intializePlayer;

//Video Functions
function exitHandler(){
"use strict";
  if (document.webkitIsFullScreen === false || document.mozFullScreen === false || document.msFullscreenElement === false){
   document.getElementsByClassName("videoControls")[0].classList.remove("fullscreen");
    fullscreenHider.style.display = "none";
 fullScreenToggler.style.display = "inline-block";}
}
function playPauseVideo(){
"use strict";
 if(vid.paused){
  document.title = "►" + " " + document.title;
  vid.play();
  playPauseButton.innerHTML = '';}
 else {
  vid.pause();
  playPauseButton.innerHTML = '';}
}
function timeSlider(){
"use strict";
 var slideTo = vid.duration * (seekSlider.value / 100);
 vid.currentTime = slideTo;
}
function videoTimeUpdate(){
"use strict";
 var timeInterval = vid.currentTime * (100 / vid.duration);
 seekSlider.value = timeInterval;
 var currentMinutes = Math.floor(vid.currentTime / 60);
 var currentSeconds = Math.floor(vid.currentTime - currentMinutes * 60);
 var durationMinutes = Math.floor(vid.duration / 60);
 var durationSeconds = Math.floor(vid.duration - durationMinutes * 60);
 if(currentSeconds < 10) {currentSeconds = "0"+ currentSeconds;}
 if(durationSeconds < 10) {durationSeconds = "0"+ durationSeconds;}
 if(currentMinutes < 10) {currentMinutes = "0"+ currentMinutes;}
 if(durationMinutes < 10) {durationMinutes = "0"+ durationMinutes;}
    currentTime.innerHTML = currentMinutes + ":" + currentSeconds;
 vidDuration.innerHTML = durationMinutes + ":" + durationSeconds;
}
function volumeChange(){
"use strict";
 vid.volume = volumeSlider.value / 100;
}
function enterFullScreen(){
"use strict";
 if(vid.requestFullScreen){
  vid.requestFullScreen();}
 else if(vid.webkitRequestFullScreen){
  vid.webkitRequestFullScreen();}
 else if(vid.mozRequestFullScreen){
  vid.mozRequestFullScreen();}
 else if(vid.oRequestFullScreen){
  vid.oRequestFullScreen();}
 else if(vid.msRequestFullScreen){
  vid.msRequestFullScreen();}
 document.getElementsByClassName("videoControls")[0].classList.add("fullscreen");
 document.getElementsByClassName("fullscreen")[0].setAttribute("draggable","true");
    fullScreenToggler.style.display = "none";
 fullscreenHider.style.display = "inline-block";
 }
function exitFullScreen(){
"use strict";
 if(document.cancelFullScreen){
  document.cancelFullScreen();}
 else if(document.webkitCancelFullScreen){
  document.webkitCancelFullScreen();}
 else if(document.mozCancelFullScreen){
  document.mozCancelFullScreen();}
 else if(document.oCancelFullScreen){
  document.oCancelFullScreen();}
 else if(document.msCancelFullScreenn){
  document.msCancelFullScreen();}
    document.getElementsByClassName("videoControls")[0].classList.remove("fullscreen");
    fullscreenHider.style.display = "none";
 fullScreenToggler.style.display = "inline-block";
}
function loopVideo(){
"use strict";
 if(!loop.hasAttribute("style")){
  loop.setAttribute("style","opacity: 1; color: rgba(22,206,170,1.00);");
  vid.setAttribute("loop","");
 }
 else {
  loop.removeAttribute("style");
  vid.removeAttribute("loop");
 }
}
function toggleIcon(){
"use strict";
if(vid.volume <= 0.01){
  muteButton.innerHTML = '';}
else if(vid.volume <= 0.42){
 muteButton.innerHTML = '';}
else {
 muteButton.innerHTML = '';
}
}
var prev_level;

function muteUnmute(){
"use strict";
 if(vid.volume >= 0.03){
  prev_level = volumeSlider.value;
  volumeSlider.value = 0;
  vid.volume = volumeSlider.value;
  toggleIcon();
 }
    else if(vid.volume <= 0.05){
  volumeSlider.value= prev_level;
  vid.volume = volumeSlider.value / 100;
  toggleIcon();
 }
}

//KeyPress Fuctions

function pressSpaceToStart(e){
 "use strict";
 if(e.keyCode === 32){
    e.preventDefault();
       playPauseVideo();}
}
window.onkeypress = function(o){"use strict"; pressSpaceToStart(o);};
window.onkeydown = function(o){"use strict"; pressSpaceToStart(o);};
@charset "UTF-8";
/* CSS Document */

/* Video Box Styling */
video::-webkit-media-controls, video::-webkit-media-controls-enclosure {display:none !important;}
section.videoSection {width: 100%; margin: auto; margin-top: 30px;}
div.mainVideo {text-align: center; width: 454px; margin: auto;}
div.mainVideo video {width: 450px; border: 2px solid black; border-bottom: 0;}
div.videoControls {width: 450px; margin: -5px auto 0px; background-color: rgba(67,41,82,0.97); padding: 10px 0px 8px 0px; border: 2px solid black; color: snow; border-bottom-left-radius: 12px; border-bottom-right-radius: 12px;}
div.videoControls button {background-color: transparent; border: 0; opacity: 0.8;}
div.videoControls span {position: relative;}
div.videoControls button:hover {opacity: 1;}
/* Slider Styling */
input[type=range] {-webkit-appearance: none; margin: 5.8px 0;}

input[type=range]:focus {outline: none;}

input[type=range]::-webkit-slider-runnable-track {cursor: pointer; box-shadow: 2.4px 2.4px 6.2px rgba(7, 7, 163, 0.72), 0px 0px 2.4px rgba(8, 8, 187, 0.72); background: #ac62ff; border-radius: 21.6px; border: 1px solid rgba(163, 0, 255, 0.79);}

input[type=range]::-webkit-slider-thumb {box-shadow: 2.4px 2.4px 9.5px rgba(4, 16, 14, 0.78), 0px 0px 2.4px rgba(9, 36, 32, 0.78); border: 1.8px solid rgba(0, 0, 6, 0.77); border-radius: 28px; background: #ffff29; cursor: pointer; -webkit-appearance: none; margin-top: -7.8px;}

input[type=range]:focus::-webkit-slider-runnable-track {background: #b16cff;}

input[type=range]::-moz-range-track {width: 100%; cursor: pointer; box-shadow: 2.4px 2.4px 6.2px rgba(7, 7, 163, 0.72), 0px 0px 2.4px rgba(8, 8, 187, 0.72); background: #ac62ff; border-radius: 21.6px; border: 1px solid rgba(163, 0, 255, 0.79);}

input[type=range]::-moz-range-thumb {box-shadow: 2.4px 2.4px 9.5px rgba(4, 16, 14, 0.78), 0px 0px 2.4px rgba(9, 36, 32, 0.78); border: 1.8px solid rgba(0, 0, 6, 0.77); border-radius: 28px; background: #ffff29; cursor: pointer;}

input[type=range]::-ms-track {width: 100%; cursor: pointer; background: transparent; border-color: transparent; color: transparent;}

input[type=range]::-ms-fill-lower {background: #a758ff; border: 1px solid rgba(163, 0, 255, 0.79); border-radius: 43.2px; box-shadow: 2.4px 2.4px 6.2px rgba(7, 7, 163, 0.72), 0px 0px 2.4px rgba(8, 8, 187, 0.72);}

input[type=range]::-ms-fill-upper {background: #ac62ff; border: 1px solid rgba(163, 0, 255, 0.79); border-radius: 43.2px; box-shadow: 2.4px 2.4px 6.2px rgba(7, 7, 163, 0.72), 0px 0px 2.4px rgba(8, 8, 187, 0.72);}

input[type=range]::-ms-thumb {box-shadow: 2.4px 2.4px 9.5px rgba(4, 16, 14, 0.78), 0px 0px 2.4px rgba(9, 36, 32, 0.78); border: 1.8px solid rgba(0, 0, 6, 0.77); border-radius: 28px; background: #ffff29; cursor: pointer;}

input[type=range]:focus::-ms-fill-lower {background: #ac62ff;}

input[type=range]:focus::-ms-fill-upper {background: #b16cff;}

/* Non fullscreen track and thumb width and height */

/* Track */
.videoControls input[type=range]::-webkit-slider-runnable-track {height: 6.4px;}
.videoControls input[type=range]::-moz-range-track {height: 6.4px;}
.videoControls input[type=range]::-ms-track {height: 6.4px;}

/* Thumb */
.videoControls input[type=range]::-webkit-slider-thumb {height: 20px; width: 8px;}
.videoControls input[type=range]::-moz-range-thumb {height: 20px; width: 8px;}
.videoControls input[type=range]::-ms-thumb {height: 20px; width: 8px;}

/* Video Controls Buttons Styling */
#playPauseButton {float: left; margin: -3px 1px 0px 3px;}
#loop {float: left; margin: 4px 5px 25px 3px;}
#seekSlider {width: 150px; float: left; margin: 10px 5px 0px -1px;}
div.mainVideo span {color: snow; font-size: 0.97em; display: inline-block; float: left; margin: 2.5px 0px 0px 1px;}
#muteUnmute {margin-top: -5px; float: left;}
#volumeSlider {width: 64px; margin: 10px 0px 0px 0px; float: left;}
#toggleFullScreen {margin: 0px 0px 0px 4px;}

/* Fullscreen settings -START-*/

.fullscreen {z-index: 2789034264 !important; position: absolute !important; width: 80% !important; bottom: 5.7% !important; left: 10% !important; right: 10% !important; height: 35px !important;}
.fullscreen button i {font-size: 2.5em !important;}
.fullscreen button#playPauseButton {margin-left: 0.2% !important; float: left !important;}
.fullscreen input#seekSlider {width: 48% !important; margin-left: 2px !important;}
.fullscreen button#muteUnmute {margin-left: 0.5%; font-size: 0.98em; margin-top: -10px;}
.fullscreen span {font-size: 1.2em !important;}
.fullscreen input#volumeSlider {width: 12%; margin-left: 1%;}
#exitFullScreen {margin-left: 0.5%; margin-top: -3px;}

/* Fullscreen track and thumb width and height */

/* Track */
.fullscreen input[type=range]::-webkit-slider-runnable-track {height: 12.8px;}
.fullscreen input[type=range]::-moz-range-track {height: 12.8px;}
.fullscreen input[type=range]::-ms-track {height: 12.8px;}

/* Thumb */
.fullscreen input[type=range]::-webkit-slider-thumb {height: 32px; width: 12px; margin-top: -10px;}
.fullscreen input[type=range]::-moz-range-thumb {height: 32px; width: 12px; margin-top: -10px;}
.fullscreen input[type=range]::-ms-thumb {height: 32px; width: 12px; margin-top: -10px;}

/* Responsibility -START- */

/* Responsibility -END- */
/* Fullscreen setting -END- */
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>

 <video preload="auto" id="vid" onContextMenu="return false;">
  <source type="video/mp4" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"/>
  <source type="video/webm" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm"/>

 </video>

   <button id="playPauseButton" title="Play/Pause">

   </button>

   00:00
   /
   00:00

   <button id="loop" title="Loop">

   </button>
   <input type="range" step="1" min="0" max="100" value="0" id="seekSlider" title="Slider" style=""/>
   <button id="muteUnmute" title="Mute/Unmute">

   </button>
   <input type="range" step="1" min="0" max="100" value="100" id="volumeSlider" title="Volume level"/>
   <button id="exitFullScreen" style="display: none; font-size: 0.95em" title="Exit fullscreen">

   </button>
   <button id="toggleFullScreen" title="Enter fullscreen">

   </button>

And now some images:

Comment: http://stackoverflow.com/a/31710969/334402 - maybe useful reference
Comment: @Mick  Almost. But I have `position absolute` not `fixed` for my controls bar.
Comment: why not using video JS ?
Comment: by the way its working fine here which version u r using ?
Comment: @IsmailFarooq You know, I'm trying to learn how to create a web player myself. I'm m using the latest version of Firefox.
Answer: Cool project!
Firefox full screen mode has a lot of quirks in my experience. In general with Firefox, you're probably better off setting full screen mode on a containing DIV rather than the element of interest per se. In this case, you can set it on class=mainVideo rather than id=vid. There might be easier ways to do this, but the following seems to work for me (I've tested in Chrome and Firefox--not sure about other browsers):
Add global variables at the top of your script to store reference to the mainVideo div, as well as the dimensions of mainVideo and vid:
var mainVideo, mainVideoHeight, mainVideoWidth, vidHeight, vidWidth;

Assign to these variables in initializePlayer():
vid = document.getElementById("vid");
mainVideo = document.getElementsByClassName('mainVideo')[0];
vidHeight = vid.clientHeight;
vidWidth = vid.clientWidth;
mainVideoHeight = mainVideo.clientHeight;
mainVideoWidth = mainVideo.clientWidth;

Modify enterFullScreen() to assign vid's and mainVideo's width and height to be equal to the screen width and height, and to request full screen on mainVideo rather than on vid:
function enterFullScreen(){
"use strict";

  if(mainVideo.requestFullScreen){
    mainVideo.requestFullScreen();}
  else if(mainVideo.webkitRequestFullScreen){
    mainVideo.webkitRequestFullScreen();}
  else if(mainVideo.mozRequestFullScreen){
    mainVideo.mozRequestFullScreen();}
  else if(mainVideo.oRequestFullScreen){
    mainVideo.oRequestFullScreen();}
  else if(mainVideo.msRequestFullScreen){
    mainVideo.msRequestFullScreen();}
  document.getElementsByClassName("videoControls")[0].classList.add("fullscreen");
  document.getElementsByClassName("fullscreen")[0].setAttribute("draggable","true");

  fullScreenToggler.style.display = "none";
  fullscreenHider.style.display = "inline-block";

  vid.style.width = screen.width + 'px';
  vid.style.height = screen.height + 'px';
  mainVideo.style.width = screen.width + 'px';
  mainVideo.style.height = screen.height + 'px';
}

Add additional code to the end of exitFullScreen() to reset the vid's and mainVideo's widths and heights to the original stored widths and heights:
   vid.style.width = vidWidth + 'px';
   vid.style.height = vidHeight + 'px';
   mainVideo.style.width = mainVideoWidth + 'px';
   mainVideo.style.height = mainVideoHeight + 'px';

The following is the full code that I tested. It will not work if you click 'Run code snippet'. You have to copy into a local file and open in a browser.

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>

    <video preload="auto" id="vid" onContextMenu="return false;">
      <source type="video/mp4" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"/>
      <source type="video/webm" src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm"/>

    </video>

      <button id="playPauseButton" title="Play/Pause">

      </button>

      00:00
      /
      00:00

      <button id="loop" title="Loop">

      </button>
      <input type="range" step="1" min="0" max="100" value="0" id="seekSlider" title="Slider" style=""/>
      <button id="muteUnmute" title="Mute/Unmute">

      </button>
      <input type="range" step="1" min="0" max="100" value="100" id="volumeSlider" title="Volume level"/>
      <button id="exitFullScreen" style="display: none; font-size: 0.95em" title="Exit fullscreen">

      </button>
      <button id="toggleFullScreen" title="Enter fullscreen">

      </button>

Comment: Giant thanks. Your script works good but! I'll paste some images here. Hope you'll update your answer. PS: maybe will be useful: I'm using iMac 21.5 running OS X. Maybe you use Windows and everything works good. Images: [Chrome,Opera and Safari](http://i.imgur.com/asaDIaF.png), [Firefox](http://i.imgur.com/8n9ZKyV.png).
Comment: If you copy the entire last code snippet in my answer into an html document that you load locally, do you get the expected appearance? It works for me on Chrome and Firefox on Mac and Chrome and Firefox on Linux. The images you show would be consistent with what would happen if the following lines of code in `enterFullScreen` were somehow not working: ` vid.style.width = screen.width; vid.style.height = screen.height; mainVideo.style.width = screen.width; mainVideo.style.height = screen.height;` Or the document you're working with differs such that these style changes don't work.
Comment: The thing is that for some reason attribute `style` is not adding after switching to full screen mode and is not deleting after going to regular mode.
Comment: Can you share the full page you're working with so that we can troubleshoot? The fact that it's working with the demo I created but not with the code you're working with suggests that there's some difference that's preventing the `style` changes from being applied in your case. But it's difficult to know without being able to play with the broken code.
Comment: Can I just upload HTML file to popular file sharing service? Will that be a ok decision?
Comment: Here, [download HTML file](https://ufile.io/se9cc) . Because your snippet (in local file) doesn't add `style` attribute to video and it's container box, I tried to add some additional functions. But they don't work too.
Comment: Try adding units in your style settings. For instance,
`function videoFSstyling(video,videoBox){
  video.style.width = screen.width + 'px';
  video.style.height = screen.height + 'px';
  videoBox.style.width = screen.width + 'px';
  videoBox.style.height = screen.height + 'px';}`
And do the same for `videoNotFSstyling`. Also, add calls to `videoNotFSstyling` in `exitFullScreen`.
Comment: Man, you're AWESOME! THANKS!
Answer: I haven't played around with this before but I hope this could help you.
I had a look at the following post : https://css-tricks.com/custom-controls-in-html5-video-full-screen/
See the topic in the post :
    By setting the controls attribute of the video element to false, we are able to hide the controls but for some reason, when entering full-screen mode they reappear, despite being hidden in normal screen mode. (Why?)
So is firefox actually not the correct one or behaving like its supposed to?
A test that you can do is set the controls attribute of the video element to true and see what it does in all the browsers. vid.controls = true;
Hopes it gives you direction or something to try.
Comment: Controls false is working nice but I need to show my goddamn custom controls bar.
Comment: `vid.controls = false` hides the default control bar in Firefox. `vid.controls = true ` shows them. That's expected.
Comment: did you try css:   .custom-video-controls {
  z-index: 2147483647;
}  "Setting it to 2147483646 made the controls disappear in full-screen mode on Firefox and, sometimes (a bug?), in Chrome, so the z-index for the controls container should be >= 2147483647."
Comment: Yes, works for Chrome, Opera and Safari. But not for Firefox and Firefox-based browsers.
Comment: When viewing it from firefox what is  z-index supplied by the user agent style sheet?
Comment: And did you set the .custom-video-controls { z-index: 2147483647; } then larger than that value? Sorry for all the questions trying to troubleshoot.
Comment: Ummm... Yes, number that I'd typed in CSS code in snippet (you may not noticed that when you're switching to full screen mode, JavaScript adds a new CSS class called `.fullscreen` to element  `div.videoControls` and when you're exiting the full screen mode it removes this full screen class) is a bit larger than 2147483647. But still doesn't work. And for some reason I can't find property z-index for embedded Firefox controls bar in inspector. Maybe I'm stupid.
Comment: I took your code and tested it in firefox.. I see what you are saying I am getting the same results only in firefox. I will continue trying to help you.. I also now want to know why.


This is not copy-initializing, or is it?

Question: In the following code I am not allowed to declare an explicit ctor because the compiler says I am using it in a copy-initializing context (clang 3.3 and gcc 4.8).
I try to prove the compilers wrong by making the ctor non explicit and then declaring the copy constructors as deleted.
Are the compilers wrong or is there any other explanation?
#include <iostream>

template <typename T>
struct xyz
{
    constexpr xyz (xyz const &)    = delete;
    constexpr xyz (xyz &&)         = delete;
    xyz & operator = (xyz const &) = delete;
    xyz & operator = (xyz &&)      = delete;
    T i;
    /*explicit*/ constexpr xyz (T i): i(i) { }
};

template <typename T>
xyz<T> make_xyz (T && i)
{
    return {std::forward<T>(i)};
}

int main ()
{
    //auto && x = make_xyz(7);
    auto && x (make_xyz(7)); // compiler sees copy-initialization here too
    std::cout << x.i << std::endl;
}

Update An unrealistic but much simpler version
struct xyz {
    constexpr xyz (xyz const &) = delete;
    constexpr xyz (xyz &&) = delete;
    xyz & operator = (xyz const &) = delete;
    xyz & operator = (xyz &&) = delete;
    int i;
    explicit constexpr xyz (int i): i(i) { }
};

xyz make_xyz (int && i) {
    return {i};
}

int main () {
    xyz && x = make_xyz(7);
}

Answer: The = notation should not affect the complaint because reference binding doesn't behave differently whether expressed by direct- or copy-initialization. What's being initialized here is the return value object, which does not have its own name.
Unfortunately, GCC is right to complain, as does Clang. According to §6.6.3/2 [stmt.return],

A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list.

So, there is an invisible = sign there and you can't get around it.
Comment: @PatrickFromberg The term *copy-list-initialization* does not refer to the copy constructor but only equivalence to usage of the `=` sign. It is not "copy initialization" but specifically *copy-list-initialization* which is an indivisible, somewhat confusingly named, concept.
Comment: What a shame! First they tell us to be clean and use *explicit* where it makes sense. Then they hammer our fingers when we do 8-(.
Comment: @PatrickFromberg TBH I'm not sure where `explicit` makes sense, aside from the C++03 case, or where a multi-argument call could be ambiguous with a `std::initializer_list` overload. But for no arguments, the default constructor has specially higher precedence over `std::initializer_list` anyway. The nominal effect of `explicit` is to force you to name the class rather than allow it to be implicit, so in this case it did its job :P .
Comment: Regarding *"force you to name the class"*. There is actually no copy between the initializer-list and the named result type. I have added a simpler example to my question to make sure. After all the ultimate reason for *copy-initializer* and *explicit* incompatibility is to prevent obscure conversions. But I see no obscure conversion here. Unfortunately as you cite correctly, the standard says this is *copy initialization* by definition and you can not argue against definition.
Comment: "_equivalence to usage of = sign_" does not really reduce the confusion. But it is not your fault, I saw that description in the [C++ Bible](http://www.amazon.com/The-Programming-Language-4th-Edition/dp/0321563840) too. But I missed indeed the difference between _copy-initialization_ and _copy-list-initialization_. Good that you point out that.


Rule to fire only on first time publish of node

Question: We are using workflow moderation for some content types and sent out emails to the author once a node has been published.
Sometimes we have the case that an author changes a node after he has been published. When this revision gets published we want to send out a different email.
I have tried many different things but I haven't been able to find a way how to determine if this was the first time the node is published or a subsequent publish. Can someone please point me in the right direction how this can be achieved?
Thanks
Answer: This is how I would try doing it:

create a field for the content type named first_publish, boolean, hidden, default value 0
create a Rule that when that content type is published, as a condition if first_publish is 0, first_publish becomes 1, add email output to user
create a second Rule that when the content type is published, as a condition if first_publish is 1, send out a different email

This will use a data field as a variable that follows the node - the rules will trigger appropriately depending on the conditions of whether or not the variable is set, giving different outcomes.
Comment: Thanks Geoff, this is one of the things I tried, however I am unable to see this field in the rules - maybe I am missing something. The field is called field_publish and I try to access it node:field_publish via Data Comparison in the rule. I can't see any fields that I have created?
Comment: if you havent already, clear the cache. if you type in node and select the 'node:...' does anything come up in the list?
Comment: Ok thanks Geoff, worked it out. Basically I had the rule fire when saving all node types. When I restrict the node type only the one in question than all custom fields come up. Was hoping I can handle two or three content types in one go, well just need to write a different rule for each of them.
Answer: I found another way to do this if you don't want to add an extra field to the node.
In Rules add a condition of type "Execute custom PHP code".
Then in the PHP code field add the following:
<code>$times_published = db_query('select count(nid) from node_revision where status = 1 and nid = ' . $node->nid)->fetchField();
return ($times_published < 2);
</code>
This checks for the number of published revision entries for that node.


Virtual synthesizer or piano roll with controllable number of keys per octave?

Question: I am interested in performing and composing in non-twelve tone scales, such as 19-EDO (aka 19-TET) or 31-EDO (aka 31-TET).  While there are virtual synthesizers that allow you to play microtonal scales, all virtual synthesizers I have seen have 12 notes as part of their user interface.  It also seems like all MIDI sequencers have 12 notes in their interface.
For 19-EDO, I want to be able to play 19 keys per octave on a virtual piano as in the image below!

Is writing on a single piano roll with 19 notes per octave possible in any existing software?   Are there virtual synthesizers with a controllable number of keys per octave?
The hacky solution I have working right now uses Propellerhead Reason with the Microtune plugin and the Distributor via this Youtube Tutorial.  For 19-EDO (and any tuning with between 12 and 24 notes per octave) I  use two differently tuned virtual instruments to play all the notes in one octave!  For 19-EDO, I have one tuned for the 12 black keys and one instrument for the 7 white keys.
Answer: For sound sources you can find information here. In my opinion, u-he plugins are especially great.
As for visual feedback - you can change your pianoroll layout to different tunnings in Reaper.


do a select on two tables and the result allows access to fields of these two selected tables

Question: Im doing a search system and Im having some problems.
I need to search in two tables (news and pages), I already had sucess doing my search system for just one table, but for two tables its not easy to do.
I already use a select statment with two tables using UNION because I want to show number of search results, that is number of returned rows of my first sql statment.
But now I need to do a select statment that allows me to acess all fields of my news table and all fields of my pages table.
I need to acess in my news table this fields: id, title, content, link, date, nViews
I need to acess in my pages table this fields: id, title, content, link
Im trying to do this also with UNION, but in this case Im not having any row returning.
Do you see what I have wrong in my code?
<?php
//first I get my $search keyword
$search = $url[1];

$pdo = connecting();
//then I want to show number of returned rows for keyword searched
$readALL = $pdo->prepare("SELECT title,content FROM news WHERE title LIKE ? OR content LIKE ?
                          UNION SELECT title,content FROM pages WHERE title LIKE ? OR content like ?");
$readALL->bindValue(1,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(2,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(3,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(4,"%$search%", PDO::PARAM_STR);
$readALL->execute();
//I show number of returned rows
echo '
Your search keyword returned '.$readALL->rowCount().' results!
';
//If dont return any rows I show a error message
if($readALL->rowCount() <=0){
    echo 'Sorry but we didnt found any result for your keyword search.';
}
else{
    //If return rows I want to show, if it is a page result I want to show title and link that I have in my page table
    //if it is a news result I want to show title and link that I have in my news table and also date of news
    echo '
';
            $readALL2 = $pdo->prepare("SELECT * FROM news WHERE status = ? AND title LIKE ? OR content LIKE ? LIMIT 0,4
                                      UNION SELECT * FROM pages where title LIKE ? OR content LIKE ? LIMIT 0,4");
            $readALL2->bindValue(1, '1');
            $readALL2->bindValue(2, "%$search%", PDO::PARAM_STR);
            $readALL2->bindValue(3, "%$search%", PDO::PARAM_STR);
            $readALL2->bindValue(4, "%$search%", PDO::PARAM_STR);
            $readALL2->execute();

            while ($result = $readALL2->fetch(PDO::FETCH_ASSOC)){
                echo '
';
                    echo '';
                    echo ''.$result['title'].'';
                    //if it is a news result I also want to show data on my list
                    //echo ''.$result['data'].'';
                echo '
';
            }
    echo '
';
    //but how can I do my select statement to have access to my news table fields and my page table fields??
}
?>

This is my news table:

This is my pages table:

When I search on my form for keyword "doc" I get this:
Your are searching for keyword: "doc"
your search returned 2 results!
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => Documents [content] => Link 1, Link 2 [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1  [id] => 1 [link] => documents ) image of news Documents
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => Documents [content] => Link 1, Link 2 [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1  [id] => 1 [link] => documents ) image of news Documents
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => About [content] => we are a company... [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1  [id] => 2 [link] => about ) image of news About
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => About [content] => we are a company... [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1  [id] => 2 [link] => about ) image of news About
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => Contacts [content] => Email: firstname.lastname@example.com [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1  [id] => 3 [link] => contacts ) image of news Contacts
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => Contacts [content] => Email: firstname.lastname@example.com [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1  [id] => 3 [link] => contacts ) image of news Contacts
Comment: Thank you for your answer Gordon Linoff. I forgot to put here my last bindValue. But in my example I have correctly and its not working! I update my question with your correction.
Answer: To query 2 tables, and have the result set contain columns from both tables:
SELECT n.id, n.status, n.views,  p.id, p.title
FROM news n, pages p
WHERE n.status = ?
AND p.title = ?
...

To simplify my answer I have omitted most of your required columns, but you simply add more to the select statement. Of course, you can always use
SELECT n.*, p.*

To select all columns from both tables.
Update:
For your specific scenario, try:
SELECT n.*, p.*
FROM news n, pages p
WHERE n.title LIKE ?
  OR n.content LIKE ?
  OR p.title LIKE ?
  OR p.content LIKE ?

Comment: @OzzC I strongly suspect why this is happening, and have a likely fix. But to prevent giving only half an answer, please can you also update your answer to replace the code with the new code that you are using, thanks
Comment: Thanks for your answer. But its not working correctly. In my first sql statment where I get number of rows returned for searched keyword Im getting 3 rows returned with my keyword "doc". In my second sql like you said, Im getting 7 returned rows, and its wrong because I just have 3 rows with my condition. Im trying like this: SELECT * FROM news, pages
 WHERE news.status = ? AND news.title LIKE ? OR news.content LIKE ?
 AND pages.title LIKE ? OR pages.content LIKE ? ORDER BY date DESC LIMIT ?,?
Comment: Thanks for your answer Alex, but I have same result. Im getting 7results and was supposed to be only 3!
Comment: Bare in mind that if the same string is found in the title of news and the title of a page, it will return a row for each. If this changes things..
Comment: I know Alex, but I just have 3 records with title or content like '%doc%', and my select as you said return 7 results! But my first with union it is correct, it returns 3 rows.
Comment: Can you update your question by doing a print_r on the 7 rows that it returns
Comment: Thanks for your answer. I did a new question trying to explain and detail everything. If you have some time take a look! And really Thanks for all the help.


I broke my A string by accident

Question: I accidentally over-tuned my A string because of my blunder for not realizing my tuner was set to bass guitar instead of acoustic. I'm a beginner myself, and had this guitar for only 3 weeks now.
Now, I'm not concern about string replacement, I'm worried about my guitar's neck. Should I de-tune the rest of my strings so it wouldn't stress the neck,, since I am dealing with the A string?
Also, does breaking by over-tuning the A string affect anything?
Sorry but I'm panicking right now. That's the only things rushing back and forth in my head right now. My new strings won't arrive until next Tuesday/Wednesday.
Comment: Don't worry, it's a normal thing to break a string. Don't detune anything just replace the A string. The neck will be fine. BTW I love the 'accidentals' tag :)
Comment: @Jarek.D thank you so much! that's a relief. It's just the sound it made when it pops traumatized me :(
Comment: I strongly recommend buying a chromatic tuner instead of a "guitar tuner" .  Two combo tuner-metronome models I like:  https://smile.amazon.com/Korg-TM60BK-Tuner-Metronome-Black/dp/B078C5HCVP/ref=sr_1_1_sspa?crid=256LMKTYL126O&keywords=korg+tuner+metronome+combo&qid=1550842891&s=gateway&sprefix=korg%2Caps%2C142&sr=8-1-spons&psc=1   or   https://smile.amazon.com/Korg-TM40-Display-Digital-Metronome/dp/B000AAGM0M/ref=sr_1_16?crid=256LMKTYL126O&keywords=korg+tuner+metronome+combo&qid=1550842891&s=gateway&sprefix=korg%2Caps%2C142&sr=8-16
Comment: @CarlWitthoft omg didnt know this exist. THank YOu!
Comment: My female boss once asked me to tune her guitar, and I broke her G string.  She seemed to think that was very funny.
Answer: Tune the rest of the strings correctly and stop worrying!   And generally the string breaks before the guitar does.
Comment: Interesting use of 'exact' to mean 'very loosely' :-)
Comment: @LaurencePayne i mean, i watched a lot tutorials, most of them cut em down like sushi.
Comment: Thank you for the confirmation. Yeah, i'll try my best not make the same mistake.
Comment: To be exact - you'll break about 1000000 strings before the guitar breaks.
Comment: Thank you @CarlWitthoft I appreciate the assurance. Also i have 1 more question, when changing the strings, is it a **must** to cut the strings? I mean the string that i'm going to replace is only like few weeks old.
Comment: No.  Why would you think cutting is necessary?
Answer: Whilst it's not normal to break a string on a guitar, obviously it can happen. A few days with one less string won't hurt the guitar. Keep things as they are.
A more important factor - and it's not the first time it's cropped up - is how so many can't tune without resorting to a tuner. Yes, it's accurate (but not in your case!), and it's quiet (not when amateurs do it!), but there's absolutely nothing wrong with being able to tune it properly yourself. That way, you'll listen to the sounds, and making a mistake like you did will be a thing of the past.
A couple of ways - fifth fret on a lower string will be the same note as the next string open. 5th fret harmonic is the same note on one string  as 7th fret harmonic on the next higher. So once one string is at the reference point you need, the others can be tuned perfectly, assuming the guitar is intonated properly. It doesn't work between 2nd and 3rd strings, but the 7th fret harmonic on fat E is the same pitch as 2nd string open. Sounds complicated, but once you get used to it, it's as quick as with a tuner, honest!
Comment: No no hahaha, my guitar is acoustic's. My mistake was mistakenly setting my **tuner** to bass guitar instead of acoustic guitar mode. Somehow it recognized my A string as D string, that led me to over-tuned it. It was a silly mistake.
Comment: @anaiya - edited accordingly. Better?
Comment: @Tim Well, technically our strings are left-to right :-) .   In practice,  all us classical string players start by tuning the A-string because that's what the orchestra's tuning note is.  For cellos, we then tune from the thinnest (A) on down; for other instruments they have to tune "up " and "down" from A-string.
Comment: For beginners, my recommendation is:  1) tune the top string w/ tuner.  2) tune by ear per your instructions. 3) check each string with tuner to see how well you did.
Comment: @CarlWitthoft -- by top string do you mean bottom string?
Comment: @DavidBowling I mean the highest-pitched string.  Sorry, I keep forgetting that guitarists are upside-down :-)
Comment: @CarlWitthoft -- Oh, so you do mean the top string! I have always found it easier to tune from the bottom (lowest-pitched), working to the top (highest-pitched). No reason you couldn't go the other way, though.
Comment: @CarlWitthoft - always seems better going thick to thin (note - no confusion!!) not sure why - larger tension changes out of the way sooner. maybe.
Comment: @CarlWitthoft - are cellists the 'right way up? Isn't their top string the thinnest/highest?

I broke my A string by accident


rails find(:all) do... how does it work?

Question: I'm on rails 2.3.5
    puts params[:_search]
    users = User.find(:all) do
    if params[:_search] == "true"
      puts "TESTTTTTTTTTTTTTT"
      pseudo    =~ "%#{params[:pseudo]}%" if params[:pseudo].present?
      firstname =~ "%#{params[:firstname]}%" if params[:firstname].present?
      lastname  =~ "%#{params[:lastname]}%" if params[:lastname].present?
      email     =~ "%#{params[:email]}%" if params[:email].present?
      role      =~ "%#{params[:role]}%" if params[:role].present?
    end
    paginate :page => params[:page], :per_page => params[:rows]
    order_by "#{params[:sidx]} #{params[:sord]}"
  end

This code always shows that it is doing the following query in server logs:
select * from users

even when the :_search parm is true.
What is this code supposed to do? Append where conditions depending on the passed in search condition?
PS:  I'm using rails plugin for jqgrid
Answer: Well it's sort of interesting, but all the assignments to psuedo, lastname, email, role are being ignored.
The formatting was slightly off above, it should be
users = User.find(:all) do
  if params[:_search] == "true"
    puts "TESTTTTTTTTTTTTTT"
    pseudo    =~ "%#{params[:pseudo]}%" if params[:pseudo].present?
    firstname =~ "%#{params[:firstname]}%" if params[:firstname].present?
    lastname  =~ "%#{params[:lastname]}%" if params[:lastname].present?
    email     =~ "%#{params[:email]}%" if params[:email].present?
    role      =~ "%#{params[:role]}%" if params[:role].present?
    end
  paginate :page => params[:page], :per_page => params[:rows]
  order_by "#{params[:sidx]} #{params[:sord]}"
end

So, the users = User.find(:all) do is a builder, and taking all of the rest of the code to end as params.
It's pretty non-standard rails code, I think it's trying to build conditions if certain params are sent in. Instead, maybe try this condition builder
User.paginate(:page=>params[:page], :conditions=>build_conditions(params))

Comment: yes condition builder..that's what I was looking for. I'll read up on that. But what did you change in the code? What formatting was off?
Comment: @samwick -- in your example the "users =" and "if params" were left-aligned. My first time reading it I did not realize that the if was under the User.find


Meaning of Criteria.POWER_LOW for LocationManager

Question: The Criteria class is not documented in much detail.
Can someone please explain what POWER_HIGH and POWER_LOW change exactly?
Is it about battery drainage?
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
...
locationManager.requestSingleUpdate(criteria, locationListener, null);

Update:
I went through some of the source code. It turns out this parameter is ignored in my example because an accuracy is set as well.
createFromDeprecatedCriteria() in  LocationRequest.java:
    ...
    int quality;
    switch (criteria.getAccuracy()) {
        case Criteria.ACCURACY_COARSE:
            quality = ACCURACY_BLOCK;
            break;
        case Criteria.ACCURACY_FINE:
            quality = ACCURACY_FINE;
            break;
        default: {
            if (criteria.getPowerRequirement() == Criteria.POWER_HIGH) {
                quality = POWER_HIGH;
            } else {
                quality = POWER_LOW;
            }
        }
    }
    ...

Answer: There are a number of different LocationProviders (gps, network, passive etc). The Criteria class can be used by the LocationManger to automatically select the best provider based on your requirements.
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);

return locationManager.getBestProvider(criteria, true);

How the Criteria class is actually used can be seen here here.
Setting the power requirement to Criteria.POWER_LOW would probably just rule out the device using the GPS location provider (since it uses far more battery than the other passive types).


Reading NIC bandwidth usage instantly

Question: I want to create a script that runs on a linux server, that script should read bandwidth usage of NICs installed on other servers and then store them in memcached.
So I need a command that reads bandwidth usage of other servers on the same LAN, and the command should be as quick as possible.
Thanks,
Answer: There's no magical command that can just read parameters of other servers. Unless you setup and use SNMP. Note that you can't read a rate, you can only read a total so far of transmitted/received traffic.
mrtg may just be the route you want to take to get there though. It'll do the calculations for bandwidth rates and store them in an RRD. You can then 'instantly' query the RRDs.
Answer: I would create a shell script that uses SSH to run an ifconfig command remotely and parse the output to grab the RX bytes: and TX bytes: values (standard grep/sed/awk). I would pass these values to a PHP/Python/Perl/Ruby script (whatever your preference is) that stores them in to memcached. Alternatively you could write the entire script in that language. I would setup SSH to use public/private keys to avoid having to use passwords in your scripts.
The other option, as MikeyB, mentioned would be setup a more complete monitoring app on your servers which would record the network bandwidth usage directly.
Comment: It is taking too long to make an SSH authentication, we have many servers SSH will take lot of time.
Answer: Installing munin-node on your servers and configuring a munin server will get  you graphical output by interface per machine.  Resolution of the data is fixed at five minute intervals.  As noted, data for current bandwidth resolution is not available as such. It needs to be derived by sampling counters over time.  Utilization is derived from (actual delta) / (rate * period).
Munin will gather a bunch of other information which can be useful when tracing bottlenecks and other problems.  It can also be configured to alarm when values stray outside configured limits.
EDIT:  If you want the latest values, you could write a script that will extract the lastest sample from the rrd file(s).  This would be for the latest 5 minute sample.
Unfortunately, bandwidth usage is not tracked directly.  If you need relatively instantaneous readings you will need to query the counters, wait some period of time, and query the counters again.  You could then calculate the bandwidth usage.  You could use munin-node to query the counters.  The command to fetch the counters is fetch ip_eth0.  The config data contains the baseline data for full utilization.  The shorter the period you wait, the higher the error you will get in your sample.
Comment: Munin is already installed on the servers, but I dont need graphs nor alerts. I need to read BW usage as a simple number at any moment. Is it possible to create a script around munin to get what I need?
Comment: @wael34218: See my edit for results. Instantaneous bandwidth is not available. If it was the values would be 0% or 100%.  Think of  a point location on a road.  It will be either occupied or not.  You need to sample over time to determine utilization.
Answer: I use two programs in bash scripts just a few lines long to give me bandwidth averages for 30 secs in addition to the 5 min averages from MRTG (which is great for historical bandwidth usage rather than 'live' usage).
bwm-ng and ifstat are both easy to script around. The first let's you output to HTML and CSV too.
Answer: About 12 years ago I was working on a project for ISP and I wrote a script in Perl + SMNP that would read number of bytes transmitted/received from dozen of access servers every minute, store it in a database and then do all sort of statistical calculations on this data. Nowadays there is RRDtool package for this (MRTG is a predecessor). But the general idea remains - you can read number of received/transmitted bytes pretty much from any device through SNMP. If you are reading this from a NIC there may be other options available but principle I think is the same.
Comment: Sampling rate of 1 minute is perfect thats what I want. How often does MRTG and RRDtool sample? can they provide accurate results for the latest 1 minute?
Comment: Essentially you define interval yourself - you just run RRDtool on your own schedule and every time it runs it collects current stats and adds it to the database.

Reading NIC bandwidth usage instantly


Class not found in drush command definition

Question: In the drush command definition hook for the Node Revision Delete project I have the following code:
use Drupal\node_revision_delete\Utility\Time;

...

function node_revision_delete_drush_command() {
  $values = array_keys(Time::convertWordToTime());

The namespace exists and is in the correct place but once I use drush cr I got this error:
Error: Uncaught Error: Class 'Drupal\node_revision_delete\Utility\Time' not found in /Users/adriancid/Sites/drupal84-test/modules/drupal.org/node_revision_delete/node_revision_delete.drush.inc:34

It's weird because I call the same function in the line 179 for the drush nrd-st command and is working fine:
Time::convertWordToTime();

Trying to understand what happens I tried to use an Utility function from the Core in the drush definition command hook and works fine without problem, but with my function call it doesn't works.
Any idea about class not found problem?
Comment: This is in hook_drush_command(), my guess is that the drupal bootstrap at that point isn't done and you can't rely on that to exist as drush will just load those files and execute the function. So this is simply not possible then.
Comment: @Berdir that's what I thought too but I don't know why it works for core utility functions like Random::name()
Comment: Because drush apparently loads that, probably because it needs functions from there itself. Those classes are not in a module, so drush doesn't need a list of installed modules and their location, core/lib/.. is static, always at the same place and therefore easy to register without having to bootstrap Drupal
Comment: @Berdir thanks, I think that this is the problem as I tried now to use a service inside the `hook_drush_command()` and I'm getting:  `\Drupal::$container is not initialized yet`
Answer: As @Berdir says it seems Drupal is not fully bootstrapped when the hook_drush_command() is called as I tried to use a service defined in a custom module and I get the following error:
\Drupal::$container is not initialized yet.

So the solution for the moment is hardcode the values that should be returned by the function.


Run callback after Views exposed filter AJAX

Question: I feel like I'm doing something really wrong here. I have a View block which has an exposed filter. Since it is in a block I have to use Ajax. I'm trying to run some JS on the views result but can't get anything to happen when the ajax call completes.
To try and keep this as simple as possible I have created a test.js file with only the following code:
<code>(function ($) {
  $(document).ajaxComplete(function (e, xhr, settings) {
    console.log('test');
  });
})(jQuery);
</code>
I add this with my theme's template.php file but when I filter my view and the results update with ajax, this code does not seem to run. I can't work out why not.
EDIT: I managed to get this to work by moving the code inside my_view.tpl.php but I'd be keen to know why it doesn't work in an external file.
Answer: JS events need to be bound when the document is ready. Drupal handles this for you if you use behaviors:
<code>(function ($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      $(document).once('mymodule-ajax').ajaxComplete(function (e, xhr, settings) {
      // ...
      });
    }
  }
})(jQuery);
</code>
Answer: I was trying to execute javascript after Ajax Views load content. Using Drupal 8.5 and Better Exposed Filter contrib module I did :
<code>(function($, Drupal, drupalSettings) {

  Drupal.behaviors.myModuleScript = {

    attach: function(context, settings) {
      // Attach action to Drupal Ajax Views event
      $(document).once('weberAjaxViews').ajaxSuccess(function (event, data) {
        if (drupalSettings && drupalSettings.views && drupalSettings.views.ajaxViews) {

          var ajaxViews = drupalSettings.views.ajaxViews;
          Object.keys(ajaxViews || {}).forEach(function (i) {
            if (ajaxViews[i]['view_name'] == 'your_view_name' &&  ajaxViews[i]['view_display_id'] == 'your_view_display_name') {
              // Do some JS here
            }
          });

        }
      });
    }

  };

})(jQuery, Drupal, drupalSettings);
</code>
I have been using ajaxSuccess instead of ajaxComplete so my code does not get executed when the Ajax call throws an Error.
Comment: Thanks, this has been really helpful. I was able to add a class on "AjaxStart" and then remove the class on "AjaxSuccess".
Answer: Have a look at my answer on another question that uses the betterExposedFilter module.


Notation for ECDF

Question: I'm reviewing statistical functionals and U-statistics, trying to make notes, and I am tripping on notation. From my understanding, $X$ is used to denote a random variable and $x$ is used to denote an observation or realization of $X$.
Essentially, imagine n i.i.d. random variables such that $X_1, ..., X_n \stackrel{i.i.d}{\sim} F$. Now, I'm seeing the ECDF defined as
$$\hat{F}_{n}(x) = \frac{1}{n} \sum_{i=1}^{n} \mathbb{I}(X_i \leq x) $$
The ECDF is determined using an observed sample so why isn't this denoted instead as,
$${F}_{n}(x) = \frac{1}{n} \sum_{i=1}^{n} \mathbb{I}(X_i \leq x) $$
and then, given realizations of $X_1, ..., X_n$,
$$\hat{F}_{n}(x) = \frac{1}{n} \sum_{i=1}^{n} \mathbb{I}(x_i \leq x) $$
What am I missing here?
Comment: Please visit https://stats.stackexchange.com/help/merging-accounts to merge your accounts.
Comment: The ECDF $\hat F$ of data is related to the population CDF $F$ in somewhat the same way as the histogram of the data is related to the population density function $f(x).$ // In both cases, for sufficiently large $n$ the former (ECDF, histogram) should estimate the latter (population CDF or PDF). // In some cases a kernel density estimator (KDE) is a better estimate of the PDF than is the histogram.
Answer: The "hat" denotes estimation generally --- it does not distinguish the estimator from the estimate
In statistical notation, when we have an estimator/estimate of an unknown object, it is usual to denote the estimator/estimate with the same symbol as the object being estimated, but with a "hat" over the top to denote estimation.  Moreover, if we want to refer to an estimator/estimate using a specific number of data points, we usually put the number of data points as a subscript.  Thus, if we have an unknown distribution $F$ then the notation $\hat{F}_n$ is a standard way to refer to an estimator/estimate of that function, using $n$ data points.
In your question, you appear to be proposing to use the "hat" to distinguish the estimator from the estimate, which is not what this notational object is usually used for.  In most statistical discussions, this distinction is made using the standard convention for using upper or lower-case letters to distinguish random variables from constants.  Unfortunately, in the present case, this conflicts with the convention of using an upper-case letter to denote a CDF, and this latter convention prevails over the former.  It is possible to distinguish the estimator from the estimate even in this case, and I will show you below how this would usually be done.  However, the "hat" is not used to make this distinction.

Distinguishing between the estimator and estimate in this problem: This is a situation where your ECDF function is implicitly dependent on other objects not specified explicitly as arguments, and this is what is leading to confusion.  Let's look again at the stated definition of the ECDF:
$$\hat{F}_{n}(x) \equiv \frac{1}{n} \sum_{i=1}^{n} \mathbb{I}(X_i \leq x)
\quad \quad \quad \text{for all } x \in \mathbb{R}.$$
A cumulative distribution function gives you a probability value for each real input, so the function itself is an element of the set $[0,1]^\mathbb{R}$.  However, you can see here that in addition to being dependent on the argument $x$, the output of this function also depends on the random sample.  Technically, the output  of this function is dependent on three things: the real argument $x \in \mathbb{R}$, the random vector $\mathbf{X}_n = (X_1,...,X_n)$ (which is a mapping $\mathbf{X}_n: \Omega \rightarrow \mathbb{R}^n$), and the realised value $\omega \in \Omega$ in the sample space.  In the above definition we are choosing not to include explicit dependence on the latter two arguments, but let's rewrite this with notation that refers to all arguments.  Taking the random vector $\mathbf{X}_n$ as a fixed mapping, we get the function:
$$\hat{F}_{n}(x, \omega| \mathbf{X}_n) \equiv \frac{1}{n} \sum_{i=1}^{n} \mathbb{I}(X_i(\omega) \leq x)
\quad \quad \quad \text{for all } x \in \mathbb{R} \text{ and } \omega \in \Omega.$$
With this new notation we are including all arguments explicitly, and we now see that the ECDF depends on the random vector that is our sample, and the outcome in the sample space.  You can now distinguish between the estimator (which is a random variable) and the estimate (which is the output you get with your observed data)
$$\begin{matrix}
\text{Estimator} & & & \hat{F}_{n}(\ \cdot , \cdot \ | \mathbf{X}_n): \Omega \rightarrow [0,1]^\mathbb{R}, \\[6pt]
\text{Estimate} & & & \hat{F}_{n}(\ \cdot , \omega | \mathbf{X}_n) \in [0,1]^\mathbb{R}. \quad \ \ \\[6pt]
\end{matrix}$$
Here we see that the estimator is a random CDF, whereas the estimate is a fixed CDF.  As you can see, all of this is a bit of a mouthful, and the notation gets a bit technical, which is why statistical exposition of estimators tends to gloss over this part, and sometimes uses the same notation for estimators and their corresponding estimates.  While the above gives a fully technically correct way of expressing things, a simpler shorthand is just to show both objects as a function of the data, and distinguish them using upper and lower-case for the input data, like this:
$$\begin{matrix}
\text{Estimator (at } x \text{)} & & & \hat{F}_{n}(x |\mathbf{X}_n), \ \\[6pt]
\text{Estimate (at } x \text{)} & & & \hat{F}_{n}(x |\mathbf{x}_n).\ \\[6pt]
\end{matrix}$$

Sometimes capitalisation helps, and sometimes it doesn't: Of course, when conventions for capitalisation and non-capitalisation permit (i.e., when they are not in conflict), we can draw a notational distinction between these objects using the standard convention of writing the random version (estimator) in upper-case and the fixed version (estimate) in lower-case.  In many contexts this is what is done --- e.g., when using the sample mean as an estimator of the true mean we would commonly use $\bar{X}_n$ and $\bar{x}_n$ as the respective notations for the estimator and the estimate.
However, in the present case, use of upper/lower case conflicts with the corresponding convention for capitalisation that distinguishes a CDF from a density function --- i.e., the letter $F$ refers here to the underlying CDF of the data, and $f$ would usually refer to its density/mass function.  Thus, if we were to use $\hat{f}_n$ here to denote the estimated CDF (i.e., the estimate), that notation would be confusing to the reader, because it would look like we were talking about an estimator for the density $f$.  As you can see, this is a case where two contradictory conventions for capitalisation occurs, and so we choose for the CDF/density distinction to prevail over the random variable/fixed value distinction.
Nevertheless, as you can see from the above technical argument, even in cases where conventions for capitalisation make it problematic to use upper-case and lower-case letters to distinguish the estimator from the estimate, it is possible to distinguish the two by making the implicit arguments explicit.  This allows us to make a notational distinction between the estimator and estimate if we wish to do so.
Comment: Thank you for the answer Ben! That helps clear things up. I think one aspect of my confusion was coming from the fact that I have seen $\bar{X}_{n} = \frac{X_1 + ... + X_n}{n}$ defined in terms of random variables and then its corresponding sample estimate denoted $\bar{x} = \frac{x_1 + ... + x_n}{n}$. Same with $S^{2}_{n}$ and $s^2$. Are these just situations where those explicit counterparts have been defined?
Comment: @eeeeejjjsss: I have expanded on my answer to address that issue.  Glad this was helpful.
Answer: Comment continued with some graphics.
Suppose you have a sample of size $n = 200$ from the distribution $\mathsf{Gamma}(\mathrm{shape} = 5, \mathrm{rate} = 1/10,$ so that the distribution mean $\mu = 50.$
Here are such data simulated in R:
set.seed(1234)
x = rgamma(200, 5, 0.1)
summary(x)
  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 11.00   35.04   47.99   50.67   61.02  145.84

Here is a histogram of the data (blue bars) with the density of
$\mathsf{Gamma}(5, 0.1)$ (black curve), and the default KDE
from R (red dotted curve).
hist(prob=T, br=15, xlim=c(0,150), xaxs="i", col="skyblue2",
      main = "n=200: GAMMA(5, .1)")
rug(x)  # tick marks along horizontal axis
curve(dgamma(x, 5, .1), add=T, lwd=2)
lines(density(x), type="l", col="red", lwd=2, lty="dotted")

Here is an ECDF of the data x (blue), along with the CDF of $\mathsf{Gamma}(5, 0.1).$
plot(ecdf(x), col="skyblue",
     main="ECDF of Sample (blue) and CDF of GAMMA(5, .1)")
 curve(pgamma(x, 5, .1), add=T, lwd=2)

Notation for ECDF


How to calculate the throughput in TCP?

Question: I am trying to calculate the throughput for TCP/MPTCP by using the parameter tp->packets_out and also tp->snd_una but they are not accurate.
How does wireshark do it?
Or does anyone know any solution?
Thanks in advance.
Answer: I am the author of https://github.com/teto/mptcpanalyzer which tries to provide some statistics for MPTCP connections. Current release has many bugs but the upcoming one is much better. Feel free to open issues there if you have any problem.

How to calculate the throughput in TCP?