(Borel) Normal number problem

Question:
Problem: Given an integer $b \ge 2$, a number $x \in [0,1)$ is (Borel) normal base-b, if its b-ary representation as a sequence $(\sigma_1,\sigma_2,...)$-where $\sigma_i \in \{0,1,...,b-1\}$ are such that $x=\sum_{i \ge 1} \sigma_i b^{-i}$-obeys the following: For eaach $r \ge 1$ and each $\overline{\sigma_1},...,\overline{\sigma_r} \in \{0,1,...,b-1\}, \frac{1}{n}\#\{k=1,...,n:(\sigma_{k+1},...,\sigma_{k+r})=(\overline{\sigma_1},...,\overline{\sigma_r})\}$ converges to $b^{-r}$ as $n \rightarrow \infty$. A number x is absolutely normal if it is normal base b for every integer $b \ge 2$. Prove if $\mathcal{U}=\textbf{Uniform}([0,1])$, then $\mathcal{U}$ is absolutely normal almost surely.

Theorem 1: Almost every real number is absolutely normal.
Proof: A number $x \in (0,1)$ is not absolutely normal if there exist $b \ge 2$, $L \in \mathbf{N}$ and $a_1,...,a_L \in \{0,...,b-1\}$ such that if $x=\sum_{n=1}^{\infty} \frac{c_n}{b^n}$ then $$\textbf{lim inf}_{n \rightarrow \infty} \frac{\# \{n \le N-L |c_{n+i}=a_i,i=1,...,L\}}{N}<\frac{1}{b^L}$$. Then there exists $s \in \{0,...,L-1\}$ such that $$\textbf{lim inf}_{n \rightarrow \infty} \frac{\# \{n \le N-L, n \equiv s (\textbf{mod L}) |c_{n+i}=a_i,i=1,...,L\}}{N}<\frac{1}{Lb^L}$$. Hence for some rational $\beta<\frac{1}{Lb^L}$, $$\textbf{lim inf}_{n \rightarrow \infty} \frac{\# \{n \le N-L, n \equiv s (\textbf{mod L}) |c_{n+i}=a_i,i=1,...,L\}}{N} \le \beta$$. Denote by $R_{b,La,s,\beta}$ the set of all $x=\sum_{n=1}^{\infty} \frac{c_n}{b^n}$ satisfying $$\textbf{lim inf}_{n \rightarrow \infty} \frac{\# \{n \le N-L, n \equiv s (\textbf{mod L}) |c_{n+i}=a_i,i=1,...,L\}}{N} \le \beta$$
. The result of the prvious paragraph is that the set of not absolutely normal number is a subset of $$\bigcup_{b=2}^{\infty} \bigcup_{L=1}^{\infty} \bigcup_{a_1,...,a_L}^{b-1} \bigcup_{s=0}^{L-1} \bigcup_{\beta \in (0, \frac{1}{Lb^L}\cap \mathcal{Q}} R_{b,L,a,s,\beta}$$.
It is sufficient to prove every set $R_{b,L,a,s,\beta}$ has zero measure. Then the set of not absolutely normal numbers is a subset of a countable union of null sets, hence it is a null set.
Let $b \ge 2, L \in \mathcal{N}, a_1,...,a_L \in \{0,...,b-1\}, s \in \{0,...,L-1\}$ and $\beta \in (0,\frac{1}{Lb^L}$. Put $A=a_1b^{L-1}+a_2b^{L-2}+...+a_L$. Let $$x=\sum_{n=1}^{\infty} \frac{c_n}{b^n}=\sum_{n=1}^s \frac{d_n}{b^n}+\frac{1}{b^s}\sum_{n=1}^{\infty} \frac{d_{s+n}}{b^{Ln}} \in R_{b,L,a,s\beta}$$. Then obviously $$\# \{n \le N-L,n \equiv s(\textbf{mod L})|c_{n+i}=a_i,i=1,...,L\}=\# \{s<n \le [\frac{N-s}{L}]|d_n=A\}$$. Hence $$\textbf{lim inf}_{M \rightarrow \infty} \frac{\# \{s<n \le M| d_m=A}{M}=\textbf{lim inf}_{N \rightarrow \infty} \frac{\# \{s<n \le [\frac{N-s}{L}]|d_n=A\}}{[\frac{N-s}{L}]} \le L\beta$$. From this we obtain $R_{b,L,a,s\beta} \subseteq P$, where $$P=\{x=\sum_{n=1}^s \frac{d_n}{b^n}+\frac{1}{b^s}\sum_{n=1}^{\infty} \frac{d_{s+n}}{b^{Ln}}|\textbf{lim inf}_{N \rightarrow \infty} \frac{\# \{s<n \le N |d_n=A\}}{N} \le L \beta\}$$. Then it is sufficient to prove that the set P has zero measure.
The complete version of the proof is found here.
An elementary proof that almost all real numbers are normal

My question is how am I supposed to mimic the proof to solve the problem? Thanks a lot!
Comment: "If $\mathcal U = {\bf Uniform}([0,1])$, then $\mathcal U$ is $X$ almost surely" means the same as "Almost every member of $[0,1]$ is $X$".
Comment: @r.e.s. Thanks, fixed it.
Answer: I found [5] in the article you mentioned particularly useful. We only need to prove a simpler version of theorem 8.1 (and corollary 8.2) in the book. So here is my answer:
Suppose $X\sim U(0,1)$. Given $b\geq 2$, and fixed $r\geq 1$. Consider the $b-$ary expansion of $x = \sum_{i=1}^\infty \sigma_ibi^{-1}$. We are interested in the probability of a given string: $(\bar{a}_1,\bar{a}_2,...\bar{a}_r)$, where $a_i = 0,1,...b-1$.
If the target string matches $x$ at index $m$, we can rewrite $x$ by replacing the digits from index $m$ to $m+r-1$:
$$
\begin{split}
    x &= \sum^\infty_1 \frac{\sigma_i}{b_i}\\
    &= \sum^{m-1}_{1} \frac{\sigma_i}{b^i} + \sum^{m+r-1}_{m} \frac{a_i}{b^i} + \sum_{m+r}^\infty \frac{\sigma_i}{b^i}
\end{split}
$$
Multiply both sides by $b^{m-1}$:
$$
b^{m-1}x = (b^{m-1}\sum^{m-1}_{1} \frac{\sigma_i}{b^i}) + \frac{a_mb^{r-1}+a_{m+1}b^{r-2}+ ...a_{m+r-1}}{b^r} + \sum_{r+1}^\infty \frac{\sigma_{m+i-1}}{b^i}
$$
The fractional part $\{b^{m-1}x\}$ doesn't contain $(b^{m-1}\sum^{m-1}_{1} \frac{\sigma_i}{b^i})$, and we have $\sum_{r+1}^\infty \frac{\sigma_{m+i-1}}{b^i}< 1b^{-r}$ since they are the trailing digits of this expansion. Therefore,
$$
\{b^{m-1}x\}\in [\frac{a_mb^{r-1}+a_{m+1}b^{r-2}+ ...a_{m+r-1}}{b^r}, \frac{a_mb^{r-1}+a_{m+1}b^{r-2}+ ...a_{m+r-1} + 1}{b^r}) = I_r
$$
Whenever there is a matching sequence, we have $\{b^{m-1}x\}\in I_r$.
Since $X\sim U(0,1)$, we have that $\{b^{m-1}X\}\sim U(0,1)$ because any fractional part is uniformly distributed across each interval $[n,n+1)$, where $n = 0,1,...b^{m-1}-1$. Since $b^{m-1}X$ is uniform, each interval has probability $1/b^{m-1}$ and therefore the marginal distribution of $\{b^{m-1}X\}$ is uniform $(0,1)$.
Given the first $N$ digits of the expansion of $x$, we need to check $N-r+1$ possible starting point of the desired sequence $b_1b_2...b_r$ and this is equivalent to $\sum^{N-r+1}_1X1_{I_r}$, where $X\sim U(0,1)$. Hence by SLLN,
$$
\lim_n \frac{\{\# k = 1,2,...n: (\sigma_k...\sigma_{k+r}) = (b_1,b_2...b_r)\}}{n} = \lim \frac{\sum^{n-r+1}_1X1_{I_r}}{n-r+1}\frac{n-r+1}{n}\xrightarrow[]{}\frac{1}{b^r}
$$
almost surely.
This is true for any $r\geq 1$, so $X$ is normal almost surely. We can do the same for every $b\geq 2$, and then take the countable intersection of the above events so that $X$ is normal with respect to every base $b\geq 2$ with probability 1. We are done.
See theorem 8.1 in https://web.maths.unsw.edu.au/~josefdick/preprints/KuipersNied_book.pdf

(Borel) Normal number problem


How to reach $k\cdot 2^{k+2}$ from $(2k)\cdot 2^{k+1}$?

Question: I was trying to figure out the step between these two equal expression:
$$(2k)\cdot 2^{k+1} = k\cdot 2^{k+2}$$
Comment: $(2k)\cdot 2^{k+1}=k(2\cdot 2^{k+1})=k(2^{(k+1)+1})=k\cdot 2^{k+2}$.
Comment: @BrianM.Scott: that's it!! I was thinking how the k goes out. It is the associative law!! Thank you all.
Comment: Does the "." represent multiplication?
Answer: HINT A number raised to an exponent tells you how many times to multiply that number by itself.
For example: $2^{k}=2*2*...*2$ k-times, so $2*2^{k}=2*(2*2*...*2)$ a total of $k+1$ times so $2*2^{k}=2^{k+1}$


Estou com erro de Apostrophe not preceded by

Question: Eu estou tentando fazer a internacionalização do meu app para o idioma inglês, mas acabo recebendo este erro

Error:(10) Apostrophe not preceded by \ (in Please note, if you're on a device with android 6.0 above, you need the permissions that the app request the following screens to the proper functioning)

esse é meu string-en.xml
<resources>
<string name="app_name">Lanterna Flash</string>
<string name="texto">Texto tester</string>

<string name="title_activity_fullscreen">FullscreenActivity</string>
<string name="dummy_button">Dummy Button</string>
<string name="dummy_content">DUMMY\nCONTENT</string>

<string name="tela1">Welcomes!</string>

<string name="tela2">Take advantage of our application, it is the flashlight for devices that have flash or the screen flash.</string>

<string name="tela3">Please note, if you're on a device with android 6.0 above, you need the permissions that the app request the following screens to the proper functioning</string>

<string name="avisoToast">Seu dispositivo não tem flash!</string>

e esse aqui é meu string.xml o que fica na pasta values:
<resources>
<string name="app_name">Lanterna Flash</string>

<string name="texto">Texto tester</string>

    <string name="title_activity_fullscreen">FullscreenActivity</string>
<string name="dummy_button">Dummy Button</string>
<string name="dummy_content">DUMMY\nCONTENT</string>

<string name="tela1">Bem Vindo!</string>

<string name="tela2">Aproveite o nosso aplicativo, ele consiste na lanterna para aparelhos que tenham flash ou para o flash de tela.</string>

<string name="tela3">Atenção se você estiver em um aparelho com android 6.0 acima, será necessário das as permissões que o app solicitar nas telas a seguir para o devido funcionamento</string>

<string name="avisoToast">Seu dispositivo não tem flash!</string>

Não linguem para a tradução apenas to fazendo um teste, até então quando adiciono lá no string-en a tela 1 ele vai mais quando adiciono a tela 2 (os textos em inglês ele da esse erro) me ajudem quem puder eu agradeço...
Comment: Altere `if you're` por `if you\'re`
Comment: A mensagem de erro significa que você usou em alguma parte do texto um apóstrofo ( ' ) sem a sequência adequada de escape ( \' )
Comment: Nossa muito obrigado ramaral e Haroldo_OK, eu estava quebrando a cabeça com isso, coisa tão simples, e eu não achava nenhum exemplo na internet que me ajudasse, mas valeu :)
Comment: @ramaral você poderia postar uma resposta?
Answer: No Android apóstrofo(') é um dos caracteres que, quando usados em resources do tipo string, têm de ser inseridos numa sequência de escape ou, em alternativa, colocar toda a string entre aspas(").
No seu caso o problema está na parte you're da string "tela3":
<string name="tela3">Please note, if you're on a device with android 6.0 above, you need the permissions that the app request the following screens to the proper functioning</string>

Coloque o carácter \ antes do apóstrofo para criar a sequência de escape:
<string name="tela3">Please note, if you\'re on a device with android 6.0 above, you need the permissions that the app request the following screens to the proper functioning</string>

ou coloque toda a string entre aspas:
<string name="tela3">"Please note, if you're on a device with android 6.0 above, you need the permissions that the app request the following screens to the proper functioning"</string>

Outro carácter que necessita dos mesmo tratamento é as aspas que, neste caso, só pode ser resolvido recorrendo à sequência de escape.
<string name="exemplo">Isto é um "mau" exemplo</string>
<string name="exemplo">Isto é um \"bom\" exemplo</string>


Beginner's theory: Emaj7 - Em7 - A what key am I in?

Question: I've only very recently started to learn about music theory so forgive me if this is a stupid question.
I was playing around the guitar and was very fond of the following chord progression: Emaj7 - Em7 - A
But I couldn't figure out which key I was in. I have seen a Rott major and minor key in the same progression before but I don't really understand why it actually sounds nice.
Thanks for your help :)
Comment: How about Emaj7 - Em7 - A - B (repeat). Or a continued series of modulations: Emaj7 - Em7 - A - Dmaj7 - Dm7 - G - Cmaj7 - Cm7 - F - Bbmaj7 - Bbm7 - Eb - Abmaj7 - Abm7 - ... etc.
Comment: Now you've changed it, the OP want's to know if the segment they've provided has a key in the first place.
Comment: Yes I changed it in two different ways. It would be excellent if the OP learned a way to play with chords and notes as tools for groping around to get a practical feel for where the tonic could be. The first one "Emaj7 Em7 A B" hopefully feels like a potential key change back and forth, and the longer one hopefully feels like a continuous sliding key change. Theory is best learned in practice, meaning, by playing examples.
Comment: Even though you've received answers I am curious about a few things, what is the timing of this progression? Maybe 2 bars Emaj7 then 1 bar each of the next two? Does it go back to the Emaj7 or somewhere else? Is the A chord just a triad or some type of 7th chord?
Comment: @John, it's one bar Emaj7, one bar Em7 and two bars A7 actually
Answer: There is no one key for that progression. It could obviously be E, or A, but with nothing else around - before or after, it's impossible to tell. Just in isolation, a way to give a clue is to let one chord ring out, and make it sound like the final one. If it does, then as far as you're concerned, that's the key. Inconclusive? Read from the start again...
Answer: It looks like you have modulated.  The E Maj7 would typically belong to either E or B.  A is the 4th of E, if E was serving as the 5th of A I'd expect E7 and not E Maj7.  It is common to resolve from the 4th to the key by going to the 4-minor.  So the E Maj7 --> E-7 in my ear would make me expect to hear B, rather than A.
But if what you played sounds cool, then it's cool.  Play it.  Like Tim said, there not a key for it.  Whatever "key" you determine it to be in there will be "accidentals".  Keys are useful but a lot of great music does not adhere to a specific key.
Answer: Based on your comment on the timing and having A7 instead of just A I hear it as E tonality, parallel major and minor. The A7 is more of a IV chord rather than having a dominant function, kind of like the IV chord in a blues.
As to why it sounds good, who can say? Maybe it's going from happy to sad to bluesy. I personally like it a lot and it's a time tested harmonic device. "While My Guitar Gently Weeps", "Norwegian Wood" and the old standard "I'm Glad There Is You" all use this tonic major/minor contrast to great effect in one way or another.
Answer: Now that we have an accepted answer, I can add my own opinion.
Even if it's Emaj7 - Em7 - A7 - A7 (and not Emaj7 - Em7 - A), I hear this as a mode-mixing soul groove which moves around B major and B minor. A cheesy ending chord would be B major.


Difference between playing a D/F# and a D in the key of G on piano

Question: Ok I am brand new to playing the piano and I apologize if this question seems idiotic. I am trying to learn how to play American Pie here. I realized that I was playing both a D and a D/F# the same way, I was hitting the D, F#, and A keys together. I know this is right for at least 1 of them, but I don't know if it's right for both.
Without getting into any extraneous details can you tell me the difference? All I want to know is which keys I need to press down, no more no less.
Sorry if this is a dupe.
Comment: The letter before the slash / assignes the chord=D, the letter after the slash tells us the bass tone. You can keep this tone in the r.h. or let it drop ...
Answer: The bass is the critical part.
D means play a D major chord ...and by default the bass should be D the chord's root.
D/F# is a so-called slash chord (or an inverted chord is standard music theory) which means play a D major chord ...but play F# - the chord's third - in the bass.
NOTE: When the third of a major chord is in the bass, there is a strong tendency for it to move up a half step to the root of the next chord, like chords D/F# to G where the bass moves F# to G. That movement isn't a rule, but it happens a lot.
Comment: @Tim, draconian? it's just the standard. That doesn't preclude re-interpreting, making variations.
Comment: When an inversion is intended, it's almost always notated — so if there's no slash, the writer almost certainly intended a root-position chord.  You're free to play what you want, of course, and changing a bass note can be one way to make a tune your own.  But that would be a change to the music, not just an interpretation.
Comment: I get the sense that this answer is more in-depth than the other, but for that reason the other was easier for me to understand so I accepted that one. Still upvoting this one too and thankful for the help!
Comment: That's somewhat draconian! I interpret it as when there's a slash chord, the bass note is after the slash, when there's simply a letter for the chord, it's down to the discretion of the player. At least, that's what I've always done. On piano *and* on guitar - I know a lot of gtr sites prefer what you suggest, but I don't understand their reasoning. Chords don't *have* to be root position.
Comment: It's just that I've never, ever seen it as a written 'rule', Don't know how long slashed chords have been around, but they make sense as far as playing is concerned, and possibly people assume that no slash means root, but I translate it as 'please yourself'. See what Wiki says.
Comment: Yeah, the "written" aspect is part of the issue. Slash chords are more informal compared with the very academic Roman numerals. Academic source tend to explain their systems in more complete detail.
Comment: @gidds: In some musical styles, it is very common to play songs with an "oom-pah" bass line without explicitly notating it.  For example, instead of writing out "G G/D G G/D C C/G C C/G D/F# D D/F# D G G/D G" simply write "G C D G".  I wouldn't regard playing the "oom-pah" bass line as a change to the fundamental music of the piece if such a bass line would be appropriate for the style.
Comment: This is actually a better answer, but the OP specifically asked for a "press these keys" sort of answer. No talk about thirds, roots, half step movements. ;)
Answer: A commonly used way to play those chords is:

D : play the three-note chord D, F#, A with your right hand, and D with your left hand an octave or two lower.
D/F# : play the same three-note chord D, F#, A with your right hand, but F# with your left hand.

When your left hand plays low bass notes, the "inversions" marked using slash chords are right, no matter how you play the chord tones with your right hand. This is a bit as if your right hand was a guitarist and your left hand a bassist.


What this is, and how can it be put into Sibelius?

Question:
If you look at the bass staff, there is one more 16th note than there should be on a 4/4 time signature. Can someone explain this to me? And what is the number of top of the barline?
Comment: There are no sixteenth notes at all.
Answer: The three eighth notes (not 16th notes) with the "3" above the beam are a "triplet": three notes in the space of one beat. There are exactly four beats in the measure.

For instructions on how to enter triplets in Sibelius, see the Sibelius manual entry "Tuplets - how to create".


How to add a link to table row?

Question: There is a field 'field_upload_artwork' that contains files. I am using them to build links to files and want to insert links after Apparel Printing in the last step of the form.
Now the markup in devtools of the browser looks like this:

   Apparel Printing

Although it should be something like this (as I see):

  Apparel Printing

    name_of_file.png

    name_of_file.png

and this is how I build the table:
$files = [];
foreach ($quote_design->get('field_upload_artwork')->getValue() as $file) {
   if ($file = File::load($file['target_id'])) {
     $file_uri = $file->getFileUri();
     $file_link = [
       'title' => [
         '#type' => 'link',
         '#title' => $file->getFilename(),
         '#url' => $file_uri,
       ],
     ];
     $files[] = [
       '#type' => 'container',
       'file_link' => $file_link,
     ];
   }
}

$services_header = [
   'col0' => $this->t('Services'),
];
       // foreach ($files as $key => $file) {
       // $services_header['col' . $key] = '';
       // }

$services_row = [
   array_merge([$quote_design->get('field_service')->value, ''], $files),
];

$form['confirm_quote'][$key]['services_table'] = [
   '#type' => 'table',
   '#header' => $services_header,
   '#rows' => $services_row,
];

What am I doing wrong here? According to the idea, we need foreach, which I commented out. But if I uncomment it, then everything breaks down.
Comment: I'm not sure table cells can contain render arrays alone.
Answer: you should try this structure:
$rows[] = [
  'data' => [
    'label' => [
      'data' => [
        'link' => [
          '#type' => 'link',
          '#title' => 'link text',
          '#url' => Url::fromRoute('custom_module.route'),
        ],
      ],
    ],
  ],
];

which in my case looks like this:
      $services_header = [
        'col0' => $this->t('Services'),
      ];

      $services_rows = [
        [$quote_design->get('field_service')->value],
      ];

      foreach ($quote_design->get('field_upload_artwork')->getValue() as $file_key => $file_item) {
        if ($file_id = $file_item['target_id']) {
          $file = File::load($file_id);
          $file_url = $file->createFileUrl(FALSE);

          $services_header['col' . ($file_key + 1)] = '';

          $services_rows['data' . ($file_key + 1)] = [
            'label' => [
              'data' => [
                'link' => [
                  '#type' => 'link',
                  '#title' => 'Art Link',
                  '#url' => Url::fromUri($file_url),
                  '#attributes' => [
                    'class' => ['entity-quote-confirm-quote-services-table-link'],
                  ],
                ],
              ],
            ],
          ];
        }

      }

Also, I found this example (but I didn't use it):
use Drupal\Component\Render\FormattableMarkup;
  $rows[] = array(

      array('data' => new FormattableMarkup('@name',
        [':link' => $entry['link_url'],
        '@name' => $entry['name']])
      ),

Answer: If using the table theme, the #rows array contents must follow some guidelines. #rows must be:

An array of the rows to be displayed. Each row is either an array of cell contents or an array of properties as described in table.html.twig Alternatively specify the data for the table as child elements of the table element. Table elements would contain rows elements that would in turn contain column elements. - https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Table.php/class/Table/10

So if #rows contains render arrays, they must be named child elements.

How to add a link to table row?


How do I iterate through a class (Category) that has a subcategory list? i.e. List(Of Category)

Question: Let's say I have:
Public Class Category

Public subCategories As List(Of Category)
Public products As List(Of Product)

End Class

and an instance of that class called allCategories. Each instance of Category inside of the list of subCategories may or may not have further subcategories, and may or may not have items, since the items could be nested away in further subcategories.
My question: How do I create a List(Of Product) that includes every item from every category throughout allCategories?
I could, of course, say
For Each category In allCategories
...
   For Each subCat In category
   ...
      For Each furtherSubCat In subCat
      ...
         For Each evenFurtherSubCat In furtherSubCat

But I'm guessing there's a better way, one that will truly iterate throughout the class.
Comment: You use recursion. Recursion is often one of the first things taught in programming classes but it is one of the least-used. It's a critical tool though, and should be used in situations where it's appropriate. Whenever the aim is to traverse a tree structure, recursion is your go-to option. An object with child objects that each has child objects and so on is inherently a tree structure. If you need more information on recursion, there is plenty around the web.
Comment: In short, you write a method that takes a `Category` object as input and returns a list of `Product` objects as output. Inside the method, you first create a list containing the `Product` items for the current `Category`, then you call the same method again for each child `Category` and add the output to the same list.  Finally, you return that list. No, I will not be writing the code for you.
Comment: There are various specific ways you could structure the code.  For instance, your method might return an array or generic `List` or you might just have one `List` at the class level that you add to directly in each method call or you might have one `List` that you pass into each method call as an argument.
Answer: Recursion, right. Thank you, jmcilhinney.
Here's what I went with:
 Function GetAllProducts() As List(Of Product)

        Dim list As List(Of Product) = New List(Of Product)()

        For Each Product In Products
            list.Add(Product)
        Next

        For Each category In subCategories
            For Each Product In category.GetAllProducts()
                list.Add(Product)
            Next
        Next

        Return list

    End Function


Git não faz o push para a branch master

Question: Estava usando o .git normalmente em meu projeto, ontem digitei alguma coisa errada e o git começou a me devolver um alerta do arquivo index corrompido.
Ok, dei um git reset, voltei um commit e tudo voltou ao normal.
Bom, trabalhei hoje de manhã, a na hora que fui dar um push para o meu servidor, simplesmente não funciona, essa é a mensagem de erro (o terminal de baixo):

Bom, não estou descobrindo o erro, todas as pastas estão com permissão 777, e pertencem ao mesmo grupo e usuário tanto na máquina local como no servidor.
Local: Ubuntu 16.4 LTS
Servidor: Debian 7
Ambas estão na mesma rede.
Comment: Já tentou rodar o comando com `sudo`?
Comment: Esse erro ja foi rodado com sudo aberto
Answer: O erro do git refere-se a perca ou a não referência entre a sua branch local master e a master remota. Perdendo a referencia do HEAD.
Ao iniciar o projeto você aplicou o comando git init?
Isso significa que qualquer pessoa que aplicar o push "forçadamente" para este ramo irá substituir o status existente da cópia de trabalho verificada, ou seja, a referência a HEAD. Isso não é uma coisa boa.
Para resolver isso, você usa um repositório descoberto como um repo "comunitário" (faça isso com git init --bare) ou trabalhe com brands a partir da master, conforme fez:
git checkout -b nome_branch

Faça as alterações nesse ramo e aplique commit. Em seguida, aplique o push seu ramo com git push origin nome_branch. Depois disso, seu ramo remoto pode ser "mergeado" no mestre.
Aconselho sempre evitar "commitar" na master. Você pode bloquear isso através do site github. Crie o hábito de criar branchs a partir da master e "mergear" as alterações nela. Só não esqueça de sempre atualizar seu master local git pull toda vez que for criar uma nova branch para sempre ter a cópia atualiza do remoto.
Comment: Eu não estou utilizando o github nesse projeto, meu repositório é interno por se tratar de um sistema intranet, teria como bloquear a branch master para todos os usuários da rede exceto o admin do servidor?
Comment: Até onde eu sei e pelo o que pude pesquisar rapidinho. Esse conceito quem aplica é o github, não o git. Por isso no seu caso já não daria certo. Eu não sei qual o motivo de você ter criado um repositório interno, mas se for apenas para tê-lo como private, há duas soluções no mercado free que podem te ajudar a aplicar o que eu expliquei na resposta. [gogs](https://gogs.io/) e [gitlab](https://gitlab.com/)
Answer: SOLUÇÃO:
1 - Criar um nova branch no pc local e setar.

git checkout -b 'project'

2 - Solicitar o push

git push --set-upstream origin project

A partir daqui, apenas usar o comando:

git push

Git não faz o push para a branch master


Sub Query with SUM and DISTINCT

Question: I have the below query for which I want to det the distinct districts and the sum of how many properties there are for each one.
I can't remember how to do the sub query.
SELECT DISTRICT, PROPREF

FROM TBL_PROPERTY

WHERE  (CONTRACT = 'ma2') AND
        (LASTSERVICEDATE <= DATEADD(HH,23,CONVERT(DATETIME,'30/05/2009', 103))) AND
        (SERVICESTATUS = 'SERVICED')) AS Sub1

GROUP BY DISTRICT, OFFICE, PROPREF

Answer: I think you want this:
select DISTRICT, count(PROPREF)
from TBL_PROPERTY
where CONTRACT = 'ma2'
    and LASTSERVICEDATE <= DATEADD(HH,23,CONVERT(DATETIME,'30/05/2009', 103))
    and SERVICESTATUS = 'SERVICED'
group by DISTRICT

If you also wanted it broken out by office, you'd add OFFICE to the select and group by clauses.
Answer: SELECT COUNT(*) AS PROPERTY_COUNT ...

Is that what you're looking for?
Answer: just figured it out sorry if anyone responded!! Also forgot to take office out i think which i got rid of in end.
SELECT DISTINCT(DISTRICT), SUM(services) AS TOTALSERVICES

FROM

(SELECT DISTRICT, COUNT(PROPREF) AS Services

FROM TBL_PROPERTY

WHERE  (CONTRACT = 'ma2') AND
        (LASTSERVICEDATE <= DATEADD(HH,23,CONVERT(DATETIME,'30/05/2009', 103))) AND
        (SERVICESTATUS = 'SERVICED')
GROUP BY DISTRICT, propref

) as sub1

GROUP BY DISTRICT, services

Sub Query with SUM and DISTINCT


A PHP Error was encountered Severity: Notice Message: Undefined index: id

Question: I really need to make this table work but I can't find what's missing in my code or why this variable is undefined. The table works fine. It displays and so is a search box above it. The html code of the table is fine bcos it displays the table. The PHP Errors appear inside the colums of the table where the id, name, etc. are being called. Please I need help..
MY CONTROLLER: (tabledisplay.php)
function index()
    {
        $data = array();
        $this->load->model('table_model');
        $data['result'] = $this->table_model->display_table();
        $this->load->view('table_view', $data);//error here

    }

MY VIEW: (table_view.php)

                   ID
                   First Name
                   Middle Name
                   Last Name
                   Position

               <?php
                $row = array();
                foreach ($row as $result); ?>//the values cannot be displayed

                   <?php echo $row['id']; ?>	//error starts here
                   <?php echo $row['fname']; ?>
                   <?php echo $row['mname']; ?>
                   <?php echo $row['lname']; ?>
                   <?php echo $row['position']; ?>
                   <button type="submit" class="btn btn-success">Sign in</button>

              <?php  ?>

MY MODEL: (table_model.php)
function display_table ()
    {

    function filterTable($query)
    {
        $connect = mysqli_connect("localhost","root","","registerusers");

        $filter_Result = mysqli_query($connect, $query);

        return $filter_Result;

    }

        if(isset($_POST['search']))
        {
              $valueToSearch = $_POST['valueToSearch'];
            // search in all table columns
            // using concat mysql function
            $query = "SELECT * FROM `user`  WHERE CONCAT(`id`, `fname`, `lname`, `position`) LIKE '%".$valueToSearch."%'";
            $search_result = filterTable($query);
        }
        else{
            $query = "SELECT * FROM `user` LIMIT 10";
            $search_result =  filterTable($query);
        }
    return $search_result;
    }

Answer: You have a $data['result'] on controller there for in foreach on view
Have $result first in foreach
<?php if ($result) {?>
<?php foreach ($result as $row) { ?>

<?php echo $row['id']; ?>
<?php echo $row['fname']; ?>
<?php echo $row['mname']; ?>
<?php echo $row['lname']; ?>
<?php echo $row['position']; ?>
<button type="submit" class="btn btn-success">Sign in</button>

<?php  } ?>
<?php  } else { ?>

Sorry No Results

<?php  } ?>

Or try like
<?php if ($result) {?>
<?php foreach ($result as $row) { ?>

<?php echo $row->id; ?>
<?php echo $row->fname; ?>
<?php echo $row->mname; ?>
<?php echo $row->lname; ?>
<?php echo $row->position; ?>
<button type="submit" class="btn btn-success">Sign in</button>

<?php  } ?>
<?php  } else { ?>

Sorry No Results

<?php  } ?>

Comment: yes correct , @wolfgang1983
Comment: Tried the two ^ but result is still Undefined Variable.. thanks.
I have edited my queries and it works fine now except for the limit of post that it gets, another prob -_-


Can these sounds be created with an electric guitar or do I need an acoustic one?

Question: It's been a while since I owned my last guitar. It was an acoustic with nylon strings. I also played on acoustic guitars with steel strings.
However, I haven't have a guitar for years and wanted to get a new one. My local music shop has a great offer on a Gibson Les Paul Less Plus 2015.
My question is now as I never had an electric guitar before and I want to use it to record some phrases in the studio, too. Can I create sounds like in those tracks or do I need an acoustic guitar for that like a Dreadnought?
Guitar loop runs through the whole track:

Guitar is most present in the break at 3:20:

Through my studio I have access to Native Instruments Guitar Rig and  Waves GTR to add/create effects.
PS: I hope this question is suitable for this stack exchange site
Comment: The guitar sounds in both tracks are those of an acoustic, not electric, guitar. But could you create them from an electric guitar? There are various acoustic simulator pedals/plugins out there, with varying levels of realism. You could also create them without any guitar at all, or using a guitar with a MIDI pickup as a controller. But if that's the sound and style you're after, I don't think a Les Paul is the right starting point.
Comment: @aparente001 Haha, no, no. Don't take this sentence too serious. It was kind of ironic. You know, I have multiple synths and they all sound different and now I'm going to have multiple guitars which sound different too, as well. And I thought one would be suitable for everything. Silly me. :)
Comment: @jonrsharpe Thanks for your comment. It seems that I have to get two guitars then. Argh. Thought the electric one would be so versatile that I can get it to be acoustic sounding as well. But the Les Paul can sound clean and nice, too? So it's not just rock music I can play with an electric one, right? I was so excited getting an electric one - now I'm unsure whether it's the right choice.
Comment: Parker Guitars and other's make electric guitars that also have an acoustic under saddle piezo to generate a more natural, realistic acoustic guitar sound.  The Parker PDF 85 is affordable and gives you both magnetic electric guitar pickups as well as an acoustic pick up.
Comment: May be best if you consider an electric and an acoustic as two different instruments. Yes with guitar rig an electric would be more versatile but both these tracks are acoustic. But as jonrsharpe mentioned, you can use a midi controller and get some decent midi instruments these days. Unless your very good at guitar it will sound much more polished than you could ever do on your own.
Comment: @DaveEngineer Yes that's probably true. Too many options. I think I might go with an acoustic one and maybe will add a MIDI converter later - if I can't get the recordings straight. But I definitely want a guitar to play an instruments without the use of a computer again. I mean, anytime I want to play some piano, I have to hook up my Doepfer, start the computer, load a decent plug in - and I can't take it with me easily to jam. :) Thanks for your input.
Comment: " It seems that I have to get two guitars then. Argh." -- Is it the expense?  The space in small living quarters?  The inconvenience of shlepping two instruments around?
Answer: These are acoustic guitars in the tracks but you could probably get a similar sound (since you will be adding effects and processing) using an acoustic simulator with a electric guitar like the Boss AC-3.
Having an acoustic simulator with a electric guitar with single coil pickups can create a nice sound. It's not exactly the same as an acoustic guitar but can still sound interesting and if processed correctly it may fit for the kind of sounds you want to create. The sound is ultimately personal preference, so try it out.
Answer: To give you a straight answer, yes, you could. It's never going to have that clear raw sound that comes from the hollow body of an acoustic but you can get close.
I would lower your bass to near 0. Increase treble and use medium reverb with a short decay.
Focus your playing on the near-bridge pickups to get a tighter sound.
Comment: I don't appreciate a down vote when you don't give a reason as to why. Have you tried the method I described? You can easily achieve an acoustic sound with an electric, and in the end it comes down to personal preference.


fill holes of raster by assigned flagmask

Question: I have a raster image with some values are nan and these are supposed to be filled by the valid values. These valid values should meet two conditions: within a certain distance to the target pixel, and are flagged as true in an input FlagMask.
The rasterio.fill.fillnodata https://rasterio.readthedocs.io/en/latest/api/rasterio.fill.html can achieve filling nodata with the distance condition but not the FlagMask condition. The inpaint in matlab https://uk.mathworks.com/matlabcentral/fileexchange/27994-inpaint-over-missing-data-in-1-d-2-d-3-d-nd-arrays works similarly as rasterio.fill.fillnodata. Would appreciate existing functions or some ideas about modifying based on some modules. An efficient algorithm will be desired as my raster input will be more than 5000*5000.
Answer: I would simply run inpaintn() and then reset those elements which are not flagged back to NaN. I'm having difficulty thinking of a scenario where the practical difference between your algorithm and my proposal is meaningful, if you have an example data set let me know.
Comment: Thanks for your answer! But I think the inpaint() is an automatic progressive process, meaning the NaN will be filled progressively until all done. I cannot find a place insert the set not flagged as NaN. I am using it to inpaint the holes in DEM, the flagged layer is Road-1 and None-road-0, I only want the valid values from the road be used in filling the NaN.
Comment: I must be misunderstanding. I'm not recommending you change `inpaint()` at all. Say you have a DEM raster image with NaNs interspersed and you know the elements which are road and which are not. Do two runs: `inpaint(image_masked_by_isroad)` and `inpaint(image_masked_by_isnotroad)`. Then recombine into a single image by using the same masks. I assume the masks provide full coverage of the image, without overlap.
Comment: Could you explain a bit more? Wouldn't the inpaint(image_masked_by_isroad) fill values outside the road and these values will then participant in filling the road progressively? My understanding about inpaint is that it is an progressive process.
Comment: When I read the code I understood it to be iterative, not progressive. An initial guess is made based on nearest neighbor interpolation and then cosine transforms are iteratively applied to smooth the result.


Capture the Search text and pass it in a URL when clicked on Submit

Question: I just cant get around this simple requirement. I am new to PHP and need help.
I need to capture the value in a Search Box and then pass it in the URL which opens in a new tab when hit on Submit.
What am I missing here..it seems like I am missing a lot of things for this to work..
<?php
 if (isset($_POST["submit"])){
    $example = $_post['searchon'];
    echo '';
 }
?>

  <form action="index.php" method="post">
    <input type="search" name="searchon" id="searchon" />
    <input type="submit" name ="submit" />
        </form>

Comment: there's no text between your `a` tags so nothing will show. Try `{PLACEHOLDER}`. Note the `{PLACEHOLDER}` value
Answer: try this code instead of your one:
<form action="http://www.amazon.in/s/ref=nb_sb_noss_1" method="get" target="_blank">
<input type="hidden" name="url" value="search-alias=aps" />
<input type="hidden" name="tag" value="orientmarketi-21" />
<input type="text" name="field-keywords"/>
<input type="submit" />
</form>

Comment: Is there a way for me to create two tabs and open two different URLs in a similar way? I actually need two to be working this way..
Comment: @user2918177 do you mean open two different tabs by clicking single button?
Comment: @user2918177 no, this approach will not work, you need to use javascript and onsubmit handler
Comment: Hmm..Could you please help me with that approach..I need to get this done urgently
Comment: I cannot help you in this case


Notes preceding slurs: legato or not?

Question: In the few piano pieces I've learned, I've sometimes seen notation ambiguous to me whether or not to play the notes immediately preceding slurs as legato.
For instance, the treble clef in bars 3 and 4 from Burgmüller's La Pastorale:

Bar 3 is clearly understood. The slur for the treble clef encompasses the entire bar. It follows the end of the slur of bars 1 and 2. So, I interpret this as "lift the right hand at the end of bar 2, play the notes in bar 3 legato, and then lift the right hand at the end of bar 3, ready for bar 4".
However, bar 4 is less clear. There is a slur, but only covering the last three notes of the treble clef, and excluding the dotted crotchet D. To me, there seems to be two different ways this could be read: which is the most appropriate?
1. Play the D legato into the slur, so all notes in bar 4's treble clef are played legato, i.e. play the notes as in bar 3.
My argument: I've learned a general rule-of-thumb in piano to play notes legato, unless they are marked deliberately not. (I realise this is not an absolute and may depend on the composer or period when a piece was written.)
2. Play the D and then lift off, before playing the three notes in the slur legato.
My argument: why would the D not be included in the slur if it is intended to be played legato into the other notes? Wouldn't the notes in bar 4 just all be notated under a slur as in bar 3 to indicate they are all legato?
Answer: Imagine a slur goes over a word. Here the word could have three syllables, or just one. In bar three, that word (whatever it is) would have all four notes sung . bar four, there's one word (of one syllable) on the D, and another - maybe three syllable word - sung to the other three dots. If you said the words, there would be a very slight gap between them, but the last three notes would be sung with no gap.
Had the writer wanted all four legato, he'd have marked it as such.
Answer: The notation is quite clear.  Bars 3 and 4 could have been notated the same way.  They aren't.   In bar 4, no slur into the D, no slur out of it.  It's a 'stand-alone' note.  Don't over-do it though, it's a subtle bit of phrasing.  If this was a vocal piece, I'd interpret it as giving that note's word full length but meticulous diction
Answer: Well, here is your problem:

My argument: I've learned a general rule-of-thumb in piano to play notes legato, unless they are marked deliberately not.

Uh, no?  Who gave you that rule-of-thumb?  Notes without additional marks are played separately, one ending before the next begins, but without a marked pause (like portato would suggest, let alone staccato).  Basically you do nothing with the end of a note: you don't connect it to the next note, you don't emphasize it by shortening it.  Legato, in contrast, means a connected sound.  If you were to play legato by default, why would there even be legato marks and instructions?
So clearly bar 4 is not to be played all-legato.
Comment: Please could you clarify the apprent contradiction in your words "one ending *before* the next begins ... you don't emphasize it by *shortening* it". Perhaps you mean that you *do* shorten the note but you don't emphasize it?
Comment: @RosieF I think that should be read add "you don't emphasise it by shortening it  _as you would do if a staccato was requested_ "
Answer: Slurs indicate phrasing and often contribute to the rhythmic quality of the piece. In a piece that lacks notation, you will have to make your own choices, but the piece posted above is clearly notated. Slur what is under a slur. Lift off the D in m. 4 before playing the slurred notes, but hold it for the full amount.

Notes preceding slurs: legato or not?


checkbox become unchecked

Question: I have this situation: http://jsfiddle.net/bRDgK/3/
In this situation I have a modal dialog with a checkbox. When the user click on the checkbox, a new modal dialog should appear and the checkbox should be checked. For some reasons the checkbox become unchecked. Any idea why?
Answer: Works fine with onchange
DEMO: http://jsfiddle.net/bRDgK/10/
Additional findings
Modal seems to be the problem. The modal is popping up and interfering with click event. Turning modal off all works fine cross browser. Suggest checking in  jQueryUI forum and/or reporting a bug
Comment: When i try your jsfiddle code, it's still unchecking the button. And i have tried with FF, IE and Chrome, no one seems to work
Comment: what browser, working good in FF. Is definitely a strange thing
Comment: This should work with click too and not only with change. In my code the onchange applies only when I am exit the checkbox (IE8). I need solution with onclick. I am using also with IE8.
Comment: see my additonal notes about modal
Comment: Please see my answer. If you have any explanation to this solution - I will be very glad :)
Answer: I really don't understand why, but if I cancel event bubble (cancel event propagation for firefox) right before open the child modal - the checkbox stays checked as it should be.
Here is example (working only on IE because the inline onclick event and the window.event usage): http://jsfiddle.net/bRDgK/16/
Any idea how this solves the problem??
Answer: I got it working for both firefox and IE8.
http://jsfiddle.net/executorjs/qevfZ/5/
I made a change on the doSomething function:
$(this).find("#ee").dialog("open");

Also changed the location of some html:

    <input type="checkbox" id="dd" onclick="doSomething();" />

Comment: you aren't using UI css so modal isn't activating. With no modal it works, along with fixing improper nesting which I did in first version
Comment: $(this).find("#ee") returns empty jquery object thus $(this).find("#ee").dialog("open"); does nothing.
Comment: Please see my answer. If you have any explanation to this solution - I will be very glad :)

checkbox become unchecked


How can I bind events to strongly typed datasets of different types?

Question: My application contains several forms which consist of a strongly typed datagridview, a strongly typed bindingsource, and a strongly typed table adapter.
I am using some code in each form to update the database whenever the user leaves the current row, shifts focus away from the datagrid or the form, or closes the form.
This code is the same in each case, so I want to make a subclass of form, from which all of these forms can inherit.
But the strongly typed data objects all inherit from component, which doesn't expose the events I want to bind to or the methods I want to invoke.
The only way I can see of gaining access to the events is to use: Type(string Name).GetEvent(string EventName).AddEventHandler(object Target,Delegate Handler)
Similarly, I want to call the Update method of the strongly typed table adapter, and am using Type(string Name).GetMethod(String name, Type[] params).Invoke(object target, object[] params).
It works ok, but it seems very heavy handed. Is there a better way?
Here is my code for the main class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;

namespace MyApplication
{
    public class AutoSaveDataGridForm: Form
    {
        private DataRow PreviousRow;

        public Component Adapter
        {
            private get;
            set;
        }

        private Component dataGridView;
        public Component DataGridView
        {
            private get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
                Type t = dataGridView.GetType();
                t.GetEvent("Leave").AddEventHandler(dataGridView, new EventHandler(DataGridView_Leave));

            }
        }
        private Component bindingSource;
        public Component BindingSource
        {
            private get
            {
                return bindingSource;
            }
            set
            {
                bindingSource = value;
                Type t = bindingSource.GetType();
                t.GetEvent("PositionChanged").AddEventHandler(bindingSource, new EventHandler(BindingSource_PositionChanged));

            }
        }

        protected void Save()
        {
            if (PreviousRow != null && PreviousRow.RowState != DataRowState.Unchanged)
            {
                Type t = Adapter.GetType();
                t.GetMethod("Update", new Type[] { typeof(DataRow[]) }).Invoke(Adapter, new object[] { new DataRow[] { PreviousRow } });

            }

        }

        private void BindingSource_PositionChanged(object sender, EventArgs e)
        {
            BindingSource bindingSource = sender as BindingSource;
            DataRowView CurrentRowView = bindingSource.Current as DataRowView;
            DataRow CurrentRow = CurrentRowView.Row;
            if (PreviousRow != null && PreviousRow != CurrentRow)
            {
                Save();
            }
            PreviousRow = CurrentRow;

        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            //
            // AutoSaveDataGridForm
            //
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.AutoSaveDataGridForm_FormClosed);
            this.Leave += new System.EventHandler(this.AutoSaveDataGridForm_Leave);
            this.ResumeLayout(false);

        }

        private void DataGridView_Leave(object sender, EventArgs e)
        {
            Save();
        }

        private void AutoSaveDataGridForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Save();
        }

        private void AutoSaveDataGridForm_Leave(object sender, EventArgs e)
        {
            Save();
        }

    }
}

And here is a (partial) form which implements it:
    public partial class FileTypesInherited :AutoSaveDataGridForm
{
    public FileTypesInherited()
    {
        InitializeComponent();
    }

    private void FileTypesInherited_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'sharedFoldersInformationV2DataSet.tblFileTypes' table. You can move, or remove it, as needed.
        this.tblFileTypesTableAdapter.Fill(this.sharedFoldersInformationV2DataSet.tblFileTypes);
        this.BindingSource = tblFileTypesBindingSource;
        this.Adapter = tblFileTypesTableAdapter;
        this.DataGridView = tblFileTypesDataGridView;

    }

}

Answer: This demontrastes how you can use an "MustInherit" base class for your typed datasets for the purpose of accessing unexposed properties.
Set this as the "BaseClass" for each of your typed TableAdapters, replacing "System.ComponentModel.Component".
By using "MustInherit/MustOverride" ("Abstract" in C#) you can get to the properties you can't otherwise reach.
Public MustInherit Class SuperTableAdapter
    Inherits System.ComponentModel.Component

    Public MustOverride ReadOnly Property MyCommandCollection As Data.SqlClient.SqlCommand()

    Public Sub New()
        MyBase.New()
        'With the command collection exposed, you can replace it with your own.  You can do the same for events.'

        For i = 0 To MyCommandCollection.Length - 1
             Dim myspecialCommand As New Data.SqlClient.SqlCommand()
            MyCommandCollection(i) = myspecialCommand
        Next
    End Sub
End Class

For each of your table adapters that you set to inherit your BaseClass you must override the required "MustOverride" property.  Without it, it won't compile.  If you add the code but do not set the TableAdapter base class, it will not compile either.  That is good thing; it ensures you do it right.
Namespace DataSet1TableAdapters
    Partial Public Class Table1TableAdapter
        Public Overrides ReadOnly Property MyCommandCollection As System.Data.SqlClient.SqlCommand()
            Get
                Return Me.CommandCollection
            End Get
        End Property
    End Class

    Partial Public Class Table2TableAdapter
        Public Overrides ReadOnly Property MyCommandCollection As System.Data.SqlClient.SqlCommand()
            Get
                Return Me.CommandCollection
            End Get
        End Property
    End Class
End Namespace

Now you can put all sorts of special code in your SuperTableAdapter.  If you need access to something that wasn't exposed, just use "MustOverride" to guarantee that it is available.


Como controlar o tamanho das células em uma tabela HTML?

Question: Estou tentando controlar o tamanho de uma célula da minha tabela HTML utilizando as propriedades de CSS height e width, porém não está funcionando.
Estou fazendo da seguinte forma:
#CelL7C1, #CelL3C1, #CelL3C3, #CelL7C3{
    height: 5px;
    width:20px;
    background-image: linear-gradient(to right, red , yellow);
}

Comment: Cara vc tem que colocar a sua tabela inteira ai não só um pedaço de CSS, sem um modelo mínimo para poder simular seu problema não da para te ajudar ...
Comment: Posta seu html da tabela, só com isso não da pra ajudar.
Answer: Pra fazer isso precisa especificar um tamanho fixo de largura na table e depois determinar o que precisa no td tipo:
table {
    max-width: 90px;
}
td {
    width: 25px;
}


React utilizando Redux, nao esta salvando estado da aplicacao

Question: Estou tentando implementar redux na minha app Web react, não da nenhum erro mas tambem não funciona, quando tento capturar estado fica como undefined
estrutura:

App.js
routes.js
store/actions.js
store/index.js
store/reducers/index.js
store/reducers/posts.js
pages/Main.js

App.js
import React from 'react';
import './App.css';
import { Provider } from "react-redux";
import store from "./store";
import Routes from './routes';

function App() {
  return (
    <Provider store={store}>
      <Routes />
    </Provider>
  );
}

export default App;

routes.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { ConnectedRouter } from "connected-react-router";

import Main from './pages/Main';
import Detalhe from './pages/Detalhe';

import history from "./history";

export default function Routes(){
    return (
        <ConnectedRouter history={history}>
        <Switch>
            <Route path="/" exact component={Main} />
            <Route path="/posts/:id" exact component={Detalhe} />
        </Switch>
        </ConnectedRouter>
    );
}

store/index.js
import { applyMiddleware, createStore, compose } from "redux";
import { connectRouter, routerMiddleware } from "connected-react-router";
import thunk from "redux-thunk";

import history from "../history";
import rootReducer from './reducers';

const initialState = {};

const middleware = [
    routerMiddleware(history),
    thunk
];

const store = createStore(
  connectRouter(history)(rootReducer),
  initialState,
  compose(
      applyMiddleware(...middleware)
  )
);

export default store;

store/actions.js
import { push } from "connected-react-router";

export const dataSave = (posts) => dispatch => ({

  type: "ADD_POSTS",
  payload: { posts }

});

store/reducers/index.js
import { combineReducers } from "redux";

import posts from "./posts";

export default combineReducers({
  posts
});

store/reducers/posts.js
export default function posts(state = [], action) {
    switch (action.type) {
      case "ADD_POSTS":
        return {...state, posts: action.payload.posts };
      default:
        return state;
    }
  }

pages/Main.js
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import './Main.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Navbar2 from '../components/Navbar';
import {isMobile} from 'react-device-detect';
import api from '../services/api';

import { connect } from "react-redux";
import * as DataActions from "../store/actions";
import { bindActionCreators } from 'redux';

function Main({ history, match, dataSave, posts }){

   /* Nao e mais um state local */
   // const [posts, setPosts] = useState([]);

    let [page] = useState(1);

    /*
    if (localStorage.getItem("posicaoScroll") === undefined &&
        localStorage.getItem("posicaoScroll") === null
      ) {
        localStorage.setItem("posicaoScroll", JSON.stringify(0));
      }
    */

    const [layout, setLayout] = useState(null);

    /*
    const [posicao, setPosicao] = useState(
        JSON.parse(localStorage.getItem("posicaoScroll"))
      );
    */

    useEffect(() => {
      async function loadDados(){

        const response = await api.get('/posts?_start=0&_limit=10');

        //Agora seta via redux
        //setPosts(response.data);

        console.log('Get da API');
        console.log(response.data);

        dataSave(response.data);

        //Teoricamente era para aparecer os posts no console agora
        console.log('Estado no Redux');
        console.log(posts);

        page = 1;

        if (isMobile) {
          setLayout('mob');
        } else {
          setLayout('web');
        }

        /*
        let scrollpos = localStorage.getItem("posicaoScroll");
        if (scrollpos !== undefined && scrollpos !== null) {
            // Timeout necessário para funcionar no Chrome
            if (scrollpos <= 100)
            scrollpos = 0;
            console.log(scrollpos); //JSON.parse(scrollpos)
            setTimeout(function() {
            window.scrollTo(0, scrollpos);
            }, 1);
        }
        */

      };

      loadDados();

    }, []);

    /*
    useEffect(() => {
      // Verifica mudanças no Scroll e salva no localStorage a posição
       window.onscroll = function(e) {
        setPosicao(window.scrollY);
        localStorage.setItem("posicaoScroll", JSON.stringify(posicao));
      }

        return () => {};
      }, [posicao, page, setPosicao]);
    */

    useEffect(() => {
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);

    /* Scroll infinito nao ta funcionando pq nao ta disparando evento ao chegar no final da pagina, talvez calculo esteja errado */
    async function handleScroll() {

        console.log(document.documentElement.scrollTop);

         //if (((document.documentElement.scrollTop) / (page * window.innerHeight)) / page >= 5.80) {
        if (((document.documentElement.scrollTop) / 1350) >= page) {

            page = page + 1;

            //Comentei para nao da erro
            fetchMoreListItems(page - 1);

        } else {
            return;
        }
    }

    async function fetchMoreListItems(pagecount) {

        const response = await api.get(`/posts?_start=${pagecount * 10}&_limit=10`);

        //Agora seta via Redux
        //setPosts(prevState => ([...prevState, ...response.data]));
        dataSave(response.data); // Isso é equivalente a linha acima?

    }

    //------

    return (

        <Navbar2/>

                    { posts.length > 0 ? (

                        {posts.map(post => (
                            <Link to={`/posts/${post.id}`} >

                                        {post.title}

                            </Link>
                        ))}

                    ) : (

Nenhum Post :(

                    ) }

    );
}

const mapStateToProps = state => ({
  posts: state.posts
});

const mapDispatchToProps = dispatch =>
bindActionCreators(DataActions, dispatch);

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Main);

No arquivo Main.js quando a funcao loadDados() executa,
ela chama a funcao do action:
dataSave(response.data);

mas quando executo:
console.log(posts);

fica como undefined :(
O que sera que estou fazendo de errado?
repositorio no github: https://github.com/felipeagger/React-Redux/tree/redux

Branch redux
Answer: Implementei seu código no CodeSandbox, ignorando algumas partes que faltavam.
Quase sempre que, ao usar o react-redux, uma ação disparada aparentemente não fizer nenhum efeito no store, é porque o dispatch não está sendo utilizado. De duas, uma:
1) você está importando em seu componente uma ação definida na pasta actions, sem envolvê-la num dispatch, através de mapDispatchToProps. Isso você fez corretamente.
2) você não está usando a função dispatch dentro da action creator. Esse foi seu caso! Você retorna o objeto que representa a ação ao invés de despachá-la ao store. O correto é:
export const dataSave = posts => dispatch => {
    dispatch({
        type: 'ADD_POSTS',
        payload: { posts }
    })
}

Além disso, algumas observações:

a ação é enviada ao store, que atualiza o componente com o novo valor. No entanto, não espere que este identificador obtenha o novo valor imediatamente após chamar dataSave(response.data). O que ela faz é solicitar ao store que modifique seu estado e, após algum tempo, o React irá reagir a essa mudança e chamar o método render deste componente com o novo posts.
cada reducer deve possuir um estado inicial que irá evoluir com o tempo. Como você usou combineReducers, o state inicial é state: { posts: [] }. Porém, o reducer posts irá alterar a subárvore posts, não o state inteiro. Logo, o correto seria utilizar algo como o seguinte

// reducers/posts.js
const INITIAL_STATE = {
  list: []
};

export default function posts(state = INITIAL_STATE, action) {
  switch (action.type) {
    case "ADD_POSTS":
      return { ...state, list: action.payload.posts };
    default:
      return state;
  }
}

// pages/Main.js
const mapStateToProps = state => ({
  posts: state.posts.list
});


Get encrypted text as NSString instead of NSData

Question: How i can get encrypted data as string instead of NSData object in Objectice -C?
I need to send this encrypted text to >net method and decryption procedures are handles in .Net code.
Or anyone can help me to encrypt a text in iOS and decrypt it in >net ?
Adding from comment - Zaph
I am using this code:
StringEncryption *crypto = [[StringEncryption alloc] init];
NSData *_secretData = [SearchKey dataUsingEncoding:NSUTF8StringEncoding];
CCOptions padding = kCCOptionPKCS7Padding;
NSData *key = [_key dataUsingEncoding:NSUTF8StringEncoding];
NSData *encryptedData = [crypto encrypt:_secretData key:key padding:&padding];

I need to send encryptedData to .Net. But i dnt know how to send NSData to .Net method , so i tried to convert this encryptedData to NSString, unfortunately it gives me nil. I tried with base64EncodedStringWithOptions,its also giving error when i am decrypting.
Comment: Sure, help is available here. Writing code is not. Study, research, write the best you can. If it doesn't work come back here with the problem code and help should be available.
Comment: Data encryption produces 8-bit bytes, not ASCII characters. As such some encoding is needed, generally that is Base64.
Comment: Encrypted data must be dealt with as 8-bit bytes, not conventional characters.  If you attempt to treat the data as characters you inevitably corrupt it and it will not decipher.  If you need a character string for transmission, encode the 8-bit bytes into Base64.
Comment: What is the StringEncryption class? What .new class? What is not shown is the mode and if CBC (it should be using CBC move) the iv and the key length. The key should not be a string (passwords) and the key should be the  correct length. So how are these things handled in StringEncryption and .net?
Answer: You can convert NSData to base 64 string.
For iOS 7,  NSData has these two methods: (direct quotes from Apple doc)
base64EncodedDataWithOptions : Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options.
base64EncodedStringWithOptions : Create a Base-64 encoded NSString from the receiver's contents using the given options.
Comment: I am using this code      StringEncryption *crypto = [[StringEncryption alloc] init] ;
 NSData *_secretData = [SearchKey dataUsingEncoding:NSUTF8StringEncoding];
 CCOptions padding =kCCOptionPKCS7Padding;
 NSData *encryptedData = [crypto encrypt:_secretData key:[_key dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
and I need to send encryptedData to .Net. But i dnt know how to send NSData to .Net method , so i tried to convert this encryptedData to NSString, unfortunately it gives me nil.i  tried with base64EncodedStringWithOptions,its also giving error when i am decrypting....
Comment: Added comment to question for formatting and question continuity.


How to get some value from the sql database based on certain criteria

Question: Suppose I have given such a table in sql
According to Gmail (which I have given in advance) I want to get the Username value.
For example, if "Gmail" would be "email@example.com" I should get string - "Gela gela".
if "Gmail" would be "firstname.lastname@example.com" I should get string - "Mamuka snaia".
How to do this?
Comment: but, I want to store it in a string variable, in visual studio
Comment: How do you get `"Mamuka snaia"` from `"firstname.lastname@example.com"`? Are there other table fields we don't know about? What language (C#, VB, etc.) are you using, and which SQL Engine (Sql Server, MySql, etc.)?
Answer: You can easily make an SQL query like:
<code>SELECT Username from tableName where Gmail = 'email@example.com'
</code>
Replace tableName with your table name.
https://www.w3schools.com/sql/sql_select.asp
Comment: w3*ools... SQL has single quotes for string literals. Double quotes are for delimited identifiers, e.g. column names with odd characters.
Comment: It looks like they also want a substring of the result (e.g. `"Gela"` from `"email@example.com"`).


Neo4j Query Optimization for Relations+Nodes

Question: I have a graph data and this data includes millions of data. I try to figure out query optimization methods in neo4j.
For example, I have a query like:
MATCH ((a1:App{appId:1}) <- [:PAID_BY] - (k:Keyword{countryCode:'US'}) - [:PAID_BY] -> (a2:App{appId:2}))
return distinct k.value
limit 50

For this query optimization, which indexes should I create it? Or is there any optimization way for this query?
Note: In this query, I try to find mutual keywords between two apps.
Comment: I suggest editing your question to show what issues you're having. Also, "how to optimize" is fairly broad and open-ended.
Answer: Your query is collecting keywords that are common between app1 and app2. You can create indices on App.appId and Keyword.countryCode. Then use this query.
RETURN apoc.coll.toSet(
 [ (:App{appId:1}) <- [:PAID_BY] -
 (k:Keyword{countryCode:'US'}) -
 [:PAID_BY] -> (:App{appId:2}) | k.value]) as keywords

 Where apoc.col.toSet will ensure that the list have unique values
 [ ] is called comprehension and similar to collect() function
 | or pipe is a way to filter data. So you list will contain keyword.value

We love APOC functions and one liner code, isn't?


Searching for WindowBuilder documentation/API

Question: I'm in a project with WindowBuilder Pro, and while trying to get a good grip of it I've been searching forever for good documentation without any luck.
The best that I've found is Googles WindowBuilder Pro Infopage but that isn't extensive enough for me.
Does anyone know any other good documentation?
Or am I perhaps a bit off track here? I have very limited Swing-experience, and perhaps I'd be better off studying the SWING API instead of looking for WindowBuilder documentation?
Very thankful for any tips.
Answer: The WindowBuilder docs that you reference are quite extensive (nearly 300 pages), but they are intended to be docs about how to use WindowBuilder itself. They are intentionally not intended to be documentation for the Swing, SWT or GWT APIs and should not be considered to be substitutes for those. There are plenty of good sources of information on those APIs.
If you are interested in info on Swing, the primary source should be the docs and tutorials provided by Sun/Oracle. Once you have a basic understanding of Swing itself, I think you will find the WindowBuilder docs to be of great help in learning WindowBuilder which itself will be great help to you in rapidly creating Swing UIs.
I should also point out that the WindowBuilder docs in place today are actually better than those in place prior to the Google acquisition of Instantiations because they represent a further six months of work and refinement. While the product has seen a change in legal ownership, it has not actually "changed hands" in the literal sense. The exact same team that developed the tool at Instantiations has continued to work on it at Google and is also forming the core of the committer team at Eclipse.org. This continuity of development stretches eight years into the past and will continue well into the future.
Comment: The google tutorial stuff has continued to improve and improve, including this great quick start: https://developers.google.com/java-dev-tools/wbpro/quick_start
Answer: This is in a really early stage but this is something that we have been working on which might be helpful for you: http://www.codemaps.org/s/WindowBuilder
Answer: WindowBuilder has changed hands several times in the last 12 months (from Instantiations to Google, followed by Google giving it to the Eclipse Foundation). Admittedly, the documentation appears to have suffered.  However, as the project is still in the process of being provisioned to the Eclipse Foundation, the best place to search for documentation should be the Eclipse WindowBuilder Documentation Page, which is available from the Eclipse WindowBuilder page.  Currently, the documentation page only lists the Google InfoPage that you've mentioned, but I suspect that in time the documentation will increase greatly in quality.
That being said, there is no substitute for a solid understanding of the underlying technology that you plan on using within WindowBuilder, be it SWT, Swing, or GWT.  WindowBuilder will make some things easier, but many of the features will be confusing if you don't have a firm grasp of the underlying concepts.  Sadly, most tutorials are still centered around hand-coding the GUI, so there is an opportunity for an enterprising documentation/tutorial writer to provide a gateway to those who wish to learn technologies like Swing and SWT using WindowBuilder.
Answer: Yea, leave the WindowsBuilder behind.  The Swing tutorials are excellent: http://download.oracle.com/javase/tutorial/uiswing/
Comment: Knowing Swing is a good idea but the code generated by WB is quite clean so it can't do any harm and it does speed up the process of making a design.
Comment: I don't see anything about any layout or gui builder stuff that works inside eclipse at the above link.  Netbeans only.


Is there any possibility to create services to achievement module in Drupal?

Question: I have using the Achievements module in my site, it's working fine.

I have one doubt, I'm using the Services module to consuming user nodes and user details.

But is there any possibility to perform services CRUD operations to achievements module by using services module?
Comment: You cold create your own custom resource and use the module api to achieve your goal here is a good [tutorial](https://www.drupal.org/node/783460) to build new resource. After that you need to check the module source code and use its api to build callbacks.
Answer: There isn't an existing integration between Achievements and Services (not one that Google is up for divulging, at least), so you would need to code that yourself. But yes, it's very possible, as both modules are well written.
For full details, check out the Services API docs and the Achievements API docs.


CentOS, How to allow SSH through only one server-ip

Question: I currently have a dedicated server with two pv4 IP addresses assigned to it. I want to make one public, and the other private for SSH/FTP related material.
IP 1 (The public ip): 22.214.171.124
IP 2 (The private SSH ip): 22.214.171.124
Anybody know how i'd BLOCK IP 1 from SSH/SFTP? Is it even possible?
Comment: You even tagged the question with `iptables`...
Comment: Because i assumed it was IPTable related rather then sshd_config.
Answer: Add/edit the following line in /etc/ssh/sshd_config:
ListenAddress 188.8.131.52
Answer: First we make sure that ssh listens only to the desired ip.
In the following file:
/etc/ssh/sshd_config

You'll see a line like:
#ListenAddress 0.0.0.0

This is commented out, but is the default, to list on all IP addresses for ssh requests. You can change this so that it is the IP address of the interface you want to accept connections on, and so only that IP address will accept ssh connections:
ListenAddress 188.8.131.52

Restart the sshd service once changed.
Then allow in iptables the interface with the private ip (eg eth1)
iptables -A INPUT -p tcp  -i eth1 --dport 22 -j ACCEPT

See also:

http://wiki.centos.org/HowTos/Network/SecuringSSH
http://wiki.centos.org/HowTos/Network/IPTables


Is it apporpriate to use two way ANOVA test if I have paired data linked to single individual?

Question: I am new in statistics. I wanted to do some statistical test to determine whether there is a difference between two samples and over the individuals.
So if I have data that looks like this:
<code>Animal type   Numbers_method_1  Numbers_method_2

Tiger         28                 32
Lion          15                 19
Turtle        187                165
Giraffe       311                233
Leopard       123                321
...
</code>
And I have 25 animal types like this. If possible I wanted to do two way comparison, between the methods, but also between the Animals. But since I have paired data linked to single animal, is it possible to use two-way ANOVA comparison, and if not, why? Do I have to link them into categories? Or in other words, is it impossible to do two way ANOVA with pairs linked only to a single case?
Also, this data is raw data, do I have to normalize it before performing such comparison between animals? ... because each animal is different of course.
Answer: If your observations for a single animal type are correlated (as it is natural to assume, if they come from the same individual animal), you should not use ANOVA, but rather a paired  comparison test if the matter of interest is the comparison between method 1 and method 2. If you were looking instead at differences between animals, than a MANOVA one-way test seems adequate (you would have bivariate observations for each animal type).
Independence of observations is a requirement in standard ANOVA, in order for the count of degrees of freedom to be correct.
Comment: In standard ANOVA, the denominator of the test statistics is something like $\sum_{ij}(y_{ij} -  y_{i.})^2/(IJ-I)$ (one way ANOVA; but the idea extends to others too). If observations are independent, this sum of squares suitably scaled is $\chi^2$-distributed with $IJ-I$ defgrees of freedom. If independence fails, this is no longer true, and the null distributions of the test statistics no longer are correct.
Comment: I don't know how you plan to normalize. I guess what you need for a paired comparisons test is that the variance of the $(y_{i1} - y_{i2})$  (difference of measures for animal $i$) is constant across $i$, or nearly.
Comment: that was useful. Why two way ANOVA cannot be used in the cases where there are no cathegories but single individual type and paired data? Also, if I use paired comparison, do I need to normalize my raw data? Because I will be comparing samples from different animals so I guess raw data wouldnt be super helpful?
Comment: I see. I have found one paper with similar data and it says:  " The distribution of the method difference in  values for each animal was compared with the normal distribution using the Shapiro-Wilk test. If the difference was distributed normally at the confidence level of 95%, the dependent t-test for paired samples was performed to determine whether or not the differences between the two samples were statistically significant at this confidence level. Otherwise, the Wilcoxon signed-rank test was used"
Comment: So as I understand I can use Sharipo-Wilk test to compare the normal distribution of my sample? Then if normally distributed I can use dependent t-test on normal data, and if not normally distributed I have to use Wilcoxon-signed ranked test, is that correct?
Comment: In order to test for normality you assume all observations come from a single distribution (otherwise, which normal you are testing proximity to?) So commonality of variances appear to me first and foremost.


Will SADMEP always work to evaluate the inverse of a function, and I should not evaluate right to left?

Question: How do you evalulate $f^{-1}(5)$ where $f(x) = (3 + 2) - (x * 4)$
I understand that if $f(x) = y$ then $f^{-1}(y) = x$
The input and output are essentially reversed. The most common place I have seen and used this is in the trigonometric functions.
So if I wanted to evaluate $f^{-1}(5)$
My approach is to set $(3 + 2) - (x * 4) = 5$
Solve for $x = 0$
Therefore $f^{-1}(5) = 0$
But I was told by a math teacher a long time ago that you could evaluate the inverse of a function by plugging in the values and reversing the order of evaluation. For example, SADMEP instead of PEMDAS.
So I want to do any subtraction first on the expression: $(3 + 2) - (x * 4)$
I believe the first step is therefore $2 - 5$
Now I have $3 + (-3) * 4$
The next step is addition, and then multiplication (since there is no division).
$0 * 4$
$0$
The method apparently works, this time. Will this always work?
Also notice that I took the $2$ and subtracted $x$ or in this case $5$
I solved the expression from left to right, as opposed to doing it right to left. Is it also a requirement to still do things left to right? I believe left to right is still necessary, otherwise this would not have come out right (24 instead of 0).
I will probably make another question asking why $f^{-1}(x) = \frac{1}{f(x)}$ unless someone has a simple answer (you probably do).
Comment: It is very rare that $f^{-1}(x) = \frac{1}{f(x)}$. You are thinking of the *multiplicative inverse* of a number $x$, which is $\frac{1}{x}$. When referring to functions, we want the *compositional inverse* of that function, which is significantly more complicated to express (in fact, it may not even exist).
Comment: The last statement ($f^{-1}(x) = \frac{1}{f(x)}$) is false. $\dfrac{1}{\sin x} = \csc x \neq \sin^{-1} x$. The confusion may arise from assuming that $\sin^k x = (\sin x)^k$, but an exception is made for $k = -1$, where we define it as the inverse function.
Comment: I see that it is false, I was very suspicious of that statement and now I see why I was mistaken.
Answer: The general framework you describe (solve for $x$ in the equation $f(x) = y$) is correct. When you are solving for $x$, you are doing "reverse order of operations", which is what your teacher is calling SADMEP. It is a coincidence that you got the correct answer here (in fact, the first step of $3 + (-3)4$ is incorrect).
I'm not sure how to diagnose the problem except to show how I would do it and ask for your questions.
First, notice
$$
(3 + 2) - (x \cdot 4)
$$
is more concisely written as
$$
5 - 4x,
$$
so we'll work with that. Now, we want to see what $x$ will give the output of $5$. That is, we want to solve
$$
5 - 4x = 5
$$
for $x$. Subtracting $5$ from both sides gives
$$
-4x = 0,
$$
and finally dividing both sides by $-4$ gives
$$
x = 0,
$$
as you've already found.
Comment: @Leonardo "SADMEP" is just an acronym for "reverse order of operations". You seem to understand how to solve for $x$ in this way, but are complicating things by trying to force it directly onto the letters S A D M E P. Notice I subtracted $5$ before dividing by $-4$, as you did in your initial example.
Comment: So there is no reason to use SADMEP, and infact it is not a correct method? I think maybe if there is a correct SADMEP, it is very ambiguous and apparently beyond me at this point. That is, starting with subtraction and ending with exponents/parentheses is itself not correct.
Comment: Yes I am taking it as an algorithmic method to evaluating, where it uses the reverse steps as PEMDAS. Thank you for clarifying why this SADMEP is not "literally" the opposite in the sense that I have considered it.


Not able to throw custom Exception in Platform specific code, and catch in shared code

Question: I have a custom Exception class and I am trying to throw that from my Platform specific implementation in .NET MAUI. And I want to catch that exception in my MainPage.xaml.cs, where the object is initialized.
<code>// Exception class
public class MyCustomException : Exception
{
    public MyCustomException(string message) : base(message) { }
}

// MyClass partial class in MainCode/Common code
public partial class MyClass
{
    public MyClass()
    {
        try
        {
            MyPrivateMethod();
        }
        catch (Exception ex)
        {
            throw new MyCustomException("Error initializing MyClass");

        }
    }

    partial void MyPrivateMethod();

    partial void MyCalledMethod();
}

// Platform-specific implementation of MyClass partial class for .NET MAUI
public partial class MyClass
{
    partial void MyPrivateMethod()
    {
        MyCalledMethod(); // Call the platform-specific implementation of MyCalledMethod
    }

    partial void MyCalledMethod()
    {
        // Implement the platform-specific code for MyCalledMethod
        // This method can throw an exception
        throw new Exception("Something went wrong in MyCalledMethod");
    }
}

// Usage in MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    private MyClass _myClass;

    public MainPage()
    {
        InitializeComponent();

        try
        {
            _myClass = new MyClass();
        }
        catch (MyCustomException ex)
        {
            // Handle the exception here
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

</code>
I get Exception Unhandled error at the MyCalledMethod in Platform Specific code. I want to handle MyCustomException in MainPage.xaml.cs and work accordingly.
Comment: @ToolmakerSteve i am running this on android. But continue doesnt work. After 2 clicks of continue. It crashes the app and gives fatal: exception not handled.
Comment: @ToolmakerSteve, finally was able to solve it. I was using an async method before and didn't rebuild the solution after removing it. Removing the bin folder and rebuilding the whole solution again, solved it.
Comment: Does the unhandled Exception crash the app? Or are you able to "Continue" from it in the Debugger? I've seen situations (not related to "partial") where debugging Android paused at an exception, but then Continue did what was expected (went to the "catch" block). That is, for some reason "Pause only if Not Handled" acts like "Pause when Exception Thrown", when debugging Android.
Comment: I made a demo using the same code in your question. Strangely, it doesn't crash and can ```Console.WriteLine($"Error: {ex.Message}");``` in the MainPage.xaml.cs.
Comment: @LiqunShen-MSFT strange. can you tell which platform did you run your code on. and your .net version.
Comment: In VS Community 17.6.0, works for me on both Windows and Android, when add your code to a default Maui project. (You don't show namespaces, but since it reached your `throw` line, I assume the platform-specific partial code for MyClass is in the `same namespace as the  common code`, not in a namespace such as `MyAppName.Droid`.) Make a `public github repo` with just enough code to build and run, to show this bug. I recommend starting over and `adding your code to a new Maui project`. If that works, then its a matter of finding what is different in your original.
Answer: First try to fix the MyCustomException constructor I see that you are using two parameters and there is just defined one.
Fix:
<code>public MyCustomException(string message, Exception ex) : base(message, ex) { }
</code>
Comment: Oh sorry thats a typo in sample code. I am just passing one param in exception and thats the message


RAILS Arquivo Seed Roda, mas Não Salva O dados no Banco de Dados

Question: Estou criando um arquivo seeds para popular meu banco de dados, esse arquivo é responsável por popular os Grupos(model :grupo) que roda sem problema e também popular TipoAtividade(model :tipo_atividade), que pertence ao grupo.

Quando eu rodo o rake db:seed ele roda normalmente e gera os grupos e aparenta ter gerado os tipos também, logo abaixo o codigo do arquivo seeds.

Porém quando vou olhar o banco de dados é isso que aparece.

Ele cria uma linha no banco de dados, mas não salva os dados nas colunas nome e a referência de grupo(grupo_id).
 Gostaria de saber o que está acontecendo, pois já pesquisei na internet e não achei nada que fosse muito claro sobre esse problema. Cheguei a ver algo de "protected_attributes", mas a gem conflita com certas versões do rails e/ou do bundler, não consegui identificar.
Caso a pergunta não fique clara é so pedir que eu edito.
Comment: Se a resposta abaixo deu certo. Você deve marcar ela como "resolvida".
Answer: No exemplo acima você criou 3 grupos.
A classe Grupo tem um relacionamento has_many :tipo_atividades
Você deve ter a instância de um Grupo exemplo:
# pegando o útimo grupo criado
grupo3 = Grupo.last
grupo3.tipo_atividades.create(nome: 'Palestra')

ou então
# pegando os últimos 3 grupos criados
Grupo.last(3).each do |grupo|
  grupo.tipo_atividades.create(nome: 'Palestra')
end

Utilizando o método has_many
Comment: AH SIM !! Deu certo, mto obg Danilo
Comment: show de bola!!!!


What are number of hidden layers in LSTM?

Question: I new to LSTM. I have not understood some terms used while implementing it in tensorflow. So I have ECG data, with each event having 60 heartbeat templates with each heartbeat template having 600 data points. (like each sentence having x words and each word represented by y size vector). So 600 amplitute points as a function of time comprise of each template and I have 60 of those and they together form one event having some class assigned to it. In all, I have 5000 such events classified in 4 classes. Now, suppose I want to classify them using LSTM, what are my input dimention for "num_hidden" if I am trying to follow the code given here for MNIST data?
num_input = 60
timesteps = 600
num_hidden = ?
num_classes = 4
Also, I don't understand what this "num_hidden" is? LSTM, as described here, doesnot contain such a parameter.
Answer: You're asking two questions here.
num_hidden is simply the dimension of the hidden state.
The number of hidden layers is something else entirely. You can stack LSTMs on top of each other, so that the output of the first LSTM layer is the input to the second LSTM layer and so on. The number of hidden layers is how many LSTMs you stack on top of each other.


Hibernate dynamic @where clause workaround

Question: Is there is any way or workaround, by which we can pass value to Hibernate @where.
I dont need to write the Criteria or any thing else.
Just wanted dynamic @where by any workaround.
Answer: No. Annotations can only have constant value.
Comment: As I mentioned, it is not possible to do with annotations. You didn't ask any question regarding your real problem which you are trying to solve.
Comment: I have a Student Table where I keep student records academic year wise. I just wanted display current academic year students records by only changing code at one place...regardless of making query where clause at everywhere...Please help...!!


BigQuery: Store semi-structured JSON data

Question: I have data which can have varying json keys, I want to store all of this data in bigquery and then explore the available fields later.
My structure will be like so:
[
{id: 1111, data: {a:27, b:62, c: 'string'} },
{id: 2222, data: {a:27, c: 'string'} },
{id: 3333, data: {a:27} },
{id: 4444, data: {a:27, b:62, c:'string'} },
]

I wanted to use a STRUCT type but it seems all the fields need to be declared?
I then want to be able to query and see how often each key appears, and basically run queries over all records with for example a key as though it was in its own column.
Side note: this data is coming from URL query strings, maybe someone thinks it is best to push the full url and the use the functions to run analysis?
Comment: And what is the problem with a JSON column?
Comment: JSON column would need to be parsed into something else for any mathematical analysis. Yes initially I can store in a single col, but further steps are needed - unless I am missing something?
Answer: There are two primary methods for storing semi-structured data as you have in your example:
Option #1: Store JSON String
You can store the data field as a JSON string, and then use the JSON_EXTRACT function to pull out the values it can find, and it will return NULL for any value it cannot find.
Since you mentioned needing to do mathematical analysis on the fields, let's do a simple SUM for the values of a and b:
# Creating an example table using the WITH statement, this would not be needed
# for a real table.
WITH records AS (
  SELECT 1111 AS id, "{\"a\":27, \"b\":62, \"c\": \"string\"}" as data
  UNION ALL
  SELECT 2222 AS id, "{\"a\":27, \"c\": \"string\"}" as data
  UNION ALL
  SELECT 3333 AS id, "{\"a\":27}" as data
  UNION ALL
  SELECT 4444 AS id, "{\"a\":27, \"b\":62, \"c\": \"string\"}" as data
)

# Example Query
SELECT SUM(aValue) AS aSum, SUM(bValue) AS bSum FROM (
  SELECT id,
    CAST(JSON_EXTRACT(data, "$.a") AS INT64) AS aValue, # Extract & cast as an INT
    CAST(JSON_EXTRACT(data, "$.b") AS INT64) AS bValue  # Extract & cast as an INT
  FROM records
)

# results
# Row | aSum | bSum
# 1   | 108  | 124

There are some pros and cons to this approach:
Pros

The syntax is fairly straight forward
Less error prone

Cons

Store costs will be slightly higher since you have to store all the characters to serialize to JSON.
Queries will run slower than using pure native SQL.

Option #2: Repeated Fields
BigQuery has support for repeated fields, allowing you to take your structure and express it natively in SQL.
Using the same example, here is how we would do that:
## Using a with to create a sample table
WITH records AS (SELECT * FROM UNNEST(ARRAY<STRUCT<id INT64, data ARRAY<STRUCT<key STRING, value STRING>>>>[
  (1111, [("a","27"),("b","62"),("c","string")]),
  (2222, [("a","27"),("c","string")]),
  (3333, [("a","27")]),
  (4444, [("a","27"),("b","62"),("c","string")])
])),
## Using another WITH table to take records and unnest them to be joined later
recordsUnnested AS (
  SELECT id, key, value
  FROM records, UNNEST(records.data) AS keyVals
)

SELECT SUM(aValue) AS aSum, SUM(bValue) AS bSum
FROM (
  SELECT R.id, CAST(RA.value AS INT64) AS aValue, CAST(RB.value AS INT64) AS bValue
  FROM records R
    LEFT JOIN recordsUnnested RA ON R.id = RA.id AND RA.key = "a"
    LEFT JOIN recordsUnnested RB ON R.id = RB.id AND RB.key = "b"
)

# results
# Row | aSum | bSum
# 1   | 108  | 124

As you can see, to perform a similar, it is still rather complex. You also still have to store items like strings and CAST them to other values when necessary, since you cannot mix types in a repeated field.
Pros

Store size will be less than JSON
Queries will typically execute faster.

Cons

The syntax is more complex, not as straight forward

Hope that helps, good luck.
Comment: Amazing, what a great answer! I will go for the `JSON` string option - mainly because I am not a DB person and have no real grasp of `STRUCT` in this case, let me know if you have a good resource for this past what is on the BQ website.


AngularJS $http.post succeeds but doesn't save the data

Question: I'm trying to save an array into a JSON file that's located on a webserver.
The response is successful but when I open the JSON it's completely empty.
I've tried to create a JSON object of my own manually but it yielded same results.
Here's the process:

app.controller('BookController', ['$window', '$http', function ($window, $http) {
this.contacts = [];

this.exportContacts = function(contacts){
    $http({
        method: "POST",
        url: '/data/contacts.json',
        headers: { 'Content-Type': 'application/json' },
        data: contacts
    }).then(function goodCall(){
        $window.alert("Save done!");
    }, function badCall(){
        $window.alert("Failed to save error! error: " + $http.status);
    });
};
}]);

I fill the array with inputs via form:

<form name="addCont" ng-show="showForm" ng-controller="ContactController as contactCtrl" ng-submit="contactCtrl.addContact(addCont, bookCtrl.contacts)" novalidate>

    First Name:
    <input name="fname" type="text" required ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.firstName"></input>

        First Name is required.
        First name must contain letters only!

    Last Name:
    <input name="lname" type="text" ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.lastName"></input>

        Last name must contain letters only!

    Phone Number:
    <input name="phone" type="tel" required ng-model="contactCtrl.contact.phone" ng-minlength="9" ng-maxlength="10" ng-pattern="/^(\d)+$/"></input>

        Phone number is too short!
        Phone number is too long!
        Phone number is required!
        Must not contain letters!

    Notes:
    <input name="notes" type="text" ng-model="contactCtrl.contact.notes"></input>

<input type="submit" value="Submit" ng-disabled="addCont.fname.$invalid || addCont.lname.$invalid || addCont.phone.$invalid" />
</form>

So the array should look somethings like this:
[{
    firstName: "Tim",
    lastName: "asdxc",
    notes: "asdasd",
    phone: "0532753940"
},{
    firstName: "Timz",
    lastName: "asdasd",
    notes: "asdasd",
    phone: "123123123"
}]

Do I somehow need to parse the array before sending it?
Comment: i think the url you give to $http is a web service. It will not work with a file
Comment: Take a look at http://stackoverflow.com/questions/17547227/angular-js-post-request-not-sending-json-data
Answer: As far as I understand your code, you are missing an important peace. You need some RESTful like service on your server. Otherwise your not able to save/write to files on your server.
I recommend you to get familiar with node and may be express for the start.
Answer: The url you give to $http should be a web service.
It will not work with a file.
You have to create a webservice who create the file on server side ( php / node.js / java ... ) and call it from $http
Answer: I think url property must be 'api/contacts':
Given that you must have a web service or web api controller: ContactsController
$http({
        method: "POST",
        url: 'api/contacts',
        headers: { 'Content-Type': 'application/json' },
        data: contacts
    }).then(function goodCall(){
        $window.alert("Save done!");
    }, function badCall(){
        $window.alert("Failed to save error! error: " + $http.status);
    });


IntelliJ uses more memory than allocated

Question: My IntelliJ goes unbearably slow, so I was fiddling with memory settings. If you select Help -> Change Memory Settings, you can set the max heap size for IntelliJ. But even after restarting, then running Mac's Activity Monitor, I see it using 5.5GB even though I set the heap to 4092MB.
It's using 1.5GB more than allocated for heap. That's a lot of memory for permgen + stack, don't you think? Or, could it be that this memory setting actually doesn't have any effect on the program?
Answer: It's the virtual memory you see, it may also include memory mapped files and many other things occupied by the JVM internals, plus the native libraries for a dozen of Apple frameworks loaded into the process. There is nothing to worry about unless you get OOM or IDE becomes slow.
If it happens, refer to the KB documents and report the issues to YouTrack with the CPU/Memory snapshots.


PHP and MySQL Project Pay

Question: Someone asked me to design a database and implement it using MySQL. Additionally, I am also asked to write PHP scripts so that one can do some "simple" data analysis with the data inside MySQL. It is not very complicated. It is like a school database and I will have to write programs that will retrieve all the classes that a student has taken and stuff like that.
I am wondering how much I should charge for this kind of project.
Comment: Related: http://stackoverflow.com/questions/366338/how-much-does-website-development-cost-nowadays
Answer: Work out time and charge a rate that you think it will cost you. Freelance rates vary hugley by location and skill level. Also what about the clients budget? Lots of factors will play a part
Also google a little, there is plenty of data out there.
http://www.bytestart.co.uk/content/contractors/contractor-guides/it-contractor-market-rates.shtml
Also a useful answer here - https://stackoverflow.com/questions/806298/short-contract-pay-rates-for-programmers-in-the-uk
Comment: Or don't work at all if it's not worth the interference with your studying. "An investment in yourself always pays the best interest!" ... Benjamin Franklin
Comment: You have answered the question then. Work with what budget is available.
Comment: I am still a student and my client doesnt have that much budget for this project. That's why they want me to do it.
Comment: @adamantinex - If you are happy with the answer please select one (Click the green tick).

PHP and MySQL Project Pay


I want to display the all true/false questions in same page using quiz module. Is it possible?

Question: I have installed drupal 7 quiz module in my project.I want to display the all true/false questions in same page. Is it possible?
Comment: What do you mean by "Same Page" ?
Comment: Quiz module display the one question per page. I want to display the all true/false questions in per page
Answer: Try using  Quiz Progress module .. It offers nice User Experience to track status of questions and navigation..
Project page says

Quiz 6.x has the limitation of displaying only one question at a time.
This makes it hard to navigate from one question to other especially
when you have a skipped question in the beginning and you have your
current question at the closure of quiz.
The "Quiz Progress" module tries to overcome this problem, it provides
a block that prints the list questions in the quiz referenced by title
or number (with tooltip) depends on the widget configured in module
settings, highlighting their status skipped, answered or unanswered as
a link.

Here is the final output using above module which lists all questions...

If you are looking for Solution from Quiz Module itself take a look at this issue in Quiz Module.. Seems like #106 works in above issue..
Answer: Add content to  "Quiz Page" content type. For example "All true/false questions" --> Go to "Manage QUestions"--> Add the newly created "Quiz Page" question-->Simply drag and drop "True/False QUestions underneath the newly added question "QUiz Page"