16 bit artimatic sum in Python

Question: I am working on a program that is creating IRIG106 Chapter 10 data for a cube-sat project. Currently it is being implemented in python and I am having difficulty implementing the final component of the Chapter 10 header.
The way I have implemented it I am currently finding checksum values that are larger than what will fit inside of an integer of the size defined by the specification (2 bytes).
The standard defines the header checksum in section 10.6.1.1 paragraph "J" of the IRIG 106-09 standard. It is defined as the following:
J Header Checksum. (2 Bytes) contains a value representing a 16-bit arithmetic sum of all 16-bit words in the header excluding the Header Checksum Word.
There is also a programming manual provided that has example C code that shows the following (from page A-2-17):
uint16_t I106_CALL_DECL uCalcHeaderChecksum(SuI106Ch10Header * psuHeader)
{
    int iHdrIdx;
    uint16_t uHdrSum;
    uint16_t * aHdr = (uint16_t *)psuHeader;

    uHdrSum = 0;
    for (iHdrIdx=0; iHdrIdx<(HEADER_SIZE-2)/2; iHdrIdx++)
        uHdrSum += aHdr[iHdrIdx];

    return uHdrSum;
}

I have implemented the following in Python using the BitString library:
def calculate_checksum(byte_data: BitArray = None, header_length_bytes: int = 24, chunk_length: int = 16):

    # Set the checksum to zero:
    checksum = 0

    # Loop through the Chapter 10 header and compute the 16 bit arithmetic sum:
    for bit_location in range(0, (header_length_bytes-2), chunk_length):

        # Get the range of bits to select:
        bit_range = slice(bit_location, (bit_location + chunk_length))

        # Get the uint representation of the bit data found:
        checksum += Bits(bin=byte_data.bin[bit_range]).uint

    # Write the computed checksum as binary data to the start location of the checksum in the header:
    byte_data.overwrite(Bits(uint=checksum, length=chunk_length), (header_length_bytes-2*8))

Any thoughts or insights you could provide would be extremely appreciated. I know it should be a simple solution but I am just not able to see it.
--- Update 2 ---
I tried doing both roll over and truncation and they both produced the same result:
test_value = 2**16
test_value1 = test_value + 500
test_value2 = test_value1 % (2**16) -> 500
test_value3 = test_value1 & 0xFFFF -> 500

--- Update 3 ---
When I compare the execution of the python and C checksum functions I have run into the following using these values as an input per the spec:
Sync = "EB25" (2 bytes)
ChannelID = 1 (2 bytes)
PacketLen = 1024 (4 bytes)

When I compare the outputs at each step I see the following:
C:
Header0: EB25
 index =  0 16bit chunk = 60197 checksum = 60197
Header1: 0001
 index =  1 16bit chunk =     1 checksum = 60198
Header2: 0400
 index =  2 16bit chunk =  1024 checksum = 61222
Header3: 0000
 index =  3 16bit chunk =     0 checksum = 61222

Python:
eb25
index:  0 chunk: 60197 checksum: 60197
0001
index:  1 chunk:     1 checksum: 60198
0000
index:  2 chunk:     0 checksum: 60198
0400
index:  3 chunk:  1024 checksum: 61222

Comment: You seem to be mixing up bits and bytes in your code: it seems unlikely that a header that's only 24 *bits* long could usefully contain a 16-bit checksum...  To truncate the sum to 16 bits, use `checksum & 0xFFFF`.
Comment: @jasonharper yes the header length itself is 24 bytes long, I am just not sure from the provided math if the correct method is to truncate it as you say or should it roll over?
Comment: Have you tried taking the checksum of the same string using both of these, and see if they are the same?
Comment: @KennyOstrom I did just try it and the both come up with the same result if I roll over ```(checksum = checksum % (2**chunk_length)``` or if I truncate them ```checksum = checksum & 0xFFFF``` The other option I found out about was bit wise addition with bit carry over but this doesn't seem like what should be done in this case.
Comment: So you're good now, right?
Comment: I just added an update 3 that shows some weird behavior once I hit 32bit (4 byte) parts of the header. while it gets to the same number I am worried about why it is being encoded the way it is as my understanding is a 32 bit int would have the byte position of 7,6,5,4,3,2,1,0 which is how the python represents it by the C appears to be grabbing it in 3,2,1,0,7,6,5,4 which makes no sense to me. Thank you so much for your help!
Answer: So, I know this question is really old, but I had the same issue. The endianess of the packet matters. In a .ch10 file, the packet start is 0x25EB because each section is little endian. Here's how I'm doing everything right now in C-ish code.
// read until the end of the file
while (!atEndOfFile)
{
    // verify that we get teh sync packet
    if ( readNextByte == 0x25 )
    {
       if ( readNextByte == 0xEB )
       {
          // store the sync packet
          byte packetHeader[24];
          packetHeader[0] = 0x25;
          packetHeader[1] = 0xEB

          // grab the rest of the header
          for ( int i = 2; i < 24; j++ )
          {
              packetHeader[j] = readNextByte;
          }

          // grab the check sum from the packet
          uint16 actualCheckSum = (packetHeader[23] << 8) |
                                  packetHeader[22];

          // calculate the checkSum
          uint16 calculatedCheckSum = 0;
          for ( int i = 0; i < 22; i += 2 )
          {
              calculatedCheckSum  += (packetHeader[i + 1] << 8) |
                                      packetHeader[i];
          }

          // verify the calculation
          if ( calculatedCheckSum == actualChecksum )
          {
              printLine( "We calculated the checksum!");
              printLine( "actual checksum: " + actualCheckSum +
                         "calculated checksum" + calculatedCheckSum );
          }
       }
    }
}

I haven't done enough digging into the irig106 library, but I believe that it handles the translation when it reads in a .ch10 file.

16 bit artimatic sum in Python


Sequelize, Validate length of field with blank value

Question: I am using Sequelize as ORM with express.
In Sequelize Model, their is field that accepts the null value. I want to validate this field by defining the length of the input with len if any value is provided.
Code:
field: {
  type: DataTypes.TEXT,
  allowNull: true,
  validate: {
    len: {
      args: [50, 200],
      msg: 'Please provide field within 50 to 200 characters.'
    }
  }
}

But, Sequelize throw error when field is empty. So, How do i allow the empty value, and just validate only when value is provided.
Answer: Have you tried this notEmpty: false ?
field: {
  type: DataTypes.TEXT,
  allowNull: true,
  validate: {
    notEmpty: false,
    len: {
      args: [50, 200],
      msg: 'Please provide field within 50 to 200 characters.'
    }
  }
}


Angular table orderBy column

Question: I try to angular table order By Date Column(descending order).But It doesn't work(Date Column data type is String,in some reason have to get String data type).Please help me.
Sample Data
Trans.Date | Receipt / Ref No | Trx Code | Description | Receipt Amt | Debit     | Credit | Running Balance

2013-08-15 | 000000000001     | OST      |  OST        | 0.00        |  150.00   | 0.00   | 150.00
2013-08-15 | 000000000001     | OTH      |  Amounts    | 0.00        |  8,000.00 | 0.00   | 8,150.00
2013-09-15 | 000000000001     | RNT      |  Rental     | 0.00        |  3,041.00 | 0.00   | 11,191.00
2013-10-15 | 000000000002     | RNT      |  Rental     | 0.00        |  3,041.00 | 0.00   | 14,232.00

Code

        Date
        Receipt / Ref No
        Trx Code
        Description
        Pay Mode
        Receipt Amt
        Debit
        Credit
        Running Balance

        {{objtrn.TRNDATE}}
        {{objtrn.TRNNO}}
        {{objtrn.TRNCODE}}
        {{objtrn.DESCR}}
        {{objtrn.PAYMODE}}
        {{objtrn.TRNAMT | number:2}}
        {{objtrn.DEBIT | number:2}}
        {{objtrn.CREDIT | number:2}}
        {{objtrn.RUNBAL | number:2}}

Comment: Why saying it does'nt work? your sample data looks ordered by date. And with this date format you can get the right order.
Comment: I'm sorry mention it before,i want descending order.
Comment: orderBy:'TRNDATE':true
Comment: Did you try with: | orderBy:'TRNDATE': true | ...
Comment: It's work,Thank You
Answer: Use the reverse argument (see documentation)
The syntax is: orderBy : expression : reverse : comparator
In your case, change your filter to:
orderBy:'TRNDATE':true

Answer: Try this : orderBy:'-TRNDATE'. I did this way for id in reverese manner. So hope it will help you.

Angular table orderBy column


Expectation Conditioned on $\sigma$-subalgebra

Question: In preparing for my upcoming qualifying exam, I have encountered the following problem:

Consider the probability space $(\Omega, \mathcal{F}, \mathbb{P})$ where $\Omega = [0,1]$, $\mathcal{F}$ is the Borel algebra on $\Omega$, and $\mathbb{P}$ is the Lebesgue measure. If $X(\omega) = \max{(\sin{(2\pi \omega)}, 0)}$ and $Y(\omega) = X^2(\omega)$, find the $\sigma$-subalgebra generated by random variable $X$, $\sigma(X)$, and $\text{E}[Y \vert \sigma(X)]$.

The second part of this problem seems quite a bit easier than the first, i.e. finding $\text{E}[Y \vert \sigma(X)]$. Since $Y$ is a function of $X$, random variable $Y$ must be measurable with respect to $\sigma(X)$ and so
$$ \text{E}[Y \vert \sigma(X)] = \text{E}[X^2 \vert \sigma(X)] = \text{E}[X^2 \vert X] = X^2 $$
I have difficulty finding an explicit expression for $\sigma(X)$, however. I understand that for $\omega \in (0,0.5)$ we have $X(\omega) = \sin{(2\pi\omega)}$ and for $\omega \in \{0\}\cup[0.5,1]$ we have $X(\omega)$. This leads me to write
$$ \sigma(X) = \{ \varnothing, \{X \neq 0\}, \{X = 0\} ,\Omega\} = \{ \varnothing, (0,0.5), \{0\}\cup[0.5,1] ,\Omega\} $$
However, I am not very confident in this answer. As a general definition, $\sigma(X)$ is the smallest $\sigma$-algebra on the defined probability space that contains all sets of the form $\{X (\omega) \leq a\}$ for all $a \in \mathbb{R}$. For $a < 0$, this is represented by the $\varnothing$ element, and for $a = 0$ we have $\{0\}\cup[0.5, 1]$, and for $a \geq 1$ we have $\Omega$. For $a \in (0,1)$, should the set be of the form
$$ \{\omega \in \Omega \colon X(\omega) \leq a\} = [0, \tfrac{\arcsin{(a)}}{2\pi}] \cup [0.5 - \tfrac{\arcsin{(a)}}{2\pi}, 1] $$
and then this would replace the $(0,0.5)$ element in the above $\sigma(X)$ expression? Perhaps something of the form
$$ \bigcup_{a \in (0,1)} \left( [0, \tfrac{\arcsin{(a)}}{2\pi}] \cup [0.5 - \tfrac{\arcsin{(a)}}{2\pi}, 1] \right) $$
Am I allowed to have a function of another variable $a$ in my representation of $\sigma(X)$? Any guidance is greatly appreciated!
Answer: Yes, it is certainly fine to have another variable to index the union in your expression for $\sigma(X)$.  The tricky part about trying for such an explicit expression for $\sigma(X)$ is that it's difficult to make it closed under unions.  Instead, it's easier to just work from the Borel $\sigma$-algebra.  Since $X$ is invertible on $(0,\frac 14)$, and $X(\frac 12 - \omega) = X(\omega)$ for $\omega \in (0,\frac 14)$, we have that if $A \in \mathcal{F}|_{(0,\frac 14)}$ then $A \cup (\frac 12 - A) \in \sigma(X)$.  Basically, if we know $X$, we can determine whether or not $\omega$ is in either $A$ or $\frac 12 - A$.  Now, if $X = 0$, then $\omega \in \{0\} \cup [\frac 12,1]$.  Hence,
\begin{align*}
\sigma(X) &= \left\{\{0\} \cup [\frac 12,1],A \cup (\frac 12 - A) : A \in \mathcal{F}|_{(0,\frac 14)}\right\}.
\end{align*}


Converter caracteres especiais para \uxxxx em Python

Question: Eu estou usando uma API que não está aceitando caracteres especiais enviados diretamente no payload JSON (como á, ó, ã...) e preciso converter esses caracteres para \uxxx. Por exemplo "não" -> "n\u00e3o". No Python, ele converte \uxxxx automaticamente para um caractere unicode, mas eu gostaria de fazer a operação inversa e converter, por exemplo, a palavra "não" para "n\u00e3o".
Answer: Se tratando de json especificamente, basta usar o método nativo, json.dumps(), ele já faz o unicode-escape automaticamente, ficando:
import json

payload = json.dumps({
    "chave1": "letra á, letra é, letra í, letra ó, letra ú",
    "chave2": "letra do alfabeto cirílico: ф",
    "array1": ["avião", "a letra ó", "letra do alfabeto cirílico: ф"]
})

print(payload)

Saída:
{"chave1": "letra \u00e1, letra \u00e9, letra \u00ed, letra \u00f3, letra \u00fa", "chave2": "letra do alfabeto cir\u00edlico: \u0444", "array1": ["avi\u00e3o", "a letra \u00f3", "letra do alfabeto cir\u00edlico: \u0444"]}

Funcionará com string também:
import json

y = json.dumps("a letra ó Ó, a letra do alfabeto cirílico: ф")

print(y)

Saída:
"a letra \u00f3 \u00d3, a letra do alfabeto cir\u00edlico: \u0444"

Nota: que a string retornada irá possuir aspas nas extremidades e aspas (double-quotes) também serão escapados

Teste online no ideone: https://ideone.com/NJBTWH
Usando unicode-escape e backslashreplace
É possível usar o unicode-escape, o problema é que ele irá transformar quebras de linha em \n e se esse não for o seu objetivo, pode complicar, mas é possível configurar como deseja tratar a saída com str.encode.
Como pode ver pelo link da documentação, por padrão str.encode(encoding='utf-8', errors='strict') usa encoding='utf-8' e errors='strict', no seu caso você quer que qualquer caractere especial esja "escapado" e caracteres comuns (provavelmente ASCII) sejam mantidos, então deverá usar enconding='ascii', isso fará o str.encode() codificar tudo o que é possível em ASCII, o que não for possível irá causar erro, para isso você deverá tratar os erros com errors='backslashreplace', ele usar a forma hexadecimal do Unicode code point com formatos \xhh \uxxxx \Uxxxxxxxx.
print('Olá mundo! ß, ♬'.encode('ascii', errors='backslashreplace'))

Saída:
b'Ol\\xe1 mundo! \\xdf, \\u266c'

E para tornar em str novamente use o bytes.decode():
print('Olá mundo! ß, ♬'.encode('ascii', errors='backslashreplace').decode())

Aqui pode conferir a diferença dos resultados:
x = '''Olá mundo!
letras: Á á É é Õ õ
outros: ф ß ♬
Emojis:  '''

unicode_escape = x.encode('unicode-escape').decode()

customizado = x.encode('ascii', errors='backslashreplace').decode()

print("unicode_escape:")
print(unicode_escape)

print("\ncustomizado:")
print(customizado)

Saída:
unicode_escape:
Ol\xe1 mundo!\nletras: \xc1 \xe1 \xc9 \xe9 \xd5 \xf5\noutros: \u0444 \xdf \u266c\nEmojis: \U0001f600 \U0001f468\u200d\U0001f469\u200d\U0001f467\u200d\U0001f466

customizado:
Ol\xe1 mundo!
letras: \xc1 \xe1 \xc9 \xe9 \xd5 \xf5
outros: \u0444 \xdf \u266c
Emojis: \U0001f600 \U0001f468\u200d\U0001f469\u200d\U0001f467\u200d\U0001f466

Referencias

Sobre o parâmetro enconding=, leia mais na documentação: https://docs.python.org/3/library/codecs.html#standard-encodings

Sobre o parametro errors=, leia mais na documentação: https://docs.python.org/3/library/codecs.html#error-handlers


How to translate a button?

Question: I have a website in English language and i want to translate some button in own language .
i know that i can add my language and simply translate all my stuff, but the point is i have to translate these buttons like subscribe in Simplenews module in en language.
Here is my step :
i went to config/regional/translate/translate and add my word to translate but i could not do that .
am i missing something ?
Answer: You can use the module String Overrides which allow you to do what you asked for.
(As my low reputation I need to put here some more useless details :-) )
Copied From the module page:
Provides a quick and easy way to replace any text on the site.
Features:
Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
Comment: Thx for your answer man
and useless details :D

How to translate a button?


Microsoft Graph Excel Comments Possible?

Question: I am working on a project where I am using the Microsoft Graph API.
I am trying to dynamically insert comments into an excel document.
I see this can be done from with the Excel JS API: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-comments
However, can this be done from within the Graph API?
I see that we can grab comment info but I don't see anything for adding a comment.
https://learn.microsoft.com/en-us/graph/api/resources/workbookcomment?view=graph-rest-1.0
Has anybody been able to accomplish this?
Thanks,
Brad
Comment: There is no create workbookcomment endpoint. Please raise a feature request in the [Microsoft Graph Feedback Forum](https://microsoftgraph.uservoice.com/forums/920506-microsoft-graph-feature-requests) so that the product team may add this feature in the future.
Comment: Moving this to Answer.
Answer: There is no create workbookcomment endpoint. Please raise a feature request in the Microsoft Graph Feedback Forum so that the product team may add this feature in the future.


Unicode identifiers (function names) for non-localization purposes advisable?

Question: PHP allows Unicode identifiers for variables, functions, classes and constants anyhow. It was certainly intended for localized applications. Wether it's a good idea to code an API in anything but English is debatable, but it's undisputed that some development settings could demand it.
 $Schüssel = new Müsli(T_FRÜCHTE);

But PHP allows more than just \p{L} for identifiers. You can use virtually any Unicode character, except those from the ASCII range (e.g. : is special or \ as that's already used as internal hack to support namespaces.)
Anyway, you could do so, and I would even consider that a workable use for fun projects:
 throw new ಠ_ಠ("told you about the disk space before");

But other than localization and amusement and decorative effects, which uses of Unicode identifiers are advisable?
For example I'm pondering this for embedding parameters into magic method names. In my case I only need to inject numeric parameters, so would get away with just the underscore:
 $what->substr_0_50->ascii("text");
  // (Let's skip the evilness discussion this time. Not quite sure
  // yet if I really want it, but the conciseness might make sense.)

But if I wanted to embed other textual parameters, I would require another unicode character. Now that's harder to type, but if there's one that would aid readability and convey the meaning ... ?
 ->substr✉0✉50->   // doesn't look good

So, the question in this case: Which symbol makes sense as separator for mixed-in parameters in a virtual function name. -- Broader meta topic: Which uses of Unicode identifiers do you know about, or would you consider okayish?
Answer: Just to make it clear: PHP does not support Unicode. And it doesn't support Unicode labels. To be more precise PHP defines a LABEL as [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*. As you can see here, it allows only a small range of characters apart from the typical alphanumeric + underscore. The fact that your Unicode labels are still accepted is only an artifact from the fact, that PHP doesn't have Unicode support. Your special characters are several bytes long in UTF-8 and PHP treats each of these bytes as a separate character and accidentally - with the characters you tried - each of them matched with the \x7f-\xff range mentioned above.
Further reading on that topic: Exotic names for methods, constants, variables and fields - Bug or Feature?
Comment: It's not "accidental" in that UTF-8 encodes all characters after U+007F as multiple bytes in the 0x80-0xFF range.
Comment: Haha okay, PHP5 only allows them accidentially. It's oblivious to wether a character sequence is valid UTF8 or just an L1 byte. The 0x80 byte range is included for future compat..
Answer:
Which symbol makes sense as separator for mixed-in parameters in a virtual function name.

\u2639?

But other than localization and amusement and decorative effects, which uses of Unicode identifiers are advisable?

The biggest hurdle after font support is going to be making the character one that can be typed.  Outside of a macro or copy/paste, unicode characters are not spectacularly easy to enter.  Forcing this upon others is very likely going to violate the "assume the people that work with your code after you are murderous psychopaths that know where you live" rule.
We use unicode characters in only a few comments in our codebase, like
// Even though this is the end of the file and we should get an implicit exit,
// if we don't actually expressly exit here, PHP segfaults.
// ♫ Oh, PHP, I love you. ♫

I think that falls into the "amusement and decorative" category.  Or the "shoot self in head after slaughtering the php-internals team" category.  Pick one.
Anyway, this is not a good idea because it's going to make your code hard to modify.
Comment: I guess that's the actual deal breaker. If you depend on autocomplete driven development or need copy'n'paste for extension, any supposed readability advantage might pale in comparison.


Multiplication law for my semidirect the same?

Question: I constructed my semidirect product and got the multiplication law to be
$$ab = ab^{64}$$
where as in the answers it said it was
$$ba = ab^8.$$
I want to know if my answer was also correct by asking:
1) Does the order of the LHS matter? So if I wrote $ab = ab^8$, would that have been correct?
2) Is $ab^{64} = ab^8$ as it is just $ab^{8^2}$, which could've been constructed with an element of the same order but differen power (if that makes sense?)
Also, I just thought of this question:I managed to get a nontrivial SDP but if I used Sylow theory, I wouldve only got the trivial one. Here is my question:

Construct explcitly a non-commutative semi direct product $H \rtimes Q$ with
$$H = C_{79} \hspace{2cm} Q = C_{13}.$$
You may assume that the least positive integer $k \geq 1$ such that $2^k \equiv 1 \mod 79$ is $k = 39$.

So, using Sylow theory, I would split.... ok, I think I've just talked myself through this. I can't use Sylow theory here becuase the group isn't a $p$ group right? I.e I can't split $79$ into primes, $p$ and $q$ to find a $n_p$  and a $n_q$ right, so I just construct my SDP like normal?
EDIT: Let me clarify the Sylow bit. What I would normally use Sylow theory for would be to split my group $H$ into seperate $p$ subgroups. This would show me exactly how many SDP's I have. I.e if I split it into to subgroups, $n_p$ and $n_q$, I can tell that I have 1 SDP as one of these subgroups will be normal and so with two normal groups, I get my SDP to be trivial.
EDIT 2: Also, one final question: Would my final answer for constructing the SDP be the multiplcation law that I get?
Comment: Is b a member of Q? Remember the orders of your elements
Comment: Yeah, and $a$ is in $H$.
Comment: So what is the order of b then?
Comment: Not all groups are commutative: $ab$ and $ba$ are usually very different things. Similarly, the equations $ab=ab^8$ and $ba=ab^8$ are very different. (The former is actually equivalent to $b^7 = 1$)
Comment: It is a different equation, but it's very close to the correct one which makes me think you wrote something down wrong or operated incorrectly.
Comment: @Mr.Guy The order of $b$ was supposed to be $13$. Here is one thing that I noticed when I was working it out. I wanted to find an element of order $13$ in the group $C_{78}$. So the way I do it is like this: $ 13 = \frac{78}{(k , 78)}$, where the denominator is the gcd of $k$ and 78. Rearranging this gives me $(k, 78) = 6$. So I get an element of order $13$ in $C_{78}$ is $\alpha^6$ ($\alpha$ generates my automorphism group), but in the answers, it says the smallest element of order $13$ in $C_{7}$ is $3$, so if I used $3$, then I wouldve got $ab^8$, but using $6$ gave me $ab^{64}$.
Comment: So the thing I noticed was the $3$ is a divisor of both $6$ and $78$ but its not the GCD is it? That would be $6$.
Comment: So, why would I use 3 instead of 6?
Comment: when finding a generator for $\text{Aut}(C_{79})$ you cannot just take a generator $k$ of $\Bbb Z_{78}$ and use the automorphism $x \to x^k$. it doesn't work that way. you need to find a primitive element of $\Bbb Z_{79}^\ast$.
Answer: Let's use the hint we were given:
If $2$ is of order $39$ in $\Bbb Z_{79}^\ast$ then $8 = 2^3$ has order $\dfrac{39}{(3,39)} = 13$ and thus:
$b \to b^8$ is an automorphism of $\langle b \rangle \cong C_{79}$ of order $13$.
In the semi-direct product $a$ (the element of order $13$) acts on $b$ by conjugation, that is, explicitly, the homomorphism:
$\phi:\langle a \rangle \to \text{Aut}(\langle b \rangle)$ is defined by: $\phi_a(b) = b^8$
If we use the product rule:
$(a,b)*(a',b') = (aa',\phi_{a'}(b)b')$ and identify $\langle a \rangle$ with $\langle a \rangle \times \{e\}$ and $\langle b\rangle$ with $\{e\} \times \langle b \rangle$, we have:
$ba = (e,b)*(a,e) = (a,\phi_a(b)) = (a,b^8) = (a,e)*(e,b^8) = ab^8$
(Note: texts differ on whether the action of conjugation is $b \to a^{-1}ba$ or $b \to aba^{-1}$, so this semi-direct product rule may look slightly different than what you're used to).


Autenticação não funciona após executar o comando make:auth

Question: Executo o comando:
SmartFlex> php artisan migrate

dentro do meu projeto e ele é finalizado corretamente. As opções de login e registro ficam disponíveis na view, mas ao tentar acessar o registro, por exemplo, ocorre o erro abaixo:

NotFoundHttpException in RouteCollection.php line 179:
  in RouteCollection.php line 179
  at RouteCollection->match(object(Request)) in Router.php line 533
  at Router->findRoute(object(Request)) in Router.php line 512
  at Router->dispatchToRoute(object(Request)) in Router.php line 498
  at Router->dispatch(object(Request)) in Kernel.php line 174
  at Kernel->Illuminate\Foundation\Http{closure}(object(Request)) in Pipeline.php line 30
  at Pipeline->Illuminate\Routing{closure}(object(Request)) in TransformsRequest.php line 30
  at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
  at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
  at Pipeline->Illuminate\Routing{closure}(object(Request)) in TransformsRequest.php line 30
  at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
  at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
  at Pipeline->Illuminate\Routing{closure}(object(Request)) in ValidatePostSize.php line 27
  at ValidatePostSize->handle(object(Request), object(Closure)) in Pipeline.php line 148
  at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
  at Pipeline->Illuminate\Routing{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
  at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 148
  at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
  at Pipeline->Illuminate\Routing{closure}(object(Request)) in Pipeline.php line 102
  at Pipeline->then(object(Closure)) in Kernel.php line 149
  at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
  at Kernel->handle(object(Request)) in index.php line 54

Já olhei em diversos post sobre problemas de rota mais nada funcionou.
Answer: Esse erro pode acontecer caso as rotas de autenticação não estejam registradas corretamente no seu arquivo de rotas.
Para confirmar isso, execute o comando abaixo e veja se as rotas referentes a autenticação estão registradas:
php artisan route:list

Na documentação do Laravel podemos encontrar:

Want to get started fast? Just run php artisan make:auth and php
  artisan migrate in a fresh Laravel application. Then, navigate your
  browser to http://your-app.dev/register or any other URL that is
  assigned to your application. These two commands will take care of
  scaffolding your entire authentication system!

Antes de executar php artisan migrate precisamos executar php artisan make:auth.
Por baixo dos panos, temos os seguintes passos que são feitos por esses comandos:

Criação das rotas de autenticação
Nesse passo são incluídas as seguintes rotas no routes/web.php
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Essas rotas apontam para os controllers que são criados junto com a instalação do Laravel em app\Http\Controllers\Auth
Criação das views de autenticação
Aqui são criados os scaffolds das views para login e registros, em resources/views/auth
Tabelas no banco de dados
O comando php artisan migrate vai executar as migrations de banco de dados que estão em database/migrations. O Laravel inclui duas tabelas que são criadas para autenticação, a tabela user e a password_resets.


What is the correct equation of AdaGrad one should use if one aims to use AdaGrad in practice as the automatic way to choose the step size?

Question: I was reading Duchi et al. AdaGrad paper and also a shorter paper on Adaptive Online Gradient Descent because I was looking to implement an update rule which was automatically chosen and that was commonly used in Deep Learning when using stochastic gradient descent such as:
$$ \theta^{(t+1)} = \theta^{(t)} - \eta_t \nabla L(y, f_\theta (x) )  $$
with respect to some loss function $L$.
In that paper I came across a lot of equations, proofs and dense mathematics but I had a hard time extracting a single equation that I could implement in a commonly used data processing program like MATLAB or Octave or python etc.
In my quest to find such an equation I thought I found something promising in optimization lecture by Cambridge University where they had:
$$ w^{(t+1)}_i = w^{(t)}_i - \frac{\eta}{\sqrt{\sum^t_{\tau = 1} g^2_{\tau,i}} } g_{t , u}$$
Where it seems that the step size that they use is:
$$ \eta_t = \frac{\eta}{\sqrt{\sum^t_{\tau = 1} g^2_{\tau,i}} } $$
however, in that lecture they don't really explain in a lot of detail what that equation means and what each term means. From reading the paper on AdaGrad it seems to me that $g_{\tau , i}$ is simply the (sub) gradient at iteration $\tau$ from entry $i$ (i.e. $\frac{\partial f_\tau}{\partial \theta_i}$ at iteration $\tau$ ).
Since the lecture nor the paper seem to explain these well here are my questions:

My question is, where is that equation in the paper? How does one get it? Is that equation the correct update one should use? I just want to make sure that is the correct equation and to possibly derive it myself next time.
What is $\eta$ in $\eta_t = \frac{\eta}{\sqrt{\sum^t_{\tau = 1} g^2_{\tau,i}} } $? Is it another weird constant I need to choose? How does one choose it? (if I could find where this equation was on the paper, I would just reference the paper... but where is it?)
For what application/scenarios is that the correct equation to use? If I have a different network I want to train, how do I change that update rule to suit the network I am training? i.e. how do I adapt it to different scenarios where SGD might be applied?

If someone finds out how to obtain that equation, I'd love to understand how to derive it from the paper or where it came from! :D
Comment: could you please add tag "adagrad", also change "AdaGard" in the title ?
Comment: See [here](https://datascience.stackexchange.com/a/38319/56981) for a general  example of using ADAGRAD to find the third step.
Answer:
The update rule

$$w_i^{(t+1)} = w_i^{(t)} - \frac{\eta}{\sqrt{\sum_{\tau=1}^t g_{\tau,i}^2}}g_{t,i},$$
is the composite mirror descent variety of ADAGRAD.  Take a look at equation 4 (or 23) from the paper.  When there's no regularization term, the update can be derived (take derivative and set to 0) as:
$$ w_{t+1} = w_t - \eta \,\text{diag}(G)^{-1/2} g_t.$$
Notice that $\text{diag}(G)^{-1/2}_{ii} = \frac{1}{\sqrt{\sum_{\tau=1}^t g_{\tau,i}^2}}$ and that multiplying a diagonal matrix by a vector amounts to element-wise multiplication.

$\eta$ is a constant step size which determines the size of the step at each update.  I would try several choices and compare them.
Changing an algorithm from SGD to ADAGRAD just requires plugging in your gradient values.  That is, you need to keep track of the sum of squared gradient elements for the term in the denominator.


How to monitor transaction isolation level changes in SQL Profiler or in any other tool

Question: I've successfully only been able to see transaction isolation level events in the Audit Login event. Are there any other ways to monitor the transaction isolation level changes using SQL Profiler or using some other tool? The reason I ask is because SQL Profiler does not seem to be able to output the events in the right order or it skips events because when setting the IsolationLevel to Serializable in my app it still shows transaction isolation level read committed.
Example Audit Login in SQL Profiler:
-- network protocol: Named Pipes
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level serializable

Answer: I am afraid there isn't one.
Even if there was one, what would you want to see where multiple tables were queried in a join and one or more had NOLOCK which is read uncommitted?
The profiler reports queries at the statement level not the table level so you would have a mix of transaction isolation levels (this is true of the profiler and extended events)
The best you could do is to manually parse the statement start (batch and procedure) and look for the set transaction isolation level.
ed
Comment: For all queries in SQL Profiler would be nice. But in this particular case I would like to see the isolation level in a simple db.Orders.Find(1) query that it is in a BeginTransaction(IsolationLevel.Serializable) using Entity Framework 6.
Comment: I don't think you will get it because even though you are running a statement (SELECT * FROM Orders probably) - to SQL that could be a view with 10 tables underneath with NOLOCK on some tables so different isolation levels
Answer: I found this question while trying to determine why Entity Framework was connecting to our database with the serializable transaction isolation level. As the original answer stated, there is no straightforward way to collect this data either from SQL Trace or Extended Events.
Below is a query to repetitively collect the transaction isolation levels from the sys.dm_exec_sessions and sys.dm_exec_requests DMVs. The tables will grow quickly but are useful for brief tracking of isolation levels from external applications:
SET NOCOUNT ON

IF OBJECT_ID('dbo.Query', 'U') IS NOT NULL DROP TABLE dbo.Query
IF OBJECT_ID('dbo.SessionData', 'U') IS NOT NULL DROP TABLE dbo.SessionData
GO

CREATE TABLE dbo.Query
(
     SessionID INT
    ,StartTime DATETIME
    ,IsolationLevel INT
    ,IsolationLevelName VARCHAR(20)
    ,ObjectName VARCHAR(300)
    ,StatementText VARCHAR(MAX)
    ,QueryPlan XML
)

CREATE TABLE dbo.SessionData
(
     SessionID INT
    ,LoginTime DATETIME
    ,IsolationLevel INT
    ,IsolationLevelName VARCHAR(20)
    ,ProgramName VARCHAR(300)
    ,LoginName VARCHAR(300)
)

WHILE 1=1
BEGIN

    INSERT INTO dbo.Query
    SELECT
         SessionID = req.session_id
        ,StartTime = req.start_time
        ,IsolationLevel = req.transaction_isolation_level
        ,IsolationLevelName =
            CASE req.transaction_isolation_level
            WHEN 1 THEN 'Read Uncomitted'
            WHEN 2 THEN 'Read Committed'
            WHEN 3 THEN 'Repeatable Read'
            WHEN 4 THEN 'Serializable'
            WHEN 5 THEN 'Snapshot'
            ELSE 'Unknown' END
        ,ObjectName = OBJECT_NAME(st.objectid, st.[dbid])
        ,StatementText = SUBSTRING
          (REPLACE
            (REPLACE
              (SUBSTRING
                (ST.[text]
                , (req.statement_start_offset/2) + 1
                , (
                   (CASE statement_end_offset
                      WHEN -1
                      THEN DATALENGTH(st.[text])
                      ELSE req.statement_end_offset
                      END
                        - req.statement_start_offset)/2) + 1)
           , CHAR(10), ' '), CHAR(13), ' '), 1, 512)
           , QueryPlan = qp.query_plan
    FROM sys.dm_exec_requests req
    CROSS APPLY sys.dm_exec_sql_text(req.[sql_handle]) st
    CROSS APPLY sys.dm_exec_query_plan(req.plan_handle) qp
    WHERE ST.[text] NOT LIKE N'%INSERT INTO dbo.Query%'

    INSERT dbo.SessionData
    SELECT
         SessionID = session_id
        ,LoginTime = login_time
        ,IsolationLevel = transaction_isolation_level
        ,IsolationLevelName =
            CASE transaction_isolation_level
            WHEN 1 THEN 'Read uncomitted'
            WHEN 2 THEN 'Read committed'
            WHEN 3 THEN 'Repeatable read'
            WHEN 4 THEN 'Serializable'
            ELSE 'Unknown' END
        ,ProgramName = [program_name]
        ,LoginName = login_name
    FROM sys.dm_exec_sessions
    WHERE security_id <> 0x01
    AND session_id <> @@SPID

END

SELECT *
FROM dbo.Query

SELECT *
FROM dbo.SessionData

Comment: "why Entity Framework was connecting to our database with the serializable transaction isolation level" - Did you find answer?


Remover auto-focus do Edit_text ao colocar windowSoftInputMode="adjustResize"

Question: Eu estou colocando no meu manifest o atributo
windowSoftInputMode="adjustResize" para que o edittext fica acima do teclado
quando ele for ativo. O problema é que ao fazer isso, o auto-focus é ativado no edittext assim que a activity é iniciada. Como posso remover esse comportamento ?
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:id="@+id/frame_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView_hora"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:textSize="18sp"
        android:text="dada" />

    <EditText
        android:id="@+id/editText_hora"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/oval"
        android:padding="8dp"
        android:layout_margin="8dp"
        android:ems="4"
        android:inputType="number" />

    <TextView
        android:id="@+id/textView3"
        android:layout_gravity="center"
        android:textSize="18sp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dada" />

    <EditText
        android:id="@+id/texto_notification"
        android:padding="14dp"
        android:gravity="start"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:background="@drawable/oval"
        android:inputType="textMultiLine" />
    <Button
        android:id="@+id/button"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:text="Cadastrar" />
</LinearLayout>

Answer: Inclua a flag stateHidden na atribuição a windowSoftInputMode:
<application ... >
    <activity
        android:windowSoftInputMode="adjustResize | stateHidden" ... >
        ...
    </activity>
    ...
</application>

Comment: Opa, muito obrigado, funcionou aqui ! vlw vlw.


Angular 1/Ui-router - Pass data from resolve to controller

Question: I want to pass a data (contactName) from the state to the controller by the resolves :
.state({
      name: 'contact.detail.overlay',
      abstract: true,
      component: 'overlayContent',
      resolve: {
        contactName: (originalContact, $rootScope, ContactService) => {
          $rootScope.contactName = ContactService.getContactName(originalContact)
          return $rootScope.contactName
        }
      }
    })

on my state all is correct, contactName is also correct, but it is not accessible in my overlayContent controller, do you have a solution to have $rootScope.contactName access in the controller ?
EDIT :
The controller :
class overlayContentComponent {

  constructor($state, $interpolate, $scope) {
    'ngInject'
    this.$scope = $scope
    this.$state = $state
    this.$interpolate = $interpolate
  }

  /**
   *
   * On initialization hook, let's check if an overlay title
   * has been defined for the current state.
   */

  $onInit() {
    const stateData = this.$state.current.data || { title: '' }
    this.overlayTitle = angular.isDefined(stateData.title) ? this.$interpolate(stateData.title)() : ''
  }
}

export const overlayContentComponent = {
  template: require('./overlay-content.html'),
  controller: overlayContentComponent
}

I can access contactName in my controller by this.$scope.$root.contactName but I would like to avoid $scope.$root by another alternative
Comment: Can you post your controller too please? What error, if any, is showing? Are you using /* ngInject */ in your resolve code, or your angularJS app in general?
Comment: @rrd The post has been modified with some more explanations
Answer: Change your constructor:
constructor($state, $interpolate, $scope, contactName) {
  'ngInject';
  // The variable you want:
  this.contactName = contactName;
  this.$scope = $scope
  this.$state = $state
  this.$interpolate = $interpolate
}

The 'contactName' resolve should be injected now, into the controller for that state (where the resolve resides). This should allow you to access it in the controller, as above.


Quality of model and dropout

Question: I am training my neural network (modified VGG) for solving the problem of 3-class classification. For reaching the best model I am trying to fit slightly different models.
I have some questions about choosing the best model via loss and accuracy plots.
Here are two plots:
First:
Second:
So the questions are:

Am I correctly understand, that in general case, not only in my task, for instance, accuracy plot depending from num of epochs should monotonously increase, but in the end, when num of epochs will be big, accuracy should stuck at some value? Similarly, for loss plot, but in that case, loss should monotonously decrease, but also should stuck at some value?

Which model is better? On the one hand, in first plot, there is no overfitting, but train and validation accuracy are not so big, as in second plot. But in the second plot, we have overfitting.

My last question is about dropout. Here is my classification part of NN:
<code> self._head = nn.Sequential(
 nn.Linear(in_features=7*7*512, out_features=12000),
 nn.ReLU(inplace=True),
 nn.Dropout(),

 nn.Linear(in_features=12000, out_features=6000),
 nn.ReLU(inplace=True),
 nn.Dropout(),

 nn.Linear(in_features=6000, out_features=3000),
 nn.ReLU(inplace=True),
 nn.Dropout(),

 nn.Linear(in_features=3000, out_features=1200),
 nn.ReLU(inplace=True),
 nn.Dropout(),

 nn.Linear(in_features=1200, out_features=600),
 nn.ReLU(inplace=True),
 nn.Dropout(),

 nn.Linear(in_features=600, out_features=num_classes),
 )
</code>
3.1. I heard, that depending on after which layer (conv or linear) I will put the dropout layer,I should assign different values for p. Moreover, this value should increase with num of linear layer. Is it true? What is the rule? Where I can read about it?
3.2. Am I correct, that if I will put larger value for p, say 0.9, the regularization effect will be more, that if p=0.5?
Comment: Please paste your code correctly formatted and not a picture of it
Answer:
Am I correctly understand, that in general case, not only in my task, for instance, accuracy plot depending from num of epochs should monotonously increase, but in the end, when num of epochs will be big, accuracy should stuck at some value? Similarly, for loss plot, but in that case, loss should monotonously decrease, but also should stuck at some value?

There is no reason why an accuracy plot should monotonically increase or a loss plot should monotonically decrease. For some machine learning models and optimization strategies this will hold true (for example logistic regression with Newton's Method and appropriate hyperparameters will converge to the global minimum and therefore the loss and accuracy plots will monotonically converge towards static values). But for a neural network using an optimiser with minibatches and/or momentum this will rarely hold true. Additionally, dropout will also make monotonic convergence unlikely as each batch is trained on a different network subset; you're crippling the network to help it generalise and in doing so its loss and accuracy will oscillate.

Which model is better? On the one hand, in first plot, there is no overfitting, but train and validation accuracy are not so big, as in second plot. But in the second plot, we have overfitting.

Any network will tend towards overfitting given enough epochs, but early stopping can be employed to select the weights from the epoch which has the lowest underfitting and overfitting. Epoch ~65 in the second model appears to have a validation loss similar to the validation loss at the final epoch of the first model. I'd argue that when early stopping is employed both networks perform similarly. The first model is more stable, which is desirable, but the second network is able to more closely fit the training set, suggesting it has a larger capacity to learn which is also desirable. One school of throught for designing good networks is to design a network which can overfit the training data and then you tame the overfitting using regularization techniques and early stopping. It's dangerous for someone to claim one of those two networks is better than the other considering they both display different properties. I'd recommend exploring regularization in the second network.

I heard, that depending on after which layer (conv or linear) I will put the dropout layer, I should assign different values for p. Moreover, this value should increase with num of linear layer. Is it true? What is the rule? Where I can read about it?

There is no 'ideal' value for $p$. Every network is different and different complex architectures can benefit from different amounts and types of dropout. Experiment with various values of $p$ and tune it based on validation set performance. I will say, however, that standard dropout is preferable for dense layers while 2D spatial dropout (dropping channels instead of individual units) is preferable for convolutions.

Am I correct, that if I will put larger value for p, say 0.9, the regularization effect will be more, that if p=0.5?

Absolutely not. Maximum regularization is achieved for $p=0.5$ as described by analysis performed in this paper: http://papers.nips.cc/paper/4878-understanding-dropout.pdf. Increasing the dropout level above 50% can sever too many connections between layers and limit the network's ability to learn.
Additionally, it has been discovered that lower dropout rates around $0.1$ - $0.2$ are preferable for convolutional layers. But, again, there is no 'rule' for optimal dropout, just guidelines for what has worked well for other networks.
Comment: Thank you, @Avelina, for such detailed answer!

Quality of model and dropout


Android Database Sqlite SQLiteException

Question: I have this is the error:
android.database.sqlite.SQLiteException: no such column: COL_1 (code 1 SQLITE_ERROR): , while compiling: SELECT COL_1 FROM registeruser WHERE  COL_2  =?  and  COL_3  =?

and this is my code:
String [] columns={"COL_1"};
        SQLiteDatabase db=getReadableDatabase();
        String selection=" COL_2 " + " =? " + " and " + " COL_3 "+ " =? ";
        String [] selectionArgs={username,password};
        Cursor cursor=db.query(TABLE_NAME, columns, selection, selectionArgs, null,null,null);
        int count=cursor.getCount();
        cursor.close();
        db.close();

Can you please help me?
Comment: Does the table called `TABLE_NAME` have a column called `COL_1` in it? What are the columns of `TABLE_NAME`?
Answer: The reason is obvious. The error message tells you that the table registeruser contains no column COL_1. You cannot retrieve a column that does not exist. Check what are you going to retrieve from the database.
Comment: I suggest you not think about *what needs to be changed*. First think of what do you want from this program - do you want it to select some data? What data? From what table? From what column? Only when you know what you need you can think how to implement it in the code.
Comment: If you want *that the table registeruser to contain a column "COL_1"*, then add this column to this table.

Android Database Sqlite SQLiteException


Classification of users by purchase history

Question: I am fairly new to machine learning and I am learning with a book.
So if I want to classify customers by their purchases, how would that look?
Age and sex would be single features, but what about the purchase history? 1 customer could have 10.000 or more purchases (each article is categorized: electronics, hardware, software, ...) some may only have 1000 or 100.
So my data should look like this
customerId | sex  | age | purchases
-----------|------|-----|-----------
383848     |  w   | 35  | 1234, 49239

and not like this?
customerId | sex  | age | purchase1 | purchase2 | purchase3
-----------|------|-----|-----------|-----------|----------
383848     |  w   | 35  | 1234      | 49239     | null

The examples I have done until now don't cover this - so any pointers are really appreciated.
Comment: Neither choice of representing the data is a good one for most purposes.  For a better and principled approach, consult resources on data modeling and relational databases.
Answer: If you have a finite number of purchase types (electronics, hardware, etc.), you could represent each category as a set of variables describing stuff like:

Total number of purchases in the category
Amount of money spent on this category
Statistics like average price of items bought, maximum price of items bought, etc.
Frequency of purchases
...generally whatever is possible to extract from your data (you did not give any details how this purchase records look like)

This whole process is called feature engineering. I would recommend first generating many such features and perhaps later remove uninformative ones using some feature selection techniques. The second step is not necessary with some classifiers which can learn ignoring uninformative features.
There is no general way how to perform feature engineering: It is an art in itself and every learning task might need different features.


Estrutura aninhada dando erro

Question: Estou tentando criar um script que leia se a pessoa é maior ou menor de idade. Eu gostaria que se por exemplo apenas 1 pessoa for de maior, ela escreva '1 pessoa' e não '1 pessoas', mas meu código tá dando algum erro se todas as pessoas forem de menor ou de maior, mas funciona se eu mesclar. O que pode ser?
from datetime import date
atual = date.today().year
maior = menor = cont = 0
for nasc in range(1, 4):
    cont += 1
    nasc = int(input(f'Ano de nascimento da {cont}ª pessoa:'))
    idade = atual - nasc

    if idade >= 18:
        maior += 1
        if maior != 1:
            p1 = 'pessoas'
        else:
            p1 = 'pessoa'
    else:
        menor += 1
        if menor != 1:
            p2 = 'pessoas'
        else:
            p2 = 'pessoa'

print(f'{maior} {p1} de maior e {menor} {p2} de menor')

Comment: Se todas as pessoas forem maiores que 18 anos (ou menores) não ocorrerá qualquer atribuição à variável p2 (ou p1) mas você considera tais variáveis no print. Assim como inicializou as variáveis maior, menor e cont inicialize também as variáveis p1 e p2.
Comment: Na verdade não precisa dessas variáveis p1 e p2: https://ideone.com/epxCR0
Comment: Muito obrigado!
Answer: Simplifique a lógica, lembre-se que saber se é "pessoa" ou "pessoas" durante o laço é irrelevante já que esta informação mudará a cada execução do laço for.
É uma informação que só interessa na hora da impressão da mensagem, logo...
from datetime import date

atual = date.today().year
maior = menor = 0

for cont in range(1, 4):
    nasc = int(input(f'Ano de nascimento da {cont}ª pessoa:'))
    idade = atual - nasc

    if idade >= 18:
        maior += 1
    else:
        menor += 1

p1 = "pessoa" if maior==1 else "pessoas"
p2 = "pessoa" if menor==1 else "pessoas"

print(f'{maior} {p1} de maior e {menor} {p2} de menor')

Esta estrutura, o p1 = ... if ... else ... é o ternário do Python e faz a mesma coisa que um...
if maior == 1:
    p1 = "pessoa"
else
    p1 = "pessoas"

Só que ocupando apenas uma linha. :-)
Ah, lembre-se que dizemos 0 pessoas e não 0 pessoa!

Estrutura aninhada dando erro


What transformation can I use to enable a relatively unbiased meta-analysis of $\alpha$ reliability?

Question: I want to meta-analyse reliability estimates. For simplicity, assume the reliability estimate in question is Cronbach's $\alpha$ (aka Guttman's $\lambda$-3). Various packages exist to do meta-analyses in general (e.g. the R 'meta' package), but do not seem to have an option for reliability. However, reliability estimates will not be distributed normally because they are capped at a maximum of 1, so treating them as normally distributed will introduce a bias.
A solution for the analogous problem for correlations is to use Fisher's r to z transformation.
So, what transformation can be performed on $\alpha$ to enable meta-analysis?
Note that this question is in many ways equivalent to asking, 'What is an approximate sampling distribution from which reliability estimates are drawn?'
EDIT:
The question was based upon the false assumption that there were no R packages that enabled meta-analysis of $\alpha$. This is not true (see my answer and @Wolfgang's comment), but may still be useful for anyone trying to understand how the transformation is performed.
Comment: There are articles about meta-analysing Cronbach's $\alpha$ but I am not familiar enough with $\omega$ to tell if they generalise.
Comment: No transformation is going to turn a bounded variable - with data at the bounds - into one that is normally distributed.
Comment: @mkt Are you familiar with Fisher's r to z transform? It turns a correlation (bounded by -1 and 1) into a z-score. It doesn't quite work perfectly as a correlation of 1 or -1 become infinite, but it is quite rare to get perfect correlations (and even rarer to get reliabilities of 1).
Comment: @mdewey Thanks. I wonder if I should have asked this first as a question about alpha and then asked a separate follow up question about whether such a response would generalise to other measures of reliability.
Comment: That's why I added the caveat about having data at the bounds. Perhaps that's not an issue for you, but it seemed implied by '*capped at a maximum of 1*'.
Comment: Ah, I see. Thanks for the clarification. It's not an issue in my case.
Answer: EDIT:
In fact, there is an R package that will do an appropriate transformation: the 'metafor' package. Details can be found at wviechtb.github.io/metafor/reference/escalc.html. Search for "Cronbach's alpha" for the appropriate section. Credit to @Wolfgang for this information.
ORIGINAL ANSWER:
Rodriguez and Maeda (2006)[1] offer a solution. They note that the ratio $$(1-r_\alpha)/(1-\rho_\alpha)$$ is an F distribution with degrees of freedom = $(n-1)$ and $(J-1)$, where $r_\alpha$ is the sample $\alpha$, $\rho_\alpha$ is the population $\alpha$, and J is the number of items[2,3]. Thus, "a nonlinear monotonic normalizing transformation of the sample coefficient alpha [is]: $$T_i=(1-r_\alpha)^{1/3}$$[4]
They point out that this transformation is biased, but it is less biased than Fisher's r to z transformation (and is also less biased than ignoring this issue entirely). They further note that the bias in Fisher's transformation is usually ignored[1,4], so (my interpretation) it is probably ok to ignore here as well.
Therefore, using this transformed $\alpha$ coefficient, the weighted mean transformed alpha can be computed with the formula: $$\overline{T}=\Sigma w_i T_i/\Sigma w_i$$ where $w_i=1/v_i$ and $$v_i=\frac{18J_i(n_i-1)(1-r_{\alpha i})^{2/3}}{(J_i-1)(9n_i-11)^2}$$ (See Hakstian & Whalen, 1976[4] for a derivation of this formula).
The variance of $\overline{T}$ is $\overline{v}=1/\Sigma w_i$ with a standard error of $\sqrt{\overline{v}}$, enabling calculation of a confidence interval.
These values can be transformed back into $\alpha$ with the formula: $$\hat{\rho}_\alpha=|1-\overline{T}^3|$$
where $\hat{\rho}_\alpha$ is the estimate of $\rho_\alpha$.
Rodriguez and Maeda[1] provide SPSS syntax to calculate these values, which may be helpful in creating code in your statistics program of choice.
References
[1] Rodriguez, M. C., & Maeda, Y. (2006). Meta-analysis of coefficient alpha. Psychological Methods, 11(3), 306–322. https://doi.org/10.1037/1082-989X.11.3.306
[2] eldt, L. S. (1965). The approximate sampling distribution of Kuder-Richardson reliability coefficient twenty. Psychometrika, 30(3), 357–370. https://doi.org/10.1007/BF02289499
[3] Kristof, W. (1963). The statistical theory of stepped-up reliability coefficients when a test has been divided into several equivalent parts. Psychometrika, 28(3), 221–238. https://doi.org/10.1007/BF02289571
[4] Hakstian, A. R., & Whalen, T. E. (1976). A K-Sample Significance Test for Independent Alpha Coefficients. Psychometrika, 41(2), 219–231.
Comment: As for R, see: https://wviechtb.github.io/metafor/reference/escalc.html and search for "Cronbach's alpha".
Comment: @Wolfgang Thanks! Would've been a whole lot easier if I'd found that first! But it's good to dig into the details of things sometimes.


C# set ComboBox DropDownList default value OR loop through all CheckBoxes

Question: I have multiple ComboBoxes in my WinForms application, which all use the DropDownList style. They don't have a default value selected, and I want them to all have their first value show up automatically without the user having to select anything.
At first I tried setting each ComboBox's selectedValue by doing:

ComboBox1.SelectedIndex = 0;

But I wasn't sure where to put this code. Ideally, it would be executed once when each ComboBox is initialized, but I don't know if this is possible.
Then I thought I could put the code into the entire Form's load method:

private void GUI_Load(object sender, EventArgs e)
{
    ComboBox1.SelectedIndex = 0;
    ComboBox2.SelectedIndex = 0;
}

This works but this gets annoying as the number of ComboBoxes gets large. So I thought of looping like so:

private void GUI_Load(object sender, EventArgs e)
{
    foreach (Control c in this.Controls)
    {
        if (c is ComboBox)
        {
            ComboBox combo = (ComboBox)c;
            combo.SelectedIndex = 0;
        }
    }
}

This wouldn't work for some reason; the only Controls it looped over were only Panels and nothing else.
What am I doing wrong with this loop? What is the best solution here?
Comment: try something like this:

[How to get ALL child controls of a Windows Forms form of a specific type ]: http://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button
Comment: Your controls are contained within panel(s). Check if c is Panel and then iterate though child controls of the panel(s).
Comment: Clean and simple @MikkoViitala! Thanks.
@Dani So is the only way to get all child controls through recursion?
Answer: ///
/// For use with Windows Forms
///
/// <typeparam name="T"></typeparam>
/// <param name="controlCollection"></param>
/// <param name="resultCollection"></param>
public static void GetControlsRecursiveWin<T>(System.Windows.Forms.Control.ControlCollection controlCollection, List<T> resultCollection) where T : System.Windows.Forms.Control
{
    foreach (System.Windows.Forms.Control control in controlCollection)
        {
            if (control is T)
                resultCollection.Add((T)control);

            if (control.HasChildren)
                GetControlsRecursiveWin(control.Controls, resultCollection);
        }
}

usage:
List<ComboBox> lstDDL = new List<ComboBox>();
GetControlsRecursiveWin<ComboBox>("<name of yourpanel>".Controls, lstDDL);

This will produce a list of all controls of type ComboBox within that control. Then you can iterate and set these controls to a desired value.


CSS3 multi-column layout converting to PDF using snappy (wkhtmltopdf wrapper)

Question: I'm trying to generate 3 column PDF (using barryvdh/laravel-snappy - wkhtmltopdf).
Because the text which is going to fill these columns is of unknown length I have to use some mechanism allowing the text fill the columns freely.
So I tried to use this CSS:
.threecol {
            -webkit-column-count: 3; /* Chrome, Safari, Opera */
            -moz-column-count: 3; /* Firefox */
            column-count: 3;
        }

This works great on a web page but I can't convert it to PDF. It doesn't show any errors. It simply converts the page with one column.
Any suggestions?
Is what I want possible to do with wkhtmltopdf?
Or maybe should I use some other library?
Comment: I was also trying TCPDF which can interpret HTML with method WriteHTML(). But it doesn't work too...
Comment: What does "can't convert" mean? Is wkhtmltopdf throwing an error, or isn't the text distributed between the columns?
Comment: "can convert" means that the PDF doesn't have 3 columns but only one like the css was not there. No error is generated.
Comment: Have you tried giving it a fixed width, to avoid sizing problems with the viewport?
Comment: No I haven't. But it just looks like the column thing was ignored. All the text is there and everything seems to be OK except the text is in one not 3 columns. The question is whether wkhtmltopdf can do it but I do something wrong or it's just impossible. And maybe there is any other way to do this what I need.
Comment: Did you sort this out?  I have tried to convert a bootstrap 4 column grid to pdf using wkhtmltopdf, and mine has just output in 1 column as well
Comment: Any luck ever since?
Comment: Nothing unfortunately :(
Answer: This feature isn't available in the Webkit version used in wkhtmltopdf. Looks like we have to use tables, with manual flow.
Comment: Can you show what a table with manual flow would look like (in the code)?
Answer: I'm two years late but hopefully this is helpful for someone. After a couple days searching the net and trying to get a multi-column / multi-page pdf going with Wkhtmltopdf this is what I came up with... works great and I haven't seen the solution around. It requires each column having a set width and height. The columns are cloned, it's contents position are offset to show the next span of text. Repeat until the entirety of the content has been displayed.
https://jsfiddle.net/pa2k6wj5/1/
HTML

            (longform text goes here...)

CSS
.column {
    position: relative;
    width: 3in;
    height: 5in;
    display: inline-block;
    overflow: hidden;
    vertical-align: top;
}
.content {
    width: 3in;
}

JS
// get elements
var parent = document.querySelector('.parent');
var column = document.querySelector('.column');
var content = document.querySelector('.content');

// calculate height values of column and it's content
var columnHeight = column.offsetHeight;
var contentHeight = content.offsetHeight;

// create an array of offset values
var offsetValues = [];
for (var i = columnHeight; i < contentHeight; i+= columnHeight) {
    offsetValues.push(i);
}

// create a new column for each offset value
offsetValues.forEach( function(offsetValue, i) {

    // init clone and add classes
    var cloneColumn = document.createElement('div');
    var cloneContent = document.createElement('div');
    cloneColumn.classList.add('column');
    cloneContent.classList.add('content');

    // populate the DOM
    cloneContent.innerHTML = content.innerHTML;
    cloneColumn.appendChild(cloneContent);
    parent.appendChild(cloneColumn);

    // apply position and offset styles
    cloneContent.style.position = 'relative';
    cloneContent.style.top = '-' + offsetValue + 'px';
});

Answer: try this brother.. :)
answer from docs: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1872#issuecomment-50742814

/* docs: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1872#issuecomment-50742814 */
.container-two-row {
  /* You *must* define a fixed height which is
     large enough to fit the whole content,
     otherwise the layout is unpredictable. */
  height: 28em;
  /* Width and count aren't respected, but you
     have to give at least some dummy value (??). */
  -webkit-columns: 0 0;
  /* This is the strange way to define the number of columns:
     50% = 2 columns, 33% = 3 columns 25% = 4 columns */
  width: 50%;
  /* Gap and rule do work. */
  -webkit-column-gap: 1px;
  -webkit-column-rule: 1px solid black;
  text-align: left;
}
.height-35em{
  height: 35em;
}
.mt-15{
  margin-top: 15px;
}

            An Article

            1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
            cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
            proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

            2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
            cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
            proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

            3. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
            cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
            proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

            4. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
            consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
            cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
            proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Answer: I don't have any problem to generate a PDF with multicolumns with Snappy.
In your class, try to add a width property like this :
.threecol {
        -webkit-column-count: 3; /* Chrome, Safari, Opera */
        -moz-column-count: 3; /* Firefox */
        column-count: 3;
        /* This is the strange way to define the number of columns:
        50% = 2 columns, 33% = 3 columns 25% = 4 columns */
        width: 33%;
    }


Finding root for the segment - found the formula but it doesn't work for some values - wrong formula?

Question: I have the segment, defined as $(x_1, y_1)$, $(x_2, y_2)$.
I know that $y_1\ge  0$ and $y_2 < 0$.
I want to compute the root point for that segment.
I decided to do it that way:
we know that:

$(x_2-x_1)(y-y_1) = (y_2-y_1)(x-x_1)$
after some operations:

$y = \frac{(y_2-y_1)}{(x_2-x_1)}x + \frac{-x_1\cdot y_2 + x_2\cdot y_1}{x_2-x_1}$
So simply, I get the line as $y = ax + b$ where:
$a = \frac{(y_2-y_1)}{(x_2-x_1)}$
$b = \frac{-x_1\cdot y_2 + x_2\cdot y_1}{x_2-x_1}$
To compute root point, I just compute $f(0)$, which is equal to $b$ in my example (for $y_1 \ge  0$ and $y_2 < 0$):
$y_0 = \frac{-x_1\cdot y_2 + x_2\cdot y_1}{x_2-x_1}$
I tested my solution for:
$(x_1, y_1) = (1, 2)$
$(x_2, y_2) = (4, -1)$
RESULT: 3

And it's ok. But for:
$(x_1, y_1) = (4528, 498)$
$(x_2, y_2) = (5527, -1500)$
RESULT: 9554

Which is WRONG. The root point of segment from $x_1$ to $x_2$ ($y_1 \ge  0$ and $y_2 < 0$) cannot be after $x_2$.
So is my formula wrong?
Comment: Than it is not $b$, $b$ is the $y$ of the point where $x=0$.

Indeed, given the line $y=ax+b$, the intersections with the axis are given by the points $(0,b)$ and $(\frac{-b}{a},0)$.

Please note that *not* every line can be written in that form.
Comment: What do you mean with "root point of a segment"? Anyway what you did does not work in the case $x_1=x_2$...
Comment: I mean the root point for the line that contains the segment ($x_1$,$y_1$ $x_2$,$y_2$). Precisely: the x value for the point of that line where y = 0. And anyway, I wrote that $y_1$>=0 and $y_2$<0 so $x_1$ is NEVER equal $x_2$ (same point does not have two y values)
Answer: $b$ should be
\begin{equation*}
b=-\frac{y_{2}-y_{1}}{x_{2}-x_{1}}x_{1}+y_{1}=\frac{-x_{1}y_{2}+x_{1}y_{1}}{%
x_{2}-x_{1}}+y_{1},
\end{equation*}
because from
\begin{equation*}
(x_{2}-x_{1})(y-y_{1})=(y_{2}-y_{1})(x-x_{1})
\end{equation*}
we get
\begin{eqnarray*}
y-y_{1} &=&\frac{y_{2}-y_{1}}{x_{2}-x_{1}}(x-x_{1}) \\
&\Leftrightarrow &y=\frac{y_{2}-y_{1}}{x_{2}-x_{1}}(x-x_{1})+y_{1} \\
&\Leftrightarrow &y=\frac{y_{2}-y_{1}}{x_{2}-x_{1}}x-\frac{y_{2}-y_{1}}{
x_{2}-x_{1}}x_{1}+y_{1} \\
&\Leftrightarrow &y=ax+b,\qquad a=\frac{y_{2}-y_{1}}{x_{2}-x_{1}},b=-\frac{
y_{2}-y_{1}}{x_{2}-x_{1}}x_{1}+y_{1}.
\end{eqnarray*}
ADDED in response to OP's comment. For $(x_{1},y_{1})=(4528,498),(x_{2},y_{2})=(5527,-1500)$ we have $a=-2$ and
$b=9554$. So
\begin{equation*}
y=-2x+9554
\end{equation*}
and
\begin{equation*}
-2x+9554=0\Leftrightarrow x=4777.
\end{equation*}
Comment: Just checked it, and yes, again my mistake. Anyway I marked Claude Leibovici's respond as answer, because he first showed me the place where I was wrong. Sad thing that I cannot mark two answers, but I have voted up your post. Thank you for help :)
Comment: I see and agree with transformations. But when I use the values $(x_1,y_1) = (4528,498), (x_2,y_2) = (5527,−1500)$ the calculated $b = -\frac{y_2-y_1}{x_2-x_1}x1+y1 = 9554$ (same as in my formula). So what's wrong now? The $x_0$ must be between 4528 and 5527, not 9554.
Comment: @PolGraphic See my edit to add the computation of $x_0=4777$.
Comment: Glad to help! Your first mistake was in the computation of $b$.
Answer: You made a mistake in the reasoning. Your equation is $y=a x + b$. Since you want $y=0$ and you look for $x$, then $$x=-\frac{b}{a}=\frac{{x_2} {y_1}-{x_1} {y_2}}{{y_1}-{y_2}}$$
Comment: You are welcome. This is the kind of mistakes I did loooong time ago and they were making me just crazy. Cheers.


Characteristic polynomial of a tridiagonal matrix

Question: Consider the polynomial recurrence
$$p_{k+1} (x) = (x - \alpha_{k+1})p_k(x) - \beta^2_{k+1}p_{k-1}(x), \quad (k=0,1,\ldots)$$
where $p_0 = 1$, $p_{-1}=0$, and $\alpha_k$ and $\beta_k$ are scalars.
Show that the roots of $p_k(x)$ are the eigenvalues of the below tridiagonal matrix
$$J_k = \begin{bmatrix} \alpha_1 & \beta_2 & & & \\
\beta_2 & \alpha_2 & \beta_3 & & & \\
& & \ddots & & \\
& & \beta_{k-1} & \alpha_{k-1} & \beta_k \\
& & & \beta_k & \alpha_k
 \end{bmatrix}$$
Answer: I think the recurrence relation should be
\begin{eqnarray}
p_{k+1}=(\alpha_{k+1}-x)p_k(x)-\beta_{k+1}p_{k-1}(x), p_0=\beta_2, p_1(x)=\alpha_1-x
\end{eqnarray}
The recurrence relation can be obtained by the cofactor expansion of $J_{k+1}-xI_{k+1}$ along the last row (or column).
Comment: Actually, the OP was almost right, the only correction is that $p_0=1$, which I've now edited to fix. Your version does not work. (This is an old question & answer, but it came up in search when I was looking just for this, so I'm commenting to prevent confusion for others in the future).


how to make unsortable header colmn in theme_table drupal 6

Question: I m using Drupal 6
I m using pager_query and theme_table
How can I make any column unsortable, by default it is making all columns sortable
$tableHeader = array(
        array('data' => ''),
        array('data' => 'Article','field' => 'a.title'),
        array('data' => 'From date','field' => ''),
        array('data' => 'To date','field' => ''),
        array('data' => 'Perpetual','field' => ''),
        array('data' => 'Access type ','field' => ''),

        );

here first column shows check boxes along each row so don't want this column sortable
Thanks
Answer: Looking at the code for tablesort_header the sortable stuff is only added if the particular header item is an array. So you can cancel off certain columns by just setting the header to a string, e.g.:
$tableHeader = array(
  'This colum header is not sortable.',
  array('data' => 'Article','field' => 'a.title'),
  array('data' => 'From date','field' => ''),
  array('data' => 'To date','field' => ''),
  array('data' => 'Perpetual','field' => ''),
  array('data' => 'Access type ','field' => ''),
);


Binary Sequences and Combinatorics

Question: I have the following problem:
Consider binary sequences of length $n$. We know there are $2^{n}$ of them. Now I take $2^{n-2}$ of them (except the zero sequence). If we take only 2- sums can we generate the remaining sequences ?.
Example: $n =4$. Take 4 of them. Lets take
$(1000),
(0010),
(1001),
(0100),$
The possible 2 - sums are
$(1000) + (0010) =(1010), (1000) + (1001)=(0011), (1100), (1011), (0110), (1101).$
Here I dont have enough sums to generate all the remaining sequences.
What about this in general. My guess says that it is not possible.
Any hints towards this will highly be appreciable.
Edit:The problem can be reformulated as taking any set with $n$ elements. Take $2^{n-2}$ non - empty subsets. Can we obtain all the remaining subsets by the 2 - symmetric differences of these elements. By 2 - symmetric I mean the symmetric difference of two subsets from our list.
Comment: There are $2^{n-1}$ binary sequences that do not have the first bit set. If you choose your $2^{n-2}$ sequences from those, no combination of them will ever produce a sequence with its first bit set, even if you add more than 2 together.
Comment: Presumably you can say $(1000)+(1000) =(0000)$ but that only adds $1$ or at most $2^{n-2}$ to your answer
Comment: By adding we can get some more. My question is how many more can we get ? Ofcourse zero at the end can be obtained in that way.
Comment: If you had started with $(1000),(0100),(0010),(0001)$ and could reuse outputs then you can get everything.  If you had started with $(1110),(1100),(1010),(1000)$ then you cannot generate $(0001)$ or anything ending in $1$.  Similarly for other $n>4$
Comment: We can not get everything as I have written I have 4 of them and 2- sums are only 6 so maximum 10 can possibly be obtained but there are $15= 2^{4} -1$. When n = 5 we take 8 of them and 2 - sums are ${8 \choose 2} = 28$ so total 36. It seems we can get all of the $2^{5} - 1$ but I guess this is not possible and that is what my question asks why and how.
Comment: I'd suspect it's possible for large $n$ (given that you get to choose the "generators"), since the number of pairs is asymptotically $2^{2n}$.
Comment: @Milten the number of pairs are only ${ 2^{n-2}\choose 2}$ since we want to use only 2 - sums.
Comment: @Mathslovershah My mistake. It's $\Theta(2^{2n})$ and asymptotic to $2^{2n-5}$. My point is just that it dominates $2^n$, but it's all of course just a heuristic.
Comment: Yes for $ n > 5$ it domintes $2^{n}$ but It seems alot of elements are repeating in the sums. But the proof might not be easy.
Answer: Partial result using probabilistic methods (but the result is deterministic). I claim that, for any $n$, you can choose the generators so that the pairwise sums will miss at most $31$ of the target binary sequences.
I'll use $\oplus$ for the XOR sum. Let $X_1,\ldots,X_k$ be $k=2^{n-2}$ bit-strings chosen independently uniformly at random (the "generators"). I claim that the $m=\binom k2$ pairwise sums $Y_{ij} := X_i \oplus X_j$, $i\ne j$, are uniformly distributed and pairwise independent. We have
$$
\newcommand{\P}{\mathbb P}
\newcommand{\E}{\mathbb E}
\newcommand{\V}{\mathbb V}
\P(Y_{ij} = y) = \sum_{x}\P(X_j = y \oplus x) \P(X_i = x) = 2^{-n},
$$
proving that they're uniform. It's clear that $Y_{ij}$ and $Y_{kl}$ are independent for $i,j,k,l$ distinct. In the case $l=i$, we have
$$ \begin{split}
\P(Y_{ij} = y_1 \wedge Y_{ik} = y_2)
&= \sum_{x}\P(X_j = y_1 \oplus x \wedge X_k = y_2\oplus x) \P(X_i = x) \\
&= \sum_{x}\P(X_j = y_1 \oplus x) \P(X_k = y_2\oplus x) \P(X_i = x) \\
&= 2^{-2n},
\end{split} $$
proving pairwise independence. Note that they're not 3-independent though, as $Y_{ij} \oplus Y_{ik} = Y_{jk}$.
Now let $I_{ij}^y$ be the indicator variable of the event that $Y_{ij}=y$, and let $I^y = \sum_{i<j}I_{ij}^y$. Let $J^y$ indicate that $I^y=0$, i.e. that we miss $y$. Let $p=2^{-n}$. We have $\E I^y = mp$ and $\V I^y=mp(1-p)$ (here we use pairwise independence). Using Cantelli's inequality (the one-sided version of Chebyshev), we get
$$
\E J^y
= \P(I^y = 0)
\le \P(I^y-\E I^y \le -\E I^y)
\le \frac{\V I^y}{\V I^y + (\E I^y)^2}
= \frac{1-p}{1-p+mp}.
$$
Note that $m=2^{2n-5} - 2^{n-3}$, which gives us
$$
\E(\textrm{number of misses})
= \E\left(\sum_y J^y\right)
\le 2^n \frac{1-p}{1-p+mp}
< 32
$$
for all $n$. Since the expected number of misses is $<32$, there must exist some choice of the $X_i$'s that has $\le 31$ misses.
Note that if we had used Chebyshev instead of Cantelli, we would get the weaker result of $\le 32$ misses for $n\ge 8$.
By the way, here are the bounds way get for each $n$:
$$
\begin{array}{c|c}
n&1&2&3&4&5&6&7&8&9&\ge10 \\
\hline
\textrm{Bound}&(2)&(4)&7&11&16&22&26&28&30&31 \\
\hline
\textrm{Bound}/2^n &(1)&(1)&.86&.69&.50&.34&.20&.11&.059&\to0
\end{array}
$$
Comment: I highly appreciate your effort and the result. Although I cant understand this probabilistic approach. But it seems that for bigger $n$ we can have this equal to zero and hence we can fine a set which generate all of the elements ?
Comment: The point of the method is that, if the average number of misses with random samples is some value, then there must be a possible sample with at most that value (and also a sample with at least that value) - otherwise the average would be larger (or lower). Unfortunately my bound approaches $32$ as $n\to\infty$, so we can't get anything better from this analysis.
Comment: @Mathslovershah Just for completion, I made a table showing the exact bound I get for each $n$. I also wanna add that this result really makes me think the problem is possible, since we are able to miss so few (a constant bound!) for any $n$. Unless of course I messed up somewhere.
Comment: Ok may be that we also check if how much the repetition occurs in the sums values.
Comment: Also what if the we take normal carry addition in binary sequences instead of XoR. My guess was that the repetitions also occur so often that we miss some value. Also every number can be written as binary sum ($ 37 = 2^{5} + 2^{2} + 2^{0}$) so when we take a smaller set we must have alot of repetitions. But for bigger $n$ this might not be the case.

Binary Sequences and Combinatorics


Imprimir Alert PHP

Question: Bom pessoal como consigo imprimir o conteudo de algo do php em uma div por exemplo :
tenho uma area de login , se os dados do usuario estiverem errado quero que imprima na tela uma div com alert (com bootstrap) na mesma pagina .
tenho essa validação no php mas quero que me mostre em uma div
segue codigos
login
         <form class="login-form" method="POST" action="pg/logar.php">
  <input required type="text" name="f_usuario" placeholder="Usuario"/>
  <input required type="password" name="f_senha" placeholder="Senha"/>
  <button type="submit">Logar</button>

logar.php
     if($linhas > 0){
    $_SESSION['usuario'] = $usuario;
    $_SESSION['senha'] = $senha;
    header("Location:../logado.php");
   }else{
    echo "Dados Digitados Incorretos";
   }

Comment: Caso sua pergunta seja diferente da indicada no fechamento, você pode clicar em [edit] e acrescentar partes relevantes que diferenciem o problema. Se realmente forem problemas com soluções diferentes das apontadas no link, pode editar e deixar um comentário para considerarmos a reabertura na pergunta.
Answer: Tente assim:
echo '
Dados Digitados Incorretos
';

Comment: eu preciso que da minha função logar ele envie Dados digitados incorretos para uma div alert na pagina de login
Comment: Bem, se eu entendi são duas paginas diferentes: uma html, e a outra php. Se você quer que o alert da sua pagina php seja mostrado no seu html fica meio complicado. O que você pode fazer a criar a pagina que você quer que receba o echo, em php ao invés de html, e fazer o require do seu php... assim quando der o erro o alert vai ser exibido normalmente como uma div como na resposta...

Imprimir Alert PHP


Question about composite mapping (matrices operations)

Question:
Let $T: V\rightarrow W$ and $U:W \rightarrow Z$ be linear mappings, and let $A= [U]^\gamma_\beta$ and $B=[T]^\beta_\alpha$, where $\alpha$={$v_1,v_2,...v_n$}, $\beta$= {$w_1,w_2,...,w_m$}, and $\gamma$={$z_1,z_2,...,z_p$} are ordered bases for V,W, and Z. Define the product AB of two matrices so that $AB$=$[UT]^\gamma_\alpha$. Consider $[UT]^\gamma_\alpha$. For 1 $\leqq$ j $\leqq n$, we have

My Question is for U($\sum_{k=1}^m B_{kj} w_k$), since the matrix operation is row by column, B is a m by n matrix, $w_k$ has m elements, somehow I don't get this operation.
Answer: Well, $U$ is a linear operator and so $U(\sum_k B_{kj}w_k) = \sum_k B_{kj}U(w_k)$.
Answer: Actually, $\sum_k {B_{kj}w_k}$ is the defintion of matrix representation ,from which we could get the jth column of the matrix $B$. Map the jth vector in the basis for V and then express them by the ordered basis in W. The coefficents of the linear combination are the jth column of B.


Component is somehow rendering despite conditional statement

Question: On my Home component, on initial load, I loop through an object of URLs, and use Promise.all to make sure they all resolve at the same time. I construct an object, and push it into state. At the start of this I have loading: true, then set to false when done pushing that object into state:
Home Component:
class Home extends Component {
  state = {
    searchTerm: null,
    movies: {
      trending: {},
      topRated: {},
      nowPlaying: {},
      upcoming: {}
    },
    loading: false
  };
componentDidMount() {
    this.getInitalMovies();
  }
getInitalMovies = () => {
    const API_KEY = process.env.REACT_APP_API_KEY;
    //set loading to true
    this.setState({ loading: true });
    //create an object with all movie URLs
    const allMovieURLs = {
      trending: `https://api.themoviedb.org/3/trending/movie/day?api_key=${API_KEY}`,
      topRated: `https://api.themoviedb.org/3/movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`,
      nowPlaying: `https://api.themoviedb.org/3/movie/now_playing?api_key=${API_KEY}&language=en-US&page=1`,
      upcoming: `https://api.themoviedb.org/3/movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`
    };

    //break down the movieURL object into entries, fetch the URL, and reassign entries with actual data
    //encapsulate within a Promise.all to ensure they all resolve at the same time.
    const moviePromises = Promise.all(
      Object.entries(allMovieURLs).map(entry => {
        const [key, url] = entry;
        return fetch(url).then(res => res.json().then(data => [key, data]));
      })
    );
    //with the returned promise from Promise.all, reconstruct the array of entries back into an object with relevant key pair values
    const movies = moviePromises.then(movieArr => {
      const dataObj = {};
      for (const [movie, movieData] of movieArr) {
        dataObj[movie] = movieData;
      }
      return dataObj;
    });
    //with the returned object, push it into current state, then turn off loading
    movies.then(movieObj =>
      this.setState({ movies: movieObj, loading: false })
    );
  };
 render() {
    const { movies } = this.state;
    return (

        <HeroImage />
        {this.state.loading ? <Loader /> : <MovieDisplay movies={movies} />}

    );
  }

MovieDisplay Component:
export default class MovieDisplay extends Component {
  render() {
    const { movies } = this.props;
    return (

        <MovieRow movies={movies.trending.results} movieType='trending' />
        <MovieRow movies={movies.topRated.results} movieType='top rated' />
        <MovieRow movies={movies.nowPlaying.results} movieType='now playing' />
        <MovieRow movies={movies.upcoming.results} movieType='upcoming' />

    );
  }
}

MovieRow Component:
export default class MovieRow extends Component {
  render() {
    const { movieType, movies } = this.props;
    return (

{movieType}

        {console.log(movies)} //This part seems to somehow mount even when conditional rendering says it shouldn't!
        <Slider {...settings} />

    );
  }
}

I then have the body do a conditional render like so, so that if the loading is complete (loading: false), then my MovieDisplay component should render, otherwise it's still loading, so show the Loader component.
I confimed that this part is working (if I search the React Devtools for Loader when loading: false it does not exist, but MovieDisplay does exist.
I'm passing down a data object via props from Home >  MovieDisplay > MovieRow, and then looping through the array to display more components.
However, on initial load, it seems the MovieRow (last, nested child component) is somehow being mounted for a quick second, because in the console it's logging 4 undefined statements briefly, before resolving with the proper data.
Main question: If the Parent Component is not rendered to the DOM, then the child components inside of the Parent should also not be rendered, right?
Secondary question: Is it possible that all the components in my app are rendering briefly for a second on initial load, despite having a conditional in the render() function? That's the only thing I can think of that's causing this.
Example: If MovieDisplay is not rendered, then everything inside of it like MovieRow should also not be rendered, correct?
Hope this isn't too confusing...please let me know if I need to edit my problem or elaborate.
Comment: I think ` `'s `render` function will get called regardless of conditional. If you don't want it's render function to get called, then wrap in a lambda and conditionally invoke it.
Answer: Can you try this:
{this.state.loading && <Loader />}
{!this.state.loading && <MovieDisplay movies={movies} />}

Answer: .then does not resolve a promise. It lets you get the value after the promise was resolved
This is because of the asynchronous nature of JS. Initially, when componentDidMount is called, you set loading = true.
Before the promise is completed(loading = true) react renders the HOME component, this is the reason it calls MovieDisplay component.
Try adding an extra condition where you call MovieDisplay
 {this.state.loading && "check your data is filled in movies object" ? <Loader /> : <MovieDisplay movies={movies} />}

Comment: So your answer wasn't exactly working, but I found out the issue because you pointed out the asynchronous nature of the `Promise` call I made in `componentDidMount`. My conditional, for a millisecond, was not changing to `true`, because all of my code ran before my `Promise.all` finished. Thank you!


How can an Activity access a method of NotificationListenerService?

Question: I have an activity class which needs to obtain the device's current interruption filter setting.
Therefore I have a MyNotificationListenerService class which derives from NotificationListenerService and implements onInterruptionFilterChanged().
However onInterruptionFilterChanged() only gets called when the interruption filter changes. When my app launches I need to find out what the current value of the interruption filter is. NotificationListenerService has a method for this which is getCurrentInterruptionFilter().
My question is: how can MyActivity call MyNotificationListenerService's getCurrentInterruptionFilter() when my app launches?
The OS automatically creates and starts MyNotificationListenerService, is there someway MyActivity can get a handle to that object in order to call getCurrentInterruptionFilter() explicitly?
If not, then what communication mechanism should there be in order for MyActivity to be able to get the initial interruption setting from MyNotificationListenerService?
.
Comment: How about creating an object for `MyNotificationListenerService` class and than accessing the methods?
Comment: @Prerak. That is exactly what my question is. HOW can MyActivity access the methods of MyNotificationListenerService? As I said in the 5th paragraph - the OS creates a MyNotificationListenerService object, therefore how can MyActivity get hold of that object is what my question is all about.
Answer: You want to bind to the service from your Activity.  The Android docs have a detailed explanation of this at http://developer.android.com/guide/components/bound-services.html
Here's an example of how it would work.
Your Activity:
public class MyActivity extends Activity {

    private MyNotificationListenerService mService;
    private MyServiceConnection mServiceConnection;

    ...

    protected void onStart() {
        super.onStart();
        Intent serviceIntent = new Intent(this, MyNotificationListenerService.class);
        mServiceConnection = new MyServiceConnection();
        bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    protected void onStop() {
        super.onStop();
        unbindService(mServiceConnection);
    }

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            mService = ((MyNotificationListenerService.NotificationBinder)binder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    }
}

Your Service:
public class MyNotificationListenerService extends NotificationListenerService {

    ...

    private NotificationBinder mBinder = new NotificationBinder();

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

    public class NotificationBinder extends Binder {
        public MyNotificationListenerService getService() {
            return MyNotificationListenerService.this;
        }
    }
}

Comment: Thanks for your answer. However I'm finding that adding this code seemingly stops NotificationListenerService  from actually working. Without the above code when the app runs NLS doesn't do anything until the user grants notification access to the app, as soon as they do that then NLS's onListenerConnected() gets called and a change to the interruption filter results in onInterruptionFilterChanged() getting called etc. However if the above code is added, then when the user grants notification access then onInterruptionFilterChanged()  does not get called then or ever.
Comment: I get an exception when the activity is being created, there's a log message that the connection is null. I read somewhere (can't find the link now) that NotificationListenerService is "special" in that only the OS can bind to it.
Comment: I've updated the answer, I left out `mServiceConnection = new MyServiceConnection();` which was responsible for the null connection.   Tested it out, and I was able to successfully bind to the Service


What is it called when the "one" of a phrase, or 8-count is accented?

Question: The verses of the song Whatchugot by Caro Emerald have a very obvious bop every 8 beats.
I'd like to find other pop songs that highlight the 1 of each 8 count, or even better the 1 of each 32-count phrase, but I don't know the terminology to describe what I'm looking for to Google.
Is there a term for this?
Comment: If you count this as 1&2&3&4&, the very obvious bop is on the first beat of every bar.
Answer: I think you are thinking of "the one" or "on the one" which I know as associated with James Brown.
You can look it up in lots of places, but this BBC video James Brown's Rhythm Of The One is a nice source.
BTW, you might be off with the count of 8 and counting eighth notes instead of quarter note beats. At least with "the one" it's an accent on beat one of a bar of four beats.
Answer: Boogie-woogie is a style often called "eight to the bar." The song sounds to me like a hybrid of boogie-woogie superimposed over a 4/4 rock backbeat.
Boogie-woogie is often swung, so to be more precise I'd this a straight boogie.
Answer: There may be other terms for this in popular music, but one related technical term in music theory is hypermeter, where measures are grouped together into larger units, so you might feel a sense of a "downbeat" every 2 bars or 4 bars or 8 bars or whatever.  In the song you mention, there is a "bop" on each hypermetric downbeat.
Otherwise in pop music, there is also the notion of a "groove," which often tends to cycle and repeat every X number of beats or measures.  (However, the term "groove" can also mean a lot of things, from the "feel"/style of a piece to a cyclic rhythmic pattern.)  Some people also just call these a "cycle" of beats.
There's probably some other term I'm forgetting but these are a few that are related to the pattern you're noticing.


count rows in a text file

Question: I have the following rows in a text file and I need to know how many rows end with a Y and how many end with a N.
there is a space after the Y and after the N.
The faster the better as it might contain a million or so rows.(so I would prefer not to loop through every line)
Comment: What have you tried? What problems are you experiencing? And of course, **what is your question**?
Comment: What is a C# Text File? Is that different from a normal text file?
Answer: Well you're going to have to loop through every line, certainly. There's really no getting around that. You could then use LINQ to count them reasonably easily:
var query = File.ReadLines("file.txt")
                .Select(line => new { Y = line.EndsWith("Y ") ? 1 : 0,
                                      N = line.EndsWith("N ") ? 1 : 0 })
                .Aggregate(new { Y = 0, N = 0 },
                           (current, next) => new { Y = current.Y + next.Y,
                                                    N = current.N + next.N });

var yCount = query.Y;
var nCount = query.N;

If there isn't exactly one space after the Y / N, change it to use Trim() instead... for example:
var query = File.ReadLines("file.txt")
                .Select(line => line.Trim())
                .Select(line => new { Y = line.EndsWith("Y") ? 1 : 0,
                                      N = line.EndsWith("N") ? 1 : 0 })
// remainder of code as before

This will iterate through the whole file just once, counting as it goes. Admittedly it's creating a lot of objects, but the GC is pretty good. It doesn't pull the whole file into memory, or read it twice.
Comment: Second paragraph in the question states that "there is a space after the Y and after the N"
Comment: @HenkHolterman: At least as long as the mentioned paragraph is actually accurate (which isn't certain, hence the proposal of the safer approach).
Comment: Since there is whitespace at the end of the lines you have to `Trim` them before checking ;)
Comment: @Tobias: How do you know there's whitespace at the end of lines? (`File.ReadLines` doesn't include the line separator, if that's what you were thinking of...)
Comment: Checking for `"Y "` and `"N "` should be enough.
Comment: If you trim the lines, you should alter your `EndsWith(...)` accordingly (regarding spaces). Just saying...

count rows in a text file


Ao fechar modal retornar ao formulário de origem passando parâmetros

Question: Estou efetuando uma consulta em meu BD em uma janela modal, agora depois da consulta feita, preciso ao clicar em um botão enviar os parâmetros selecionados para a página chamadora e jogar esses parâmetros em alguns inputs, anteriormente tinha feito isso usando uma url devolvendo os valores desejados fechando a modal, mas tinha um problema, isso causava um novo carregamento da página fazendo com que os dados anteriormente preenchidos de outros campos se perdessem.
Fiz isso ao clicar no botão enviar:
<button type="button" class="btn btn-primary btn-mini" data-toggle="modal" onclick="EnviaDados()"> enviar </button>
<input id="NomeCooperante" type="hidden" value="<?php echo $Retorno->NomeCooperante; ?>" />

E na página de retorno assim:

function EnviaDados() {
    $('#ModalCooperante').modal('hide');

    // var valor = $('input[type="text"][name="NomeCooperante"]').val();
    var NomeCoop = $(this).attr("NomeCooperante");
    alert("COOPERANTE: " + NomeCoop);

}

Fiz alguns testes, o resultado do alert está sendo:
COOPERANTE: [Object HTMCollection]

O que tenho é isso, a busca:

E os campos que preciso preencher no retorno.
Comment: Você consegue incluir um **[exemplo de código que reproduza o que está acontecendo](http://pt.stackoverflow.com/help/mcve)**?
Answer: A solução para o meu problema, foi essa:
Passei os parâmetros obtidos na busca para a chamada de uma função, ficou assim:
<button type="button" class="btn btn-primary btn-mini" data-toggle="modal" data-dismiss="modal" onclick="mostraDados('<?php echo $Retorno->IdCooperante; ?>','<?php echo $Retorno->NomeCooperante; ?>','<?php echo $Retorno->IdPropriedade; ?>','<?php echo $Retorno->LocalVistoria; ?>','<?php echo $Retorno->IdMunicipio; ?>','<?php echo $Retorno->IdUF; ?>')"> enviar </button>

Na página chamadora, recuperei os parâmetros e atribui aos campos, como segue:

function mostraDados(pIdCooperante,pNome,pIdPropriedade,pVistoria,pUF,pIdMunicipio) {

    // ATRIBUINDO VALORES RETORANDOS AOS CAMPOS
    $("#ID").val(pIdCooperante);
    $("#Cooperante").val(pNome);
    $("#Propriedade").val(pIdPropriedade);
    $("#Vistoria").val(pVistoria);
    $("#UF").val(pUF);
    $("#Municipio").val(pIdMunicipio);

    $("#ModalCooperante").closemodal();

}