Exemplo para interagir res/xml/prefs.xml com uma atividade.java

Question: Por mais que eu tenha procurado, nunca encontrei um exemplo exacto onde interaja um arquivo de preferência com uma atividade em Java, por exemplo:
private void Bemvindo(){
Toast.makeText(this, "Seja bem vindo", Toast.LENGHT_SHORT).show();
}

E no arquivo preferência localizado na pasta res/xml terá esse checkbox:
<CheckBoxPreference
                android:defaultValue="true"
                android:key="enable_boasvindas"
                android:title="Mostrar mensagem de boas vindas" />

Como faz para o checkbox ser mandante?
Se ele tiver marcado, chama o método Bemvindo e aparece o Toast, caso contrário deixa o método nulo.
Outra coisa; o método Bemvindo terá de ser escrito na atividade principal (MainActivity.java) ou na atividade de preferência (Settings.java)?
Se for na atividade principal, como chama-lo a partir da atividade Settings?
Muito obrigado, agradeço desde já! abraços.
Answer: Para trabalhar com CheckBox, no seu layout crie um CheckBox:
<CheckBox
  android:id="@+id/checkBox"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Seu CheckBox"/>

Na sua MainActivity, instancie o objeto:
public class MainActivity extends AppCompatActivity {
    private CheckBox checkBox;

    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.SEU_LAYOUT_XML);

         checkBox = (CheckBox) findViewById(R.id.checkBox);
         checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             // Se estiver selecionado então mostre a mensagem de boas vindas
             if (checkBox.isChecked())
                 benVindo();
           }
        });
    }
    private void bemVindo() {
         Toast.makeText(this, "Seja bem vindo", Toast.LENGHT_SHORT).show();
    }
}

Quanto a sua dúvida em deixar o método bemVindo nessa classe ou em uma outra classe, vai de sua preferência (Regra de negócio), caso queira que o método bemVindo() esteja em outra classe, você deverá chama-lo dessa maneira:
 public class Configuracoes {
      public static void bemVindo(Context context) {
           Toast.makeText(context, "Seja bem vindo", Toast.LENGHT_SHORT).show();
      }
 }

Agora na sua MainActivity:
public class MainActivity extends AppCompatActivity {
private CheckBox checkBox;

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.SEU_LAYOUT_XML);

     checkBox = (CheckBox) findViewById(R.id.checkBox);
     checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         // Se estiver selecionado então mostre a mensagem de boas vindas
         if (checkBox.isChecked())
             Configuracoes.bemVindo(MainActivity.this);
       }
    });
}

}

Para salvar o "status" do CheckBox use o SharedPreferences desta forma:
private void salvar(final boolean isChecked) {
     SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("check", isChecked);
    editor.commit();
}

private boolean carregar() {
   SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
   return sharedPreferences.getBoolean("check", false);
}

// Você pode associar esse método ao click do botão salvar por exemplo, ou caso não queira
private void salvarStatusCheckBox() {
    save(checkBox.isChecked());
}

// No onResume você carrega o sharedPreferences
@Override
public void onResume() {
    super.onResume();
    checkBox.setChecked(load());
}

Comment: Vou adicionar à minha resposta a parte do SharedPreference. @TechPositivo
Comment: Acho que não foi isso que foi perguntado. Ele está falando sobre CheckboxPreference.
Comment: Boooooa mano, muito obrigado. Pensando bem, ao invés de chamar a tela de preferência /xml/prefs.xml, vou criar um layout e seguir este exemplo. Muuuito obrigado. Agora só faltou implementar o SharedPreference pra deixar a opção sempre marcada ou desmarcada, rs. Tu poderias implementar?
Comment: @LeonardoRocha Amigo, nem sei como lhe agradecer. Obrigado de coração. Então, antes de ver sua resposta, eu já havia pesquisado e encontrei um método para salvar o status do checkbox. Tá salvando beleza, mas a mensagem de boas só aparece quando é marcado ou desmarcado a caixinha, ou seja, quando eu fecho e abro o aplicativo novamente não aparece mais. Esse seu código corrigi isso? Especificamente eu acho que é no onResume, né?
Comment: @LeonardoRocha Fiz tudo conforme está escrito! Só que deu a perceber que o método 'onResume' da um reset nas opções marcadas.
Comment: @TechPositivo você quer que a mensagem de "Bem Vindo" seja mostrada apenas em quais momentos?
Comment: @LeonardoRocha Sempre quando o aplicativo é aberto, ou no onResume() mas já conseguir mano. Eu criei vários CheckBox's e coloquei diferentes chaves para cada uma delas. Muito obrigado, você foi super útil.


Jeffreys prior for linear regression model

Question: Consider the linear regression model
$${\bf y} = {\bf X}\beta + {\bf e},$$
where ${\bf y}$ is an $n\times 1$ vector, $\beta$ is a $p\times 1$ vector, ${\bf e}$ is an $n\times 1$ vector. Assume also that $e_j\stackrel{ind.}{\sim} N(0,\sigma)$.
What is the Jeffreys prior of the parameters $(\beta,\sigma)$?  I am basically looking for a reference where I can find this.
Comment: If you want your account deleted just flag the question and leave a comment to the moderator to delete your account....
Answer: I have found a reference.
The Jeffreys prior in the normal linear regression model is:
$$\pi(\beta,\sigma^2)\propto \dfrac{1}{(\sigma^2)^\frac{p+2}{4}},$$
or more commonly in the $\sigma$ parameterization:
$$\pi(\beta,\sigma)\propto \dfrac{1}{\sigma^\frac{p+2}{2}}.$$
The reference is: http://www.jstor.org/stable/2290514 (see text just after Eq. 2.9 -- a bit hard to read!)
Comment: Most people drop the $(p-2)/2$ term and simply use $$\pi(\beta,\sigma^2)\propto\frac{1}{\sigma^2}$$


Suzuki Sporadic Group on Sage

Question: I need to call the Suzuki Sporadic group in Sage. I found the following command in the documentation.
G = groups.permutation.SuzukiSporadic()

This gives me a GAPError so I tried similar commands, but they all give me an error.
Comment: In GAP, you can create it using `SimpleGroup("Suz");` so however this translates into Sage syntax should do.
Answer: You need to install the optional gap_packages Sage package. If you look at the documentation for groups.permutation.SuzukiSporadic(), you should see:
sage: groups.permutation.SuzukiSporadic?
Init signature: groups.permutation.SuzukiSporadic()
Docstring:
   Suzuki Sporadic Group

   EXAMPLES:

      sage: G = groups.permutation.SuzukiSporadic(); G # optional - gap_packages internet
      Sporadic Suzuki group acting on 1782 points

The part after the command "optional -gap_packages ..." is the clue.
How to actually install that package may depend on how you've installed Sage. Running sage -i gap_packages or make gap_packages from the top-level Sage directory should do it. But this is not a math question anymore (if it was at all), so please direct inquiries about installation to the sage-support Google group or to ask.sagemath.org.

Suzuki Sporadic Group on Sage


Am I observing subharmonics using this method on guitar?

Question: Are we hearing a subharmonic? Friends and I hear a note that is lower than my lowest unfretted string on my standard acoustic guitar with standard tuning when I use the following very simple, easy method, pictured here:

As seen in the picture, a guitar pick is placed on top of the bass E string and under the next string (A string) in a manner similar to the way folks usually store a pick near the top of the fingerboard. I wedge the pick in between the E and A strings so that the edge of the pick rests on the fingerboard and the A string pushes down on the pick. The pick pushes down on the E string in this manner. (If the guitar action is too high to get the wedge affect, a piece of light cardboard can be placed under the edge of the pick that contacts the fingerboard, in order to shim it.)  Then the E string is gently stroked or plucked with my finger.  We hear a very low note that is much lower than the E unfretted string would make.
The resultant note is constant frequency, with unremarkable amplitude falloff in a fraction of a second or so.  It does not warble or "beat", as far as we can tell. It sounds an octave or so lower than the bass E string.
I am wondering and investigating if it is the brain filling in the "missing fundamental," which is a known phenomenon of human hearing. I cannot find an example of a mechanical system that will produce subharmonics.
Comment: Does it matter exactly where the pick goes?
Comment: Would be useful to have video or audio of this.
Comment: And I agree that you need to put audio up.  You are asking us all to speculate and guess.  You could be hearing things and we would need to hear the same thing.
Comment: This seems like a dup or related to a question asked last year about sub harmonics.
Comment: Is in on the 19th or 20th fret? Or alternately, how many frets are on that guitar?
Answer: The actual tone you hear is lower, because the pick adds mass to the strings. When wedged as shown in the picture, the pick and two strings vibrate together. The frequency is determined by the tension and mass of the strings, the mass of the pick and additional rotational inertia because the pick rotates around its contact point with the fretboard.
On my electric guitar I get almost exact octave drop with a one millimeter Ultex pick, lighter picks produce smaller changes.
Regarding the point about half node presented in the other answer, I believe the pick stays connected to the fretboard and strings all the time. If you pluck the string hard enough that the pick loses contact with one of the parts, you get a buzzing sound not unlike fret buzz and the pick does not stay in place.
Edit: I had a guitar and audio interface at hand, so I had to see what really happens. It turned out that the base frequency drops from E2 to D#2, but with that special pick the first harmonic is much reduced, which makes the usually weak base frequency more audible. This was with the pick at 16th fret, with the pick at 12th fret the pick stops the base frequency and 1st harmonic is stronger.
Answer: Based on the answers to my question about subharmonics, I think yes, this is a subharmonic. As ojs's answer suggests, you are creating a compound vibrating system out of the two strings and the pick. (Do be scared, so far this is just fancy words describing everything that's already been said)
Think about the whipping around of a string or rope or hose that you've played with in childhood. Now slow down the movie. Sometimes parts of the string are moving up while other parts are moving down and always with some amount of spin around the axis.
The pick wedged against the string creates an artificial node in the string's vibration, but also in a way it's making only half a node because the string can lift off the pick a tiny amount since there is no obstruction in that direction.
The pick absorbs some energy from the pressure and impact of the first string and sets about vibrating, too.
Some of the vibration from the pick is sympathetically transferred to the second string, giving rise to a resonant vibration.
The two (or three) different parts vibrating can easily give rise to the intermodulation effect where difference pitches (aka Tartini tones) are observed.
But I think, sadly the real conundrum for most guitar players will be: "If my pick is wedged in like that, how on earth am I gonna pick the string?" :)
Comment: Tartini and Paganini both played the violini. I learned the name Tartini from an excellent youtube video by Adam Neely. I know you can add youtube and soundcloud links to posts, but I don't know how to embed them nicely. I'm sure there's a way by following the help links.
Comment: I am new to this forum and format.  I do not see how to include a recording, and could use some help with that.
Comment: Thanks for the enthusiastic and thoughtful responses.  To answer a few things: The
Comment: The fret used was the 19th fret.  Interestingly if the 15th fret is used, a higher frequency note is sounded.  (Normally, this would result in a lower frequency note.)

I read luser droog's answer, and still have some questions in mind.  For example, the note I hear is the loudest note.  If it is a beat frequency, i would expepct to hear the two notes that form the beat to be present and louder than the beat.
Comment: Also, thanks for mentioning the Tartini tones.  I read that part of your answer to my gf, and she started giggling, only stopping long enough to mention things like Tonya's Tortellini TTorts and other more clever deviations.

I looked up Tartini tones in an excellent book called "Why You Hear What You Hear" by Heller.  It's excellent, but above my understanding of acoustics.
Comment: Thanks for mentioning the Adam Neely Youtube videos. But now I am convinced that the effect I noticed is not a difference frequency, otological ear noise or a missing fundamental.  If it was, we would be able to hear the other notes, as in the Neely demos.


spacetime R: How to handle missing data in a space-time-full data structure for spatio-temporal kriging purposes?

Question: I am using R and the spacetime package.
I am having problems using STFDF.
I want to use the STF data-structure since I have spacetime data with recurrent observations for fixed spatial coordinates. The problem is that there are some missing values here and there (both space and time wise). What should I do to fill the gaps? Can I put NAs in it?
The data is composed by daily ozone mean measures for each station during a period of 1 year (2016, Jan to Dec). The stations are 30, however most of them don't have 366 records. Here is the distribution of stations by number of yearly measures:

How should I handle this? Do I need to add the records putting NAs / interpolating them? Can spacetime work around the NAs or automatically interpolate them?
Comment: Kriging already does the interpolation. It is unclear what the problem is. I don't know STFDF but, did you try reading the manual and try putting NA in place of the empty spots?
Answer: According to the title of the question, the data is to be processed by kriging.
Kriging does not require, in general, that the observations should be taken on a grid.
So, unless the particular software that you are using insists on having observations on a grid, you should simply do nothing and use your dataset as it is.
Comment: @Pigna : then please edit your question to clarify that you are asking about this particular package.  If possible, specify also which function(s) in the package you have been trying to use, and why you have failed.
Comment: I was not clear, sorry. I am using the spacetime package with R. In order to do the kriging it seems like you must put the data in some sort of structure (at least, that's what happens in all spacetime tutorials I have found)


Wildcard www to non www redirection nginx

Question: I'd like to redirect all traffic from
www.*.*.<gTLD>
to
*.*.<gTLD>
If possible, I'd like to do that outside the block that serves the application. This block does not use a server_name because it listens to 5,000+ hostnames on the same app.
Do you have an idea on how to achieve that please ? All the example I find is only for named hosts....
Thank you
Answer: You can define a server block with a regular expression server_name. For example:
server {
    server_name ~^(www\.)(?<domain>.+)$;
    return 301 $scheme://$domain;
}

See this document for more.
Comment: nice, it's a good start. But the problem is with what you gave me www.example.com will redirect to example.com. And I don't want that. I only want subdomains to be redirected to non www.
Comment: Change the regular expression to match your specific requirement. Or if `www.example.com` is the only exception - add it to the `server_name` of your `default_server` block.
Comment: Complete regex is `server_name ~^(www\.)(?.+\..+\..+)$;`
Comment: Any idea why it does not work for me? For example this: `server_name www.example.com;    return 301 $scheme://example.com$request_uri;`
but the one you posted above does not.
Answer: With the help of @Richard Smith
I came with a result of :
server {
    server_name ~^(www\.)(?<domain>.+\..+\..+)$;
    return 301 $scheme://$domain;
}

It works well :-)
Comment: You should upvote and accept his answer then. You can add your regex (which is the only thing you modified from his answer) as a comment or an edit.


Attention based models for machine comprehension

Question: Currently, I am understanding Attention models. I specifically need it to build a machine comprehension model (a model which can find answer to a question from a given comprehension). But I want to understand the model generally and not specifically to this topic. I have a question about attention layer but before that I would like to share what I understood.
The things I understood so that you can correct me if I made some mistakes
For this, I have referred an article online which I am sharing here - http://www.wildml.com/2016/01/attention-and-memory-in-deep-learning-and-nlp/
It gave basic intuition of what the attention layer does - It asks the model the model to focus on a specific part of the input in order to generate the output. Here's an image of it - http://www.wildml.com/wp-content/uploads/2015/12/Screen-Shot-2015-12-30-at-1.51.19-PM.png
The pink shades are defined by attention variables 'a(i)'. These variables are actually probability distribution that shows 'the probability that the model should focus on the area represented by that variable'. So, a general figure on any attention based model is as - http://www.wildml.com/wp-content/uploads/2015/12/Screen-Shot-2015-12-30-at-1.16.08-PM.png - where 'a's are the attention variables (weights). These variables are trained by the model.
The question
I have a question in mind. Are the attention weights same for every inputs (in machine comprehension, input = 'comprehension'). If so, then independent of the comprehension, the model will focus on a very small part of every comprehension to find an answer. And it isn't necessary that the answer lies in same part of all comprehensions.
If the weights are different for different inputs, then how will we train them. Because, as per my knowledge, in every neural network, the weights are trained for all the input data irrelevant of the input identifier i.e the final weight values at the end of training is same for all the inputs. And after training, these weights are the final values which are used in real-time application.
Answer: The attention "weights" are not weights in the sense that the word is usually used -- they aren't trainable parameters. They are usually computed as a function of the input and some other parameters, so for question answering, the weight might be $a_t = \text{softmax}(h_t^T W q)$, where $h$ is the hidden state, $W$ is a parameter, and $q$ is the question you're trying to answer. So $a_t$ is different for different inputs, but the weight matrix $W$ is learnable and can be fixed.
Comment: Can you elaborate please? And how will this 'W' be related to "a(t)"? Can you provide an intuitive understanding for this?
Comment: @KadamParikh $W$ is the parameter responsible for directing attention. I'm not sure what you're confused about. See [this post](https://stats.stackexchange.com/questions/344508/what-are-attention-mechanisms-exactly) for more info
Comment: Ok.. I understood what you said. But let me make my question clear. Here, we will find 'W' such that for all different inputs, it will produce different output which tells the model where to focus. Right?

But I doubt that it is efficient. As to train such model we will need a large dataset which can train the parameter 'W' on (nearly) all the inputs. So, can we do this really?

In short, I understood the way attention works but I doubt that it will work on all the inputs correctly.
Comment: @KadamParikh "So, can we do this really?". Yes, SGD is quite adequate for training nueral networks, and W is just another parameter of the network.


Tirar uma amostra sem repetição levando em consideração 2 variáveis no R

Question: Possuo duas bases. Uma com as linhas que gostaria de tirar a amostra e a outra com o tamanho da amostra com as data. A primeira que é a base de dados de fato que preciso fazer a amostra, está exemplificada abaixo chamada "bons":
CNPJ    data
333333  201601
333333  201612
111111  201612
111111  201610
111111  201607
111111  201611
22222   201605
22222   201606
22222   201610
22222   201509
99999   201605
99999   201612
99999   201611
99999   201601

A segunda base está abaixo chamada "tamamostra", ela possui apenas o tamanho da amostra que necessito para cada data, sendo que essa amostra deve ser feita com CNPJs que não se repetem:
data    201509  201510  201512  201601  201602  201603  201604  201605  201606  201607  201610  201611  201612  Total
ruins   1          1       1       6       4       3       2       4       3       5       5       4       6       45
bons    3          3       3       14      10      7       5       10      7       12      12      10      14      105
Total   4          4       4       20      14      10      7       14     10    17         17      14      20      155

Preciso fazer uma amostra de tamanho "bons" para cada data sem repetir o mesmo CNPJ. Ou seja, para 201509 preciso de uma amostra de tamanho 3 com 3 CNPJs diferentes sendo que esses CNPJs não podem se repetir para as outras datas, para 201601 preciso de uma amostra de tamanho 14 com CNPJs que não se repetem na data anterior e assim sucessivamente, tendo, no final, uma amostra total de tamanho 105 com CNPJs únicos. Vale destacar que existem alguns CNPJs que não possuem algumas datas.
Tentei utilizar o for com o sample para fazer essa amostra, porém, como não especifiquei que o CNPJ não podia se repetir, alguns CNPJs saíram repetidos:
for(i in 2:14){
bons1[i]<-subset(bons,data==tamamostra[1,i])[sample(nrow(subset(bons,data==tamamostra[1,i])), tamamostra[3,i]), ]
}

Como fazer isso no R? Acredito que o pacote dplyr deve ter alguma solução.
Comment: Pode não haver uma tal amostra. Por exemplo, se os 4 CNPJs de 201510 forem os mesmos de 201512, não tem como escolher 3 de um e 3 do outro sem haver algo em comum.
Comment: Não ficou claro a sua pergunta. Você precisa de uma amostra de tamanho n com n CNPJs, para as m datas, ok, mas qual a relação entre os dois conjuntos de dados?
Comment: Editei a pergunta. A base é grande e é possível fazer.
Comment: @T.Veiga, ainda não ficou claro qual a relação da base 1 com a base 2, veja para seu exemplo, data = 201509, vc precisa de 3 amostra, ou seja 3 CNPJs, essa amostra seria retiradas da base 1 (bons), correto? Cada CNPJ seria aleatório ou teria alguma relação com a coluna data? Essa saída os CNPJs seriam mesclados ou separados?
A saída possível para esse exemplo poderia ser: "111111", "22222", "333333" ou 11111122222333333?
Answer: Como seus dados de exemplo não possuem tamanho suficiente para uma amostragem sem repetição, estou gerando outros, mais simples, só para demonstração:
dados <- data.frame(
  CNPJ = rep(1:20, each = 3),
  data = 2015:2017
)

tam <- data.frame(
  data = 2015:2017,
  bons = 1:3
)

A tabela com o tamanho das amostras precisa estar em formato "longo". No caso dos seus dados, você pode convertê-los da seguinte maneira:
tamamostra <- read.table(text = c('
  data    201509  201510  201512  201601  201602  201603  201604  201605  201606  201607  201610  201611  201612  Total
  ruins   1          1       1       6       4       3       2       4       3       5       5       4       6       45
  bons    3          3       3       14      10      7       5       10      7       12      12      10      14      105
  Total   4          4       4       20      14      10      7       14     10    17         17      14      20      155')
)
tam <- as.data.frame(t(tamamostra[,-c(1,ncol(tamamostra))]))
names(tam) <- tamamostra[[1]]

Usando loop com subset
A ideia aqui é sequencialmente amostrar CNPJs por datas e cortar os sorteados da tabela de dados:
#data.frame para receber as amostras
amostra <- data.frame(
  CNPJ = NA,
  data = rep(tam$data, tam$bons)
)

# cópia dos dados, para preservar o original
dados -> dados.temp

for (data in tam$data) {
  samp.cnpj <- sample(dados.temp[dados.temp$data == data, 'CNPJ'], size = tam[tam$data == data, 'bons'])
  samp.cnpj -> amostra[amostra$data == data, 'CNPJ']
  dados.temp <- dados.temp[!dados.temp$CNPJ %in% samp.cnpj,]
}; rm(dados.temp, samp.cnpj)

> amostra
  CNPJ data
1    6 2015
2   18 2016
3    8 2016
4    7 2017
5   15 2017
6   19 2017

Sorteando primeiro uma data para cada CNPJ
Aqui a ideia é primeiro sortear uma data para cada CNPJ (de modo que não haja repetição) para depois amostrar os CNPJs por data, usando para isso o pacote data.table. Esta solução é potencialmente mais rápida para um conjunto de dados muito grande, mas podem não restar CNPJs suficientes para fazer a amostragem.
library(data.table)
setDT(dados)
amostra <- dados[, .(data = sample(data, 1)), by = CNPJ][tam, on = 'data'][, sample(CNPJ, bons), by = data]
names(amostra)[2] <- 'CNPJ'

> amostra
   data CNPJ
1: 2015    9
2: 2016    1
3: 2016   16
4: 2017    2
5: 2017    8
6: 2017    7

(Agradecimento ao @juan-antonio-roldán-díaz pela sugestão desta ideia)
Comment: @t-veiga Eu não uso `dplyr`, mas se quiser usar a segunda proposta com ele, esta resposta no SO em inglês pode ajudá-lo: https://stackoverflow.com/a/41669338/9817508


Delete Sqlite Table on Activity start

Question: How i can delete sqlite table when my application start.
my DataBaseHelper have:
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
   _db.execSQL("DROP TABLE IF EXISTS CARS");
}

But when app start nothing is happening. I want to drop tables if they exist on every start of application.
Thanx
Comment: Why dont you use the onCreate to delete and create new? Or is it just one table not whole db? Also possible you create a new method and call it on app start
Comment: Just 3 tables, i must save 1 table, but i was think maybe if i cannot to delete just table, that i make two .db, one delete, and create new, and one save?
Comment: What library do you use to work with Sqlite?
Comment: @Joseph, to be honest i don't know , i am still noob with android. I have packege android.database.sqlite in android.jar (17) if that help? or can you help me how to check?
Comment: @Nick  please see my answer, and if it helps mark it as your answer, thanks
Answer: OnUpgrade is only called if the DB_VERSION has changed, so the database need to be modified or something.
In your case i suggest to create a single Method which is doing the job and call that from the activity method onCreate. Then it it will be called on every start.
Edit:
The Db Helper Class:
public static final  String DB_NAME = "MyDbName";
public static final int DB_VERSION = 1;

private SQLiteDatabase db;

public DbHelper(Context context ) {
    super(context, DB_NAME, null, DB_VERSION);
}

public void deleteTable() {
    if (db == null || !db.isOpen())
        db = getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS CARS");
}

Activity onCreate:
dbManager.deleteTable();

Comment: This can help you: http://stackoverflow.com/questions/7444327/how-to-initialize-sqlite-database-once-from-a-helper-class-in-android
Comment: Just one question how to define db? (sorry but i still learning) . I have onUpgrade(SQLiteDatabase _db..) but if i define that way, i must define in on activity create to,yes?
Comment: @nick sry, my mistake i'll add it
Comment: Now i getting error:
08-04 17:50:37.045: E/AndroidRuntime(22940): FATAL EXCEPTION: main
08-04 17:50:37.045: E/AndroidRuntime(22940): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.police.car/com.police.car.LoginActivity}: java.lang.IllegalArgumentException: Version must be >= 1, was 0
:(
Comment: @Nick You have to add the Version 1 at least. I added some code as sample
Comment: in your answer.. "db.execSQL("DROP TABLE IF EXIST CARS");" it's not EXIST.. you are missing an S. it's EXISTS ! :)
Answer: I work always on Android with OrmLite, but onUpgrade method is called when version of database change, and when you execute a query to sqlite database. You need to call a method to delete a database.
Answer: You can create a method that drops the table, and just call it on the "onCreate()" of your Activity.
the onUpgrade() method is only called when the DATABASE_VERSION is changed, so there is no guarantee that it will always be called on every start.

Delete Sqlite Table on Activity start


how to return activity based on timedate mysql 5.7

Question: this is my fiddle https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=5422fb347abaf2bde082eb522f5be4fb
table data2
+--------------------------------------+-----------------+----------------+----------+
|               user_id                | event_timestamp |   event_name   | level_id |
+--------------------------------------+-----------------+----------------+----------+
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_complete |        1 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02      | level_complete |        2 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02      | level_complete |        3 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-02      | level_complete |        4 |
+--------------------------------------+-----------------+----------------+----------+

table data3
+--------------------------------------+-----------------+------------+----------+
|               user_id                | event_timestamp | event_name | level_id |
+--------------------------------------+-----------------+------------+----------+
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2019-12-31      | level_end  |        1 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_end  |        2 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_end  |        3 |
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2020-01-01      | level_end  |        4 |
+--------------------------------------+-----------------+------------+----------+

so i have 2 tables, if user_id has completed the level, then that data come to data2 table, but if failed the level, then the data come to data3 table. so i want to order by the event_timestamp so the expected results was like this
+--------------------------------------+-----------------+------------------+----------+
|               user_id                | event_timestamp |    event_name    | level_id |
+--------------------------------------+-----------------+------------------+----------+
| 895A8F53-C61C-471A-B934-CC2795286E19 | 2019-12-31      | level_end        |        1 |
|                                      | 2020-01-01      | level_completed  |        1 |
|                                      | 2020-01-01      | level_end        |        2 |
|                                      | 2020-01-01      | level_end        |        3 |
|                                      | 2020-01-01      | level_end        |        4 |
|                                      | 2020-01-02      | level_compeleted |        2 |
|                                      | 2020-01-02      | level_completed  |        3 |
|                                      | 2020-01-02      | level_completed  |        4 |
+--------------------------------------+-----------------+------------------+----------+

i've tried with this query
select * from data2
inner join data3 on data2.user_id = data3.user_id
order by data2.event_timestamp, data3.event_timestamp;

but the output was not like i expected
Comment: Not join.. maybe using `UNION`?
Comment: https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=20f828f5b99e54e2acd56cd8b4c3de0c it become like this
Comment: The structure does not provide integrity check (i.e. `level1>level2` does not guarantee `date1`>=`date2` in any table, and `data2.level=data3.level` does not guarantee `data2.date>=date3.date`). What output do you need if these conditions are false? PS. The tables stores the same entity, and only one attribute differs, it seems. Why two tables are used?
Answer: Something like this:
select * from data2 union
select * from data3
order by event_timestamp, level_id;

Using UNION and order by event_timestamp, level_id;
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=03b02e0d079011aa4f9e3af7974a98f1
Comment: @FachryDzaky *yes it only show once for every user_id* Do it (replace `user_id` with empty string if the value in previous row is the same) on the client side.
Comment: this was true, but almost true, can i make it into just like my expected results? because in my real case, there's a lot of user_id
Comment: i've tried with this https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=7ea8662ddf5060a5c66416477fa29ec5
Comment: The error you specify is because of `sql_mode=only_full_group_by` setting. Is your real database setting using it (the sql_mode)? This is how you quickly resolve the `sql_mode=only_full_group_by` issue in any fiddle https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=cc36879bdf7de09be16560ba29c752a2
Comment: Your expected result means on the left side of `user_id` it only show once?
Comment: I can think of a way but only if you're using MySQL 8.0 or MariaDB 10.3 and above ... something like this https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7e294f9ca792fea07171c7a41f9f2dd4


expected a; but I already have a ;

Question: hello I am trying to do my college homework but I keep getting an error saying expected a ; but I already have a ; on that line. my error is during the cin answer
#include <iostream>
#include <string>
using namespace std;

int main()
{
string name;
cout << "Welcome to the Prison of Elders, Guardian, what is your name ?.";
cin  >> name;

cout << "are you ready to face a challenge" << name <<  "!" << endl;
cin answer;

while (1);
return 0;

Comment: s/`cin answer; `/`cin >> answer; `
Comment: You have a mistake: `cin answer; `
Comment: thanks guys, I was confused on this I should have added the >>
Answer: cin answer;

should be replaced by
cin >> answer;

More generally, the "expected thing" as compiler message should always be treated with caution. It's just some guess that matches the syntax from the compiler. However, it is always the sign of a syntax error somewhere. (And not necessarily at the line where you see the "expected thing")
To elaborate on why ";" was expected :
cin is an identifier, as well as answer
You wrote identifier identifier;, which is never a correct syntax in C++.
the compilator was confused by seeing two identifiers next to each other. So it suggested this :
cin; answer;

which is syntactically correct and solve the confusion, but complete nonsense semantically in your code.

expected a; but I already have a ;


Autolayout works when viewController is loaded from XIB but does not work when loaded from Storyboard

Question: I Have a project here. Autolayout constraints is working only when loaded from a Xib file.
When you run the project you will see a single screen with a NSPagecontroller on it that has two views (swipe left/right to get the other view).
Both views are exactly the same with the exact same auto layout constraints on it. One is loaded using Xib, while the other is loaded using Story board.
Try resizing the window when the xib loaded one is on screen. You can see every thing resizes correctly. Now swipe the screen left. Try resizing the window now. The view loaded from story board will not autosize.
Is this Apple bug?
Answer: The views are not exactly the same. If I delete the view in the storyboard, and copy-paste the view from the xib, then the storyboard version behaves as expected.
The trouble with all of this storyboard/xib constraints goodness is that they are a complete pain to debug if something goes wrong.
Try spot the difference:
(1) ViewController.xib

(2)Storyboard

For this reason, I tend to handle all of my constraints in code these days.
Top left button comparison:
(1) ViewController.xib

(2)Storyboard

The other buttons constraints differ also.
Comment: thanks a mil man. This was stupid. In order to get the constraints of the view to work on story board I had to do what you did. Delete the view from story board and then copy view from the xib unto the storyboard to set as the ViewController's new view. Only then did the view on storyboad have the constraints. Without doing this, it doesnt seem like Interface builder storyboard allows you to set constraints for the view directly under the Viewcontroller.


integral of a product of sine function with a polynomial

Question: What is the integral of this function :

$$\int_{-\infty}^{+\infty}x^{\alpha} \sin{ax} \, \mathrm{d}x$$ with $\alpha, a$:real values?
Comment: Let me WolframAlpha it for you: [link](http://tinyurl.com/q85nkm2)
Answer: Here is a compact closed. We split the integral as
$$ I = \int_{-\infty}^{0}x^\alpha \sin(ax)dx + \int_{0}^{\infty}x^\alpha \sin(ax)dx \longrightarrow (*). $$

$$ \implies I = (1+(-1)^{\alpha+1}){a}^{-\alpha-1}\Gamma  \left( \alpha+1 \right) \sin \left( \frac{\pi \,
 \left( \alpha+1 \right)}{2}  \right) .$$

To get the above answer follow the steps
1) make the change of variables $t=-x$ for the first integral in $(*)$,
2) use the Mellin transform tables since the integral
$$ \int_{0}^{\infty} x^{\alpha} \sin(ax ) dx$$
is nothing but the Mellin transform of $\sin(a x)$

$$ F(s)= \int_{0}^{\infty}x^{s-1} \sin(ax)dx\,\quad -1<Re(s)< 1 .$$

with $s=\alpha +1$.
Note: I tried Maple 17 and wolfram alpha no response. However they give closed form answers for special cases. For instance $\alpha=-1/2$.
Comment: @ Mhenni Benghorbal thank you for your help :)
Comment: @AhmedAbrous: Pay attention to what of values of $\alpha$ the integral converges. See what I added.
Comment: and if we have a cosine in the place of a sine function? I mean $\cos(ax)$
Comment: @AhmedAbrous: Just see what's the Mellin transform of $\cos(x)$.
Comment: @AhmedAbrous: You are welcome.


Armazenar quantos dados eu quiser em uma coluna de uma tebela em oracle apex

Question: Estou criando uma página no apex e preciso criar um gráfico com os motivos que mais causam multas, mas uma multa pode ter vários motivos. Não estou conseguindo armazenar esse motivos de forma que eu consiga gerar o gráfico
CREATE TABLE "MULTA"(
    "COD_MULTA" NUMBER(*,0),
    "DATA_APLICACAO_MULTA" DATE,
    "QNT_PARCELAS" NUMBER(*,0),
    "VALOR" FLOAT(2),
    "CPF" VARCHAR2(11),
    "NOME_MOTIVO" VARCHAR2(1000),
    PRIMARY KEY ("COD_MULTA")
    USING INDEX ENABLE
)

CREATE TABLE "MOTIVO"(
    "COD_MOTIVO" NUMBER(*,0),
    "NOME_MOTIVO" VARCHAR2(1000),
    PRIMARY KEY ("COD_MOTIVO")
    USING INDEX ENABLE
)

Alguém pode me ajudar com isso?
Comment: Explique "não estou conseguindo armazenar esse motivos" , numa analise rápida o modelo deveria ser MULTA----<MOTIVO_MULTA-----MOTIVO
Answer: Se uma multa pode ter mais do que um motivo então a relação entre a multas e motivos é de 1-N. Dessa forma é necessário uma terceira tabela que relacione cada multa com os seus vários motivos.
Algo deste género:
CREATE TABLE motivos_multa (
  COD_MULTA NUMBER,
  COD_MOTIVO NUMBER
);

Não inclui intencionalmente as referências às chaves estrageiras. Esta tabela tem de ser populada sempre que uma multa é inserida, associando a multa aos seus motivos (uma linha por cada motivo associado).
Para obter o motivo de multas mais frequentes a query em baixo é suficiente:
SELECT motivo.NOME_MOTIVO, count(1)
FROM motivos_multa
  INNER JOIN motivo ON motivos_multa.cod_motivo = motivo.cod_motivo
GROUP BY motivo.NOME_MOTIVO;


Difference between expensive/cheap xlr cable

Question: I noticed that you can get cheap and expensive xlr cables, why would anyone buy the more expensive ones?
Is the only difference how well the cable "age"? Or are there also differences in how well the cable leads electricity?
Example:

$18 xlr cable
$8 xlr cable
Comment: The links provided compare a 2-pack of 6' cables to a single 3' cable?  That sounds like a packaging price difference.  For other comparisons, there can be differences of metals used on the connectors, quality of the cable insulation, gauge, brand, color.....  And of course of merchant trying to make more money than another.
Comment: Note that "aging" also means "reliability", and whenever you are doing something important with your cables (say, playing a live gig or steering an airplane) you do *not* want them to suddenly develop connection faults, so a quality / brand-name cable might be worth it just for reliability and peace of mind. (Also, I imagine finding the broken cable in a complex audio setup is a very special kind of hell.)
Answer: The things that affect the quality and price of a cable are similar to what affects quality and price for any product: parts and labor. Specifically for cables:

The cable itself, including the type of metal used as conductors, the quality of the metal, the dialectic type and quality, and the insulator type and quality. Also the strand count and size of the wiring and the braid pattern, density, and weave quality of the shield.
The connector design and materials. If you unplug and plugin in a lot of XLRs, you'll start to appreciate good connectors a lot more. I won't buy any XLR cables that don't have Neutrik connectors any more. I should point out that others hate Neutriks and instead are die hard fans of the s Switchcraft design.
The solder joint and strain relief between the cable and the connectors is critical, and there is a huge variance in quality when it comes to solder joints. The solder itself can vary a lot, and choosing the right solder is pretty tricky these days. The temperature of the soldering process, the contact time, the amount of solder, all of these can give you a connection that will last decades if done well or maybe only days if done poorly.

There are other details that matter in cables. Really you have to decide for yourself what you are comfortable with. I am easily frustrated by cheaper cables but other people don't notice or don't mind the difference. And still other people insist on cables even more expensive than what I'm willing to use.
Comment: "what affects quality and price for any product: parts and labor" – Don't forget _brand/marketing_. Towards the upper end of the price spectrum, that tends to become a very significant part of the price, and in case of some audiophoole scams it's basically the entire price.
Comment: Agree about Neutrik - especially the older variety. Still gigging using leads that are 35+ yrs old. Don't normally buy a lead with connectors aleady on - always need a different length! Having said that, I tend to buy really long cables, and make two or three out of one. +1.
Answer:
Is the only difference how well the cable "age"?

Yes, pretty much. I bought a couple of really cheap mic cables for use at home once (where, I thought, the stresses would be so much less than on stage that it wouldn't matter), but even then they broke after something like a year. Whereas good quality cables can last many years even when used weekly in a less-than-gentle manner on those rough stages.

Or are there also differences in how well the cable leads electricity?

Yes, but they don't really matter because XLR is a well-designed standard (unlike many other audio connections). Concretely, they are balanced so that hum/brizzle etc. interferences are mostly cancelled out, and have a well-chosen impedance that prevents either capacitance (which has a big influence on the very high-Q guitar connections) or resistivity (which swallows power in the very low-Q speaker connections†) to have any significant influence on the transmission★ – at least for reasonable cable lengths; for kilometre-long transmissions you might run into problems but who would need that?
That means in particular that super-premium mic cables, advertised as sounding particularly good, are just bogus. In case of guitar cables those may actually sound different (typically because of very low capacitance, but even then the price is usually not justified because you could just use a shorter cable and/or a suitable buffer), but for mic connections they will sound exactly the same, unless they have some deliberate nonlinearity built in – which, when it actually does improve sound, you should better dial in with a simple equaliser.
Very low quality cables may also have strange sonic effects, like clicks when you step on them, but those are just trash. Any two decent mic cables will not give notably different sound so long as they work at all.

†There are actually good reasons why speaker connections have such low impedance. As long as the connections are kept short, this isn't really an issue (best is to have the power amps right next to the speakers or even inside the (active) speakers).
★This assumes of course that the devices you connect are actually standards-compliant, i.e. have the correct impedance and high common-mode rejection. That's not always a given; in particular, if you use an XLR cable through an adapter as an extension to an unbalanced line one, then the XLR part will also be unbalanced and therefore happily pick up any interference that makes it through the shielding. The correct thing to do here is to use a DI box instead of a plain adapter.
Answer: Once you actually hold a good XLR cable, you really can feel the quality in it. You're looking at $3-10 per foot, depending on length (longer is cheaper per foot).
Warranty is also a factor. All cables break eventually. I have some 12 year old cheaper XLR and guitar cables with a life-time warranty. If (when) they break, I can just take them into a local store, and they'll give me a new one.
They'll also do the same with my (much more expensive) cables. The difference is, the expensive cables are heavier duty, and less likely to give out during a gig. I generally carry the expensive ones (and spares) with me, and a couple of cheaper ones as loaners/gifts if someone else has a problem.


Prove that $\sum_{k = 0}^{r}\binom{n + k}{ k} = \binom{n+r+1}{ r}$ whenever $n$ and $r$ are positive integers.

Question: Question:
Prove that $\displaystyle\sum_{k = 0}^{r}\binom{n + k}{ k}  = \binom{n+r+1}{r}$ whenever $n$ and $r$ are positive integers.
a.) using combinatorial argument.
b.) using Pascal's identity.
My Attempt:
a.) I've got nothing here.
b.) This one is basically algebra manipulation so I don't need help here.
I really don't have a clue where to start about the combinatorial argument. Can someone help me.
Comment: http://math.stackexchange.com/questions/505367/surprising-identities-equations/673179#673179
Answer: We have $n+1+r$ people lined up in a row, and want to choose $n+1$ of them. That can be done in $\binom{n+1+r}{n+1}$ ways, which is $\binom{n+1+r}{r}$, for we are rejecting $r$ people.
Let us count the number of choices another way. Suppose the first person in the line that is chosen is person $1$. Then there are $\binom{n+r}{n}$ ways to choose the others.
Maybe the first person chosen is person $2$. There are $\binom{n+r-1}{n}$ to choose the rest.
Maybe the first person chosen is person $3$. There are $\binom{n+r-2}{n}$ to choose the rest.
And so on.  That gives total
$$\binom{n+r}{n}+\binom{n+r-1}{n}+\binom{n+r-2}{n}+\cdots +\binom{n}{n}.$$
Recalling the combinatorial fact that $\binom{a+b}{a}=\binom{a+b}{b}$, and reversing the sum above, we get
$$\binom{n}{0}+\binom{n+1}{1}+\cdots +\binom{n+r-1}{r-1}+\binom{n+r}{n},$$
which is the desired sum.
Remark: It should be easy to change the story, so that we can obtain $\binom{n+1+r}{r}$ and $\binom{n+k}{k}$ directly, and not as $\binom{n+1+r}{n+1}$ and $\binom{n+k}{n}$.


Matching, ranking based on relevance of each criteria

Question: I have a growing database containing:

a table of demands (multiple criteria)
a table of offers (multiple criteria)

Criteria can be string (e.g.: country name), boolean, numeric, ...
I would like to find all demand-offer which match more or less (a little like job banks, matchmaking, ...)
If tables didn't contain many rows I would calculate as follows:

for each demand, calculate for each offer the relevance of matching by averaging the relevance of each criteria.

But for an important database this would take too much time, wouldn't it?
What solution do you recommend?
Answer: To extend the answer from June 24, 2010 -- Capture the pre-calculated relevance score in a Join Table (Demand Key, Offer Key, Relevance Score).  Be aware that this Join Table could hold Count(Demands) * Count(Offers) records; it may be prudent to store only those records with Relevance Scores greater than some threshhold value.
This approach has a computation complexity of O(n) on Data Insert.  You may be able to reduce this complexity to O(log(n)) if the assumption that the Feature Space for Demands (similarly for Offers) is such that two Demands that have high Relevancy Scores for the same Offer are also 'Close' within their Feature Space, holds:

Perform a K-Nearest Neighbours analysis on the Comparison Features of Demands (and separately for Offers) and limit the value of K to be approximately log(n) of your data set.
Calculate the Match Relevance between the representative Feature Vectors of the Clusters and store that in a database table.
On Insert measure the 'Distance' between the new record and each of the Clusters of that type and store a Foreign Key to the Cluster on the new record.
When searching for Offers to match a Demand -- follow the links from the Demand to its Cluster to the most relevant Offer Cluster to individual Offers.

This will trade specificity for speed.  Verify the veracity of the initial assumption by comparing a sample of Demands to each Offer and sort on Relevance; traverse the ordered set of Offers and count how many you find in the result set from the Cluster Search before you find one that is missing.  A subjective analysis of this test will give you an idea of how much Clustering is costing you.
Answer: I'd do it the way you describe - but with a rolling caching mechanism and some indexes.
Work out the relevance on creation and then see how it goes. Incremental additions could be fine if the frequency is low (high-read, low-write). If it is high on both ends, you could split into two databases... process updates on one, then periodically push the post-processed data into the other, which is the default source for reading.
Comment: Not an ideal situation - but it rarely is in computing! Hope you have success.


Preferred way of class member initialization?

Question: class A { public: int x[100]; };

Declaring A a will not initialize the object (to be seen by garbage values in the field x).
The following will trigger initialization: A a{} or auto a = A() or auto a = A{}.
Should any particular one of the three be preferred?
Next, let us make it a member of another class:
class B { public: A a; };

The default constructor of B appears to take care of initialization of a.
However, if using a custom constructor, I have to take care of it.
The following two options work:
class B { public: A a;  B() : a() { } };

or:
class B { public: A a{};  B() { } };

Should any particular one of the two be preferred?
Comment: Please clarify your question regarding the context in which you would like to use the initializers. Are you only interested in empty initializers? Are you looking to determine a more general approach for complex objects?
Answer: Initialization

class A { public: int x[100]; };

Declaring A a will not initialize the object (to be seen by garbage
  values in the field x).

Correct A a is defined without an initializer and does not fulfill any of the requirements for default initialization.

1) The following will trigger initialization:
A a{};

Yes;

a{} performs list initialization which
becomes value initialization if {} is empty, or could be aggregate initialization if A is an aggregate.
Works even if the default constructor is deleted. e.g. A() = delete; (If 'A' is still considered an aggregate)
Will warn of narrowing conversion.

2) The following will trigger initialization:
auto a = A();

Yes;

This is copy initialization where a prvalue temporary is constructed with direct initialization () which

uses value initialization if the () is empty.
No hope of aggregate initialization.

The prvalue temporary is then used to direct-initialize the object.
Copy elision may be, and normally is employed, to optimize out the copy and construct A in place.

Side effects of skipping copy/move constructors are allowed.

Move constructor may not be deleted. e.g A(A&&) = delete;
If copy constructor is deleted then move constructor must be present. e.g. A(const A&) = delete; A(A&&) = default;
Will not warn of narrowing conversion.

3) The following will trigger initialization:
auto a = A{}

Yes;

This is copy initialization where a prvalue temporary is constructed with list initialization {} which

uses value initialization if {} is empty, or could be aggregate initialization if A is an aggregate.
The prvalue temporary is then used to direct-initialize the object.

Copy elision may be, and normally is employed, to optimize out the copy and construct A in place.

Side effects of skipping copy/move constructors are allowed.

Move constructor may not be deleted. e.g A(A&&) = delete;
If copy constructor is deleted then move constructor must be present. e.g. A(const A&) = delete; A(A&&) = default;
Will warn of narrowing conversion.
Works even if the default constructor is deleted. e.g. A() = delete; (If 'A' is still considered an aggregate)

Should any particular one of the three be preferred?

Clearly you should prefer A a{}.

Member Initialization

Next, let us make it a member of another class:
class B { public: A a; };

The default constructor of B appears to take care of initialization
  of a.

No this is not correct.

the implicitly-defined default constructor of 'B' will call the default constructor of A, but will not initialize the members. No direct or list initialization will be triggered. Statement B b; for this example will call the default constructor, but leaves indeterminate values of A's array.

1) However, if using a custom constructor, I have to take care of it. The
  following two options work:
class B { public: A a;  B() : a() { } };

This will work;

: a() is a constructor initializer and a() is a member initializer as part of the member initializer list.
Uses direct initialization () or, if () is empty, value initialization.
No hope of using aggregate initialization.
Will not warn of narrowing conversion.

2) or:
class B { public: A a{};  B() { } };

This will work;

a now has a non-static data member initializer, which may require a constructor to initialize it if you are using aggregate initialization and the compiler is not fully C++14 compliant.
The member initializer uses list initialization {} which
may become either value initialization if {} is empty or aggregate initialization if A is an aggregate.
If a is the only member then the default constructor does not have to be defined and the default constructor will be implicitly defined.

Clearly you should prefer the second option.

Personally, I prefer using braces everywhere, with some exceptions for auto and cases where a constructor could mistake it for std::initializer_list:
class B { public: A a{}; };

A std::vector constructor will behave differently for std::vector<int> v1(5,10) and std::vector<int> v1{5,10}. with (5,10) you get 5 elements with the value 10 in each one, but with {5,10} you get two elements containing 5 and 10 respectively because std::initializer_list is strongly preferred if you use braces. This is explained very nicely in item 7 of Effective Modern C++ by Scott Meyers.
Specifically for member initializer lists, two formats may be considered:

Direct initialization a() which becomes value initialization if the () is empty.
List initialization a{} which also becomes value initialization if {} is empty.

In member initializer lists, fortunately, there is no risk of the most vexing parse. Outside of the initializer list, as a statement on its own, A a() would have declared a function vs. A a{} which would have been clear. Also, list initialization has the benefit of preventing narrowing conversions.
So, in summary the answer to this question is that it depends on what you want to be sure of and that will determine the form you select. For empty initializers the rules are more forgiving.
Comment: Could you please elaborate on what could be the implications of the constructor mistaking the `{}` in `a{}` for `std::initializer_list`?
Comment: My question was specifically for empty braces. I found the answer in the book that you pointed out: empty braces will call the default ctor, and not the initializer-list ctor with an empty list. Hence the empty `()` and `{}` should behave exactly the same.
Comment: Interesting point about the empty braces. I've updated the answer to include some additional points.
Comment: Speaking of most vexing parse, one observation relevant outside of init lists: `{}` instead of `()` can avoid it, but this is only necessary in certain situations. The problem seems to be that it is allowed to write the argument list to the ctor (even if empty) next to the object that is being defined, that is, `A a()`. To correct this, use `A a{}`. However, the following is ok as well: `A a = A()` or `auto a = A()`. Now more and more people seem to write `auto a = A{}` and say that "this" prevents most vexing parse. This claim can be confusing since the `{}` do not make the difference here.
Comment: @LasseKliemann Sometimes the form makes a difference. I've made some updates.


How should I deal with Views URL parameter "page" in Google web master tool?

Question: I have node view which has pager with URL parameter "page". I want Google bot crawls all the pages ( page=1 page=2 page=3... ) but regard all of them as just one and only the first page (without parameter "page") should appear on the search result.
On the webmaster setting page I have set URL parameter for "page" as below but now I'm getting duplicated title and description.

How does this parameter affect page content: Paginates
  Which URLs with this parameter should Googlebot crawl: Every URL

What's the best way to configure URL parameter for Views "page" on Google Webmaster Tools?
Answer: Try Nodewords module for Drupal 6 or Meta tags for Drupal 7.
These modules will allow you configure the NOINDEX and NOFOLLOW parameters for listing pages in order to get only 1st page in SERP.
Comment: The question is how to change the settings on Google Webmaster Tools, not on the Drupal site.
Comment: Then you have asked question in wrong forum.
Comment: I didn't ask the question. Still, this is not the answer for the asked question.
Answer: Unfortunately I don't see a setting in Google Webmaster Tools to do this however, you could actually do this in your robots.txt file that ships with drupal by adding at the bottom:
Disallow: /*?page=
Disallow: /?page=&*
Disallow: /?page=0
Answer: There is no "best way" I think. It depends on your site niche.
I have a blog and it has page=X like URL params. I have set it as "paginates" and "Crawl all pages" same as your setup.
It now crawls and shows all pages.
That duplicate title problem is still there at my site. I don't mind it because I didn't receive any dupe problem from Google.
If you really want to change it, you can do it in template.php level.
function THEMENAME_preprocess_html(&$vars) {
 if (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0){
   $vars['head_title'] = str_replace('|', '('.t('Page @pager', array('@pager' => $_GET['page'] + 1)).') |', $vars['head_title'], 1);
 }
}

This will rewrite your HTML title tag's content to "My Blog Posts (Page 2) | MyAwesomeBlog" on Pages where a pager is set. We add 1 to the pager value because when you are on page=1, it's actually the second page for human users.


How to create EditText hint as Text with image in android

Question: How to create EditText hint/placeholder with Text & image in android. I write like this
<EditText
    android:id="@+id/name"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:lines="1"
     ................................
...............................

android:drwableLeft="@drawable/image1"
android:hint="enter name here"/>

Here we can see image & text (hint) within edittext but image still visible even after user enters something in that field. My requirement is if there is no text in EditText show hint with image, if  EditText is not empty hide hint text and image
Comment: You can use like this android:drawablePadding="10dp" property.
Comment: how can i put some gap between hint and drawable left
Comment: [ImageSpan](http://stackoverflow.com/a/33563267/3291140) should do the trick.
Answer: What you can do is set an drawableLeft as you did in your xml and add an addTextChangedListener to your EditText. When typing occurs this listener will be warned and you can check in the listener if the textsize is bigger than 0. If so, then just set the drawableLeft assigned in the xml programmatically to null.
@Override
public void afterTextChanged(Editable s) {
    if(s.toString().length() > 0) {
        editText.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
    } else {
        //Assign your image again to the view, otherwise it will always be gone even if the text is 0 again.
        editText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.image, 0, 0, 0);
    }
}

Answer: I did this by placing my EditText inside a FrameLayout, and then also including a TextView inside the FrameLayout.  The TextView serves as the hint text.  I have a drawableStart attribute on the TextView.  When the user starts typing the TextView is hidden using code similar to that in the accepted answer from Dion.


Class 'Illuminate\Routing\ControllerServiceProvider' not found While Upgrading from Laravel 5.1 to 5.2

Question: I have a Laravel 5.1 install that I am upgrading.  I meticulously followed the instructions available at https://laravel.com/docs/5.3/upgrade#upgrade-5.2.0 for the upgrade, including removing Illuminate\Foundation\Providers\ArtisanServiceProvider and Illuminate\Routing\ControllerServiceProvider from the config/app.php file (I am stressing this point, as googling for this issue has suggested this in every response).
Despite this, I am still getting this error when I run composer cache:clear
<code>[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Illuminate\Routing\ControllerServiceProvider' not found error
</code>
and see this error in my browser:
<code>FatalThrowableError in ProviderRepository.php line 146:
Class 'Illuminate\Routing\ControllerServiceProvider' not found
</code>
Thinking that perhaps references to these classes were being cached, I checked bootstrap/cache/services.json and removed the references from there as well and then ran composer dump-autoload but I am still getting this error.
I also made sure to copy over example config/app.php from Laravel 5.2 clean install example here: https://raw.githubusercontent.com/ziyed/Laravel-5.2/master/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php
I have read through the similar threads on StackOverflow and Laracast and tried tried to use the advice contained inside, but nothing seems to work.
Any help would be greatly appreciated. For reference, my dev setup is running on a local XAMPP stack under a Windows 10 OS.  The other environments are remote, using a traditional LAMP stack with Amazon Linux 2. I was trying to do the upgrade locally.
Comment: Please share more details  - have you checked in your whole application whether that class is referenced anywhere? Have you cleared your cache manually?
Comment: Does this answer your question? [Fatal error while upgrading Laravel 5.1 to 5.2](https://stackoverflow.com/questions/34395129/fatal-error-while-upgrading-laravel-5-1-to-5-2)
Answer: Illuminate\Routing\ControllerServiceProvider is not present anymore.
When I recently had to upgrade the same versions as you, I had to run composer update before and after removing Illuminate\Routing\ControllerServiceProvider::class and Illuminate\Foundation\Providers\ArtisanServiceProvider::class to make it work. Also worth to mention you need to clear bootstrap/cache. It worked for me.
Edit: i noticed now you tried the last step partially as well. You can remove all php files from cache.
Answer: I am closing this question, not because I found an answer, but because continuing down this path just didn't pass a cost/benefit analysis.  After upgrading to 5.2, the next upgrade would be 5.3, and the breaking changes between 5.2 to 5.3 is a lot higher than between 5.1 to 5.2. After some thought, it was obvious that the better approach would be a fresh install on my target version, and then start porting over each module in my project by copying over the views, updating the routing, and making changes to the controllers and middleware as needed.
Or just using Laravel Shift.
Thank you to everyone who chimed in with suggestions!


push_array between function with a call

Question: At the top of document I declared
$final = array();

Then I got the following functions
function delivery($optional = null){

   global $db;
   //$return = $_POST;
   if(!empty($optional['reportdate_from'])) {
    //$return1['from'] = $optional['reportdate_from'];
   }
   if(!empty($optional['reportdate_to'])) {
    //$return1['from'] = $optional['reportdate_from'];
   }
   $sth = $db->prepare("SELECT  DATE(date) Date, COUNT(number) totalCOunt FROM numbers GROUP BY  DATE(date)");
   $sth->execute();
   $result = $sth->fetchAll();
            $return1['name'] = 'W doręczeniu';
            foreach ($result as $row1) {
            $date1 =strtotime($row1['Date'])*1000;
            $return1['data'][] = array($date1, (int)$row1['totalCOunt']);
            }
return array_push($final,$return1);
// echo json_encode($final,true);

}
function delivered($optional){
   global $db;
   $return = $_POST;
   if(!empty($optional['reportdate_from'])) {
    //$return1['from'] = $optional['reportdate_from'];
   }
   if(!empty($optional['reportdate_to'])) {
    //$return1['to'] = $optional['reportdate_to'];
   }
   $sth = $db->prepare("SELECT  DATE(date) Date, COUNT(number) totalCOunt FROM numbers Where `return` = 1 AND rdate != '0000-00-00 00:00:00' GROUP BY  DATE(date)");
   $sth->execute();
   $result = $sth->fetchAll();

            $return1['name'] = 'Doręczone';
            foreach ($result as $row1) {
            $date1 =strtotime($row1['Date'])*1000;
            $return1['data'][] = array($date1, (int)$row1['totalCOunt']);
            }

return array_push($final,$return1);

}

and at the very bottom of the document I have got:
echo json_encode($final,true);

The overall output is [] No Properties
And Warning:  array_push() expects parameter 1 to be array, null given in
All the arrays are not null it only happens if they are array_push(ed)
Calling the functions.
 case "test": delivery($optional); break;
 case "test1": delivered($optional); break;

Why is this error occuring?
Comment: [`json_encode()`](http://php.net/manual/en/function.json-encode.php) does not take a boolean as it's second parameter. It takes an optional `BITMASK` as defined in the docs and an optional `depth` parameter...
Answer: You never did global $final inside your functions, so the global $final you defined as an array is out-of-scope/invisible/non-existent inside your function.
return array_push($final,$return1);

This line will create a NEW local $final, push $return1 on onto it, and return that new array to the calling context. And since you don't CAPTURE that return value anywhere, the array then simply gets tossed into the garbage.
If you had something like this:
case "test":  array_push($final, delivery($optional)); break;

then your code would have worked
Comment: Adding final on top and global $final isnide functions causes Warning:  array_push() expects parameter 1 to be array, null given other ideas?
Comment: Very fine that case line. ;) That's what I needed
Answer: You add to $final inside a function, but unlike javascript, php doesn't know about global variables unless you "include" them in your function with the keyword global or when you pass them as a parameter (which I prefer)

push_array between function with a call


Recover data from ubuntu encrypted drive (LUKS)

Question: I had a Host with Ubuntu 12.10 installed, and the entire harddrive was encrypted (with LUKS it appears), I remember the passphrase, but I have trouble to "open it".
I am now on a beta version of Ubuntu 14.04, installed on a new harddrive. the old hard-drive is also still connected. the new drive is sda and the old drive is sdb
when I try to open the drive in "files" it ask for the passphrase, and when entered says that it does not find a filesystem.
I googled it and found this:
sudo cryptsetup luksOpen /dev/sdb5 myopen

and
sudo mount /mnt/open

with a fstab like this
/dev/mapper/myopen /mnt/open ext4 defaults,noauto 0 1

but I get this error:
mount: wrong fs type, bad option, bad superblock on /dev/mapper/myopen,
       missing codepage or helper program, or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

Answer: After some trial and error, and some more google, I came accross the solution. I think others might enjoy this, so I answer myself:
it turns out that the drive is a LVM (http://en.wikipedia.org/wiki/Logical_Volume_Manager_(Linux))
so, to fix this I do the following:
install LVM (this is for ubuntu)
apt-get install lvm2

modprobe dm-mod

scan the disks for volume groups
vgscan

change volume group to the one I just found above, in my case ubuntu-vg
vgchange -ay ubuntu-vg

find out about my locical volumes:
lvs

create a place to mount it:
mkdir /mnt/open

then use the above information to mount the volume
mount /dev/ubuntu-vg/root /mnt/open -o ro,user

then you can go to the open disk like this
cd /mnt/open

in my case I just want to recover some important files, then reformat. so case closed
Comment: Thanks! Your answer helped me recover data from an encrypted Ubuntu 15.10 install that stopped booting. The LiveCD allowed me to mount the encrypted partition using the pass-phrase and see that the data was intact but when even that stopped working I thought I'd lost my chance at recovery. Ended up doing a parallel install on a fresh disk then used your guide for one last try. It worked saving me a lot of time and effort.
Comment: thanks for the editing help, I will try to get it right one day  :)


Integral of $\sin(\pi x) \cos(n\pi x)$ and $\sin(\pi x) \sin(n\pi x)$

Question: For an assignment, I am required to calculate the fourier series of this function:
$$ \\
f(x) = \begin{cases}
0 & -1 < x < 0\\
\sin(\pi x) & 0 < x < 1
\end{cases} $$
To do this, I need to find these integrals for $n \ge 1$:
$$\int_{-1}^1 f(x) \cos(n \pi x) \, dx$$ and $$\int_{-1}^1 f(x) \sin(n \pi x) \, dx$$. These are zero for the range where $f(x)$ is zero, and so I still need:
$$ \int_0^1 \sin(\pi x)\cos(n \pi x) \, dx$$ , and
$$ \int_0^1 \sin(\pi x)\sin(n \pi x) \, dx$$
But I'm having trouble with these. The only thing I can see to try is integration by parts, but I get a mess. The first one gives me:
$$ \frac{\sin(\pi x) \cos(n \pi x)}{n\pi} - \frac{1}{n}\int_0^1 sin(\pi x) \sin(n \pi x)$$
So this actually depends on the result of the other one, which seems.. slightly nice, I guess. But treating this integral the same way gives me:
$$ \frac{-\sin(\pi x) \cos(n \pi x)}{n \pi} + \frac{1}{n}\int_0^1 \cos(\pi x) \cos(n \pi x) \, dx$$
And it does look like this will end up with the original integral in it again after another iteration, but the algebra this is generating is already getting beyond me. Is there any easier way to do this that I've missed?
Answer: Try the product and sum formulas:
$$\sin x \cos y=\frac{1}{2}[\sin(x+y)+\sin(x-y)]\\
\sin x\sin y=-\frac{1}{2}[\cos(x+y)-\cos(x-y)]$$
Answer: I don't know Fourier series. But I know how to integrate.
$-2\sin(\pi x)\sin(n\pi x)= \cos\pi (1+n)x-\cos\pi (1-n)x$
$$-\int \sin(\pi x)\sin(n\pi x)dx=\frac{1}{2}\cdot\big(\int \cos\pi (1+n)xdx-\int\cos\pi (1-n)xdx\big)$$
Now integration is easy.


References on piecewise linear functions

Question: I've been looking for references on piecewise linear functions in analysis books but I can't find many. Some treat the subject a bit passing and not general. Do you know of any references that might be useful?
Thanks in advance.
Comment: Piecewise linear (or affine) **and continuous** ? Being restricted to a certain domain [a,b] and "clamped" at the border (with $f(a)=f(b)=0$) ?  In this case they can be considered as spline curves with degree 1. Otherwise, they have the fundamental property of being sums of (non necessarily symmetric) "tent functions".
Comment: @JeanMarie: I was thinking not continuous and not necessarily over a domain of the form [a,b].
Answer: There is a whole tome entitled Introduction to Piecewise Linear Topology by Rourke and Sanderson. It probably (almost certainly?) has too much information in comparison with what you want to know. But it also contains the basics.


How can I provide anonymous user to access my REST GET API without providing any auth information?

Question: The Drupal 8 REST UI configuration page asks me to select Authentication providers for GET method; otherwise, it doesn't allow me to export the REST request.
How can I provide anonymous user to access my REST GET API without providing any auth information?
Comment: That is done through `People -> Permissions`, but you most likely have to pick at least one authentication provider. I recommend cookie.
Comment: @tyler.frankenstein, as for Drupal 8.4, seems that no permissions available to be set there.
Answer: According to the Drupal documentation : https://www.drupal.org/developing/api/8/rest

Don't forget to grant the corresponding permission! In case of a decoupled site, you typically need to grant the authenticated user role permission to GET content. In case of a web service, you typically need to grant the anonymous users permission to GET/POST content. Grant them at /admin/people/permissions#module-rest, or using Drush: drush role-add-perm anonymous 'restful  ', for example: drush role-add-perm anonymous 'restful get entity:node'

basically add the anonymous permission for the GET resource.
Comment: I can confirm this works in 8.5
Comment: Does not work in Drupal 8.4
Comment: It works on Drupal 8.9 too
Answer: You could create your own authentication provider; it could then allow anonymous users access to your resource. It is not that difficult, the only thing I found is that you have to be careful to make sure the authentication provider only applies whe you specifically want it to. Look here for a tutorial:
http://enzolutions.com/articles/2014/12/28/how-to-create-an-authentication-provider-in-drupal-8/
Comment: Again, simple thing made complicated. Why anonymous users are denied access by default in the first place. I won't run Drupal 8 ever, I just installed it to benchmark its RestFUL API against other frameworks. A benchmark, Drupal 8 surely will lose.
Comment: Just ran the benchmark: Drupal 8 = 75 requests/second vs. another new framework (not PHP based) = 550 requests/second. Amazing. There will be no Drupal 9.
Comment: @W.M. Because maybe you don't want to allow anonymous users to get access to the endpoints, this is normal, some endpoints return information that should not be public.


Plotando Gráficos ggplot dentro de loop

Question: Estou querendo criar uma for usando ggplot:
Carteira<-cbind(A, B, C,D,E,F)

A, B, C,D,E,F sao dados no formato "zoo".
Meu código é:
 for(i in 1:6){

  ggplot(Carteira[,i], aes(Carteira[,i])) +
  geom_histogram(aes(y =..density..),
                 breaks=seq(-20, 20, by = 2),
                 col="black",
                 fill="blue",
                 alpha = .1) +
  geom_density(col=1) +
  labs(title="Histogram ") +
  labs(x="Returns", y="Count") +
  xlim(c(-20,20))
}

O curioso é que nada acontece. Nem menssagem de erro aparece.
Onde estou errando?
Answer: O problema é que você está dentro do loop então você tem que pedir explicitamente para dar print no gráfico do ggplot.
Por exemplo, no comando abaixo, nada vai aparecer:
for(i in 1:6) i

Já se você colocar print, os números aparecem:
for(i in 1:6) print(i)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

É a mesma coisa com o gráfico do ggplot. Por exemplo, o comando abaixo não plota nenhum gráfico:
for(i in 1:6) ggplot(mtcars, aes(mpg, cyl)) + geom_point()

Já colocando o print os 6 gráficos aparecem:
for(i in 1:6) print(ggplot(mtcars, aes(mpg, cyl)) + geom_point())

Answer: Cara tenta adicionar um print nesse seu ggplot:
     for(i in 1:6){

#print foi adicionado na plotagem do histograma para percorrer os índices

      print(ggplot(Carteira[,i], aes(Carteira[,i])) +
      geom_histogram(aes(y =..density..),
                     breaks=seq(-20, 20, by = 2),
                     col="black",
                     fill="blue",
                     alpha = .1) +
      geom_density(col=1) +
      labs(title="Histogram ") +
      labs(x="Returns", y="Count") +
      xlim(c(-20,20)))
    }

Plotando Gráficos ggplot dentro de loop


Statistical tests to do data quality checks

Question: I want to identify bad responses in the data we get from our vendors. To assess the quality of the data, what statistical tests can i apply to identify bad respondents?
I performed Discriminant analysis to identify the % similarity of responses among surveys completed by a particular interviewer. How can i further authenticate my findings?
(added from comments)
What i mean by bad responses is: Interviewers who have very high similarity in the responses they collect in the survey. they might tick for "4" for a particular question for all the respondents (Flat Liners or Speeders)
Suppose an interviewer has conducted 10 surveys and i notice similarity in the answers of those questionnaires for each question. Is there any statistical test which authenticates my finding that the interviewer has probably filled responses himself or has ticked the same response for each question? How can we check a particular data using Statistical tests? I hope i have clarified my question.
Comment: You need to tell us more about what you mean by "bad responses" and "bad respondents"; you also seem interested in "bad interviewers".
Comment: What i mean by bad responses is: Interviewers who have very high similarity in the responses they collect in the survey. they might tick for "4" for a particular question for all the respondents (Flat Liners or Speeders)
Comment: Suppose an interviewer has conducted 10 surveys and i notice similarity in the answers of those questionnaires for each question. Is there any statistical test which authenticates my finding that the interviewer has probably filled responses himself or has ticked the same response for each question??? How can we check a particular data using Statistical tests?? I hope i have clarified my question.. PLEASE HELP...
Comment: My first thought would have been to look at methods to detect *cheating* on multiple choice items, although methods to handle *extreme response style* or *inter-rater analysis* are likely candidates.
Comment: I'm not sure why you need a statistical test. If you suspect that the interviewer has ticked the same response for the same question across all interviews, then the sum or mean of responses for that interview can be examined. That will tell you absolutely that the same answer is chosen every time. Falsifying survey data requires another, trusted interviewer to interview the same respondent, so you have two results to compare.
Comment: I agree with Michelle, the best way to prevent bad interviewers is through project management techniques, rather than analysis techniques. Standard techniques include requiring supervisors to listen in on X% of calls, and re-contact Y% of calls to verify key datapoints. The client should listen in on both interviewer calls and supervisor calls.
Answer: The keywords to search for are "interviewer falsification". AAPOR/SRMS guidelines are a good starting place, and RTI system is useful, too. As far as I know the evidence, the interviewers may be able to get the first moments OK, but they have a more difficult time with higher order moments, so falsified data may be detected via unusual variances and correlations/crosstabs.
Comment: (+1) That looks indeed like the right keyword to search for!
Comment: Hi...thanks for your suggestions. I am using discriminant analysis to group the responses that a particular interviewer gets for a question which basically tells me the % of similarity of the groupings. But this is countered by saying that the reason you are having similar responses is because your questions are similar. Now how do i prove that my questions are not similar. Is there any statistical procedure for this...thanks a lot all of you for your help...
Comment: In psychometrics, somewhat similar ideas are covered under the umbrella of "divergent validity": if items are measuring something different, they should vary. That's again the second order moment issue of (co)variance between items. I am not even sure I see how you apply discriminant analysis here.
Answer: I don't know of a statistical test that does what you want, although there may be one. Probably, though, you will need to define "bad interviewer" more precisely.
There is some literature on interviewer effects, and that might be a place to start looking.
Answer: If your interviewers have completed more than 20 interviews you might consider the Wald-Wolfowitz test for randomness. Falsified data has a tendency to mix or cluster whereas randomly sampled data should exhibit a random order. Note that this only works for dichotomous variables.
Comment: Precisely what would you be testing for "randomness"?  At a minimum it seems your assertion about the "tendencies" of falsified data, in order to have some authority, needs to be circumscribed by a description of what range of applications you have in mind.  For instance, responses to polls and surveys and responses to sets of related questions would normally exhibit "clusters" and degrees of similarity.


Read php code on string without eval function

Question: I know eval() in php is to evaluate php code inside string. I also was create a simple template class with eval. But, in practice this way is not comfortable. Very hard to maintain. So, here the simple short snippet code as example
<code>function render($view,$data)
    {
        extract($data);
        ob_start();
        include SOMEPATH . 'views/' . $view . EXT;
        $result = ob_get_contents();
        ob_end_clean();

        $result = str_replace('<cihtml name="apa">',file_get_contents( SOMEPATH . '/views/sample.php' ),$result);

        echo eval( '?>' . $result);
    }
</code>
I can render it. But in some case, there is always problem where eval get error with specific reason.
Now, what I need here is the concept template parser without eval() function. Thanks for your advance.
Answer: Why reinvent the weel? Most people use frameworks for these kind of things.
Look into
http://phalconphp.com/
http://docs.phalconphp.com/en/latest/reference/volt.html
Comment: I know there are a lot of framework, but what I want is basic concept in making template engine without using eval function.
Comment: PHP originally was intended as a template language (code in html). When eval is the answer you are asking the wrong question. P


Similar arrays behaving different

Question: I'm writing an app with mongoose and Express, but before using mongoose I was using the standard MongoClient from mongodb. That returned me an array I could use to render my twig view just fine. However, after making the switch, the array from Mongoose is not working like I expected it to, case being that I can't properly select the array's key's values, like in this code example.
With mongoose:
router.get('/:page', function (req, res, next) {
    Page.find({'title': req.params.page.toLowerCase()}, function (err, page) {
        if(!Array.length) {
            next(createError(404));
            return;
        }
        res.send(page[0].title);
    });

Response is: nothing, blank.
For some reason, if I do page[0] or just page, it will return me the array like it should.
Without mongoose:
const MongoClient = require('mongodb').MongoClient;
    MongoClient.connect('mongodb://localhost/ezcm', function (err, db) {
        if (err) throw err;
        let dbo = db.db("ezcm");
        let query = {title: req.params.page.toLowerCase()};
        dbo.collection("pages").find(query).toArray(function (err, result) {
            if (!Array.isArray(result) || !result.length) {
                next(createError(404));
                return
            }
            db.close();
        });
    });

(ignore the extra bits of unrelated code)
Response: what I was looking for, like About me if it was localhost:3000/about.
Seems like they are both arrays, but different kinds of arrays? As a beginner, I can't quite distinguish and work with them. Help me!
Thanks in advance.
Comment: Why are you doing `if(!Array.length)` instead of `if (!page || !page.length)`?  `Array.length` has nothing to do with `page` at all.
Comment: @jfriend00 oh, i changed that already, but as expected no effect with my issue
Comment: What type of object is `page` when you `console.log` it?
Comment: @Houseman object Array
Comment: @MucaP Does the zeroth index exist inside this array? Does it have a title property?
Answer: Use JSON.parse(array) to the result, mongoose loves to handle their objects and arrays differently than the standard JSON.
Comment: Nope, fails: SyntaxError: Unexpected token _ in JSON at position 2
    at Object.parse (native)

Similar arrays behaving different


Buscar CEP React?

Question: Estou com uma dificuldade em implementar uma consulta por CEP no React
O que desejo fazer e o usuário informa o número do CEP no campo <input/> e automaticamente os campos do formulário são preenchidos.
O que preciso fazer para que o formulário seja populado com a busca pelo CEP e ao tentar fazer da forma que implementei apresenta o seguinte erro:

:3000/#/cadastro-clientes:1 Access to fetch at 'https://viacep.com.br/ws/-/json/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.viacep.com.br/ws/-/json/:1 Failed to load resource: net::ERR_FAILED

Porém a busca e feita apesar do erro.
handleChange = (event) => {
    const value = event.target.value;
    const name = event.target.name;
    this.setState({ [name] : value })
    this.buscarCep();
}

buscarCep() {
    if(this.state.cep.length < 9) {
        return;
    } else {
        fetch(`https://viacep.com.br/ws/${this.state.cep}/json/`)
        .then((res) => res.json())
        .then((data) => {
         this.state.uf = data.uf;
         this.state.cidade = data.localidade;
         this.state.uf = data.uf;
         this.state.bairro = data.bairro;
         this.state.logradouro = data.logradouro;
        });
    }
}

render( ){
    return (
        <Card>

                    <FormGroup id="inputCep" label="CEP: *" >
                        <InputMask id="inputCep"
                               className="form-control"
                               name="cep"
                               mask="99999-999"
                               value={this.state.cep}
                               onChange={this.handleChange}/>
                    </FormGroup>

                    <FormGroup id="inputLogradouro" label="Logradouro:" >
                        <input type="text" id="inputLogradouro"
                               className="form-control"
                               name="logradouro"
                               value={this.state.logradouro}
                               onChange={this.handleChange}  />
                    </FormGroup>

                    <FormGroup id="inputBairro" label="Bairro:" >
                        <input type="text" id="inputBairro"
                               className="form-control"
                               name="bairro"
                               value={this.state.bairro}
                               onChange={this.handleChange}  />
                    </FormGroup>

                    <FormGroup id="inputCidade" label="Cidade:" >
                        <input type="text" id="inputCidade"
                               className="form-control"
                               name="cidade"
                               value={this.state.cidade}
                               onChange={this.handleChange}  />
                    </FormGroup>

                    <FormGroup id="inputUf" label="UF:" >
                        <input type="text" id="inputUf"
                               className="form-control"
                               name="uf"
                               value={this.state.uf}
                               onChange={this.handleChange}  />
                    </FormGroup>

        </Card>
    }
}

Comment: deu certo .....
Comment: Benvindo ao SO! A resposta de @novic é um exemplo completo e funcional. Caso tenha sanado dúvidas ou sido importante, sugiro que você marque como resposta, daí outros usuários com a mesma dúvida verão que sua pergunta foi respondida.
Answer: Problemas:

Quanto for utilizar o fetch precisa especificar o seu modo de operação que em seu caso e
{ mode: 'cors' }

esse objeto sendo o segundo parâmetro quando o verbo de requisição for GET.

Um outro ponto é que não foi utilizado o método setState para mudar o estado antigo para o novo objeto de valores que foi requisitado pela fetch e também não coloque os dados de um objeto direto na raiz do seu this.state sempre crie chaves, porque, com isso abre para ter novos estados nesse componente.

Como foi relatado na pergunta, deseja que em um determinada quantidade de números forem digitados (no caso é 8, fato descrito na API) acione a busca dinamicamente, vale muito lembrar que o this.setState tem um segundo parâmetro que é uma função e nessa função significa que o estado já foi alterado com isso this.state.data.cep já tem todos os números digitados e pode então utilizar a função this.buscarCep() para verificar se já pode fazer a sua requisição, do outro jeito o estado ainda não foi alterado cansando problema pela falta de dígitos nesse número.

Fiz um exemplo mínimo:

const dataInit = {
  cep: "",
  logradouro: "",
  complemento: "",
  bairro: "",
  localidade: "",
  uf: "",
  ibge: "",
  gia: "",
  ddd: "",
  siafi: "",
}
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: dataInit
    }
  }
  url = () => {
    return `http://viacep.com.br/ws/${this.state.cep}/json/`;
  }
  handleChange = (event) => {
      const value = event.target.value;
      const name = event.target.name;
      this.setState({ [name] : value }, () => {
        this.buscarCep();
      });
  }

  buscarCep() {
      if(this.state.cep.length < 8) {
          return;
      } else {
           fetch(this.url(), {mode: 'cors'})
            .then((res) => res.json())
            .then((data) => {
                if (data.hasOwnProperty("erro")) {
                    this.setState({data: dataInit});
                    alert('Cep não existente');
                } else {
                    this.setState({data});
                }
            })
            .catch(err => consolelog(err));
      }
  }
    render() {
      return (

           Digite o cep:
            <input
               name="cep"
               maxlength={8}
               value={this.state.cep}
               onChange={this.handleChange}
            />

Endereço/Rua: {this.state.data.logradouro}

Complemento: {this.state.data.complemento}

Bairro: {this.state.data.bairro}

Cidade: {this.state.data.localidade}

UF: {this.state.data.uf}

IBGE: {this.state.data.ibge}

Gia: {this.state.data.gia}

DDD: {this.state.data.ddd}

Siafi:{this.state.data.siafi}

      )
    }
  }
ReactDOM.render( <App/> , document.getElementById('root'));

Buscar CEP React?