I have column entries mixed with multiple "_" character, how can I replace the figure before the first "_" with a function while leaving the rest

Question: I have column entries that have characters mixed with multiple '_ ' (e.g. 67_0000100-478_NA_d202xz97406_t17199m2156).
Using SQL (DB is Postgres), I want to replace only the figure before the first '_'  with a function (e.g. its square + itself) while leaving the remaining character the same way.
Current entry: 67_0000100-478_NA_d202xz97406_t17199m2156
Desired output: 4556_0000100-478_NA_d202xz97406_t17199m2156
Based on my research and exploring useful closely related previously answered questions on this platform, I figured most problem cases were for replacing/ deleting some texts when the text entries only have the character occurring just once.
My progress so far (Updated based on suggested comments), however I am getting syntax error (I am not an SQL expert):
CREATE OR REPLACE VIEW public.v_events AS
SELECT uid, serial_id, session_id, start_time, code, event_name, end_timestamp, temp_code
FROM public.events_data
update public.v_events
    set uid = concat(
                       (split_part(uid, '_', 1))::int^2 + (uid),
                       substr(uid, strpos(uid, '_')))

Note: The uid is the column entry to be replaced with the function (uid^2 + uid). I understand that can be done using Power() in SQL.
What I need done is to create a view (public.v_events) of the original table (public.events_data) and replace only the figure before the first '_' (e.g. 67) with a different function (uid^2 + uid).
I would really appreciate help from anyone?
Comment: Are you sure this is [tag:postrgresql]? The question is tagged with it, but `charindex` isn't a PG function
Comment: Postgres has similar function `position()` but definitely does not support `charindex`, which is SQL Server.
Comment: @Mureinik my database is actually Postgresql and not SQL Server
Comment: Thanks @Stu, I agree
Comment: @Dipops I edited my MSSQL version below to convert it to a working Postgres version.
Answer: On the assumption this is actually SQL Server (because of the use of charindex), here is a simple method you can use.
If your database actually is Postgres it has easily substitutable string functions you can use.
select mytext, Stuff(mytext, 1, p.pos, n.v*n.v) as Replaced /* implement desired function here */
from t
cross apply (values(CharIndex('_',mytext)-1))p(pos)
cross apply (values(Try_Cast(Left(mytext,p.pos) as int)))n(v)

Edit
Converting the above to a Postgres version:
select MyText, overlay(MyText placing cast(n.v*n.v as varchar(5)) from 1 for p.pos)
from t
join lateral (select position('_' in mytext)-1 pos) p on true
join lateral (select cast(Left(mytext,p.pos) as int) v)n on true;

DB<>Fiddle example
Answer: Getting the square of the first element can be done e.g. using split_part() this can then be concatenated with the rest of the string:
update the_table
    set the_column = concat(
                       (split_part(the_column, '_', 1))::int^2,
                       substr(the_column, strpos(the_column, '_'))
                     )

(split_part(the_column, '_', 1))::int returns the string before the first _ as an integer. It will result in an error if the value cant be converted to an int.
If you don't want to change the table, use that expression in a SELECT statement:
SELECT concat((split_part(uid, '_', 1))::int^2 + (uid),
               substr(uid, strpos(uid, '_'))) as uid,
       serial_id,
       session_id, start_time, code, event_name, end_timestamp, temp_code
FROM public.events_data

Comment: I updated the question based on your suggestion. I am getting syntax error.
Comment: You can't put an UPDATE statement into a view. You need to use a SELECT expression


Como fazer select MySQL utilizando input tipo date com php?

Question: Estou tentando listar determinadas colunas do banco de dados pela data mas não funciona.

Segue trecho do código:
<?php
if($_GET['busca'] == "data") {
  $datai = date('Y/m/d', strtotime($_POST['data']));
  $nome  = $_POST['nome'];
  $preco = $_POST['preco'];
  $qtd   = $_POST['qtd'];

  $query = mysqli_query("SELECT data, nome, preco, SUM(preco) AS pr, SUM(qtd) AS qtd, date_format(data, '%d/%m/%Y') AS data FROM tbl_carrinho WHERE idGarcon='$garcon' AND data BETWEEN '$datai' AND '$dataf' AND time BETWEEN '$hora1' AND '$hora2' GROUP BY data") or die(mysqli_error());
}

while($resultado = mysqli_fetch_array($query)) {
  $data = $resultado['data'];
  $nome = $resultado['nome'];
  $qtd = $resultado['qtd'];
  $preco = $resultado['preco'];
?>

  <?php echo $data ?>
  <?php echo $nome ?>
  <?php echo $preco ?>
  <?php echo $qtd ?>

?>

Answer: Bom, se caso a coluna de data da sua tabela mysql esteja no formato correto tipo (date=Y-m-d), eu converteria a data de acordo com a tabela mysql.
EX:
Se você tem os dados armazenados cujo as datas estejam dessa forma '2017-08-15', o ideal é que você converta sua variável:
$datai = date('Y/m/d', strtotime($_POST['data']));

para
$datai = date('d-m-Y', strtotime($_POST['data']));

A mesma coisa eu faria com a variável $dataf e na instrução mysql eu faria da seguinte forma:
"SELECT data, nome, preco, SUM(preco) AS pr, SUM(qtd) AS qtd, data FROM tbl_carrinho WHERE idGarcon='$garcon' AND data BETWEEN ".$datai." AND ".$dataf." AND time BETWEEN ".$hora1." AND ".$hora2." GROUP BY data"

Procure não colocar suas variáveis utilizando aspas simples dentro de aspas duplas, pois o php pode interpretar isso como uma string e não como uma variável.
EX.
Problema:
$sql = "SELECT * FROM table WHERE col='$val'";

Solução alternativa
$sql = "SELECT * FROM table WHERE col=".$val."";

ou
$sql = "SELECT * FROM table WHERE col = {$val}";

Espero ter ajudado.
abs.
Answer: Primeiro, você só está passando uma data, se quer filtrar por um período entre duas datas é melhor passar as duas datas (logicamente) e caso ele digite só uma ele pegue os registros somente dessa data.
Primeiro crie os campos para data inicial e data final no formulário.
Veja se o método do seu form é POST ou GET e altere o código.
O código ficaria mais ou menos assim:
<?php
if(isset($_POST['dataIni']) && (isset($_POST['dataFin']))) {
  $dataIni = date('Y/m/d', strtotime($_POST['dataIni']));
  $dataFin = date('Y/m/d', strtotime($_POST['dataFin']));
  $nome  = $_POST['nome'];
  $preco = $_POST['preco'];
  $qtd   = $_POST['qtd'];

  $sql = "SELECT data, nome, preco, SUM(preco) AS pr, SUM(qtd) AS qtd, date_format(data, '%d/%m/%Y') AS data FROM tbl_carrinho WHERE idGarcon='$garcon' AND data ";

  if ($dataFin != '') {
    $sql .= "BETWEEN '$dataIni' AND '$dataFin' GROUP BY data"
  else
    $sql .= "= '$dataIni' GROUP BY data"

  $query = mysqli_query($sql) or die(mysqli_error());

  while($resultado = mysqli_fetch_array($query)) {
?>

  <?php echo $resultado['data'] ?>
  <?php echo $resultado['nome'] ?>
  <?php echo $resultado['preco'] ?>
  <?php echo $qtd ?>

<?php } } else { echo 'Informe o período!'} ?>

Não tive tempo de testar.
Answer: Aparentemente, você não está utilizando corretamente a linguagem SQL.
A instrução GROUP BY geralmente é usada com funções agregadas (COUNT, MAX, MIN, SUM, AVG) para agrupar o conjunto de resultados por uma ou mais colunas.

Exemplo do uso: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_groupby

O melhor a ser usado seria ORDER BY
A instrução ORDER BY é usada para classificar o conjunto de resultados em ordem ascendente ou decrescente.

Exemplo do uso: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_orderby

ficaria dessa forma a linha do código já alterada:
$query = mysqli_query("SELECT data, nome, preco, SUM(preco) AS pr, SUM(qtd) AS qtd, date_format(data, '%d/%m/%Y') AS data FROM tbl_carrinho WHERE idGarcon='$garcon' AND data BETWEEN '$datai' AND '$dataf' AND time BETWEEN '$hora1' AND '$hora2' ORDER BY data") or die(mysqli_error());

// foi utilizado order by ao invés de group by


Como forçar o download de um arquivo de texto?

Question: Como forçar o download de um arquivo de texto?
Tenho esse código porém não é feito o download, quando clico no link seu contéudo é exibido pelo navegador.
<?php

include "conecte.php";

$querymail = mysql_query("select cod,name from usuarios");
fopen("listar.txt", "w+");
while($data = mysql_fetch_array($querymail)) {
    $log = str_pad($data[0], 30, " ", STR_PAD_RIGHT);
    $log2 = str_pad($data[1], 30, "0", STR_PAD_RIGHT);
    if (!$savelog = fopen('listar.txt', "a")){
        exit;
    }
    if (!fwrite($savelog, $log . $log2. "\r\n")){
        exit; fclose($savelog);
    }
}
?>

Clique aqui para baixar

Comment: Qual é a sua dúvida?
Comment: Colega, o arquivo será criado onde estiver seu PHP. Para baixar é só clicar em salvar como ali no final. Qual é a dúvida?
Comment: Preciso baixar o arquivo gerado em uma pasta no pc quando clicar em (Clique aqui para baixar) ? Como está ele somente abre no navegador...
Comment: O servidor não tem conhecimento das pastas do cliente, logo o arquivo vai para a pasta padrão de download definida pelo navegador.
Comment: Já observei na pasta padrão download e não consta...
Comment: O texto é exibido em uma página quando clica no link isso? o correto seria fazer o download??
Answer: Crie um novo arquivo(download.php) nele defina o cabeçalho a ser enviado ou seja em qual formato o navegador deve interpretar a informação abra o arquivo e envie para o cliente.
download.php
header('Content-disposition: attachment; filename=lista.txt');
header('Content-type: text/plain');
$str = file_get_contents('log/lista.txt');
echo $str;

Chamada:
Clique aqui para baixar

Um opção mais otimizadada, citada pelo Wallace Maxters é trocar file_get_contents() por readfile()
header('Content-disposition: attachment; filename=lista.txt');
header('Content-type: text/plain');
readfile('log/lista.txt');

Relacionado:
PHP readfile vs. file_get_contents
Comment: Funcionou perfeitamente!
Comment: Rray, se importa com uma sugestão? Usar `file_get_contents` seguido de um `echo` é um pouco de desperdício de memória (dependendo do tamanho do arquivo). `file_get_contents` lê o arquivo e retorna sua string, e no seu caso, salva numa variável. Nesse caso, utilize `readfile` que já lề o arquivo imprimindo o conteúdo imediatamente, sem armazenar nada em memória
Comment: @WallaceMaxters `readfile(file_get_contents('log/lista.txt'));` ?
Comment: Não, é assim: `readfile('log/lista.txt')`
Comment: @WallaceMaxters isso :D, foda q documentação do php ta bloqueada aqui kkk wtf O.o?
Comment: Quem sabe você mesmo responda: [Qual é a diferença entre readfile e file_get_contents?](http://pt.stackoverflow.com/questions/126718/qual-%C3%A9-a-diferen%C3%A7a-entre-readfile-e-file-get-contents)
Comment: @WallaceMaxters LOL olha a edição
Comment: Linka eu ae também, kkkkk
Answer: A questão foi respondida, mas existe uma outra solução ou complemento. Você pode utilizar o atributo download numa tag a:
 Texto

Exemplo:

 Baixar

Essa forma você irá baixar o HTML dessa página, ao invés de acessar normalmente.
Isso é novo, inserido no HTML 5!
Suporte:
Chrome: 14.0+
Internet Explorer: 13.0+
Mozilla: 20.0+
Safari: Não suportado
Opera: 15.0+

Comment: +1, eu acho uma ideia bacana, se for no caso de alguém que use apenas o `HTML` , por exemplo


Display newly added form element at the bottom

Question: I altered a form, and I added a <code>$form['priorities']</code> form element.
Why is it appearing right after the title form element, and not at the bottom of the form? How can I make it at the bottom?
Comment: You can assign #weight attribute for that. I mean when you alter form assign #weight to your new field and give their weight last compare to other component.
Answer: Like KrishaWeb said you need to add a #weight attribute to your new element.
It would look like:
<code>$form['priorities'] = array(
  ...
  '#weight' => 99,
  ...
);
</code>
You can also set weights on the other form elements so the form is explicitly in order.


What do P1 M2 M3 P4... mean when describing scale intervals?

Question: I have seen scale intervals described using P1 M2 M3 P4 etc and it's not clear what the P and M mean. I am guessing the M means major because I've also seen lower case m which probably means minor. But the meaning of P is not clear.
For example, I have seen the major scale (Ionian mode) described as
P1 M2 M3 P4 P5 M6 M7 P8

Comment: I guess, that P stands for *perfect*, since there is no minor nor major octave.
Comment: @guidot  - there also is no major or minor 4th and 5th.
Answer: P=perfect, M=major, m=minor, +=augmented, o=diminished.
The P is octave, fourth and fifth,as they appear the same in major or minor, unchanged from each.
Augmented (a semitone larger than P4, P5, etc.)is usually designated '+' sometimes '#', in a chord; diminished is 'o' or 'b' in a chord, occasionally '-', but that can get confused with the NNS '-' for minor. Not seen A5, but that could get mixed up with an A power chord!
So, E+ would be spelled E G# B#, with the 5 (B) sharpened. Eo is E G Bb. There's a lot of crossover between the naming of chords and intervals.
Comment: Note that "perfect" also applies to *unisons*, as in the 'P1' designation in the original question.
Comment: @ToddChaffee I personally have seen both of those notations, and I expect most learned musicians, if they haven't seen them, would understand them.
Comment: Exploring some other resources I have seen A5 for augmented perfect interval, and d5 for diminished. Is that something that is also in common use as an alternative to + and o? And would it be +5 and o5 for example? Maybe you could add some examples to your answer?
Answer: Intervals are two general categories perfect and imperfect. The perfect intervals - designated with 'P' - are unison, octave, fourth, and fifth.
P1 perfect union
P8 perfect octave
P4 perfect fourth
P5 perfect fifth

The imperfect intervals are second, third, sixth, and seventh. The imperfect intervals are of two basic qualities major 'M' and minor 'm'.
m2 minor second
M2 major second
m3 minor third
M3 major third
m6 minor sixth
M6 major sixth
m7 minor seventh
M7 major seventh

Each of the intervals can also be described as diminished 'd' or augmented 'A.' Diminished means one half step smaller than a perfect or minor interval, and augmented means one half step bigger than a perfect or major interval. Examples:
d5 diminished fifth
A4 augmented fourth
A2 augmented second (commonly found in the harmonic minor scale)
A6 augmented sixth (used with the various augemented sixth chords)
...etc

Keep in mind some interval pairs are enharmonic equivalents meaning their distances are the same, but their names are different:
P1 perfect unison = d2 diminished second
P8 perfect octave = A7 augmented seventh
m7 minor seventh = A6 augmented sixth

...some of those enharmonic equivalent names are a little strange and would be used in special notation situations.
The some other details to consider. 'Tritone' is a special name for the d5. Also, there are compound intervals which are bigger than an octave, ex. M10 major tenth = P8 + M3.
Check out the Wikipedia page for intervals for a more complete overview.
Comment: Never heard of 'imperfect' intervals. Just because they're not 'perfect', does that really make them imperfect?
Comment: @Tim: Yes. "imperfect interval", "imperfect consonance", etc. You can use "imperfect" in context to mean the intervals not union, fourth, fifth, octave, generally it should convey your are discussing major/minor defining elements - scale degrees or chord intervals. It's common usage... https://www.google.com/search?tbm=bks&q=music+imperfect+interval
Comment: So common, that in 60+ yrs of playing, I'vee never heard it! Perhaps not to the East of the pond! And won't imperfect consonance be the same as dissonance?!
Comment: I suppose it depends on what you read. No, imperfect consonance doesn't equal dissonance. A third is an imperfect consonance, but seventh is an imperfect dissonance. Can't say I've heard that particular wording "imperfect dissonance." The concern seems to be mostly between imperfect and perfect consonances like thirds versus perfect fifths. While both are consonances their treated different re. voice leading and at cadences.
Comment: One of my favorite uses of the term is the much simplified voice leading rule of thumb that goes something like: _similar motion only to imperfect consonances_. That's concise, positive wording that covers the prohibition on parallel/direct 5ths & 8vas.


Pandas dataframe split based list of column values

Question: I have a large data set of regions, I want to split the datframe into multiple dataframes based on the list of regions.
Example:
regions         val1    val2
A                1        2
A                1        2
B                1        2
C                1        2
D                1        2
E                1        2
A                1        2

I want to split the above dataframe by grouping (A,E), (B,C,D)
DF1:
    regions         val1    val2
    A                1        2
    A                1        2
    E                1        2
    A                1        2

DF2:
    B                1        2
    C                1        2
    D                1        2

I tried this by manually specifying df[(df['regions'] == 'A') | (df['regions'] == 'E')]. I want to avoid manually specifying these regions codes while creating the dataframes. I'm quite new to pandas. Is there anyway to do it?
Answer: You can create dictionary of DataFrame for avoid manually creating DataFrames with dictioanry comprehension and Series.isin and boolean indexing for filtering:
L =  [('A','E'), ('B','C','D')]

dfs = {'_'.join(x):df[df['regions'].isin(x)] for x in L}
print (dfs)
{'A_E':   regions  val1  val2
0       A     1     2
1       A     1     2
5       E     1     2
6       A     1     2, 'B_C_D':   regions  val1  val2
2       B     1     2
3       C     1     2
4       D     1     2}

For select each DataFrame use key:
print (dfs['A_E'])
  regions  val1  val2
0       A     1     2
1       A     1     2
5       E     1     2
6       A     1     2

print (dfs['B_C_D'])
  regions  val1  val2
2       B     1     2
3       C     1     2
4       D     1     2

Maanually solution is:
df1 = df[df['regions'].isin(('A','E'))]
print (df1)
  regions  val1  val2
0       A     1     2
1       A     1     2
5       E     1     2
6       A     1     2

df2 = df[df['regions'].isin(('B','C','D'))]
print (df2)
  regions  val1  val2
2       B     1     2
3       C     1     2
4       D     1     2


Book for introductory nonparametric econometrics/statistics

Question: My work implies a lot of econometrics, and I had a good formation about it. Nevertheless, I am regularly faced with some semi or non parametric techniques (for instance I had to use quantile regressions, partial estimation, or nonparametric estimation of whole distribution estimations), and I had no courses about it, neither in statistics or econometrics.
So my question is which book would you recommend for someone to have both a good overview and a logical presentation of this domain ? I would like to have a good background for these techniques. I precise that I have a graduate level in econometrics and applied statistics, so some maths are fine, but with some intuition is very good too !
Thanks in advance
Answer: I would recommend two books if you are interested in smoothing techniques, especially in density estimation and regression (rather than in tests that don't require classical normality assumptions, which are often based on ranks rather than the raw data):

Nonparametric and Semiparametric Models by Härdle, Müller, Sperlich, and Werwatz
Li and Racine's Nonparametric Econometrics: Theory and Practice

The first is much slimmer, a bit more introductory, with lots of examples and illustrations. It covers histograms, nonparametric density estimation, nonparametric regression, semiparametric and generalized regression models, single index models, generalized partial linear models, additive models and their marginal effects and generalized additive models.
The second tome covers nonparametric kernel methods, semiparametric methods, consistent model specification tests, nonparametric nearest neighbor and series methods, and some time series, simultaneous equations, and panel data models at the end. There is not too much about QR in this book. Koenker's QR would make a nice supplement.
It is also worth mentioning some other books. While comprehensive and worth reading later, I found Pagan and Ullah to be a difficult first introductions to this material. I have heard good things about Yatchew's Semiparametric Regression book, but I have not read it myself.
Answer: There is a recent title by Henderson/Parmeter: Applied Nonparametric Econometrics. As the name suggests, its focus is more applied than that of Li and Racine, although it does devote quite some attention to theoretical underpinnings, too.
Compared to the titles mentioned by @Dimitriy, it (unsurprisingly given its more recent date) surveys many of the recent developments in for example the area of nonparametric instrumental variables or panel data estimation.
What I additionally like a lot (probably in line with many CVers) is its usage of R as well as...cross-validation ;-).
Answer: The online StatSoft textbook is a good place to start.
Comment: Welcome to CrossValidated! It does look like a useful resource, but could you add a few sentences summarizing the contents or explaining why you like it.
Comment: Welcome to the site. Please don't sign your posts. Your username & a link to your userpage are automatically added to all your posts. Since you are new here, you may want to take our [tour](http://stats.stackexchange.com/tour), which contains information for new users. (I'm not the downvoter, btw.)


My react application is not running and getting error

Question: My react application is not running with npm start and getting high severity vulnerability. I tried npm audit fix --force but still not luck. Need help to understand how to fix it.
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using email@example.com
3 info using firstname.lastname@example.com
4 verbose stack Error: missing script: start
4 verbose stack     at run (C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:155:19)
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\lib\run-script.js:63:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:116:5
4 verbose stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:436:5
4 verbose stack     at checkBinReferences_ (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:391:45)
4 verbose stack     at final (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:434:3)
4 verbose stack     at then (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:161:5)
4 verbose stack     at ReadFileContext.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\read-package-json\read-json.js:350:20)
4 verbose stack     at ReadFileContext.callback (C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\graceful-fs.js:123:16)
4 verbose stack     at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:264:13)
5 verbose cwd C:\Users\kunal.vijan\react-app
6 verbose Windows_NT 10.0.19042
7 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
8 verbose node v14.6.0
9 verbose npm  v6.14.6
10 error missing script: start
11 verbose exit [ 1, true ]

Comment: Make sure you are in the right project location (root path) to run `npm start`
Comment: You have to run npm scripts from the root directory where package.json is located
Answer: It appears that you are using old version of node 14.x.. You should do following would help application up on npm start,

Remove node_module folder
Remove package.lock.json file.
Check node version in you machine execute command node -v
If it is not 16.x.x. execute nvm use 16.15.1
Execute npm install
Execute npm start


Degrees of freedom for linear regression

Question: I'm reading on a text book about linear regression, and when I thought I finally understood degrees of freedom, I found a statement that made me doubt what I know so far. Well it's in the context of a simple linear regression (1 input).

The orange, blue and green squares
  indicate the MSEs associated with the corresponding curves in the lefthand
  panel. A more restricted and hence smoother curve has fewer degrees
  of freedom than a wiggly curve—note that in Figure 2.9, linear regression
  is at the most restrictive end, with two degrees of freedom.

What degree of freedom they talking about in here?
What I know is that: df(regression)=p with p is the number of features used. So for this case it must be 1.
df(residuals)=n-(p+1).
df(total)=n-1.
n is the sample size.
Any help on what that 2 might be?
Here is the two panels of the figure 2.9.
Comment: My guess is the authors counted 1 for the intercept and 1 for the slope (aka, the 1 you took from n in your question). The orange line is straight so it should be a one-predictor regression.
Comment: Could you give us the full quote and name of the textbook?
Comment: Yes of course, it's from Introduction to statistical learning. The full quote is: "A more restricted and hence smoother curve has fewer degrees
of freedom than a wiggly curve—note that in Figure 2.9, linear regression
is at the most restrictive end, with two degrees of freedom."
Comment: I am more impressed that you understand the degrees of freedom of the locally fitting model, @YoussefEsseddiq :). Way harder to compute, too.
Comment: In the first graph, x axis is labeled "Flexibility". What does it mean? Another name for degree of freedom?
Comment: Penguin_Knight That's what i assumed at the end that, they are talking about degrees of freedom for yi hat (estimate of yi). So the intercept and slope are the ones free to vary, hence 2 dfs. Don't know how accurate is this reasoning tho.
Comment: a_statistician.. well formaly it's the degree of freedom on the x axis, but they call it flexibility for simplification matters.
Answer: I second @Penguin_Knight 's assertion in the comments: The second loss of d.f. comes from the intercept term in $\hat{y}=\hat{\beta_0} + \hat{\beta_1}x_1$. Every term you must estimate removes a degree of freedom from the residuals.
Most texts I have seen denote $\text{df(residuals)} = n - p$, where $p$ is the number of parameters you estimated in the model (so for linear regression, the number of covariates plus one).
Answer: This is about overfitting. You can fit a higher order polynominal to the curve and archive lower MSE (1st Figure). In your case you have a simple function $f(x)$ with $x$ having 1 dimension. Now you can try to fit a linear curve $\hat f(x) = ax + b$ or a higher order polynomal like $\hat f(x) = ax^3 + bx^2 + cx + d$ using linear regression (2nd Figure). You are still learning linear parameters $a,b,c,d$ by solving $\min_{a,b,c,d}(\hat f(x) - y)^2$, hence linear regression.
However, this might overfit on the training data and perform worse on your actual use case. (1st Figure)
Comment: I think OP is asking why the simplest model appears to be a straight line but in the text it was described to have 2 degrees of freedom.
Comment: I quess you are right. Your comment is already the answer then.


Is a section of Prelude from the JSB Partita No. 3 for Violin Solo (BWV 1006) commonly repeated or missing from the score?

Question: I am trying to learn this solo, but to better my sounds, I am trying to play along to a recording once I get it down with a metronome. IN measure 58 there seems to be a repeat, however, in every performance I can find that isn't in the score. That or they are playing a totally different part not in the score.
This score is exactly the same as what I have in my book of classical tunes.
https://musescore.com/user/27667841/scores/6551312
Here is an example of someone playing this extra section.
Comment: @musicamante It would be helpful to turn these comments into an answer so that users can see that it has one.
Comment: That score doesn't absolutely seem very reliable, it's probably just a "simplified" version. There's nothing "repeated", it's missing more than half of that prelude, and that's a lot of very important stuff too. Why don't you check it on [imslp.org](https://imslp.org/wiki/6_Violin_Sonatas_and_Partitas,_BWV_1001-1006_(Bach,_Johann_Sebastian)), for example?
Comment: Actually, even between those printed versions there are some drastic differences in the second half, but this seems to be what I hear most often. https://imslp.simssa.ca/files/imglnks/usimg/6/6e/IMSLP250590-SIBLEY1802.21004.93cd-39087009905870score.pdf
Comment: What drasticly different versions are you referring to?
Comment: Look at this version (page 47):

https://imslp.simssa.ca/files/imglnks/usimg/b/b4/IMSLP237324-SIBLEY1802.15620.895b-39087009905888score.pdf
Comment: Measures 55-123 are the missing ones from this "simplified" version.
Comment: The last version you linked is actually missing 2 *pages* of the book... That's not a "version" problem, but a scanning one.
Answer: As many examples can be seen in various reliable editions of the piece (for example, at imslp), the only actual differences are mostly ornaments, writing of voices, technique markings and slurs, stems/flags/groupings and some dynamics, while the structure remains intact as it can be listened in the embedded video as well as thousands of other audio/video sources around the web.
The score reported in the link is a shortened version, probably intended for beginners.
On a personal note, I don't really see the point in skipping so much important material, as more than half of the piece is missing, the missing parts are not that difficult compared to what's left (and they are very important for its structure too): it is a difficult piece, there's no benefit in shortening to make it "easier", if the result completely denaturalize it.
Comment: I think the purpose of doing so in the book I was using is that it is a classical fakebook, and they want things to fit on 1-2 pages where possible. In that sense, It's a cool survey of the styles, but now I know that if I like a piece I will need to get the original. It's a cool way to work on sight reading and learn about composer's styles, without having to invest too much time into a piece you may not like.
Comment: @bartcubrich I see your point, but I still believe it's not a very good practice: as said, that's not an easy piece, and if you're going to play it (at least on the violin) you probably already know that style. Also, a "fakebook" would make sense for excerpts, short melodies, more or less as they do with common themes with children methods (the usual "Ode to Joy", for instance). With a piece like this, you've already got to almost half of it, "cutting" it down, especially like that, is just a pity (some would say it's a shame).


Is there a difference between YES/NO,TRUE/FALSE and true/false in objective-c?

Question: Simple question really; is there a difference between these values (and is there a difference between BOOL and bool)?  A co-worker mentioned that they evaluate to different things in Objective-C, but when I looked at the typedefs in their respective .h files, YES/TRUE/true were all defined as 1 and NO/FALSE/false were all defined as 0. Is there really any difference?
Comment: From a practical standpoint there is no difference.  You can probably do various tricks to demonstrate a difference, but you'd generally be straying into "undefined behavior" territory.
Comment: On this topic, I recommend you checkout my interesting question: https://stackoverflow.com/q/65517700/5492956 You can see there is nuances of `YES` and `true`.
Answer: I believe there is a difference between bool and BOOL, check out this webpage for an explanation of why:
http://iosdevelopertips.com/objective-c/of-bool-and-yes.html
Because BOOL is an unsigned char rather than a primitive type, variables of type BOOL can contain values other than YES and NO.
Consider this code:
BOOL b = 42;

if (b) {
    printf("b is not NO!\n");
}

if (b != YES) {
    printf("b is not YES!\n");
}

The output is:

b is not NO!
b is not YES!

For most people this is an unnecessary concern, but if you really want a boolean it is better to use a bool.  I should add: the iOS SDK generally uses BOOL on its interface definitions, so that is an argument to stick with BOOL.
Comment: But note that the original C implementation had no `bool`, and hence it's been the tradition to use an `int` or `char` as a Boolean, sometimes with a #define to hide the difference and sometimes not.  In fact, I'm not sure if even current standards require `bool` to be implemented in a way that prevents examining it's internal structure.
Comment: Although, the first `printf` tells lies. The value of `b` is not `YES`, it's "not zero", which is what the condition tests. So you should have `printf("b is not zero")`, which is not necessarily the same as `YES`. In this case, `b` is both "not zero" and "not YES".
Comment: @HotLicks there's no inherent difference between 0, not zero and false and true. As long as the value is intended to be a logical boolean, it will always have this interface in order to preserve binary compatibility. The problems begin when you use non booleans that seem like booleans, for example c standard library application entry function, main returns 0 on success, many end up thinking of this 0 as a boolean, when in fact it's an application defined enumeration or user defined value, which callees often expect to be nonzero on abnormal termination.
Comment: Thanks Lawrence, I've made an update along those lines.
Comment: Indeed, i didn't get the second output in Xcode 8.2. Where I fail?
Comment: ps: magic numbers are no more meaningful than macros that represent them. In many cases macros and constants are LESS meaningful than the magic numbers, for example, you're more likely to find the meaning of the boot signature `0xaa55` on google than `MYSIG`, which makes reading source code for bootloaders often less intuitive than without the macros. True and False are less meaningful than int in that we can't deterministically know their size, because while int is always 16 or 32 bits, bool might through some heresy be 1 byte or 8 bytes.
Answer: There is no practical difference provided you use BOOL variables as booleans.  C processes boolean expressions based on whether they evaluate to 0 or not 0. So:
if(someVar ) { ... }
if(!someVar) { ... }

means the same as
if(someVar!=0) { ... }
if(someVar==0) { ... }

which is why you can evaluate any primitive type or expression as a boolean test (including, e.g. pointers). Note that you should do the former, not the latter.
Note that there is a difference if you assign obtuse values to a so-called BOOL variable and test for specific values, so always use them as booleans and only assign them from their #define values.
Importantly, never test booleans using a character comparison -- it's not only risky because someVar could be assigned a non-zero value which is not YES, but, in my opinion more importantly, it fails to express the intent correctly:
if(someVar==YES) { ... } // don't do this!
if(someVar==NO ) { ... } // don't do this either!

In other words, use constructs as they are intended and documented to be used and you'll spare yourself from a world of hurt in C.
Answer: I did an exhaustive test on this. My results should speak for themselves:
//These will all print "1"
NSLog(@"%d", true == true);
NSLog(@"%d", TRUE == true);
NSLog(@"%d", YES  == true);
NSLog(@"%d", true == TRUE);
NSLog(@"%d", TRUE == TRUE);
NSLog(@"%d", YES  == TRUE);
NSLog(@"%d", true == YES);
NSLog(@"%d", TRUE == YES);
NSLog(@"%d", YES  == YES);

NSLog(@"%d", false == false);
NSLog(@"%d", FALSE == false);
NSLog(@"%d", NO    == false);
NSLog(@"%d", false == FALSE);
NSLog(@"%d", FALSE == FALSE);
NSLog(@"%d", NO    == FALSE);
NSLog(@"%d", false == NO);
NSLog(@"%d", FALSE == NO);
NSLog(@"%d", NO    == NO);

//These will all print "0"
NSLog(@"%d", false == true);
NSLog(@"%d", FALSE == true);
NSLog(@"%d", NO    == true);
NSLog(@"%d", false == TRUE);
NSLog(@"%d", FALSE == TRUE);
NSLog(@"%d", NO    == TRUE);
NSLog(@"%d", false == YES);
NSLog(@"%d", FALSE == YES);
NSLog(@"%d", NO    == YES);

NSLog(@"%d", true == false);
NSLog(@"%d", TRUE == false);
NSLog(@"%d", YES  == false);
NSLog(@"%d", true == FALSE);
NSLog(@"%d", TRUE == FALSE);
NSLog(@"%d", YES  == FALSE);
NSLog(@"%d", true == NO);
NSLog(@"%d", TRUE == NO);
NSLog(@"%d", YES  == NO);

The output is:
2013-02-19 20:30:37.061 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.061 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.072 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.073 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.073 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.074 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.074 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.075 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.075 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.076 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.077 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.077 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.078 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.078 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.079 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.079 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.080 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.080 BooleanTests[27433:a0f] 1
2013-02-19 20:30:37.081 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.081 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.082 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.091 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.092 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.093 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.093 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.094 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.094 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.095 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.095 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.096 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.096 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.097 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.098 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.101 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.102 BooleanTests[27433:a0f] 0
2013-02-19 20:30:37.102 BooleanTests[27433:a0f] 0

Comment: @SamuelRenkert I've never been comfortable with a language taking a non-Boolean value in an `if` or a `while`. Like... `while("guitar gently weeps")` shouldn't work...
Comment: [[NSObject]alloc]init] does not equal TRUE or YES. So testing for object initialization with if ([[NSObject]alloc]init]==TRUE) will fail. I've never been comfortable with a Language defining a singular "true" value when in fact any non zero value will do.
Comment: @SamuelRenkert also the Linux backdoor that was found in 2003: `if (user_id = ROOT_UID)`
Answer: The main (dangerous!) difference between true and YESis in JSON serialization.
For example, we have JSON-type server request and need to send true/false in json sence:
NSDictionary *r1 = @{@"bool" : @(true)};
NSDictionary *r2 = @{@"bool" : @(YES)};
NSDictionary *r3 = @{@"bool" : @((BOOL)true)};

Then we convert it to JSON string before sending as
NSData *data = [NSJSONSerialization  dataWithJSONObject:requestParams options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

The result is
jsonString1 // {"bool":1}
jsonString2 // {"bool":true}
jsonString3 // {"bool":true}

Due to API logic jsonString1 could result in an error.
So be careful with booleans in Objective-C.
To sum up, only exact @YES and casted value as @((BOOL)expression) are of __NSCFBoolean type and converted to true with JSON serialization.
Any other expressions like @(expression1 && expression2) (even @(YES && YES)) are of __NSCFNumber (int) type and converted to 1 in JSON.
P.S. You can simply use string-valued boolean
@{@"bool" : @"true"}; // in JSON {"bool":true}

Answer: You  might want to read the answers to this question. In summary, in Objective-C (from the definition in objc.h):
typedef signed char        BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#define OBJC_BOOL_DEFINED

#define YES             (BOOL)1
#define NO              (BOOL)0

Answer: There is a subtle bug that no one has mentioned here, that I thought I would include... more of a logical error than anything:
int i = 2;
if(i);        //true
if(i==YES);   // false
if((!!i)==YES); //true

so the issue here is just that (YES==1) and in C the comparison isn't a boolean one, but one based on value.
because YES is just a #define (rather than something intrinsic to the language), it has to be some value, and 1 makes the most sense.
Comment: This is essentially the same answer as DanJ's, from 2+ years earlier, with less detail.
Comment: @LawrenceDol I don't know, it mentions that YES is only #defined to be 1 and not intrinsic to the language, like it might be in a higher level language... someone could possibly get value from that... but good trolling, with ya.
Answer: I think they add YES/NO to be more self-explanatory in many cases. For example:
[button setHidden:YES];

sounds better than
[button setHidden:TRUE];

Comment: I disagree as well. If anything, it reads poorly due to not sticking to the unwritten standards that have been used for years in other languages. IE is a prime example of what happens when you fail to adhere to a great number of standards.
Comment: I disagree; they both read the same, to me.  However, in a UI for a lay person I think Yes/No looks nicer.
Comment: Half downvote for 2 imprecise answers and half downvote for [signing your answers](http://meta.stackexchange.com/a/3021/280621)
Answer: First let's examine what true and false is and what gives them meaning in the first place.
we can construct a structure called if a then b else c in lambda calculus as follows:
(\ifThenElse. <use if then else>)(\a. \b. \c. a b c)

In JavaScript, This looks like this:
(function(ifThenElse) {
    // use ifThenElse
})(function(a) {
    return function(b) {
        return function(c) {
            return a(b)(c);
        };
    };
});

in order for ifThenElse to be useful, we need a function "true" that chooses either right or left, and does that while ignoring the other option, or a function "false" that chooses the option "true" doesn't take.
We can define these functions as follows:
(\true. <use true>)(\a. \b. a) and (\false. <use false>)(\a. \b. b)

in JavaScript it looks like this:
(function(True) {
    // use True
})(function(a) {
     return function(b) {
         return a;
     }
});

(function(False) {
    // use True
})(function(a) {
     return function(b) {
         return b;
     }
});

now we can do the following
(\true. \false. \ifThenElse. \doThis. \doThat. ifThenElse true doThis doThat)
(\a. \b. a)(\a. \b. b)(\a. \b. \c. a b c)(\a. ())(\a. ())

with doThis and doThat being (\a. ()) because lambda calculus does not offer any services such as printing/math/strings, all we can do is do nothing and say we did it(and later cheat by replacing it with services in our system that provide side effects we want)
so let's see this in action.
(function(True) {
    return (function(False) {
        return (function(ifThenElse) {
            return (function(doThis) {
                return (function(doThat) {
                    return ifThenElse(True)(doThis)(doThat);
                });
            });
        });
    })
})(function(a) {
     return function(b) {
         return a;
     }
})(function(a) {
     return function(b) {
         return b;
     }
})(function(a) {
    return function(b) {
        return function(c) {
            return a(b)(c);
        };
    };
})(function(a) { console.log("you chose LEFT!"); })
(function(a) {console.log("you chose RIGHT");})();

That's a deep environment that could be simplified if we were allowed to use arrays/maps/arguments/or more than one statement to split into multiple functions, but i want to keep is as pure as I can limiting myself to functions of exactly one argument only.
notice that the name True/False has no inherent significance, we can easily rename them to yes/no, left/right, right/left, zero/one, apple/orange. It has significance in that whatever choice is made, it is only caused by the kind of chooser made it. So if "LEFT" is printed, we know that the chooser could only be true, and based on this knowledge we can guide our further decisions.
So to summarize
function ChooseRight(left) {
    return function _ChooseRight_inner(right) {
        return right;
    }
}
function ChooseLeft(left) {
    return function _ChooseLeft_inner(right) {
        return left;
    }
}

var env = {
    '0': ChooseLeft,
    '1': ChooseRight,
    'false': ChooseRight,
    'true': ChooseLeft,
    'no': ChooseRight
    'yes': ChooseLeft,
    'snd': ChooseRight,
    'fst': ChooseLeft
};
var _0 = env['0'];
var _1 = env['1'];
var _true = env['true'];
var _false = env['false'];
var yes = env['yes'];
var no = env['no'];

// encodes church zero or one to boolean
function lambda_encodeBoolean(self) {
    return self(false)(true);
}
// decodes a Boolean to church zero or one
function lambda_decodeBoolean(self) {
    console.log(self, self ? env['true'] : env['false']);
    return self ? env['true'] : env['false'];
}

lambda_decodeBoolean('one' === 'two')(function() {
    console.log('one is two');
})(function() {
    console.log('one is not two');
})();

lambda_decodeBoolean('one' === 'one')(function() {
    console.log('one is one');
})(function() {
    console.log('one is not one');
})();

Answer: No, YES/NO is a different way to refer to TRUE/FALSE(1/0)


Using years when calculating linear regression?

Question: I'm new to statistics, and I'm currently trying to solve an assignment for my course.
The assignment is to calculate the linear regression analysis/regression equation for a data set containing years and the percentage of unemployment in the population at that time.
While I'm not entirely sure how to do this, my primary question is basically:
When using years to perform the analysis, should the actual years be used in the calculation (2009, 2010, etc.) or should they be replaced with 1,2,3, etc.?
Answer: The second series can be written as the first one minus 2008.

Ought it to make a difference to how we think unemployment changes over time when we start counting years from—the birth of Christ or the start of the data series?
Look at the least-squares equations & try to work out the effect of subtracting a constant from the predictor. Of the estimated coefficients & the predicted values what will change, & how?
Check by performing the regression both ways.
Comment: +1. As a quiz trivium, note that the birth of Jesus is not now usually dated to year zero (early scholars got the chronology wrong), nor was there a year zero in any case. http://en.wikipedia.org/wiki/0_(year) So, the question is whether a notional year 0 for the Western calendar has intrinsic relevance as a natural origin for data analysis and the answer is (almost always) a resounding No. Further, the intercept if you use such an origin is often an absurd number because it represents a projection way beyond the data. It's better to have an intercept you can interpret.
Comment: See also http://stats.stackexchange.com/questions/71038/regression-of-data-that-includes-a-date
Answer: In principle, it doesn't matter - only the intercept term will be affected. Say that you want to estimate the regression Y = a + bX + e. Remember that the slope coefficient can be calculated as b = Cov(Y, X) / Var(X), and a = Ym - bXm, where Ym and Xm are the sample means of the respective variables. Now, let's add a constant C to the X variable (corresponding to switching the year definition in your example): b = Cov(Y, X + C) / Var(X + C) = [Cov(Y, X) + Cov(Y, C)] / [Var(X) + Var(C)]. Furthermore, Cov(Y, C) = Var(C) = 0, because C is a constant. This gets us back to the same expression for b as before. For the intercept, we get a = Ym - b*(Xm + C).
In practice, you can sometimes run into issues when using very large values for a variable. This is because you can run into the limits of your computers level of numerical precision, but in your case, I can't imagine that it would make any difference.
Comment: The other issues here are (1) interpretability of the intercept (touched on in the other answer) and (2) correlation between slope and intercept.  Neither of these make the answer technically wrong, but both are reasons to consider centering or otherwise shifting the predictor variable.
Comment: Because this is homework I thought giving the answer might be less helpful than hinting how to get to it, as per the [self-study tag wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: Good point @Scortchi, and thanks for the link. I'll keep this in mind for the future.
Comment: when `x=0` is far away from the data range there is a strong correlation in the *sampling distribution* of the parameters between the slope & intercept.  (Heuristically, a small change in the estimated slope will cause a large change in the estimated intercept.)
Comment: @BenBolker, I completely agree with (1), but I'm not sure I understand what (2) means - given that the intercept is constant in this model, how could it be correlated with the slope?
Answer: a) If you're sure (or in this case specifically told) you only need to use year as linear variable (no interactions, no quadratic terms, no other terms), and you only have one timeseries, then in this case it doesn't make any difference (just results in a constant offset). So might as well use year as is.
b) In general), if you're looking at an arbitrary unknown modeling problem, where you might well need quadratic, higher-order or nonlinear terms, then you should define a time-index: yearx = year - 2007. We usually define time-index to start at 1, not 0, since many useful functions object to 0, such as log, 1/x etc. (But this is more broad than your example.)
c) There's another, more basic reason: if you have multiple timeseries, each with a different start-year (e.g. one series starts in 1996, another in 2008). Then if you want to focus on the relative time lag, and remove hard year numbers from the model coefficients, graphs etc., again compute yearx = year - start_year for each series.
Answer: Yes, you can use years as the predictor variable in linear regression. The basic code would be Outcome = Year. The beta coefficient from such a model would allow you to predict the outcome for an unobserved year.
It is important to remember that the p-value for the beta coefficient is testing whether there is a linear relationship between Year and Outcome across all years. This is often untrue even if the first and last year are obviously different. If you are really interested in whether the first year is significantly different from the last, you should restrict your data to just those two years, in which case linear regression would not be an appropriate method.


Como Faço para meu Modal só aparecer na primeira visita do cliente ?

Question: Eu fiz um modal, esse código java que eu utilizei
    $(document).ready(function(){
    $(".janelaModal, .fundoModal").fadeIn();
    $(".botao").click(function(){
    $(".janelaModal, .fundoModal").fadeIn();
    });
    $(".fecharModal, .fundoModal").click(function(){
    $(".janelaModal, .fundoModal").fadeOut();});});

Como eu faço para que modal só apareça na primeira visita do usuário?
Answer: Você pode utilizar JsCookies
if (Cookies.get('visita') != true) {
    Cookies.set('visita', true);
    $(".janelaModal, .fundoModal").fadeIn();
    $(".botao").click(function(){
        $(".janelaModal, .fundoModal").fadeIn();
    });
    $(".fecharModal, .fundoModal").click(function(){
        $(".janelaModal, .fundoModal").fadeOut();
    });
}

Comment: Valeu pela ajuda, só que agora ele não fecha mais o modal, com esse código
Comment: Bem, não tenho como reproduzir o problema para te ajudar, tente mais um pouco e retorne aqui com alguma mensagem.
Comment: eu entrei no site JsCookies, na minha index eu coloquei o
  e coloquei o que vc aconselhou no código acima, tem algo mais tenho que fazer ?
Comment: Não sei, preciso ver seu código de uma forma mais ampla pra entender o problema.
Answer: Você pode armazenar esta informação no Cliente, seja através de Cookies, localStorage, sessionStorage ou IndexedDB.
Levando em consideração, que ao armazenar em um cookie esta informação irá trafegar entre o cliente e o seu servidor em cada request, assim gerando um trafego adicional de uma informação que possivelmente não será utilizada no servidor, al´m da questão que um cookie possui data de expiração, então eu diria que Cookies não são uma boa ideia para o seu cenário.
Por um outro lado, IndexedDB lhe fornece uma estrutura grande demais para este problema, seria como matar uma formiga com uma bomba de fusão nuclear.
Então você pode usar localStorage ou sessionStorage, porém o sessionStorage irá desaparecer assim que a aba ou o browser for fechado, então se quiser que está informação permaneça até o fim dos tempos (ou o usuario limpar o Storage), deverá escolher pelo localStorage.
lembrando que o localStorage uma chave e um valor, ambos como string, se precisar armazenar um objeto, deverá fazer uso do JSON.parse e do JSON.stringify.

var json = localStorage.getItem("dados de acesso");
var dados = {};

if (!json) {
  dados = { primeiroAcesso: true };
} else {
  dados = JSON.parse(json);
}

console.log(dados);

if (dados.primeiroAcesso) {
  /* Abra o seu dialog */

  dados.primeiroAcesso = false;
  localStorage.setItem("dados de acesso", JSON.stringify(dados));
}

console.log(dados);

Como o Snippet roda sandbox, não é possível usar o localStorage no mesmo, então o exemplo acima não vai funcionar, porém você pode abri-lo no JSFiddle
Comment: Valeu mesmo, mas onde coloco tudo isso, sou extremamente iniciante, e não quero ser programador, não quero ser dominador de java, etc, só quero aprender o necessário para fazer meu site funcionar. Agradeço muito se poder me ajudar.


js if any value in array is under or over value

Question: say you have (any amount) values in an array and you want to see if any of them is over (lower amount) and under higher amount, how would you do that?
answer without doing a for loop or any lengthy code.
Maybe something like:
var havingParty = false;
if ((theArrayWithValuesIn > 10) && (theArrayWithValuesIn < 100)) {
    havingParty = true;
} else {
    havingParty = false;
}

would work.
Please note: x and y, collision detection, compact code.
Comment: And whats wrong with this code? You want to get all values betwen these numbers? Why a loop no good?
Comment: @lolka_bolka because i already have enough for loops and it could be an array of numbers or a single number that isn't in an array. do you get what i mean
Answer: If I understand your question correctly, you want to check if a given array has any value greater than some other value.
There is a useful function for this called some (Documentation here)
An example of using this would be:
const a = [1, 2, 3, 4, 5];
a.some(el => el > 5) // false, since no element is greater than 5
a.some(el => el > 4) // true, since 5 is greater than 4
a.some(el => el > 3) // true, since 4 and 5 are greater than 3

A similar function to this is every, which checks if all the values fulfil a given condition (Documentation here).
An example of this would be:
const a = [1, 2, 3, 4, 5];
a.every(el => el > 3) // false
a.every(el => el > 0) // true

My examples simply check for greater than, but you could pass in any callback that returns a boolean value for more complicated checks.
So for your example, something like this might do the trick if you want to check that all the elements fill the requirement:
const havingParty = theArrayWithValuesIn.every(el => el < 100 && el > 10);

or
const havingParty = theArrayWithValuesIn.some(el => el < 100 && el > 10);

if you you only care that at least one element fills the requirement.
Comment: so, is some like an any while every is like an all?
Comment: also, how does `value < other value` when not in an if work? is it like how setting a value to a literal string works? is an expression a literal?
Comment: Exactly, `some` translates to `any` in other programming languages, and `every` is basically `all`. I'm afraid I don't understand your second question.
Comment: does english count as a programming language?
Comment: I suppose not, you got me there. I was simply trying to point out that the method names are not consistent across programming languages.
Comment: I'm about to try it and see if any errors occur. wish me luck!
Comment: heh, good to look back, i now use dartlang and it uses any, much better wording.
Comment: And now i'm looking back at this, i still use dartlang, and this whole thing is just a simple `list.any((x) => x > 10 && x < 100)`, geez i was 11 when i asked this.
Answer: Here is a simple answer :
var arr = [0,10,100,30,99];
var config = {min:0,max:100};

// filter is a method that returns only array items that respect a
//condition(COND1 in this case )
var arr2 = arr.filter(function(item){
  //COND 1 :
  return item > config.min && item < config.max;
});

Comment: please add comments to the code so i understand it and can adapt it to my needs
Comment: Just as an addition: if you only want to know if an element exists that fulfills the condition, you could check the length of arr2 like: `var exists = arr2.length > 0`
Answer: According to your condition

"if any of them is over (lower amount) and under higher amount"

Array.some function will be the most suitable "tool":
var min = 10, max = 100,
    result1 = [1, 2, 3, 30].some((v) => min < v && v < max),
    result2 = [1, 2, 3, 10].some((v) => min < v && v < max);

console.log(result1);  // true
console.log(result2);  // false


CURLOPT_HEADERFUNCTION - Retorno de cookies

Question: Tenho esta função que retorna Cookies de um determinado site, estou aprendendo HTTP HEADERS,
Mas eu não sei o porque deste aviso se estou retornando meus cookies tudo ok,
O que tem de errado no meu código?

Notice: Object of class stdClass could not be converted to int in
  C:\wamp64\www\tr\api\login.php on line 34

Aqui está meu código:
<?php

function cookies() {
    $request = curl_init();
    curl_setopt_array($request, [
            CURLOPT_URL                         => 'https://tr.com',
            CURLOPT_CUSTOMREQUEST       => 'GET',
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_HEADER                  => true,
            CURLOPT_HEADERFUNCTION  => function($curl, $header) use (&$cookie) {
                if (stripos($header, 'Set-Cookie:') === 0) {
                    $cookieOBJ = new \stdClass();
                    $cookieOBJ->cookies = '';
                    if (preg_match_all('/^Set-Cookie: \s*([^;]*)/i', $header, $matches)) {
                        foreach ($matches[1] as $cookie) {
                            $cookie = explode('=', $cookie);

                            $key = (!empty($cookie[0])) ? $cookie[0] : '';
                            $val = (!empty($cookie[1])) ? $cookie[1] : '';

                            $cookieOBJ->{"$key"} = $val;

                            $cookieOBJ->cookies .= $key . '=' . $cookieOBJ->{"$key"} . '; ';
                        }
                    }
                    return $cookieOBJ;
                }
                return strlen($header);
            }
        ]
    );
    $response = curl_exec($request);
    curl_close($request);
}

var_dump(cookies());

Obs: Preciso que me retorne da seguinte forma:
C:\wamp64\www\tr\api\login.php:28:
object(stdClass)[2]
  public 'cookies' => string 'fm=; ' (length=5)
  public 'fm' => string '' (length=0)

E ao utilizar a minha variável $cookieOBJ me retorna todos ou $cookieOBJ->cookies, porém se eu utilizar $cookieOBJ->fm me retorna um erro:

Notice: Undefined property: stdClass::$fm in
  C:\wamp64\www\tr\api\login.php on line 28

Qual a solução?
Answer: Esse código não vai funcionar nunca, primeiro veja a documentação do CURLOPT_HEADERFUNCTION:

This callback function must return the number of bytes actually taken care of. If that amount differs from the amount passed in to your function, it'll signal an error to the library. This will cause the transfer to get aborted and the libcurl function in progress will return CURLE_WRITE_ERROR.

O seu return $cookieOBJ; não faz o minimo sentido. Assim como também não faz sentido fazer um foreach nem preg_match_all, se cada vez só terá um cookie, não vários. Afinal, pelo CURLOPT_HEADERFUNCTION:

The header callback will be called once for each header and only complete header lines are passed on to the callback.

Se for ver a RFC6265:

Origin servers SHOULD NOT fold multiple Set-Cookie header fields into a single header field. The usual mechanism for folding HTTP headers fields (i.e., as defined in [RFC2616]) might change the semantics of the Set-Cookie header field because the %x2C (",") character is used by Set-Cookie in a way that conflicts with such folding.

Logo, cada cabeçalho do Set-Cookie, enviado pelo servidor, terá apenas um único cookie.

Uma maneira muito mais fácil, que inclusive você já usou, inclusive deve ter surgido daqui e foi explicado aqui:
CURLOPT_HEADERFUNCTION => function($curl, $cabeçalho) use (&$cookie){

    if(stripos($cabeçalho, 'Set-Cookie:') === 0){
        if(preg_match('/Set-Cookie:\s?(.*?);/i', $cabeçalho, $matches)) {
            $cookie .= $matches[1] . '; ';
        }
    }

    return strlen($cabeçalho);
}

Isso irá criar uma string, contendo Nome=Valor;, mas se realmente deseja um objeto, basta alterar o REGEX e criar o objeto FORA da função.
A ideia é passar a variável como referencia em &$cookie que vai permitir obter o resultado, ou seja:
function cookies()
{
    $request = curl_init();
    $cookie = new \stdClass();  // Inicia aqui fora

    curl_setopt_array($request, [
            CURLOPT_URL => 'SEU.SITE.COM',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_NOBODY => true, // Você só precisa o header, não do corpo
            CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, // Você só usa HTTPS, não STMP, por exemplo.
            CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2, // A versão mais segura de TLS.
            CURLOPT_SSL_VERIFYHOST => 2, // Usar false é claramente inseguro.
            CURLOPT_SSL_VERIFYPEER => 1, // Usar false é claramente inseguro.
            CURLOPT_HEADERFUNCTION => function ($curl, $header) use (&$cookie) {
            // Estamos usando o `&$cookie` ou seja uma "referencia" a variável lá de fora.
                if (stripos($header, 'Set-Cookie:') === 0) {
                    if (preg_match('/^Set-Cookie: \s*([^=]*)=([^;]*)/i', $header, $matches)) {
                        $cookie->{$matches[1]} = $matches[2];
                    }
                }
                return strlen($header);
            }
        ]
    );

    $response = curl_exec($request);
    curl_close($request);

    return $cookie; // Retornamos aqui.
}

O REGEX /^Set-Cookie: \s*([^=]*)=([^;]*)/i fará o trabalho de pegar o nome e valor do cookie, isot será adicionado usando:
$cookie->{$matches[1]} = $matches[2];

O $cookie é uma referencia (devido ao uso do (&$cookie)) ao $cookie = new \stdClass(); iniciado nas primeiras linhas. Algumas outras mudanças foram feitas por segurança, se isso não for importante, o que é comum em PHP, basta remove-las.
Comment: Ué, está retornando justamente o que você diz querer na sua postagem "Obs: Preciso que me retorne da seguinte forma:". Se você quer acessar cada valor basta fazer `$seuscookies = cookie();` e então `$seuscookies->fm`. Se quiser formatar todos os cookies, para ficar tudo junto, utilize `http_build_query($seuscookies, '', '; ', PHP_QUERY_RFC3986) . ';';`, assim ficará tudo da maneira "que agora você quer".
Comment: Ta tudo certo, mas eu queria, que retorna-se por exemplo: `fm=0;` e está me retornando assim: `public 'fm' => string '0' (length=1)`
Comment: Funcionou. Obrigado.


Melhorar a Cognição do gTTS

Question: é possível melhorar a cognição do gTTS com Python?
Estou criando um projeto com enfase no "reconhecimento de voz" para comandos no PC // Arduino // Rasp // outros porém percebi que quando falo algo simples como apenas um "SIM" ele as vezes demora para dar um "stop" na captação... Segue as linhas de código que tenho do gTTS:
<code>with SR.Microphone() as source:
    r   = SR.Recognizer()
    r.adjust_for_ambient_noise(source)
    audio = r.listen(source)
    os.system(beep)
    audio = r.listen(source)
os.system(boop)
with open(rec, 'wb') as song:
    song.write(audio.get_wav_data())
try:
    with open('/home/pi/bot/logs/yk12mmkiy78.db', 'a', errors = 'ignore') as datafile:
        datafile.write(r.recognize_google(audio, language="pt-BR") + ';')
</code>
Por enquanto ele está escrevendo o que foi dito num arquivo de texto chamado yk12mmkiy78.db e as vezes até palavras simples
ele escreve errado é possível melhorar a cognição e o entendimento?
Answer: Olá , tenho um pouco de experiência com TTS e ASR em sistemas Asterisk PBX , Amazon Poly e  Google TTs aqui na empresa, e o que fazemos para melhorar o entendimento e timing do processo é:

Evitamos a 'fala aberta' , normalmente mapeamos as intenções com o Ngram para ficar mais assertivo a tomada de decisões para comandos e você configura a acurácia pois os TTS e ASRs de fato não são 100% eficientes.

Exemplo:
Palavra dita : 'Não' , o que a plataforma entende 'Pão'.
Se você configurar a acurácia em 80% por exemplo , a palavra "Pão" será aceita como "Não" dentro da intenção que você quer capturar do usuário.

Ao invés de abrir o microfone direto , gravamos a fala do usuário e cortamos (em tempo de execução) caso fique muito tempo mudo (normalmente 2 segundos) antes de enviar o áudio para a plataforma transcrever (até para evitar custos).
Acho que você já usa o google mas mesmo assim vou frisar pois pra nós fez uma grande diferença.  O reconhecimento de voz do google está muito mais evoluído para a fonética brasileira use -o.

Espero ter ajudado.
Comment: Carlos desculpe a demora para dar uma resposta, não entendi muito bem o "-o" onde devo coloca-lo ?

Melhorar a Cognição do gTTS


Retrieving the primary Key column

Question: I have been using this query to query Postgres Table Primary Key Column.
SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'semstudent'::regclass
AND    i.indisprimary;

I want to perform the above query in Drupal. Below is my code:
$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->condition('i.indrelid', '"semstudent"::regclass')
    ->condition('i.indisprimary', true)
    ->execute();

The query above create the error below:

PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type oid: ""semstudent"::regclass"
      LINE 5: WHERE  (i.indrelid = '"semstudent"::regclass') AND   (i.indisp...
                               ^: SELECT a.attname AS attname, a.atttypid AS atttypid,   a.atttypmod AS atttypmod
      FROM
      {pg_index} i
      INNER JOIN {pg_attribute} a ON a.attrelid = i.indrelid AND a.attnum =     ANY(i.indkey)
      WHERE  (i.indrelid = :db_condition_placeholder_0) AND (i.indisprimary =   :db_condition_placeholder_1) ; Array
      (
          [:db_condition_placeholder_0] => "semstudent"::regclass
          [:db_condition_placeholder_1] => 1
      )
      in myid_get_template_table_primary_key() (line 755 of C:\xampp\htdocs\drupal-  7.34\sites\all\modules\myid\includes\myid_inputting.inc).

I guess it has something to do with the statement below.
->condition('i.indrelid', '"semstudent"::regclass')

How do I convert it?
UPDATE:
Suggestions below are appreciated but it doesnt make any changes in my code. I have somehow managed to get it working manually. See code below:
 $database = 'import';
 $table = 'semstudent';

 $query=db_select('pg_index', 't1',array('target' => $database));
 $query->join('pg_attribute' , 't2' ,'t2.attrelid = t1.indrelid AND t2.attnum = ANY(t1.indkey)');
 $result = $query
    ->fields('t2', array('attname','atttypid','atttypmod'))
    ->condition('t1.indrelid', myid_get_table_oid($table, $database))
    ->condition('t1.indisprimary', true)
    ->execute();

I have made the function myid_get_table_oid supplied with two parameters: $table and $database. $table represents the name of the the table. $database represents the target database.
//A function that returns the oid of a particular table.
function myid_get_table_oid($table_name, $database){

    $query=db_select('pg_class ', 't1',array('target' => $database));
    $result = $query
        ->fields('t1', array('relfilenode'))
        ->condition('t1.relname', $table_name)
        ->execute();

    $oid = '';
    foreach($result as $record){
        $oid = $record->relfilenode;
        break;
    }
    return $oid;
}

In many instances, the code I made is working but there is one scenario the function returns no primary key. When I use the code above with a particular table myid_template_27 in my database. The function myid_get_table_oid returns an oid    8948915. But the converted query doesnt return anything.
I am pretty sure that the table myid_template_27 have a primary key column. It must return the column biginta.See image below:

To see if biginta really exist on pg_attribute table, I made a query below:
SELECT t1.indrelid, t2.attname AS attname, t2.atttypid AS atttypid, t2.atttypmod
AS atttypmod
FROM pg_index t1
INNER JOIN pg_attribute t2 ON t2.attrelid = t1.indrelid AND t2.attnum =     ANY(t1.indkey)
WHERE  (t1.indisprimary = true)  AND (t2.attname = 'biginta')

The result shows a different indrelid oid which is different from the value returned by my function myid_get_table_oid.

Where did I go wrong?
Comment: Do you get any error, or is the result not the expected one? In the former case, please report the error you are getting; in the latter case, please report what you are getting and in which way is different from what you are expecting.
Comment: "Invalid text representation" is probably talking about the quotes, try reversing them (`->condition('i.indrelid', "'semstudent'::regclass")  `
Comment: try `>condition('i.indrelid', semstudent::regclass)`
Answer: As some people already mentioned and the error itself describes, this is a variable interpolation/auto-quoting problem.
The most appropriate option here - following the D.O.'s documentation - would be to use where(), instead of condition().

$query->where($snippet, $args = array())
The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and
  if it has variable content it must be added using a named placeholder.
  The $args array is an array of placeholders and values that will be
  substituted into the snippet. It is up to the developer to ensure that
  the snippet is valid SQL. No database-specific modifications are made
  to the snippet.
(Copied from https://www.drupal.org/node/310086)

And here is a rewrite of your code:
$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->where("i.indrelid = 'semstudent'::regclass")
    ->condition('i.indisprimary', true)
    ->execute();

I just tried this and it worked without any problems, hope it works for you too!
Answer: Have you tried db_query It will be clear to write the same query with minimal edit.
 db_query('SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
    FROM   pg_index i
    JOIN   pg_attribute a ON a.attrelid = i.indrelid
                         AND a.attnum = ANY(i.indkey)
    WHERE  i.indrelid = :tablename::regclass
    AND    i.indisprimary', array(':tablename' => $tablename));

Retrieving the primary Key column


Cmake links only to executable

Question: I have a problem that in my project I have multiple libraries who all link eachother differently.
And then there is one executable that links to only one library.
Now there are two problems:
1) The linked libraries are not showing up in the librarian of the static libraries.
2) the librarires are all showing up at the executable.
So here is my project order
Game|- Engine|--Core|---Graphics|----Libpng|---Platform
so Graphic links Libpng
Core links Graphics and Platform
Engine links Core
Game links Engine
Utilities is an interface library so headers only
what happens is that all Additional dependencies are at Game
The librarian of Core, Engine and Graphic containts no additional dependencies.
This is the Root CMake
<code>cmake_minimum_required(VERSION 2.8.9)
set(CMAKE_GENERATOR "Visual Studio 14 2015")
project(EngineOnly)

set(CMAKE_SUPPRESS_REGENERATION true)

if(WIN32)
    set(PLATFORM WIN32)
else()
    set(PLATFORM LINUX)
endif (WIN32)

add_subdirectory(UTILITIES)
add_subdirectory(PLATFORM)
add_subdirectory(GRAPHICS)
add_subdirectory(CORE)
add_subdirectory(Engine)
add_subdirectory(Game)

set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT Trinity.Game)
</code>
This is game

<code>#UTILITIES LIB
include_directories(../UTILITIES/INCLUDE)
include_directories(../ENGINE/INCLUDE)

#SOURCE
file(GLOB SOURCES "SOURCE/*.cpp")
file(GLOB INCLUDES "INCLUDE/*.h")

#PROJECTNAME
set(PROJECTNAME "Trinity.Game")

#LINK ALL
add_executable(${PROJECTNAME} ${SOURCES} ${INCLUDES})

set_target_properties(${PROJECTNAME} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/../BIN/${PLATFORM}/DEBUG"
RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/../BIN/${PLATFORM}/RELEASE"
)

target_link_libraries(${PROJECTNAME}
LINK_PRIVATE Trinity.Engine
)
</code>
Engine
<code>#UTILITIES LIB
include_directories(../UTILITIES/INCLUDE)
include_directories(../CORE/INCLUDE)

#SOURCE
file(GLOB SOURCES "SOURCE/*.cpp")
file(GLOB INCLUDES "INCLUDE/*.h")

#PROJECTNAME
set(PROJECTNAME "Trinity.Engine")

#LINK ALL
add_library(${PROJECTNAME} ${SOURCES} ${INCLUDES})

set_target_properties(${PROJECTNAME} PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY_DEBUG "${CMAKE_CURRENT_BINARY_DIR}/LIB/${PLATFORM}/DEBUG"
ARCHIVE_OUTPUT_DIRECTORY_RELEASE "${CMAKE_CURRENT_BINARY_DIR}/LIB/${PLATFORM}/RELEASE"
)

target_link_libraries(${PROJECTNAME}
LINK_PRIVATE Trinity.Core
)
</code>
Core
<code>#UTILITIES LIB
include_directories(../UTILITIES/INCLUDE)
include_directories(../GRAPHICS/INCLUDE)
include_directories(../PLATFORM/INCLUDE)

#SOURCE
file(GLOB SOURCES "SOURCE/*.cpp")
file(GLOB INCLUDES "INCLUDE/*.h")

#PROJECTNAME
set(PROJECTNAME "Trinity.Core")

#LINK ALL
add_library(${PROJECTNAME} ${SOURCES} ${INCLUDES})

set_target_properties(${PROJECTNAME} PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY_DEBUG "${CMAKE_CURRENT_BINARY_DIR}/LIB/${PLATFORM}/DEBUG"
ARCHIVE_OUTPUT_DIRECTORY_RELEASE "${CMAKE_CURRENT_BINARY_DIR}/LIB/${PLATFORM}/RELEASE"
)

target_link_libraries(${PROJECTNAME}
LINK_PRIVATE Trinity.Graphics
LINK_PRIVATE Trinity.Platform
)
</code>
The other look the same.
I've tried PRIVATE instead of LINK_PRIVATE but the result is the same.
Answer: You can't link static libraries against each other and it is normal that they only showing up at the executable. Does your code not compiling?
For more information about static and dynamic libraries I suggest this article.
If you want to change the library type in cmake specify the add_lib command:
<code> add_library(${LIB_NAME} ${LIB_TYPE} ${SOURCE})

 # with ${LIB_TYPE} = STATIC or SHARED
</code>
more informations about cmake
If you have more problems or my answer answer to you is not enough please specify your question.
Comment: Thanks, I did not know that. Yea my code was not compiled and I thought it's because of this.
But it's now working as I fixed the .lib.lib from zlib and libpng. Gonna look into it whether I'm gonna use a pre/post build to link the libraries or not

Cmake links only to executable


What chord do we get by raising the fifth of a minor triad?

Question: Raising the fifth of a major triad gives an augmented triad. For example, you can get from C (C-E-G) to C+ (C-E-G♯) by raising the fifth.
However, what happens if this is done to a minor triad? Doing it to Cm (C-E♭-G) gives C-E♭-G♯, which is enharmonic to C-E♭-A♭, a first inversion A♭ major triad. Is there any special name for chords like C-E♭-G♯, or are they just treated as major triads in the first inversion? An E augmented triad is not a C inverted augmented triad, so is this new chord also functionally different from an inverted major triad?
Comment: Similar, but more general: https://music.stackexchange.com/questions/56332/triads-with-thirds-that-arent-major-or-minor
Answer: I'm not sure if these are the best examples, but I'm trying to draw a parallel between the difference in enharmonic spelling of something like a German augmented sixth chord and a dominant seventh chord, where the two enharmonic spelling reflect two different harmonic functions, and this case of an enharmonically respelled major triad.

The first phrase is just to set a key of C minor. The second phrase is where the chord in question sounds like a Neapolitan chord so we want to spell it sensibly with an A♭ for a half step above tonic G. The third phrase spells the chord with a G♯ as part of a chromatically ascending line, labelled p.c. for passing chord, where the dominant/tonic relationship is the ending on a B♭ chord.
In the second example the N6 Neapolitan chord is a well known chord type and is considered a type of altered subdominant, a iio diminished chord with the root lowered. If the linear movements coincide with those particular functions, it makes sense to enharmonically spell things to make the notation explicitly read as such.
In the third example the chord in question could by an A♭ triad in key Cm, which in terms of function is VI, a fairly "weak" modal chord, but the phrase doesn't continue in Cm. The chord could also be labelled ♭VII in key B♭, but that again would be a weak modal type chord. In this case I think the chord truly is ambiguous in terms of harmonic function, and that ambiguity provides sensible leeway to spell the chord one way or another. One of those options is to spell it to highlight the chromatically ascending line. And that choice then give us a minor triad with the chordal fifth raised. Technically, because of its spelling, it is not a standard triad type of either major, minor, diminished, or augmented. Functionally it's a harmonic non-entity. (It doesn't fulfill predominant-dominant-tonic harmonic function so there isn't much point in giving it a Roman numeral analysis label.) It's just the result of contrapuntal movement.
You might also make a comparison to the 'classical' harmonic label French augmented sixth chord with the jazz label for the same chord. In jazz it's called a dominant seventh flat five chord (or depending on context it could be called a tritone substitution chord, but that's another topic.) Notice of the jazz label is a literal description of the alteration of a standard 'classical' harmony chord type? That's basically the same as how you presented your question. You, in essence, called a first inversion A♭ major triad a C minor sharp five chord. If jazz theory can use such process oriented labels, why can't you?
One final thought. Just because something doesn't have a conventional label does not mean it is musically meaningless. Think of a conventional label as a convenience. Something that make a musical action easy to talk about. Absent a convenient label you can still see and hear and describe how something is working. Things like root progression, TI-DO & FA-MI dominant function, harmonic sequence, melodic/contrapuntal motion, non-chord tone identification, and resolution of dissonance are some of the big concepts that come up in analysis.
Answer: "The theory" is based on the idea that all (root position) triads are made up of minor thirds and major thirds.

dim = m3 + m3
min = m3 + M3
maj = M3 + m3
aug = M3 + M3

So, strictly speaking, C - Eb - G# is not a triad recognized within that theory: it contains an augmented third (Eb - G#). Even supposing it's an inversion, no "legal" triad can be made with those three pitches spelled as they are.

C - Eb - G# = m3 + a3
Eb - G# - C = a3 + d4
G# - C - Eb = d4 + m3

Thus, the chord is either a misspelled Ab major chord, or it's a passing result of chromatic voice leading.

But even in this case, the chord genuinely sounds like Ab major; the spelling just assists the reader in seeing the voice-leading, perhaps.
Comment: @mathlander Yes, but allowing there might be a situation like the one I constructed where it really is just a chromatic passing chord and *doesn't* sound like Ab. In that case, it wouldn't be named, just designated as a passing chord.
Comment: So, it should just be called A♭ major, right?
Answer:
Raising the fifth of a major triad gives an augmented triad. For example, you can get from C (C-E-G) to C+ (C-E-G♯) by raising the fifth.

Correct.

...C-E♭-G♯, which is enharmonic to C-E♭-A♭

Not necessarily.
In tunings other than 12-TET and its multiples, this becomes a completely different chord. In this case, C–E♭–G♯ is a Cm(♯5) chord.

An E augmented triad is not a C inverted augmented triad, so is this new chord also functionally different from an inverted major triad?

Yes.


Get Div's Text in Drupal Forms API

Question: I have this code below:
$form['id']['mypreview_modal'] = array(
    '#type' => 'item',
    '#markup' =>
        '
12345
'
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'myid_user_page_form_ajax_submit',
    ),
);

function myid_user_page_form_ajax_submit() {
     $myid_user = ; //Get mypreview_modal's text/innerHTML
}

I want to get mypreview_modal text and assign it to myid_user. How will I do that?
Comment: As side note, an AJAX callback doesn't get any submitted value; it is not a submission callback at all. See the AJAX examples for Drupal, because the function parameters for myid_user_page_form_ajax_submit()` are wrong.
Comment: The best you could do is getting 12345 all times, but why would you need to get a value that doesn't change?
Comment: @kiamlaluno --> The div's text is dynamic. I just dont include the code that changes text in the div for brevity.
Answer: An AJAX callback is not a submission callback; the submission callback is the usual one a form uses, independently from the form using AJAX or not.
An AJAX callback is given the $form and $form_state parameters, allowing it to produce a result, which it returns for rendering. Since it gets $form as parameter, accessing that value simply means parsing $form['id']['mypreview_modal']['#markup'].
function myid_user_page_form_ajax_submit($form, $form_state) {
  // Parse $form['id']['mypreview_modal']['#markup'].
}

Keep in mind that usually an AJAX callback just returns the part of the form that needs to be rendered. See poll_choice_js() as example.
function poll_choice_js($form, $form_state) {
  return $form ['choice_wrapper']['choice'];
}

The rest is done from the submission handler. (In the case of the Poll module, and for the form using the previous AJAX callback, this is poll_more_choices_submit().)
  // If this is a Ajax POST, add 1, otherwise add 5 more choices to the form.
  if ($form_state ['values']['poll_more']) {
    $n = $_GET ['q'] == 'system/ajax' ? 1 : 5;
    $form_state ['choice_count'] = count($form_state ['values']['choice']) + $n;
  }
  // Renumber the choices. This invalidates the corresponding key/value
  // associations in $form_state['input'], so clear that out. This requires
  // poll_form() to rebuild the choices with the values in
  // $form_state['node']->choice, which it does.
  $form_state ['node']->choice = array_values($form_state ['values']['choice']);
  unset($form_state ['input']['choice']);
  $form_state ['rebuild'] = TRUE;

Answer: If you want to pass values you should just use one of the form api form elements.
Doing something similar to this
// This shows a preview to the user but doesn't actually pass any values.
$form['mypreview_modal'] = array(
    '#type' => 'item',
    '#markup' =>
        '
12345
'
);

// This passes the actual value (change this dynamically aswel).
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => 12345
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#ajax' => array(
        'event' => 'click',
        'callback' => 'myid_user_page_form_ajax_submit',
    ),
);

After form submission you will be able to access all the user input via the $form_state, notice that 2 parameters have been added to the submit handler.
function myid_user_page_form_ajax_submit($form, &$form_state) {
    $myid_user = $form_state['input']['id']; // Gets the value of the hidden form element.
}

On a side note, any submit button automatically calls the submit handler. Wich is normally used to process the input of the form. As previously mentioned you should use that instead of your custom ajax callback for processing.

Get Div's Text in Drupal Forms API


What is a "proper face" of a graph?

Question: This document uses the term "proper face". I do not know what this term means. At a guess, perhaps it could mean "a face that is not the external face"; but since the term "internal face" is a more obvious way to say the same thing, this seems somewhat unlikely.
I looked at the Wikipedia page "Glossary of Graph Theory", but it does not define this term (or at least, the string "proper face" does not occur anywhere on the page). I also searched this Stack Exchange site for the term, but the search did not return any results that I could understand and that related (so far as I can tell) to graphs.
Answer: You may rest assured that:

This is not common terminology, and
Neither of the two textbooks cited in "We assume the reader is familiar with basic graph theory appearing for example in [11, 26]" ever uses the term.

I would guess that "proper face" means "internal face" even though the term "internal face" would make much more sense. This is at least plausibly consistent with the context in the paper.
I did find another paper, An algorithm for the graph crossing number problem by Julia Chuzhoy, that seems to use "proper face" in this way. That paper defines $F_{\textsf{out}}$ to be the "outer face" and twice says that something is a "proper face, distinct from $F_{\textsf{out}}$".

Some related terminology that doesn't help:

A proper face-coloring of a planar graph is a coloring of the faces such that adjacent faces get different colorings. It has nothing to do with "proper faces": it is a "proper coloring" of the faces.
In the context of simplices or polytopes, a face doesn't have to be two-dimensional; vertices, edges, and higher-dimensional analogs are also considered faces. In this case, a proper face of $P$ is just a face that's not all of $P$ (by analogy with proper subsets).

What is a "proper face" of a graph?


How to search for multiple keywords in sql

Question: I have a current SQL search query that lets users enter keywords to search for my SQL database. At the moment, the search will work with multiple words, but only the same order, ie "Ford Mustang" will show results that include "Ford Mustang" in that exact order. If a user types in "Mustang" or "Mustang Ford" then no results show. How do I change the search query to show results that have both keywords, but not necessarily in the same order? I have search through this site and others and have found similar questions, but have not been able to find any answers that I have been able to work out.
public function getProductByName($name){
    $stmt = $this->pdo->prepare('SELECT * FROM tbl_products WHERE name LIKE :name');
    $name = "%".$name."%";
    $stmt->execute(array('name' => $name));
    return $stmt;
}

Someone suggested the following, which works to search for either keyword, but I need to search for both keywords, just not in order.
public function getProductByName($name){
    $stmt = $this->pdo->prepare('SELECT * FROM tbl_products WHERE name REGEXP :names');
    $names = "[[:<:]](" . str_replace(" ", "|", $name) . ")[[:>:]]";
    $stmt->execute(array('names' => $names));
    return $stmt;
}

Comment: Split the input and write multiple dynamic LIKE conditions... I'm sure you'll find a pre-existing answer on this site.
Comment: If someone searches for `red red wine`, how many times must the word `red` occur in the column?
Comment: sorry, it probably only needs to occur the once for each word
Answer: If you can alter your table to add FULLTEXT to your name column then you can use the Full text Search option.
select *
from tbl_products
where match(name) against ('+Mustang +Ford' in boolean mode)

Check demo here
Comment: A caution: https://hackernoon.com/dont-waste-your-time-with-mysql-full-text-search-61f644a54dfa and some words are ignored: https://www.w3resource.com/mysql/mysql-full-text-search-functions.php
Comment: A quote from w3resource: Boolean queries against a MyISAM search index can work even without a FULLTEXT index.


Google desktop on Server - indexing takes a long time

Question: How is your experience of Google desktop on server?
My server is relatively slow (quite slow actually). I have installed Google desktop to speed up the search process. It started indexing a week ago. It quickly started to 6% complete, then slowly and slowly ... 40% over the next 5 days. Now it just started to index again and has reached 6%.
While Google desktop runs quick and awesome on desktop, how is your experience with server? Are there things that I do not know?
I am running it on MS Windows Server 2003.
Answer: Why on earth would you install Google Desktop on a server? That's got bad idea written all over it. I don't mean that question rhetorically, either. I literally cannot think of a single legitimate reason to install it on a server and I'm curious about why you think your situation dictates its usage.
If the Microsoft-blessed Windows Search 4.0 isn't doing it's job, then you should figure out why. Clearly if you are having problems with both that and Google Desktop, you have a problem with your server. Break out perfmon and find your problem, don't try and hide it by trying a different tool.
Comment: @SavageGarden Even if it did, just because something is supported doesn't mean it's a good idea.
Comment: I also read Google Desktop does not support Win Server 2003.
Comment: But I do not know why it is a bad idea?
Comment: @SavageGarden What problem do you think it solves that you're currently facing? The general answer is that it's unnecessary software. Nothing that it does is useful on a server. Installing crap on a server exposes it to more security holes and can cause stability problems. The specific answer depends on what problem you're facing.
Comment: when I search server for a word, it takes hours to complete. The bottle neck which I found is memory (only 2GB on server).
Comment: @SavageGarden Why are you searching for files on the server? Do you have Windows Search 4.0 installed? Is the location that you're searching indexed? 2GB RAM is certainly not a lot, but if the files are indexed and the disk isn't being crushed, it shouldn't take that long. Methinks your problem is elsewhere.
Comment: I installed Windows Search 4.0 after this question and removed Google desktop. The server contains archive which needs to be searched once in a while.


Proof of generalized Eisenstein criterion

Question: Let $R$ be an integral domain, $P$ be a prime ideal of $R$. Let $f\in R[x]$, where $f(x):=a_nx^n +\dots + a_1x+a_0$, such that $a_n\not\in P$, $a_i\in P$ ($i<n$), $a_0\in P^2$. Then $f$ is irreducible.
I was trying to prove this by analogy with the proof in the book Contemporary Abstract Algebra by Gallian, but I have no idea what the author means when he says "... so there is a least integer $t$ such that $p\nmid b_t$. Also, where he says "Let $a_t=b_tc_0 + b_{t-1}c_1+\dots+b_0c_0$" - it is not clear where this is coming from and what this means. [Aside: Actually, I have been penalized several times for omitting much more obvious things in my proof. So, if Gallian wrote his proofs in an assignment or an exam in my university, he'd surely not get top marks].
I would appreciate your help in trying to figure out this stuff.
Comment: Come on... Did you try what he wrote ? Expand the coefficients of $g(x) h(x)$ and find a contradiction
Comment: Does the author of the book mean that $t$ is at most $r$?
Answer: In fact he wants to say the smallest $t$ such that $p$ does not divide $b_t$ such a $t$ exists since $p$ does not divide $b_r$ So $p$ divides $b_{t-1},...,b_0$.
The expression of $a_t$ comes from the multiplication of $g$ and $h$, he writes the coefficient $t$ of $gh$ ,if you write $a_t=b_ta_0+b_{t-1}c_1+...+b_0a_t$, you have $p$ divides $b_{t-i}a_i, i=1,...,t$. Since $p$ divides $b_{t-i}$, you deduce that $p$ divides $b_ta_0$ since $p$ divides $a_t$. This is impossible since $p$ is a prime and $p$ does not divide neither $a_0$ nor $b_t$.
Comment: Sorry, but you basically said the same words that the author of the book mentioned above. Unfortunately, this does not add any clarity. So, if $p$ does not divide $b_r$, then why is it supposed to divide some $b_t$. What *is* $b_t$, in the first place?

For your second paragraph, it is also not clear what the index $t$ stands for. Is $0 \le t< n$? It is not clear since the author did not define $t$.
Comment: $g(x)=b_0+b_1x+..+b^rx^r$. $t$ is an integer in the set $\{0,1,...,r\}$. The author says $p$ divides $b_0$ and $p$ does not divide $b_r$, so you can take $t$ to be the smallest integer such that $p$ does not divide $b_t$.
Comment: "Let us say $p|\;b_0$". So $p$ DOES divide  $b_t$ for some $ t\in \{0,1,...,r\}.$  He did not need to define $t.$ He defined $\{b_t: 0\leq t\leq r\}.$   And since $p\not |\;b_r$ but $p|\;b_0$  there exists a least non-negative integer $t$ such that $p\not |\;b_t$, and we must have  $t\leq r$.... It is customary in def'ns such as $g(x)=b_rx^r+...b_0$ to assume that $b_t$ only exists for integer $t\in \{0,...,r\}$.
Comment: Does the author of the book mean that $t$ is at most $r$?