Solutions for a growing Postgresql database on Amazon EC2?

Question: I've been doing a lot of research into scaling issues on Amazon EC2, especially growing databases. I looked into how I can make the database more solid and sound (I use PostgreSQL). Many sources say using RAID0 with streaming replication and WAL archiving is pretty fault tolerant.
All the postresql data & tables will be stored on the EBS volumes that have RAID0. Many sources claimed that using an XFS system would be ideal. Is it possible to add more EBS volumes to this RAID0 array if I ran out of space while keeping the database online? If so, is there some sort of recipe or source I can follow?
Answer: Assuming you're using Linux's md software RAID I'm pretty sure can hot-add volumes to a RAID 0 using the --grow command, but I would recommend testing this to verify that I'm right and that it's supported by your md version.
If you're planning on using real-time replication anyway and you're confident you can run a good, reliable replication and backup system you might as well use the instance store rather than EBS, especially if you can justify a High I/O instance. Remember that if you terminate an instance store based instance or it crashes you will lose the data on that instance permanently, so backups and replication to other AZ's / regions are vital.
Personally I prefer to run DBs on other hosting providers that're cheaper and offer much better I/O performance, but EC2 has some management advantages.
I wrote a post on this a little while ago that may be useful: Improving PostgreSQL performance on EC2.
Comment: hey! I came across your post a few months back, it was very useful, I'm trying to find a really good tutorial for RAID0 setups


Tabelas com dados de base de dados

Question: Alguém sabe como restringir um certo numero de linhas na tabela, mas ao fazer scroll ver o resto dos dados?
Por exemplo, uma empresa que guarda os dados dos clientes na BD e quer ver todos os dados dos clientes numa tabela, mas apenas 10 clientes por página. Só que em vez de ter um botão para mudar dos 10 primeiros clientes para os 10 seguintes, usar scroll para isso.
Tipo isto, sem aqueles números, mas sim com um scroll:

Alguém me pode dizer como se chama isso ou um site que mostre ou então mesmo mostrar o código?
Comment: Você precisa manter o cabeçalho ao fazer o scroll?
Comment: @MaiconCarraro Sim, preciso.
Answer: Esse problema de scroll na tabela e manter o cabeçalho é bem famoso.
Primeira solução jQuery Scrollable.
Importante, esse plugin carrega toda tabela de uma vez.
Exemplo:

jQuery(document).ready(function($)
{
    $('#thetable').tableScroll({width:500});
});
<link href="http://www.farinspace.com/css/jquery.tablescroll.css" rel="stylesheet"/>

      city
      state code
      zip
      latitude
      longitude
      county

      Holtsville
      NY
      00501
      40.8152
      -73.0455
      Suffolk

      Holtsville
      NY
      00544
      40.8152
      -73.0455
      Suffolk

      Adjuntas
      PR
      00601
      18.1788
      -66.7516
      Adjuntas

      Holtsville
      NY
      00544
      40.8152
      -73.0455
      Suffolk

      Adjuntas
      PR
      00601
      18.1788
      -66.7516
      Adjuntas

      Holtsville
      NY
      00544
      40.8152
      -73.0455
      Suffolk

      Adjuntas
      PR
      00601
      18.1788
      -66.7516
      Adjuntas

      Holtsville
      NY
      00544
      40.8152
      -73.0455
      Suffolk

      Adjuntas
      PR
      00601
      18.1788
      -66.7516
      Adjuntas

      Holtsville
      NY
      00544
      40.8152
      -73.0455
      Suffolk

      Adjuntas
      PR
      00601
      18.1788
      -66.7516
      Adjuntas

-
Segunda solução jQuery DataTables
Com ele é possível carregar por demanda igual sua necessidade atual.
Sugestão do Marcus Vinicius

$(document).ready(function() {
  $('#example').dataTable( {
    "bScrollInfinite": true, /* você precisa dessa propriedade */
    "bScrollCollapse": true,
    "sScrollY": "200px"
  } );
});
<link href="http://legacy.datatables.net/release-datatables/media/css/demo_table.css" rel="stylesheet"/>

   Nº.Feder.
   Clube
   Tipo HCP
   Data Actual
   TipoJogador

   Nº.Feder.
   Clube
   Tipo HCP
   Data Actual
   TipoJogador

   22739
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   42944
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   23060
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227391
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429441
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230601
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227392
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429442
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230602
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227393
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429443
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230603
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227394
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429444
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230604
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227395
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429445
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230605
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227396
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429446
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230606
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

   227397
   083-Oitavos
   HCP EGA
   2015-06-10
   Amador

   429447
   165-ACGB
   Suspenso
   2015-06-11
   Amador

   230607
   083-Oitavos
   Suspenso
   2015-06-08
   Sra.AmadorA

Se quiser conhecer os outros parâmetros deste plugin é só dar uma olhada aqui.
Comment: Não é só isso que ele quer, ele quer carregar linhas dinamicamente na tabela conforme o scroll for ocorrendo. Mais ou menos assim: http://legacy.datatables.net/release-datatables/examples/basic_init/scroll_y_infinite.html
Comment: @MarcusVinicius Entendi, interessante esse exemplo... não compensa você transformá-lo em resposta já que ele pediu indicação de site ou exemplo?
Comment: Preciso montar um exemplo aqui, mas estou sem tempo. Fique a vontade se quiser.
Comment: @MarcusVinicius Feito :)
Comment: @MaiconCarraro Muito Obrigado isso ajudou imenso. Mas será que podia dizer qual é, no segundo exemplo que deu, o código que dá pesquisa?
Comment: @MaiconCarraro e como faço para por limite na tabela? por exemplo, ao todo são 100 dados como faço para por apenas 10 e depois fazer scroll? Será que é com css diminiur o tamanho da tabela? já agora os dados são diretamente da base de dados
Comment: @BrunoGibellino De acordo com a documentação que eu coloquei no último link ali o limitador de itens é esse atributo `iDisplayLength`
Comment: Sobre a busca da uma procurado por `Search` nesse link da documentação ou [aqui se preferir](http://legacy.datatables.net/ref)

Tabelas com dados de base de dados


`composer require` fails because "Source directory docroot/core has uncommitted changes"

Question: Symptom: You have a script that fails while executing a composer require command, resulting in output like the following:
$ ./example.sh
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)

In VcsDownloader.php line 242:

  Source directory docroot/core has uncommitted changes.

Attempting to execute the offending composer require command manually results in output like the following:
$ composer require drupal/examples
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
    The package has modified files:
    M core.services.yml
    M includes/install.core.inc
    M includes/install.inc
    M lib/Drupal/Core/Config/ConfigInstaller.php
    M lib/Drupal/Core/Config/ExtensionInstallStorage.php
    M lib/Drupal/Core/Config/InstallStorage.php
    M lib/Drupal/Core/Entity/EntityViewBuilder.php
    M lib/Drupal/Core/EventSubscriber/ConfigImportSubscriber.php
    M lib/Drupal/Core/Extension/ExtensionDiscovery.php
    M lib/Drupal/Core/Extension/ModuleExtensionList.php
    19 more files modified, choose "v" to view the full list
    Discard changes [y,n,v,d,?]?

Conditions: You are using Composer to manage your Drupal site dependencies and applying patches with cweagans/composer-patches. You may be using Acquia BLT.
Answer: Explanation: The problem is that cweagans/composer-patches is applying patches to Drupal Core after cloning it, leading Composer to believe you've modified the affected files and therefore to prompt you to overwrite them lest you unwittingly lose work in progress.
Solution: Configure Composer to discard-changes which "[sets] the default style of handling dirty updates when in non-interactive mode... [to] always discard changes in vendors", then modify your script to pass the --no-interaction (or -n) flag. E.g.:
$ composer config discard-changes true
$ composer require -n drupal/examples
Using version 1.x-dev for drupal/examples
./composer.json has been updated
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
Deleting docroot/core - deleted
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/core (8.6.x-dev 8dbf42a): Cloning 8dbf42a90c from cache
  - Applying patches for drupal/core
    https://www.drupal.org/files/issues/2869592-remove-update-warning-7.patch (2869592 - Disabled update module shouldn't produce a status report warning)
    https://www.drupal.org/files/issues/2885441-2.patch (2885441 - EntityReferenceAutocompleteWidget should define its size setting as an integer)
    https://www.drupal.org/files/issues/2018-09-24/2815221-109.patch (2815221 - Add quickedit to the latest-revision route)
    https://www.drupal.org/files/issues/2018-10-12/1356276-531.patch (1356276 - Allow profiles to define a base/parent profile and load them in the correct order)
    https://www.drupal.org/files/issues/2018-07-09/2914389-8-do-not-test.patch (2914389 - Allow profiles to exclude dependencies of their parent)

Writing lock file
Generating autoload files


Use orConditionGroup with query (non entity)

Question: I've used orConditionGroups with queries before. Specifically with entity queries. But now I have a custom sql table I created separate from drupal but still on the same database I have access to. I want to update a row if any of the fields are different but I'm having generating the or statement. Here was my attempt.
<code>$connection = \Drupal::database();
$orConditionGroup = $connection->orConditionGroup()->condition('address', $fulladdress, '!=')->condition('full_name', $fullname, '!=')->condition('telephone', $workphone, '!=');
  $connection->update($table)->fields(['full_name' => $fullname, 'address' => $fulladdress, 'telephone' => $workphone, 'email' => $email])->condition('id', $id)->condition($orConditionGroup);
</code>
But I get the error

undefined method
  Drupal\Core\Database\Driver\mysql\Connection::condition()

Which makes sense since the connection class isn't a query object on its own, but not sure how else to tackle this. How would I create an orConditionGroup for just a plain direct sql query that isn't a drupal entity or anything like that?
Answer: I was able to get it to work by added the select method to the connection object like so:
<code>$orConditionGroup = $connection->select($table)
                    ->orConditionGroup()
                    ->condition('address', $fulladdress, '!=')
                    ->condition('full_name', $fullname, '!=')
                    ->condition('telephone', $workphone, '!=');
</code>


jquery input validation+background color

Question: I have an HTML form where I want to add some validation logic.
In that form i have two input fields, one of them has to get always integer values, while the other one have to get always float values. (first one is items number and other one is total cost).
I want those input fields to change background color to light red if the input value is wrong (float value as item number, for example) and i want to care only for the logic of it, maybe i can guess jQuery can take care of everything else, but I can't find any help on internet on how to get this done without reinventing the wheel.
Does anyone have some hints on how to do that?
Comment: Have you looked at jQuery Validation? http://goo.gl/Ret4
Answer: You seem to be talking about form validation
you can write your own code in javascript or jQuery.... or google about form validation you will get tons of result...
for a primer you can check this jQuery validate plugin
<code>http://jquery.bassistance.de/validate/demo/

http://docs.jquery.com/Plugins/Validation
</code>


The Constant in Integration

Question: I have a rudimentary understanding of calculus and  I know that if $y = f(x) = 2x + 3$ then, $\frac{dy}{dx} = 2$ and now if I were to perform the inverse operation, integration, $\int 2 dx = 2x + C$ where $C$ is called the constant of integration.
As a definite integral (?), pardon my ignorance, $\int_1^2 2 dx$, I get $(2(2) + C) - (2(1) + C) = 2$ . It is not necessary to know what $C$ is. However, what about, if $g(x) = \int 2 dx$, $g(0)$? $g(0) = C$ but we can't know $C$.
Comment: It sounds like you understand what's going on: the antiderivative is not unique, it's only unique up to addition of a constant. What's your question?
Comment: Generally it is not important to know the constant of integration. And, more importantly, it is not possible to uniquely determine it - two different people using different methods to compute an indefinite integral might come up with different values of the constant.
Comment: If all you know about $a$ is that $a^2=4$, then you can't know the sign of $a$. But you can compute that $a^4$ is $16$. If $g(x)=\int 2dx$, then all you know about $g$ is that $g'(x)=2$, and that does not uniquely determine the value of $g$ at $0$, but you can use it to compute your definite integral. So yes, what you've said is correct. Did you have some further question?
Comment: Is it not important to know $C$ (the constant of integration)? The derivative of a constant is $0$ and so a function $y = f(x) = 4$ would have a slope/derivative = $0$. I now *can't* integrate to $y = f(x) = 4$. Notice this is different from $a^2 = 4$ where $a = \pm 2$.
Comment: @Karl, has no one tried to work on the problem. It would be nice, *cogito*, if we could find out the correct $C$. Can we perhaps *guesstimate* it? For example if $y = f(x) = F - 0.5x$, where $y$ is the amount of fuel left in the gas tank after travelling $x$ miles, the constant of integration would be $F$ and we know that gas tanks have a maximum capacity of $200$ gallons.
Answer: The $+C$ at the end of the indefinite integral $\int f dx = F(x) + C$ represents the fact that for any integrable function $f$ there are infinitely many valid antiderivatives. In fact, they form an equivalence class, and the notation $\int f dx$ represents this class while $F(x) + C$ represents a generic member of the class.
By that measure, it's not wrong to write $\int 2x\ dx = x^2 + 3 + C$, for example. After all, $G(x) = x^2 + 3$ is as much an antiderivative of $2x$ as $F(x) = x^2$ is, and any valid antiderivative can be written as $G(x) + C$ for some value of $C$. We just tend to choose the simplest (for some definition of simple) antiderivative to represent the whole class as a matter of convention. (It also means that if you use two different methods to integrate a function $f$ and you come up with two different solutions, it is entirely possible that it's because the difference between those solutions is just a constant.)
When we calculate a definite integral via the Fundamental Theorem of Calculus, it doesn't matter which antiderivative of $f$ we choose, it only matters that we choose the same one at both bounds of integration, which is why the constant $C$ vanishes.
(There are some details I've left out here, e.g. an assumption about the region that $f$ is integrable over, but hopefully this provides some basis for understanding.)
Comment: Would I be correct if I were to say that what we don't know about the *antiderivative* is the *shift* along the $y$ axis or the $y$ intercept?
Comment: Broadly, yes. When you get past plain differentiation and integration into differential equations, though, you will come across similar families of functions where the parameter(s) that separate elements aren't just an added constant. For example, while the equation $\frac{dy}{dx} = -x$ has the solution set $\{-\frac{x^2}{2} + C\}$, the equation $\frac{dy}{dx} = -y$ has the solution set $\{Ce^{-x}\}$.

The Constant in Integration


Possible to have independent observations without random sampling?

Question: Is some form of random sampling required for observations to meet the "independence" assumption of various types of regression analysis and hypothesis testing?
My data (fish counts, without replacement - i.e., didn't throw it back) was collected like this:
Sites for observation were selected based on a particular interest/purpose and each site has been repeatedly visited over time (with breaks in-between, so not continuous).
Does this "clustering" or "grouping" of the data at specific locations mean that each observation is not independent? Does it depend on what type of data is collected (a mobile vs. stationary target population)? Is this clustering of the data points (a non-random sampling method) all someone needs to know if they wish to determine if the data are independent?
Answer: First selecting a number of sites, and than collecting observations from those sites is a classic example of not independent samples. This is very common; most national surveys do that when they want to do in person interviews. If they do random sampling, then the interviewers need to travel all over the country. It is much more efficient to first select a few towns, and than sent an interviewer to each of these towns and do all the interviews in that town. But, when you do your analysis you will need to take that into account.
Comment: Correct, two persons randomly drawn form the same town will on average be more similar on a lot of characteristics than two person randomly drawn from the entire population.
Comment: Thank you for your answer. For my own understanding, the data collected "within" each site are not independent from each other or there's no independence between sites? Or both? The data at each site are too related because they all come from the same location and therefore may share too many similar characteristics; that commonality equates to being "not independently surveyed?"


Why is $\sum\limits_{i=0}^{n}(r-1)^{n-i}{n\choose i} = r^n$?

Question: I was solving a problem and found that $\sum\limits_{i=0}^{n}2^{n-i}{n\choose i} = 3^n$. So I tried to generalise it and got $\sum\limits_{i=0}^{n}(r-1)^{n-i}{n\choose i} = r^n$. Is it true for $r > 1, r \in \mathbb{Z}$?
Comment: It's the binomial theorem i.e. $(1+x)^n=\sum_{i=0}^n \binom{n}{i}x^n$ with $x=r-1$.
Comment: @Semiclassical I feel like an idiot asking the question. Anyway, thanks.
Answer: Yes, it's true. Note that
$$r^n=\{(r-1)+1\}^n=\sum_{i=0}^{n}\binom{n}{i}\cdot (r-1)^{n-i}\cdot 1^i.$$
Answer: Consider counting $r$-tuples of sets $(A_1,\dots,A_r)$ such that $A_1 \subseteq \dots \subseteq A_r$. The number of such is clearly $r^n$ since we may view it as choosing which of the sets $A_1, A_2 \setminus A_1, \dots, A_r \setminus A_{r-1}, [n]\setminus A_r$ each element of $[n]$ belongs to.  The left hand side is conditioning on what bottom set we take (i.e., what $A_1$ is).
Answer: http://en.wikipedia.org/wiki/Binomial_theorem
$$(x+y)^n = \sum_{i=0}^n {{n}\choose{i}}x^iy^{n-i}$$


Closed line integral, arrow direction, is this correct?

Question: I have the following closed integral (with circle through the integral sign):
$\int y^2dx + 2ydy$
and the curve is drawn as two functions: y1 = $\sqrt{x}$ and y2 = $x^2$, they intersect at (x,y) = (1,1), and the arrows are drawn: upwards on y2 and downwards on y1.
I parametrize both: x = t, y1 = $\sqrt{t}$, y2 = $t^2$ , 0 <= t <= 1
$\int_0^1 t^4dt + \int_0^1 2*t^2dt - \int_0^1 tdt - \int_0^1 2*\sqrt{t}dt$
is the parametrization correct? I'm not sure about the + and - signs though, thanks for the help !
Comment: Btw you can use \oint to get the closed line integral symbol
Answer: Recall that after you parameterize, you want
$$\int_C y^2dx + 2ydy = \int_0^1 \left(y^2\frac{dx}{dt} + 2y\frac{dy}{dt}\right)dt$$
Now, it's easier to work with $C$ if we break it up into two paths. We can do that as follows:
Let $C_1=\alpha(t)$ be the path given by $y_1=x^2$ and $C_2=\beta(t)$ be the path given by $y_2=\sqrt{x}$. (Note that I switched $y_1$ and $y_2$, so that we're going "upwards" on $y_1$.) Then, we can parameterize each as follows:
$$\alpha(t) = t^2, \ \ \ \  t \in [0,1]$$
$$\beta(t) = \sqrt{1-t}, \ \ \ \ t \in [0,1]$$
(Why do we use $\sqrt{1-t}$?) This gives us the proper orientation. Now, remember to take derivatives when transforming coordinates. Namely,
$$\frac{dx}{dt}=1, \ \ \ \ \ \ \ \ \frac{dy_1}{dt} = \frac{d\alpha}{dt} = 2t, \ \ \ \ \text{ and } \ \ \ \ \frac{dy_2}{dt} = \frac{d\beta}{dt} = -\frac{1}{2}(1-t)^{-1/2}$$
Now, we have
$$\int_C y^2dx + 2ydy = \int_{C_1} y^2dx + 2ydy + \int_{C_2} y^2dx + 2ydy$$
We can now compute each individually. For example,
$$\int_{C_1} y^2dx + 2ydy = \int_0^1 ((t^2)^2 + (2t^2)(2t))dt$$
Comment: On second thought, you can indeed use $\beta(t)=\sqrt{t}$, as long as you take the negative of the integral, as you did. But both parameterizations are equivalent. Just make sure you also remember to take derivatives when transforming coordinates.
Comment: Thanks, that helped a ton!


Pegar selector de um plugin

Question: Estou tentando criar um plugin mas não consigo pegar o selector, e ele ainda foi removido da versão 1.9.
Se eu usar $(this).selector no plugin, ele retorna uma string #div #elementoA, #div #elementoB. Já tentei usar this.each pra tentar pegar individualmente, mas não consegui.
Preciso de uma forma que retorne ou um array, ou um objeto, mas com os selector's individuais: '[#div #elementoA] [#div #elementoB]. É possível usando o 1.9?
$('#div #elementoA, #div #elementoB').plugin()

Answer: Parece que não tem mais jeito.
A documentação inclusive dá um exemplo onde um plugin que precisa saber do seletor deve recebê-lo repetido como um parâmetro da função.
Exemplo de declaração:
$.fn.foo = function( selector, options ) { /* código */ };

Exemplo de chamada:
$( "div.bar" ).foo( "div.bar", {dog: "bark"} );

Não é uma resposta satisfatória, mas é a resposta oficial.
Creio que o melhor seria reformular seu código para não depender do seletor, se possível, caso contrário seria possível criar uma alternativa mais bonita do que a repetição. Um exemplo bem simples e pouco sofisticado seria:
function applyPlugin(selector, options) {
    $(selector).plugin(selector, options);
}

Se possível, edite a pergunta explicando exatamente o que você não conseguiu fazer com com o each.
De qualquer forma, fica o modelo do uso do each:
$.fn.myNewPlugin = function() {
    return this.each(function() {
        // ação em cada elemento aqui
    });
};

Comment: Uma GAMB que eu fiz foi dar um `split` : `$(this).selector.split( ', ' )`. Retornou um array como queria, mas gambiarra é gambiarra né, nunca se sabe... rs
Comment: Coloquei os links dentro de um `element` e nele eu faço um loop para pegar cada item. TKS
Comment: O `each` seria apenas para tentar pegar o selector de forma individual. Nunca criei um plugin, o que estou fazendo é um aprendizado, mas de forma geral eu chamo `$('#div #A, #div #B').plugin()` e dentro do plugin   eu uso `.attr('id')` pra trabalhar o `CSS`. Certamente estou fazendo errado, por isso queria tentar pegar o `selector`. Mas vou tentar aprender melhor. Valeu pela resposta.
Comment: @papacharlie mas pra que exatamente vc precisa dos seletores? Se é apenas para aprendizado o split deve funcionar bem, talvez com uma expressão regular mais avançada fique mais confiável.
Comment: O seletor `#div #elementoA` me daria a garantia de somente esse elemento ser manipulado. Não é nada complexo, é falta de conhecimento mesmo.
Comment: @PapaCharlie Já pensou em contar o número de elementos? Por quê é importante garantir que somente um elemento está sendo manipulado?

Pegar selector de um plugin


301 htaccess redirect dynamic url help needed

Question: I'm trying to redirect this
hhttp://www.website.net/forum/index.php?showtopic=12345
to
hhttp://www.website.ORG/forum/t12345
12345 being the dynamic topic ID
I also need any information to be stripped away if it is found after the topic ID, for example
hhttp://www.website.net/forum/index.php?showtopic=12345&view=getlastpost
I want &view=getlastpost or any similar that may appear after the ID number to be get rid of.
I've tried
RewriteCond %{QUERY_STRING} ^(([^&]&))showtopic=([^&]+)&?(.*)?$
RewriteRule ^index.php$ http://www.website.org/forum/t%3?%1%4/ [L,R=301]
but it didn't work. I get trash in the URL.
hhttp://www.website.org/forum/index.php?showtopic=29294&view=getlastpost (when that link is clicked - the result is hhttp://www.website.net/forum/t29294?view=getlastpost/)

hhttp://www.website.org/forum/index.php?showtopic=29029 (when that link is clicked - the result is hhttp://www.website.net/forum/t29029?/).

How can I clear it out?
Comment: added hhttp in order to escape the restrictions of url number in the question by this websites' system. sorry.
Answer: $2 implies there are two bracketed areas, but I only see one in your rule, so changed that to $1.
Also your URL starts /forum/ so need to include that in the rule.
And the . in index.php needs to be escaped if you don't want it treated as a regex special character.
And if you want to ditch anything after the showtopic=1234 then just remove the $ that indicates the end of the string
RewriteRule ^forum/index\.php?showtopic=([0-9]*) http://www.website.org/forum/t$1/ [L,R=301]

Comment: sorry, it didnt work. check first question I ve updated some things.


Flash player debug problem

Question: I have installed flash player 10,1,82,76. When i tried to debug my application, it returned this alert message ..
C:\WINDOWS\system32\Macromed\Flash\NPSWF32.dll
Flex Builder cannot locate the required debugger version of Flash Player. You might need to install the debugger version of Flash Player 9 or reinstall Flex Builder.
Do you want to try to debug with the current version?
And When i tried to install flashplayer_10_ax_debug.exe, i got this message.
"The version of Adobe Flash Player that you are trying to install is not the most current
version. Please visit the Player Download Center to obtain the latest, most secure version."
What is the solution ?
Answer: What browser are you targeting? You may need to disable/remove the current version before continuing with the debug player install. I went through this process before for testing diff player versions (9, 10) in IE, Firefox and Chrome, and detailed it here
Answer: I had similar problem when I was trying to debug my application with an internal Eclipse web browser. When I changed preferences so that debug started in external web browser like Firefox or Opera, problem disappeared.
Hope that it'll be of any help to you.

Flash player debug problem


How does contains() in PL-SQL work?

Question: Have a lot of unnecessary results using contains() method in my query. Don't tell me to use like or something else. It is hardcoded and couldn't be changed.
Comment: can i pass any params into contains to narrow search results to exact result
Comment: Select * from blabla where contains(dFullText, "car")
Answer: Contains is used on text fields that have a 'CONTEXT Index', which indexes a text field for searching.  The standard usage is like this (using the score operator to display what is returned from the contains clause based on the 1 in contains matching the 1 in score):
SELECT score(1), value
FROM table_name
WHERE CONTAINS(textField, 'searchString', 1) > 0;

For data like this in table table_name
value  |  textField
-------|-----------------------------------------------
A      |   'Here is searchString.  searchString again.'
B      |   'Another string'
C      |   'Just one searchString'

That query would return
2 A
1 C

So contains is similiar to like, but will count how many times a string occurs in a text field.  I couldn't find a resource using Contains the way it is used in the query you posted, but I think that would return rows where dFullText has at least one instance of car in it, or the equivalent of this sql:
Select * from blabla where dFullText like "%car%"

Here is another source.
Comment: @Rene, yes they are different.  `Contains()` counts how many times a string occurs in a text field and would return that number.  `instr()` searches for a string in a field (or other string) and returns the index of the first search string found (or 0 if it's not found).  See examples of `instr()` at http://www.techonthenet.com/oracle/functions/instr.php
Comment: Is there any difference between contains() and instr() ?
Answer: See this example from oracle.com
declare
rowno number := 0;
   begin
   for c1 in (SELECT SCORE(1) score, title FROM news
          WHERE CONTAINS(text, 'oracle', 1) > 0
          ORDER BY SCORE(1) DESC)
   loop
   rowno := rowno + 1;
   dbms_output.put_line(c1.title||': '||c1.score);
exit when rowno = 10;
end loop;
end;

How does contains() in PL-SQL work?


Replace my textview with a string called from another objects java.lang.NullPointerException

Question: Im not sure why im getting NullPointerException. The method getQuestion() currently points to a hard coded String for troubleshooting purposes. Im trying to generate a different string before setContentView() runs to avoid having to refresh the UI.
First I call the method getQuestion()
    TextView t=new TextView(this);
    t=(TextView)findViewById(R.id.textView4);
    try {
        //above executes well :) ... problem is below
        t.setText(quiz.getQuestion());
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        Toast.makeText(AlarmReceiverActivity.this, "getQuestion() failed", Toast.LENGTH_LONG).show();
                    e1.printStackTrace();
    }

    setContentView(R.layout.main);

This is some of my Question.class:
    Question(){
    question="null";
    answer="null";
    try {
        newQuestion();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}//Question constructor

String getQuestion(){
    return "This is a question?";
}//get question

Comment: Provide full log from `LogCat` please
Answer: you cannot call t=(TextView)findViewById(R.id.textView4); before calling setContentView(R.layout.main);. First you need to set your layout, then findViewById can find the view from your defined layout
Answer: You should Call the method setContentView() before calling the method findViewById() .
You should set the content layout of your Activity before trying to find Views, that's why it gives you a NullPointerException
setContentView(R.layout.main);//should be called before any findViewById()
TextView t=new TextView(this);
    t=(TextView)findViewById(R.id.textView4);
    try {
        //above executes well :) ... problem is below
        t.setText(quiz.getQuestion());
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        Toast.makeText(AlarmReceiverActivity.this, "getQuestion() failed", Toast.LENGTH_LONG).show();
                    e1.printStackTrace();
    }

Answer: First call
setContentView(R.layout.main);

and then call
TextView t = (TextView)findViewById(R.id.textView4);


Add class to views row if image fields has content

Question: I have views which has multiple image fields. In some cases all those image fields are empty, but some cases one of them has content.
When image field has content I want to have extra class .has-image for views row.
There is image fields: image_field_1, image_field_2 and image_field_3
It can be done programmatically, but I'm lost how to check those fields.
I know this much:
function YOURTHEME_preprocess_views_view_unformatted(&$vars){

SOLUTION
There can not be used $vars['classes_array'][$id][] because $classes_array[$id] is not an array.
Here is code for working solution.
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image) || !empty($row->field_field_image_2) || !empty($row->field_field_image_3)) {
      $vars['classes_array'][$id] .= ' has_field';
    }
    else {
      $vars['classes_array'][$id] .= ' has_no_field';
    }
  }
}

Comment: assuming the class only affects the images, why not just include the row class under settings, regardless of whether or not there is an image present?
Comment: Nope. I'm trying to make this and seems that it is not possible without creating extra class for those views rows which has image:  http://stackoverflow.com/questions/24991350/center-div-vertically-when-img-tag-is-not-displayed
Comment: see if this helps (http://drupal.stackexchange.com/questions/3059/dynamically-adding-a-css-class-to-a-view-row-with-template-php)
Answer: When you use the preprocess function you find the result in
$vars['view']->result

and the corresponding classes array under
$vars['classes_array']

where in results and in classes array the corresponding rows have the same key.
You can do now something like this in your preprocess function:
foreach ($vars['view']->result as $rid => $row) {
  if (isset($row->YOUR_FIELD) && !empty($row->YOUR_FIELD)) {
    $vars['classes_array'][$rid][] = 'has_field';
  }
  else {
    $vars['classes_array'][$rid][] = 'has_no_field';
  }
}

It is untested and just a little scribble but maybe it helps you.
Comment: I'm getting: Fatal error: [] operator not supported for strings in. Any help?
Comment: I got it work by using this, but now it adds same class (has_field) to every row even if field_image has content or does not have : `function theme_preprocess_views_view_unformatted(&$vars) { $view = $vars['view']; $rows = $vars['rows']; foreach ($vars['view']->result as $id => $row) { if (isset($row->field_image)) { $vars['classes_array'][$id] = 'has_field'; } else { $vars['classes_array'][$id] = 'has_no_field'; } } }`
Comment: Hmm, could it be because I use one field to show all content. So I have field which has Rewrite results and then tokens. So it basically loads all fields no matter if they does not have content? Here is my field Rewrite results: `[field_image][field_image_2][field_image_3][field_tile_title][field_text_to_frontpage_box]`
Comment: So code should check if field has value (content) or not. Any tips?
Comment: Do you use devel module? There is a function `dpm()` which shows you the content of an array or anything else. Maybe add `dpm($vars['view']->result); ` to your preprocess function to find out how the field looks like when there is content and when there is no content.
Answer: An alternative solution to using a preprocess function (because I wanted to override this in a module not the theme and didn't want to delve into the possibility of overriding the theme registry), I did the following:

created a custom version of the view's theme template Style Output: views-view-unformatted.tpl.php, by removing the div wrapper within the foreach loop
created a custom version of Row style output: views-view-fields.tpl.php by wrapping the fields with a div there and adding class names based on the field data in $row->field_YOUR_FIELDNAME[0]['raw']['value']

I had a boolean field I was checking, so you may want to log (with watchdog) or print out $row->field_YOUR_FIELDNAME[0]
and see what's available.


ML method to determine growth of accounts in a bank

Question: Assume a bank has today N checking accounts, and also has 10 years history of the account balances. The history also includes related features such as "Allow overdraft" (Yes/No) and "Opening branch" (integer code). The accounts have 30 more features.
What I need is to train a ML model to learn how many accounts will be opened monthly in the next year. What ML method should be used to approach this?
Comment: Well, I'm not going to simply *do* your job for you over the internet.  Moreover, the solution depends on the data, which is not available to me.  Forecasting is an extremely well researched topic.  Excellent tools exist for these sorts of problems (see Rob Hyndman's R package `forecast` and the accompanying book).  I suggest starting there and refining your question as needed.
Comment: @Demetri, you are a PhD candidate, why are you assuming that what is simple for you would be simple for others? A little bit more insight would help. thanks.
Comment: This sounds like a simple time series problem.
Comment: Thanks, that's what I needed, a place to start
Comment: @Demetri All the time series examples that I see are based on a sequence of time/value pairs, but what I need is additional attributes/features related to each data point, can you be a little bit more specific? thanks
Comment: I'll post a more robust answer once I get home from the gym
Answer: There's very little use in ML if that's all you have on accounts. ML has a chance when you get a lot of features of individual accounts.
Otherwise, advanced time series analysis plus manual adjustments (using product managers' input and utlooks) will do the job. In any case, if your boss is pushing to do ML, make sure that you have a baseline forecast using time series methods to compare performance of ML models with. I bet that time series will beat ML every day.
Comment: I adjusted the question, the features mentioned were just examples. Let's say I have 30 features.
Comment: One issue to deal with is that historical data is on _existing_ customers, while you're trying to predict _new_ customers. When forecasting your goal is to find what's persistent. So, this set up makes it difficult. You must make assumption that new customers will react the same way like existing ones. However, what can be persistent is the bank's product management, it's priobably slowly changing over time. So you focus on this aspect. Incidentally, this points to importance of communcation with and input from product people
Answer: I can't offer more than Aksakal does in their answer.
Here are my three suggestions:
1. Time series methods
I've already suggested this in a comment.  I think this is a particularly good approach as compared to ML methods because

They are faster to iterate over (you can try many different approaches with time series quickly because they are easy to fit).
They offer estimates of uncertainty (so when you inevitably get the prediction wrong, you can see if the real number was within the prediction interval of the model).
A priori there should be no reason why the number of accounts which provide, for instance, overdraft protection, should influence the accrual of new clients.

For these reasons, I think it is sufficient to simply aggregate the number of new accounts created by month, and then create a time series model via forecast or similar methods.
2. Linear Regression
Linear regression may be one way forward of time series prove too difficult.  Simply aggregate how many accounts were opened last month to predict how many will open this month.  You can include features for month of year to capture seasonality, and year to capture trends.
You can count the number of accounts which have overdraft, etc., and use that as a feature.  Though I don't think including that information will be relevant, for reasons stated above.
3.  Machine Learning
See 2. but instead of doing linear regression, use any ML model you like.  If you do this, you lose the ability to make probabilistic statements about the outcome, which you may not care about.
That is really all I can say about your problem. There is no "best" ML approach for these types of things, and you certaintly won't need something like a LSTM NN.  Group your data by year-month, count the new accounts, and model as a function of whatever covariates you think are relevant.
Comment: I ended up using option #3 as there are features that I need to take into account. The "overdraft protection" it is just one example of many attributes that need to be included in the modeling. I used regression trees/random forests.
Comment: Demetri, thanks for taking the time. One last question about item 3 in point 1. What if the customer opens a new account _because_ it has overdraft protection? That's why I think that the model should somehow forecast accounts opened by feature.
Comment: That may well be the case, but I doubt that the number of accounts with overdraft presently open affects the number of accounts that will open with overdraft.  If your hypothesis is contrary to this (and its fine to make that hypothesis, I just don't think it is a reasonable one), then use one of options 2 or 3.


Does CentOS 5.4 properly handle leap seconds?

Question: Apparently the IERS have announced a leap second due at midnight, June 30th this year.
Is CentOS/RHEL 5.4 properly updated to support/transition along with updated NTP systems? I was under the impression that it would need an updated tzdata package but wasn't sure.
UPDATE:
I checked the change-log for the tzdata package and noticed the following:
* Tue Feb 27 2007 Petr Machata <firstname.lastname@example.com> - 2007c-1
- Upstream 2007c
  - Pulaski County, Indiana, switched back to eastern time.
  - Turkey switches at 01:00 standard time, not at 01:00 UTC.
- Upstream 2007b
  - Changes to the commentary in "leapseconds".
- Resolves: #230089

* Tue Aug 22 2006 Petr Machata <firstname.lastname@example.com> - 2006j-1
- Upstream 2006j
  - Honduras stopped observing DST on Monday at 00:00
  - America/Bermuda will follow the US's lead next year
  - America/Moncton will use US-style rules next year
  - New Zone America/Blanc-Sablon, for Canadians who observe AST all
    year
  - New zone: America/Atikokan instead of America/Coral_Harbour
  - New zones: Europe/Jersey, Europe/Guernsey, Europe/Isle_of_Man
  - Historical changes
  - Commentary updates
- Upstream 2006i
  - localtime.c fixes
- Upstream 2006h
  - zic leapsecond fix

Is the "zic leapsecond fix" related?
Answer: You can verify that a given leap second update has been applied using the zdump command.  On CentOS this is
/usr/sbin/zdump -v right/UTC

You're looking for a line similar to:
right/UTC  Sat Jun 30 23:59:60 2012 UTC = Sat Jun 30 23:59:60 2012 UTC isdst=0 gmtoff=0

This should be mentioned in the changelog for the tzdata package:
rpm -q --changelog tzdata | less

On a poorly-patched CentOS 5.7 box, I'm not finding this update.  On current Ubuntu 11.10 and Debian squeeze boxes, I'm finding it.  YMMV.
For more on this (from a Debian PoV but it should largely apply to CentOS):  http://lists.debian.org/debian-user/2005/12/msg03343.html
Comment: Interesting.  So I don't see the line in zdump output but the change log does include references to "changes in commentary in 'leapseconds'" and a "zic leapsecond fix"
Answer: As long as you have updated your system, it should be fine. Also, NTP should ensure that everything's under control.
Answer: Your question is answered in the Red Hat knowledge base:
https://access.redhat.com/knowledge/articles/15145
Synopsis:
There is a known potential problem for some versions of RHEL 4 and 5 which may cause the kernel to crash at midnight for systems which are also running NTP.  If you are patched higher than 5.4 and 4.8 you should be ok (assuming all appropriate related files are patched correctly).  Alternatively you can choose to not run NTP however you will need to be sure you have the tzdata data file updated to the appropriate level.
Bottom line if you are on a fully updated system you should not have any issues.
Further information is available in Red Hat Bugzilla:
https://bugzilla.redhat.com/show_bug.cgi?id=479765
Answer: You won't see the 2012 leap second in the timezone files unless you've installed the RHEL / CentOS errata package "tzdata-2011n-2" or later, released in March 2012. Older packages don't know about it because leap seconds are only announced with 6 months' notice. Further, to use these updated files your boxes must be configured to use a "right" timezone, e.g. "right/America/New_York".
If your systems are running ntpd and your NTP upstream servers support leap second pre-announcements then ntpd will instruct the kernel to jump a second at the appropriate time. Any applications using libc gettimeofday() will see 23:59:59.XXX UTC repeated twice.
Upstream NTP servers will only start announcing the "leap indicator" after 2012-06-30 00:00:00 UTC, as the protocol doesn't allow for any more notice. If the upstream reference clocks are leapsecond-aware (e.g. GPS), ntpd should correctly cascade the leap indicator to all hosts. If the upstream references are not leapsecond aware (e.g. some pulse-per-second radio clocks), and the stratum 1 ntpd operator has not configured a "leapseconds" file. If you have a mixture of reference clocks, any one of them can provide the leap indicator.
Comment: Sorry, but I'm getting confused.  What will happen if I am running ntpd on a server, don't have the installed tzdata-2011n-2 package or later, and the NTP upstream servers support leap second pre-announcements?  Will this cause issues? Or will it just be ignored?
Comment: In the scenario you describe, the system clock will repeat 23:59:59.XXX. Whether this causes issues depends on whether you have any applications which rely on smooth, continuous, non-stepping clocks. Probably not though.
Comment: How does one know if the upstream server supports leap second announcements ?
Comment: The only sure way is to check for the leap indicator within 24 hours of a leap second. As above, it depends on the ultimate clock source e.g. GPS, radio etc.
Answer: If you're hit with the leap second bug and experience high load on your servers just stop ntp and set time with ntpdate see here


How to search a database with the name of a var

Question: So, I have this code right here, and all it does is error a... 404???? (Just a glitch, but still. Using remote HTTP access it does not work. It should)

<code>// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO $user(Username, Password, Membership)
VALUES ($usn, $psw, $membership)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>
Comment: A 404 comes from the server, not your PHP code (well, unless you're sending out headers, which you clearly aren't)
Comment: Yes, but it is a random error. But I still can't get this code to work on the 404 bypass (Http service)
Answer: Why wouldn't you try:
<code>$sql = "INSERT INTO " . $user . "(Username, Password, Membership) VALUES (" . $usn . "," . $psw . "," . $membership. ")"
</code>
Comment: A 404 error is the webserver saying that the file isn't there. I don't think this is being caused by the PHP code, as apparently the webserver can't even find the file to run it.
Comment: That's functionally identical to what's already there, though.
Comment: So you still say the problem might be the variables?
Answer: You probably meant to write either:
<code>$sql = "INSERT INTO ".$user."(Username, Password, Membership)
VALUES
('".$usn."', '".$psw."', '".$membership."')";
</code>
or
<code>$sql = "INSERT INTO user(Username, Password, Membership)
VALUES
('".$usn."', '".$psw."', '".$membership."')";
</code>
Escaping your input and adding a real_escape_string() call would be even better.
So I would write it in a way that the values are escaped as strings and the query handles them as strings:
<code>$sql = "INSERT INTO user(Username, Password, Membership)
    VALUES
    ('".$conn->real_escape_string($usn)."',
     '".$conn->real_escape_string($psw)."',
     '".$conn->real_escape_string($membership)."'
    )";
</code>
I hope that helped at least a little.


Information about widget context/lifecycle

Question: I've a widget that is packaged in an application and I've several doubts about the context/lifecycle of the widget/application:

The application and widget share the same process, and consecuently singletons?
If I've services they have to be remote ones?
What's the lifecycle of the process that updates the widget? Is only for the widget?

In general any information about the widget lifecycle/context would be very apreciated
Comment: isn't this http://developer.android.com/guide/topics/appwidgets/index.html enough?
Comment: No, I had read it and I'm not able to answer to my questions with that information
Answer:
The application and widget share the same process

If you look at your code, you will find a class that extends AppWidgetProvider, in all likelihood. This is the code that updates the home screen UI for the portion of it taken up by your app widget.
If you look at your manifest, you will see that you added your AppWidgetProvider as a <receiver>. This indicates that AppWidgetProvider is a BroadcastReceiver. Manifest-registered BroadcastReceivers live for a very short time -- long enough to process onReceive(), and that's about it.
Hence, it is possible that "the application and widget share the same process" momentarily, insofar as if you already have a process (e.g., the user is inside one of your activities right now), and onUpdate() of your AppWidgetProvider is triggered, then the AppWidgetProvider will be in that same process. However, if your application is not running, then onUpdate() for your AppWidgetProvider will run in some process, which may or may not have hosted any of your code before.

and consecuently singletons?

You should not rely upon this.

If I've services they have to be remote ones?

Absolutely not, for any definition of "remote".

What's the lifecycle of the process that updates the widget? Is only for the widget?

See above.
Comment: I understand that I haven't to use remote services because it's guaranted that if in some moment the application and the WidgetProvider are running at the same time they will be sharing the process?
Comment: @lujop: Yes. That being said, you cannot know ahead of time if your `AppWidgetProvider` is running in the same process with anything else. That is one of a few reasons why `AppWidgetProvider` should use `startService()` to communicate with services.


How to remove event listeners attached with onclick

Question: I need a way to remove event listeners attached with onclick="func()" in javascript
below is sample code

<!DOCTYPE html>

  <button id="b1" type="button" onclick="f1()">B1</button>
  <button id="b2" type="button" onclick="f2()">B2</button>

Answer: Add another blank listener to it as
document.getElementById("b1").onclick = function() {
     return false;
   }

Answer: You just set the onclick property of the element to null.

<!DOCTYPE html>

  <button id="b1" type="button" onclick="f1()">B1</button>
  <button id="b2" type="button" onclick="f2()">B2</button>

This is because when you do onclick="f1()", the browser creates a new function for you, somewhat (but not entirely) equivalent to this:
elem.onclick = new Function("event", "f1()")

Which gives you a function, something like this:
elem.onclick = function(event) {
  f1()
}

So setting that property to null simply overwrites the assigned function, setting it back to its default value.
Answer: You can change it:
document.getElementById("b1").removeEventListener("click",f1);

for it:
document.getElementById("b1").onclick = null;

<!DOCTYPE html>

  <button id="b1" type="button" onclick="f1()">B1</button>
  <button id="b2" type="button" onclick="f2()">B2</button>

Answer: Setting the onclick to null works fine, but you might notice if you inspect the DOM your onclick is still there.
So another way is to use removeAttribute
eg.

<!DOCTYPE html>

  <button id="b1" type="button" onclick="f1()">B1</button>
  <button id="b2" type="button" onclick="f2()">B2</button>


Novos tipos do PHP: qual a vantagem de usar o tipo de retorno void e qual a diferença com o tipo never introduzido recentemente?

Question: O ganho no uso de void como tipo de retorno de métodos/funções é apenas de legibilidade?
E o tipo never introduzido nas últimas versões (mais especificamente na versão 8.1) do PHP é semelhante ao void? Quais os contextos de seu uso?
Answer: Já respondi sobre a vantagem de usar a tipagem declarada de tipos em funções aqui e aqui. O ganho é principalmente em robustez. Quem sabe um dia o JITter possa dar algum ganho de performance em algumas situações quando há o tipo explícito.
Ter o tipo declarado e documentado pode melhorar a facilidade de entender o que a função exerce e o que se espera fazer com ela, então pode facilitar um pouco o uso do recurso. O código em si não chega ficar mais legível por causa disso, mas a documentação fica, se é que podemos usar esse termo.
void
void é um tipo, pelo menos na maioria das linguagens, que indica que não deve ter nada ali, nem mesmo um valor nulo para indicar invalidade. Ele é muito usado em tipos de retorno de funções.
Em geral, em muitas linguagens, ele impede de usar o resultado da função em uma expressão, você não poderia nem chamar em um echo por exemplo, mas não em PHP que é aceito e funciona normalmente, não podendo valer alguma coisa dependendo do contexto, até pode ser usado como se fosse um 0.
Então a vantagem dele, além da geral já citada acima, é que no return ele dará errado se tentar colocar alguma coisa. Não é uma ótima vantagem, mas ajuda.
function funcao(): void {
    return 1; // dá erro
}

never
Já o never só deve ser usado em uma função que nunca retorna, ou seja, ela nunca terminará de executar, é uma função de fim de execução do script. Raramente ele é útil, mas é interessante informar quando a função tem essa característica de matar a execução em algum momento dela e que nada depois dali será executado. Funções assim só devem ser chamadas no fim do script ou condicionalmente, se fizer sentido. Se a função tiver esse tipo de retorno declarado não pode ter um return dentro da função, nem mesmo implicitamente poderá ter um.
function funcao(): never {
    exit();
    return 'fim'; // dá erro
}

Mas também dá erro porque há um return implícito no fim da função:
function funcao(): never {
    if (false) exit();
}

Coloquei no GitHub para referência futura.
Uma exceção também pode ser usada para encerrar a função sem um return.
Então com eles o código fica mais robusto e documenta melhor a intenção.


JAVA: Need help fixing my movie ticket program for class

Question: I am creating a movie ticket program for a class assignment and am having some trouble getting a few things to work.

I can't figure out how I am going to calculate the total cost of the tickets the user wants because I don't know how to tell the program to use a different formula for matinee vs evening tickets?
I also need to find a way to not allow the user to buy tickets for children if the movie is rated R?

My code is below...
/**
 * @param args
 */
public static void main(String[] args)
{
    //initializes variables for the various costs of each ticket
    double adultMatCost = 7.50;
    double adultEveCost = 9.50;
    double childMatCost = 7.00;
    double childEveCost = 7.00;
    double seniorMatCost = 5.00;
    double seniorEveCost = 7.00;

    //introduces the user to the program, creates scanner for program,
    //and asks user to enter their name
    Scanner scan = new Scanner(System.in);
    System.out.println("Welcome to the J-Town Theater.");
    System.out.print("Please enter a name for our transaction records:");
    String name = scan.next();

    //thanks user and asks user which movie they would like to choose
    //assigns a String movie is assigned text based on what the user chose
    //if user enters a value other than 1 or 2 the program terminates gracefully
    System.out.println("Thank you, " + name);
    System.out.println("Which movie would you like to see?");
    System.out.println("[1] My Little Pony (PG)");
    System.out.println("[2] Blade Runner 2049 (R)");
    System.out.print("Enter movie choice: ");
    int movieChoice = scan.nextInt();
    String movie = "";
        if (movieChoice == 1){
            movie = ("My Little Pony");
        }
        else if (movieChoice == 2){
            movie = ("Blade Runner 2049");
        }
        else{
            System.out.println("I'm sorry, " + name + ", but that is an invalid choice");
            System.out.println("Goodbye.");
            return;
        }

    //asks user what time they want to see the movie
    //user enters M/m for Matinee and E/e for evening
    //if user enters something besides M/m/E/e the program terminates gracefully
    System.out.println("What time of day would you like?");
    System.out.println("[M] Matinee");
    System.out.println("[E] Evening");
    System.out.print("Enter movie time:");
    String timeDay = scan.next();
    double totalCost = 0;
    String timeDayResult = "";
    double timeDayME = 0;
        if (timeDay.equals("m")){
            timeDayResult = ("Matinee showing");
        }
        else if (timeDay.equals("M")){
            timeDayResult = ("Matinee showing");
        }
        else if (timeDay.equals("e")){
            timeDayResult = ("Evening showing");
        }
        else if (timeDay.equals("E")){
            timeDayResult = ("Evening showing");
        }
        else{
            System.out.println("I'm sorry, " + name + ", but that is an invalid choice.");
            System.out.println("Goodbye.");
            return;
        }

    //asks how many tickets they would like and shows the price for each ticket
    //user enters number between 0 and 10 if they enter something besides that
    //the program will terminate gracefully
    //if the movie chosen was rated R no tickets can be sold to children
    System.out.println("How many tickets would you like?");
    System.out.println("Child : $7.00");
    System.out.println("Adult : $7.50");
    System.out.println("Senior: $5.00");
    System.out.print("Enter number of children (0-10):");
    int ticketsChild = scan.nextInt();
        if (ticketsChild >= 0){
            int ticketsChildTotal = ticketsChild;
        }
        if (ticketsChild <= 10){
            int ticketsChildTotal = ticketsChild;
        }
        else{
            System.out.println("I'm sorry, " + name + ", but that is an invalid choice.");
            System.out.println("Goodbye.");
            return;
        }
    System.out.print("Enter number of adults (0-10):");
    int ticketsAdult = scan.nextInt();
        if (ticketsAdult >= 0){
            int ticketsAdultTotal = ticketsAdult;
        }
        if (ticketsAdult <= 10){
            int ticketsAdultTotal = ticketsAdult;
        }
        else{
            System.out.println("I'm sorry, " + name + ", but that is an invalid choice.");
            System.out.println("Goodbye.");
            return;
        }
    System.out.print("Enter number of seniors (0-10):");
    int ticketsSenior = scan.nextInt();
        if (ticketsSenior >= 0){
            int ticketsSeniorTotal = ticketsSenior;
        }
        if (ticketsSenior <= 10){
            int ticketsSeniorTotal = ticketsSenior;
        }
        else{
            System.out.println("I'm sorry, " + name + ", but that is an invalid choice.");
            System.out.println("Goodbye.");
            return;
        }

    //gives a transaction summary for the user showing what movie they want,
    //what time they want, and how many tickets they want total,
    //then the program calculates the total ticket price
    System.out.println("Thank you, Penolope, here is a record of your purchase.");
    int totalTickets = ticketsSenior + ticketsAdult + ticketsChild;
    System.out.println(movie + " (" + timeDayResult + "): " + totalTickets + " tickets total");
    System.out.println("Children: " + ticketsChild);
    System.out.println("Adults: " + ticketsAdult);
    System.out.println("Seniors: " + ticketsSenior);

    double totalMatineeCost = (childMatCost * ticketsChild) + (adultMatCost * ticketsAdult) + (seniorMatCost + ticketsSenior);
    double totalEveningCost = (childMatCost * ticketsChild) + (adultMatCost * ticketsAdult) + (seniorMatCost + ticketsSenior);

    System.out.println("Total cost: $" + totalCost);

}

}
Comment: I have downvoted this question because there is no evidence of any debugging performed on this code.  Please [edit] your question to show us what your debugging has uncovered, as well as a specific question about an actual line of code.  See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and [How to Debug Small Programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/).
Answer:
I can't figure out how I am going to calculate the total cost of the tickets the user wants because I don't know how to tell the program to use a different formula for matinee vs evening tickets?

You already have the costs calculated in two separate variables, so just use a condition to pick which one you need based on the user input.
if("Matinee showing".equals(timeDayResult)){
    totalCost = totalMatineeCost;
}else{
    totalCost = totalEveningCost;
}

I also need to find a way to not allow the user to buy tickets for children if the movie is rated R?

Again, use a condition before you ask for the number of children. Something like:
if(movieChoice == 2){
    //Set number of child tickets to 0, perhaps inform user they are not allowed to buy child tickets since movie is rated R
}else{
    //ask the user for number of child tickets
}

A few final thoughts - you have several bugs in your program. I noticed these, but there are probably more:

The calculations for total cost are wrong.
The logic that is validating your user input is wrong.

Make sure you thoroughly test your code.


Where do I put the Houzz Badge code?

Question: I'd like to add a Best of Houzz badge on our site.  I have the code, but don't know where to put it.
Is it Admin --> structure --> ... then what?
Since the site was built by someone else and now I'm maintaining it, I really don' want to mess anything up by poking around and "experimenting."
Answer: Go to: YOUR_SITE/admin/structure/block/add and fill the info like this:

In Block body field you must put the code of the badge and go to the bottom of the page to Save block.
Then in the YOUR_SITE/admin/structure/block page search your block, in this case the name is "Best of Houzz badge" then select the region where the block will be displayed (in this case Sidebar first)

Go to the bottom of the page and click in the Save blocks button.
And you will see the block in your site.
Comment: thank you so much.  I'll check that out.  Have a great day!
Comment: @Caynine A pleasure, let me know the result ;-)
Comment: @Caynine If my answer help you consider accept it as correct, if you don't know how you can read this http://drupal.stackexchange.com/tour

Where do I put the Houzz Badge code?


How in Object Pascal find whether a character is alphanumeric or underscore working in both Delphi compiler and FPC?

Question: There are similar or same questions all over the internet, but the answers don't work for me. We develop multiplatform product, which is compiled both under Delphi's compiler and under FPC.
First, I used:
Uses:
  System.Character;

and
Character.TCharacter.IsLetterOrDigit(..)

, but it couldn't be compiled under FPC, so according to some other source, I used:
Uses:
  Character;

and
TCharacter.IsLetterOrDigit(..)

instead, but still can't be compiled under FPC.
Can someone find a way that the code will work on both Delphi compiler and FPC? I don't have FPC set up to work with my project, so I can't figure out on my own, how to fix the code to work in FPC (I can test it only in complicated way via build server) and can't find a way, how to do it.
I also wanted to write it using regex, but colleagues say, that it would be too complicated for them.
Comment: I would make my own function in separate unit and use `{$IFDEF FPC}` to branch between Delphi and FPC implementation.
Comment: Yes, I would use something like if ( in ['0'..'9', 'a'..'z', 'A'..'Z', '_']), but colleagues say, that there must be some function that does it more neatly (and can be reusable on more places). I care only about the ASCII btw. And I don't want to create a new function, because I really think that it's already written.
Comment: You didn't understand what Victoria said. Your new function doesn't do the grunk work. It just calls the library methods of Delphi and FPC, conditionally. In doing so it presents a platform independent interface.
Comment: Aha, sry, ok, I can conditionally do it also outside new function, but I don't know how to correctly call in from FPC, because the compilation always fails.
Comment: Anyway, you don't need to do it conditionally at all. You can use `TCharacter.IsLetterOrDigit` in both. Now some harsh advice. Don't ever ask about errors without giving the details of the error. "can't be compiled" is really no help to anybody. Perhaps you don't read error messages, but we do. And if you don't, you need to learn how to read them right away.
Comment: Please name versions(My Delphi doesn't have an unit character.) and what exactly goes wrong.
Comment: Ok, I just set up FPC anyway to try it and following code worked, so I guess that our buildservers have some strange configuration:
Program test;
uses Character;
var
text: ansiString;
begin
  text := 'whatever';
  TCharacter.IsLetterOrDigit(text), 1);
end.
Comment: Any time something *"can't be compiled"*, please, please include the error messages.
Comment: @Marco: which Delphi is that? AFAICT, XE2 up to Tokyo have a unit `Character` or `System.Character`. The class is `TCharacter`. It only has class methods. The unit also contains a number of global functions. The FPC version I use (3.0) also has such a unit, which looks very much the same.
Comment: @Rudy, [that's what came to mind immediately](https://www.youtube.com/watch?v=YlRLfbONYgM&feature=youtu.be&t=1m11s) :)
Comment: @Victoria: I'm afraid I don't get it.
Comment: @Rudy, I think that EMBT could "borrow" something from FPC as well in time ([quid pro quo](https://en.wikipedia.org/wiki/Quid_pro_quo)). And you're a doctor :)
Comment: Sry to all, because it always worked on my PC, but didn't work on our buildserver and I don't know, how is it run on it.
Comment: Well, this was D7, something a customer uses to keep his HMI's running. The Delphi version is also important for things like System.Character and just Character (XE2 introduced that?), so D2009,2010 and XE have just character too.
Answer: Both Delphi and FPC include a class named TCharacter which exposes a method named IsLetterOrDigit. In other words, the premise of your question is wrong. It is perfectly reasonable to use TCharacter.IsLetterOrDigit.
Documentation links:

Delphi: http://docwiki.embarcadero.com/Libraries/en/System.Character.TCharacter
FPC: https://www.freepascal.org/docs-html/3.0.0/rtl/character/tcharacter.html

It's entirely possible that you are using an out of date version of FPC, which would explain why your code fails. Although that is guesswork since you did not include any details of the error message.
Comment: @RudyVelthuis In the end, I used "CharInSet(, ['0'..'9', 'a'..'z', 'A'..'Z', '_'])" and it works well and without warnings/hints.
Comment: I realized, that our buildservers have some strange configuration and I did it different way, like  in ['0'..'9', 'a'..'z', 'A'..'Z', '_'], because my colleagues don't want to use TCharacter anyway and this is lesser evil. Thanks.
Comment: The `in ['0'..'9', 'a'..'z', 'A'..'Z', '_']` expression will not work properly in Delphi, as in Delphi, Char is mapped to WideChar, and sets can only contain 0..255 values, hence no WideChars. Use `TCharacter` instead, no matter if your colleagues, for some unknown reason, don't want to use it.
Comment: FWIW, `Tcharacter ... deprecated 'Use TCharHelper';` in XE7 help, did not check earlier.
Comment: @TomBrunberg: it may be deprecated, but it still works, and TCharHelper probably won't work in FPC.
Comment: FPC trunk supports value type helpers. Maybe even 3.0 does.HelperBut the RTL support usually lags


JFreeChart array as dataset

Question: I am using JFreeChart to plot a line graph. I would like to load arrays as the data set... one array for the x-axis and another array for the y-axis.
I am having a problem when trying to pass the array as the data to use in the dataset.
The following is what I've tried;
public DefaultCategoryDataset createDataset(int[] epochNo, int[] BFacts)
{

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i<epochNo.length(); i++)
    {
        dataset.addValue(epochNo[i], BFacts[i]);
    }
    return dataset;
}

Thanks in advance!
Comment: What is the problem you're referring to?
Answer: There are two solutions; with a normal line chart, you use a DefaultCategoryDataset. The addValue method has three arguments, the second being the name of the dataset. And the third is the column label:
dataset.addValue(BFacts[i], "myline", String.valueOf(epochNo[i]));

There other solution is to see this as an XY line chart (using ChartFactory.createXYLineChart). In that case your dataset is an XYDataset instead of a CategoryDataset:
private XYDataset createDataset(int[] epochNo, int[] bFacts) {
    final XYSeries myline = new XYSeries( "myline" );
    for (int i = 0; i < epochNo.length; i++) {
        myline.add(epochNo[i], bFacts[i]);
    }
    final XYSeriesCollection dataset = new XYSeriesCollection( );
    dataset.addSeries(myline);
    return dataset;
}

See more in this example
Comment: Thanks for your answer. I just cannot understand how the structure of the project could be ... at the moment this is what I have ;
Comment: public class MyClass extends JFrame
    {
    public static void main (String [] args)
    {

    //train the neural network and fill chartEpoch & chartBFacts
    //When trained do the chart i.e. Chart(chartEpoch, chartBFacts);

    }
    }

    //method to create chart
    //method to create Dataset

JFreeChart array as dataset


Difference between 2 methods of adding a CSS files in theme.info?

Question: What is the different between these 2 methods of loading a CSS files?
<code>; Method 1
css[typography.css][name] = Typography
css[typography.css][description] = Typography
css[typography.css][options][weight] = 99

; Method 2
stylesheets[all][] = css/typography.css
</code>
Method 1 means the CSS file is loaded further down the page head, which I need for my theme. However from looking at the documentation it seems Method 2 is more standard?
Answer: Method 2 is provided by core (probably why it seems more standard, it'll be used more often).
Method 1 is something specifically provided by the Omega theme.
I think the only reason to use Method 1 is if you want to be able to control the use of the stylesheet through the optional stylesheets setting in the UI.


Cardinality of the set of all functions with finite support

Question: Let F be a countable field and B an infinite set. Let $(F^B)_0$ be the set of all functions with finite support from F to B. Is it true that $|(F^B)_0|=|B|$?
Answer: Assuming the axiom of choice, yes.
To see this note that there is an injection from $B$ into $(F^B)_0$ in the obvious way; in the other direction $(F^B)_0$ is a subset (or rather, can be identified with a subset) of $(B\times F)^{<\omega}$, the set of all finite sequences from $B\times F$.
The cardinality of $(B\times F)^{<\omega}$ is $\sum_{n\in\Bbb N}|B\times F|=|B|\cdot|F|\cdot\aleph_0$, but since $B$ is infinite, you get that this just equals $|B|$.
Comment: Asaf , I think that you use $|B\times F|^n=|B\times F|$.
Comment: Yes, that is correct.
Comment: @AsafKaragila doesn't this prove that for $X,Y$ with $|X|\geq |Y|\geq 2$ and $X$ infinite, $|(Y^X)_0|=|X|$?
Comment: @Exterior: What if $X=\Bbb N$ and $Y=\Bbb R$?
Comment: @AsafKaragila I see. Could you explain the cardinality argument in [this question](https://mathoverflow.net/questions/13322/slick-proof-a-vector-space-has-the-same-dimension-as-its-dual-if-and-only-if-i)?
Comment: @Exterior: Try http://math.stackexchange.com/questions/58548/why-are-vector-spaces-not-isomorphic-to-their-duals for starters.
Comment: @AsafKaragila so we generally have $|M^\ast|=|k|^{\dim V}$, and in the infinite dimensional case we have $|V|=\max (|k|,\dim V)$. I am still confused at why we may conclude $\operatorname{card}V <\operatorname{card}V^\ast$ if we merely assume $\dim V \geq |k|$. If the assumption is actually a strict inequality, then I don't understand how knowing every field has a countable subfield helps.
Comment: @Exterior: It seems to me that you are asking a question which deserves a proper answer, and not in the comments. And since I'm going to bed, I will now leave you in the capable hands of the rest of the site. But you should write a question where you give a correct context (because frankly, I'm still not entirely sure what you're trying to understand *exactly*), and explain what step you seem to be missing out on. And if you can do that, you'll surely receive a good answer from one person or another.
Comment: @AsafKaragila thanks. I asked my question [here](https://math.stackexchange.com/questions/1534223/trying-to-understand-the-slick-proof-about-the-dual-space).


When typing the URL to my website, it adds words to the end

Question: I have a problem which I tried Googling for solutions but couldn't find it. When I type a URL of my website's page or visit it from a bookmark, it adds words at the end of the URL, leading to a 404 error.
So I have this URL:
https://www.mywebsite.com/whmcs/admin/
When I type the URL or visit it from a bookmark, it returns this:
https://www.mywebsite.com/whmcs/admin/whmcs/admin/
This is a WordPress website. What could be the problem? Thanks in advance.
# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]

    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1
</IfModule>
# END WordPress

Comment: Post your .htaccess file.
Comment: looks like a url rewrite rule that uses the wrong rewrite base perhaps
Comment: `# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1

# END WordPress`
Comment: Sorry I'm new to Stack Overflow. How do I add a line break to code? I tried the two spaces at the end of the line and it doesn't work.
Comment: is there another `.htaccess` within the admin directory or is this it?
Comment: There no other .htaccess except for one in a directory which is a PHP script and is not related to WordPress. Could it be the culprit?
Comment: it's unlikely that this other `.htaccess` file is to blame then. I don't know anything about wordpress but if the htaccess file is not blame and this is the default htaccess file then it must be some setting with some config file but I can't guide you - sorry.
Comment: I think I have a clue. When I use http:// instead of https:// it sometimes give the error I mentioned. So could it be the SSL that has the problem?
Answer: There should be a line-break between RewriteEngine and RewriteBase
RewriteEngine On
RewriteBase /

Comment: Still doesn't work. This error happens whether I add a slash at the end or not.


How do I use a sub-string of a field?

Question: How do I convert SELECT title , SUBSTRING(title,13,4) as num FROM node_field_data ORDER BY ABS(num) to the format for Drupal 8?
I tried this code.
 $query = $db->select('node_field_data', 'nfd')
  ->extend('\Drupal\Core\Database\Query\TableSortExtender')
  ->extend('\Drupal\Core\Database\Query\PagerSelectExtender');
  $query->limit('50');
  $query->fields('nfd',array('title',substring(title,13,4) as num,'changed','nid'));
 ->orderBy('num', 'ASC')

Answer: You need to add an expression with SelectInterface::addExpression:
$query = $db->select('node_field_data', 'nfd')
  ->fields('nfd', ['title'])
  ->extend(\Drupal\Core\Database\Query\TableSortExtender::class)
  ->extend(\Drupal\Core\Database\Query\PagerSelectExtender::class);

$expr_alias = $query->addExpression('SUBSTRING(title, 13, 4)', 'num');

$query->orderBy($expr_alias, 'ASC')->limit('50');

How do I use a sub-string of a field?


Which wind instruments are a problem with braces?

Question: Which wind instruments are a problem with braces?  Please make a list showing the relative difficulties.

Clarification: I am also interested in what most people would consider minor inconveniences.  My 12yo has Tourette Syndrome and some sensory issues which set off some Tourette symptoms.  He has a mild orthodontic problem, and my bank account has a major problem (older son in college).  There are so many factors to consider when helping this child choose next year's band instrument, and deciding whether and when to get braces.
Additional background info: He likes the idea of braces in theory; he hasn't met an instrument he didn't want to play, and he picks them up quickly and does very well with all instruments he chooses to study.  He has a natural affinity for jazz, but likes all styles of music.
Wind instruments played so far: 4th grade, trombone; 5th grade, bassoon; 6th grade, bari, sax and halfway through, added tenor sax.  He doesn't want to go back to bassoon, but he still picks up his trombone sometimes, and he is undecided about continuing with bari/tenor.
So, I want to understand better how braces impact the playing of a wind instrument.
Answer: Speaking purely from personal experience, braces are an annoyance but not a problem.  I played the clarinet thru 3 years' worth of old-fashioned metal-band&wire braces, with some lip shredding, some applications of dental wax, and so on.  Abrasion on internal (mouth) surfaces is likely with any  instrument.
In the woodwind family,  since only single-reeds require direct tooth pressure on the mouthpiece/reed,  flautists and double-reed players will not have to deal with tooth pain related to each tightening/adjustment of the braces.  Obviously you can't play with external headgear but AFAIK those are almost never used any more.
Brass instrument players will find it quite advisable to cover the front teeth's braces with wax or some such to preserve their lips.  This is highly personal and only experimentation will tell you what your best approach is.
I would recommend removing retainers,  invisalign, and the like while playing any wind instrument because   these items change the air cavity inside your mouth,  and that isn't good :-) .
Comment: As a trumpet player, I had the somewhat unique experience of letting my embrochure atrophy, then getting braces, then trying to play again after getting the braces off again.  I think I tried to play WITH braces exactly twice, and it was so unnatural-feeling that I couldn't get a satisfactory embrochure at all.  It is like starting from scratch.  When I got the braces off and started to play again, it was much worse than before getting them on (even with the atrophied embrochure at the time).  After playing 2yr free, I feel 3 years behind where I was when I stopped playing in the first place.
Comment: To elaborate, the *mental* aspect of playing is tied very intricately with the physical aspect, and if you have highly developed neuromuscular structures in place already then braces will basically move them around to all the wrong places.  What were once good habits are now bad habits, and the new good habits feel like what was once bad.  As others have said, many people improve long-term after braces, so it's probably a matter of what your level is beforehand (I was already semi-professional) and what structures and habits you already had.
Comment: @AsianSquirrel there is no space in the percussion section at his school.  The teacher won't let him switch to percussion.
Comment: I'm wondering, for example, whether single reed woodwind is commonly be less vulnerable than brass to the effect of getting braces.
Comment: @aparente001 I think so, but I can ask a few clarinet and sax friends today at school to make sure. Percussion is a safe bet for sure though; I'm not a true  percussionist, but I taught myself drum set for fun and my playing wasn't affected at all by my braces. :)
Answer: Just some supplementary comments: The effects of braces on playing vary from person to person, based on how they play, their facial structure, and how much they're willing to work to adjust to braces and then readjust after they get them off.
I play the French horn and I was totally fine until I got braces in seventh grade. Now, at the tail end of my senior year, I'm still working on correcting bad habits I picked up while trying to figure out how to play with braces, and it is very frustrating. I highly recommend having a private lesson teacher supervise and guide any wind players who get braces. I take private lessons from an incredible instructor and he has been able to help many other people to continue to play and to play well, with and without braces.
Additionally, when I was in middle school, there was a trumpet player whose playing actually improved drastically after he got braces.
It really all depends on the person.
Also, I think there are now different kinds of braces. One option might be the type that affix to the back of the teeth. For brassplayers, the main issue is usually the protrusion of the braces on the front top teeth. However, if there is something attached to the back of one's teeth, one's articulation (tonguing)  could be affected. Again, I highly recommend consulting (and signing up with) a private instructor if at all possible. Contact a local school that has a band program, or any local band or full orchestra organizations in your area for recommendations. (It's very important to find a good teacher.)
Comment: My wallet can't handle more private lessons right now.  This kid is a dancer, violist and pianist, and it gets expensive!
Comment: @aparente001 Just a side note, at some point it can be good to focus on one or two hobbies max, and really try to get into the depth of that art, as opposed to just touching the surface of many different areas. During my childhood I always had around 5 regular activities in addition to school and family. Now I have two (one sports, one music) and I find it much more satisfying, as the practice time I spend on both allows me to be much better than I ever was before.
Comment: @RafaelCichocki there is something in what you say!  Our music room currently has a hand-me-down drum set, a trombone, a bari sax, a tenor sax, a piano, a viola, a practice pad, and a djembe.  I sometimes feel like Superman's mother.  This kid really thrives on new things.  See my self-answer about the sax family solution.
Comment: All the answers provided were helpful.  "For brassplayers, the main issue is usually the protrusion of the braces on the front top teeth" was one of the most helpful sentences."
Answer: Today I was able to meet with my son's band teacher.  He said that with a single reed instrument, one can buy a special foam thing to cover the lower braces, and that by playing every day for about 10 days, one will adjust pretty quickly to having the braces.  He said single reed would be easier than brass.  So we decided to stick with the sax family.
One nice thing about the sax family is that my son, who thrives on new challenges, will be able to add another member of the family when he feels that he needs a new challenge, but much of what he's already done will transfer over to the sibling.


Empty data returning from many to many relationship laravel 5

Question: I've two model called application and user.
Application
id | name
user
id | first name
application_user
id | application_id | user_id | comment| rating | like
Here is the model classes
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\ModelValidator;

class Application extends ModelValidator
{
    //
    protected $table = "application";

    public function user()
    {
        return $this->belongsToMany('App\User','application_user','application_id','user_id')->withPivot(['rating','like','comment'])->withTimestamps();
    }

    public function getComment()
    {
        $comments = array();

        foreach ($this->user as $user) {
            $comments[] = $user->comment;
        }

        return compact($comments);
    }
}

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;

class User extends ModelValidator implements AuthenticatableContract,CanResetPasswordContract
{
    use Authenticatable,CanResetPassword;

    protected $table = 'user';

    public function application()
    {
        return $this->belongsToMany('App\Application')->withPivot(['rating','like','comment'])->withTimestamps();
    }
}

But when i run the below code it prints empty array.
$apps = \App\Application::all();

        foreach ($apps as $app) {
            print_r($app->getComment());
        }

Why its returning empty array  ?
Thanks in advance
Comment: Hey Moin, can you explain me that any relationship is exists between application and user table? because i can't find user_id in application table or application_id in user table. it's return empty array because laravel not find any relationship between user and application table right
Comment: the relationship between application and user is many to many,thats why there is another table called application_user.you ill find the ids from that table
Answer: just change your relationship like
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\ModelValidator;

class Application extends ModelValidator
{
    //
    protected $table = "application";

    public function user()
    {
        return $this->hasMany('App\ApplicationUser','application_id','id')
               ->withPivot(['rating','like','comment'])->withTimestamps();
    }

}

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;

class User extends ModelValidator implements AuthenticatableContract,CanResetPasswordContract
{
    use Authenticatable,CanResetPassword;

    protected $table = 'user';

    public function application()
    {
        return $this->belongsToMany('App\Application')->withPivot(['rating','like','comment'])->withTimestamps();
    }
}

change your code like this.
foreach ($apps as $app) {
    print_r($app->user);
}

Now you get data from application_user table, you got empty result because of you trying to find a data into user table so for that you got empty result.
Comment: it does return some data but in my case i need the comments from the pivot table
Comment: it's working for me it's return data from application_user table


Existence of homomorphism from $GO(2n,\mathbb{C})$ to $\mathbb{C}^*$ that doesn't lose too much information

Question: L.S.,
Denote $GO(2n,\mathbb{C})$ the group of matrices that leave an inner product invariant up to a scalar. We have for all $A \in GO(2n,\mathbb{C}), v,w$ vectors, that: $\langle A(v),A(w)\rangle = \lambda_A \langle v,w \rangle$.
It is known that the function $f$ that maps $A$ to $\lambda_A$ is a homomorphism from $GO(2n,\mathbb{C})$ to $\mathbb{C}^*$. However I find it somewhat unfortunate that we lose too much information, since for instance $f(-I) = f(I)$. Is there maybe a way to construct a homomorphism from $GO(2n,\mathbb{C})$ to $\mathbb{C}^*$ that doesn't lose this particular information? So that we have $f(-A) \neq f(A)$ for all $A \in GO(2n,\mathbb{C})$? I already found out that we can factor $A$ as $A = ab$, with $b \in O(2n,\mathbb{C})$ and $a^2 = \lambda_AI$.
Many thanks!
Answer: If $n>1$, I don't think it is possible.
Denote $f:GO(2n,\mathbb{C})\rightarrow \mathbb{C}^*$ a group morphism. You might already know that $SO(2n,\mathbb{C})$ is a simple Lie group. In particular, $SO(2n,\mathbb{C})$ contains no non-trivial normal connected subgroups.
It means that $Ker(f)\cap SO(2n,\mathbb{C})$ is either $SO(2n,\mathbb{C})$ or discrete. If your group morphism $f$ were not $SO(2n,\mathbb{C})$ then $SO(2n,\mathbb{C})$ quotiented by a discrete subgroup would be isomorphic to a subgroup of $\mathbb{C}^*$ which is not possible if $n>1$ (for dimensional reason).
Hence a group morphism  $f:GO(2n,\mathbb{C})\rightarrow \mathbb{C}^*$ not only needs to trivialize $-I$ but also any element of $SO(2n,\mathbb{C})$.
Comment: @WillemBeek, you are welcome. What I mean about this... We are working with complex Lie groups, so the group morphism $f$ is smooth. Since the kernel is discrete,  differential at the identity has for kernel the tangent space of the kernel of $f$ which is trivial since the kernel is discrete. Hence $T_{1_G}f$ the differential of $f$ at the identity is injective but it implies that the Lie algebra of $SO(2n,\mathbb{C})$ is included in the Lie algebra of $\mathbb{C}^*$ which is $1$-dimensional over $\mathbb{C}$ ...
Comment: ...It implies that $SO(2n,\mathbb{C})$ is at most $1$-dimensional over $\mathbb{C}$ but its dimension is $\frac{(n-1)n}{2}$, so $n=1$.
Comment: Clément, such an argument was exactly what I was looking earlier for but couldn't find. I really appreciate you answer, thank you. Could you maybe specify just a little bit what you mean with ''If your group .. dimensional reason).''?
Comment: Once again, thank you very much.


How to unsubscribe from all repos within an organisation

Question: After you join an Organization on Github you automatically subscribed to all of its repos and you start getting all those updates you don't really want. To unsubscribe you need to go per repo and do it manually. Is it possible to unsubscribe from all repos within a particular Organisation at once?
Answer: You can unsubscribe from all repos or one by one under https://github.com/watching
Maybe not exactly the best way but I find it useful. Hope it helps!
Comment: There's a "Unwatch all" button there now.
Comment: You're a legend! Thanks :)
Answer: It should be possible since Jan. 2022, 6 years later.

Unwatch all repositories owned by a given user or organization

Users can now unsubscribe from all repositories owned by a given user or organization.
Navigate to github.com/watching to find a list of the repositories that you are subscribed to.
The Unwatch All button gives you the option to unsubscribe from all repositories, or just the ones that belong to a specific user or owner.
It will appear when you are watching all activity or custom notifications on over 10 repositories.

Clicking any of the dropdown options opens a modal to confirm unwatching repositories owned by the selected user/organization (or all repositories).

You can read more about how to unwatch a single or multiple repositories in the 'Managing your subscriptions' documentation
Answer:
Is it possible to unsubscribe from all repos within a particular Organisation at once?

I don't know about unsubscribing, but you can go to Settings->Notification Center->Notification email and change the custom routing for the organization in question. That'll cause all e-mail for repositories in that organization to be sent to the new (possibly invalid) address.
Comment: while it's not really what I wanted, but at least it helped me to eliminate all those emails to my home address.
Comment: You can also turn off Automatic Watching, so that you don't receive messages for any repos that you haven't specifically watched. But then you have to go and watch all the repos for which you *do* want messages, which is the same problem in reverse.
Answer: The below script helps to easily customize, add exceptions, etc.
# Make sure the personal access token has access to notifications & repo
GH_TOKEN=<TOKEN-HERE>
ORGANIZATION=<ORG-NAME>
MAX_REPO_COUNT=5000
repolist=$(GH_TOKEN=$GH_TOKEN gh repo list $ORGANIZATION -L $MAX_REPO_COUNT --json name --jq '.[].name')
echo $repolist | while read repo; do
  echo "Unsubscribing from $ORGANIZATION/$repo\n"
  GH_TOKEN=$GH_TOKEN gh api -H "Accept: application/vnd.github+json" /repos/$ORGANIZATION/$repo/subscription --method PUT -F ignored=true | jq '.'
done


Display special character in Django HTML templates

Question: I wonder how to display special character in Django template
In models.py i have
chessman=models.CharField contain for example '♝', what suits https://en.wiktionary.org/wiki/%E2%99%9D, but in html templates does not replace to symbol.
It is problem in encoding on website or .py files or database? Or i have to change type?
Answer: This is probably because of autoescaping. If you're sure there's nothing dodgy in your variable as well as that character, you can mark it as safe:
{{ myvar|safe }}

Comment: But unfortunately i have problem with display special characters in admin panel:

        `def __str__(self):
        return "figure: { chessman|safe }"
            .format( chessman=self.chessman)`

it return "Unresolved reference"
Comment: Well, that's a template tag, you can't use it outside a template. Use [`mark_safe`](https://docs.djangoproject.com/en/1.11/ref/utils/#django.utils.safestring.mark_safe).
Comment: `from django.utils.safestring import mark_safe` (In the headline)

and
`def __str__(self): return mark_safe("figure: { chessman|safe }" .format( chessman=self.chessman))` it is works :)
Comment: Again i have similar problem... :(
Is it possible for these symbols to be displayed for example in admin site or in the form on the website on drop down list?


Fully qualified interface name

Question: Is there a way to get fully qualified interface name similar to MyClass::class?
For example:
namespace Example\Tests;

use Example\Interfaces\InputInterface;
...

class CommandTest ...
...
public function createInputMock()
{
    // I want to replace next string with something similar to MyClass::class
    $this->getMockBuilder('Example\Interfaces\InputInterface')
...

Thank you.
Comment: `InputInterface::class` isn't good?
Comment: Thank you. I didn't find this in the php documentation related to interfaces so I thought it works only with class names. You could post your comment as an answer and I'll accept it.
Answer: The ::class name resolution can work with any imported namespaces: classes, interfaces, functions, ...
namespace A\B\C {
    interface Interface_Bar {}
    function Function_Foo() {}
    function Function_Foo_Bar() {}
    const Const_BARFOO = 123;
}

namespace {
    use A\B\C\Interface_Bar;
    use A\B\C;
    use Undefined\Classes\UndefinedClass;
    use function A\B\C\Function_Foo_Bar;
    use const A\B\C\Const_BARFOO;

    echo Interface_Bar::class, "\n"; // print A\B\C\Interface_Bar
    echo C\Function_Foo::class, "\n"; // print A\B\C\Function_Foo
    echo C\Const_BARFOO::class, "\n"; // print A\B\C\Const_BARFOO
    echo UndefinedClass::class, "\n"; // print Undefined\Classes\UndefinedClass

    echo Function_Foo_Bar::class, "\n"; // print Function_Foo_Bar <- warning
    echo Const_BARFOO::class, "\n"; // print Const_BARFOO <- warning
}

Answer: If I got you right, you can't move to PHP 5.5 with ::class notation, so you want to have something similar in your 5.4 or earlier vesrion.
So the short answer is — no, there is no way.
The lack of this functionality in the previous versions of PHP is what made core developers to add ::class to PHP 5.5.
You can make a weird dirty hack if it's a class name: using get_class on new instance, but don't do it.

Fully qualified interface name


Third central moment of a sum of a random number of iid random variables

Question: Inspired by this question, I tried to get an expression for the third central moment of a sum of a random number of iid random variables. My question is whether it is correct and, if not, what is wrong or what additional assumptions might be missing.
Specifically, let:
$$S=\sum_1^N{X_i},$$
where $N$ is a non-negative integer-valued random variable.
Suppose that the distributions of both $N$ and $X$ are known (and $X_i$ are iid), I want to know the value of the third central moment of $S$.
Using the law of total cummulance:
$$\mu_3(S)=E[\mu_3(S|N)]+\mu_3(E[S|N])+3cov(E[S|N],V[S|N]),$$
but $E[S|N]=N\cdot E[X]$, $E[S|N]=N\cdot V[X]$ and, if I am right, $\mu_3(S|N)=N\cdot \mu_3[X]$. Hence:
$$\mu_3(S)=E[N\cdot \mu_3(X)]+\mu_3(N\cdot E[X])+3cov(N\cdot E[X],N\cdot V[X]),$$
and, since the moments of $X$ are supposed to be known:
$$\mu_3(S)=\mu_3(X)E[N]+E[X]^3\mu_3(N)+3E[X]V[X]cov(N,N)$$
Of course, $cov(N,N)=V[N]$, so:
$$\mu_3(S)=\mu_3(X)E[N]+E[X]^3\mu_3(N)+3E[X]V[X]V[N]$$
Is it right? What is wrong? What additional assumptions am I missing?
Answer: Your steps look right to me. We need to assume that the moments exist. The only step I was unsure about was $\mu_3(S | X) = N \cdot \mu_3[X]$. But, we can prove that:
\begin{align}
\mu_3(S | X) &= E\left[(S - E[S])^3 | N \right] \\
&= E\left[ \left( \sum_{i=1}^N (X_i - E[X]) \right)^3 \middle| N \right] \\
&= E \left[ \sum_{i=1}^N (X_i - E[X])^3 \middle| N\right]
\end{align}
where to establish the last equality, we can use the multinomial theorem. For a given $n$,
\begin{align}
E\left[ \left( \sum_{i=1}^n (X_i - E[X]) \right)^3 \right] &= E \left[ \sum_{\sum_{i=1}^n k_i = 3} {3 \choose{k_1, \ldots, k_n}} (X_1 - E[X])^{k_1} \cdots (X_n - E[X])^{k_n} \right] \\
&= E\left[ \sum_{i=1}^n (X_i - E[X])^3 \right],
\end{align}
because when $k_i = 2$ for any $i$, there exists another $j$ where $k_j=1$ (Due to independence of $X_i$ and $X_j$ and the fact that the expectation of $X_j - E[X]$ is zero, causing that particular term to become zero). Now it should be clear that $\mu_3(S | X) = N \cdot \mu_3[X]$.