MIDI and Bit Order

Question: I'm stuck trying to format a MIDI Sys Ex message that a device keeps rejecting as invalid. The problem is a section of the message that involves a type of data encoding described below.
According to the manual,
the device "will encode/interpret a consecutive group of 4-bytes"
Byte #0 - b31b30b29b28b27b26b25b24
Byte #1 - b23b22b21b20b19b18b17b16
Byte #2 -   b15b14b13b12b11b10b09b08
Byte #3 -   b07b06b05b04b03b02b01b00
as the following 5 consecutive SysEx bytes:"
Byte #0 - 0   b06b05b04b03b02b01b00
Byte #1 - 0   b13b12b11b10b09b08b07
Byte #2 - 0   b20b19b18b17b16b15b14
Byte #3 - 0   b27b26b25b24b23b22b21
Byte #4 - 0   0   0   0  b31b30b29b28
where "b" is the bit number. Notice the bit numbering has been flipped. Which way are you supposed to read the bits? MIDI data is, by convention, reverse bit ordered (MSB=7), if that helps. Also, the manual notes that "all data types are in Motorola big-endian byte order."
Here's a description of the message I'm trying to format correctly -
"A command will allow a consecutive group of one to four bytes to be edited. When 3 or less bytes are specified the device expects the Parameter Value field to be bit ordered as if it was performing a full 32-bit (4 byte) parameter change. For example, when editing a two byte parameter, Byte #0 will occupy the bit range of b24-b31, while Byte #1 will occupy bits b16-b23. The remaining bits (b00-b15) in the parameter value field should be set to zero."
bb      Parameter Offset    -   0   b06b05b04b03b02b01b00
bb      Parameter Offset    -   0   b13b12b11b10b09b08b07
bb      Parameter Offset    -   0   b20b19b18b17b16b15b14
bb      Parameter Offset    -   0   b27b26b25b24b23b22b21
bb      Parameter Offset    -   0   0   0   0   b31b30b29b28
0b      Parameter Byte Size (1 to 4)
00
00
00
00
bb      Parameter Value -   0   b06b05b04b03b02b01b00
bb      Parameter Value -   0   b13b12b11b10b09b08b07
bb      Parameter Value -   0   b20b19b18b17b16b15b14
bb      Parameter Value -   0   b27b26b25b24b23b22b21
bb      Parameter Value -   0   0   0   0   b31b30b29b28
So, when trying to enter offset values of 15H, 16H, 17H, and 18H, with respective values of let's say 00, 01, 02, 03 respectively, how would I encode those hex values, or do I even need to encode them? If I do need to, which direction do I write the bits so the binary values are correct?
Comment: You can use   to make subscripts. I changed the bit numbers into subscripts to make the question easier to read.
Answer: When written, the order of bits in a byte is always big-endian, i.e., MSB first.
This can be confirmed by the fact that the MSB must be zero for data bytes.

Four bytes:
  15h -> 00010101
  16h -> 00010110
  17h -> 00010111
  18h -> 00011000
SysEx bytes:
         0 0011000 -> 18h
         0 0101110 -> 2eh
         0 1011000 -> 58h
         0 0101000 -> 28h
         0000 0001 -> 01h

Four bytes:
  01 -> 00000001
  02 -> 00000010
  03 -> 00000011
  04 -> 00000100
SysEx bytes:
        0 0000100 -> 04h
        0 0000110 -> 06h
        0 0001000 -> 08h
        0 0001000 -> 08h
        0000 0000 -> 00h

Comment: Thanks! So b31 is the MSB in this example and b00 the LSB? Are bits usually represented with such numbers?
Comment: The bit numbers *do not matter*, except for knowing how to rearrange them. If the bits were called A, B, C … or Tom, Dick and Harry, it would not make any difference.
Answer: The basic approach to this conversion is to combine the four 8-bit values into a 32-bit value and then successively move the least significant seven bits into five bytes. Here's a sample program that does what you need.
#include <stdio.h>
#include <stdint.h>

void convert(uint8_t byte0, uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t *outBytes) {
    uint32_t inBytes = byte0 << 24 | byte1 << 16 | byte2 << 8 | byte3; //combine the input bytes into a single 32-bit value
    for (int i = 0; i < 5; i++) {
        outBytes[i] = inBytes & 0x7F; //Copy the least significant seven bits into the next byte in the output array
        inBytes >>= 7; //Shift right to discard the seven bits that were copied
    }
}

void printByteArray(uint8_t *byteArray) {
    for (int i = 0; i < 5; i++) {
        printf("Byte %d: %02xh\n", i, byteArray[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[]) {
    uint8_t sysExBytes[5]; //Five bytes to contain the converted SysExData

    convert(0x15, 0x16, 0x17, 0x18, sysExBytes);
    printByteArray(sysExBytes);

    convert(0x00, 0x01, 0x02, 0x03, sysExBytes);
    printByteArray(sysExBytes);

    return 0;
}

Output:
Byte 0: 18h
Byte 1: 2eh
Byte 2: 58h
Byte 3: 28h
Byte 4: 01h

Byte 0: 03h
Byte 1: 04h
Byte 2: 04h
Byte 3: 00h
Byte 4: 00h

Comment: Thanks @SSteve. Do you think you could explain the algorithm in plain english? I'm not a programmer, and I don't really understand the syntax you're using.
Comment: I'm not going to have time this week to write up anything in depth, sorry. The essence is that you put the four eight-bit bytes together and then divide the bits up in groups of seven instead of eight.
Answer: Your question is a bit confusing.  1 byte is 8 bits, therefore the following lines:

Byte - #0 b31b30b29b28b27b26b25b24
Byte - #1 b23b22b21b20b19b18b17b16
Byte - #2 b15b14b13b12b11b10b09b08
Byte - #3 b07b06b05b04b03b02b01b00

Do not make sense to me.  The first line #0 has 8 bytes in it.  I did some searching and this is a better explanation (http://www.music.mcgill.ca/~ich/classes/mumt306/midiformat.pdf).  Taking the contents from page 2 and editing them for clarity.
 Offset           | Byte 0 | Byte 1 | Byte 2 |  Byte 3
 --------   bits  |  24-31 | 16-23  |  8-15  |   0-7
 00000000         |    00  |        |        |
 00000040         |    40  |        |        |
 0000007F         |    7F  |        |        |
 00000080         |    81  |   00   |        |
 00002000         |    C0  |   00   |        |
 00003FFF         |    FF  |   7F   |        |             <--- example
 00004000         |    81  |   80   |   00   |
 00100000         |    C0  |   80   |   00   |
 001FFFFF         |    FF  |   FF   |   7F   |
 00200000         |    81  |   80   |   80   |   00
 08000000         |    C0  |   80   |   80   |   00
 0FFFFFFF         |    FF  |   FF   |   FF   |   7F

Example at offset 3FFF
Hex format 0xFF7F_0000 (32-bit number, unused bits are 0)

31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16
 1  1  1  1  1  1  1  1  0  1  1  1  1  1  1  1

15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

Does this help?
Comment: This doesn't address the question. The issue is that MIDI data bytes must have a zero in the MSB. The question is about how to do that.

MIDI and Bit Order


Showing a +255 byte in a byte[]

Question: I really hope someone can help me.
I have a single byte[] that has to show the amount of bytes in die byte[] to follow. Now my value is above 255. Is there a way to display/enter a large number?
Comment: What do you mean by "a single byte[]" exactly? Do you mean you've got a byte array of length 1? Your question is very unclear. Code would help...
Comment: it almost sounds like you are expecting to store a value larger than 255 in a byte...that doesn't sound like a good idea
Comment: You cannot store a value greater than 255 in a byte, so there would be no way to display a byte value above that.
Comment: Do you mean you're using the first entry in the array to store the number of entries total in that array?
Comment: I got a byte array of 300. This is going into a message sent to a server. Now one of my bytes has to show the length of the byte[] so that the server knows when to stop reading. Now that byte has to have the value of 299.
Comment: This is for a current server, and I am working from their API document.
Comment: Does the server know how to deal with lengths greater than 255? That is, if you sent an int instead of the byte, would it handle this properly?
Comment: If you need to store something larger than 255 in a single byte, you can't. If you has a number of bytes available, you simply take the integer value and extract the discrete bytes from that. See my answer.
Comment: driis... that makes sense, but how do one do that?
Comment: I see a handful of options: (1) use multiple bytes to represent the length, (2) use a larger data type to represent the length, (3) restrict the length of the byte array to 255 per message, or (4) change your design. Without more information, I can't give a solid recommendation.
Comment: You could also break the array into two or more separate ones (each with length less than 255) and send them one after the other to the server, treating each like a separate transaction.
Comment: No, 299 cannot be represented by a `byte`. If you can't change the format of the message, then you have to restrict the length of each message to 255 bytes. You can either display an error or break larger messages into several smaller ones.
Answer: A byte holds a value from 0 to 255. To represent 299, you either have to use 2 bytes, or use a scheme (which the receiver will have to use as well) where the value in the byte is interpreted as more than its nominal value in order to expand the possible range of values. For instance, the value could be the length / 2. This would allow lengths of 0 - 510, but would allow only even lengths (odd length arrays would need a pad byte).
Comment: I blame fumbly fingers and a bad track-pad. Sorry! Corrected
Answer: You can use two (or more) bytes to represent a number larger than 255. Is that what you want ?
short value = 2451;
byte[] data = BitConverter.GetBytes(value);

If this is needed in order to exchange data with some external system, remember to read about Endianness.
Comment: Driis! That makes my head work in the right direction! That works perfectly in my situation. I overlooked that i had two bytes to display the value! Thanks
Answer: That depends on what you consider a good approach. You can perform some form of encoding to allow you store larger than 2 bytes worth of data. I.e. perhaps setting the first byte as 0xFF means you will consider the next byte as part of its data.
[0x01,0x0A,0xFF,0x0A]
Would be interpreted as 3 values of [1,10,265]

Showing a +255 byte in a byte[]


Trocar texto em ícone de acordo com texto

Question:

Massa Muscular
"

Não manjo muito de programação de site mas estou fazendo um site com o que sei, queria um script que muda o "Massa Muscular" pra um ícone
tipo assim, se estiver escrito "Massa Muscular" aparece um ícone de um braço, se estiver escrito "Emagrecer" aparece uma balança no lugar do texto
o site é esse -> https://www.standsuplementos.com/
Não tenho acesso ao HTML por isso preciso fazer tudo via script pra adicionar algo no site, agradeço desde já!
Answer: Pelo visto você está bem limitado então visei utilizar tudo da forma mais simples possível, vamos entender o código.

tags : Ali vai o elemento que você quer que o código verifique
searchText : Texto a ser encontrado
o for vai simplesmente varrendo todos os objetos encontrados pelo tagname e comparar seu texto, caso seja igual ele substitui o html do elemento por uma imagem, modifique conforme sua necessidade, vale lembrar que caso voce tenha em mente o lugar exato é só modificar o código para um getElementById evitando assim for!

var tags = document.getElementsByTagName("p");
var searchText = "Massa Muscular";

for (var i = 0; i < tags.length; i++) {
  if (tags[i].textContent == searchText) {
    tags[i].innerHTML = '';
  }
}

Massa Muscular

Teste

Massa Muscular

Answer: Pessoal consegui o que queria, vou deixar a solução caso alguém queira fazer o mesmo

$().ready(function () {
    $('.modeloProduto').each(function () {
        string = $(this).text('Massa Muscular');
        $(this).html('');
    });
});

Massa Muscular
"

Com isso onde está escrito "Massa Muscular" aparece a imagem no lugar =D
Achei a solução aqui:
https://onelittledesigner.com/rapidweaver/rapidweaver-snippets/replacing-text-with-an-image-using-jquery/
Comment: Cuidado, você está perdendo toda a informação de .modeloProduto dessa forma, o .html altera todo o conteúdo, o correto não seria alterar apenas o texto do  ?
Comment: É, parece que o código que deixei não vai servir, o seu ficou do jeito que eu queria, valeu!


How to obtain $N_{\mu, i} (\lambda)=c_n \text{vol} (Q_i) \lambda^{\frac{n}{2}}+o(\lambda^{\frac{n}{2}})$? - Weyl's law

Question: I am trying to prove the Weyl's asymptotic law for eigenvalues. In the document Weyl's law of p. $4$, I have managed to go up to the step $$\tilde{\nu_k} \leq \nu_k \leq \mu_k \leq \tilde{\mu}_k \implies N_{\tilde{\nu_k}}(\lambda) \leq N_{\nu_k}(\lambda) \leq N_{\mu_k}(\lambda) \leq N_{\tilde{\mu}_k}(\lambda).$$ Right after, it is indicated that $N_{\mu, i} (\lambda)=c_n \text{vol}(Q_i) \lambda^{\frac{n}{2}}+o(\lambda^{\frac{n}{2}})$. Does someone could explain to me how it is possible to find an explicit function for $N_{\mu, i} (\lambda)$?
Comment: It is not an explicit function, it is the first term of an asymptotic expansion.
Comment: You are right, but could you show me how to find this asymptotic expansion?
Comment: It comes from what you have done for rectangles, but for higher dimensions. The proof should be more or less the same.
Answer: You're not going to find an explicit function for $N$. (For example, $N$ is not even continuous.)
To prove the asymptotic expansion
$$N(\lambda) = c_n|\Omega|\lambda^{n/2} + o(\lambda^{n/2})$$
for the Dirichlet counting function on a domain $\Omega$, the simplest way in bounded Euclidean domains --- and one that I assume you're to use, since you appear to have the inequality between Neumann and Dirichlet eigenvalues --- is to appeal to Dirichlet-Neumann bracketing.
This idea stems from Weyl's original papers (1911,1912) and is described very well in volume 1 of Courant-Hilbert, Methods of Modern Mathematical Physics. The basic idea is to cover $\Omega$ with small $\epsilon$-cubes $\{\chi_j\}$. Denote by $N_*^D$ the Dirichlet eigenvalue counting function and $N_*^N$ the Neumann eigenvalue counting function for the domain $*$. Let $\mathcal{S} = \{\chi\ |\ \chi\subset\Omega\}$ and let $\mathcal{T} = \{\chi\ |\ \chi\cap\Omega\neq\emptyset\}$.
Then argue that as
$$ S = \bigcup_{\mathcal{S}} \chi \subset \Omega \subset \bigcup_{\mathcal{T}}\chi = T  $$
by Dirichlet monotonicity and by the inequality you give in the question above, we have the following inequalities among counting functions:
$$ N_S^D \leq N_\Omega^D \leq N_T^D \leq N_T^N $$
Next, use the fact that all the $\chi$ are isometric, Dirichlet monotonicity, and Neumann monotonicity to argue that the following holds:
$$ (\#\mathcal{S})N_\chi^D \leq N_\Omega^D \leq (\#\mathcal{T})N_\chi^N $$
(Here $\#$ denotes the cardinality operator.)
Finally, use the explicit upper bounds you already know for the Dirichlet and Neumann counting functions of cubes to produce explicit upper and lower bounds for $N_\Omega^D$. The last step is to choose how $\epsilon\to 0$ as $x\to\infty$.
(There is a bit of a subtlety here, for as $\epsilon\to 0$, the bounds at a fixed $\lambda$ becomes very, very bad. This is an expression of the uncertainty principle: When the wavelength is larger than the size of the square, you can't capture the eigenfunction anymore. However, by letting $\lambda\to\infty$ as the squares shrink, you are able to keep the eigenfunctions "in resolution," as it were, and this lets you prove the theorem.)
Comment: For the rectangle $D \subset \mathbb{R}^2$, I've computed $\lim_{\lambda \to \infty} \frac{N(\lambda)}{\lambda}= \frac{A(D)}{4 \pi}$, where $A(D)$ is the area of the rectangle. Could you tell me why $\lim_{\lambda \to \infty} \frac{N(\lambda)}{\lambda}= \frac{A(D)}{4 \pi}$ is equivalent to $N(\lambda) = c_2|\ A(D)|\lambda + o(\lambda)$?
Comment: @SpinningAtInfinity $c_2 = \frac{1}{4\pi}$. If $N(\lambda)/\lambda \to c_2A(d)$ then $N(\lambda) = c_2A(D)\lambda + \mbox{stuff}$ where $\mbox{stuff}$ has the property $\mbox{stuff}/\lambda\to 0$, i.e., is of class $o(\lambda)$. To be more precise, unwind the $\epsilon$-definition of a limit.
Comment: In the document, it is just defined to be $\frac{1}{4 \pi}$, sorry
Comment: I have already seen that before, but I don't remember why $stuff=o(\lambda)$. Could you remember me where this is it come from?
Comment: @SpinningAtInfinity Start with the $\epsilon$-definition of a limit and work with it. Then if you don't understand, pinpoint where you got stuck and ask a new question. :)


XSLT: filter and apply conditional logic while grouping/sorting

Question: For input XML like:
<FlightOptions>
  <item>
     <Fares>
       <item>
         <FareClass>A</FareClass>
         <Fare>100</Fare>
         <FareType>E</FareType>
         <Seats>5</Seats>
       </item>
       <item>
         <FareClass>B</FareClass>
         <Fare>200</Fare>
         <FareType>E</FareType>
         <Seats>10</Seats>
       </item>
       <item>
         <FareClass>C</FareClass>
         <Fare>250</Fare>
         <FareType>E</FareType>
         <Seats>20</Seats>
       </item>
       <item>
         <FareClass>N</FareClass>
         <Fare>100</Fare>
         <FareType>F</FareType>
         <Seats>5</Seats>
       </item>
       <item>
         <FareClass>M</FareClass>
         <Fare>200</Fare>
         <FareType>F</FareType>
         <Seats>50</Seats>
       </item>
       <item>
         <FareClass>O</FareClass>
         <Fare>300</Fare>
         <FareType>F</FareType>
         <Seats>20</Seats>
       </item>
     </Fares>
     <Flight>
         <FlightNumber>YY232</FlightNumber>
         <Origin>JFK</Origin>
         <Destination>LHR</Destination>
         <DepTime>1300</DepTime>
         <ArrTime>2000</ArrTime>
     </Flight>
    </item>
</FlightOptions>

For the above XML, I need to preserve only a few Fares/item nodes where I first group by FareType (E and F) and keep the items starting from the cheapest Fare, but stopping if the Seats is >= 9. Eg., since A has only 5 seats, I need to pick the next highest fare B, but not C. Also, if Seats >= 9, I need to cap it to 9.
I am able to do the group and sort, but unable to walk the fares and apply the logic to pick the fares as long as Seats <= 9 for that FareType. The other complication is that the output XML must reorder the Fares/items such that FareType E nodes come first in descending order of Fare, followed by N node (if present in the source), and then the other FareType F nodes in descending order of Fare.
Output XML would be:
<FlightOptions>
  <item>
     <Fares>
       <item>
         <FareClass>B</FareClass>
         <Fare>200</Fare>
         <FareType>E</FareType>
         <Seats>9</Seats>
       </item>
       <item>
         <FareClass>A</FareClass>
         <Fare>100</Fare>
         <FareType>E</FareType>
         <Seats>5</Seats>
       </item>
       <item>
         <FareClass>N</FareClass>
         <Fare>100</Fare>
         <FareType>F</FareType>
         <Seats>5</Seats>
       </item>
       <item>
         <FareClass>M</FareClass>
         <Fare>200</Fare>
         <FareType>F</FareType>
         <Seats>9</Seats>
       </item>
     </Fares>
     <Flight>
         <FlightNumber>YY232</FlightNumber>
         <Origin>JFK</Origin>
         <Destination>LHR</Destination>
         <DepTime>1300</Deptime>
         <ArrTime>2000</ArrTime>
     </Flight>
    </item>
<FlightOptions>

Have been trying to readup on Muenchian grouping examples but I am having trouble understanding how to apply along with an identity transform (since I have to keep the Flight structure along with the Fares/item nodes).
Thanks!
Comment: I'm a little confused about some of your requirements. You should paste the exact output you're expecting for the XML above.
Comment: What do you mean by "cheapest fare"? I don't see any price information. Please, explain. An example of the wanted output (for the given XML document) together with explanation why exactly this output is produced, would be great.
Comment: The  item is the price of the airline seat. So this would be treated as a number sort.  The output XML would be a copy of the input XML I posted, except that the additional Fares/item nodes would be removed, keeping only the Fares that met the criteria, and keep the Flight node intact for that overall item
Comment: Apologies for not being clear - this is my first time posting to stackoverflow, so I was struggling with the XML formatting. I've now updated the original post with the desired output XML. Hope this helps!
Comment: Could you post the XSLT you are currently using, as that would help too? Thanks!
Answer: You could get away with not using grouping in this instance, as really all you are doing are sorting, and just excluding some elements.
So, when matching the Fares element, you sort the item elements, like so
     <xsl:apply-templates select="item">
        <xsl:sort select="FareType"/>
        <xsl:sort select="Fare"/>
     </xsl:apply-templates>

Next, when you match each such item element, you can just test for whether any previous element with the same FareType is already greater than 9. If there are no such nodes, then because you have sorted by Fare, you know to include the node.
<xsl:template match="Fares/item">
    <xsl:if test="not(preceding-sibling::item[FareType=current()/FareType][Seats > 9])">

    </xsl:if>

Here is the full XSLT...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="Fares">
      <xsl:copy>
         <xsl:apply-templates select="item">
            <xsl:sort select="FareType"/>
            <xsl:sort select="Fare"/>
         </xsl:apply-templates>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="Fares/item">
      <xsl:if test="not(preceding-sibling::item[FareType=current()/FareType][Seats > 9])">
         <xsl:call-template name="identity"/>
      </xsl:if>
   </xsl:template>

   <xsl:template match="Seats[. > 9]">
      <xsl:copy>9</xsl:copy>
   </xsl:template>

   <xsl:template match="@*|node()">
      <xsl:call-template name="identity"/>
   </xsl:template>

   <xsl:template name="identity">
      <xsl:copy>
         <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>

When applied to your sample XML, the following is output:
<FlightOptions>
   <item>
      <Fares>
         <item>
            <FareClass>A</FareClass>
            <Fare>100</Fare>
            <FareType>E</FareType>
            <Seats>5</Seats>
         </item>
         <item>
            <FareClass>B</FareClass>
            <Fare>200</Fare>
            <FareType>E</FareType>
            <Seats>9</Seats>
         </item>
         <item>
            <FareClass>N</FareClass>
            <Fare>100</Fare>
            <FareType>F</FareType>
            <Seats>5</Seats>
         </item>
         <item>
            <FareClass>M</FareClass>
            <Fare>200</Fare>
            <FareType>F</FareType>
            <Seats>9</Seats>
         </item>
      </Fares>
      <Flight>
         <FlightNumber>YY232</FlightNumber>
         <Origin>JFK</Origin>
         <Destination>LHR</Destination>
         <DepTime>1300</DepTime>
         <ArrTime>2000</ArrTime>
      </Flight>
   </item>
</FlightOptions>

Do also note the template match for Seats to limit then to 9.
Comment: Tim - sorry for the delay in getting back - this was absolutely a life saver! My understanding and deep appreciation for XSLT and moreso the guru's who practice it has grown manifold! Thanks a lot.
Comment: Hi Tim C - your answer worked fabulously all this while. Now we have a small enhancement, and i'm trying to figure out the right way. Using the same XML/XSL info in this question, what we need now is to sequentially replace the "FareClass" letter with A,B,C... except the FareClass letters G and Y which should be preserved. I've seen stackoverflow question #7011714 - but not able to determine how to call it.
Comment: Hello! As this question is a year old, the best thing to do would be to ask a new question. Thanks!
Comment: Sure Tim - appreciate your prompt response! I'll repost the XML and XSLT right away
Comment: Hello Tim C - have posted http://stackoverflow.com/questions/12924600/replace-xml-values-with-sequential-alphabets-in-xsl-transform


writing, then reading serial port in python changes when printing?

Question: I am communicating with different devices on a RS485 network with a single RS485MAX device running through the UART pins on a Raspberry Pi.
It is using serial port /dev/serial0.
The UART flipper is used to flip the RS485MAX device from send to receive and back.
It works fine when communicating with other devices, but for one in particular, it only reads the response from the serial port if there is a print statement:
<code>with Serial(port=rs485_manager.port,
                            baudrate=rs485_device.baud_rate,
                            bytesize=rs485_device.byte_size,
                            parity=rs485_device.parity,
                            stopbits=rs485_device.stop_bits,
                            timeout=rs485_device.read_timeout) as s:
                payload = send_packet.get_payload()
                rs485_manager.uart_flipper.setup_for_write()
                #
                # Note that this sleep breaks it again, even if the print statement is there
                #
                time.sleep(1)

                print(flush=True)  # tried adding this - makes no difference
                s.reset_output_buffer()  # tried adding this - makes no difference
                s.reset_input_buffer()  # tried adding this - makes no difference
                s.flush()  # tried adding this - makes no difference

                s.write(payload)
                #
                # If I add this print statement, it receives the packet correctly from the serial port:
                #
                print('this is a test this is a test this is a test this is a test this is a test this is a test this is a test this is a test')
                rs485_manager.uart_flipper.setup_for_read()

                while s.in_waiting > 0:
                    received_bytes += s.read(s.in_waiting)

                print('read bytes: {}'.format(as_hex(received_bytes)))
</code>
When the print statement is present, it very consistently reads the data from the comm port (unless I have a sleep statement before it - see comments above)
I have tried substituting the print statement with a sleep (even up to a few seconds!) and it does not fix the problem.
Its almost as if the stdout is affecting the serial port
Comment: Without the slight delay introduced by the `print()`, I suspect that the first check of `s.in_waiting` returned zero - so the `while` loop never executed, and nothing got read.  You need some more reliable means of determining when you've reached the end of the data, as the number of waiting bytes can legitimately go to zero even in the middle of a message.  Perhaps calling `.read()` with a timeout set would work.
Comment: @jasonharper It doesn't work even with a sleep.
Comment: So I changed the print to a file.write() to quiet the output.  It works, but it is still a troubling hack
Comment: I also added received_bytes = s.read()  before checking the in_waiting count.  Note that I am setting the timeout for the device to 1 second - which should be PLENTY of time for the remote device to read my request and respond)
Answer: OK... After much thinking, testing, scoping, hair-pulling, I think that the problem is with the RS485MAX.  It takes too long to flip the transmit/receive switch and for some reason the random amount of time it took to write to the file did something to occasionally allow it to work.
I replaced it with a conventional USB-RS485 dongle and it is working fine with no bizarre timing issues.
My take-away: if you have PLENTY of time to flip between transmit and receive, the RS485MAX may work for you... Otherwise, buyer beware ;-)


How to add scrollbars in iframe

Question: I want to add scrollbars in my iframe. Below is my code.

I am writing this in Drupal 7. Problem is it doesn't show iframe with scrollbars and border. Earlier I simply set the source without width and height and scrolling options and it showed iframe with scrollbars but after adding width and height,it disappeared.
Thanks
Comment: I have made change to my answer for scroll and border to appear
Answer: scrolling="yes" and also frameborder aren't valid HTML5 attributes anymore. They can't be found in the list of allowed attributes, see: W3C: 4.7.6. The iframe element or MDN: .
Use CSS instead:
iframe {
    overflow: scroll;
    width: 1349px;
    height: 100%;
    border: 1px solid black;
}

But actually all browsers show the scrollbars right away if needed.
Demo
Try before buy
Comment: @bsm It seems that it's common among all browsers (I didn't test IE actually) that they don't show the scrollbars for an `´ if they aren't needed.
Comment: But why this horizontal scrollbar is disabled here?
Comment: Okay.I am testing it in Firefox.
Comment: @vapcguy Well, actually it does. Tested it using the demo link. Note that that horizontal scrollbar might not be visible, as the example page is responsive and will fit into the iframe. [Try this link instead](http://jsfiddle.net/7jx9fL14/).
Comment: @insertusernamehere Odd - yours works, but please look at mine:  http://jsfiddle.net/navyjax2/v8oof0g0/  I have a link opening CNN's main page in a modal dialog. The right-side scrollbar appears, but doesn't work on the main contents (I noticed it actually scrolls CNN's right-sidebar menu, if you expand the window height), and there is no horizontal scrollbar.
Comment: The link to w3.org seems to be a dead link. I found this on Mozilla's site which outlines the attributes for `iframe` and what's supported and what not https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe
Comment: @SmurfEkko Good catch. W3C moved the current documentation to *github.io*. I've updated the link accordingly, I also added the MDN link. Thanks for your feedback.
Answer: you were missing scrolling="yes" in your code try the following code

Answer: Change scrolling="auto" to scrolling="yes" and add frameborder="1"
Try the style:
iframe {
   border: 1px solid #000 !important;
   overflow: scroll !important;
}

Comment: Thanks..I tried this but still there is disabled horizontal scrollbar and iframe box is without border.
Comment: I have made some changes to my answer
Answer: Change the scrolling attribute to
scrolling="yes"

Comment: @DrSatan1, do not enter in filler text. If you're answer is too short try adding a description of what your purposed changes do, which you should do anyway.
Comment: Thanks for your quick reply. After making this change, it shows disabled horizontal scrollbar also there is no border..
Answer: This is not an issue with Firefox, ie, or edge.
The way i solved my particular issue is removing a class's overflow: auto
and replacing it with the following on the parent of (in my current case) a table
class {
 overflow-y: scroll !important;
}

How to add scrollbars in iframe


Programa em C++, string não aceita mais caracteres, e trava o console, o que acontece?

Question: Fiz um programa em C++ que converte um código morse, para letras.
Porém esse programa irá receber até 1000 caracteres. Mas não sei o que acontece, ele no máximo recebe 400 caracteres, e ai o console trava.
O que acontece?
Segue código abaixo:
<code>#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

string convertMorse(string s) {
cout<<s<<endl;
if(s=="=.===")return "a";
if(s=="===.=.=.=")return "b";
if(s=="===.=.===.=")return "c";
if(s=="===.=.=")return "d";
if(s=="=")return "e";
if(s=="=.=.===.=")return "f";
if(s=="===.===.=")return "g";
if(s=="=.=.=.=")return "h";
if(s=="=.=")return "i";
if(s=="=.===.===.===")return "j";
if(s=="===.=.===")return "k";
if(s=="=.===.=.=")return "l";
if(s=="===.===")return "m";
if(s=="===.=")return "n";
if(s=="===.===.===")return "o";
if(s=="=.===.===.=")return "p";
if(s=="===.===.=.===")return "q";
if(s=="=.===.=")return "r";
if(s=="=.=.=")return "s";
if(s=="===")return "t";
if(s=="=.=.===")return "u";
if(s=="=.=.=.===")return "v";
if(s=="=.===.===")return "w";
if(s=="===.=.=.===")return "x";
if(s=="===.=.===.===")return "y";
if(s=="===.===.=.=")return "z";

return "lixo";
}

int main(void) {

ios_base::sync_with_stdio(false);
cin.tie(0);

int t; cin>>t;
string str;
string saida;

 while(t--) {

    cin>>str;
    string nova;
    int contap = 0;
    for(int i=0;i<str.size();++i) {

        if(str[i]=='=') {

            if(contap==3) {
//              cout<<"n: "<<nova<<endl;
                saida += convertMorse(nova);
                contap=0; nova.clear();
            }

            if(contap==7) {
                    saida+=convertMorse(nova);
                saida+=' ';
                nova.clear();
                contap=0;
            }

            while(contap>0) {
                contap--; nova+='.';
            }

            nova+=str[i];
        } else {
            contap++;

        }

    }

    saida+=convertMorse(nova);

    cout<<saida<<endl;
    saida.clear();

}

return 0;
}
</code>
Comment: Que erro dá na consola? Receber 1000 caracteres de um ficheiro de texto, como por exemplo?
Answer: Bom galera, o Dev C++ estava com erro, por causa que ficou muito tempo aberto e as vezes gera algum bug, este foi o motivo de não estar lendo 1000 caracteres, fechei o programa, coloquei o código e salvei novamente e funcionou.


Cauchy sequences over $\mathbb{Q}$: A basic question

Question: Define an equivalence relation on Cauchy sequences in $\mathbb{Q}$ by $(x_n)\equiv (y_n)$ if $\lim (x_n-y_n)=0$.
The question I am trying to prove is that

If $(x_n)$ and $(y_n)$ are Cauchy sequences in $\mathbb{Q}$ such that $(x_n)(y_n)\equiv (0)$ then $(x_n)\equiv (0)$ or $(y_n)\equiv (0)$.

Here, I am considering the problem only over $\mathbb{Q}$ and not considering anthing about $\mathbb{R}$.
Some part of proof: Suppose $(x_n)\not\equiv (0)$. We show that $(y_n)\equiv (0)$.
Since $(x_n)\not\equiv (0)$, so $(x_n)$ is a Cauchy sequence but its limit is not $0$.
Hence there is an $\epsilon>0$, such that for every $i\in\mathbb{N}$, there is $n_i$ such that $|x_{n_i}|\ge \epsilon$.
What this says is that infinitely many terms of $(x_n)$ are bounded away from $0$.
How to proceed now, to show that $(y_n)\equiv (0)$?
Answer:
Hence there is an $\epsilon>0$, such that for every $i\in\mathbb{N}$, there is $n_i$ such that $|x_{n_i}|\ge \epsilon$.

Correct. You can use that and the fact that $(x_n)$ is a Cauchy sequence to get the even stronger statement that there exists $N\in\mathbb{N}$ such that $|x_n|\geq\frac{\epsilon}{2}$ for all $n\geq N$. That makes it straightforward to show $y_n\rightarrow 0$.


Error on creation AWS DB Instance via Terraform

Question: I'm trying to create a new AWS RDS instance thru Terraform, but I'm has been receiving a strange error as below snippet:
resource "aws_db_subnet_group" "sng_marketplace_stg" {
  name     = "sng-marketplace-stg"

  tags = { Name = "Marketplace Staging" }

  subnet_ids = [
    "${aws_subnet.sbn_1_us.id}",
    "${aws_subnet.sbn_2_us.id}"
  ]
}

resource "aws_db_instance" "marketplace_staging" {
  identifier                  = "db-marketplace-stg-staging"
  engine                      = "postgres"
  engine_version              = "12.4"
  # ...
  # omitted
  # ...
  db_subnet_group_name        = "${aws_db_subnet_group.sng_marketplace_stg.id}"
}

The 1st group creates a subnet group called sng-marketplace-stg this step is ok, and TF can apply.

The 2nd step raise error a Error creating DB Instance: DBSubnetGroupNotFoundFault: DBSubnetGroup 'sng-marketplace-stg' not found.

Well, when I access AWS Console RDS the subnet group has been created, as expected, but if I rerun the TF apply (or plan) the terraform show the correct change (create new RDS instance), but when applied, the error is raised again, like if the subnet group not exist.
Anybody saw this error before or any suggestion to fix it?
Thank 4 any help or direction to solution.

The complete error trace here:
Error: Error applying plan:

1 error occurred:
        * aws_db_instance.marketplace_staging: 1 error occurred:
        * aws_db_instance.marketplace_staging: Error creating DB Instance: DBSubnetGroupNotFoundFault: DBSubnetGroup 'sng-marketplace-stg' not found.
        status code: 404, request id: da567898-...

Comment: The code you've provided is correct. I don't see a reason why it would not work. Are you sure that the snippets you've given are representative of your actual code?
Comment: Yeah, the code are correct, but a reaseon (i don't know) the AWS <> Terraform not recognize the resource.
Answer: I had the same problem with my code, and I realized that you have to add the resource aws_db_parameter_group in your main.tf file.
Here's an example extracted from the official website of terraform
resource "aws_db_parameter_group" "education" {
  name   = "education"
  family = "postgres13"

  parameter {
    name  = "log_connections"
    value = "1"
  }
}

Then, I run terraform plan and terraform apply and everything works ok (make sure your IAM role has all permissions it needs, you can add them when appears error messages in terraform console related to permissions).
Good luck!
Answer: You have to create db parameter group.
resource "aws_db_parameter_group" "education" {
  name   = "education"
  family = "postgres13"

  parameter {
    name  = "log_connections"
    value = "1"
  }
}

Also you have to reference it while creating the db instance.
In your case.
resource "aws_db_instance" "marketplace_staging" {
  identifier                  = "db-marketplace-stg-staging"
  engine                      = "postgres"
  engine_version              = "12.4"
  # ...
  # omitted
  # ...
  db_subnet_group_name        = "${aws_db_subnet_group.sng_marketplace_stg.id}"
  parameter_group_name        = aws_db_parameter_group.education.name
}

Further more if you want to allow the traffic. Add a security group with referencing your vpc id.
resource "aws_security_group" "rds" {
  name   = "education_rds"
  vpc_id = module.vpc.vpc_id

  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "education_rds"
  }
}

and also reference that in creation of your database. In your case.
resource "aws_db_instance" "marketplace_staging" {
  identifier                  = "db-marketplace-stg-staging"
  engine                      = "postgres"
  engine_version              = "12.4"
  # ...
  # omitted
  # ...
  db_subnet_group_name        = "${aws_db_subnet_group.sng_marketplace_stg.id}"
  parameter_group_name        = aws_db_parameter_group.education.name
  vpc_security_group_ids      = [aws_security_group.rds.id]
}

Reference: https://github.com/hashicorp/learn-terraform-rds/blob/main/main.tf


Neck is bowed and truss rod cannot be tightened further

Question: I recently noticed a bow in my guitar and that it has been much harder to play than it should be. I tightened the truss rod to bring the string height back down and unfortunately, the string height is still to high for my taste. Tonight I once again looked at the neck and it was still slightly bowed, concaved that is. I turned the truss rod again to tighten and unbelievably, it was as if I couldn't turn it anymore. I used 1/4 turns and always gradual and slow. Since there is still a bow and my action is not where I want it, does there mean something is wrong with my guitar? I don't feel it is stripped or anything and my neck is not bent, twisted, cracked or anything like that. Thank you guys for all your help.
P.S. Guitar is a PRS SE 7-String - no tremelo.
Comment: There is the remote possibility the truss rod is broken, or has come detached from the other end. That would be a job for a luthier. How many extra turns did you have to put into the screw? More than a couple of flats would suggest something inside has come loose, unless you just swapped for a much heavier string gauge recently.
Comment: Guitar necks are supposed to be bowed somewhat. Here is a video on guitar setup by the great Joe Walsh. https://www.youtube.com/watch?v=D7gMwE7phoM
Answer: Truss rod adjustments do not usually affect the neck with an immediate change. Depending on the base wood, it could take 30 minutes to an hour before the truss rod has had it's full effect on the neck. My recommendation would be to wait 30 minutes to an hour and check again.
If you feel you have made the proper adjustments, but your guitar neck is skill skewed, it is possible your neck is warped. However, your neck shouldn't be perfectly straight. Some 7 string guitars come with reinforcement rods, so an adjustment might take even longer to notice.
Quick tip: capo the first and 12th fret and measure the height of the strings before and after an adjustment. That should tell you what affect the adjustment is having.
Comment: Additionally, if the only problem you notice is with the string height, then yes - adjust the bridge! Just keep track of all of your tinkering so you can get things back if you feel you have made things worse.
Comment: A warped neck can be fixed, but it isn't cheap. Depending on the neck, a luthier can remove the fret board and replane the base wood until it is straight. Then, they can glue a new fret board to the base wood.
Comment: Thank you, but what if it was warped? I mean, is that fixable? I don't think this is the case here but I have never had a warped neck before. And I did wait quite a while before checking again. Maybe the adjustment now needs to be made at the bridge?
Answer: First port of call - Paul Reed Smith. He may well have seen the problem before. It makes life easier to slacken the strings before tightening the truss rod.While they're loose, try to turn another turn, you'll feel if it's binding or the thread has gone, more easily.
Answer: To add to the other answers, the truss rod really isn't for adjusting the action.  The truss rod works against the string tension on the neck.  To check the truss rod's adjustment you need to hold down the strings to the 1st and 12th fret (e.g. with two capos) with the guitar fully strung and in tune and measure the gap at the 7th fret.  This should be somewhere around 7 thousands of an inch or about 0.18mm for a 6 string electric.  Not sure about 7-string.  The slight bow in the neck helps prevent buzzing on the lower frets with low action.  Once the truss rod is properly adjusted the action can be adjusted at the nut and the bridge saddle.
If you can't adjust the guitar within spec it's also possible the frets themselves are worn out and the surface of the neck is no longer straight, in this case the guitar might need a fret job.
Comment: Can't see how the two E strings would both have the same clearance. And .007" is just thicker than a human hair, whereas 1.8mm is around 5 visiting cards thick.
Comment: @Tim the bottom of the string acts as a straightedge here, so the bottom of both E strings rests on their respective fret wires and so you should observe very similar relief on all strings.  This is different than when you adjust action where each string's action is set differently.  I'm off by one decimal place on my metric, sorry, I'll fix that!
Answer: I have a Yamaha FG 110 and the neck warped beyond what the truss rod is capable of correcting.  This might have happened because it was stored for many years under full string tension (not a good idea).  If the truss rod was broken or stripped it would likely turn too easily.  If you can loosen the truss rod but only tighten it so far before it won't turn any more, the truss rod is probably fine.  But it is very possible that the neck is warped.  I straightened my neck slightly by taking all the strings off and applying pressure over a period of weeks but still could not get the bow out.  I just put super light strings on it and keep it tuned half step flat and only use it for occasional practice to save fret wear on my other guitars.  It plays fine in first position but Barre chords past the 5th fret are almost impossible to play.  If that won't work for you I recommend a new guitar, or a new neck.  Attempting to sand and carve and straighten a bowed neck may improve play-ability some, but not enough to justify the expense.  Good luck.
Comment: Yeah, I don't have that kind of problem lol. I have never seen a warped neck but wondered if it were possible. Fortunately, I don't think this is the case. My action is great compared to many- just not good enough for me.
Comment: Well it sounds like you may have a slight bow since you have tightened the truss rod as far is it will go and you still have a bow.  Lighter strings will put less tension on the neck and may very slightly lower the action.  The other  thing you can do to achieve lower action is lower the height of the saddle by filing it down.
Answer: I had the same problem, could not tighten the truss rod any further and still a bit of up-bow to the neck. Found a solution on the web that worked for me. If the problem is that there is not enough thread left on the rod for the bolt to move on, it helps to take the bolt off, put a few washers on, and put the bolt on again. This wins you some length of thread, so you can adjust some more. The challenge is to find washers of the right diameter (to fit the rod and to fit the cavity). Also, it helped to do the adjustment with the neck forced straight, or even with a slight down-bow. That way the trussrod does not have to do the pulling work, just to keep the whole contraption in place. Of course this is something to be very careful with - worked for me but no guarantees.
Answer: Yes I have a Takamine , when I got it the action was very low but with no buzz or any thing ,after a few month, noticed it was a lot higher The neck was not to bad , anyway I had a go at tightening the rod ,but it seamed fully tightened .so I loosened off all of the strings and got a bit on it , but the action is no we're near to what it was , I think next port of call I have to take some of the saddle .That might be your next move JA
Answer: I have a Simon and Patrick Songsmith acoustic. The neck would not straighten from too much up bow no matter how much I adjusted the truss rod. I backed off all the strings and put my guitar in the bathroom with the shower on hot for about 15 minutes. To my astonishment the guitar straightened out. Anyone who is having issues and who knows their truss rod isn't broken maybe this experience with help you.
Comment: Hi Danial - I have edited both your profile pic and this post. Please avoid offensive comments.
Comment: Additionally - I do not think I'd recommend this technique. Especially for acoustic guitars - you could do an awful lot of damage. Humidity is something that should be well controlled.
Answer: I'm having this same issue, I recently watched a video and I am considering trying the technique. He basically took the neck off and clamped it to a leveling beam with another piece of wood on the backside to prevent damage to the neck. He used 3 clamps. He then put a couple of shims in around the 7th fret to give it the slight bow and baked it in the oven for an hour at 150°.
Comment: So did the neck being baked in the oven at 150 for an hour work out after he shimmed it an clamped it all up and we're there any burn marks left on it.


What is an intuitive way to think about why high variance in predictions is associated with overfitting of a model?

Question: I read that for linear models, when more variables are added to the regression, typically the bias of the predictions decreases and the variance increases. That is:

Too few covariates yields high bias, known as underfitting.

while

Too many covariates yields high variance, known as overfitting.

I am having a hard time intuitively understanding why too many covariates would yield high variance. Isn't it the case too many covariates sort of "pin" the estimates and would actually reduce the variance? And is there a way to also think about how the bias would decrease? Thanks.
Answer: In this context, "variance" refers to the variance of the training data which is predicted by the model. You are exactly correct, more covariates will "pin" the estimates to real data points because there are more degrees of freedom for your model to manipulate to actually fit the data.
However, consider that including completely superfluous variables in a linear model will impact model predictions with limited data. In this case, your model will be "pinning" estimates to points in your input space where most of the dimensions are nonsense. In this case, the bias will be lower because the training data will fit better, the model will perform badly because it will overestimate the importance of these superfluous variables.
At the extreme limit, consider you have $N$ 1-D data points which is captured in a linear model with 1 variable with an $R^2$ of 0.95. Now, generate $N-1$ random numbers and append them to each of the $N$ data points such that these data points are now $N$-dimensional. Now, when you fit your linear regression model, your variance increases and bias decreases, in fact, you get $R^2= 1.00$! However, this is clearly an overfit model because it using random numbers to predict outcomes.


Routing Rules with VPN

Question: Im newbie with this network things and need some help. I have setup like this
 ------------         ------------         ------------
|     A      |       |     B      |       |     C      |
| 10.148.x.x |-------| 10.184.x.x |-------| 192.168.x.x|
|    APP     |       |    VPN     |       |   VPN      |
 ------------         ------------         ------------

I have a topology like this. Where B and C are connected as tunnel VPN site-to-site. I want to send traffic (e.g ICMP/API REQ/etc) from A to C through B and vice versa. Both A and C will received incoming traffic from B, not from real source (So, for example when C PING-ing B, B will direct that PING to A and tell A that the source of ping is from B). After surfing on many problems I found this rules works on me with IPTABLES and applied to B.
This is routing for A to C:
-A PREROUTING -s 10.148.x.x -d 10.184.x.x -p tcp/icmp -j DNAT --to-destination 192.168.x.x
-A FORWARD -s 10.148.x.x -d 192.168.x.x -p tcp/icmp -j ACCEPT
-A POSTROUTING -o eth0 -j MASQUERADE

This is routing for C to A:
-A PREROUTING -s 192.168.x.x -d 10.184.x.x -p tcp/icmp -j DNAT --to-destination 10.148.x.x
-A FORWARD -s 192.168.x.x -d 10.148.x.x -p tcp/icmp -j ACCEPT
-A POSTROUTING -o eth0 -j MASQUERADE

Its work great at common server but at this case:
I used TCPDUMP for dump the traffic at B. When C PING-ing B the traffic looks like
10:18:04.706713 IP 192.168.x.x > 10.184.x.x: ICMP echo request, id 49458, seq 12987, length 40
10:18:04.706806 IP 10.184.x.x > 10.148.x.x: ICMP echo request, id 49458, seq 12987, length 40
10:18:04.719587 IP 10.148.x.x > 10.184.x.x: ICMP echo reply, id 49458, seq 12987, length 40
this traffic direct to A but its seems like B cannot reply to 192.168.x.x

When A PING-ing B the traffic looks like the traffic return DUP!
64 bytes from 10.184.x.x: icmp_seq=1 ttl=187 time=48.1 ms
64 bytes from 10.184.x.x: icmp_seq=1 ttl=187 time=48.1 ms (DUP!)
64 bytes from 10.184.x.x: icmp_seq=1 ttl=187 time=48.2 ms (DUP!)
64 bytes from 10.184.x.x: icmp_seq=1 ttl=187 time=48.2 ms (DUP!)

from man ping:

Duplicate and Damaged Packets
ping will report duplicate and damaged packets. Duplicate packets
should never occur, and seem to be caused by inappropriate link-level
retransmissions. Duplicates may occur in many situations and are
rarely (if ever) a good sign, although the presence of low levels of
duplicates may not always be cause for alarm.
Damaged packets are obviously serious cause for alarm and often
indicate broken hardware somewhere in the ping packet's path (in the
network or in the hosts).

What did i missed?
EDITED: I'm so sorry if I'm not clear deliver the problem. Now I edited the IP, so the IP shown above all are Private IP instead of Public IP. There is no tunnel in A-B and tunnel VPN just between B-C. For this case, my user just want both A and C just hit and know IP B. Therefore, Either A and C just hit B.
Answer: You are making things way to complicated. In your setup, you are mapping the complete IP range 184.108.40.206/8 to 192.0.0.0/8 in one direction and in the other direction to 10.0.0.0/8. This implies that at site B, none of the 18.104.22.168/8 IPs will be reachable and directly useable.
First, 126.96.36.199/8 and 192.0.0.0/8 are public IP ranges which exists inside the internet, this is not meant for private use. How should your pc know if the public or the private ip is meant?
you should stick in your setup to the dedicated private ip ranges, which are 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. These should be more than enough private ips, I doubt that you have 24 million devices at each site.
If I were you, I would setup the topology that the site-to-site VPN tunnel A-C is direct, so you have A-C and A-B as seperate tunnels. But there may be cases where this is not possible / wanted, I will assume that this is one of them. If I were you, I would setup the VPN tunnels with "visible" IPs:
The tunnel A-B is routing 192.0.0.0/8, with the tunnel endpoint inside B as gateway. B-C is routing 10.0.0.0/8 directly with tunnel endpoint inside B as gateway.
That way, you do not have to mess with DNAT rules, all three IP ranges are fully useable and visible from all three sites. But please remember to change those subnets (for example to 10.1.0.0/16. 10.2.0.0/16 and 10.3.0.0/16)
[edit]
And, if you really want to make your setup working, and set aside all warnings from my side: you need to remove the masquerade rule, and replace it with two SNAT rules.
a MASQUERADE target replaces ALL source IPs with the IP of the gateway, making it impossible for the destination to know from which ip the request came from. This is obviously not what you wanted...
[edit2] Concerning the updated question:
a) "hide" the vpn behind B (the typical home office scenario) - this implies that the app cannot open an connection to C, C has to open the connection to A.

remove DNAT rule
modify MASQUERADE rule (you want to masquerade traffic only in one direction): -t nat -A POSTROUTING -s 192.168.0.0/16 -o eth0 -j MASQUERADE

b) "publish" the routing connection to the whole app network: in this scenario, you will completely remove DNAT and MASQUERADE rules, and do it via routing: on site A) : route add -net 192.168.0.0/16 gw <place IP of B here>10.148.0.0
c) the virtual IP mapping scenario: The idea behind this scenario is to create a virtual IP, which is being used to access a server which stands in an private subnet not reachable otherwise. In this scenario, you need a full NAT (DNAT and SNAT) and an IP, which is not used anywhere. And plus, the correct routing needs to be in place, too... This is the most complicated scenario, since you are new to network things (as you say) I clearly discourage the usage of this solution.
Comment: Thank you so much for your answer, really helped me. I've done edited my questions. I'm sorry if I cant deliver clear problem before, hope this time will be good. Could you please re-read again the question and take a look at EDITED section at the bottom of the question? Much appreciate from me
Comment: I updated my answer, too. Next time, please be precise when asking the question... You changed your question to a whole different direction.

Routing Rules with VPN


jssor slider clips images on Firefox 35.1 (#2)

Question: With a recent release of Firefox (approx 18th Jan) jssor is now clipping images to varying degrees (bottom 20% - 50% of image).
A demonstration page can be found here https://erentz.com/jssor.php
Comment: It  happens with firefox 35 only. And it affects other sliders as well.
Comment: Many thanks, hoping that the folks at Mozilla are on the case.
Comment: This issue has been resolved with release of Firefox 36
Answer: Just updated to Firefox 36.0 and the problem is solved at my site!


Qual a diferença entre npm e npx?

Question: Estou estudando react native e reparei que muitos lugares utilizam o comando:
npx react-native run-android

Por que eu não posso utilizar o seguinte comando?
npm react-native run-android

E qual a diferença de utilizar o npx ou direto o pacote, como no exemplo a seguir?
react-native run-android

Comment: npm serve para você gerenciar os pacotes, instalando localmente, globalmente ou removendo-os, o npx serve para você executar sem instalar, o comando `react-native run-android` só é possível após uma instalação global, ex.: `nps install -G packageName`
Comment: @DenisRudneideSouza poderia escrever uma resposta com mais detalhes, por favor? (:
Comment: npx é um outro programa que instala e executa um pacote NPM que possua um comando de CLI, dentro de um comando só. Se você tivesse pesquisado no google teria uma resposta bem completa.
https://www.npmjs.com/package/npx
Answer: npm é o gerenciador de pacotes node, ele irá instalar na sua máquina um pacote para que você possa utiliza-lo em outros projetos sem precisar baixar novamente.
já o npx ele irá usar o pacote sem precisar baixar em sua máquina, sendo assim você irá instalar um pacote no seu projeto ou até mesmo usar esse pacote, sem baixar os arquivos em sua máquina.
Para que o npx é util?

Já instalou algum pacote global e precisou usá-lo pouquíssimas vezes?
Já teve problemas de incompatibilidade com pacotes globais por diferença de versões em múltiplos projetos?
Já sentiu que sua máquina está poluída por diversos pacotes globais?

Quando você instala react-native em sua máquina e começa um projeto usando ele ao invés de NPX, você está usando a versão do react-native do pacote instalado em seu node_modules, já quando usa npx você usa um pacote na nuvem do node, então isso te da liberdade para usar até outras versões que não tem em sua máquina.
Comment: agora com o node atuando no backend, o NPM acronimo de Node package manager, acaba sendo um gerenciador de pacotes frontend e backend.
Comment: Pode crer, entendi. (:
Comment: O `npm` só consegue gerenciar pacotes front-end? o.o
Answer: O que é NPX?
NPX é um executor de pacote NPM que torna realmente fácil instalar qualquer tipo de executável de Node.js que normalmente teria sido instalado usando NPM. Se o NPM é um gerenciador (manager) de pacotes, o NPX é um executor, por isso o X no final da sigla. O X vem de eXecutor.
O NPX foi desenvolvido pela Kat Marcán, atualmente é mantido pelo NPM, que foi comprado recentemente pelo Github. O NPX é um binário que está presente no NPM desde a versão 5.2.
Por que usar o NPX?
Existem várias maneiras de instalar pacotes do Node.js, você pode colocá-los localmente (local para o projeto) ou instalar globalmente (no ambiente do usuário).
Às vezes, em vez de usar um dos dois métodos de instalação acima, você pode apenas usar o pacote e pronto.
Às vezes, você pode querer apenas experimentar uma lista de pacotes, pois pode não saber exatamente o que precisa.
Nesses casos, em vez de instalar localmente ou globalmente, você pode ir direto para a execução desses pacotes com NPX.
Como funciona?
Quando você executa um pacote usando NPX, ele procura o pacote no registro local e global e, em seguida, executa o pacote.
Se o pacote ainda não estiver instalado, o NPX baixa os arquivos do pacote e instala o pacote, mas apenas armazenará os arquivos em cache em vez de salvá-los, ou seja, contradizendo o que foi dito na outra resposta:

já o npx ele irá usar o pacote sem precisar baixar em sua máquina,

Para usar NPX, você executaria um comando como este:
npx some-package

Uma ótima maneira de ver a rapidez com que o NPX funciona é criar um aplicativo de React usando:
$ npx create-react-app my-app

Obs: create-react-app não é recomendados ser usado, foi apenas um script de exemplo. Veja em: Goodbye create-react-app
O comando acima irá gerar um app react, denominado my-app, no caminho em que o comando foi executado usando o pacote create-react-app. O NPX então:

Procura o pacote em seu ambiente localmente (node_modules do projeto).
Se não for encontrado, procura o pacote em seu sistema (node_modules global).
Se não for encontrado, o NPX baixa os arquivos e executa o comando para criar um novo app react, usando apenas aquela linha de comando.

Como mostrado acima, NPX não só busca no site do npmjs, como busca de dentro da node_modules do projeto também ou até mesmo na node_modules global antes de ir na Internet buscar os pacotes e executar.
No exemplo do React, ter o react-native cli ou create-react-app na máquina ocupa espaço e essas bibliotecas são atualizadas muito rápido, então não compensa ficar mantendo elas na máquina. O comando create-react-app, por exemplo, é feito uma vez e depois nunca mais, a menos que você comece outro projeto.
Observação
Uma desvantagem do NPX é que ele precisa pesquisar os pacotes, estejam eles instalados ou não, antes de realmente executá-los. Todo aquele caminho que já mencionei (1, 2 e 3) é percorrido pelo script do NPX. Isso pode ser uma sobrecarga quando você precisa fazer as coisas muito rapidamente, principalmente se os pacotes devem ser procurados e/ou baixados para ai sim serem executados.

Fonte:

Conhecendo o NPX - Executor de Pacotes do NPM

Qual a diferença entre npm e npx?


Programmatically create a organic group

Question: How would you programmatically create an OG group? I have tried node_save() but to no joy.
Comment: Which Drupal version?
Comment: 6. Tag added to question.
Comment: Hmmm... looking at the [og_nodeapi](http://drupalcontrib.org/api/drupal/contributions--og--og.module/function/og_nodeapi/6) function, it looks like node_save should do the trick. I can't see why it doesn't work. Just a thought: maybe you can try building a $form_state array and run [drupal_execute](http://api.drupal.org/api/drupal/includes--form.inc/function/drupal_execute/6).
Answer: It's simpler than attaching node as group post:
  <?php
  global $user;
  $node = new stdClass();
  $node->type = 'group'; // Change this to group node type name.
  $node->uid = $user->uid;
  $node->title = t('Title'); // Change title generation
  $node->body = t('Body'); // Change body generation
  $node->og_description = t('Group description'); // Change group description generation
  $node->og_selective = OG_CLOSED;
  $node->og_register = OG_REGISTRATION_NEVER;
  $node->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
  $node->og_private = 0;
  node_save($node);
  og_insert_group($node);
  og_save_subscription($node->nid, $node->uid, array('is_active' => 1, 'is_admin' => 1));

(ofcourse you also need to check the return values from alle the three functions)
Answer: I don't really understand the question, but I created a lot of groups using the Mass Create module.
Comment: well laxman13 and Reg Gordon - thx for the answer. I try to do it like you. I come back and report all my findings!
Answer: I was in the same struggle, but I realized that to create a new OG group programatically, the Rules module could be the key.
If you look for the right trigger and conditions, the first action would be "Entities > Create a new entity >OG group.
You can use the Rules scheduler to do the timing, if necessary.

Programmatically create a organic group


"Kolmogorov complexity with time"

Question: Kolmogorov complexity of object is minimal length of program that print this object.
1)Kolmogorov complexity is not a computable function.
2)If there is little program that print object for  billion years we say that Kolmogorov complexity of object is little yet. I think it is strange.
We can define "Kolmogorov complexity with time" of  $x$ as min of $\{L_PT_P\}$, where $P$ is program that print $x$, $L_P$ - its length, $T_P$ - is time of its work.
So its definition solve the first and seconds problem.
Is there resulats about "Kolmogorov complexity with time"?
Answer: There's a survey paper here of some "resource bounded" variants of Kolmogorov complexity and their relation to complexity theory. It doesn't have your exact definition, but Levin's and Allender's (definition 2.5 and 2.6 respectively) are pretty close.

"Kolmogorov complexity with time"


How to explain the truth table of $φ=>ψ$?

Question: I was taking the coursera of "Introduction for Mathematical thinking". In one lecture, we are given the following truth table about:
$$\begin{array}{c|c|c}
φ &ψ &φ \implies ψ\\
\hline
T &T &T\\
T &F &F\\
F &T &T\\
F &F &T
\end{array}$$
The first two lines are easy to understand.
But what about third and fourth lines?
Let me make two examples:
"I am a dog"(False) implies that "I am a student"(True); this is true.
"I am a dog"(False) implies that "I am an American"(False); this is true.
The above two claims are ridiculous!
How can they be true? Did I make any mistakes for these two claims?
Edit:
Thanks for answering the questions! It seems all about the definition of vacuous truth.
Comment: The third and fourth lines are [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth). Try a search too: http://math.stackexchange.com/search?q=vacuous
Comment: @AlexisOlson many thanks I am having a look.
Comment: Really, you find the first line easy to understand? How about: 'if snow is white then grass is green'?
Comment: @Bram28 This deduction should not be true but still it can be understood.
Comment: @zlin So how do you understand it? Anyway, I recommend you search for 'material conditional' or 'material implication'... Many people have asked your question before, and there are some really good answers there.
Comment: @Bram28 ok I will check. Many thanks!
Answer: The key point is that an implication makes no claim when the antecedent is $\color{red}{\text{false}}$. When you say "if I am a dog, then I am an American," how would I prove you wrong? I would have to first argue that you are a dog, and then that you are not an American. I take you at your word that you are not indeed a dog, so this is a hopeless task.
So the implication $\phi \implies \psi$ says that whenever $\phi$ is $\color{green}{\text{true}}$, $\psi$ is also $\color{green}{\text{true}}$. If $\phi$ is $\color{red}{\text{false}}$, there is nothing to check, and the implication holds vacuously.
Answer: You made no mistake, your truth tables are correct.  But the claims are not as ridiculous as you might think.  Imagine the statement "If $x>1$ then $x^2>1$."  You'd like this to be true, because you can prove it.  But what if you set $x=-400$?  The statement says "If $-400>1$ then $(-400)^2>1$".  This is an example of false implies true.
Or if you plug in $x=0$: "If $0>1$ then $0^2>1$".  This is an example of false implies false.  The point is that with the "If-Then" structure, we only really care about what happens if the "If" part is true, because that's all the statement is concerning itself with.  It doesn't worry about what happens if the "If" part is false; no matter what comes after, the statement is still true.


How to filter the datetime column in a SQL table with SQLalchemy in python?

Question: I have a SQL table, and I query the table with SQLalchemy with python.
goog = pd.read_sql("\
\
SELECT dp.price_date, dp.adj_close_price \
FROM symbol AS sym \
INNER JOIN daily_price AS dp \
ON dp.symbol_id = sym.id \
WHERE sym.ticker = 'GOOG' \
ORDER BY dp.price_date ASC",

con = engine,
index_col='price_date')

Now my problem is, the price_date data type is datetime, I tried to filter in the WHERE clause, but failed. Like this:
price_date BETWEEN 2021-11-08 00:00:00.00000 AND 2021-11-12 00:00:00.000000

and this:
price_date BETWEEN 2021-11-08 AND 2021-11-12

Any solution?
Answer: in both cases dates need a single quote
price_date BETWEEN '2021-11-08 00:00:00.00000' AND '2021-11-12 00:00:00.000000'

and this:
DATE(price_date) BETWEEN '2021-11-08' AND '2021-11-12'

Also good for reading about quotes in mysql When to use single quotes, double quotes, and backticks in MySQL


Using .less to get the width of the screen

Question: I want to make a page that has a 200px header and a gradient that stretches from each side of the 200px to the edge of the screen. Can i use .less to say: make the width of each gradient section the width of the screen - 200px, divided by 2 (because there are 2 gradients, one on each side)
Comment: LESS **is** CSS. If you can't do it with CSS, you won't be able to do it with LESS.
Answer: LESS compiles to CSS, so it can't measure.
If I understand your question correctly, you could make a gradient 100% percent width, and position it behind your header, and give your header a background color.
HTML:

    [...]

LESS:
#gradient-wrapper {
  // CSS for gradient
  width: 100%;

  header {
    width: 990px;
    margin: 0 auto;
    height: 200px;
    background-color: white;
  }
}


how do I build a dynamic URL in views?

Question: I am using drupal 7, have a content type and two taxonomy categories, size and shape.
Im trying to build a dynamic url such as mysite.com/node/nid/tid/tid, which would get rewrote as e.g mysite.com/page-1/large/square.
I want the content of the url to just show the node, so in this case node/1. But I am also going to make 2 blocks one for category size and another block for category shape which will get the relevant IDs from the url and show the relevant content, in this case block 1 will show large and block 2 will show square.
I thought I could generate the page in views by setting the URL to node/%/%/% or node/%//
and setting arg 1 to nid, but this comes back as page not found.
So I am wondering is this possible in views if not how can I create a url such
/arg1/arg2/arg3 which represents /a nid/a category 1 tid/a category 2 tid, and then populate the page dynamically?
Thanks for any help
edit/
So I have got the arguments working. mysite.com/%/%/% by setting the last argument as the target page rather than the first argument. But how can I rewrite the url. So arg1 becomes node title, arg2 becomes term id 1 and arg3 becomes term id 2 title?
Answer: You'll need to set your pathauto pattern settings to rewrite your URL. Goto Configurations > Search and metadata > URL aliases > Patterns. Set the pattern for your content type to:
<code>[node:title]/[node:field_...]/[node:field_...]
</code>
Where the "node:field_..." is replaced with the respective tokens for your taxonomy fields.

how do I build a dynamic URL in views?


Can I SSH to my Google Cloud compute engine VM without allowing traffic from 0.0.0.0/0 in firewall rule?

Question: I wish to access my debian VMs in Google Cloud Compute Engine with SSH, but I don't want to allow traffic from universal range i.e 0.0.0.0/0 in the firewall rules as we process confidential information and want only authorized traffic to connect to our VMs.
Is there a way to attain that?
Comment: The obvious solution is changing the firewall rules to only allow traffic from your IP address(es). What stops you from doing that? I don't really see a question to be answered here.
Comment: We have tried doing that, but then when we try to SSH, 'SSH unable to connect port 22' error comes. It gets corrected when we set the IP ranges to 0.0.0.0/0 again.
Comment: That means you have specified wrong IP addresses in firewall rules. Make sure you have a static IP address where you are connecting with SSH from, and then specify that in firewall rules.
Answer: I advice you to try adding one by one the IP to your firewall rule, and see if its not working for all of them or only for a few of them or for a specific one. Another thing you can check is the mask on the firewall rule, probably you are missing something in there. Let me know if you have some progress


OpenOffice extension to change UI behavior

Question: Is it possible to develop an extension to intercept some functions such as Save, Save As, Save All, Send by Email, Print, etc.
I would need to intercept both mouse click and shortcuts when applies.
Thanks on advanced.
Answer: Look at Tools> Customize...
You can hook macros to these events.
Comment: AFAIR there is a way, designing the macros as `FUNCTION`s and returning `FALSE` - but I can't find the answer now.
OTOH see this thread in the AOO community forum
https://forum.openoffice.org/en/forum/viewtopic.php?f=5&t=23144
for intercepting the dispatched commands.
Comment: You can get notifications but you can't change the behavior.
Comment: Do you know if the user can uninstall this macros from the UI?
Comment: If installed in user space libraries - they can (even if password protected).
Install system wide.


Atualizar chave em state quando outra chave for atualizada

Question: A ideia principal baseia-se em um carrinho de compras, quando um produto é adicionado ao carrinho (chave products) a chave orderTotal é atualizada.
Dentro da chave products possuo um object com varios produtos que contem cada um o valor, e o total de produtos de compra: ordered e price, exemplo:
state = {
    products: {
        "a": {
            name: "A",
            price: 2
            ordered: 5
        },
        "b": {
            name: "B",
            price: 5,
            ordered: 2
        }
    },
    orderTotal: 0
}

Tentei colocar um reduce() dentro de componentWillUpdate(), porém não consigo usar this.setState() dentro de componentWillUpdate() pois isso gera um loop infinito.
componentWillUpdate () {
    const products = {...this.state.products};
    const orderTotal = Object.keys(products).reduce((sum, next) => {
        return sum + (products[next].ordered * parseFloat(products[next].price));
    }, 0);
    this.setState({ orderTotal }); // Loop infinito.
}

Preciso que toda vez que o products for atualizado, realizar um loop realizando o calculo de ordered * price e armazenar a soma de tudo em orderTotal, qual método posso utilizar?
Comment: O componente Carrinho recebe o objeto products via props?
Comment: @MiguelAngelo não, o state `orderTotal` fica somente no componente pai não é passado pra nenhum outro componente.
Comment: Mas e o objeto **products**? De onde ele vem?
Comment: Ele é iniciado vazio através do construtor, para o usuário adicionar produtos eu passo uma função para um componente filho que consegue adicionar outros objetos dentro de produtos
Answer: Sobre setState
Como os dados são armazenados no state do Carrinho, então a melhor forma de ativar uma nova renderização é usando setState do Carrinho. Essa nova renderização será feita assim que possível, mas não imediatamente... é como se fosse um setTimeout passando 0.
Importante: Isso quer dizer que o state não é alterado imediatamente após a chamada de setState.
Dito isso, existem duas alternativas para alterar o state, caso mais de uma alteração dependa do state anterior:

alterar tudo de uma vez:
setState({total: valorTotal, partes: valoresDasPartes })

alterar usando callback:
setState({partes: valoresDasPartes})
setState((s,p) => {total: s.partes.reduce((a, b) => a + b, 0)})

A questão que resta é onde se deve usar setState?

R: Dentro da callback que Carrinho passa para o filho.

Exemplo
class Carrinho extends React.Component {
  render() {
    var listaProds = []
    for (var n = 1; n < 10; n++)
      listaProds.append(
        <Produto
          nome={"Produto "+n}
          adicionar={p => this.addProd(p, +1)}
          remover={  p => this.addProd(p, -1)}
          />)
     return (

{listaProds}

Total: {this.state.orderTotal}

       )
  }

  addProd(p, quant) {
    // adicionando o produto
    this.setState(function (state) {
        var s = {}
        s.products = state.products
        p = s.products[p.key] = s.products[p.key] || Object.assign({}, p, {ordered: 0})
        p.ordered = Math.max(p.ordered + quant, 0)
        return s
    });
    this.recalculaTotal()
  }

  recalculaTotal() {
    this.setState(function (state) {
        return {
            orderTotal: state.products
                             .map((p) => p.ordered * parseFloat(p.price))
                             .reduce((a, b) => a + b, 0)
        }
    });
  }
}

Comment: Miguel acho que minha questão não ficou clara o suficiente, os componentes filho do "carrinho" não alteram o state, para facilitar o entendimento por favor veja [este link do arquivo no github](https://github.com/rafa-acioly/simple-store/blob/master/src/components/FrontStore/FrontStore.jsx), quando passo os produtos para os componentes filho eles só renderizam e para "alterar" essa prop eu passo uma função via prop para poder atualizar o state do componente pai.
Comment: Neste caso, fica valendo apenas o segundo ponto da minha resposta. Veja que dentro de `addProduct` eu chamo `recalculaTotal`.
Comment: entendi, é que o valor precisa ser recalculado diversas vezes, tanto quando é adicionado um produto quanto alteração de quantidade e etc.
Comment: Exato... eu falei sobre isso. Apaguei o primeiro ponto que não fazia sentido.
Comment: o `React` por sí só não possui nenhum método do tipo então? para realizar "watch" na alteração do state... ?
Comment: Acho que a proposta do React é essa... os caminhos que levam à alteração de um dado são lineares, previsíveis. Ao contrário do Angular por exemplo, que permite essas cascatas de eventos.
Comment: quando você passa a função `addProd` para o componente de `produto` na teoria teriamos que usar um `onChange` do lado do componente produto e chamar a função `addProd` com `this.props.adicionar()`? não entendi bem essa parte...
Comment: É isso... no meu exemplo o componente de produto chamaria this.props.adicionar passando como argumentos os dados do produto, ou this.props.remover pro caso contrário... lembrando que quando vc passa uma callback pra um componente vc tem que dar bind no this, ou usar a notação de lambda que já faz o bind automático.
Comment: @RafaelAcioly Conseguiu resolver? Ficou claro o que eu falei? Se não eu tento de outra forma. =)
Answer: Na documentação oficial diz que o this.setState() não deve ser chamado dentro do componentWillUpdate, se deseja atualizar o state quando uma propriedade for modificada deve fazer isso dentro do método componentWillReceiveProps.

componentWillUpdate() is invoked immediately before rendering when new
  props or state are being received. Use this as an opportunity to
  perform preparation before an update occurs. This method is not called
  for the initial render.
Note that you cannot call this.setState() here. If you need to update
  state in response to a prop change, use componentWillReceiveProps()
  instead.
Comment: O state atualizado é em um "componente pai", eu passo um objeto para um componente filho juntamente com uma função, logo, o que está sendo alterado é o state não uma prop.


cakephp label in checkbox

Question: i'm trying to get a checkbox with his label
echo $this->Form->checkbox('straordinari', array('div'=>'true', 'label' => 'Straordinari'));

in browser i get
<input id="ReportStraordinari_" type="hidden" value="0" name="data[Report][straordinari]">
<input id="ReportStraordinari" type="checkbox" value="1" label="Straordinari" div="true" name="data[Report][straordinari]">

but there is no label
where is the problem?
Answer: You should get what you are looking for with the following:
echo $this->Form->input('straordinari', array('type' => 'checkbox'));

Answer: I using :
<?php
echo $this->Form->input('coupDeCoeur',
array('div' => false,
'label' => false,
'type' => 'checkbox',
'before' => '',
'after' => 'coupDeCoeur'
));
?>

cakephp label in checkbox


What is the difference between a Low-pass filter and a Cut-off filter

Question: The TB-03 has a knob labelled 'CUT OFF FREQ'. I assume it´s a cut-off filter because Roland´s manual describes this knob as 'Filter cutoff (brightness of the sound)':

The Allen&Heath Xone 4D mixer has a filter called 'Low-pass filter':

When I turn both knobs it seems to me that they do the same thing: they filter out the high frequencies and pass the low frequencies.
Therefore my question: What is the difference between a low-pass filter and a cut-off filter?
Note: I think there is no difference. I think the term 'cutoff' refers to the point where Low-pass and High-pass filters begin to cut off the frequency.
Comment: You may find it interesting that the "wah-wah" pedal, is effectively a variable band-pass filter - that is, it cuts off all frequencies both below and above certain points. These cut off points are changed more or less in parallel so that the 'slot' of frequencies that are passed shifts upwards or downwards as the control is used.
Comment: Are you absolutely sure that the "cut off frequency" means you have a "cut off filter"?  Low pass filters require a cut off frequency.
Comment: it seems that in the audio industry "cut off" is used as a generic term for band pass filters, high pass as well as low pass, etc.  I am not used to this use of terminology.
Comment: @ggcg: regarding your first question, here my answer: "I assume it´s an Cut-off filter".
Comment: See my second.  It is typical for specialized industries to make their own jargon out of physics and engineering terms.  I am not that adept at synth, or the use of effects on my guitar (I play clean).  But from a purely signal processing point of view "cut off" is a term that applies to all filters so it's hard to tell.  Which is why I'm asking in comments rather than answering.  I find it interesting.
Answer: "Cut-off" is ambiguous, since it could be cutting off either low or high-frequency material.  Since the manual you quote refers to 'brightness' of sound, my guess is that it's a low-pass, high-cut filter.
For completeness' sake, a "bandpass" filter is just that: cuts everything above and below a specified frequency range.
Comment: @David Z: Yes, his description of a bandpass filter sounds also accurate to me. But both filters, the one of the TB03 and the one of the Xone 4D are no bandpass filters.
Answer: Every filter requires a cutoff frequency, which determines the point at which the filter begins to attenuate the frequencies in the appropriate direction (low pass filter attenuates high frequencies, hipass filter attenuates low frequencies).
This is almost certainly a low pass filter, and the knob controls the cutoff frequency, thus controls the brightness of the sound based upon setting the frequency beyond which we begin to attenuate.
Every filter has a cutoff frequency. I've never seen the term "cutoff filter" used in a professional context.
Note: you will almost never find a hi pass filter on a synth or drum machine that does NOT have a low pass filter. Hi pass filters are considered somewhat of a luxury on hardware and are quite rare to find. I cannot think of a single synth or drum machine that has a hi pass filter which does NOT have a low pass filter. Although, they probably exist (very rare) and perhaps someone can share one in the comments if they know of one. The rule of thumb is to always assume a low pass filter. Also, band pass filters are even more rare.
Comment: Um, allpass filters have little to do with comb filters; those rather act like a cascade of notch filters. And like with notches, their frequency parameter doesn't set "where the notch begins", but instead the singular frequency that is completely removed. What allpass filters do is simply rotate the phase of the signal without affecting its amplitude – which is similar to what a _delay_ does. And a simple comb filter is built by mixing a signal with a constant-delay copy, I reckon that's what you meant there.
Comment: "Every filter has a cutoff frequency" – you wouldn't call it _cutoff_ though for many filters. That term doesn't make sense for notch filters, shelving filters, allpass filters, etc. etc.. For hi- and low pass filters I've heard it quite often though. As for hi pass filters... I know nothing about drum machines, however it's certainly not such an uncommon feature on general synths. But yeah, low pass filters are always much more common.
Comment: It is extremely uncommon on a synthesizer to have a hi pass filter and NOT have a low pass filter. In the grand scheme of hardware synths, the majority do not have hi pass filters, but yes they are not terribly uncommon. As for shelving filters, the term "cutoff" seems wholly appropriate, given that if you attenuate the frequencies beyond that point you effectively have a low / hi pass. If you boost the frequencies instead you have inverted the filter and effectively attenuate the opposite end. Notch filters use a cutoff to determine where the notch begins, and Q to determine the width.
Comment: Allpass filters are essentially comb filters. Their cutoff value simply adjusts the phase relationship based on a certain frequency. It does effectively provide a multi notch filter that is dependent on the frequency and the notes played. In a technical jargon sense, one would still expect to hear this lingo imo.
Comment: @leftaroundabout you're right, I was thinking of an allpass filter being constructed from a feed forward and feedback comb filter. But that's true, it does have a different spectrum than a simple comb filter.
Answer: In this case, both filters appear to do the same, according to the symbols and language.  High and lowpass filters, however, can also be implemented as "shelving" filters which is pretty common for equalizing purposes.  In that case, the frequency response becomes level ("a shelf") again when going significantly beyond the corner frequency of the filter.
The cutoff filter symbol for the Allen&Heath appears to suggest a resonant bump in the frequency response at the corner frequency before going down.  That makes for a steeper filter curve at the cost of, well, a bump.
Comment: This is nothing to do with the Gibbs phenomenon. It's a by-product of one approach to designing second-order filters, and musically it is quite useful, since many acoustic instruments have a similar "bump" at the top end of their frequency response. Usually,  you can control the width of the "bump" with a control labeled "Q factor" or similar, and the center frequency of the bump with the "cut off". If you set the Q to 1, the effect is the same as a simple low-pass filter without a bump in response at the corner frequency.
Comment: "... bump..."  See "GIbbs Overshoot Phenomenon"
Comment: Really "Many acoustic instruments"? Can you provide some links to test data on orchestral instruments?
Answer: If you look at the devices these knobs are on - a bass synth/sequencer and a DJ mixer offering some weird 'effects' - not just zooming in on one knob, you'll see that they are both part of a resonant filter with both a Cut-off control and a Resonance one.  It's more than a 'tone control' setup.
It's generally futile to analyse the labels on music-tech gear too pedantically.  But in this case I think we can say they do just about exactly the same thing.
Comment: It sounds like you experience with these devices is quite similar to mine and labeling the knobs is affected by the perspective of the designers.


SQL Query to Count data between 6:00 Am to next day 6:00 AM

Question: I am new to programming.
I want to count the column value from 6 Am to next day 6 AM. I tried using the below query but it gives the value for 12 AM to 12 AM. The Query is
SELECT      (COUNT  (COLUMN_NAME)) AS TOTAL
FROM        TABLE_NAME
WHERE       AREA = 1
AND         TRIM(DATE_COLUMN) = TRIM ((SYSDATE)+6/24)

Here I cannot use date, this will update the value in Windowsforms app developed in delphi2007.
Comment: `trim()` is for string/character values , **not** for `DATE` columns. you probably meant to use `trunc()`
Answer: select count(column_name) as total
from the_table
where area = 1
  and the_date_column
           between trunc(sysdate) + interval '6' hour
               and trunc(sysdate + 1) + interval '6' hour;

trunc(sysdate) sets the time part of the date to 00:00:00 when you then add 6 hours to that you get 06:00 (6 AM)
trunc(sysdate + 1) returns a date a midnight so if it's currently 2016-10-08 17:00:00 that will return 2016-10-09. If you add 6 hours to that, it's 06:00 the next day.

Not sure what you mean with "I can not use DATE". If made the big mistake to store your dates as  VARCHAR you should change that and store them correctly in a DATE column. If for one reason you can't do that, you should convert that column to a date and compare dates, not strings:
and to_date(the_date_column, 'yyyy-mm-dd hh24:mi:ss') between ...

Make sure you specify the correct format mask to convert the varchar to a DATE.
Answer: DECLARE @StartDate datetime = '2014-01-01';
DECLARE @EndDate datetime = '2014-01-02';

SET @BeginDate = DATEADD(HOUR, 9, @StartDate);
SET @EndDate = DATEADD(HOUR, 8, @EndDate);

SELECT
 YourTable.ReadingDate,
 YourTable.Hours,
 YourTable.Data1,
 YourTable.Data2,
 YourTable.Data3
FROM
 YourTable
WHERE
 DATEADD(HOUR, YourTable.Hours, YourTable.ReadingDate) BETWEEN @StartDate AND @EndDate;

Comment: While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Comment: That is not valid for oracle
Answer: Why you can't use  date?
you may use a charcter string and change format to properly one.
variable = '2016-10-08'
to_Date(varable||' 06:00:00','yyyy-mm-dd HH24:MI:SS')

If you want just get values between today 6 o'clock and ensuing day 6 oclock
For example
SELECT (COUNT (COLUMN_NAME)) AS TOTAL
FROM TABLE_NAME
WHERE AREA = 1
AND DATE_COLUMN between trunc(sysdate,'DD') + 6/24 and trunc(sysdate+1,'DD') + 6/24


Google App Engine - SQL Access Control - Could not complete the operation

Question: I've created my app and SQL container on Google App Engine. All is ready to go, I just need to grant network access to the SQL server from the application. When clicking the Add Item button, then entering the Application ID (I verified through what appears to be an ancient deprecated interface) then clicking save I get the following error:
Could not complete the operation. Dismiss
I've read the instructions and as far as I can tell this is the correct method. It's the same region as the App. Tried us-east and us-west.
I created another SQL instance just in case with the same results.
I checked the dns records of the provided application URL and added the 4 IPv4 and IPv6 addresses that were returned just in case I could do it that way. The app still can't connect to the database.
I'm not sure what to try next, does anybody have an idea how to allow access in this situation?
Answer: I created my Project in US-east1 originally, had the same problem as above. Went back and created another project in US-central. This problem "Could not complete the operation. Dismiss" went away. Easy way to tell that it is working, the "Preferred location" will auto populate with "Follow App Engine app", the "App Engine application id" will auto populate with your project app id, the "Authorized App Engine applications" will auto populate with the project app id as well.


NSDate show wrong date with NSTimezone

Question: Hi I am trying to display GMT time to my device time.
my device time zone is EDT.
I got the GMT time as a string
<code>       // GMT Time-----2014-11-27 19:32:00

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter.dateFormat = @"HH:mm:ss";
 NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
 NSDate *startDate = [dateFormatter dateFromString:@"2014-11-27 19:32:00"];
</code>
I am getting this start date as -
<code>    //startDate---2014-11-27 19:32:00 +0000
</code>
Now I am trying to convert this into my local time
<code>NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
dateFormatter2.dateFormat = @"hh:mm a";
NSTimeZone *local = [NSTimeZone localTimeZone];
[dateFormatter2 setTimeZone:[NSTimeZone localTimeZone]];
NSString *startDateStr = [dateFormatter2 stringFromDate:startDate];
</code>
As per my timezone(EDT) the result must be - 3:32 PM
But I am getting wrong time as
<code>  //startDateStr---02:32 PM
</code>
I have printed my timezone difference with GMT
<code>    NSLog(@"TimeZone  %d",[[NSTimeZone localTimeZone] secondsFromGMT]);
   // TimeZone   -14400     - this correct and as per this the startDate must be 03:32 PM
</code>
Where I am making the mistake ?
Please help me
Answer: Very clever. The date that you converted was on January 1st 2000. So daylight savings time was different back then. 19:32 GMT on the 1st of January was 2:32pm in your time zone. But 19:32 GMT today is 3:32pm in your time zone.
Comment: Please see my updated question. I have changed the start date, but still it getting wrong time.

NSDate show wrong date with NSTimezone


What argument to pass in the SARIMAX model

Question: I have daily data for 3 years and I want to use a SARIMA model. However, I'm a bit confused about what argument I should pass into the seasonal_order regarding the seasonal period.
I use python and the corresponding SARIMA model is statsmodels.tsa.statespace.sarimax.SARIMAX. I have the impression it should be 365, but I am no entirely sure, since I get a memory error.
Comment: https://stats.stackexchange.com/questions/188597/forecasting-technique-for-daily-data-with-monthly-and-day-of-week-seasonality/188618#188618 provides analytic options which use anthropogenic factors.
Answer: The seasonal order that needs to be passed to a SARIMA model needs to be identified beforehand. To identify that, you need to identify a) Seasonality S; b) the seasonal differencing order D which typically is either 0 or 1; c) the seasonal autoregressive order P; and d) the seasonal moving average order Q. One way to obtain preliminary values for those, is to visually scan the autocorrelation function (ACF) together with the partial autocorrelation function (PACF) of your time series (if the time series is stationary) or ACF and PACF of your appropriately differenced time series, if your time series is non stationary.
a) To identify seasonality S, take a look at the ACF. If you notice a spike at multiples of a certain integer S, i.e. at lag S, 2*S, 3*S, etc. that is a tell-tale sign that the seasonality is S. E.g., if you have hourly data, S may be 24 (hours); if you have weekly data S may be 7 (days); if you have quarterly data S may be 4 (quarters); etc. When identifying S, it is easier to look at the ACF with a pre-conceived expectation of what the seasonality might be.
b) To identify D look at your ACF and observe if the spikes at seasonal lags (i.e. at lag S, 2*S, 3*S, etc.) tend to be persistent or whether they die out quickly after a few (typically one or two) lags. If they are persistent D is tentatively identified to be 1; otherwise (if they die out "quickly") 0.
c) To tentatively identify a value to be passed for P, put ACF and PACF next to each other and visually scan their behavior only at the seasonal lags. If PACF has $P^*$ spikes at seasonal lags after which it cuts off abruptly, while ACF shows a more or less gradually decaying pattern of spikes at seasonal lags, that is an indication that $P=P^*$
d) To tentatively identify a value for Q, again consider ACF and PACF and focus only at the seasonal lags. If ACF has $Q^*$ spikes at seasonal lags after which it cuts off abruptly, while PACF shows a more or less gradually decaying pattern of spikes at seasonal lags, that is an indication that $Q=Q^*$
To get a better grasp at this, read Bisgaard, S. R., & Kulahci, M. (2008). Quality quandaries: Forecasting with seasonal time series models. Quality Engineering, 20(2), 250-260.


Conditional Expectation Inequality for bounded moment

Question: I was going through a proof in Agnostic Estimation of Mean and Variance (Lemma 3.12, page 21) and encountered the following:

Let $X$ be a random variable with $\mathbf{E}[X] = \mu$ and $\mathbf{E}[(X-\mu)^2] = \sigma^2$
Let $A$ be an event that occurs with probability $1-\epsilon$ and let $A^c$ be the complement (i.e. $P(A^c)=\epsilon$)
Let $d \Omega$ be the probability measure

Using $E\big[(Y - E[Y])^4\big] \geq \big(E\big[(Y-E[Y])^2\big]\big)^2$ for a random variable $Y$, and $P(A^c)=\epsilon$, we have
$$
\frac{1}{\epsilon} \bigg( \int_{A^c} (X - \mu)^2 d\Omega \bigg)^2 \leq \int_{A^c} (X - \mu)^4 d\Omega
$$
What I do not understand is where the $\frac{1}{\epsilon}$ is coming from when just using the proposed inequality with $Y = X \mid A^c$?
And how to show the inequality still holds?
Answer: So this is actually trivial but the notation was confusing me.
Because $d\Omega$ is the probability measure for the entire space, $\int_{A^c}(X-\mu)^2 d\Omega=P(A^c)Var(X \mid A^c)$ so we'd have to normalize it.
$$
\begin{aligned}
&\bigg( \int_{A^c} (X - \mu)^2 d \Omega \bigg)^2 \leq \int_{A^c} (X - \mu)^4 d\Omega
\\
&\implies \bigg( \frac{1}{P(A^c)} \int_{A^c} (X-\mu)^2 d\Omega\bigg)^2 \leq \frac{1}{P(A^c)} \int_{A^c} (X - \mu)^4 d\Omega\\
&\implies \frac{1}{P(A^c)}\bigg(  \int_{A^c} (X-\mu)^2 d\Omega\bigg)^2 \leq \int_{A^c} (X - \mu)^4 d\Omega
\end{aligned}
$$


Show that every real number is a limit of rational number.

Question:
Show that every real number is a limit of rational number.

I understand that the statement is true and very trivial. But how can I mathematically show that! Please help.
Answer: Hint
$$\forall x\in\mathbb R,\quad x_n=\frac{\lfloor10^n x\rfloor}{10^n}\to x$$
Comment: Is $x_n$ rational?
Comment: Of course it's rational as quotient of two integers.