How to get constant string array field into db_query?

Question: First post here :)
Here's a valid MySQL query: SELECT "'a','b'" AS FieldStrArray;
(To enter as a string in PHP, remember the backslashes before double quotes.)
At least in Drupal 7's db_query(), this produces a fatal PDO exception, complaining that 'a','b' is not a known field.
My question: how do I work around this apparent limitation of db_query()/PDO?
(Yes, I need a constant string array as one of the field results. This is a minimal replication of the problem... :) )
Any suggestions MOST welcome... including a) whether this is also a problem in PHP itself, b) how to report this as a bug to the Appropriate Authorities, c) Any creative ideas for a workaround assuming it is a real bug.
Thanks!
Answer: Not sure if this is a bug or not (I've seen weird things with single and double quote in PDO queries before), but either way you can work around it by using single quotes to wrap the expression:
$sql = "SELECT '\'a\',\'b\'' AS FieldStrArray";
$val = db_query($sql)->fetchField();
// $val == "'a','b'"

Comment: I would say take the slashes over the double apostrophe. Easier to read when you or someone else comes back to it later.
Comment: Hooray! Thanks, Clive.

Double-apostrophe quoting works too:
`$sql = "SELECT '''a'',''b''' AS FieldStrArray";`
Comment: Better than slashes or doubled-up quotes is to use a heredoc string. `$sql = <<<SQL\n  SELECT 'a', 'b' AS FieldStrArray;\nSQL;` Use actual newlines instead of `\n`.


Large regime asymptotics of sum

Question: Can we give an asymptotic description of the behaviour of the sum
$$F(x):=\sum_{\{n_1,n_2 \in \mathbb Z: n_1^2+n_2^2\le x\}}   (n_1+n_2)^2 $$
for large $x$?
I was thinking of rewriting this as a Riemann sum
$$F(x):=\left(\sum_{\{n_1,n_2 \in \mathbb Z: n_1^2+n_2^2 \le x\}}  1 \right) \times \frac{1}{\sum_{\{n_1,n_2 \in \mathbb Z: n_1^2+n_2^2 \le x\}}1  }\sum_{\{n_1,n_2 \in \mathbb  Z: n_1^2+n_2^2 \le x\}}   (n_1+n_2)^2 $$
but did not get anywhere with this.
EDIT: My apologies, it is $n_1^2+n_2^2$ in the summation index not $(n_1+n_2)^2.$ Please let me know if you have any questions.
Comment: It is not clear what you are trying to describe in the second paragraph. Try to be more precise there.
Comment: @the homeworker it is definitely $\Theta(x^2)$ (i.e. $c_1 x^2 \le F(x) \le c_2 x^2$ for some constants $c_1,c_2 > 0$). Did you want something more specific than this?
Comment: @mathworker21 yes, the constant $c=\lim_{x \rightarrow \infty} F(x)/x^2.$
Answer: $F(x) = \frac{\pi}{2}x^2+O(x^{3/2})$.
$$F(x) = \sum_{(n_1,n_2) : n_1^2+n_2^2 \le x} n_1^2+n_2^2+2n_1n_2.$$ Note that $\sum_{(n_1,n_2) : n_1^2+n_2^2 \le x} n_1n_2 = 0$ since we can pair up the terms $(n_1,n_2)$ and $(n_1,-n_2)$. We're left with $2\sum_{(n_1,n_2) : n_1^2+n_2^2 \le x} n_1^2$. We get a factor of $4$ by restricting to $n_1,n_2 \ge 0$. So we have $$8\sum_{n_1 \le \sqrt{x}} n_1^2\sum_{n_2 \le \sqrt{x-n_1^2}} 1 = 8\sum_{n_1 \le \sqrt{x}} n_1^2\left[\sqrt{x-n_1^2}+O(1)\right],$$ where, e.g., "$n_1 \le x$" means "$1 \le n_1 \le x$". Now, using the general $\sum_{n \le t} n^2 \sim \frac{1}{3}t^3$, we have $$8\sum_{n_1 \le \sqrt{x}} n_1^2 = O(x^{3/2}),$$ so ignore the $O(1)$ term above. We're left with $$8x^2\sum_{n_1 \le \sqrt{x}} \left(\frac{n_1}{\sqrt{x}}\right)^2\sqrt{1-\left(\frac{n_1}{\sqrt{x}}\right)^2}\frac{1}{\sqrt{x}},$$ which I wrote in this way so that it is basically the Riemann integral $8x^2\int_0^1 t^2\sqrt{1-t^2}dt$, which gives $\frac{\pi}{2}x^2$. The convergence of the sum to the Riemann integral can of course be justified fairly easily.
Answer: The easiest way to get the desired estimate is
\begin{align*}
&\int_{-\sqrt{x}}^{\sqrt{x}} \; \int_{-\sqrt{x-n_1^2}}^{\sqrt{x-n_1^2}} \; (n_1+n_2)^2 \, \mathrm{d}n_2 \, \mathrm{d}n_1  \\
&= \int_{-\sqrt{x}}^{\sqrt{x}} \; \frac{2}{3} (x+2n_1^2) \sqrt{x-n_1^2} \,\mathrm{d}n_1  \\
&= \frac{\pi}{2} x^2  \text{.}
\end{align*}
We might wonder if this estimate is even close to the true value of $F$.

Looking at the second line in the display, a guess at the error term is $O(x^{3/2})$.  (This method of guessing is usually wildly pessimistic.)  Plotting residuals, this seems feasible on $x \in [0,1000]$, but seems pessimistic as we push out further, to $x = 10\,000$.  (The dashed orange lines are $\pm x^{3/2}$.)

Continuing to larger $x$, we see that $O(x^{3/2})$ continues to be pessimistic...
Comment: Perhaps the question was not entirely clear, but what I would like to know is: How does  $F(x)$ grow as $x$ tends to infinity. Moreover, if the growth is let's say quadratically, then I am also interested in $a:=\lim_{x \to \infty} F(x)/x^2.$
Comment: @TheHomeworker : Answered.  $F(x)$ is infinitely large as soon as $x =1$.  You do realize that the set $\{(n_1, n_2): (n_1 + n_2)^2 =0\}$ contains infinitely many points?
Comment: @EricTowers I apologize. After seeing the OP's comment on your answer and then skimming through your answer, I thought you just said $F(x)$ goes to $\infty$ as $x \to \infty$, while OP asked for asymptotics for $F(x)$.
Comment: @TheHomeworker : For instance, $(0,0), (1,-1), (2,-2), \dots$ as well as $(-1,1), (-2,2), \dots$.
Comment: @EricTowers my apologies, I made a mistake in the set that we sum over. It is $n_1^2+n_2^2$ rather than $(n_1+n_2)^2$
Comment: @EricTowers you should delete this "answer" now
Comment: @mathworker21 : Why?

Large regime asymptotics of sum


Markov C++ read from file performance

Question: I have my 2nd assignment for C++ class which includes Markov chains.  The assignment is simple but I'm not able to figure out what is the best implementation when reading chars from files.
I have a file around 300k.  One of the rules for the assignment is to use Map and Vector classes.  In Map (key is only string) and values will be the Vectors.  When I'm reading from the file, I need to start collecting key pairs.
Example:
File1.txt
1234567890
1234567890

If Select Markov k=3, I should have in my Map:
key     vector
123  -> 4
456  -> 7
789  -> 0
0/n1 -> 2
234  -> 5
567  -> 8
890  -> /n
/n   -> NULL

The professor's suggestion is to read char by char, so my algorithm is the following
while (readchar != EOF){
tempstring += readchar
increment index
if index == Markovlevel {
       get nextchar if =!EOF
       insert nextchar value in vector
       insert tempstring to Map and assign vector
       unget char
}

}

I omit some other details.  My main question is that if I have 318,000 characters, I will be doing the conditional every time which slows down my computer a lot (brand new MAC pro).  A sample program from the professor executes this file in around 5 seconds.
I'm not able to figure out what's the best method to read fixed length words from a text file in C++.
Thanks!
Comment: Could you please reformat the code so it's more readable?
Answer: Repeated file reading will slow down the program.
Read the file in blocks, of say size 1024, put into a buffer. Then process this buffer as you require for the assignment. Repeat for the next block till you are done with the file.
Answer: Have you actually timed the program? 318,000 conditionals should be a piece of cake for your brand new MAC pro. That should take only microseconds.
Premature optimization is the root of all evil. Make your program work first, optimization comes second.
Comment: Thanks! will follow ur advise
software Dev phase :)

Markov C++ read from file performance


Is there any way to Import CSV file to Sqlite Database in Flutter way?

Question: I have been searching to import csv to database in flutter way. But unfortunately, I cannot find articles related to this case. So I wonder if there is a way to import csv to database. If yes, how can I achieve that? For my case, I open the file picker and want to import csv file. I can easily do it in Kotlin way but not in a flutter way. I would appreciate any help.
Comment: use https://pub.dev/packages/sqflite - most likely execute `db.insert` in a loop - one `insert` per row
Comment: I use sqlite, but how can I read contents and add them in sqlite database? In Kotlin I read with headLine(BufferedReader(file)) and remove "," and save in a array and insert to database. How can I achieve that way in Flutter since its been only 1 month that I started learning Flutter.
Comment: see `File.openRead()` and `LineSplitter`
Comment: OK, I will take a look
Comment: more here: https://fluttermaster.com/how-to-read-file-using-dart/ - i forgot that for small files you can use `File.readAsLines()`
Comment: btw, does it have to be csv file? why not a normal [sqlite dump](https://www.sqlitetutorial.net/sqlite-dump/)?
Comment: Yes it need to be CSV, because I need to import some csv files as Master to check Received Item.
Answer: Well, it's not straightforward.
You'd normally use something like https://pub.dev/packages/csv or https://pub.dev/packages/spreadsheet_decoder in order to parse CSV.
So it'd look something like:
final input = new File('documents/file.csv').openRead();

Then convert it to the list:
final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();

After you did that, you'd normally have a function that is going to do a bulk update.
First, create a database
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  await db.execute(
      'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});

Then you could use some helper method like mentioned here => https://stackoverflow.com/a/56507307/1737811 in order to populate the database fields with your result.
That way you'd pass your tablename, and of course your List containing the values from the CSV that you've just decoded.
Comment: Can you please tell me more about implementing some helper method? I don't get it.


can't connect to my sqlite database

Question: i have a windows phone application and am trying to connect to a database. The database is valid, i have verified. I am using codeplex's sqlite client to try to connect.
First i add my database to my project using ">add>Existing item>" and after that i try to connect using the code :
db = new SQLiteConnection(@"Database.db");
db.Open();

Debug.WriteLine("DB opened");
SQLiteCommand cmd = db.CreateCommand("SELECT * FROM Tags");
var lst = cmd.ExecuteQuery<Tags>();

foreach (Tags r in lst)
{
    Debug.WriteLine(r.Tag);
}
Debug.WriteLine(":D");

My Tags class looks like this :
public class Tags
{
    public int id { get; set; }
    public string Tag { get; set; }
}

And i get an error in the sqlite project ( in Sqlite3.Vdbe Prepare()) saying that there is no such table:Tags . The table is there, i've viewed the database and the name of the table is correct.
What am i doing wrong?
Comment: Shouldn't it look like
db = new SQLiteConnection(@"Data Source=Database.db");
Comment: doesn't work, the app can't find the location of the database
Comment: Just realized you're on WP7. I don't think it's supported there. On WP7 you can use either IsolatedStorage or XML files. If you need sql database - create a backend and call it via a web service. I know it's strange as both iOS and Android include sql support by default :(
Comment: @aloneguid from mango (wp7.5) there is a linq to sql database framework(-ish) but there are methods of implementing sqlite (just not natively, but in a way like a wrapper in isolatedStorage, but thought it might work outside of isolatedStorage)
Answer: Try supplying the full path instead of just the file name. I believe windows phone does not have a "current directory" so the application probably looks in the root folder.
If you supply a file that does not exist to the SQLite client, it will silently create an empty database for you and "connect" to that.
Comment: what is the entire path of a local file defined in the project's root? i try to give it the entire windows path but i guess the winPho7 VM doesn't allow it(outside the app's sandbox)
Comment: You may be able to use `Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).AbsolutePath)` to get the directory of the executable. Also, test `File.Exists(path_to_database)` prior to opening the connection so you can verify this is indeed the issue.
Comment: I wouldn't know how to get the project's root folder then. I have only worked with Windows CE devices (WinCE used to be quite similar to win mobile), no virtual devices. Perhaps someone else can help you with that? It shouldn't freeze, thats for sure.
Answer: i've found that my database must be in the IsolatedStorage. Here is a sample i found useful http://dotnetslackers.com/articles/silverlight/Windows-Phone-7-Native-Database-Programming-via-Sqlite-Client-for-Windows-Phone.aspx

can't connect to my sqlite database


Can we write a complex number z like this Re(z)+Im(z)?

Question: I mean without the i. Re(z) and Im(z) would be real numbers right?
Comment: No for the title, and yes.
Answer: No, but you can write it $z = \operatorname{Re}(z) + i \operatorname{Im}(z)$. (Note that $\operatorname{Im}(z)$ is a real number.)
Comment: The map $z=x+iy→x+y$ is not one-to-one. But if you supplement it with a second map $z=x+iy→x-y$  then you can retrieve z from both. However, I see no advantages in proceeding along these lines.
Comment: Are the $\Im$ and $\Re$ maps traditionally regarded as $\mathbb{C} \to \mathbb{R}$, or as $\mathbb{C} \to \{x+0i| x \in \mathbb{R}\}$. If the first, then when we write ${\Re}(z) + i {\Im}(z)$, the concatenation of $\Im(z)$ with $i$ is not really multiplication, right?
Answer: for $z\in \mathbb{C}$, we can write $z=a+b\mathrm{i}$. In this case $a=\mathrm{Re}(z)$, and $b=\mathrm{Im}(z)$.
Answer: Let a complex number $ z $ be: $ z = a + ib $; then we define $ \text{Re}(z) = a $ and $ \text{Im}(z) = b $.
As you see $ \text{Re}(z) $  and $ \text{Im}(z) $ are real numbers and thus the real number $ z_2 = \text{Re}(z) + \text{Im}(z) $ is different from $z$.
Answer: for $z\in \mathbb{C}$, we can write $z=a+b\mathrm{i}$. In this case $a=\mathrm{Re}(z)$, and $b=\mathrm{Im}(z)$.
Re(z) and Im(z) would be real numbers right?
Yes.
$\forall \, z \in \mathbb{C}, \exists! \, (a,b) \in \mathbb{R}^2, z = a + b\imath$
And you have:
Re(z) = a
Im(z) = b
Thus, Re(z) and Im(z) are real numbers.
Can we write a complex number z like this Re(z)+Im(z)?
Yes.
You can write a complex number z such as z = Re(z) + Im(z).
$z = 0$ works, for example.
Let's take $z \in \mathbb{C}, \exists! \, (a,b) \in \mathbb{R}^2, z = a + b\imath$.
$z = Re(z) + Im(z)$
$\Leftrightarrow a + b\imath = Re(z) + Im(z)$
$\Leftrightarrow a + b\imath = a + b$
$\Leftrightarrow b = 0$
Thus, $z = Re(z) + Im(z) \Leftrightarrow z \in \mathbb{R}$. In fact, all the real numbers works.


Post do v-form não manda dados

Question: Criei um formulário básico para ver se recebo dados na minha API utilizando o vuetify porém, ao dar o submit os dados do v-select não são enviados e não consigo compreender o motivo, já que em geral os exemplos destes formulários não fazem realmente uma requisição POST, segue trechos do código que estou utlizando:
 <v-form method="post" action="http://127.0.0.1:3000/produtos">
  <v-text-field name="escola" v-model="name" required :rules="nameRules"></v-text-field>
  <v-select
    v-model="selectPessoa"
    :items="pessoas"
    :rules="[v => !!v || 'Item is required']"
    item-value="id"
    item-text="nome"
    label="itens"
    required
    name="pessoa"
    return-object
    value="id"
  ></v-select>
  <v-btn color="warning" type="submit">Submit</v-btn>
</v-form>

Trecho do código javascript:
data(){
    return { pessoas: [{ id: 1, nome: "sandro" },
                       { id: 2, nome: "haiden" }],
             name: '',
             selectPessoa: null,
    }
}

A informação que eu digitar no v-text-field eu recebo na API node, mas a do v-select não:
Tela do formulário

Tela de log da API
Answer: Olá,
Seu erro está nessa linha:

value="id"

De acordo com a documentação de Interligação de Formulários VueJs
você tem que "bindar a id ao value" dessa forma:

v-bind:value="id"

Essa é a forma como o Vue referencia o Id ao Elemento.
Creio que isso resolva seu problema.
Comment: O bind para o id não funcionou pois não tenho uma propriedade id no 'data(){   }', resolvi meu problema tendo uma propriedade para campo no formulário e fazendo o post das propriedades name e selectPessoa através do axios.
Answer: Tente criar uma função para enviar seus dados para a API, segue o exemplo:
 <v-form method="post" action="onSubmit()">
  <v-text-field name="escola" v-model="name" required :rules="nameRules"></v-text-field>
  <v-select
    v-model="selectPessoa"
    :items="pessoas"
    :rules="[v => !!v || 'Item is required']"
    item-value="id"
    item-text="nome"
    label="itens"
    required
    name="pessoa"
    return-object
    value="id"
  ></v-select>
  <v-btn color="warning" type="submit">Submit</v-btn>
</v-form>

data(){
    return { pessoas: [{ id: 1, nome: "sandro" },
                       { id: 2, nome: "haiden" }],
             name: '',
             selectPessoa: null,
    }
},

methods: {
  onSubmit() {
    /* Aqui você envia os dados para a API (this.name e this.selectPessoa)
    Aconselho você a utilizar o Axios para esta tarefa */
  }
}

Post do v-form não manda dados


Can't logically find critical points but everything works

Question: I'm trying to find the critical points of:
$$ f(x,y) = (x^2 + 2y^2)e^{1-x^2-y^2} $$
I applied the product rule and chain rule for each of the partial derivatives to get these two:
$$f_x(x,y) = 2x(e^{1-x^2-y^2}) + (x^2 + 2y^2)(-2x)(e^{1-x^2-y^2})$$
$$f_y(x,y) = 4y(e^{1-x^2-y^2}) + (x^2 + 2y^2)(-2y)(e^{1-x^2-y^2})$$
When I set those two to zero I can reduce them to:
$$x^2 + 2y^2 = 1$$
$$x^2 + 2y^2 = 2$$
Which I'm pretty sure is right. Trying to solve those two I only get nonsense like
$1 = 2$ or the square root of a negative. I looked at the answer and the points are
$(1,0), (-1,0), (0,1), (0,-1), (0,0)$
I can see that those work out with the two formulas right above but I can't get there logically. Is there a flaw in my reasoning so far or do I just need to keep working to solve those two partials ? Also if $y$ is undefined for a value of x does that make it critical value of $x$ ?
Comment: One way you could check your work is to test one of the answer's critical points and see what happens.  For example, $(0,0)$ is a critical point according to your initial $f_x$ and $f_y$, but not according to your reduced equations.  So then you know that something went wrong when you took that step.
Comment: Why did you drop $x=y=0?$
Comment: "$y$ is undefined for a value of $x$" doesn't make sense. You mean that for a value of $x$, there are no values of $y$ where $(x,y)$ is a critical point?
Comment: Thanks I left (0,0) out because I thought of it as a gimmie
Answer: You cancelled out $x$ in the first equation and $y$ in the second. That leaves with the possibility of $x=0$ and $y=0$ providing critical points. In fact, $x=y=0$ gives the absolute minimum of $f$. Note that $x=0, x^{2}+2y^{2}=2$ and $y=0, x^{2}+2y^{2}=1$ also have solutions.
Answer: You lost some parts when you reduced your equations. They should read
\begin{align*}
2x(1-x^2-2y^2)e^{1-x^2-y^2} &= 0,\\
2y(2-x^2-2y^2)e^{1-x^2-y^2} &= 0.
\end{align*}
Sure, the exponential does not matter, but this system of equations has more solutions than yours, e.g., $x = 0$ solves the first equation and then you can solve for $y$ in the second one. You also get the solution $(0,0)$, which apparently the answer also missed.
Comment: How is this different than what I have above ? What I have is just a manipulation of (1−^2−2^2). If either expression in parentheses goes to zero then the whole thing becomes zero that's why I was solving for it individually. Is that correct ?
Comment: Yes, but you missed that $x = 0$ and $y = 0$ also cause the equations to be zero.
Answer: After eliminating the exponential factor (which is never zero), the system to solve should be
$$\begin{cases}
x(x^2 + 2y^2 - 1)=0\\
y(x^2 + 2y^2 - 2)=0
\end{cases}$$
From the first one we get
$$\begin{cases}
x=0\\
y(x^2 + 2y^2 - 2)=0
\end{cases}
\cup
\begin{cases}
x^2 + 2y^2=1\\
y(x^2 + 2y^2 - 2)=0
\end{cases}
$$
that is
$$\begin{cases}
x=0\\
y(y^2 - 1)=0
\end{cases}
\cup
\begin{cases}
x^2 + 2y^2=1\\
y=0
\end{cases}$$
or
$$\begin{cases}
x=0\\
y(y-1)(y+1)=0
\end{cases}
\cup
\begin{cases}
(x-1)(x+1)=0\\
y=0
\end{cases}$$
Therefore the critical points are $(1,0), (-1,0), (0,1), (0,-1)$ AND $(0,0)$ (which is a global minimum point since $f(0,0)=0$ and $f\geq 0$).
Comment: A little above my head thank you though


ARIMA model on yearly data using R

Question: Im new to time series forecasting, and I was trying to model the folowing time series data using ARIMA model in R, so that I can predict for the future 10 time periods.
data: cereal_dataset

When I try to decompose the time series using stl() I get the following error.
   Error in stl(cereal_ts, s.window = "per", robust = TRUE) : series is not periodic or has less than two periods

Also the ACF and PACF plots didn't return anything promosing.
# plot acf
acf(cereal_ts)
# plot pacf
pacf(cereal_ts)

Next I tried to fit a model using auto.arima() in R which returned ARIMA(0,0,0).
model <- auto.arima(cereal_ts)
summary(model)

Series: cereal_ts
ARIMA(0,0,0) with non-zero mean

Coefficients:
          mean
      178.5572
s.e.    2.5958

From the graph, it looks like something that can be modelled. Or am I looking at a dead end. Im new to time series forecasting, so please suggest any alternative or better way of doing it.
Comment: The link to the data set requires a password/permission. The data looks small enough that you can just run `dput(cereal_ts)` in R and paste the output into your question.
Comment: @AkselA you are not able to download it either?
Answer: stl() returns an error because your time series is not a priori periodic. In monthly or quarterly data, we expect possible yearly seasonality, i.e., recurring patterns with fixed cycle length (12 or 4, respectively). For these, we would set a frequency attribute for the time series object. There are very few yearly series where we would expect such a fixed cycle length (sunspots being one example).

From the graph, it looks like something that can be modelled.

Be very careful with this kind of intuition, especially in time series. In this field, it is extremely easy to spot "patterns" that simply do not exist, and are not useful for forecasting.
auto.arima() detects a model that is simply the long-run average, with no autoregressive or moving average dynamics that can be leveraged for forecasting. Looking at your time series and your ACF plot (I trust auto.arima() more than ACF/PACFs, Selecting ARIMA orders by ACF/PACF vs. by information criteria), that looks exactly right. I would absolutely trust this. auto.arima() is in my opinion the gold standard in automatic ARIMA modeling and forecasting. Yes, your forecast will be a flat line. And this is very probably the best you can do, as disappointing as this may be.
Here is a fun little exercise: simulate 19 time series off the fitted model, and with the same length as your series (arima.sim()). Randomly arrange these and your series in a $4\times 5$ grid. Does your focal series stand out in any way? Chances are it doesn't. (Also, show the grid to your friends and ask them whether one series stands out. Can they identify yours?) That is because its pattern is absolutely consistent with an ARIMA(0,0,0) process. See Source for inter-ocular trauma test for significance.
Some threads that may be useful:

Is it unusual for the MEAN to outperform ARIMA?
Resources/books for project on forecasting models with lots of resources on time series forecasting
How to know that your machine learning problem is hopeless? for the frustration you may be feeling about your flat forecast - see also Kolassa (2023); feel free to ping me on ResearchGate for that paper if you are interested

ARIMA model on yearly data using R


Envio de formulário para banco de dados com Mysql, Html e php

Question: Estou tentando mandar para um banco mysql os dados gravados por um formulário. Tenho criado um BD 'db_provida' e uma tablela 'testemunho' com 4 colunas. Eu não consigo fazer esse código gravar o registro. Aqui os componentes:
Tabela 'testemunho':

Código html:
<form action="testemunho.php" method="post">
    Nome: <input type="text" name="nome"/>

    Email: <input type="text" name="email"/>

    Testemunho: <textarea name="testemunho" rows="10" cols="80"></textarea>

    <input type="submit" value="Enviar"/>
</form>

E código php:
<?php
    //verifica se existe conexão com bd; caso não tenta, cria uma nova
    $conexao = mysql_connect('localhost','giuseppe','joanin21') //porta, usuário, senha
    or die("Erro na conexão com banco de dados"); //caso não consiga conectar mostra a mensagem de erro mostrada na conexão

    $select_db = mysql_select_db("db_provida"); //seleciona o banco de dados

    //Abaixo atribuímos os valores provenientes do formulário pelo método POST
    $nome = $_POST['nome'];
    $email = $_POST['email'];
    $testemunho = $_POST['testemunho'];

    $string_sql = "INSERT INTO testemunho (id,nome,email,testemunho) VALUES (null,'$nome','$email','$testemunho')"; //String com consulta SQL da inserção

    mysql_query($string_sql,$conexao); //Realiza a consulta

    if(mysql_affected_rows() == 1){ //verifica se foi afetada alguma linha, nesse caso inserida alguma linha
        echo "
Testemunho Registrado
";
        echo 'Voltar para formulário de cadastro'; //Apenas um link para retornar para o formulário de cadastro
    } else {
        echo "Erro, não foi possível inserir no banco de dados";
    }

    mysql_close($conexao); //fecha conexão com banco de dados
?>

Comment: Qual o erro? [Recomendo](https://pt.stackoverflow.com/questions/579/por-que-n%C3%A3o-devemos-usar-fun%C3%A7%C3%B5es-do-tipo-mysql/4675#4675).
Comment: Oi Francisco! É que não encontro nada de gravado na tabela 'testemunho', nem ele apresenta qual erro está acontecendo. Como se o formulário não passasse pelas tags do testemunho.php.
Comment: editei a resposta com mais detalhes e também um exemplo do seu código rodando no meu servidor
Comment: Oi Leo!Muito obrigado por compartilhar os seus conhecimentos. Eu trabalho num centro de telecomunicações de uma universidade e, somente agora me dei conta que o ambiente da minha máquina (compartilhada com outros usuários) tem o mariaDB como gerenciador de banco de dados e o nginex como servidor web. Ainda estou controlando, mas acho que o problema da falta de comunicação com o DB deve ser uma questão do ambiente da localhost.
Comment: Ok Leo! De fato, deletei tudo o que tinha no www - onde até tinha um Joomla instalado - e, colocando este teu código, tudo voltou a funcionar certinho, também com a gravação das strings. Obrigado mano!
Comment: então não deixe de ler esse post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Answer: A query que você coloca na variável $string_sql está considerando as variáveis $nome, $email e $testemunho como string. O maneira certa de fazer isso, ou seja, pras variáveis não serem consideradas string, tem que ser feito assim:
$string_sql = "INSERT INTO testemunho (id,nome,email,testemunho) VALUES (null,'{$nome}','{$email}','{$testemunho}')"; //String com consulta SQL da inserção

Comment: Oi! Substitui a linha mas ainda não está gravando na tabela. Além disso, não está mostrando nem o erro de conexão previsto no php.
Comment: Coloca isso no começo do arquivo PHP: `ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);` . Roda o código de novo e vê se vai mostrar algum erro.
Comment: eu uso values ('$nome', sem problemas
Answer: Eu rodei seu script com PHP 5.4.43 e rodou direitinho!
Só ficou faltando um if (isset($_POST... para que não haja insert ao entrar na pagina, pois do jeito que está vai inserir campos nulos ao acessar a página. Depois preenchendo os campos vai inserir direitinho!
Seu caso deve ser o abaixo explicado.
As funções mysql_connect, mysql_affected_rows ficaram obsoletas no PHP 5.5.0 e as funções mysql_ * foram removidas no PHP7!  Saiba mais com []
Aproveita a ocasião e atualize-se!
Com MySQLi  a conexão pode ser feita do seguinte modo:
//aqui é só um exemplo para não rodar o script abaixo sem necessidade
if ((isset($_POST['email']))&&(!empty($_POST['email']))){

   //porta, usuário, senha, nome data base
   //caso não consiga conectar mostra a mensagem de erro mostrada na conexão
   $conexao = mysqli_connect("localhost", "giuseppe", "joanin21", "db_provida") or die("Erro na conexão com banco de dados " . mysqli_error($conexao));

  //Abaixo atribuímos os valores provenientes do formulário pelo método POST
  $nome = $_POST['nome'];
  $email = $_POST['email'];
  $testemunho = $_POST['testemunho'];

   $string_sql = "INSERT INTO testemunho (id,nome,email,testemunho) VALUES (null,'$nome','$email','$testemunho')";
   $insert_member_res = mysqli_query($conexao, $string_sql);
   if(mysqli_affected_rows($conexao)>0){ //verifica se foi afetada alguma linha, nesse caso inserida alguma linha
       echo "
Testemunho Registrado
";
       echo 'Voltar para formulário de cadastro'; //Apenas um link para retornar para o formulário de cadastro
   } else {
       echo "Erro, não foi possível inserir no banco de dados";
   }
   mysqli_close($conexao); //fecha conexão com banco de dados
}else{
    echo "Por favor, preencha os dados";
}


How to precompile ASP.NET 4.0 to a Single DLL with VS 2010

Question: I recently upgraded from VS 2003 where I was working on a ASP.NET 2.0 website to VS 2010 where I have migrated to ASP.NET 4.0.  So far it has been a big headache to get my site compiling with the new version.  One problem was that my aspx.cs pages could not find the shared code libraries in my project.  I solved this by moving my shared code to the App_Code folder (if there's a different/better way to do it please let me know).
Another issue that I am finding confusing is with pre-compilation.  With VS 2003 I could click the build project button and it would precompile my site into a myweb.dll and myweb.pdb files.  Now I'm having trouble doing the same in VS 2010.  When I build the site in VS 2010 the dll is not created.  I did manage to find an option to "Publish" the site which takes forever (like 2 minutes) and involves duplicating the site to another folder.  This would have been acceptable but instead of making the single DLL file, it makes a bunch of files: App_code.compiled, app_code.dll, App_code.pdb, App_global.asax.compiled, App_global.asax.dll, App_global.asax.pdb, App_Web_lrpcway1.dll, App_Web_lrpcway1.compiled, App_Web_lrpcway1.pdb.
The application works - I can deploy it with all these files.  However, I'd really like someone to explain what are the extra files and if there is a better way how to do it.
Thanks
Comment: asp.net 2.0 with vs 2003? typo?
Answer: This is the difference between a website and a web application.
You can convert your website to a web application to have it
behave more like you are used to.
The files in appCode are compiled when required to run and thus
does not provide dll.s in the bin/debug folder, but they should
be created when the application actually runs (but it is not
put in the same location).
Here is a nice write up about it Link
Answer: You can use the ASP.NET Merge Tool to combine all of the little DLLs into one big one.
http://msdn.microsoft.com/en-us/library/bb397866.aspx


How to decide which physical interface RMI Transport Layer should use?

Question: When I use a remote reference from the client everything is OK. If I try to use this remote reference from the simu, the communication failed because the server try to use the IP from eth0. What bothers me is that the exception gets reported on the simulator.
I think I missed something?
[EDIT]
The simu provides this exception:

java.rmi.ConnectIOException: Exception creating connection to eth0_IP;
nested exception is: java.net.SocketException: network is unreachable
Answer: You need to set the java.rmi.server.hostname property to tell the RMI Registry which hostname or IP Adress to return in its RMI URLs.
This defaults to the IP address of the first interface on the system which explains why it's only working through eth0.
So you'll need something like:
String ipAddress = "10.1.2.3"; //IP address of eth1
System.setProperty("java.rmi.server.hostname",ipAddress);

or
String hostname = "myserver"; //hostname that resolves for client and simu
System.setProperty("java.rmi.server.hostname",hostname);

Comment: @chepseskaf - The setting on the server affects the data sent to the client.  The client is connecting to the RMI Registry via `eth1` and asking where the RMI service is and being told something like `rmi://eth0/yourservice`.  You can use the `java.rmi.server.hostname` property to set the hostname/IP address returned by the RMI Registry.
Comment: This property has to be set on the server, but I think the problem will occur for the client...
Comment: Thank you, it works! Sorry to be so slow, I was not seeing things the same way.
Comment: The setting does not 'tell the RMI Registry which hostname or IP Adress to return in its RMI URLs'. It affects the contents of the remote stub itself, when it is first constructed when the remote object it refers to is exported.


Como limpar/resetar bootstrap fileinput após de selecionar nova imagem?

Question: Estou tentando limpar/resetar após de selecionar nova imagem.
Após de selecionar imagem, limpar Initial Preview
Segue o código:
HTML:
<input id="input-pd" name="input-pd[]" type="file" multiple class="file-loading">

JS:
$("#input-pd").fileinput({
    uploadUrl: "/file-upload-batch/1",
    uploadAsync: false,
    minFileCount: 2,
    maxFileCount: 2,
    overwriteInitial: false,
    initialPreview: [
        // IMAGE DATA
        "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Desert.jpg",
        // IMAGE DATA
        "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Lighthouse.jpg"
    ],
    initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
    initialPreviewFileType: 'image', // image is the default and can be overridden in config below
    purifyHtml: true, // this by default purifies HTML data for preview
    uploadExtraData: {
        img_key: "1000",
        img_keywords: "happy, places",
    }
}).on('filesorted', function(e, params) {
    console.log('File sorted params', params);
}).on('fileuploaded', function(e, params) {
    console.log('File uploaded params', params);
});

    $('#input-pd').on('change', function(event) {
        $('#input-pd').fileinput('clear');
        $('#input-pd').fileinput('reset');
        //$('#input-edit').fileinput('refresh');
    });

Aqui está em jsfiddle: https://jsfiddle.net/DTcHh/30077/
Alguma solução ?
Answer: Às vezes estamos tão concentrados a "focar a imagem de perto quando deviamos estar a focar de longe".
Penso que foi apenas uma falta de atenção no código. Se reparares bem tens ali uma opção desse plugin logo no início do código que diz:
overwriteInitial: false,

Basta apenas trocá-la para:
overwriteInitial: true,

https://jsfiddle.net/shuffledPixels/DTcHh/30078/
$("#input-pd").fileinput({
    uploadUrl: "/file-upload-batch/1",
    uploadAsync: false,
    minFileCount: 2,
    maxFileCount: 2,
    overwriteInitial: true,  /** <-- ###### Aqui está a opção a que me referi acima */
    initialPreview: [
        // IMAGE DATA
        "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Desert.jpg",
        // IMAGE DATA
        "http://kartik-v.github.io/bootstrap-fileinput-samples/samples/Lighthouse.jpg"
    ],
    initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
    initialPreviewFileType: 'image', // image is the default and can be overridden in config below
    purifyHtml: true, // this by default purifies HTML data for preview
    uploadExtraData: {
        img_key: "1000",
        img_keywords: "happy, places",
    }
}).on('filesorted', function(e, params) {
    console.log('File sorted params', params);
}).on('fileuploaded', function(e, params) {
    console.log('File uploaded params', params);
});

$('#input-pd').on('change', function(event) {
    $('#input-pd').fileinput('clear');
    $('#input-pd').fileinput('reset');
    //$('#input-edit').fileinput('refresh');
});


Each column has at most $s$ zeros, the matrix has rank $\leq s+1$?

Question: Each column has at most $s$ zeros, the $n\times n$ matrix has rank $\leq s+1$?
Is this true? Can we prove this by induction on $n$ or $r$?
Comment: The identity matrix is a counterexample.
Comment: Please consider that it may be a bit rude to radically change the problem after it's already been answered.
Comment: Generate a random large matrix with a random real entry from $[-1,1]$. It is almost certain that each column has no zeros, and it is almost certain that the matrix is of full rank.
Comment: @user i am sorry for this. I may post another problem in later convenience.
Answer: This answers the revised post. Let $I$ be the $n\times n$ identity matrix. To make the matrix $A$, add $2$ to every entry of $I$. The matrix $A$ has full rank.  For its determinant is congruent to $1$ modulo $2$.
The matrix $A$ has at most $0$ zeros in each column. Thus $A$ has rank $\gt s+1$ for all $n\ge 2$.
Comment: The matrix $A$ has full rank?
Comment: @xldd: It does. But I changed it a little to make the fact of full rank trivial.
Comment: I have no idea on your idea.
Comment: We show that the $n\times n$ matrix with $3$'s down the main diagonal and $2$'s elsewhere is of full rank (invertible). Imagine finding the determinant in the usual way. The determinant will be odd, and therefore non-zero.


Java Beginner: the mechanism behind "|" operator in Shell s = new Shell(d, SWT.CLOSE | SWT.RESIZE);

Question: hi I was wondering about the mechanism behind the "|" operator in the next code.
Display d = new Display( );
Shell s = new Shell(d, SWT.CLOSE | SWT.RESIZE);

p.s: I already checked the source code, but didn't understand
Comment: http://en.wikipedia.org/wiki/Bitwise_operation - not about java, but it's like essential knowledge for any kind of programming. In a nutshell, SWT.CLOSE and SWT.RESIZE are integers which in binary representation only have 1 bit set (but different bits). When you combine them you get the an integer with both those bits set. And each bit sort of represents one option, that way you can keep many options in one integer value.
Answer: SWT.CLOSE and SWT.RESIZE are int flags. the | means Binary OR between them which meant for passing both of them.
For example. if RESIZE = 1 (00000001 binary) and CLOSE = 2 (00000010 binary), SWT.CLOSE | SWT.RESIZE = 3 (00000011 binary) and later on the method called will know to respcet them both.
Edit - what's next
If the constructor behaves according to the flags, it might look like this:
public Shell(Display d, int flags)
{
      if ((flags & SWT.CLOSE) > 0)//the close flag is on
      { /*do some stuff*/ };
      if ((flags & SWT.RESIZE) > 0)
      { /*do some stuff to enable resize..*/ };
}

Now, instead of passing many unnecessary arguments to the constructor, we tell it with one argument (flags) many things to do. The first if for example, checks if the CLOSE flag is set in flags: flags = 3 (00000011 binary) (as we set it before) SWT.CLOSE = 2 (00000010 binary) and flags & SWT.CLOSE = 3 & 2 = 00000010 binary which is bigger than zero and is set.
Comment: thanks alot but does this mean, that there is an option== 3, why not use it instead ? doesn't this complicate things more ? I mean what's the benefit of doing this
Comment: There could be a lot of possible combinations (2^32). So it's better and easier to use like this.
Answer: It's the bitwise OR operator.
Using correct integers it can be used to define options. If your integers are - but not necesseraly - set unique bits in an integer it can be used on the accepting method to select options.
Example:

Highlight foreground: 001 => 1 (HIGHLIGHT_FG)
Highlight background: 010 => 2 (HIGHLIGHT_BG)
Bold: 100 => 4 (BOLD)

So oring the constants BOLD | HIGHLIGHT_FG will be 5.
But it can be defined also a HIGHLIGHT_ALL with 011 => 3.
Answer: It's the bitwise or operator. In this case it is used for a bitfield, i.e. SWT.CLOSE | SWT.RESIZE sets two bits in an integer variable.
Answer: What is your question, exactly?
The pipe operator is a bit-wise inclusive OR operation.
In general when programming, it lets you OR two values bits together. For example,
0001b | 0010b yields 0011.


Can rpcbind packagebe removed in debian wheezy, installed by default?

Question: After installing new debian server, i made intense scan on it to check that it does not have redudant software/open ports.
I found that port 111 is used via rpcbind daemon (debian wheezy installs rpcbind package by default).
I found that they are used for NFS. Does they affect anything else?
Can i remove this package, and will my server keep safe after that?
Answer: Actually rpcbind included with the nfs-client package isn't installed by default. It's installed by default if you choose the "standard system utilities" in the tasksel menu during installation.
It's safe to remove everything from this list if you don't want a "bloated distribution". As example it will not install Exim4 MTA, which in my opinion is a waste of time on small server.
If you need NFS Client services just install the nfs-client package after the installation and you'll keep a low footprint on your server box.
Answer: Yes, you can safely remove rpcbind if you don't plan on using NFS on your server.
Comment: I confirm mounting a NFS share works without rpcbind on the client. Thanks @Thor.
Comment: I use NFS as a client, not as a server (/var/git is mounted as an NFS share from another server on my LAN). Can I still remove rpcbind?
Comment: @Cyrille yes, I think you can still remove it. From https://access.redhat.com/site/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Storage_Administration_Guide/s2-nfs-methodology-portmap.html: "RPC processes notify rpcbind when they start, registering the ports they are listening on and the RPC program numbers they expect to serve. The client system then contacts rpcbind on the server with a particular RPC program number. The rpcbind service redirects the client to the proper port number so it can communicate with the requested service". There are no services on a client. But, test first.


What kind of "measure" is $dB_{t}(\omega)$

Question: In stochastic integration one considers integrals as $L^2(P)$ limits of simple functions w.r.t  $dB_{t}(\omega)$ where $B$ is standard brownian motion.
It is not clear to me what kind of object this $ dB_{t}(\omega)$ is, it is certaintly not a measure in the usual sense. How should one think about this object? And is there a name for it in general?
Comment: The idea is to consider $\int f_t d(B (t,\omega) )$ as a generalisation of the Riemann-Stieltjes integral indexed by the $\omega$ in the probability space, only of course $B_t$ is not of bounded variation and so more work has to be done - the resulting construction is I think pretty unanimously known as the Ito integral, and so $dB_t(\omega)$ is the integrator of the Ito integral.
Comment: @Nadiels right, but these kind of object has no name in general?
Comment: For the Riemann-Stieltjes integral the term $d g(x)$ often gets referred to as the integrator, so I would be reasonably happy to refer to $dB_t(\omega)$ as the integrator of the Ito-integral, I'm afraid I don't know if there is a more universally accepted name though
Answer: This is not a measure in the usual sense, but in a probabilistic sense.
Specifically, let $\mathcal B_f(\mathbb{R})$ denote the family of Borel sets having finite Lebesgue measure.

An independently scattered Gaussian measure (with Lebesgue control measure) is a random set function $$\{B(A,\omega),A\in \mathcal B_f(\mathbb{R}), \omega\in \Omega\}$$ (you can understand this a $\mathcal B_f(\mathbb{R})$-indexed stochastic process) such that

for any $A\in \mathcal B_f(\mathbb{R})$, $B(A)$ is a centered Gaussian random variable with variance $\lambda(A)$;
for any disjoint $A_1,A_2,\dots,A_n \in \mathcal B_f(\mathbb{R})$, the random variables $B(A_1),B(A_2),\dots,B(A_n)$ are independent;
for any disjoint $A_1,A_2,\ldots \in \mathcal B_f(\mathbb{R})$ such that $\bigcup_{n=1}^\infty A_n \in \mathcal B_f(\mathbb{R})$,
  $$
B\biggl(\bigcup_{n=1}^\infty A_n\biggr) = \sum_{n=1}^\infty B(A_n)\quad \text{ a.s.}
$$

Using it, you can define various objects like

Wiener process (Brownian motion) $B_t = B([0,t])$;
stochastic integral etc.

However, here are some important remarks.

In the Gaussian case, the independence is equivalent to orthogonality, and the almost sure convergence of a series with independent terms is equivalent (thanks to the Kolmogorov three series theorem) to the mean-square convergence. So any reference on measures with orthogonal increments will do.
Despite the $\sigma$-additivity is in almost-sure sense, the exceptional set depends on the particular sequence of sets. And there is no version of $B$ which is a signed measure for almost all $\omega$, so it is not possible to define the integral w.r.t. $B$ as that w.r.t. a signed measure; it can just be defined in the mean-square sense (you should know this already).
Comment: @user1, see the updated answer.
Comment: Nice ! You know a good reference for this approch?


Prevent automatic rounding off in Java

Question: I am trying to prevent automatic rounding off in Java. As mentioned below, I am using 2 variables which is x and y double variables.
double x = 1.05d;
double y = 2.55d;

System.out.println(x + y); => 3.5999999999999996

When I tried to sum these 2 variables, it gave me 3.5999999999999996 like number with higher precision. I want to prevent this behaviour without using BigDecimal. Is there any solution?
Comment: Yes, because floating point math is not exact. If you need arbitrary precision math, use `BigDecimal`.
Comment: If you can live with rounding errors, you can always use `Math.round` or format with `"%.2f"` as format specifier
Comment: @knittl I have another problem too. Assume that, this happened inside a calculating process and we are expecting 3.6. But java gives that 3.5999999. This means my logic will be runied know?
Answer: Here is a method you can use to round double data type values to whatever precision you like. Read the comments in code:
/**
 * Will round a double data type value either Up (default) or Down with
 * whatever desired precision.
 *
 * @param value (double) The double data type value to round.
 *
 * @param precision (int) The desired decimal precision. If you provide 0
 * as a precision value then there will be not decimal component, it will
 * be 0, for example if rounding up (default) 3.5 then 4.0 will be returned.
 * If rounding down 3.5 then 3.0 will be returned
 *
 * @param roundDown (Optional varArgs - boolean) Default is false which
 * tells the method to round up if the next digit after the precision is
 * 5 or more. If true is supplied then the value is rounded down but only
 * if the next digit after the precision is 5 or less. If next digit after
 * precision is greater than 5 then the value is rounded up.
 *
 * @return (double) The supplied double type value returned as a rounded
 * double type value.
 */
public double round(double value, int precision, boolean... roundDown) {
    boolean rndDown = false;
    if (roundDown.length > 0) {
        rndDown = roundDown[0];
    }
    return java.math.BigDecimal.valueOf(value).setScale(precision,
            (rndDown ? java.math.RoundingMode.HALF_DOWN :
                    java.math.RoundingMode.HALF_UP)).doubleValue();
}

This is how you might use the above method:
double x = 1.05d;
double y = 2.55d;
double sum = x + y;

System.out.println("Original Sum: " + sum);

double val = round(sum, 1);   // Precision of 1.

System.out.println("Rounded Sum to a precision of 1: " + val);

The Console Window should display:
Original Sum: 3.5999999999999996
Rounded Sum to a precision of 1: 3.6

Prevent automatic rounding off in Java


window function to identify what values are for a key over month

Question: I have data that looks like this:
product | month | purchased
a           jan     online
a           jan     instore
b           jan     online
c           jan     instore

what I want to do is identify how the product was purchased in a given month in the same result set like this:
product | month | purchased | method
a           jan     online      online-instore
a           jan     instore     online-instore
b           jan     online      online
c           jan     instore     instore

I was wondering if there was a way to write a window query that could do this instead of writing a separate query and then joining that back to the result set.
Answer: MIN/MAX windows functions can be used:
SELECT product, month, purchased,
       CASE max( purchased ) OVER (partition by product, month )
       WHEN min( purchased ) OVER (partition by product, month )
       THEN min( purchased ) OVER (partition by product, month )
       ELSE max( purchased ) OVER (partition by product, month )
            || '-' ||
            min( purchased ) OVER (partition by product, month )
       END As method
FROM Table

Answer: select
  product, month,
  array_agg(purchased) over (partition by product, month) as method
from
  your_table
group by
  product, month, purchased;

If you want exactly method1-method2-... result then change array_agg(purchased) to string_agg(purchased, '-')


Congruence Proof Graham

Question: My problem is the following:
1) gcd(a,b)=1. I need to prove that $$\gcd(a-b, c_0a^n+c_1a^{n-1}b+...+c_{n-1}ab^{n-1}+c_nb^n)=\gcd(a-b, c_0+c_1+...c_n).$$ I know that $x \equiv y$ (mod m) implies $\gcd(m, x)=\gcd(m, y)$. So I am looking to rewrite $c_0a^n+c_1a^{n-1}b+...+c_{n-1}ab^{n-1}+c_nb^n$ and to put it in the following form $(a-b)*(...)+(c_0+c_1+...c_n)$. Can you help me?
2) Also, using $a=10$ and $b=1$, I need to "derive the test for divisibility by 9" from the previous formula.
Thank you.
Comment: You should assume that a and b are relatively prime.
Comment: Yes, I edited, I forgot to mention it.
Answer: Hint $ $ By Euclid $\ \gcd(a\!-\!b,f(a,b)) = \gcd(a\!-\!b, f(a,\color{#c00}b)\bmod a\!-\!b) = \gcd(a\!-\!b,f(a,\color{#c00}a))\ $ for any polynomial $\,f\,$ with integer coefficients, by applying $\,\color{#c00}{b\equiv a}\pmod{\!a\!-\!b}$

Congruence Proof Graham


JsTree-grid undefined value from JSON

Question: JsTree-grid plugin won't work as expected for me. I am getting node data (including data for grid columns) by AJAX request responding by JSON file.
JS snippet:
<code>    .jstree({
    'core' : {
        'data' : {
            'url' : '/cms/ajax/ajax_json_tree.php?table=subpages_tree&operation=get_node',
            'data' : function (node) {
                return {
                    'id' : node.id,
                    'seo_title' : node.seo_title
                };
            },
            'dataType' : 'json'
        },
        'check_callback' : true,
        'themes' : {
            'responsive' : false
        }
    },
    'plugins' : ['state','dnd','contextmenu','grid'],
    grid: {
        columns: [
            {width: 300, header: "Name"},
            {width: 100, header: "SEO", value: "seo_title"}
        ]
    },
    'force_text' : true

})
</code>
JSON response from:
/cms/ajax/ajax_json_tree.php?table=subpages_tree&operation=get_node
<code>[
   {
      "id":255,
      "text":"NEWS",
      "children":true,
      "seo_title":"news"
   },
   {
      "id":256,
      "text":"DEVWEBMAIL",
      "children":false,
      "seo_title":"devwebmail"
   }
]
</code>
Somehow node.seo_title is always undefined. Can you explain why this is? It seems the problem is with the grid plugin integration in jstree.
Versions: I am using jstree 126.96.36.199 and jstreegrid 3.4.2.
Answer: Finally, I`ve make it work. The problem was in JSON data file. It has to have a bit different data structure:
<code>[
   {
      "id":255,
      "text":"NEWS",
      "children":true,
      "data" {
          "seo_title":"news"
      }
   },
   {
      "id":256,
      "text":"DEVWEBMAIL",
      "children":false,
      "data" {
          "seo_title":"devwebmail"
      }
   }
]
</code>

JsTree-grid undefined value from JSON


"Property does not exist in type"

Question: I've recently started studying Angular and I'm currently working on an assignment, which is about making a form with radius inputs. After doing the form, I'm working now on checking if the answers are correct, but I'm getting two errors when doing this check. What I'm trying to do is, to delete from the array all incorrect answers (value = 0).
This is the HTML file:
 <form>

{{question.question}}

      <input class="subtotal" type="radio" name="{{question.question}}" value="{{alternative.value}}"> {{alternative.answer}}

</form>

This is the Typescript file:
  sumValue(){
    let radius = document.querySelectorAll(".subtotal:checked");
    if(radius.length == 11){
      console.log(radius);
      for (let index = 0; index < radius.length; index++) {
        console.log(radius[index].value);
        if(radius[index].value == 0){
          radius.splice(index, 1);
        }
      }
    } else {
      console.log('error');
    }
  }

On the "console.log(radius[index].value);" I get the following error:
[ts] Property 'value' does not exist on type 'Element'.

And on "radius.splice(index, 1);" I get:
[ts] Property 'splice' does not exist on type 'NodeListOf<Element'.

I still haven't reputation to post images yet, but this is the view on VSCode
I appreciate any help and explanations on other ways to solve my problem which is, how to leave in the array only the answers that are correct. Thank you!
Comment: check if the value property exists before using it directly
Comment: The console.log(radius[index].value) shows the values on the console, but it says they don't exist. How do I check if it exists or declare it? Thank you
Comment: check if the value exists for every items. It might happen that value exists for some item and doesn't for other. Then it will throw error. So check it like that if (radius[index] && radius[index].value){......}
Comment: And btw, you can't use splice in Nodelist. querySelectorAll returns a Nodelist which is diff than array. You can't use splice(), push(), join(), indexOf(), and many other methods on Nodelist.
Comment: Oh I see, damn I don't know how to get the values from the arrays anymore then.
Comment: you can convert it to an array tho. use foreach and push every item in an actual empty array. Then Nodelist will be be converted into an array with all the methods available. If you using Ecmascript 6 then you can do it with one liner: var arr = Array.from(radius);
Answer: What you are seeing is a type error.
When calling document.querySelectorAll, it returns a NodeList<Element> because it doesn't know that the matched elements are going to be <input/>s. What it returns instead is the base type for all elements, which is a super class of <input/>.
The second issue is that NodeList does not have a splice method.
To fix the first issue, you can give the radius variable a type:
let radius: NodeList<HTMLInputElement> = document.querySelectorAll(".subtotal:checked");

However, your use of HTML elements in the component is not the "correct" angular way. You do not want to access HTML elements directly in your angular component - you want to maintain separation between your page and the logic behind it. Instead, you can use Angular's binding system. More specifically, ngModel:
 <form>

{{question.question}}

      <input class="subtotal" type="radio" [attr.name]="question.question" [value]="alternative.value" [(ngModel)]="question.answer"> {{alternative.answer}}

</form>

Now, whenever the user edits the input, the question.answer property gets updated automatically. In your component, you can iterate over the structure to remove invalid alternatives:
sumValue(){

    this.questions.forEach(question => {
        question.alternatives = question.alternatives.filter(a => a.value != 0);
    });

}

This code uses the filter method of an array to create an array of just the elements with values that are not equal to zero. We can then use that to replace the old alternatives array. Angular will handle rendering the page to reflect the changes in data.
You can read more about ngModel here.
You can also read more about how to use radio buttons with angular here.
Comment: Thanks! This solved the compilation problem, but has led me to another one. The console now logs "Error: If ngModel is used within a form tag, either the name attribute must be set or the form
      control must be defined as 'standalone' in ngModelOptions.". I tried setting a name to it, or using the [ngModelOptions]="{standalone: true}", when I do this the compilation happens without errors, but when I choose one option, it marks the last wrong answer in all 10 questions, or the right answer in all of them if the first one chosen is the correct one. I really appreciate your help!
Comment: I removed the form tag as I wasn't using any of it's properties and changed it to a div. Now I don't get the console error, but the one where all wrong or all right options persist. Any ideas on why this is happening and how to solve it?
Comment: If you made and shared a Plunkr, I could help get it working. Here is an empty Angular Plunk: https://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5 When you have a form element in the page, angular requires it has a name so it can track and validate the input. Can you try name="{{question.question}}" instead?

"Property does not exist in type"


Hardware emulation vs Software emulation during guitar recording

Question: I've tried to emulate guitar amps and pedals on Line 6 Pod Farm, Amplitube and Guitar Rig but I've never heard the sound I desired.
Days ago a friend of mine told me about hardware emulators as Line 6 Pod X3, Line 6 Pod HD Pro X that should perform better than the softwares.
Is software emulation better than hardware emulation or vice-versa?
Comment: The "hardware emulation" boxes really use software running on a specialized processor (a DSP). So, no. They're both using software, and while you don't have a DSP in your PC or Mac, your processor is more than up to the job.
Answer: I think this all might get a bit subjective, but in theory, Pod Farm is the same as a hardware Pod; the main difference being possibly the apparent latency [the time between you hitting a note & actually hearing it] which may be much lower in a hardware device.
I have used an old hardware Pod2 extensively, & also Guitar Rig [from v1 through v5]
Though I do like the immediacy of the Pod, I have actually developed a taste for Guitar Rig - though it does require me to really knock my computer's latency down whilst recording - because it gives me the opportunity to keep tweaking the amp sound right up until the final mix; or bounce the sound to disk to save on some processing power, once I'm happy.
I also think I prefer the sound of Guitar Rig, but that again is very subjective - it does what I want it to do, which may not be the same as what you want it to do.
Amplitube, I've used, but not enough to really have an opinion.
Objectively, I would say 'they are the same', within acceptable parameters.
Comment: Latency depends mostly on your hardware and software configuration, and you can get it down to something like, say, 3ms (equivalent of being 3 feet away from the speaker) on a computer, which would be not noticeable.
Comment: Depends on how many other plugins you have running, & whether you can bypass the very high latency ones for recording - but yes, sure, that's exactly what I do.
Answer: The Line 6 hardware devices have essentially^* the same software models as the Pod Farm software, provided that you are comparing versions of the same generation.  There should be no difference in the digital modeling between them running on your PC vs. running the Line 6 dedicated hardware; however the Line 6 software has evolved over time, so if you're currently using older versions of the software newer versions might help.
It is possible that the limiting factor in your current setup is your audio interface: i.e. the device that converts the analog electrical signals into digital.  If your running into problems with clipping, or latency or timing errors, or in general getting poor sound quality due to low quality A/D converters removing it from your signal chain may help.  In this case, getting a hardware unit that can also serve as an audio interface (I believe most of the Line 6 products nowadays provide USB audio capabilities) may provide you with a better experience.  However, just changing out your audio interface may provide the same advantages.
This is a case where you need to examine your entire signal chain, including the software models, and assess what is the weak link in the chain.  If you can, to your own satisfaction, verify that it is indeed the software models that are letting you down then getting a dedicated unit (Pod or similar) won't provide much added value.
A little more discussion:
All of the Line 6 Pod products, and the computer hosted models are doing digital modeling of the amps/effects;  thus I would not consider a Line 6 Pod to be a "hardware emulator".  The only company that I'm aware of doing hardware mdoeling is Tech 21, who design analog circuits with an eye towards recreating the sound of other amps.
^* Note: there are various versions of Line 6 Pods, and related software and thus the actual software may have changed, but at a given time, and up to date Pod should have the same software models as an up to date version of the Pod Farm software.
Comment: now I'm using a Line 6 UX2 interface and the sound is poor even if I send a real marshall 100 watt amp signal into the input. My guitar is a Jackson made in India, should it be a problem? The Pod hardware solution would not help me if I'd decide to test this possibility? Thanks
Comment: Are you using the line out of the real amp? They sound pretty bad in general.
Comment: @cyco130 pfff... some people told me to proceed in this way.
Anyway I can't get a sound that I like neither on my marshall 100 watt cabinet.. I guess it could be a guitar problem.. it's made in india
Comment: @kamauz Even cheap guitars are made OK nowadays. But there may be a problem with your guitar of course. Maybe you want to check [this](http://music.stackexchange.com/questions/22382/what-kind-of-equalization-is-done-for-different-music-genres-for-your-guitar-ton) thread to learn a few things about dialing guitar tones.
Comment: I've tried different times to change eq settings. I'll try again.. thanks for support @cyco130 anyway :)
Comment: Maybe you should try with another guitar? Are you able to get a sound you like in a guitar store ? (with another guitar / amp). You should experiment in a store to see if it's the amp (maybe you don't like how it sounds) or the guitar.
If it's the guitar, consider checking your guitar setup (intonation...), changing the strings brand (cheap & might be effective) or changing the pickups (they have a HUGE impact on the sound).
Answer: Currently I own a Line 6 Pod X3 Live and I owned a Pod XT before that. Over the last 8-10 years I used both of them extensively, both for recording and on stage. Although X3 is supposed to have a higher sampling rate, I can't tell the difference between XT and X3 (other than the fact that X3 can process two channels at once). I never did an A/B test but after transferring my tones to my new processor, I didn't notice any change. Same is true between Pod Farm software and Pod X3 Live. This time I confirmed it with many A/B tests.
The main problem with the pre-HD Line 6 devices is that they don't include a power amp stage distortion simulation. For some sounds it's OK. But for many others, newest generation software simulators (including some free ones) sound much better to my ears. As far as I understand, Pod HD series do have power amp stage distortion simulation but I didn't have a chance to give them a real try.
If the quality/latency of your sound interface is indeed the problem like others have predicted, you can use your Line 6 device as a sound interface. I use my X3 Live and I record the "dry" (i.e. non processed) signal. I dial in a good enough tone and I monitor through that tone but only record the dry signal. Afterwards I put my favorite software sim and fine tune to taste. It's not 100% ideal because what I hear during recording is different than the end result but at least I don't have latency problems, which can be very annoying because I record on 96 kHz.
Apart from the latency issues, many sound interfaces, including my otherwise awesome MOTU 8-pre, claim to have instrument inputs but those inputs have way too low input impedances. It causes a high frequency loss in the guitar signal. Guitar inputs of PODs have correct impedance. A buffer pedal (any analog pedal with no true bypass on bypass mode or a neutral pedal, like an eq pedal with flat settings) can solve impedance problems.
Comment: That would point to Dave's answer as being valid, though you never mentioned it in your original question... "It is possible that the limiting factor in your current setup is your audio interface"
Comment: I don't think you understand what power amp distortion is. Real guitar amps produce (at least) 3 types of distortion: preamp, power amp and speaker. Preamp distortion is easy to simulate and that's the only distortion stage that older Pods simulate. But the power amp distortion is very important for many guitar sounds. I personally don't like the speaker distortion but it's a matter of taste. Now, can you get a good tone from a real amp with your guitar? If not, maybe that's the problem.
Comment: so with Pod HD products I should have no crappy distortion problems?
Comment: @kamauz You need to give details about what you mean by "crappy distortion".
Comment: @cyco130 In all my records I use distortion effects and amp and I never get a good sound quality.. you said that pre-HD version have no "power amp stage distortion simulation" so the interfaces can't manage distortion power properly? Buying a Pod HD should be a solution? I've already tried 2 different kind of audio interfaces (Line 6 UX2 and Lexicon Lambda)


Hangfire server in .Net Worker Service

Question: I am trying to start Hangfire server in .Net Worker Service using example:
Configure Hangfire dashboard in a worker service in .Net 5? answer by Ruslan Gilmutdinov https://stackoverflow.com/users/1734655/ruslan-gilmutdinov but following code
using Hangfire;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace WorkerServiceHangfire
{
    public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }

            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(builder =>
                {
                    builder.Configure(app =>
                    {
                        app.UseRouting();

                        app.UseHangfireDashboard();
                        app.UseEndpoints(endpoints =>
                        {
                            endpoints.MapHangfireDashboard();
                        });
                    });
                })
                    .ConfigureServices((hostContext, services) =>
                    {
                        services.AddHangfire(conf => conf.UseSqlServerStorage("connection string"));
                        services.AddHangfireServer();

                        services.AddHostedService<Worker>();
                    });
        }
}

gives error at builder.Configure(app => line:

Error CS0411  The type arguments for method
'OptionsConfigurationServiceCollectionExtensions.Configure(IServiceCollection,
IConfiguration)' cannot be inferred from the usage. Try specifying the
type arguments explicitly.

Any suggestions?
Answer: You have to include the namespace Microsoft.AspNetCore.Hosting wich contains WebHostBuilderExtensions an extension class that among other extension methods contains also the one you are trying to use:
public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action<IApplicationBuilder> configureApp)
using Microsoft.AspNetCore.Hosting
Comment: I have seen that you have updated the question with all the includes but `using Microsoft.AspNetCore.Hosting` is missing, is possible that you have confused it with `using Microsoft.Extensions.Hosting;`? you need them both
Comment: using Microsoft.AspNetCore.Hosting is included.
My usings:

using Hangfire;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;
Comment: Just for test can you try to edit the .csproj and add:
Comment: Done, but same error :(
Comment: Now it works !!! Thank you so much!!! Mixed up Microsoft.AspNetCore.Hosting and Microsoft.Extensions.Hosting

Hangfire server in .Net Worker Service


Moments of $\text{exp}(-|x|^{1/2})$

Question: I'm supposed to show that all of the moments of the density $\text{exp}(-|x|^{1/2})$ are finite.
I'm not convinced this is true though. The $p$th moment is
\begin{align*}
\mathbb{E}[X^p] &= \int_{-\infty}^\infty  x^p \text{exp}(-|x|^{1/2}) dx
\\
&= - \int_0^\infty x^p e^u x^{1/2}dx
\\
&=\int_0^\infty u^{2p+1} e^u du
\end{align*}
where the second equality comes from u-substitution with $u = -x^{1/2}$, $du = -1/2 x^{-1/2}dx$, and the fact that the integrand is even (so that we consider the range $0$ to $\infty$).
This last integral is infinite since I believe that $\int_0^\infty u^p e^u du = \infty$ for any $p> 1$.
What am I doing wrong?
Comment: I get by substitution (for even p) $\int_0^\infty u^{2p+1} e^{-u} du$, which is a Gamma function
Comment: @kjetilbhalvorsen oh.... so you let $u = x^{1/2}$? This would make sense
Answer: First note that the factor necessary to make this a density function on the real line is $1/4$. So
\begin{align}
   \int_{-\infty}^\infty x^p e^{- |x|^{1/2}}/4 \; dx = \\
   \frac14 \int_0^\infty \left[ (-1)^p+1\right] u^p e^{-u^{1/2}} \; du = \\ \begin{cases} 0, \text{odd $p$} \\
          \int_0^\infty u^{2p+1} e^{-u}\; du, \text{even $p$}
    \end{cases} =\\
\begin{cases} 0, \text{odd $p$} \\
              (2p+1)!, \text{even $p$}
\end{cases}
\end{align}
so is clearly finite for all positive integers $p$. The integrations above are done by successive substitutions. The last equality is by the definition of the Gamma function, and the well-known equality $\Gamma(n)=(n-1)!$, which can be proved by induction.
Comment: Perfect thank you! Could you explain why $\int_0^\infty u^{2p+1} e^{-u} du = (2p+1)!$?

Moments of $\text{exp}(-|x|^{1/2})$


Intervalo de datas em uma Collection Laravel

Question: Tenho a seguinte collection Laravel
"data": [
         {
            "id": 1,
            "uuid": "5f948b5b-b8c1-45de-9d8b-b8c272df53ad",
            "issue_date": "2009-01-02",
            "issue_date_end": "2012-03-12",
        },
    ]

Como posso fazer uma comparação de intervalo baseado na chave issue_date e issue_date_end?
Exemplo: Gostaria de testar se a data 2010-09-06 está entre a issue_date e issue_date_end.
Tenho feito da seguinte forma:
$query->collection= $query->collection->filter(function ($row) use ($request) {
    return collect($row['issue_date'])->where('issue_date','<=', 2010-09-06)
                                      ->where('issue_date_end','>=', 2010-09-06);
});

Mas isso parece não funcionar,tentei tambem com o whereBetween, mas não funcionou com Strings.
Comment: @Danizavtz esta enganado, o where() no Eloquent não é a mesma coisa que o WHERE da sintaxe SQL, no eloquent existe o where(), whereIn(), whereColumn(), whereTime(), etc. Esses **métodos** adicionam "instruções ao "QueryBuilder", para no "final" gerar a query de verdade, é um ORM então.
Comment: tu colocou duas clausulas `where`. Em `sql` isso não é possível. Se quer utilizar mais condições nas clausuras where deve usar `OR` ou `AND`.
Comment: O caminho é usar between. O problema é que você está tratando `2010-09-06` numericamente (calculando) em vez de usar uma string ou data, efetivamente mandando o valor `1995` para a query. Fundamental nesses casos um [mcve] do problema.
Comment: Sim,mas isso não e `SQL`
Answer: $query->collection = $query->collection->filter(function ($row) use ($request) {
    return strtotime($row->issue_date) <= strtotime("2010-09-06") &&
        strtotime($row->issue_date_end) >= strtotime("2010-09-06");
});


Geolocation Field Oops! Something went wrong

Question: I'm using Geofield Gmap as Field in a Content Type. Each time I try to create/Add a node, the (Geofield) field display the below Error message

"Oops! Something went wrong this page didn't load google maps
correctly. See the javascript console for technical details."

The Steps that I did:

Create API key For Google Map.

UPDATE:
I tried to apply the following patch:
patch -p1 < https://www.drupal.org/files/issues/fix-api-key-not-being-used-2746209-5.patch

I see this message:

No such file or directory
Comment: You either download the patch locally or manually apply the changes yourself.
Comment: @Kevin but nothing wrong with my Command?
Comment: You can also use an IDE to apply a patch, such as PHPStorm, if CLI is giving you trouble.
Comment: see my update in the answer
Answer: Usually you see this message when you don't have in the Geolocation module the Google API Key or the Google API Key is not working well. For this you need to go to:
http://YOURSITE/admin/config/content/geofield_gmap

Write your working Google API Key and save the Configuration.
Edit:
To apply the patch you need download the file to:
sites/all/modules/geofield/modules/geofield_map

then go to the dir and run:
patch -p1 < fix-api-key-not-being-used-2746209-5.patch

Comment: I just update my post
Answer: You can possibly solve it by looking at the JavaScript console for technical details. Click on F12 and view the JavaScript error.
EDIT:
If you got a missing key map error, then it is probably misconfigured and you should find a solution here.
Comment: Please not that your answer showed up in the "low quality posts" review queue. Can you think of a way to somehow improve it? That would reduce the risk it gets deleted via moderation. Good luck! PS: why not at least some "possible causes" (even if they are only guesses) what might be causing it)?


Latent semantic classification

Question: How can I create a training data set for document classification using LSA? I have created a term-to-document matrix and have class labels also. I don't know whether to add these class labels in a term-document matrix or to create anther matrix. I don't know the exact steps to follow to create training data.
Answer: You proceed the same way you would without LSA:

take some labeled corpus (e.g. 20 newsgroups)
preprocess (remove stop words, stem, etc)
convert to the vector space model, weight by tf-idf
do LSA
build a classifier

So the only additional step here is the 4th one.
Here's an example for scikit learn adapted from here:
<code>dataset = fetch_20newsgroups(subset='all', shuffle=True, random_state=42)
labels = dataset.target
true_k = np.unique(labels).shape[0]

hasher = HashingVectorizer(n_features=opts.n_features,
                           stop_words='english', non_negative=True,
                           norm=None, binary=False)
vectorizer = make_pipeline(hasher, TfidfTransformer())
X = vectorizer.fit_transform(dataset.data)

svd = TruncatedSVD(true_k)
lsa = make_pipeline(svd, Normalizer(copy=False))

X = lsa.fit_transform(X)

clf = MultinomialNB().fit(X, labels)
</code>
Here's a list of useful links on how to work with textual data in scikit learn:

http://scikit-learn.org/stable/datasets/twenty_newsgroups.html
http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html
Comment: I am not able to understand why you passed "true_k" i.e. labels to TruncatedSVD. It is supposed to take number of components and algorithm as arguments.
Comment: No particular reason
Comment: @AlexeyGrigorev are you sure this works? I don't see how `MultinomialNB` would work on negative values, and it looks like the output of the `lsa` step could certainly have negative values after the l2-norm is applied.
Comment: I copied that from the documentation. Now when you say it, I am not sure. Any other classifier would do, I suppose

Latent semantic classification


Which chord is Cm6?

Question: I am not sure if this is an inversion or some other chord.  Notation is Cm6.  Is this an inversion of C minor chord?  Or is it a sixth chord of some sort - C minor with a sixth added?  Key signature in the song is G major.
Answer: Cm6 is C-Eb-G-A. It's Cminor with an added 6th note. Note that the 6th note is from the major scale and melodic minor ascending scale, not the harmonic or natural minor.
Answer: Cm6 is C Eb G A.   C minor triad with an added sixth.   It's one of the extended chords that doesn't fit into the "pile of thirds" hierarchy, it's not a Cm13 (C Eb G Bb D [F] A) with missing notes!
And it's just fine in the key of G.  Here's a common, corny even, useage - firmly within a G major tonality.
Answer: Yes, according to the most common use of such symbols, in popular music and jazz transcriptions, Cm6 would be C minor chord with an added 6th (i.e. a natural A).
The figure 6 (written as superscript) can be used to mean a first inversion of a major or minor chord, but that is usually in the context of the so called "roman numeral analisys" of tonal harmony. So in that context a roman numeral in relation to the tonality, not the note name, would normally be used to designate the chord.

Which chord is Cm6?


Understanding State of JS in Drupal

Question: I have a simple contributed module that I have written. It has pretty basic javascript. I decided to clean it up and write it in vanilla js, removing jQuery since that seems to be the direction we're going. Here is the resulting code...
const viewSourceLinks = document.querySelectorAll(
  '.simple-styleguide--view-sourecode'
);

[].forEach.call(viewSourceLinks, el => {
  el.addEventListener('click', () => {
    el.nextElementSibling.classList.toggle('active');
  });
});

const calculableElements = document.querySelectorAll('.calculate');

[].forEach.call(calculableElements, el => {
  const measuredElement = el.querySelector('.measure');
  const info = el.querySelector('.info');
  const lineHeight = `line-height: ${
    window.getComputedStyle(measuredElement).lineHeight
  }`;
  const fontSize = `font-size: ${
    window.getComputedStyle(measuredElement).fontSize
  }`;
  const margins = `margin: ${
    window.getComputedStyle(measuredElement).marginBottom
  }
        ${window.getComputedStyle(measuredElement).marginRight} ${
    window.getComputedStyle(measuredElement).marginBottom
  } ${window.getComputedStyle(measuredElement).marginLeft}`;

  info.innerHTML = `${fontSize}<br/>${lineHeight}<br/>${margins}`;
});

My question is, is this ok? Is this good enough to include as is? In general, it seems the advice is to always add your javascript within attached behaviors.
However, once I go down that road, I'm pretty much having to include jQuery in the wrapper. And I would much rather just have vanilla javascript.
The resulting code with behaviors ends up being something like this...
(($, Drupal) => {
  Drupal.behaviors.simpleStyleguide = {
    attach(context) {

      const viewSourceLinks = context.querySelectorAll(
        '.simple-styleguide--view-sourecode'
      );

      [].forEach.call(viewSourceLinks, el => {
        el.addEventListener('click', () => {
          el.nextElementSibling.classList.toggle('active');
        });
      });

      const calculableElements = context.querySelectorAll('.calculate');

      [].forEach.call(calculableElements, el => {
        const measuredElement = el.querySelector('.measure');
        const info = el.querySelector('.info');
        const lineHeight = `line-height: ${
          window.getComputedStyle(measuredElement).lineHeight
        }`;
        const fontSize = `font-size: ${
          window.getComputedStyle(measuredElement).fontSize
        }`;
        const margins = `margin: ${
          window.getComputedStyle(measuredElement).marginBottom
        }
              ${window.getComputedStyle(measuredElement).marginRight} ${
          window.getComputedStyle(measuredElement).marginBottom
        } ${window.getComputedStyle(measuredElement).marginLeft}`;

        info.innerHTML = `${fontSize}<br/>${lineHeight}<br/>${margins}`;
      });

    },
  };
})(jQuery, Drupal);

I've also read that if you have BigPipe enabled, you have to include jQuery. Not sure if that's true or not.
The vanilla js code above seems to be working. I just want to know that I'm doing this right, and that I'm not violating some Drupal standard by not wrapping it in a behavior.
Note: I should mention there is no ajax behavior in this module. If there were, perhaps I would have to use behaviors and context.
Answer: The best practice is still to use Drupal's behaviors system even when not relying on jQuery. See Drupal 8 Drupal.behaviors without jquery for reference.
That said, I think you're on the right path. I find jQuery just slows down the page load when vanilla JS will usually do the trick. That's just my opinion and there's a lot of debate out there.

Understanding State of JS in Drupal


is it possible to connect to sites over the internet

Question: I have two sites which are 3km away from each other, both sites have internet access from the same ISP. I would like both sites to have access to each other throught the internet routers (TP-Link TD-W8968). Is it possible?? if not, please explain what do I need to achieve the connection with the lowest cost possible.
Answer: Yes, use IPsec VPN to connect the two routers. You can do this directly between your current routers - no need to spend any money.
According to the manual these routers support up to 10 IPsec tunnels (you only need one). IPsec is fast and secure, and with the VPN running from edge to edge you have no NAT issues.
Refer to the linked pdf at page 61 for configuration instructions.
Comment: thank you, I will check this. I just started to go with the Dynamic DNS solution. If you can recommend a reliable provider if you know any, I will be thankful.
Comment: You may have issues with site to site VPN with dynamic IPs. I would actually recommend you talk to your ISP about getting static IPs for your two sites. It is usually very cheap and will be much simpler for you.
Comment: it is not cheap at all in here. It would cost me 100$ monthly. That's why I have been looking for alternative ways. as most Dynamic DNS providers provide the service with their own software to keep your external IP address updated to your hostname. I have already tried some free providers and its working well till now. am just wondering which one of them is reliable and trusted as there are too many of them.
Answer:
I would like both sites to have access to each other throught the internet routers

Yes, this is called a VPN (Virtual Private Network). People have been doing this since the birth of the internet. There are a thousand different VPN solutions out there, but the common ones in use today are L2TP, IKEv2, IPSEC.

P-Link TD-W8968

No idea, but routers that do site-to-site VPNs are plentiful so if your router doesn't do it, get one that does. It shouldn't cost much.
Comment: thank you, I had the site to site option on mind as someone offered me the solution from NE section just before redirecting me in here.  and I will have a look at IPSEC.
Answer: You will have to use a Virtual Private Network (VPN) to achieve this. It's very very common and you will find a whole host of VPN providers, some expensive some cheap, that will be able to offer you a solution. Just do your research and see what suits you best.
Comment: I have been looking for hosts and found no-ip services, am just wondering if they require from me to have a static IP address from my ISP, because it is expensive in here. thanks for the response by the way.


Qual é o papel dos parâmetros?

Question: Sei o conceito de função e procedimentos, mas estou com um pouco de dificuldade em entender o papel dos parâmetros.
Comment: [Entendendo parâmetros e argumentos em funções](https://pt.stackoverflow.com/q/175434/91) e [Qual a diferença entre parâmetro e argumento?](https://pt.stackoverflow.com/q/32448/91)
Comment: Por função dos parâmetros você quis dizer "papel dos parâmetros" ou algo assim?
Comment: "Para que servem os parâmetros", é isso que você quis dizer? Misturando com o termo matemático ficou um pouco ambíguo...
Answer: Parametrizar informações, tornar genérico algo que seria específico, dar variabilidade para um algoritmo com dados externos desconhecidos naquele local, é para estabelecer um ponto de comunicação entre o algoritmo local e o algoritmo externo.
O parâmetro é uma variável local como outra qualquer, pelo menos na maioria das linguagens ou todas mainstream, cujo valor será conhecido apenas na chamada da função. Então a atribuição do seu valor é sempre feita em tempo de execução, salvo alguma otimização que consiga eliminar isto.
Ele tem escopo, tempo de vida e visibilidade local, então só existe dentro da função, enquanto ela está sendo executada. A única diferença para a variável é o momento da atribuição do valor que ocorre na chamada e não dentro da função.
Note que o parâmetro existe na função, ao contrário da chamada onde se passa um argumento. Um argumento já pode ser qualquer expressão válida na maioria dos casos. Pode ser uma variável, um literal, uma expressão com fórmulas, etc. Mas tem argumentos que precisam ser variáveis , aí depende de tipagem.
Em geral parâmetros precisam ser validados já que o valor recebido pode não ser adequado ao que se propõe o algoritmo. Mas depende da linguagem, da disciplina de tipagem, do estilo de programação.
Passar parâmetros tem custo e não deve ser abusado. Cada um deles há um cópia de dados, mesmo os tipos por referência precisa copiar o endereço do ponteiro.
O abuso pode se dar também do ponto de vista de organização. Fica muito complicado administrar funções com muitos parâmetros.
Assim como pode-se receber parâmetros (dicionário) pode-se comunicar saindo da função com o retorno dela. Geralmente pode ter apenas um retorno, ainda que algumas linguagens usam tuplas implícitas ou explícitas para retornar mais de um dado. A comunicação na saída pode ocorrer por um parâmetro também, desde que ele seja uma referência e permita que o dado seja modificado, então entra com uma valor e quando termina isto está com outro valor. Obviamente que isto só será útil na chamada se for uma variável.
Isto pode ser útil: O que acontece quando chamamos uma função?
Comment: @OrdasIvarov sim, ela é uma variável local que só existe ali dentro.
Comment: Uma expressão lambda `v((x) -> x.y > 0)` ou uma função anonima `v(fun(p) { })` pode ser considerado um argumento?
Comment: Sim, qualquer coisa que pode ser passada para a função é um argumento. Lambdas são funções, provavelmente de [primeira classe.](https://pt.stackoverflow.com/q/227485/101). No caso o parâmetro será uma referência para a função da *lambda* e ela poderá ser chamada normalmente.
Comment: Então os parâmetro é como se fosse uma variável que só será lida e modificada em uma sub-rotina?

Qual é o papel dos parâmetros?


Sitrecore MinValue

Question: I need to sort very large number of item in Sitecore.
So I used negative number, something like this:
item.sortOrder = int.MinValue + someId

minValue = -2147483647
but sitecore sort correctly only for value greater then -2143053648 so there is a difference of 4430001
so now my code is
item.sortOrder = int.MinValue + 4430001 + someId

and it sorts correctly
does anyone ever experienced something like this, am I doing something wrong?
Comment: Why do you need such large numbers? Sitecore recommends no more than 100 items at any level in the tree.
Comment: there aren't more then 100 item in one folder, but the order is cross folder.
Comment: what we are sorting are all the article of the italian constitution. it's a very complex structure. Many books each one contains chapters, with section... and the sorting is supposed to be throw chapters and section
Answer: I'm not sure what exactly you are trying to achieve but it would be better to define a public constant for Sitecore SortOrder Minimum value somewhere accessible.
public const int SortOrderMinimumValue = -2143053648;

And then reference like this
item.Fields["__Sortorder"].Value = SortOrderMinimumValue + someId;

That way the minimum value can be accessed any other code and can be altered at one location should you want to change the minimum value for your sorting.
To sort Items by sort order you then will need to do the following
public class ItemComparer : IComparer
{
    public int CompareSortOrder(Item item1, Item item2)
    {
        int sortOrder1;
        bool parsed1 = int.TryParse(item1["__Sortorder"], out sortOrder1);

        int sortOrder2;
        bool parsed2 = int.TryParse(item2["__Sortorder"], out sortOrder2);

        if (!parsed1 || !parsed2)
            throw new Exception("Sort order value is incorrect type");

        if (sortOrder1 < sortOrder2)
            return -1;
        if (sortOrder1 > sortOrder2)
            return 1;
        else
            return 0;
    }
}

And then reference the code when sorting;
var itemComparer = new ItemComparer();
items.Sort(itemComparer.CompareSortOrder);

Comment: the problem is not with the code, on sitecore I found the exactly same value the code calculate...
Comment: thank yout jRobbins but the problem is not with the code, on sitecore I found the exactly same value I've calculated with that code, or some code really close to that... But when it comes to sort item according to the sortorder, I've found that value closer to int.Minvalue doesn't work, item goes straight to last position

Sitrecore MinValue


Is the Baroque Schleifer, slide, or glissando symbol evolved from the Gregorian chant quilisma?

Question: I posted this question on Wikipedia a year ago, with no answers.  These two musical signs look eerily similar.

The Baroque Schleifer or slide (see Wikipedia page):

The quilisma in Gregorian chant (see French Wikipedia page):

Coincidentally, their performance is nearly identical.  The Gregorian quilisma is now known to have been originally sung as a quick sliding glissando or portamento towards a higher note, or, equivalently, as a quick rising grace or passing tone towards that note.
In the picture above, the two signs above the staff are the quilisma as it appears in ninth-century Laon/Lorraine/Metz notation of Gregorian chant, where it is depicted as a medieval question mark ('?' upside-down) to indicate the rising of the voice.
The four signs below the staff are the quilisma in ninth- and tenth-century St. Gall notation.  I highly suspect this is the ancestor of the Schleifer sign, on account of

identical shape,
identical performance, and
St. Gall notation being regional to Germany and Switzerland at the end of the first millennium.

Could this be a pure coincidence?  Is it possible to conclude from any evidence a true ancestral relationship here?
Do we have samples of similar signs used in music between 1100 and 1600 that could suggest a continuity of the symbols' application?
Comment: You would ask Prof. Hartmut Krones from the music university of Vienna. He has a quite big knowledge in this area.
Comment: Good recommendation. I reached out the other day, but no reply yet. I saw he is 'Emeritus'.
Comment: Did he reply to you in the meantime?
Comment: Nope. Dead end.
Comment: the answers of craig  are not so wrong. upvote!
Answer: No, this is not an accidental coincidence:
There is enough evidence from your wiki site to answer all other questions in your post with yes!
The quilisma and the schleifer are both a graphic sign to illustrate a glissando in singing or instrumental music. As it was used in the notation of Gregorian chant it will be obvious that it was took over in the square notation like all other signs as the torculus and the porrectus etc. and was always used in music notation to anytime after Gregorian chant. The glissando in human speaking, singing and instrumental playing is ubiquitous and was a use long before the notation of Greg. Chant. So the Schleifer is 100 % developed by this.
(But if any newbie, a composer of New music or a primary schoolteacher had to think about a graphic notation of something like a slide or a glissando he would surely came to a similar result of a sign. So  in this case you might speak about an coincidence, if someone doesn't know the use in history of music...)
 Geschichte der Musik"]2]2 dtv-Atlas zur Musik  (transcription of Gregorian chant sign forms)
Comment: There is enough evidence from your wiki site to answer all other questions in your post with yes! (and to proof this we don't need the answers of a Prof. Dr. in music and arts of Vienna):
music theory and music history is not an exact science. questions like this mayl never be answered in an objective way. would it more objective if a monk in the middle age, or a Flemish composer, or Fux or C. Ph. E. Bach himself would have mentioned that a sign is developed of another sign from the Gregorian chant? it would be the same subjective as when I declare it!
Comment: Thanks, but can you back up your "100%" confidence?  The scientist in me just doesn't find near-identical shape and performance to be enough, given that Baroque and Gregorian chant are two very different genres with 4 to 5 centuries between them.  I imagine the kind of evidence to support this continuity hypothesis would be, say, if the sign could be found in certain musical books or folios from each of the 13th, 14th, 15th, and 16th centuries, where it might have been applied in the same manner.  That would help diminish the likelihood of mere or even partial coincidence.
Comment: Also, unless I missed something, the French Wikipedia article hardly says a thing about the tradition of the symbol outside Gregorian chant.
Answer: I'm afraid I have to take the skeptical view and say that Baroque musicians chose the most suitable symbol for the job, which it turned out the medievals had chosen eight centuries earlier.
The quilisma (and other ornamental neumes, such as the oriscus and trigon) are found only in the oldest traditions of neumatic notation for monophonic liturgical chant, current c. 800-1200. Around 1100, composers turned their greatest efforts toward polyphony, developing the art of (mainly contrary) motion between stable intervals: fifths, fourths, octaves, and some thirds. Now these stable intervals lose their striking purity unless each voice sings a steady pitch. Hence the systematic purging of quilismas and other ornamental neumes from the chant melodies used as tenors for polyphony, and eventually in monophonic music as well.
Thus in the Montpellier Codex, our biggest source for 12th-century polyphony, one looks in vain for the quilisma; when music printing hit the world stage in 1501, no type case included it; and it wasn't until the 1600s that the harmonic, monodic hearing of music was sufficiently grounded (and culture's appetite for novelty sufficiently voracious) that the Schleifer could be invented, or some would say reinvented.
Comment: By "Montpellier Codex" I mean this manuscript: https://imslp.org/wiki/Montpellier_Codex_(Various).
Comment: A good source for medieval notation is Apel: https://archive.org/details/notationofpolyph00apel/page/87   The quilisma is conspicuous by its absence. I conjecture that the reason is that the neumes of Gregorian chant (indicators of phrasing) were repurposed as the ligatures of mensural notation (indicators of note length), and the quilisma, having never had a very definite rhythm, was dropped.
Comment: Great info, but can you provide sources? Also, which Montpellier Codex? Can you provide the manuscript number?
Answer: I did not bother with Wikipedia, however from what I learned in college I can list for you the direct ancestry the issues you brought into question:
BAROQUEN- A reference to the "Church Mode" scales and chords. Although these scales were used in much of music, they were made famous in the modern world by blues gutairist "Eric Clapton", (then later, by an exclusive Clapton stylist, "Eddie Van Halen"). Today they are taught by virtually all gutairist as beginning gutair.
SLIDE- Is a slide is a slide. More or less established and recognized in the 19th and 20th centuries.
GLISSANDO- A reference to establish the way(or technique) one is to play the section or piece
GREGORIAN- An interval or harmony once thought to be EVIL!  At one point in history this combination of notes carried the death penalty
SO - ANSWER TO QUESTION -Unlikely, since dates don't align with the creation of such musical technology (joke) or development through the centuries
Don't get too focused on the similarly in notation. Some was established as long as 300-400 years ago, and some as recent as 50. Anything earlier than the 15th century is either written on a scroll or has been translated numerous times. That is most likely why you didn't get many replies to your questions, people probably thought the questions had complicated answers.
A great deal of your secondary data is based on speculation. While it might make for interesting conversation material, it needs some heavyweight reformatting before it would make for clear question and answer material.
Craig
`
Comment: It may have been a while since you were at college. It may be that your tutors told you misinformation. It may be that you weren't listening properly. There is a fair bit of inaccuracy here. Please check details before broadcasting answers like this. And Wikipedia may not be perfect, but it's worth consulting...
Comment: @Craig Wilson With all due respect, I don't think this is a very helpful response. There are many vague terms like "more or less established" and "anything earlier than the 15th century is ... written on a scroll". Since Coemgenus is asking for proof of his insightful conjecture, which it appears you cannot prove or disprove, I'm sorry, but I have to give you -1 on that.
Comment: music theory and music history is not an exact science. questions like this mayl never be answered in an objective way. would it more objective if a monk in the middle age,  or a Flemish composer, or Fux or C. Ph. E. Bach himself would have mentioned that a sign is developed of another sign from the Gregorian chant? it would be the same subjective as when I declare it! and in 200 years one will cite my post here and say there is  proof that the baroque Schleifer is evolved by the quilisma of Gregorian chant as Albrecht Hügli posted this already in 2019 in stack overflow! look up my anwer ;)