Atribuição de operação em C

Question: Não entendo por que ao fazer esta operação, mesmo já tendo declarado o r como float, se não colocar o operador de cast se atribui um int.
#include <stdio.h>

void main() {
    float r;
    r = (float) 8 * 2 / 3;
    printf("O resultado eh: %.2f", r); // Sem o cast r= 5.00 que é errado.
}

Comment: Porque você está dividindo por `3` e não por `3.0`... Faça `r = 8*2/3.0;`.
Answer: Não precisa do cast, mas precisa usar um número que indique que é um float de alguma forma. Tanto o 8, quanto o 2 quanto o 3 são números inteiros, então quando ele fizer os cálculos eles gerarão números inteiros, não há um cast implícito só porque teve uma divisão que potencialmente poderia dar uma parte decimal. Se quer a parte decimal então diga isto.
#include <stdio.h>

void main() {
    printf("O resultado eh: %.2f", 8.0 * 2.0 / 3.0);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Precisa colocar a parte decimal em todos? Neste caso não precisa, mas tem caso que pode precisar por causa da precedência e associatividade. Se está trabalhando com float use literais que já sejam float.
Comment: Entendi, devo deixar explicito no calculo em ao menos um número. Obrigado!
Comment: No número mais importante, não é que basta em um, pode ser em um, depende do local. Em vez do literal poderia usar o *cast*, mas é feio.

Atribuição de operação em C


Difference between robust regression and weighted regression

Question: In stata, robust regression (rreg) uses weights proportional to the size of the residuals. Is this conceptually the same as weighted OLS (weight by 1/variance)? And both can be applied, for example, in scenarios with heteroskedasticity?
Answer: They are not the same, because in weighted OLS, weights are given apriori, they are not a function of size of residuals, as in some types of robust regression.  However, there is a connecteion, as robust regression sometimes can be calculated via IRLS, iteratively reweighted least squares.  For the last, see can you give a simple intuitive explanation of IRLS method to find the MLE of a GLM?
Comment: +1 which would you choose for linear regression with heteroskedasticity?


How do I make the space before the text disappear without making the space between the texts disappear on every sheet?

Question: How do I make the space before the text disappear without making the space between the texts disappear  on every sheet ? I've tried to come up with the following code.
    Public Sub Test()
    Dim rng As Excel.Range
    For Each rng In ActiveSheet.UsedRange 'or change to something like ActiveSheet.Range("A1:A100") for a specific range
        rng.Value2 = Trim(rng.Value2)
    Next
End Sub

But it's really slow and will only apply to the first sheet out of my 3 sheets. Basically I want to change a cell like "       Total Revenue" into "Total Revenue" and would like to apply my code on all 3 sheets I, B and C. Thank you guys in advance !
Comment: Those extra spaces heavily improve the readability of your page, why do you want to remove them?
Answer: Trim Ranges
Basic

Note that this will convert any formulas to values.

Sub TrimAllWorksheetsBasic()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    ' or:
    'Set wb = ActiveSheet.Parent ' workbook of the active sheet

    Dim ws As Worksheet

    For Each ws In wb.Worksheets
        ws.UsedRange.Value = Application.Trim(ws.UsedRange.Value)
    Next ws

End Sub

Only Cells With Values
Sub TrimAllWorksheets()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    ' or:
    'Set wb = ActiveSheet.Parent ' workbook of the active sheet

    Dim ws As Worksheet, rg As Range, arg As Range

    For Each ws In wb.Worksheets
        On Error Resume Next
            Set rg = ws.UsedRange.SpecialCells(xlCellTypeConstants)
        On Error Goto 0
        If Not rg Is Nothing Then
            For Each arg In rg.Areas
                arg.Value = Application.Trim(arg.Value)
            Next arg
            Set rg = Nothing ' reset for the next iteration
        End If
    Next ws

End Sub

Specific Worksheets
Sub TrimSpecificWorksheets()

    Dim TrimSheets(): TrimSheets = Array("I", "B", "C")

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    ' or:
    'Set wb = ActiveSheet.Parent ' workbook of the active sheet

    Dim ws As Worksheet, rg As Range, arg As Range

    For Each ws In wb.Worksheets(TrimSheets)
        On Error Resume Next
            Set rg = ws.UsedRange.SpecialCells(xlCellTypeConstants)
        On Error Goto 0
        If Not rg Is Nothing Then
            For Each arg In rg.Areas
                arg.Value = Application.Trim(arg.Value)
            Next arg
            Set rg = Nothing ' reset for the next iteration
        End If
    Next ws

End Sub

Comment: Thank you ! I also have other worksheets in the actual real file. Is there anyway I could only specifically target worksheet I , B and C ?
Comment: I have corrected the code: `Set rg = Nothing` is necessary while `arg.Value` instead of `arg` is optional, a matter of being explicit when the expression `arg.Value = Application.Trim(arg.Value)` translates to something like: 1.) return the values of the range in an array (`arg.Value` on the right side of the expression), 2.) trim all values in the array (`Application.Trim(arg.Value)`) and 3.) write the trimmed values of the array back to the range.


react-i18next use withTranslation got type and ref error, I don't how to fix

Question: after use withTranslation, react-native ts got errors, ref error and type error, I don't know how to fix

    "i18next": "^23.5.0",
    "react": "18.2.0",
    "react-i18next": "^13.2.2",
    "react-native": "0.72.4",

Answer: find a way to solve the two errors while use ts and ref and class component with react-i18next withTranslation
datePickerRef: React.RefObject<DatePickerRef> = React.createRef<DatePickerRef>();

//region withTranslation with ts and ref
//https://github.com/i18next/react-i18next/blob/fdab4e8953b2cdaf29d21d716d33ebfd0eca99f2/src/withTranslation.js#L5
//https://stackoverflow.com/questions/77677338/react-i18next-use-withtranslation-got-type-and-ref-error-i-dont-how-to-fix
//https://github.com/i18next/react-i18next/issues/1122#issuecomment-1859634674
export interface DatePickerRef extends DatePicker {}
export default withTranslation(undefined, { withRef: true })(DatePicker) as React.ForwardRefExoticComponent<
  Omit<DatePickerProps, keyof WithTranslation> & RefAttributes<DatePickerRef>
>;
//endregion

Answer: I think the most easiest way to solve this error would be to follow your IDE's hint and make use of typeof
datePicker: React.RefObject<typeof DatePicker> = React.createRef<typeof DatePicker>()

What you are trying to do is following
const MyObject = {
 name: "Joe Doe",
 age: "99"
}

//Wrong
React.RefObject<MyObject> = React.createRef<MyObject>()

//Correct
React.RefObject<typeof MyObject> = React.createRef<typeof MyObject>()

Comment: yes, I did tried, but also have the second error from the page, property 'ref' does not exit, thanks for the answer, I will post a new answer soon.


Random "No application encryption key has been specified"

Question: I have a website built on laravel 6.
Every things work fine. But there is a strange issue:
When browsing the website, i randomly get the error: No application encryption key has been specified. The error goes a way when i refresh the browser.
Lets say of 15 to 20 request, 1 or 2 requests fails with that error.
I am using laravel 6 years ago. I am quite aware of generating keys and clear cache so the problem is not here. More over if the problem is with configuration, then the website well not work at all. But in my case it works and i get that error occasionally.
I am using laravel valet on mac (imac 2020) and wamp server on windows 10 (hp core i7 hq). With php 7.3 and xdebug extension activated. The same problem on both machines.
I dont think its related to machine performance because are good enough.
Any one facing this issue?
Answer: There is possibly a mix-up with the session and the app's encryption key most likely.
Try running php artisan key:generate to create a new app key.

Random “No application encryption key has been specified”


scanf problem when adding multiple strings

Question: So I have a code, which gets in input arbitrary number of lines of arbitrary length. Each line generally contains one or more words separated by whitespace. I have to output that strings.

So this my code. I am newbie in C, and don't be so rude for my
dumb-code ;)

#include <stdio.h>
#include <stdlib.h>

int main () {
    int i = 1;
    char **list = malloc(1000 * sizeof(char*));
    while(!feof(stdin)){
        list[i] = malloc(1000 * sizeof(char));
        printf("Enter string with num %d: ", i);
        scanf("%99[^\n]", list[i]);
        i++;
    }
    printf("\n");
    for (int j = 1; j < i; j++)
        printf("Your strings by num %d: %s\n", j, list[j]);

    return 0;
}

But I have problem with scanf, and I can't contiune my inputting after whitespace.
I think my problem is

scanf("%99[^\n]", list[i]);

In addition to that, I can't use the gets(), getchar() families, and also specifications %c and %m.
Comment: You should read through [Why is "while ( !feof (file) )" always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)
Comment: Does this answer your question? [How to take Line input in C language with whitespace](https://stackoverflow.com/questions/68792715/how-to-take-line-input-in-c-language-with-whitespace)
Comment: I can't use gets, because it is task
Comment: Always check the value returned by `scanf`, which, BTW may be `EOF`.
Comment: @CyberDemon You should decide if your line length is max. 99, max. 999, or truly arbitrary.  Given your current format string of `%99[^\n]`, you could get away with `list[i] = malloc(100)`.
Comment: Better `fgets (list[i], 1000, stdin)` followed by `list[i][strcspn(list[i], "\n")] = 0;` to trim the `'\n'` from the end... and you **NEVER** ever want to use `gets()` -- which is so prone to exploit by buffer overrun it has been removed from the C-library in C11.
Comment: Year, I can't use gets(), because it is restriction from my teacher. And sorry for being rude)
Comment: @CyberDemon - if this lesson is about `scanf()` that is fine -- it is one of the, if not the, most misused input function by new C programmers. It has a number of pitfalls that unless you know the manual (man page) cold, are likely to bite you. Spend an hour with [man 3 scanf](https://man7.org/linux/man-pages/man3/scanf.3.html) and it will save you 100 hours of grief. That said, if you are not required to use `scanf()` then generally all user-input should be taken with `fgets()` using a buffer of sufficient size (don't skimp 1024 is fine). Trim the `'\n'` with `buffer[strcspn(buffer,"\n")]=0;`
Comment: To get the length and trim the `'\n'` in one-shot, `size_t len; ... buffer[(len = strcspn(buffer, "\n"))] = 0;`. Put that in your hip-pocket for later. Also in  your case here. Since user-input takes a second or two, you can read the input into a fixed buffer, and only allocate a pointer and storage for the input after validating the input is good. You simply call `realloc()` to allocate one more pointer and then allocate for length (+1) characters needed. This avoid pre-allocating all 1000 pointers up front. Reading all input at once from a file, then pre-allocation makes sense.
Answer: with %99[^\n] you scan till you encounter \n. So first line is read without hitch. But as the \n has not been scanned, it remains in the unread part of stdin. The next time you scan, you encounter '\n' again and you have actually scanned an empty string. So use %99[^\n]%*c the %*c part means you ignore a character.
Comment: In the question, OP stated that they are not allowed to use the `%c` format specifier. This is probably a constraint on their homework assignment. However, I am still upvoting the answer, because the constraints do not make sense, unless OP is expected to use `%s` instead of `%[set]`.
Comment: Consider proposing `" %999[^n]"` (note the leading space) instead, as mentioned in this [comment](https://stackoverflow.com/questions/68792715/how-to-take-line-input-in-c-language-with-whitespace#comment121576084_68792715) to the proposed dupe.
Comment: Technically the `'*'` is the "*assignment-suppression character*" which when paired with a *conversion specifier* causes `scanf()` to read and discard the characters matching the specifier.
Answer: You have done one of the No. 1 things that is guaranteed to cause problems with your logic. You are mixing i as 1-based (for counting), but should be 0-based for indexing. In C all arrays and storage are Zero-based. The first element is element 0. When you start mixing a 1-based counter with 0-based indexing, you complicate your logic and must account for the shift in each instance the variable is used as a counter or as an index -- try and avoid this at all costs.
Instead of initializing int i = 1; initialize as int i = 0; you are using it as an index. When you need to output as a counter simply use i + 1. In your case this means you are allocating for 1000 pointers but you never use the first one. (you can do that -- but it is just sloppy) Always index from 0 and adjust the output numbering as needed by adding to the index. (also rather than just using i to track the number of pointers allocated, just a more descriptive variable name, e.g. n_pointers or nptrs)
As mentioned in the comment, since you are taking user-input from the keyboard, there is no benefit in pre-allocating for 1000 pointers at the beginning -- there is no program efficiency gained. In the time it takes a user to type "cat" you can have reallocated a new pointer and allocated for storage 1000 times over without introducing any delay.
A better approach here is to simple declare a fixed buffer (character array) to use for all input and then after you validate that good input was received, just realloc() a new pointer and allocate storage for the input. That way you do not over-allocate pointers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXC 1000       /* if you need a constant, #define one (or more) */

int main () {

    size_t nptrs = 0;       /* counter for no. pointers allocated */
    char **list = NULL,     /* list and fixed buffer for read */
         buf[MAXC];
    ...

Since you are apparently stuck using scanf(), as mentioned in the comments, spend an hour with the man page -- it will save you 100 hours of grief later. scanf() is full of pitfalls for the new C programmer, like knowing which conversion specifiers discard leading whitespace and which don't and ... 50 more pitfalls just like it.
Here you want to read whitespace separated words with scanf() so you are going to use the %[...] conversion specifier to read all characters not-including the '\n' character. (lesson, %[...], %c and %n are the conversions that do NOT discard leading whitespace). So in your case, to discard leading whitespace, you will need to include a space before " %[^\n]".
You will also need to know the number of characters consumed so you can check against your 999 field-width limit to know whether the line you just tried to read is too long to fit. You can use the pseudo-conversion %n to get the number of characters consumed up to the point where it appears in your format string.
Since your read with not include the '\n' character at the end, if your buffer is filled 999 characters (plus the nul-terminating character), additional characters in that line remain unread which you will need to read and discard so your next read will start with the next line.
(you would normally do that looping with getchar() until the '\n' is found, but since you can't use it, you will use scanf() again but WITHOUT discarding leading whitespace)
Whenever you are looping collecting user-input (especially when specific input like an integer value is required), you will use a continual loop around your input routine to require the user to provide the needed type of input as well as any input within a specific value range. When you receive and validate the needed input was provided, you simply break your read-loop. Otherwise, you simply loop again until you get what you need. The key to validating any user-input is to check the return (and the value within limits if needed).
Putting the approach to reading into a fixed buffer, validating, and discarding characters if the line is too long, you could do:
    ...
    puts ("input\n");
    while (1) { /* loop continually until manual EOF */
        int nchar, rtn;     /* no. of chars consumed, scanf return */

        printf ("Enter string with num %zu: ", nptrs + 1);  /* prompt */
        rtn = scanf (" %999[^\n]%n", buf, &nchar);          /* save return */
        if (rtn == EOF) {                                   /* check EOF */
            puts ("EOF\n\noutput\n");
            break;
        }
        if (nchar == 999) { /* check line-too-long */
            fputs ("errro: line exceeds MAXC chars.\n", stderr);
            while (nchar == 999) {  /* loop discarding remainder of line */
                if (scanf ("%999[^\n]%n", buf, &nchar) != 1) {
                    goto getnextline;   /* skip over allocation/storage */
                }
            }
        }
        ...

Now reallocating an additional pointer and storage for each input and copying from the fixed buffer to allocated storage, you could do:
        ...
        /* always realloc using temp pointer or risk memory leak */
        void *tmp = realloc (list, (nptrs + 1) * sizeof *list);
        if (!tmp) {
            perror ("realloc-list");
            break;
        }
        list = tmp;         /* assign realloc'ed block of ptrs to list */

        list[nptrs] = malloc (nchar + 1);           /* allocate for string */
        memcpy (list[nptrs], buf, nchar + 1);       /* don's scan for \n */

        nptrs += 1;         /* increment pointer count */
        getnextline:;
    }
    ...

All that remains is outputting your lines (and shifting your index to counter to match your input prompt). Since you are ending your program, don't forget to free() the storage for each line and then free the pointers at the end. Yes, that will happen when the program exits, but you will not always be allocating in main() and failure to free the memory you allocate in a function will create a memory leak in your program. So build good habits early. Always track your memory allocations and free() the memory when it is no longer needed, e.g.
    ...
    for (size_t j = 0; j < nptrs; j++) {
        printf("Your strings by num %zu: %s\n", j + 1, list[j]);
        free (list[j]);     /* free storage for string */
    }
    free (list);            /* don't forget to free pointers */
}

That's it. That will take all of the input needed, eliminate any limit on the number of lines that can be entered (up to the limit of your virtual memory), output all stored lines and free all memory allocated before exiting.
Example Use/Output*
$  ./bin/scanflines
input

Enter string with num 1: string with   1
Enter string with num 2:       string with   2
Enter string with num 3:      string with   3
Enter string with num 4:     string with   4
Enter string with num 5:    string with   5
Enter string with num 6:   string with   6
Enter string with num 7:  string with   7
Enter string with num 8: string with   8
Enter string with num 9: EOF

output

Your strings by num 1: string with   1
Your strings by num 2: string with   2
Your strings by num 3: string with   3
Your strings by num 4: string with   4
Your strings by num 5: string with   5
Your strings by num 6: string with   6
Your strings by num 7: string with   7
Your strings by num 8: string with   8

Memory Use/Error Check
In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.
It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.
For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.
$ valgrind ./bin/scanflines
==7141== Memcheck, a memory error detector
==7141== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7141== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==7141== Command: ./bin/scanflines
==7141==
input

Enter string with num 1: string with   1
Enter string with num 2:       string with   2
Enter string with num 3:      string with   3
Enter string with num 4:     string with   4
Enter string with num 5:    string with   5
Enter string with num 6:   string with   6
Enter string with num 7:  string with   7
Enter string with num 8: string with   8
Enter string with num 9: EOF

output

Your strings by num 1: string with   1
Your strings by num 2: string with   2
Your strings by num 3: string with   3
Your strings by num 4: string with   4
Your strings by num 5: string with   5
Your strings by num 6: string with   6
Your strings by num 7: string with   7
Your strings by num 8: string with   8
==7141==
==7141== HEAP SUMMARY:
==7141==     in use at exit: 0 bytes in 0 blocks
==7141==   total heap usage: 18 allocs, 18 frees, 2,492 bytes allocated
==7141==
==7141== All heap blocks were freed -- no leaks are possible
==7141==
==7141== For counts of detected and suppressed errors, rerun with: -v
==7141== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors.
There is a lot here to digest, so take your time and make sure you understand why each line was written the way it was and what it is doing. If you have questions, drop a comment below.
In closing, know that in this case fgets() into buffer would have been a far better and recommended approach over using scanf(). But since it appears that is off limits, it can be done with scanf(), and is a good learning exercise -- but absent the learning exercise, fgets() is the much better choice.
Complete Program
For convenience:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXC 1000       /* if you need a constant, #define one (or more) */

int main () {

    size_t nptrs = 0;       /* counter for no. pointers allocated */
    char **list = NULL,     /* list and fixed buffer for read */
         buf[MAXC];

    puts ("input\n");
    while (1) { /* loop continually until manual EOF */
        int nchar, rtn;     /* no. of chars consumed, scanf return */

        printf ("Enter string with num %zu: ", nptrs + 1);  /* prompt */
        rtn = scanf (" %999[^\n]%n", buf, &nchar);          /* save return */
        if (rtn == EOF) {                                   /* check EOF */
            puts ("EOF\n\noutput\n");
            break;
        }
        if (nchar == 999) { /* check line-too-long */
            fputs ("errro: line exceeds MAXC chars.\n", stderr);
            while (nchar == 999) {  /* loop discarding remainder of line */
                if (scanf ("%999[^\n]%n", buf, &nchar) != 1) {
                    goto getnextline;   /* skip over allocation/storage */
                }
            }
        }
        /* always realloc using temp pointer or risk memory leak */
        void *tmp = realloc (list, (nptrs + 1) * sizeof *list);
        if (!tmp) {
            perror ("realloc-list");
            break;
        }
        list = tmp;         /* assign realloc'ed block of ptrs to list */

        list[nptrs] = malloc (nchar + 1);           /* allocate for string */
        memcpy (list[nptrs], buf, nchar + 1);       /* don's scan for \n */

        nptrs += 1;         /* increment pointer count */
        getnextline:;
    }

    for (size_t j = 0; j < nptrs; j++) {
        printf("Your strings by num %zu: %s\n", j + 1, list[j]);
        free (list[j]);     /* free storage for string */
    }
    free (list);            /* don't forget to free pointers */
}

Comment: Whoever dowvoted this answer, kindly have the **integrity** to explain why? There is not a single incorrect part of the answer.


Expectation of first of moment of symmetric r.v. in terms of variance

Question: Let $X$ be a symmetric random variable with bounded moments and standard deviation $\sigma$. I want to lower-bound $\mathbb E[|X|]$ in terms of $\sigma$. Here is the formal conjecture; I wonder if this is true or could be refuted:
There exists a global constant $C$ such that for every symmetric r.v. $X$ with bounded moments and standard deviation $\sigma$, it holds that $\mathbb E[|X|] \geq C \sigma$.
I suspect that this is a straightforward result, but I could not find anything about it nor could I prove it myself. Any ideas?
Edit: Symmetry w.r.t. zero, namely $f(x)=f(-x)$ for all $x$.

Some examples:

If $X$ has Rademacher distribution (-1 w.p. 0.5 and 1 w.p. 0.5), then $\mathbb E[|X|]=1$ and $Var(X)=1=\sigma^2$; therefore, $\mathbb E[|X|] = 1\cdot \sigma$ (the above holds with $C=1$).
For $X\sim Uniform(-b,b)$ for some $b>0$, $Var(X)=\frac{b^2}{3}=\sigma^2$ and $\mathbb E[|X|]=\frac{b}{2}$; thus, the above holds for $C=\frac{\sqrt{3}}{2}\approx 0.866$.
For $X\sim N(0,\sigma^2)$, $|X|$ is half-normal and $\mathbb E[|X|]=\sigma \sqrt{\frac{2}{\pi}}$; hence, the above holds for $C=\sqrt{\frac{2}{\pi}}\approx 0.797$.
Comment: @AvidLearner OK, thanks for the clarification.  That makes it a more interesting question.
Comment: The power-mean inequality shows you have the inequality in the wrong direction!
Comment: Could you please elaborate on your meaning of "symmetric"?  For instance, many (if not most) people consider all Normal distributions symmetric, but because all your examples are symmetric about $0,$ I wonder whether that's part of your definition, too.  The resolution of your question for distributions symmetric about $0$ follows easily from the [power-mean inequality.](https://stats.stackexchange.com/questions/244202)
Comment: Regardless $X$ is symmetric or not, you can always simply take $C = E[|X|]/\sigma > 0$ to make your conjecture hold (or $ C = 0.5E[|X|]/\sigma$ if you want a strict inequality).  So this "inequality" is actually quite trivial.  Your examples also showed the way how you determined $C$ followed this route.
Comment: @whuber Thanks, I should have said that specifically. I assume that $f(x)=f(-x)$ for all $x$. Could you sketch the proof? I can't see how it follows from the power-mean inequality.
Comment: @Zhanxiong But who promises us that $C$ won't be arbitrarily small for some distributions? Note the quantifier order: I want a value $C$ that satisfies the above for *all* symmetric r.v.
Comment: @Zhanxiong Those examples demonstrate that *if* the statement holds, then the value of the global constant $C$ is lower-bounded by $C \geq 0.797$.
Comment: @whuber The other side is straightforward to obtain with Jensen's inequality and $C=1$. I wondered whether it could be sandwiched a la Khintchine inequality. Apparently the answe is no.
Answer: You can actually develop your first example a little more to refute this conjecture, that is put some mass at $0$.
Let $X$ be the random variable such that $P[X = 0] = 1 - p$, $P[X = -1] = P[X = 1] =
\frac{1}{2}p$, where $p \in (0, 1)$.  It is then easy to verify that $E[|X|] = p$,
$\sigma = \sqrt{E[X^2]} = \sqrt{p}$, whence $\frac{E[|X|]}{\sigma} = \sqrt{p}$. So if your conjecture held, the global constant $C$ must be bounded above by $\sqrt{p}$, which can be arbitrarily small.  This requires that $C$ cannot be positive but $0$.
Comment: Thanks! It seems I need more conditions on $X$...


Create Bi-directional relation between two vertices using OpenCypher with Apache AGE

Question: In the below example I create a one-direction relation between two vertices (from b to a), is there a way I can create a relation from (a to b) at the same time?
SELECT *
FROM cypher('test_graph', $$
    MATCH (a:Person), (b:Person) WHERE a.name = 'hossam' AND b.name = 'omar'
    CREATE (b)-[r:REL {name: b.name+'->'+a.name}]->(a) RETURN r
$$) as (v agtype);

I tried remove the arrow symbol > before (a) like:  CREATE (b)-[r:REL {name: b.name+'->'+a.name}]-(a) but it results with a syntax error.
Answer: Create two relations in one go:
SELECT *
FROM cypher('test', $$
    MATCH (a:Person), (b:Person) WHERE a.name = 'hossam' AND b.name = 'omar'
    CREATE br =
    (b)-[r:REL {name: b.name+'->'+a.name}]->(a)<-[r:REL {name: b.name+'<-'+a.name}]-(b)
    RETURN br
$$) as (v agtype);

AGE ensures your graphs have a bi-directional relationship in terms of Edges.
Try the following query to check:
SELECT * FROM cypher('test_graph', $$ MATCH (a)-[r]->(b) RETURN r $$) as (v agtype);

Returns:
 {"id": 9570149208162308, "label": "REL", "end_id": 9851624184872964, "start_id": 9851624184872963, "pro
perties": {"name": "omar->hossam"}}::edge

The query for the opposite relation match
SELECT * FROM cypher('test_graph', $$ MATCH (b)-[r]->(a) RETURN r $$) as (v agtype);

Returns:
 {"id": 9570149208162308, "label": "REL", "end_id": 9851624184872964, "start_id": 9851624184872963, "pro
perties": {"name": "omar->hossam"}}::edge

If however you need the relation to be in the form of hossam->omar. You'll need to define another relation, preferably from (a)-[r]->(b). And it will show up as another edge.
OR,
A better approach is to just imply the relation as the following b.name+'<->'+a.name
Answer: As of right now i believe the most straightforward way to achieve bidirectional relations is to set it as a property, you can't just remove the  direction at the moment of creation. For example:
SELECT * FROM cypher ('graph', $$
MATCH (a:Person), (b:Person)
WHERE a.name = "hossam" AND b.name = "omar"
CREATE (a)-[e:FRIENDS]-(b)
RETURN e
$$) as (e agtype);

this will return as you said the error
ERROR:  only directed relationships are allowed in CREATE
LINE 4: CREATE (a)-[e:FRIENDS]-(b)

and the same thing will happen if you use bidirectional edge
SELECT * FROM cypher ('graph', $$
MATCH (a:Person), (b:Person)
WHERE a.name = "hossam" AND b.name = "omar"
CREATE (a)<-[e:FRIENDS]->(b)
RETURN e
$$) as (e agtype);
ERROR:  syntax error at or near ">"
LINE 4: CREATE (a)<-[e:BORDERS_WITH]->(b)

You need to try something like this:
SELECT * FROM cypher ('graph', $$
MATCH (a:Person), (b:Person)
WHERE a.name = "hossam" AND b.name = "omar"
CREATE (a)-[e:FRIENDS{ type:"<->" }]->(b)
RETURN e
$$) as (e agtype);

by assigning the "<->" as properties you can search search all the bidirectional relations in your graph using:
SELECT * FROM cypher ('graph', $$
MATCH (a)-[e:FRIENDS]->(b)
WHERE e.type = "<->"
RETURN e
$$) as (e agtype);

Since the feature of bidirectional relations isn't yet supported I believe this is one way to get around that.
Answer: No, there is no way to create bidirectional relationships in Apache AGE.
There is no way to create bidirectional relationships in Neo4j either as written in the answers to this question. The reasoning being since you are allowed to make non-directional queries, bidirectional relationships become essentially same as disregarding the direction altogether.
On a more technical level:-
The edges are stored with a vertex start_id and an end_id in the edges table. Having bidirectional relationship means that both the start_id and the end_id need to have 2 values.
You have 2 alternatives:-
1.) Make another relationship in the opposite direction (however it takes more space).
2.) Make non-directional queries.


Why Auto Update does not work for sample MyApp using Squirrel.Windows

Question: As per documentation I followed all the steps but the application did not update to 3.0.0. Which I suppose should happen automatically when App was opened. (It stayed at 1.0.0)

I updated the Assembly Info version:

Did release again from Visual Studio

Updated Nuget meta data in Nuger package manager

Executed squirrel --releasify MyApp.3.0.0.nupkg

This indeed created new .nupkg with 3.0.0:

P.S. I'm trying 1.0.0 to 3.0.0 as an example.
App was indeed 3.0.0 when running directly from Visual Studio

My releases folder has been set correctly:
Folder Path:

In Code

In <code>%LocalApp\MyApp</code> version 3.0.0 had not been downloaded:
Answer: Learnt that Main method must be async and await must be used.


Question regarding the square root of a squared number.

Question: I've learnt that the square root of a number squared is equal to the absolute value of that number, but I haven't really understood why. I have looked through other questions on MSE but didn't really find a good answer.
As an example: for me there are two ways to arrive at a solution for $\sqrt{(-5)^2}$
First: $\sqrt{(-5)^2}= $ $\sqrt{25}=5$
Second: $\sqrt{(-5)^2}= $ $\ (-5)^{\frac{2}{2}}$$\ =(-5)^1=-5$
but according to the $\sqrt{x^2} = | x | $  rule 5 is the only solution.
What is the flaw in my logic in getting -5 as a solution. I would really appreciate a comprehensive explanation that clears this up. Thanks in advance.
Comment: It boils down to the fact that although the square function $ \text{sq} $ maps $ \mathbb{R} \to [0,\infty) $, the square-root function $ \sqrt{\cdot} $ maps $ [0,\infty) $ to $ [0,\infty) $, not back to $ \mathbb{R} $, assuming that you choose only non-negative square roots so that $ \sqrt{\cdot} $ does not become multi-valued.
Comment: If you regard $\sqrt{\,\,}$ as a function then it can only give one value.  So even if $x^2=25$ may have two solutions, $x=\sqrt{25}$ can only have one.
Comment: Possible duplicate of: [Significance of $\sqrt[n]{a^n}$](http://math.stackexchange.com/questions/13094/significance-of-displaystyle-sqrtnan). Also [Proving square root of a square is the same as absolute value](http://math.stackexchange.com/questions/258876/proving-square-root-of-a-square-is-the-same-as-absolute-value)
Comment: You may also find this article useful: [Absolute Value](http://eaton.math.rpi.edu/coursematerials/fall08/mk1500/AppdxE.pdf)
Answer: We define $\sqrt k$ to be the positive square root of $k$. This means that taking square roots is a valid function on the positive reals - if we allowed it to have multiple values, then it wouldn't be a function.
This is different to the solutions of the equation $x^2=k$. Here we are looking for all real numbers whose square is $k$, so we must also consider the negative square root.
In you second case, the flaw in the argument is that you are implicitly taking the square root of a negative number - you are saying that $$\sqrt{(-5)^2}=\sqrt{-5}^2$$which gets messy, as taking the square root of a negative number, even if we allow complex numbers, requires a choice of root, and the rules of indices don't apply in the complex case in the same way they do in the real case.
Comment: k i got what u mean. thnx
Answer: You can think this in this way.
Let $$f: \mathbb{R}\rightarrow\mathbb{R}^+$$
$$x\mapsto x^2$$
where $x\in\mathbb{R}$
and $$g:\mathbb{R}^+\rightarrow\mathbb{R}^+$$
$$y\mapsto \sqrt{y}$$
where  $y\in\mathbb{R}^+$
So to solve this problem, we must follow this order of arithmetic just like your first illustration and your second should be $\sqrt{(-5)^2}=[(-5)^2]^{\frac{1}{2}}$
Answer: How do you know if $25$ is $5^2$ or $(-5)^2$ ? Numbers have no "memory".


Dynamically Add forms to table rows Using jQuery

Question: I'd like to know a good way to add form to a dynamically created tables with jquery. I've added a form in the following way, but when I press the button the function is not called!
I'm new to jquery so I think that there should be a better way to create the tables.
$("#aggiornaButton").click(function () {
    //alert('button clicked');
    $.ajax({
        url: 'Servizi/selectAllCoseDaFare.php',
        data: "",

        dataType: 'json',
        success: function (data) {
            $("#coseDaFareBody").empty();

            var formElimina = "<form action='' method='post' name ='eliminaForm' id='eliminaElementoSingolo' class='eliminaForm'>"
                    + "<fieldset>"
                    + "<input type='hidden' name='codID' id='codID'  value='166'/>"
                    + "<button id='eliminaButtonSingolo' class='eliminaButtonSingolo'>elimina</button>"
                    + "</fieldset>"
                    + "</form>";

            $.each(data.risultati, function (idx, obj) {
                if (idx % 2 === 0) {
                    var classe = "
"
                } else {
                    var classe = "
"
                }
                $("#coseDaFareBody").append(
                        classe + obj.id +
                        "	" + (obj.dataInserimento || "") +
                        "	" + (obj.descrizione || "") +
                        "	" + (obj.dataScadenza || "") +
                        "	" + (obj.isUrgente || "") +
                        "	" + (obj.inseritoDa || "") +
                        "	" + (obj.assegnatoA || "") +
                        "	" + (obj.fattoDa || "") +
                        "	" + (obj.isCompletato || "") +
                        "	" + (obj.dataEsecuzione || "") +
                        "	" + formElimina +
                        "
"
                );
            });

The function is:
$('.eliminaForm').submit(function (event) {
    var $form = $(this);
    var id = $('#codID', $form).val();
    alert("prova prova prova.");
});

Thank you.
Comment: can't repeat ID's in a page, use classes instead
Answer: Use event delegation for newly created dom elements
$(document).on("submit" , '.eliminaForm' , function(event) {
 var $form = $(this);
 var id = $('#codID', $form).val();
 alert("prova prova prova.");
});


Highest Formula One WDC ranking without a podium finish?

Question: Last year, with only drivers from Mercedes, Ferrari and Red Bull finishing on the podium, Force India drivers Sergio Perez and Esteban Ocon finished 7th and 8th in the championship with no podium finishes, but only having 3 and 2 non-points finishes, respectively.
Throughout F1 history, which driver has the highest finishing position in the drivers championship without a podium finish?
Answer: Two drivers have finished a season on rank 6 without a single podium finish throughout the respective season:

Robert Kubica in 2007, highest finish position was 4.
Felipe Massa in 2011, highest finish position was 5.

Several drivers finished a season on rank 7 without a podium position: Wolfgang von Trips (1960), Jacques Villeneuve (2000), Jenson Button (2002),
Rubens Barichello (2006), Nico Rosberg (2009) and Sergio Pérez (2017).
Answer: Looking at the past season, I will focus on post-2003 seasons since points were awarded for lower finishing positions from 2003 onwards, meaning more drivers could score points and therefore rank higher in the standings by scoring points more often by simply being consistent:

2010-present: points for top 10 finishers
2003-2009: points for top 8 finishers
1960-2003: points for top 6
pre-1960: points for top 5

Checking the season summaries (since 2003) on Wikipedia, I found that Massa and Kubica hold the record for highest WDC position without scoring any podiums:

Kubica, sixth place in 2007 (source)
Massa, sixth place in 2011 (source)


Restore hacked website from database without source

Question: I have a database backup from a hacked drupal site. The source code of the hacked website has been lost. When I try to make another installation of the site working using the old database, I have the following error:
Fatal error: require_once(): Failed opening required 'C:\ampps\www\drupal.fox\drupal/sites/all/modules/date/date_api/date_api.module' (include_path='.;C:\php\pear') in C:\ampps\www\drupal.fox\drupal\includes\bootstrap.inc on line 3168

How could I avoid such errors? is there any way to make drupal runs temporarly without missing modules or even is there a tool that able to download and install missing modules?
Answer: You can set status to '0' in table 'system' for missing modules
P. S. 'drush cc all' is a must-run command after the manipulation like this or manually empty cache tables
Comment: Good, I tried this but I still got the error. Is there any way to clear cache from the database?
Comment: There is another mention about enabled modules, in 'cache_bootstrap'. Just truncate all cache tables for being sure or use 'drush cc all'
Answer: Not sure about a tool to download all the modules, but you can do this pretty easily by checking the system table.
Run this:
SELECT *  FROM 'system' WHERE 'filename' LIKE '%module' AND 'status' = 1

You will get a list of module names, and the filename shows where the file was stored. Now, you can download the modules from drupal.org (check the schema version if you have doubts about 1.x, 2.x, etc minor version).
If the status of the module is shown as 1, that means the module is enabled, and there can be tables or any other database changes done by this module. You should not uninstall those modules, because you are going to lose all that data when you uninstall it (!= disabling a module).
Also, use registry rebuild module, which adds a handy drush rr to rebuild the registry. You will also need to clear caches a lot (drush cc all) to fix any theme registry mismatches. If you have a custom theme and/or have custom tpl.php files custom modules or custom themes, you will not be able to restore the 100% functionality unless you have those files.


$\{ a \mid a\not \in [G,G],\ a \in Z(G) \} \cup \{e\}$ is a group or not

Question: Let $G$ be a group. I want to check whether the set
$$\{ a \mid a\not \in [G,G],\ a \in Z(G) \} \cup \{e\}$$
is a subgroup or not, where $[G,G]$ and $Z(G)$ are the commutator subgroup and center of the group $G$ respectively.

In a vector space $V$ we can find the complement subspace $U$ of any its subspace $U$ such that $V=W\oplus U$? Can we generalize this to my case?
Comment: Why are you moving to vector spaces?   I thought we were discussing groups.
Comment: I was thinking for an analogous case.
Answer: This is not true.
Let $G$ be any finite group where $[G,G]\cap Z(G)$ is a proper, non-trivial subgroup of $Z(G)$. (E.g., $C_2\times D_8$.) Thus it contains at most half of the members of $Z(G)$. Your subset, therefore contains more than half of the members of $Z(G)$ (as it also includes the identity), so cannot be a proper subgroup by Lagrange's theorem.
Comment: Pedantic note: except when $G$ is abelian.
Comment: @MeesdeVries your note was not pedantic at all. In fact, non-abelian $[G,G]$ not containing $Z(G)$ was not enough either. I need exactly the consequence I claimed. Edited.
Comment: Thanks for the answer.
Comment: Should be "non-trivial proper subgroup"?
Comment: @spin If it's trivial then yes, the set in the OP's question would be $Z(G)$. Edited.
Answer: This is not true.
Take $G=\text{GL}_2(\mathbb{R})$ and denote your set by $A(G)$. Then we have $-2\cdot I_2,\frac{1}{2}\cdot I_2\in A(G)$ but their product is not in $A(G)$. Indeed, $[G,G]=\text{SL}_2(\mathbb{R})$ and the center of $G$ are the scalars, i.e. $Z(G)=\{\lambda\cdot I_2:\lambda\in \mathbb{R}\setminus\{0\}\}$.
Let me know if something is unclear.
Comment: thanks for your answer. Its really nice.
Answer: The following is just an expanded version of David Craven's answer.
Denote $Z = Z(G)$, and $H = [G,G] \cap Z$. The set you are looking at is $(Z \setminus H) \cup \{e\}$.
In general, you would not expect this to be a subgroup of $Z$, for any subgroup $H$ of $Z$.
Here is one reason:

Let $G$ be any group, and let $M$ be a proper subgroup. Then $G \setminus M$ generates $G$.

So if $(Z \setminus H) \cup \{e\}$ were a subgroup, it would have to be equal to $\{e\}$ or $Z$. In other words, either $H = Z$ or $H = \{e\}$.
Thus for a counterexample to the claim, it suffices to find $G$ such that $\{e\} \lneq [G,G] \cap Z(G) \lneq Z(G)$.
One example, given in the other answer: $G = C_2 \times D_8$.


Writing a function $ f: U \to \mathbb{R} $, where $ U $ is an open ball in $ \mathbb{R}^{n} $ centered at $ \mathbf{0} $, in terms of the dot product.

Question: Let $ U $ be an open ball in $ \mathbb{R}^{n} $ centered at the origin $ \mathbf{0} $. Let $ f: U \to \mathbb{R} $ be a continuous function. Here is my question:

If $ \displaystyle \lim_{\mathbf{x} \to \mathbf{0}} \frac{f(\mathbf{x})}{\| \mathbf{x} \|} = 0 $, then does there necessarily exist a continuous function $ \epsilon: U \to \mathbb{R}^{n} $ such that the following properties hold?

$ f(\mathbf{x}) = \epsilon(\mathbf{x}) \bullet \mathbf{x} $ for all
  $ \mathbf{x} \in U $, where $ \bullet $ denotes the dot product on
  $ \mathbb{R}^{n} $.
$
  \displaystyle \lim_{\mathbf{x} \to \mathbf{0}} \epsilon(\mathbf{x}) = \mathbf{0}
  $.

I was able to prove the existence of $ \epsilon $ without the requirement that it be continuous on all of $ U $. The basic idea is to use the fact that the taxicab norm and the Euclidean norm on $ \mathbb{R}^{n} $ are equivalent.
Thank you very much for your kind assistance!
Comment: $f$ is differentiable at the origin with derivative $0$.
Comment: @Rubertos: That must be the case since $f$ is continuous and the above properties hold.
Comment: Are you assuming $f(0)=0$?
Comment: @Rubertos: That already follows from the fact that $ f $ is continuous and $ \displaystyle \lim_{\mathbf{x} \to \mathbf{0}} \frac{f(\mathbf{x})}{\| \mathbf{x} \|} = 0 $.
Comment: Is $f$ differentiable, at least at the origin?
Answer: Consider
\begin{align}
\epsilon(\mathbf{x}) = \frac{f(\mathbf{x})}{|\mathbf{x}|^2}\mathbf{x}
\end{align}
which is continuous everywhere not the origin. At the origin, we see that
\begin{align}
|\epsilon(\mathbf{x})| = \frac{|f(\mathbf{x})|}{|\mathbf{x}|}\rightarrow 0
\end{align}
as $\mathbf{x} \rightarrow 0$. This shows that $\epsilon$ is continuous at the origin since $f$ is differentiable at the origin.  Moreover, we have that
\begin{align}
\epsilon(\mathbf{x})\cdot \mathbf{x} = f(\mathbf{x}).
\end{align}
Comment: Thank you! This was easier than I thought.
Answer: Define $\phi(x) = \begin{cases} {f(x) \over \|x\|}, & x \neq 0 \\
0, & \text{otherwise} \end{cases}$. By assumption $\phi$ is continuous
on $U$ and $\phi(0) = 0$.
Let $\epsilon(x) = \begin{cases} \phi(x) {x \over \|x\|}, & x \neq 0 \\
0, & \text{otherwise} \end{cases}$.


When creating a Chaos Tools content type plugin, what is a subtype and how are they used?

Question: I'm perfectly fine with creating Chaos Tools content types for use in Panels, but I've always used single => TRUE.
I've looked through the docs, but still can't quite seem to grok how to utilise subtypes.  None of the examples shipped with Chaos Tools seem to use them (they also all implement single => TRUE, and a quick grep of the Chaos Tools directory only shows the Custom Content type using subtypes, and it only appears to use it for including the export functionality (unless I'm reading it wrong - which is likely).
Answer: It's a good question, and some further information can be found in the ctools help file context-content.html

The CTools pluggable content system provides various pieces of content
  as discrete bits of data that can be added to other applications, such
  as Panels or Dashboard via the UI. Whatever the content is added to
  stores the configuration for that individual piece of content, and
  provides this to the content.
Each content type plugin will be contained in a .inc file, with
  subsidiary files, if necessary, in or near the same directory. Each
  content type consists of some information and one or more subtypes,
  which all use the same renderer. Subtypes are considered to be
  instances of the type. For example, the 'views' content type would
  have each view in the system as a subtype. Many content types will
  have exactly one subtype.

Also, in ctools_content_get_subtypes

Get all of the individual subtypes provided by a given content type.
  This would be all of the blocks for the block type, or all of the
  views for the view type.

So in a sense, the subtypes are individual instances of that type, such as individual Views or Blocks, or custom content instances, that use the same rendering functions as the parent content type.
For example, you can see in ctools_content_process
// If a subtype plugin exists, try to use it. Otherwise assume single.
if (function_exists($function_base . 'content_types')) {
  $plugin['content types'] = $function_base . 'content_types';
}

In the example of the block content type, this function returns the content types, or sub types for that plugin.
/**
 * Return all block content types available.
 *
 * Modules wanting to make special adjustments the way that CTools handles their blocks
 * can implement an extension to the hook_block() family, where the function name is
 * of the form "$module . '_ctools_block_info'".
 */
function ctools_block_content_type_content_types() {
  $types = array();
  foreach (module_implements('block_info') as $module) {
    $module_blocks = module_invoke($module, 'block_info');
    if ($module_blocks) {
      foreach ($module_blocks as $delta => $block) {
        $info = _ctools_block_content_type_content_type($module, $delta, $block);
        // this check means modules can remove their blocks; particularly useful
        // if they offer the block some other way (like we do for views)
        if ($info) {
          $types["$module-$delta"] = $info;
        }
      }
    }
  }
  return $types;
}

Lastly one more example for good measure from the views_content content type plugin
/**
 * Return all content types available.
 */
function views_content_views_content_type_content_types($plugin) {
  $types = array();
  // It can be fairly intensive to calculate this, so let's cache this in the
  // cache_views table. The nice thing there is that if views ever change, that
  // table will always be cleared. Except for the occasional default view, so
  // we must use the Views caching functions in order to respect Views caching
  // settings.
  views_include('cache');
  $data = views_cache_get('views_content_all', TRUE);
  if (!empty($data->data)) {
    $types = $data->data;
  }

  if (empty($types)) {
    $views = views_get_all_views();

    foreach ($views as $view) {
      if (empty($view->disabled)) {
        $types[$view->name] = _views_content_views_content_type($view);
      }
    }

    views_cache_set('views_content_all', $types, TRUE);
  }

  return $types;
}

In this case _views_content_views_content_type returns
function _views_content_views_content_type($view) {
  $title = $view->get_human_name();

  $icon = 'icon_views_page_legacy.png';

  return array(
    'view' => $view->name,
    'title' => $title,
    'icon' => $icon,
    'description' => filter_xss_admin($view->description),
    'category' => t('Views'),
  );

}

Comment: Interesting...I wonder then if a subtype's relationship to a ctools plugin is analogous with a core field instance's relationship to a field definition - perhaps that drove the design decision
Comment: Thanks David - I've only just opened the bounty, so I'll let it run for a few more days. But it looks promising for you ;-)
Comment: Thanks for the answer - but as I mentioned, I've already looked through the docs, and they don't *actually* answer the question :( I should probably have changed the title somewhat - I understand what they are, but not how to implement them myself :)
Comment: @David - but please have an upvote anyway :-)
Comment: @Chapabu thanks :-) , I've included some additional information on how the block subtypes are returned with `ctools_block_content_type_content_types` perhaps the example helps to clarify a little more there.


Multiform/Wizard module

Question: I'm looking for a module, that changes the workflow of creating a node. I want to be able to have several fields in named group sections so the author of a node has some structure.
But when editing the node the author should be able to quickly jump around the forms.
So for example the Content Type "Article" has the following group sections:
Content > Images > Related Articles
In each section there are fields.
How can I do that? Are there mature modules for that case?
Comment: _"the author should be able to quickly jump around"_ As enjoyable as the image that conjures up is, could you clarify what you mean exactly?
Comment: You're right :D I hope it is more clear now ;)
Comment: You have to use both http://drupal.org/project/field_collection and http://drupal.org/project/field_group and set the dependency according to your requirement in field collection
Comment: I think field_collection is not really what I'm looking for, since the field_collection itself represents it's own field.
Answer: You could check out the field group module. You have several options to group your fields:

<code>Fieldsets
Horizontal tabs
Vertical tabs
Accordions
Divs
Multipage steps: Note: This is only client side.
</code>
Comment: So as I understand it, I have to use JS to create the multipage form? I checked it a little, and yes, it seems not that bad.
Comment: Oh I just forgot to create a Multipage group. That module seems to do all I want. And it uses JS, that is great!

Multiform/Wizard module


Qual é a finalidade do : (dois pontos) no PHP?

Question: Eu tenho essa questão que está me deixando com pulga atras da orelha. Eu não entendo, de jeito nenhum.
O que quer dizer o sinal de : dois pontos. Alguém sabe me explicar?
Exemplo:
if ( have_posts() ) : while ( have_posts() ) : the_post();
Comment: vejo que encontrou esses snippets de código no wordpress, não é isso?
Comment: Exatamente! Eu estou estudando o WordPress de A a Z. estou acreditando que assim vou me tornar independente em PHP.
Answer: Essa é uma sintaxe alternativa para um bloco que é delimitado por chaves { }. Nesse caso a abertura vira os dois pontos : e o fechamento é um end seguido do nome instrução que inicou pode ser um endif, endforeach etc. Essa sintaxe se aplica as instruções if, while, for, foreach, and switch.
$arr = range(1,5);

foreach ($arr as $item){
    echo $item .'
';
}

O mesmo código com a outra sintaxe.
$arr = range(1,5);

foreach ($arr as $item):
    echo $item .'
';
endforeach;

Documentação
Comment: Muito obrigado. Eu só conhecia as chaves. Agora está fazendo sentido.
Comment: Eu fiquei na duvida sobre os dois pontos dentro do "IF", também é uma condição, dentro de uma condição?
Comment: @Narsejo tem um exemplo para mostrar?
Answer: Complementando a resposta do @rray. Você também irá encontrar o sinal de dois pontos : como parte do operador ternário ?: usado para condições.
Veja um exemplo:
$user = "gato";

echo ($user === "gato") ? "meow" : "nao eh um gato :(";

Saída:

meow

Veja mais na documentação.
Comment: Essa eu sabia. Era exatamente o que estava me confundindo muito. Agora tudo está fazendo sentido pra mim.


Very simple characterisation of $(-1)$-curves

Question: Let $X$ be a complex surface (i.e., complex dimension 2) and $C$ a $(-1)$-curve in $X$, i.e., a reduced, compact, connected curve $C$ with self-intersection $-1$. I'm trying to understand the proof of the equivalent characterization of $(-1)$-curves, namely, $$C^2 < 0 \ \ \text{and} \ \ (C, K_X) < 0.$$ Indeed, if $C$ is a $(-1)$-curve, then $C^2 =-1$ by definition and by adjunction we have $$K_C = K_X \otimes \mathcal{O}_X(C) \vert_C.$$ Then $$(C, K_C) = (C, K_X) + (C, \mathcal{O}_X(C) \vert_C),$$ since the intersection product is bilinear with respect to the tensor product of line bundles. How do we deduce from this that $$(C,K_X) <0?$$
Answer: The adjunction formula allows us to write
$$\text{deg}(K_C) = (K_X + C)C = (K_X \cdot C) + C^2.$$
Now we use that $C$ is a $(-1)$-curve:

It is isomorphic to $\mathbb{P}^1$, so that $\text{deg}(K_C) = -2$
We have $C^2 = -1$

Hence we get $$-2 = (K_X \cdot C) -1$$ by the formula above, i.e. $(K_X \cdot C) = -1$.
Comment: Thank you very much, this is exactly what I was looking for.
Comment: Glad that I could help.


Linear Algebra Involving nonsingular matrices.

Question: $A^2+A+I=0$, show that $A$ is non-singular and $A^{-1}=A^2$.
Can someone please explain this to me?
Comment: Rearrange: $I=-A^2-A=A(-A-I)$. Can you conclude that $A$ is invertible? What is the inverse and how can it be written differently using the original identity?
Answer: Next time, please tell us what you have tried to solve the problem. Here is a hint:
$$A^3-I=(A-I)(A^2+A+I)=0.$$
Comment: how'd you get a^3, sorry if its a dumb question
Comment: Break the brackets $(A-I)(A^2+A+I)=A(A^2+A+I)-(A^2+A+I)$.
Answer: Let $(\lambda,x)$ be an eigenpair of $A\implies \lambda\in\{\omega,\omega^2\}$ where $\omega,\omega^2$ are the complex cubic roots of unity. Since $\lambda\ne 0$, $A$ is nonsingular and hence, from the given equation, $A^{-1}(A^2+A+I)=0\implies A^{-1}=-(I+A)=A^2$


Different CSS file when in development mode

Question: Using Gulp I create two css files. One style.css and one style.min.css. Is it possible to load the style.css when developing (locally) and the style.min.css when in production (remote)?
Comment: Try reading about the config split: [Creating a simple split configuration: Dev modules only in dev environments](https://www.drupal.org/docs/8/modules/configuration-split/creating-a-simple-split-configuration-dev-modules-only-in-dev). This may also be relevant: [Creating advanced theme settings](https://www.drupal.org/docs/8/theming-drupal-8/creating-advanced-theme-settings).
Comment: If you use the Advanced Aggregates module you can have all the CSS and JS you use minimised and aggregated automatically. https://www.drupal.org/docs/8/modules/advanced-cssjs-aggregation/advanced-aggregates
Comment: It's possible yes. You can check for environment variables or base URL or use config split to enable different modules per environment to attach different libraries. For all 3 mentioned approaches you can use `hook_page_attachments`.
Answer: You can specify two different libraries in mymodule.libraries.yml. Then in your mymodule.module file attach the one that matches your current deployment env:
<code>function mymodule_page_attachments(array &$attachments) {
  if (PRODUCTION) {
    $attachments['#attached']['library'][] = 'mymodule/lib_prod';
  } else {
    $attachments['#attached']['library'][] = 'mymodule/lib_dev';
  }
}
</code>
I am using code like this to decide on which deployment level I am:
<code>  public static function getDeploymentStage() : string {
    // lazy cache
    static $ds = null;

    if (null == $ds) {
      if (isset($_SERVER['SERVER_NAME'])) {
        switch ($_SERVER['SERVER_NAME']) {
          case 'anwalt-seiten.de':
          case 'www.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_PROD;
            break;
          case 'stage.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_STAGE;
            break;
          default:
            $ds = AsdentBaseService::DS_DEVELOPMENT;
            break;
        }
      } else {
        $ds = AsdentBaseService::DS_DEVELOPMENT;
      }
    }

    return $ds;
  }
</code>
Note that any drush command will run in dev-mode here.
You can also use $settings from settings.php or any environment variable instead.
Comment: `if (getenv('MYENVFOOBAR') === 'production')` ...
Comment: Thanks it works. I used the base URL to check if its in running local or remote. Does this have any negative effect on the performance? Do the files get loaded later because of the hook or the way I'm figuring out it is local or remote?
Comment: Don't think there's any impact on performance (use caching!) - and also there's no change in processing order by calling that hook.
Comment: One more question, I noticed when using this. The attached css also overwrites styling on my admin pages. Is there a way to have this only work on none admin pages?
Comment: Use another theme for admin at the bottom of /admin/appearance
Comment: Another approach is to check for the current user in the mymodule_page_attachments() decision. But then you need to add "user" to the cache context of each page.


Explain the convolutions of setp function

Question: $$ t* u(t-a)= \frac{1}{2}(t-a)^2 u(t-a)$$
attempt:
$$ t* u(t-a)= \int_{-\infty}^{+\infty} tu(t-a)dt$$
I don't quiet understand what i write before. What mean that t is a causal function?
$$ t* u(t-a)= \int_{0}^{t} (t-\tau)u(\tau-a)d\tau $$
$$ t* u(t-a) = \frac{1}{2} (t-a)^2...$$
Comment: When you convolve there should be an additional variable for the argument of the convolution (since the convolution is itself a function).
Answer: Let
\begin{align}
f(t)&=u(t-a)\\
g(t)&=t\\
\end{align}
Therefore,
\begin{align}
f(t)*g(t)&=\int_{0}^{t}f(\tau)g(t-\tau)d\tau\\
&=\int_{0}^{t} u(\tau-a)(t-\tau)d\tau\\
&=\int_{a}^{t}(t-\tau)d\tau \,\,\,\,\,\,\,\,\,\,\,\,\text{assuming}(t\ge a)\\
&=-\frac{1}{2}(t-\tau)^2\biggl|_a^t u(t-a)\\
&=\frac{1}{2}(t-a)^2 u(t-a)
\end{align}


How to extract data between two delimiters '|' from a text file using getline function in c++?

Question: There's data arranged between delimiters in a file which looks like this:
|  No. |  name. |  product. |  price. |
I want to read one data at a time.
Each section partitioned by these delimiters contains one or more syllables (one or few words). How to I read this ?
Comment: Or, better, read the entire line and then use `stingstream s (line)` and then `while (getline (s, val, '|'))` so you do not read more than 1 line of data at a time.
Comment: You called it. `getline(stream, token, '|')` will get you everything from the start to the first |, between two |s or from the last | to the end of the stream.
Answer: The basic approach for a delimited file would be to read the entire line into a string, then create a stringstream from the line and loop over the stringstream calling getline with the delimiter ('|' here) to separate the value into the fields.
(this way the number of fields need not be known ahead of time -- without stringstream you must limit your read of fields to the number present using getline or getline will happily begin reading data from the next line)
Below the example just reads each field of the input file into a string, but for your needs you may want an additional conversion, (e.g. stol or the like) to convert the individual fields to int or double (that is left to you).
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <limits>

using namespace std;

int main (int argc, char **argv) {

    string line;

    if (argc < 2) {
        cerr << "error: usage, program <filename>\n";
        return 1;
    }

    ifstream f (argv[1]);   /* open file */
    if (!f.is_open()) {     /* validate file open for reading */
        perror (("error while opening file " + string(argv[1])).c_str());
        return 1;
    }

    while (getline (f, line)) {         /* read each line */
        string val;                     /* string to hold value */
        stringstream s (line);          /* stringstream to parse fields */
        /* output original line */
        cout << "line: " << line << "\n\n";
        /* skip 1st delim */
        s.ignore(numeric_limits<streamsize>::max(), '|');
        while (getline (s, val, '|'))   /* for each field */
            cout << "  value: " << val << '\n'; /* output each field value */
        cout << '\n';
    }
}

Example Input File
$ cat dat/fields.txt
| 1   | Joe   | marbles  |   1.25 |
| 2   | Mike  | jacks    |  13.49 |
| 3   | Jill  | pail     |   4.50 |

Example Use/Output
$ ./bin/iostream_strstream_fields dat/fields.txt
line: | 1   | Joe   | marbles  |   1.25 |

  value:  1
  value:  Joe
  value:  marbles
  value:    1.25

line: | 2   | Mike  | jacks    |  13.49 |

  value:  2
  value:  Mike
  value:  jacks
  value:   13.49

line: | 3   | Jill  | pail     |   4.50 |

  value:  3
  value:  Jill
  value:  pail
  value:    4.50

Look things over and let me know if you have further questions.

Rewrite in C for 32-year old Operating System
Since you are attempting to compile with a still unidentified C++ compiler on a 32 year old operating system, (none of which was specified in your original question), you are probably much better served writing your parse routine in C. Why? The C++ standard was very amorphous at that time. It was more a superset of C then compared to what C++ is today. In the Turbo C and Borland C++ compilers of that day, all included files still used the C header file include format (which contain the '.h' at the end of the header name, e.g. #include <string.h>) This explains your "failure to find header" issue.
C on the otherhand was much closer to what is available today. Though it has gone through several standard revisions, the basic function available then and now are the same. The following has a much better chance at compiling on whatever you have DOS 3.2 running on that the C++ code.
#include <stdio.h>
#include <string.h>

#define FLDSZ 32   /* maximum file size for name and product */
#define MAXC 256   /* maximum length for line (including '\0') */

int main (int argc, char **argv) {

    char buf[MAXC] = "";    /* buffer to hold each line */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) {
        int id;                     /* id from file */
        char name[FLDSZ] = "",      /* name */
            product[FLDSZ] = "";    /* product */
        float price;                /* price */
        size_t len = strlen (buf);  /* length of string in buffer */
        if (len == MAXC - 1 && buf[len - 1] != '\n') {  /* check it fit */
            fputs ("error: line too long.\n", stderr);
            return 1;
        }
        if (sscanf (buf, "|%d | %31s | %31s | %f",      /* parse fields */
                    &id, name, product, &price) != 4) {
            fputs ("error: failed to parse line.\n", stderr);
            continue;
        }
        /* output parsed fields */
        printf ("%3d %-10s %-10s %.2f\n", id, name, product, price);
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    return 0;
}

(the program expects the data filename as the 1st argument, or it will read from stdin if no argument is given)
Example Use/Output
$ ./bin/fieldparse ~/dev/src-cpp/tmp/dat/fields.txt
  1 Joe        marbles    1.25
  2 Mike       jacks      13.49
  3 Jill       pail       4.50

All I can tell you is give it a try and let me know what happens.
Comment: thank you sir. but the problem is my editor does not support some functions as it does not recognise the header files. can you give any other alternative ??
Comment: What compiler? (those are all C++-standard headers.) What does your compiler say is not recognized? Can you compile with the `-std=C++11` option?
Comment: @VinitaKumari I have compiled on both Linux and Windows7 (old VS) and it compiles and runs fine on both. I can't image you have something older than Win7?
Comment: no, actually i m using ms dos to write my c++ program
Comment: Oh, like Borland C++ days? What version of MSDOS? I used to use Borland on DOS 4.1 (got rid of the 33M partition limit from DOS 3.X). What compiler are you using so I can look up what it has? (oh, goodness, that was for my 386DX with Math Co-Processor) The only header I can think of that wouldn't be there is `` is that what your compiler can't find? Let me know.
Comment: ms dos 3.2, the same inbuilt compiler
Comment: This one [Borland for Dox 3.x](https://winworldpc.com/product/turbo-c/3x)?? Dos 3.2 is from 1986 - 32 years ago. It came on 5.25 inch floppies. (yes I still have many) You can't get anything newer than that?? If I were dealing with something that old, I write in C, not C++. C++ was just being developed.
Comment: Also note at that time the C++ include files still required the `'.h'` at the end (e.g. `#include `) -- long, long ago.


Cant get onclick event to trigger my function in javascript

Question: I'm working on an application that will allow me to click a button on the web page and then start my timer object. However, the timer will not start onclick.

 Your Objectives:

 Blue Buff:
 <button id="yosb" onclick ="startBlue();">Start Blue</button>

Comment: onclick ="startBlue();" should be onclick="startBlue();" (NO SPACE BEFORE =)
Comment: If my answer below works for you, please select it as the answer. If not I will be happy to help you out some more.
Comment: vivekvasani, that did the trick thank you!
Answer: Your problem isn't the space, it is a scope and reference issue.
var index, obj;  //define index and obj outside of startBlue().
function startBlue(){
    index = 300;  //initialize without redefining (remove 'var').
    obj = new Timer();  //initialize without redefining (remove 'var').
    obj.Interval = 1000;
    obj.Tick = timer_tick;  // store the actual function in obj.Tick, not the return (remove the '()' from the end of timer_tick)
    obj.Start();
}

If you define a variable inside of a function, then that variable is only accessible inside the scope of that function only. By defining it outside, you allow that variable to be accessed from the outer scope.
To store functions in variables, you must be sure not to include the parens at the end of the function name. Otherwise the function will be executed first, and the return value will then be stored in the variable instead of the function it self.
Answer: The following line
<button id="yosb" onclick ="startBlue();">Start Blue</button>

Should be changed to
<button id="yosb" onclick="startBlue();">Start Blue</button>

You are adding an unnecessary space between the onclick and the =.
Comment: I fixed that line, still having issues getting the onclick event to initialize.
Comment: What is the timer being used for?


Encryption at rest for VM storage in a hypervisor done properly/elegantly

Question: Given a very simple infrastructure - a single machine running a hypervisor(Proxmox if it matters), I want to achieve a good data protection against the hardware being stolen.
Let's say there are various VM's running on the hypervisor - most of those don't need to be encrypted, but for the NAS/personal cloud ones I want the data to be safe if the hardware gets stolen.
I would like to get some ideas on the best practices to handle such scenarios. I've thought about it a bit and came up with several approaches from which I have hard time choosing which is optimal and if there are any problems/risks that I'm overlooking.
Full disk encryption of the host
This is out of the question, because the hardware is often left unattended, so it has to be able to recover in a reboot on itself and some of the VM's(CCTV, web servers, etc) need to start without intervention
Encrypting the disk/partition containing the VM volumes on the host
An easy approach would be encrypting a disk that would hold the sensitive VM volumes.
What I like in this approach is I can group all qcow2 volumes I need into a storage bucket that's locked on startup and I manually unlock it via SSH or a custom API.
What I don't like is this has to live on the Proxmox host and I'd like to keep it as clean as possible. Also a downside is that I can't boot a VM without some of its vm disks available(I hoped it would behave just like trying to boot a real computer with a harddisk removed). This would basically mean I can't have the NAS boot without the sensitive disk attached.
There is a way to programmatically detach the disk from the vm, and attach it on unlocking, but again I would like to keep the Proxmox side as clean as possible.
A third potential drawback are backups, since the actual qcows and FS's inside are not encrypted, so I have to take additional care of encrypting the backup itself.
Delegate all encryption to the VM guests
The cool thing here is each VM can handle the encryption on its own - like a VM that I want fully encrypted, I can turn on full disk encryption on the system drive and need to connect via VNC/console to unlock it on boot, OR, I can have a single partition/vm disk encrypted on the guest side(for example the NAS storage drives I need to be safe).
On the downside I need to unlock each VM separately, also this brings the responsibility to maintain/backup the luks headers for each partition encrypted, and I'm concerned if so many levels of abstraction of the storage could become fragile - in this case it would be the FS of the host, a qcow2 storage on top of it, then inside - a virtual disk, then on top of it - luks/dm-crypt, then the fs and partitions themselves.
The huge upside is this would be completely irrelevant for the host so backups will have the guest fs's encrypted, no modifications of the host, and most flexibility on the VM's. I think sounds the most convenient and "compatible" way of doing it, treating the VM's as standalone machines. My only worry here is this many levels of abstraction - am I paranoid?
Encrypted hdd passthrough
I'm currently using this approach where the sensitive storage is a fully encrypted separate disk, that's passed-through into the NAS system. Although this feel safest, as I don't have additional layers of abstraction, this causes me some pains in terms of automatic backups and Proxmox not being particularly friendly to passed-through disks - it doesn't count them as standard storage, doesn't expose any UI for maintaining them, etc.
The good side is, it's a completely standard data drive that I can just unplug, put into another PC and decrypt/read.

So, from an elegance standpoint I think I'm leaning towards option 3 - treating each VM as a standalone PC that bears the responsibility for its encryption - whether it's the whole disk encryption for the VM, or encrypting a single partition/virtual disk inside.
I have several concerns which I have no idea how valid or sensible are:

Is there any "safe limit" to the size of a qcow2 file? Like, is there any downside in having a storage virtual disk in a qcow2 format with a size of, say, 1TB?
Is there any real additional in having these additional abstraction levels in storage in terms of hidden data corruption, etc? I suppose the ordeal of data recovery of such a filesystem would be hellish, so reliable backups become even more paramount?
Is there a "standard" way of handling storage dependencies in services running under Linux? Meaning, let's say I let the NAS boot, but its backup storage isn't unlocked. A separate VM that depends on this storage via NFS won't be able to mount it, so if whatever service uses the 2nd VM, it would start writing in the mount point. I surely can script my way out of this, but I don't want to rediscover the wheel if good practices are already laid out.

Any ideas or advice are very welcome.
Comment: I would suspect that Proxmox doesn't have an equivalent offering that exists from Microsoft/VMWare. This is a legitimate business problem that existed for 10+ years, but security enhancements in mainstream products have addressed these gaps.  Trying to cobble something together may satisfy the requirements of a small audience, but I don't see this approaching anything near what is available in commercial products such as Hyper-V.
Comment: I would suggest that you take a look at the proxmox forum or create a ticket for your business environment. Since you must running a business environment to ask here, I assume that you also have a support plan for proxmox and furthermore can then get a support case on it.
Comment: I forgot to mention this is a home lab, so it's for my own convenience and experiment :) But I guess an elegant solution would also be suitable for a small business - I doubt large businesses would rely on such a solution at all :)
Answer:
Full disk encryption of the host

I think either you don't understand Full disk encryption, or you haven't had enough experience with this.
There's a number of ways of doing this in a perfectly servicable way - one option is just to use SEDs (self-encrypting disks), it's totally transparent to the disk controller and above (OS, hypervisor, VMs). Another is to get the controller to manage the encryption - HPe controllers are particularly good at this - you set a key on the controller and it encrypts/decrypts onto any regular disks - again this is transparent to the OS etc.
Either of these are secure, performant and requires no input from the OS, and allow for unattended reboots.
Comment: I understand but this site is for pro-sysadmins, most of which will have access to SEDs and encrypting-disk-controllers - if your organisation cannot afford these for you you can only do this via the 'in-server' methods you're aware of already, and inherently these sometimes need a degree of user interaction.
Comment: Thanks for the useful input - I didn't know about SEDs. Sadly this seems available only for server-grade hardware which I don't have :) By FDE on the host I was talking the "default" approach used by OS's like Debian where apart from the bootloader everything is encrypted and you enter a password on boot. That's not good for me because the hypervisor and most of the vm's are not related to the encryption thing and have to start unattended :)
Comment: Indeed I was made aware through another comment, although pretty rude, that SuperUser site is the place for consumer-grade infrastructure.
Answer: 2.29. Encryption of Disk Images
Oracle VM VirtualBox enables you to transparently encrypt the data stored in hard disk images for the guest. It does not depend on a specific image format to be used. Images which have the data encrypted are not portable between Oracle VM VirtualBox and other virtualization software.
Oracle VM VirtualBox uses the AES algorithm in XTS mode and supports 128-bit or 256-bit data encryption keys (DEK). The DEK is stored encrypted in the medium properties and is decrypted during VM startup by entering a password which was chosen when the image was encrypted.
Since the DEK is stored as part of the VM configuration file, it is important that it is kept safe. Losing the DEK means that the data stored in the disk images is lost irrecoverably. Having complete and up to date backups of all data related to the VM is the responsibility of the user.
2.29.1. Limitations of Disk Encryption
There are some limitations the user needs to be aware of when using this feature:
<code>This feature is part of the Oracle VM VirtualBox Extension Pack, which needs to be installed. Otherwise disk encryption is unavailable.

Since encryption works only on the stored user data, it is currently not possible to check for metadata integrity of the disk image. Attackers might destroy data by removing or changing blocks of data in the image or change metadata items such as the disk size.

Exporting appliances which contain encrypted disk images is not possible because the OVF specification does not support this. All images are therefore decrypted during export.

The DEK is kept in memory while the VM is running to be able to decrypt data read and encrypt data written by the guest. While this should be obvious the user needs to be aware of this because an attacker might be able to extract the key on a compromised host and decrypt the data.

When encrypting or decrypting the images, the password is passed in clear text using the Oracle VM VirtualBox API. This needs to be kept in mind, especially when using third party API clients which make use of the webservice where the password might be transmitted over the network. The use of HTTPS is mandatory in such a case.

Encrypting images with differencing images is only possible if there are no snapshots or a linear chain of snapshots. This limitation may be addressed in a future Oracle VM VirtualBox version.
</code>
2.29.2. Encrypting Disk Images
Encrypting disk images can be done either using the GUI or VBoxManage. While the GUI is easier to use, it works on a per VM basis and encrypts all disk images attached to the specific VM. With VBoxManage one can encrypt individual images, including all differencing images. To encrypt an unencrypted medium with VBoxManage, use:
VBoxManage encryptmedium uuid|filename
--newpassword filename|- --cipher cipher-ID --newpasswordid "ID
To supply the encryption password point VBoxManage to the file where the password is stored or specify - to let VBoxManage ask you for the password on the command line.
The cipher parameter specifies the cipher to use for encryption and can be either AES-XTS128-PLAIN64 or AES-XTS256-PLAIN64. The specified password identifier can be freely chosen by the user and is used for correct identification when supplying multiple passwords during VM startup.
If the user uses the same password when encrypting multiple images and also the same password identifier, the user needs to supply the password only once during VM startup.
2.29.3. Starting a VM with Encrypted Images
When a VM is started using the GUI, a dialog will open where the user needs to enter all passwords for all encrypted images attached to the VM. If another frontend like VBoxHeadless is used, the VM will be paused as soon as the guest tries to access an encrypted disk. The user needs to provide the passwords through VBoxManage using the following command:
VBoxManage controlvm uuid|vmname addencpassword ID password [--removeonsuspend yes|no]
ID must be the same as the password identifier supplied when encrypting the images. password is the password used when encrypting the images. Optionally, you can specify --removeonsuspend yes|no to specify whether to remove the password from VM memory when the VM is suspended. Before the VM can be resumed, the user needs to supply the passwords again. This is useful when a VM is suspended by a host suspend event and the user does not want the password to remain in memory.
2.29.4. Decrypting Encrypted Images
In some circumstances it might be required to decrypt previously encrypted images. This can be done in the GUI for a complete VM or using VBoxManage with the following command:
VBoxManage encryptmedium uuid|filename --oldpassword file|-
The only required parameter is the password the image was encrypted with. The options are the same as for encrypting images.
Comment: VB does offer that feature, but Proxmox(which I'm using) can't work with its native images. QCOW2 also offers encryption, but Proxomox can't use that too. For now I'm testing out how it behaves with data volume encryption inside the guest using autofs.


The custom node template file is not working

Question: I've created template file named node--product-display.tpl.php as suggested by the Theme developer module, but the changes I made to this file don't show up.
I've also copied the node.tpl.php file in my templates directory. The changes in the latter one show up but that in the former one doesn't.
Do you have any suggestion?
I have cleared the cache. The template file is for a "Product Display" content type, whose machine name is "product_display."
Answer: Try node--product_display.tpl.php.
If your file is empty, it will show the default template file; make sure you have write something in your custom file.
Be sure to clear the cache.


Finding coordinate vector for a polynomial in P3 relative to a given ordered basis

Question: Find the coordinate vector of $x^3 + 3x^2 - 4x + 2$ relative to ordered basis $(x, x^2 - 1, x^3, 2x^2)$.
My answer is $(-4, -2, 1, 5/2)$ while the textbook says it is $(-4, -2, 1, 5)$. Was wondering if my answer is correct or the textbook's is. I feel quite familiar with the process of finding a coordinate vector and was certain my answer was correct but I might be missing something.
Comment: It looks to me like $5/2$ is correct
Comment: It's easy enough to check each one for yourself. The coordinates are the coefficients of a linear combination of the basis vectors.
Answer: $$-4x -2(x^2-1) + x^3 +5(2x^2) = x^3 + 8x^2 -4x +2$$
$$-4x -2(x^2-1) + x^3 +\dfrac52(2x^2) = x^3 + 3x^2 -4x +2$$
You are right.
Comment: That's exactly how I tested it as well. Thank you!


What is the definition of slow practice for classical guitar?

Question: Everyone who teaches guitar says that you should practice slowly because that is the best way. One example is here, but there are billions of others who say it too.
I try to take their advice to heart, but it frustrates me because "slow" is relative so what is it? I'm a numbers person so I want exact definitions, not "slow enough."
For example, I'm practicing a piece by Carulli called Andante Grazioso arranged by Eythor Thorlaksson and I'm playing it at a slow tempo of 40 bpm(*). The piece is 64 bars long (including repeats) and 3 beats/bar meaning one play through takes about (64 * 3 * 1.5 = 288 seconds) five minutes.
How do I know if that is slow practice or fast practice? The only definition I've heard is that you shouldn't play a piece faster than you can play it perfectly. What is perfect? Obviously unattainable for a human, what you want is "good enough." So what is good enough? Much harder to attain for a self-critical person who is good at spotting errors.
I can play the piece "really good" (to my untrained ears, that is!) at that slow tempo. If I increase the tempo to 60 bpm, with minor faults, to 80 bpm with major faults and to 100 bpm with glaring errors.
And almost as obviously, I can play it even better at 30 bpm or 20 bpm! But why stop there? 10 bpm or one note every six second because if slow is good, then slooooooooooooow is better. :)
Essentially, I'm looking for a number between 0-120 which is the bpm value I should set my metronome to when practicing this piece to receive the most guitar skill/time unit invested. I also want to know what logic I should use to figure out what this bpm value is when practicing other pieces.

I know classical music isn't supposed to be played at a fixed tempo, but more fluidly. But I'm not good enough for playing like that yet.
Comment: Try to give 'comfortable' a number. 'Slow practicing' for me is practicing (a given piece) at such speed that I feel comfortable and (almost) don't make errors. Maybe one could measure his heart rate while playing and count the music's beats per minute and count the errors per minute. You don't want your heart rate to go up and you want zero errors but maximum beats per minute of the piece. What function do we then need to optimize? That's the question.
Comment: dH/dB + c.E/B would be a function to minimize (H = heart rate, B = piece's beats per minute, E is number of errors in the piece. c is a factor still to be determined. But no kidding, I upvoted Tim H's answer because I agree with his statement about awareness. And listen a lot how better players play the piece and try to understand their expressiveness and learn from them.
Answer: I'm afraid I have some bad news, Björn: in my experience, there's not really any mathematical logic to this.
From my experience, I just slow down my metronome to a tempo where I can play it without any technical errors. (It's also impossible to define exactly what "good enough" is!) Once I have that consistent, I'll slowly increase the tempo, and over the span of a practice session, or a week, or several weeks, eventually I'll get to the goal tempo.
In going through that process, I naturally end up experimenting with a number of musical decisions so that, by the time I'm up to tempo, I have the musicality included as well (and thus I don't have to reset the metronome to practice that slowly, as well).
But here's the kicker: in some cases, slow practice can be bad! I once worked on a deceitfully tricky Poulenc piece for piano. After weeks of slow practice it wasn't getting any better. So finally I just started practicing it at tempo. It was ugly for a little bit, but ultimately that was the only thing that actually prepared me to play the piece.
The Key Point: Every musical situation is different. Your abilities as a performer are always changing, the repertoire is changing, the particular day is changing, every performer is different, and no one's definition of "good enough" matches. Thus there's just no mathematical way of clarifying all of this; these are just decisions you have to make, and as you improve in your musical life you'll learn how to make these decisions more and more efficiently.
Comment: What is a technical error?
Answer: The key to practicing slowly is making room for awareness.
It can be detrimental to just play your piece slowly because 'you have to', or because 'it's supposed to be good for you' (like eating vegetables). This can be very boring, wastes practice time and makes you hate your piece little by little.
When practicing slowly your mind has to be active. You have to notice all those little things in your music, how it feels, how it sounds, what it means,... Notice the movement of your hands. Notice how it affects the sound you make. Think about the notes that are coming up. Think actively how you want to play them, and then do it. Think about the place of these notes in the phrase, and the place of the phrase in the piece... Because you are playing slowly there is space in your head to do all of this. In a way it's a very creative moment in your practice time. You are making concious decisions about how you want to play. When you play fast a lot of these decisions are made subconcious because there is no time, or worse when your experience is low: it's at random.
So to answer your question: you need to choose a speed where you can be actively aware of what you are doing.
Or even more specific: take half of the goal speed and try what it does to you. Change to a faster (probably not) or slower speed if needed.
Answer: Slow practice doesn't mean playing the whole piece slowly.
Instead, play the piece first at a normal tempo, and notice which parts you stumble through.  Based on your description I would say that would be about 60 bpm.
Next, play those sections as slow as you need to so that you can play them smoothly and without mistakes.  This may be extremely slow.
Once you've done that, you can work on bringing them up to speed.
Comment: +1 "Slow practice doesn't mean playing the whole piece slowly. " - In fact, you can remove two words from that and it's still true: "*Practice doesn't mean playing the whole piece*".
Answer: Something that took me a long to realise but helped me in the end was to realise that a slow piece of music is still music. Before that I'd seen practising slowly as a tedious mechanical way to get to be able to play fast.
For me,'slow enough' is the speed at which my mind is able to listen to and interpret the music as I play. The notes remain the same but the interpretation can differ every time you play the piece. If you play at a speed that allows you to play, to interpret, and to listen simultaneously then you will naturally slow down to begin with.
Concert soloists can sometimes be heard playing a piece much too fast and that is because they have played it so many times that they can play, hear and interpret very quickly. An audience member however just feels they are being rushed.
So, to sum up, play at a speed at which you are actually producing real music even if that seems incredibly slow. Speeding up will just happen of its own accord.


Small sample sizes and the Kolmogorov-Smirnov test

Question: I have split my data set into four categories but one of them only has four data points in it.
I have run K-S normality tests on the other three categories which are each normal and when the data set is not split into four it is also normal.
For this fourth category, do I assume it is normal, and run a parametric analysis, or assume it is non-normal and run a nonparametric analysis?
This is one of many calculations I have run on the same method using the K-S test for normality but would it be inconsistent for me to suddenly switch to a Shapiro-Wilk test for this one analysis?
Comment: (i) the KS test is for completely specified distributions. It doesn't sound like you have that. (ii) Why are you testing normality?
Comment: The best "test" for a subset with 4 points is likely to be informal. If any of 4 points looks like an outlier with respect to the rest of the data, really watch out and think if that makes sense scientifically. If those 4 points look asymmetric, watch out. If you test it as you tested the other subsets and flag that you know the test is of limited worth, you may cover many of the possible reactions. If you don't test, be prepared for an argument about consistency of method. My own flag is that I never use K-S to test for normality, but look at quantile plots and transform or use a GLM, etc.
Answer: The Kolmogorov-Smirnov (K-S) test can be used to compare other distributions, so if you have enough data in the fourth category, I think you should be able to compare its distribution to the distribution(s) of the data in the other categories.  It seems unlikely that you will have enough power to reject the null with only four data points in the fourth category's distribution though.  I doubt this would provide sufficient power for most NHSTs, but there may be exceptions.
I think you should probably know already if it's safe to assume your four data points in the fourth category were sampled randomly from a normal distribution.  That is, if you don't know that it's safe to assume this for prior theoretical and methodological reasons, it probably isn't safe to assume. However, the degree and manner of deviation from a normal distribution is more important in most cases than the simple, binary outcome of a NHST of your distribution's normality. You may want to consider a related, popular question here on Cross Validated: Is normality testing 'essentially useless'?
Here's a useful quote I found in an answer to that question:

As a rule of thumb (not a law of nature), inference about means is sensitive to skewness and inference about variances is sensitive to kurtosis.

This suggests you might at least wish to test the skewness or kurtosis separately, focus on whichever is more relevant to the subsequent analysis you have in mind, and pay attention to the value of the skewness or kurtosis statistic itself, not just the $p$ value of whatever NHST to which you might've felt obligated to cede inferential authority.
Nonparametric analyses do not assume non-normal distributions.  Most also possess power and reliability that match equivalent parametric tests. Therefore you probably haven't got much to lose by just defaulting to the nonparametric alternative and skipping the normality test entirely. The main tradeoffs are usually computational complexity and the need to provide references due to methodological unconventionality, but all this necessitates are a modern computer and a little extra reading and writing, so it's probably generally advisable to just go for the nonparametric alternative. This depends on what analysis you have in mind though, so you may want to look into the drawbacks of the particular nonparametric alternative you have in mind for yourself.
Last, I don't see how you'd do any additional harm in switching to a Shapiro-Wilk (S-W) test, but if you want to compare its result to those of the K-S tests, I'd say you should also perform S-W tests on those distributions so you have some idea of how the method variance affects your test statistics within each sample distribution. Also, bear in mind that the S-W test is directly contraindicated by many of the answers to the aforementioned question...but I assume many of those objections would apply similarly to a K-S test that references a normal distribution.


RoR projects on linux + developers can't see each other's files?

Question: Can I set up ssh access to my linux box for

few developers working on different RoR and Wordpress&php projects
so they have rw access only to their projects?

if yes, can I make a set up to run svn over ssh without write access to svn repository directory for these developers?
Answer: You can have ssh restrict them to a chroot after login; see the ChrootDirectory directive in man sshd_config.  You'll need to make sure all tools they need are available inside the chroot (there are several chroot tutorials on the net that explain that).
You probably also want to use a Match Group or Match User block in sshd_config then, if you don't want yourself locked into a chroot...
Subversion is a matter of configuring it right and making sure everything needed is available in their chroot.  (You might want to use something like svnserve if you need different access rights for different users.)
Comment: really nice explanation ...
Answer: Yes - set up a separate group for each project and the associated users and make the files associated with this group writeable/executable, not writeable/executable by others. The webserver should access the files/dirs as the 'other' user (so it needs to be readable for others, and also executable if its a directory).
Directories for the project should have the group sticky bit set so that new files / directories are created as owned by that group.
Finally, it'd be good practice to restrict SSH access to these groups you've added.
Comment: but if others can read files that means the each project user can read every other project files, right? I don't want them to be able to read anything but their project files...
Comment: @Radek - you didn't state that was a requirement. There is no way to represent this using the Unix permissions model securely - since all files must be readable by the webserver - therefore while a particular developer cannot read files from another project directly, their code can.


Como rodar um container docker com ownership privado?

Question: Ao utilizar o portainer.io na versão 1.14.2 e listar todos os containers pode-se ver a coluna ownership. Através da interface do portainer é possível modificar para privado e mudar o controle de acesso para administradores ou restrito para algum perfil ou usuário específico. Como posso ao criar o container através da linha de comando e definir que o ownership é privado e para determinado usuário ou perfil?
Answer: Ownership é uma configuração exclusiva do Portainer. O máximo que você consegue fazer nesse tipo de automação é com a utilização de labels, mas o que você consegue sequer é trabalhar sob o aspecto de segurança, você consegue somente esconder containers criados com determinada label/valor.