Play Cards Game Tournament Algorithm

Question: I am currently trying to find algorithm to minimize the total time of a tournament.
The game requires $2$ teams of $2$ players in each team (total $4$ players).
Then, the perfect number of tournament players (to have $4$ players in the final game), must be $2^n$
However, it is very hard to always have registered players matching this perfect number. So, I can substitute computer players to complete the perfect number.
The number of sets of games to be played until the end is $n-1$
Each set of games will take in average $5-7$ minutes.
Lets have an example:
Registered players for tournament $ = 100$
Nearest perfect $2^n$ is $128=2^7$
Number of sets of games $n-1=6$
Total average time of tournament is $30-42$ minutes
I tried to split the $128$ players into $2$ tournaments and play simultaneously but there is no difference. Each tournament will have $25-35$ minutes ($64=2^6$ and number of sets is $5$) plus $5-7$ minutes for the final game of winners of two tournaments.
Comment: I don't think you can do anything to shorten the time.  You have the same number of rounds, no matter what you do.
Comment: Are the teams constant throughout the tournament?  That is, if A and B play as a team in the first round and win, do they play as a team in subsequent rounds?  If this is true, can we assume that players enter as teams, so that there are always an even number of players?
Comment: Yes, the winner teams move to the next level and so on until reaching the final. No, the system assign players to teams randomly. And I have AI players (computer players) I can use to fill the gaps.
Answer: You cannot reduce the time of the tournament. The constraints of your game seem to be the following: Exactly two teams play a game together and exactly one of the teams wins. Also I assume you want to find the best team in the following sense: Team A is better than team B iff A won against B or if there is team C such that A won against C and C is better than B. In other words: The "better-than" relation is the transitive closure of the "won-against" relation. (I assume here that the "better-than" relation defines a total order on the teams).
We can think of the teams as nodes in a graph G. If team A won against team B then we add a directed edge from A to B. Team A is now the winner of the tournament iff for every other team B there is a directed path from A to B. The minimum number of edges needed in order to be sure that A is the best team is thus $n-1$ if we have $n$ teams.
Your proposed algorithm:
We now construct a tournament where in every round some teams play against each other. In every round every team can only play one game. If we think about it, we realize that a loosing team cannot be the best team in the set of teams. So as soon as a team looses, we do not have to consider it anymore. We now want to find the best team by eliminating teams who loose. In order to do this as fast as possible, we have to eliminate as many teams as possible in every round. Assuming there are $2^k$ teams, we can eliminate at most half of them in the first round. Then half of the remaining in the second route etc. Thus we need $k$ rounds to eliminate all but one team.
This strategy is optimal: Let $n = 2^k$ the number of teams. Then we need at least $n-1 = 2^k - 1$ games (because that's the minimal number of edges we need) to determine the best team. In the first round we can at most play $2^{k-1}$ games. In the second round at most $2^{k-2}$ etc. This is because letting teams play who lost will not give us additional information. Now since $n-1 = \Sigma_{i=0}^{k-1}2^i$ we need at least $k$ round to get to the desired $n-1$ edges.

Play Cards Game Tournament Algorithm


Carregar um campo TEXTAREA a partir de um SELECT com Jquery

Question: Tenho um modal que realiza envio de e-mail. Só que eu criei alguns modelos de email no banco de dados mysql. Na tela aparece o meu select com todos os modelos para seleção, só que eu gostaria de quando for selecionado o modelo, ele preenchesse o input "assunto" e o textarea "conteudo" com as informações vindo do banco de dados.
Abaixo segue o meu HTML com select usando PHP:

    Assunto:
    <input type="text" class="form-control limpar" id="assunto">

    Modelo:
    <select class="form-control m-input limpar" id="select_acao" name="id_atividade_tipo">
      <option>Selecione</option>
      <?php
                      $sql_modelo = $db->prepare("SELECT * from modelo_email");
                      $sql_modelo->execute();   $atv = 0  ;
                                      while($row_modelo=$sql_modelo->fetch(PDO:: FETCH_ASSOC)){
                                        $atv++; ?>
        <option value="<?php echo $row_modelo['id']?>">
          <?php echo utf8_encode($row_modelo['nome'])?>
        </option>
        <?php }?>
    </select>

  <textarea class="summernote" id="conteudo" name="conteudo">

                 </textarea>

Acredito que esse processo deva ser feito com jquery e Ajax fazendo requisição em uma página PHP, mas não sei como faria dessa forma.
Answer: Como você disse, tem que chamar um Ajax para uma página PHP e retornar o assunto e o conteúdo. Você pode retornar um JSON do PHP com esses dois valores e quando o Ajax for completado, inserir cada valor no seu campo.
Primeira coisa é colocar um onchange no select para chamar uma função que irá processar o Ajax. Coloque no select:
onchange="carrega()"

E insira a função no script:
function carrega(){

   $("#select_acao").prop("disabled", true); // desabilita o select

   $.ajax({
      url:'pagina.php',
      dataType: 'JSON',
      type: 'POST',
      data: 'id='+ $("#select_acao").val(), // envia o valor do select
      success: function(data){
         data = JSON.parse(data);
         $("#assunto").val(data.assunto); // insere o assunto no input
         var conteudo = data.conteudo.replace(/\/n/g, '\n'); // restaura a quebra de linha
         $("#conteudo").val(conteudo); // insere o conteúdo do email no textarea
      },
      complete: function(){
         $("#select_acao").prop("disabled", false); // reabilita o select
      }
   });
}

No exemplo acima o Ajax chama um PHP pagina.php, mas você pode usar outro nome que quiser.
Na página PHP você deve retornar um JSON com duas chaves: assunto e conteudo, neste formato, fazendo um echo:
echo json_encode('{"assunto": "'.$assunto.'", "conteudo": "'.$conteudo.'"}');

As variáveis $assunto e $conteudo você irá puxar do banco de dados de acordo com o id recebido com $_POST['id'] que foi enviado pelo Ajax.
Problema: A variável $assunto é uma linha só, não tem problema. O problema é com o conteúdo do email que vai na variável $conteudo que pode ter quebras de linha, e isso tonará o JSON inválido.
Para resolver você deve eliminar as quebras de linha com str_replace antes do echo. Minha sugestão é inverter a barra do \n:
$conteudo = str_replace("\n", "/n", $conteudo);

O PHP ficará algo assim:
<?php
// consulta o banco de dados de acordo com o valor em $_POST['id']
$assunto = valor da coluna "assunto" do banco;
$conteudo = valor da coluna "conteudo" do banco;

$conteudo = str_replace("\n", "/n", $conteudo); // elimina as quebras de linha
echo json_encode('{"assunto": "'.$assunto.'", "conteudo": "'.$conteudo.'"}');
?>

Comment: Muito obrigado DVD


how to prove this recurrence of determinants

Question: the question is :
Let Dn = $[a_{ij}]$n × n be a (n × n) determinant with the following conditions:
$$a_{ij} = 4 ;i=j$$
$$a_{ij} = 2 ;|i-j|=1$$
$$a_{ij} = 0 ; otherwise$$
then we have to prove that :
$$ D_n = 4D_{n-1} - 4D_{n-2}$$
my approach:
I found $D_1 =4 ,D_2=12, D_3=32$
but I don't know how to prove this as higher order determinants are take much more time to get calculated and I couldn't find a pattern  .Thanks for all help.
Comment: In fact $D_n=(n+1)2^n$, which is perhaps easier to prove if we halve the matrix, so its leading diagonal is all $2$s and the next-to-leading diagonals are all $1$s, and we wish to show the resulting determinant is $n+1$.
Answer: \begin{align}
D_n
&=\overbrace{\begin{vmatrix}
4&2&0&\cdots&0&0&0\\
2&4&2&\cdots&0&0&0\\
0&2&4&\cdots&0&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots\\
0&0&0&\cdots&4&2&0\\
0&0&0&\cdots&2&4&2\\
0&0&0&\cdots&0&2&4\\
\end{vmatrix}}^{n\text{ columns}}\\
&=
4\cdot\overbrace{\begin{vmatrix}
4&2&0&\cdots&0&0&0\\
2&4&2&\cdots&0&0&0\\
0&2&4&\cdots&0&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots\\
0&0&0&\cdots&4&2&0\\
0&0&0&\cdots&2&4&2\\
0&0&0&\cdots&0&2&4\\
\end{vmatrix}}^{(n-1)\text{ columns}}
-2\cdot\overbrace{\begin{vmatrix}
2&2&0&\cdots&0&0&0\\
0&4&2&\cdots&0&0&0\\
0&2&4&\cdots&0&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots\\
0&0&0&\cdots&4&2&0\\
0&0&0&\cdots&2&4&2\\
0&0&0&\cdots&0&2&4\\
\end{vmatrix}}^{(n-1)\text{ columns}}\quad\text{(expanding first row)}\\
&=
4\cdot\overbrace{\begin{vmatrix}
4&2&0&\cdots&0&0&0\\
2&4&2&\cdots&0&0&0\\
0&2&4&\cdots&0&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots\\
0&0&0&\cdots&4&2&0\\
0&0&0&\cdots&2&4&2\\
0&0&0&\cdots&0&2&4\\
\end{vmatrix}}^{(n-1)\text{ columns}}
-4\cdot\overbrace{\begin{vmatrix}
4&2&0&\cdots&0&0&0\\
2&4&2&\cdots&0&0&0\\
0&2&4&\cdots&0&0&0\\
\vdots&\vdots&\vdots&\ddots&\vdots&\vdots&\vdots\\
0&0&0&\cdots&4&2&0\\
0&0&0&\cdots&2&4&2\\
0&0&0&\cdots&0&2&4\\
\end{vmatrix}}^{(n-2)\text{ columns}}\quad\text{(expanding first column)}\\
&=4D_{n-1}-4D_{n-2}\\
\end{align}
Comment: understood it,thanks for your support


Erro no .First(), pois não existe resultado selecionado

Question: No meu controller de Login utilizo o seguinte código para fazer a seleção do usuário caso exista, porém sempre que ele o usuário digita o nome ou senha incorreto, ele dá um erro, pois não encontra o resultado para o .First. Preciso fazer um tratamento, para quando não encontrar nenhum resultado não dá esse erro.
var user = db.Usuario.First(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha));

Answer: Existem algumas soluções para isto, uma delas é usar o FirstOrDefault().
var user = db.Usuario.FirstOrDefault(u => u.Nome == model.Nome && u.Senha.Equals(model.Senha));

Obviamente você terá que tratar o resultado depois se não existir nenhum usuário compatível com o que foi informado, afinal, o resultado será um null se não achar nada, sem um tratamento, só estará empurrando o problema mais pra frente. Mas fazendo assim, usará o fluxo normal. Algo do tipo:
if (user == null) return false;

Coloquei no GitHub para referência futura.


IIS 7.5 fails to open database after computer machine on that database server is working restarts

Question: I decided to post this question also here in case the issues we have is related to sql server.
There is a problem that bother me for some time. I have an asp.net mvc that uses NHibernate for modeling the database. The infrastructure is the following: Windows 2008 R2 for all virtual machines. IIS 7.5 is working on one virtual machine. Sql Server 2008 is working on another virtual machine. We have couple of databases, two that stores application data and one that registers all unhandled exceptions.
Sometimes virtual machine that hosts database server restarts (in the middle of the night, not quite sure about the reason) after that connection to the databases that stores application data is not working and as result there are thousands of unhandled exceptions that get registered in the third database. Important to mention that databases are accessible from Management Studio. The problem is solved by resetting IIS. Connetion are handled via NHibernateUtil class which opens and closes session at each request.
Answer: Looks like a coding error to me. Basically - yes, the app is not usable while sql server restarts. Happens (look into a second server running a mirror if you fix that).
If the web app though gets permanently unusable something is bad with the handling of database connections. Like the app "holding on" to unusable database connections, instead of letting them go and just open new ones. Breaking best practices (keep db connections only open as lnog as needed).
The reason for sql server restart may be patching, btw., CHeck auto update settings.


A slight generalization of the Sieve of Sundaram that might shed light on the $6n \pm 1$ phenomenon of sequence A002822.

Question: There's the $n$ such that $6n \pm 1$ is a twin prime pair sequence: https://oeis.org/A002822
It contains all twin prime averages (divided by $6$) other than $4$.

Notice this sequence: Positive numbers $n = 6xy + x + y$ such that $x,y \in \Bbb{Z}$.  That sequence is the complement (all entries found in $\Bbb{N}$ that are not in A002822, by its very definition).
But notice the $6xy + x + y$ part.  That reminded me of the Sieve of Sundaram's $2ij + i + j$ form. Thus:

Start with a list of integers from $81$ to $N$, and cross out all elements of the form $6ij + ki + lj$ such that $k, l \in \{1,3,5\}$ and $i,j \geq 1$.  Then taking the remaining elements, multiplying them by $6$ and adding respectively $lk = 1,3,5,9,15, $ or $25$; and of course we union the result of each case / cross-out form.
We have the following possibilities:
$$
6(6ij + i + j) + 1 = (6i + 1)(6j + 1) \\
6(6i + i + 3j) + 3 = (6i + 3)(6j + 1) \\
6(6ij + i + 5j) + 5 = (6i + 5)(6j + 1) \\
6(6ij + 3i +3j) + 9 = (6i + 3)(6j + 3) \\
6(6ij + 3i + 5j) + 15 = (6i+5)(6j+3) \\
6(6ij + 5i +5j) + 25 = (6i + 5)(6j + 5) \\
$$
The above will cover all odd numbers $\geq  81$ which we find by setting $i=j = 1$ and computing the smallest formula above which is $(6i + 1)(6j + 1) = 81$.
Thus we've filtered out all and only composites $\geq 81$, clearly, and via inspection of the above factorizations.
See: Sieve of Sundaram.

However, all primes $\gt 3$ are of the form $6n + 1$ or $6n + 5$.  Thus we can cross out lines $2,3,5$ in the above 6 formulas, or namely the lines with added $3,9,15$.  But $6n + 25 = 1 \pmod 6$ so it is left and the list of cross-out forms in the generalized Sundaram sieve becomes:
$$
6ij + i + j \\
6ij + i + 5j \\
6ij + 5i + 5j \\
i,j \geq 1
$$
Thus, that is the Sundaram sieve method genralized to a multiple of $6$ instead of just $2$.  You could probably do similarly, with other multiples.
Question. Can we remove even more unecessary cross-out forms so that there would be less than $3$?
Comment: Maybe you find your answer here: https://math.stackexchange.com/questions/3818314/sieve-for-primes
Answer: No, you can't remove more, $3$ is the minimum. In fact, there are $4$, but one of them is superfluous because of symmetry. Before getting to the point, a first observation: the $6xy+x+y$ form you mention at the top of your question is equivalent to, and better known as $6xy \pm x \pm y$, and if you take your $3$ final forms modulo 6, you'll realize they're in fact identical to that form.
And there's a good reason for that: the proof that positive integers $n$ that can't be written in the $6xy \pm x \pm y$ form are bijectively related to twin primes is mostly just a simple change of coordinates for an elliptic curve equation. The derivation should prove a fun exercise. And essentially, you'll arrive at
$$
6xy \pm x \pm y = n \quad \text{has no solutions for $(x,y) \in \mathbb{Z}^2$.}\\
\big\Updownarrow \\
X^2-Y^2=6n \pm 1 \quad \text{both have only one solution.}
$$
So yeah, I'm afraid you do need all $3$ of them.
Answer: First note that $6(0)+5$ is prime, so you would need it in $6(1)-1$ form for the last inequality to hold.  But yes, the Sieve of Sundaram has generalizations to all multiplicative groups. It can be reduced to $6ij\pm i\pm j$ if you need to save space but might want to save that for mod 30 with 36 cases.
In Addition, it can be generalized to find semiprimes with lower bounds on factors etc. Just let $i,j$ not be also representable using some other values. Then it's a product of primes. If exactly 1 is of the form of a semiprime has 3 prime factors ...  But 3 cases exist with 2 possibilities each.
Comment: $(6i+1)(6j+1)=36ij+6i+6j+1$ and $(6i-1)(6j-1)=36ij-6i-6j+1$ are both  composites of form $6n+1$ if $i,j > 0$  and $(6i+1)(6j-1)= 36ij-6i+6j-1$ is the same for form $6n-1$ . only if a number $n$ misses the floor of the division by 6 of the first two, and the ceiling of division by 6 of the other, will it be a value such that $6n\pm 1$ are both primes.
Comment: Could I say that the complement of the set $\{6xy + x + y: x,y  \in \Bbb{Z}\}$ is roughly the set of twin prime averages (plus some initial values where say $x,y = 0, 1$)?


Invalid cast exception: trying to join two tables using linq-sql

Question: I'm trying to join two tables using their common id which is MOTHERID. But he code below was working fine but at some point it starts  throwing "Invalid cast exception" at:
 var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();

I think the exception is being caused by the toList() conversion because when I remove .ToList() it works fine but I need to use that for the rest of the code to work properly. Here is some part of the code:
MaternalVisitData _maternalvisitvaluedb =
new  MaternalVisitData(MaternalVisitData.strConnectionString);
MaternalCareData _maternalcarevaluedb =
new MaternalCareData(MaternalCareData.strConnectionString);

var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();
var secondQuery = (from t in _maternalcarevaluedb.Value select t).ToList();

var result = (from s in firstQuery
join k in secondQuery
on s.MotherId equals k.MotherId
where (DateTime)s.SecondVisit.Date == DateTime.Now.Date
select s).ToList();

Thanks for your help!
Answer: try specific type alternate of var in below lines :
var firstQuery = (from s in _maternalvisitvaluedb.Value select s).ToList();
var secondQuery = (from t in _maternalcarevaluedb.Value select t).ToList();

like this :
List<maternalvisitvaluedb> firstQuery = (list<maternalvisitvaluedb>)(from s in _maternalvisitvaluedb.Value select s).ToList();
List<maternalcarevaluedb> secondQuery = (List<maternalcarevaluedb>)(from t in _maternalcarevaluedb.Value select t).ToList();

it's a pseudo , I hope it helps you
Comment: I have tried it and the data contexts maternalvisitvaluedb and maternalcarevaluedb doesn't consider them as valid datatypes.
Comment: i knew they are not valid datatypes,please change them to their valid datatype that you are using
Comment: I have changed to its valid datatype still it is throwing the invalid cast exception.
Comment: 1.does these tables have relations?if they are,check them to doesn't be null. 2.Is motherid a primary key?if it's not check it to doesn't be null.


Confusion with sscanf_s

Question: I am having issues with sscanf_s, essentially I have this line of code:
sscanf_s( line.c_str(),
          "<float_array id=\"%*s[^\"]\" count=\"%*d\">%[^<]s",
          numString);

I am feeding it this line of text:
<float_array id="Cube-mesh-positions-array" count="24">1 1 -1 1 -1 -1 -1 -0.9999998 -1    -0.9999997 1 -1 1 0.9999995 1 0.9999994 -1.000001 1 -1 -0.9999997 1 -1 1 1</float_array>

What I am trying to achieve is read the number array written after count="24"> and pass it to another function, however numString remains with a value of "" after being passed through the equation, therefore causing the subsequent functions to fail. if anyone could offer me insight into why this is occurring I would be very appreciative.
A short SSCCE that I have tested has revealed that the problem lies elsewhere, I shall have to investigate this further - sorry for wasting your time, and thank you for taking your time to try and help me.
Comment: What type is `numString` ? can you give an [sscce](http://www.sscce.org/) ? note that sscanf_s is C and thus your question might be better reformulated as a C question, unless some C++ specific thing is part of the question.
Comment: numString is just a string variable (using std::string), and my apologies about the mismark as a C++ question, I was using C++ and have no experience in C and so was not aware that this was a C function
Comment: Note that the `s` at the end of the format string is a literal `s`, not part of the scan-set notation.  Fortunately for you, there's no way to tell that it fails to match in the input string.
Answer: The function sscanf_s is a Microsoft invention, intended to be "more secure" than the standard sscanf function.
As such, if you are using "%s" or "%c", it requires two parameters: One being the buffer to write the input to, and an integer specifying the available size of the buffer, so that a long input string does not result in a buffer overflow.
Unfortunately this is not quite that obvious to users of the function (like yourself), resulting in frequent mis-use of the function (which somewhat reduces the "security" implied).
Link to the Microsoft docs; refer to the section "remarks".
So what you have here is undefined behaviour, as sscanf_s attempts to read an integer from the stack where you haven't put one. You end up lucky that the memory read is apparently zero, so zero bytes are written to numString.
This should do nicely:
size_t BUFSIZE = 50;
char numString[ BUFSIZE ];
sscanf_s( line.c_str(),
          "<float_array id=\"%*s[^\"]\" count=\"%*d\">%[^<]s",
          numString, BUFSIZE );

Note that numString better actually be a char[]. Your question was initially tagged as C++; if numString is actually a std::string, be advised that you cannot use the scanf family function with std::string parameters.

(Sorry for the edits, got it wrong the first few times. That format string is something... ;-) )
Comment: True that format better as `"%[^<]",` (drop _2_ s).  `C` ans `S` are MS extensions.  `sscanf_s` is in the C spec in the appendix.
Comment: Minor: "if you are using `"%s"` or `"%c"`" should also include `"%["`.
Comment: @chux: Actually it's "type field characters c, C, s, S, or string control sets that are enclosed in []." I've never had use for [] myself, so I wrongly assumed that the specifier is actually `"%[]s"`. Which raises another point with the OP's code: The trailing `"s"` is erroneous.
Comment: I tried the edits you suggested (using much larger numbers, as this system is supposed to work for long strings as well as short) and am still coming across the same problem, except now `numString` is equal to `"ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ..."` after the function fires
Comment: @user2289437: An update of your question including a [SSCCE](http://www.sscce.org) would be nice.
Comment: added as close to an SSCCE as I could manage, sorry if I screwed it up
Comment: @user2289437: No, that's not what "short" means. "Short" would be one line defining the string to be scanned, one line scanning the string, one line printing what was scanned. If your problem really is with `sscanf_s`, those three lines would suffice, and all the remaining code is superfluous. If your problem is *not* with `sscanf_s` (let's say, you've got an error in your reading-from-file), you would find out while reducing the code. You know, right now I'm sitting on my terrace, enjoying the sunshine at 33 degree celsius. If you want me to give an answer, make the question easy. ;-)
Comment: this means if you use sscanf_s in accordance with %f, you don't need to specify any buffersizes since 'float' has a fixed size, correct?
Comment: @AgentM: As the linked docs state, *"...a buffer size parameter is required when you use the type field characters c, C, s, S, or string control sets that are enclosed in []."* -- As %f is not mentioned here, no buffer size parameter is expected.
Comment: How could sscanf_s be used insecurely?
Answer: char numString[ 256 ];
sscanf_s( line.c_str(),
          "<float_array id=\"%*[^\"]\" count=\"%*d\">%255[^<]",
          numString, 256);

Comment: Maybe explain a bit more.
Comment: There is an extra `s` in the code of the OP. OP also need to specify the buffer size.

Confusion with sscanf_s


Best way to start an app in Free or Pro mode

Question: I have an Android app and I also offer 1 inapp purchase to unlock such app to the Pro version.
I know how to do use the inapp purchase API and such but I found discordant ways on how to check if the app should start as Free or Pro.
Many people suggest that after a successful purchase the app should store the Google Play receipt or other information in a local database and let the app check the presence of that information at startup (in order to start properly as Free or Pro)
My question is, instead of bothering saving the purchase information and retrieving it from a local database why not calling the restore purchase API RestorePurchases(), have a look at the returned object if the InApp item is present and unlock the app accordingly?
As far as I know the call doesn't require internet connection, it's just a local call to the local Google Play authority... am I missing something?
Answer: Let me explain how we manage it at QuitNow!, an app with the same behavior than yours.
We only have one SKU called unlock_all_pro_features. If the user has it, it means that the user bought the PRO features before.
So, in the Android side, everytime the app is started we try connecting to IInAppBillingService. When onServiceConnected() is called, we ask it for all the user owned SKU's.  If it has our lovely SKU, we store in a SharedPreference that the user was a PRO one. And then, if it wasn't PRO before doing all this magic, we update the screen to show the brand new features.
Bad things there: the user can return the SKU!
To face that, when we consider that a user was a PRO one, we also ask if the user has the needed SKU. If that check fails 20 times, we reset the features to the FREE version.
Why checking it 20 times instead of just one time? Sometimes, we found that the service said that the user had any SKU, while he actually had the PRO one. Why? Don't know. So, checking it 20 times is a simple way to assure that we don't kick PRO users when unneded.


How to find out the pitch of a melody in Ableton live 10?

Question: I have a sample that plays 4 chords. I have no idea what their key/pitch is. I've tried using the tuner audio effect but it doesn't say anything at all. Does anyone know an alternate way to find the pitch of a sample?
Comment: I have a launchpad pro. Does that count?
Comment: Do you own *any* other musical instrument?
Comment: Yes, kind of… but not really in this context, because it doesn't use quantifiable notes. The very simplest way to find out what note something is playing is to find the same note on any instrument you can name the notes of [whether you do this by "talent" or by hitting notes at random until you find one that matches is really just a matter of expediency;)
Comment: Isn't there some sort of tool or audio effect that can do what i'm trying to do?
Comment: Melodyne can recognise multiple pitches in chords etc, but at €150 I'm sure it would be cheaper & simpler to find some old keyboard & just play at "find the note" like musicians have been doing for centuries.
Comment: Have you tried converting harmony to MIDI?
Answer: There is a free app called TE Tuner, available in the Apple and Google play store. This app has a function called Analysis which displays pitch, and another function called Sound - which will display the key of whatever 'sound' it hears. HTH Catz
Comment: I have used it for chord practice, using the Sound selection. it does not recognize every chord.
Comment: Can that identify chords? It doesn't look like it can.
Answer: You can try using the 'audio to midi' conversion of a clip. See Chapter 12.2 of Ableton Live manual


how to change background-image when the page reloads?

Question: Well, iam trying to create a page with diferents backgrounds this is what i did so far.
export default {
  name: 'app',
  components: {
    NavBar
  },
  data(){
    return{
      images:[
        {img: '"./assets/img1.jpg"'},
        {img: '"./assets/img2.jpg"'},
        {img: '"./assets/img3.jpg"'},
        {img: '"./assets/img4.jpg"'},
        {img: '"./assets/img5.jpg"'},
        {img: '"./assets/img6.jpg"'},
      ]
    }
  },
  methods:{
    changeBackgroundImage() {

      var item = this.images[Math.floor(Math.random() * this.images.length)].img
      //test 1:
      // document.body.style.backgroundImage = "url(" + item + ")"

      //test 2:
      document.body.style.backgroundImage = "url('./assets/img6.jpg')";

      //test 3:
      // document.body.style.background= 'red'

    },
  },
  created: function(){
    this.changeBackgroundImage()
  },
}

so, i get a random item on the array, i then put him on the background image right(test 1)?
 but this are not working, so for tests, i try put the path directly (test 2), still not working, no error or message, just... not happen.
So i tried another style command (test 3), just for have sure that this are working, and yah, work normally, letting everything red.
when i go on network, there is a img there, but she is full white, not the one a choose.
So, why are javascript ignoring my background images?
https://github.com/RamonRemo/Projeto1-LembreSee-Front
Comment: When using VueJs you should not manipulate the dom yourself. Check out computed properties and style in their documentation.
Comment: Quick (but probably dirty, not an expert in Vue) fix: https://pastebin.com/ZF5HYVMn
Comment: Kastasx this actually work on the test2, but when i do on test 1 document.body.style.backgroundImage = `url(${require(item)})`; it doest =(
Comment: For anyone coming here years later, like me, this answer takes care of it beautifully: https://stackoverflow.com/a/66925623
Answer: You're missing a set of quotes in your first test, try like this:
document.body.style.backgroundImage = "url('" + item + "')";

Comment: not work =(,
Thats why i was using double quote, i remove them and try your way, but no success


How to understand isNaN

Question: I try below code block, the isNaN return true. The value is not NaN why the return value is true?
true 06-19 12:20:30.200

        var t = d3.timeParse("%Y-%m-%d %H:%M:%S.%L")("2022-06-19 12:20:30.200");
        v = d3.timeFormat("%m-%d %H:%M:%S.%L")(t)
        var isNan = isNaN(v)
        console.log(isNan,v)

Answer: You should use Number.isNaN() instead. The global version of isNaN() has some confusing behavior.

When the argument to the isNaN function is not of type Number, the value is first coerced to a Number. The resulting value is then tested to determine whether it is NaN.

        var t = d3.timeParse("%Y-%m-%d %H:%M:%S.%L")("2022-06-19 12:20:30.200");
        v = d3.timeFormat("%m-%d %H:%M:%S.%L")(t)
        var isNan = Number.isNaN(v)
        console.log(isNan,v)

How to understand isNaN


Sliding menu highlight not working

Question: I'm trying to implement this sliding menu highlight but having some difficulty. I have a fiddle to demonstrate the problem.
HTML:

            Home

            Contact

            Portfolio

CSS:
body {
    background: #ccc;
}
.nav {
    border:0;
}
.nav ul {
    margin:auto
}
.nav li {
    float:left;
    position:relative
}
.nav li a {
    border-bottom:0
}
.nav li ul.sub-menu, .nav li ul.children {
    margin-top:0;
    border:1px solid #ccc;
    border-top:0;
    position:absolute;
    display:none;
    z-index:8999
}
.nav li ul.sub-menu li a, .nav li ul.children li a {
    padding-left:10px;
    border-right:0;
    display:block;
    width:180px;
    border-bottom:1px solid #ccc
}
.nav li ul.sub-menu li:last-child a, .nav li ul.children li:last-child a {
    border-bottom:0
}
.nav li:hover ul {
    top:auto;
    display:block
}
.nav.top-nav ul {
    margin:0 auto;
    list-style:none;
    position:relative
}
.nav.top-nav ul li {
    display:inline-block
}
.nav.top-nav ul li a {
    position:relative;
    z-index:200;
    display:block;
    float:left;
    padding:6px 10px 4px 10px
}
.nav.top-nav ul li a:hover {
    color:#fff
}
.nav.top-nav ul li#sliding-highlight {
    position:absolute;
    top:0;
    left:0;
    width:100px;
    background:#f2065f;
    z-index:100;
    -moz-border-radius:25px 25px 25px 25px;
    -webkit-border-top-left-radius:25px;
    -webkit-border-top-right-radius:25px;
    -webkit-border-bottom-right-radius:25px;
    -webkit-border-bottom-left-radius:25px;
    border-radius:25px 25px 25px 25px
}
.nav.top-nav ul .current_page_item a {
    color:#fff
}
.nav .ie6 .top-nav li, .nav .ie7 .top-nav li {
    display:inline
}

JavaScript:
/* Menu sliding animation script */
$(function () {

    var $el, leftPos, newWidth;
    $mainNav = $(".top-nav ul");

    $mainNav.append("

");

    var $slidingHighlight = $("#sliding-highlight");

    $slidingHighlight.width($(".current_page_item").width())
        .height($mainNav.parent().height())
        .css("left", $(".current_page_item a").position().left)
        //.data("origLeft", $(".current_page_item a").position().left)
        .data("origWidth", $slidingHighlight.width());

    $(".top-nav li a").hover(function () {
        $el = $(this);
        leftPos = $el.position().left;
        newWidth = $el.parent().width();
        $slidingHighlight.stop().animate({
            left: leftPos,
            width: newWidth,
            backgroundColor: $el.attr("rel")
        })
    }, function () {
        $slidingHighlight.stop().animate({
            left: $slidingHighlight.data("origLeft"),
            width: $slidingHighlight.data("origWidth")
        });
    });

    /* Kick IE into gear */
    $(".current_page_item a").mouseenter();

});

I have two problems I know of right now:

The height isn't being set on the li item created by the script.
The left position attribute is not being set when the hover event fires.

I know the selector I'm using to get the height and left position are good because other attributes like the width are being set properly.
Any suggestions how I might make this work?
Answer: I think there is problem with position() method try with offset() method i have updated your code in [fiddler][1] please check and let me know you have any concerns
jsfiddle.net/3C89r/3/

Sliding menu highlight not working


How update user info using its UID in a custom module?

Question: We have a webform and when submitting this form we would like to update user info in the database regarding values of submitted Webform.
I already managed to get the submitted values from the webform in my custom module. But I don't know how to update the user info in the database because all user info are in separated tables.
I can run a few update queries for each value but it's not a logical way for me!
Any other suggestions?
Answer: You can equally use either user_save() or field_attach_update().
// Load the user's account.
global $user;
$account = user_load($user->uid);
$edit = $account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
user_save($account, $edit);
// field_attach_update
$account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
field_attach_update('user', $account);

The difference between using one function or the other is that user_save() will update all the user fields whereas field_attach_update() will update only the specified field.
Comment: thx for ur answer, just a question, is this line getting the user ID and update it's profile '$account = user_load($user->uid);' ?
Comment: Welcome! No, you need the `$user->uid` to `user_load` a user and then when you `user_save` to update the user. The `uid` is a field attached to the `$user` entity, do a `describe users;` to your database and you will see all the available user fields. Thus, we are never getting the user id in the way you mean it, as a single/isolated value, instead, we are getting the user object with all its fields attached (from the db) and we decide to which field(s) to refer to.
Comment: Thx @mchar I understood :)
Comment: @Soheyl Using `user_load($user->uid)` is just an example. In your code you will use the user ID you have, if you have one, or the code shown in this answer, if you need to save a field for the currently logged-in user.


List of lists to dictionary to pandas DataFrame

Question: I am trying to fit this data:
[['Manufacturer: Hyundai',
  'Model: Tucson',
  'Mileage: 258000 km',
  'Registered: 07/2019'],
 ['Manufacturer: Mazda',
  'Model: 6',
  'Year: 2014',
  'Registered: 07/2019']]

to pandas DataFrame.
Not all labels are present in each record, for example some records have 'Mileage' and others don't and vice versa.
I have a total of 26 features and very few items have all of them.
I would like to construct pandas DataFrame that will hold features in columns and if feature doesn't exists than content should be 'NaN'.
I have
colnames=['Manufacturer', 'Model', 'Mileage', 'Registered', 'Year'...(all 26 features here)]
df = pd.read_csv("./data/output.csv", sep=",", names=colnames, header=None)

Few first prerequisite columns are giving expected output but when it comes to optional features than missing data causing features after that to turn out under wrong columns.
Records are mapped correctly only if all features are present.
I forgot to mention that some features that are missing value also don't have ":" but are present in list.
So in this 2 cases:

'Mileage', (value missing, but also ':' is missing)
missing 'Mileage' from record altogheter

assignment for both cases should be 'NaN'.
Answer: Use nested list comprehension for list of dictionaries and pass to DataFrame contructor, if same key is missing is added NaN:
L = [['Manufacturer: Hyundai',
  'Model: Tucson',
  'Mileage: 258000 km',
  'Registered: 07/2019'],
 ['Manufacturer: Mazda',
  'Model: 6',
  'Year: 2014',
  'Registered: 07/2019']]

df = pd.DataFrame([dict(y.split(':') for y in x) for x in L])
print (df)
  Manufacturer     Mileage    Model Registered   Year
0      Hyundai   258000 km   Tucson    07/2019    NaN
1        Mazda         NaN        6    07/2019   2014

EDIT: You can use .split(maxsplit=1) for split by first whitespace:
L = [['Manufacturer Hyundai',
  'Model Tucson',
  'Mileage 258000 km',
  'Registered 07/2019'],
 ['Manufacturer Mazda',
  'Model 6',
  'Year 2014',
  'Registered 07/2019']]

df = pd.DataFrame([dict(y.split(maxsplit=1) for y in x) for x in L])
print (df)

  Manufacturer    Mileage   Model Registered  Year
0      Hyundai  258000 km  Tucson    07/2019   NaN
1        Mazda        NaN       6    07/2019  2014

EDIT:
L = [['Manufacturer  Hyundai',
  'Model  Tucson',
  'Mileage  258000 km',
  'Registered  07/2019'],
 ['Manufacturer  Mazda',
  'Model  6',
  'Year  2014',
  'Registered  07/2019',
  'Additional equipment aaa']]

words2 = ['Additional equipment']

L1 = []
for x in L:
    di = {}
    for y in x:
        for word in words2:
            if set(word.split(maxsplit=2)[:2]) < set(y.split()):
                i, j, k = y.split(maxsplit=2)
                di['_'.join([i, j])] = k
            else:
                i, j = y.split(maxsplit=1)
                di[i] = j
    L1.append(di)

df = pd.DataFrame(L1)
print (df)
  Additional_equipment Manufacturer    Mileage   Model Registered  Year
0                  NaN      Hyundai  258000 km  Tucson    07/2019   NaN
1                  aaa        Mazda        NaN       6    07/2019  2014

Comment: Awesom! Works perfectly! Thank you sooooo much!
Comment: It says : ValueError: dictionary update sequence element #18 has length 1; 2 is required . Thats first empty element in first record.
Comment: My mistake. actually those elements are not just missing, they don't have ":" after feature name.
Comment: Your 1st version work perfectly on records with missing features. I'm already super-thankful for that! Unfortunately updated version is not working on records where features have 2 words ('Additional equipment',) for example .


How get numbers from string (C#)

Question: I have the following string:
{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}

I need to get as result an array of numbers:
5
19
34
I can't find the necessary regex expression for this action.
Thanks for help in advance.
Answer: Here you go:
string input = "{ (MerchantId eq 5 or MerchantId eq 19 or MerchantId eq 34)}";
Regex regex = new Regex(@"(\d+)");
List<int> numbers = new List<int>();

var matches = regex.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
    numbers.Add(Int32.Parse(matches[i].Value));
}

If you insist on arrays use this instead:
var matches = regex.Matches(input);
int[] numbers = new int[matches.Count];

for (int i = 0; i < matches.Count; i++)
{
    numbers[i] = Int32.Parse(matches[i].Value);
}

Comment: Thanks yo so much! List is valid too!

How get numbers from string (C#)


Show that $A∩B∩C= ∅$ is only true when $A∩B = ∅, A∩C = ∅$ or $B∩C = ∅$ or show a counterexample.

Question: Show that $A∩B∩C= ∅$ is only true when  $A∩B = ∅, A∩C = ∅$ or $B∩C = ∅$ or show a counterexample.
My answer:
True, Let set A={a,b,c,...}, set B={1,2,3,...} and set C={-1,-2,-3...}. Then there is not common elements in A, B or C. Thus, A∩B∩C= ∅. A∩B = ∅, A∩C = ∅ or B∩C = ∅.
Is my prove right?
Comment: I believe you are confused about the question itself, which I believe to be the following: *Suppose $A, B, C$ are three sets, such that $A \cap B \cap C = \emptyset$. Is it true that $A \cap B = A \cap C = B \cap C = \emptyset$?*
Comment: As a general comment, remember that if you want to prove a given property you must do that formally not by an example. You provide an example where the statement hold. This does not imply that the statement is always true ($A=B=$non empty, $C=\emptyset$). On the other hand it suffices only one counterexample to show that the statement does not always hold.
Comment: It's not clear what the statement is. If it is "If $A\cap B\cap C=\emptyset$, then $A\cap B=\emptyset$, $A\cap C=\emptyset$ and $B\cap C=\emptyset$", then you can't prove it by example (and, by the way, it is false).
Comment: No, probably better to fix this posted question, otherwise it would look like an attempt to make a duplicate of one's own question when people complain about the first question. That is seen as an attempt to circumvent the system.
Comment: So, as advised also by @egreg, try to find three sets $A, B, C$ which satisfy $A \cap B \cap C = \emptyset$ but not (any of) the $A \cap B = A \cap C = B \cap C = \emptyset$. You don't have to look far, you can choose $A, B, C \subset \{1, 2, 3\}$.
Comment: I edited your question (partially); check it please
Comment: did you mean **or** - the proof is more complicated
Comment: @ Jon Mark Perry , oh yes, my mistake. its suppose to be oA∩B∩C= ∅. A∩B = ∅, A∩C = ∅ OR B∩C = ∅.
Comment: bit late for that now - try another posting :))
Comment: @user1 has probably given a perfect answer!
Answer: (Just another counterexample.)
Answer: Hint: consider $A=\{1,2\}$, $B=\{2,3\}$ and $C=\{1,3\}$.

When you have a statement of the form

If $A\cap B\cap C=\emptyset$, then $A\cap B=\emptyset$, $A\cap C=\emptyset$ and $B\cap C=\emptyset$

you can't prove it true by example. You can prove it false by showing a counterexample.
Answer: $$A=\{1,2\}, B=\{2,3,4,5\}, C=\{1,5\}$$ then:
A∩B∩C= ∅
A∩B={2}
A∩C= {1}
B∩C= {5}
Comment: It is the perfect answer, I think...


Dados de tabela React Data Table Component não aparecem

Question: Criei uma tabela usando React Data Table Component. Fiz a tabela como um componente separado, importando-a para o App onde será usada. A princípio, as colunas e os dados da tabela devem ser passados pelo App, já que a ideia é usar o componente tabela também em outros lugares. Sendo assim, criei o App passando as colunas e os dados por props para o componente. O problema é que apenas os nomes das colunas aparecem no cabeçalho da tabela, mas os dados ficam em branco. O engraçado é que as linhas da tabela são criadas, mas os dados não aparecem. No exemplo abaixo, passei um array de dados com 5 objetos e foram criadas 5 linhas na tabela. Porém as linhas ficam em branco. Poderiam me ajudar?
import Tabela from '../../componentes/dataTable';

export function Card(){

    const arrayColumns = [
        'Nome',
        'Prod_vtex',
        'Tipo',
    ]

    const arrayData = [
        {
            id: 1,
            nome: 'name01',
            prod_vtex: '0001',
            tipo: 'tipo1'
        },
        {
            id: 2,
            nome: 'name02',
            prod_vtex: '0002',
            tipo: 'tipo2'
        },
        {
            id: 3,
            nome: 'name03',
            prod_vtex: '0003',
            tipo: 'tipo3'
        },
        {
            id: 4,
            nome: 'name04',
            prod_vtex: '0004',
            tipo: 'tipo4'
        },
        {
            id: 5,
            nome: 'name05',
            prod_vtex: '0005',
            tipo: 'tipo5'
        }

    ]

    return(

             <Tabela
                 columns = {arrayColumns}
                 data = {arrayData}
             />

    )
}

No componente da Tabela está assim:
import DataTable, { createTheme } from 'react-data-table-component';

const Tabela = (props) => {

    createTheme('solarized', {

        background: {
            default: '#dcdcdc'
        },

        striped: {
            default: '#ffffff',
        }
    })

    const customStyles = {
        headCells: {
            style: {
                backgroundColor: '#000',
                color: '#fff',
                height: '50px',
                fontWeight: 'bold',
                fontSize: '15px'
            }
        },
    }

    let columns = props.columns.map((i) => {
        return (
            {
                name: i,
                selector: row => row.i,
                sortable: true,
            }
        )
    })

    let data = props.data

    return (
        <>
            <DataTable
                columns={columns}
                data={data}
                pagination
                customStyles={customStyles}
                theme='solarized'
                striped
                fixedHeader
                fixedHeaderScrollHeight="400px"
                highlightOnHover
                subHeader
                subHeaderComponent={
                    <input
                        type='text'
                        placeholder='Pesquisar'
                        className='form-control'
                    />
                }
                subHeaderAlign='left'
            />
        </>
    )
}

export default Tabela

Já tentei criar uma variável para os dados e retornar props.data de uma function, percorrer o array, dentre outras coisas e nada. Se eu der um console.log(data) me retorna um array com os objetos.
Enfim, é isso...
Comment: @CésarRodriguez era exatamente isso! Muito obrigado!
Comment: Se lá no seu objeto ```arrayData``` você mudar o nome da propriedade ```id``` para ```key```, acontece algo diferente? Ficaria ```key: 1,``` até ```key: 5,```.
Comment: @CésarRodriguez Infelizmente não. Continua do mesmo jeito...
Comment: Opa! Comparando com a documentação, acho que o problema está aqui: ```selector: row => row.i,```. Em JavaScript, para usar nomes dinâmicos de propriedades, você precisa da notação com colchetes, então creio que o correto seria ```selector: row => row[i],```. Teste e diga se funcionou.
Comment: Mesmo que ```i``` seja uma variável que contém o valor "nome", para acessar a propriedade "nome" do objeto "foo" você precisa fazer ```foo[i]```. Se você fizer ```foo.i```, seu código não interpreta o conteúdo da variável, ele busca uma propriedade literalmente chamada i.
Comment: @CésarRodriguez substituí `selector: row => row.i` por `selector: row => row[i]`, porém continua da mesma forma. :(
Comment: Agora, provavelmente o nome das colunas não está batendo porque o javascript distingue maiúsculas de minúsculas. Faça mais essa modificação: ```const arrayColumns = [ 'nome', 'prod_vtex', 'tipo' ]``` (ou seja, troque as maiúsculas por minusculas, pra ficar igual às propriedades do objeto data).
Comment: Mantenha a alteração anterior (```row[i]```), mas não precisa manter a primeira (pode deixar as chaves id, como está no exemplo da documentação).
Answer: Olá! Conforme a documentação da API, as colunas são definidas por objetos, os quais devem ter uma propriedade selector, cujo valor é uma arrow expression que avalia para a propriedade do objeto de dados que aquela coluna deve exibir.
No seu caso, houve dois erros:

Os nomes dos objetos a serem passados no selector da coluna devem corresponder às propriedades respectivas no objeto-fonte de dados, e JavaScript é case-sensitive. Então, ou você muda sua array do nome das colunas, ou trata elas com um toLowerCase() antes de passar pro selector da coluna. Como a segunda opção vai acoplar o título da coluna (visível ao usuário do site) ao nome da propriedade, vou adotar a primeira opção. É só mudar sua array com os nomes das colunas para os nomes em minúsculas, exatamente como as propriedades da array de dados:

const arrayColumns = [
    'nome',
    'prod_vtex',
    'tipo',
]

Para referenciar uma propriedade de um objeto de forma dinâmica usando uma variável, o javascript não permite a notação com ponto, é necessário usar a notação de colchetes. Veja essa resposta.. Portanto, os selectors da array columns devem ser mapeados assim:

let columns = props.columns.map((i) => {
    return {
        name: i,
        selector: row => row[i],
        sortable: true,
    }
})


Open the web browser on Android emulator

Question: I just installed the Android SDK on my Windows 7 64-bit. I'm creating a web app, so all I'd like to do is open the Android web browser. I double clicked on tools/emulator.exe, but all it did was flash a CMD box on the screen for a split second. I proceeded to read the documentation. It says I have to type this command in CMD to open the emulator:
emulator -avd <avd_name>

What exactly do I put in <avd_name> to open the web browser?
Comment: AVD is the name of your emulated device. It has nothing to do with what you're going to do with what you're going to do with the device. You can use ADB to run something on your device once the emulator has loaded.
Answer: First you must create an AVD (Android Virtual Device). How to do that, find out here. Afterwards, you can start it using the command you provided. When the emulator has started, you can simply click on web browser's icon to start it.
To create an AVD, I'd recommend using Eclipse and Android development tools for Eclipse; it's easier than using command line if you're just beginning Android development.
Comment: I created an AVD with a 128 MB SD card and the rest of the settings left as defaults. It took nearly 5 minutes to launch the AVD. Clicking around the interface feels sluggish. My computer is a Core i7 920 with 6 GB of DDR3 RAM. This should be more than enough to run a measly Android device. What's going on?
Answer: this has nothing to do with your app : you ave to create an AVD first, by using the AVD & SDK Manager, lauched by  android-sdk-dir\tools\android.bat
Answer: AVD represents the name of the emulator and it has nothing to do with the application that you want to run, follow this procedure if you are using eclipse : go to run, select run configuration>>select your project>>go to target>> here you can select the specific android device according to your needs >> hit run.
i think that will solve your problem.


Put random numbers inline in Ruby

Question: I have two counters with simple animation that puts numbers under each other. How to make them all inline with the same functional? Thanks for watching!
1000.times do

    puts "Press Enter"
    gets

        x = rand (0..5)
        y = rand (0..5)

        # "x" counter
        10.times do |xx|

            meter = rand (0..5)
            if xx < 9
                print meter
                print "\r"
                sleep 0.08
                else print x
            end
        end

    puts

        # "y" counter
        10.times do |yy|

            meter = rand (0..5)
            if yy < 9
                print meter
                print "\r"
                sleep 0.08
                else print y
            end
        end

    puts

end

Answer:
Use "\b"  backspace (0x08) character instead of "\r" carriage return (0x0d) character.

1000.times do

  puts "Press Enter"
  gets

  x = rand (0..5)
  y = rand (0..5)

  # "x" counter
  10.times do |xx|

    meter = rand (0..5)
    if xx < 9
      print meter
      print "\b"
      sleep 0.08
    else print x
    end
  end

  print ' '

  # "y" counter
  10.times do |yy|

    meter = rand (0..5)
    if yy < 9
      print meter
      print "\b"
      sleep 0.08
    else print y
    end
  end

  puts

end

Put random numbers inline in Ruby


How to get list to sort by alphabetically by last name but keep first name first in javascript

Question: I'm playing around with an API that returns back a list of names. I have the list displaying but I need it to sort alphabetically by the last name but keep the first name first. Here is the code that works:
const url = 'https://swapi.co/api/species/1/';
   function fetchData(url) {
  return fetch(url).then((resp) => resp.json());
}

  function constructTableRow(data) {
    const row = document.createElement('tr');
    const { name, height, mass, hair_color } = data;
    row.appendChild(constructElement('td', name))
    row.appendChild(constructElement('td', height))
    row.appendChild(constructElement('td', mass))
    row.appendChild(constructElement('td', hair_color))
    return row;
  }

  const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];
     fetchData(url).then(data =>
     data.people.forEach(personUrl =>
     fetchData(personUrl).then(result => {
     result.name.sort()
     const row = constructTableRow(result);
     swTable.appendChild(row);
   })
  )
);

When I add result.name.sort() to the last block of code, it breaks and says:
Uncaught (in promise) TypeError: result.name.sort is not a function
    at fetchData.then.result
what's missing here?
Answer: Assuming name contains two space separated strings.
This is the minimal code I can think of, for helping you in solving your case.
function fetchData(test)
{
    return {"name": test};
}

data = {people:["foo deep", "flying bar", "come and"]};
list = [];
data.people.forEach(personUrl =>{
    list.push(fetchData(personUrl));
});
list.sort(function(a, b) {
    var a_last_name = a.name.split(" ")[1];
    var b_last_name = b.name.split(" ")[1];
    if(a_last_name < b_last_name)
        return -1;
    else if (a_last_name == b_last_name)
        return 0;
    return 1;
});

Comment: Thanks the names actually are in the JSON as name: "Luke Skywalker"
Comment: @MikeL5799, yes I have written it assuming 2 word names, you can modify it accordingly, if you need something else.
Comment: so when I add this code inside of` fetchData(url).then(data =>` it doesn't work. should this be after that instead?
Comment: I have updated it for more clarity. Can you print the result before sorting it. This will help in understanding the problem better.
Comment: thanks. That actually makes an error:`result.sort is not a function` the joys of coding lol
Comment: can you please print the `result` before calling `sort`, I'm sure, its not an array, if you are getting the above mentioned error.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/168341/discussion-between-harman786-and-mikel5799).
Answer: You can try this code to get sort by alphabetically by the last name
var sortedPeople= data.people.sort(function(a, b){
   if(a.lastNameKey  b.lastNameKey) return 1;
   return 0;
});

sortedPeople.forEach(function(element) {
     const row = constructTableRow(result);
     swTable.appendChild(row);
});


Product of binomial coefficient as a basis

Question: I am stuck with the following problem. Every polynomial of degree $d$ can be expressed as
$$
p(x) = p_d \binom{x}{d}+ p_{d-1}\binom{x}{d-1} + \cdots + p_0 \binom{x}{0}
$$

What is the representation of
  $$
\binom{x}{i} \binom{x}{j}
$$
  in such a basis?

I have no idea how to solve this...
Comment: The coefficients are the divided differences. See http://en.wikipedia.org/wiki/Newton_polynomial.
Comment: See Propositions 3.35 and 3.36 in my *Notes on the combinatorial fundamentals of algebra* ( https://www.cip.ifi.lmu.de/~grinberg/primes2015/sols.pdf ). (If the numbering changes, search for "S-junction" and scroll up a bit, or else get the frozen version from 10th January 2019: https://github.com/darijgr/detnotes/releases/tag/2019-01-10 )
Answer: There is a nice combinatorial interpretation. The product
$$\binom{x}{i}\cdot\binom{x}{j}$$
gives the number of ways in which one can select $i$ objects among $x$, then select $j$ objects among $x$. Let $I$ be the set of the elements chosen in the first instance, $J$ be the set of the elements chosen in the second one. In how many cases $I$ and $J$ are disjoint? We have to choose $i+j$ elements among $x$, then choose the elements of $I$ among the $i+j$ selected, so $I$ and $J$ are disjoint in:
$$\binom{x}{i+j}\binom{i+j}{i}$$
cases. In how many cases we have $|I\cap J|=k\leq i$?
The answer is clearly:
$$\binom{x}{i+j-k}\binom{i+j-k}{k}\binom{i+j-2k}{i-k},$$
since we have to choose the $(i+j-k)$ elements that belong to $I\cup J$, which $k$ of these belong to $I\cap J$, which $i-k$ of the remaining belong to $I$. So we have:
$$\binom{x}{i}\cdot\binom{x}{j}=\sum_{k=0}^{i}\binom{x}{i+j-k}\binom{i+j-k}{k}\binom{i+j-2k}{i-k}.$$
Answer: In reply to this post, which has been closed as being a duplicate
of the present one, let me submit an alternative formulation, which looks more symmetrical as requested in the mentioned post.
Starting from
$$
\eqalign{
  & x^{\,\underline {\,n\,} } x^{\,\underline {\,m\,} }  = \sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,n} \right)}
  {\left( { - 1} \right)^{\,n - k} \left[ \matrix{  n \cr   k \cr}  \right]x^{\,k} }
  \sum\limits_{\left( {0\, \le } \right)\,j\,\left( { \le \,m} \right)}
  {\left( { - 1} \right)^{\,m - j} \left[ \matrix{  m \cr   j \cr}  \right]x^{\,j} }  =   \cr
  &  = \left( { - 1} \right)^{\,n + m} \sum\limits_{\left( {0\, \le } \right)\,q\,\left( { \le \,n + m} \right)}
  {\left( {\sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,\min \left( {q,n} \right)} \right)}
  {\left( { - 1} \right)^{\,q} \left[ \matrix{  n \cr   k \cr}  \right]
  \left[ \matrix{  m \cr   q - k \cr}  \right]} } \right)x^{\,q} }  =   \cr
  &  = \left( { - 1} \right)^{\,n + m} \sum\limits_{\left( {0\, \le } \right)\,q\,\left( { \le \,n + m} \right)}
  {\left( {\sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,\min \left( {q,n} \right)} \right)}
  {\left( { - 1} \right)^{\,q} \left[ \matrix{  n \cr   k \cr}  \right]
  \left[ \matrix{  m \cr   q - k \cr}  \right]} } \right)
  \sum\limits_{\left( {0\, \le } \right)\,s\,\left( { \le \,q} \right)}
  {\left\{ \matrix{  q \cr   s \cr}  \right\}\,x^{\,\underline {\,s\,} } } }  =   \cr
  &  = \left( { - 1} \right)^{\,n + m} \sum\limits_{\left( {0\, \le } \right)\,s\,\left( { \le \,m + n} \right)}
  {\left( {\sum\limits_{\left( {s\, \le } \right)\,q\,\left( { \le \,n + m} \right)}
  {\sum\limits_{\left( {0\, \le } \right)\,k\,\left( { \le \,\min \left( {q,n} \right)} \right)}
  {\left( { - 1} \right)^{\,q} \left[ \matrix{  n \cr   k \cr}  \right]
  \left[ \matrix{  m \cr  q - k \cr}  \right]
  \left\{ \matrix{  q \cr   s \cr}  \right\}} } } \right)x^{\,\underline {\,s\,} } }  =   \cr
  &  = \sum\limits_{\left( {0\, \le } \right)\,s\,\left( { \le \,m + n} \right)} {F(n,m,s)\,x^{\,\underline {\,s\,} } }  \cr}
$$
and putting that into matricial form I could deduce that
$$ \bbox[lightyellow] {
F(n,m,s) = \left( {n + m - s} \right)!\binom{  m }{   s - n } \binom{  n}{   s - m }
\quad \left| \matrix{  \;0 \le n,m,s \in \mathbb Z \hfill \cr   \;s \le n + m \hfill \cr}  \right.
 }$$
In fact, that is proved by being
$$
\eqalign{
  & \sum\limits_{\left( {0\, \le } \right)\,s\, \le \,m + n} {\left( {n + m - s} \right)!
 \binom{  m }{   s - n } \binom{  n }{  s - m }\,x^{\,\underline {\,s\,} }}  = \cr
  &  = \sum\limits_{\left( {0\, \le } \right)\,s\, \le \,m + n}
 {\left( {n + m - s} \right)!
 \binom{  m }{  n + m - s } \binom{  n }{  s - m }\,
 x^{\,\underline {\,m + \left( {s - m} \right)\,} } } =    \cr
  &  = \sum\limits_{\left( {0\, \le } \right)\,s\, \le \,m + n}
 {\binom{  n}{   s - m } m^{\,\underline {\,n - \left( {s - m} \right)\,} } \,
 x^{\,\underline {\,m\,} } \left( {x - m} \right)^{\,\underline {\,s - m\,} } }  =    \cr
  &  = x^{\,\underline {\,m\,} } \sum\limits_{\left( {0\, \le } \right)\,k\, \le \,n}
 {\binom{  n }{   k } m^{\,\underline {\,n - k\,} } \,\left( {x - m} \right)^{\,\underline {\,k\,} } }  =    \cr
  &  = x^{\,\underline {\,m\,} } x^{\,\underline {\,n\,} }   \cr}
$$
where:
 (1st step) binomial symmetry;
 (2nd) reducing the first binomial and splitting the falling factorial;
 (3rd) changing summation index;
 (4th) binomial expansion of falling factorial.
$F(n,m,s)$ is called "connection  coefficient" in this Wikipedia article
The conversion to the product of binomials follows immediately.


Regular expression exclude µ from [\W_]

Question: I have to replace all not alphanumeric character ("_" included) and i had success with :
<code>.replaceAll("[\\W_]", "%");
</code>
Now I need to exclude from that regex the greek char especially µ .
I had no success with "^", how can i do that?
Thanks a lot
Comment: [^a-zA-Z0-9\µ] I use that it should be good
Answer: You could try this:
<code>[^a-zA-Z0-9-()/\s\p{IsGreekandCoptic}]
</code>

Regular expression exclude µ from [\W_]


Do 1.$\sum_{n=2}^{\infty} \frac{\cos{n}}{n^\frac{2}{3} + (-1)^n}$ 2. $\sum_{n=1}^\infty(e^{\cos n/n}−\cos\frac{1}n)$ converge?

Question: Does
$$ 1. \hspace{8mm} \sum_{n=2}^{\infty} \frac{\cos{n}}{n^\frac{2}{3} + (-1)^n} $$
and
$$ 2. \hspace{8mm} \sum_{n=1}^{\infty} \left(e^\frac{\cos{n}}{n} - \cos\frac{1}{n}\right) $$
converge? In $\sum_{n=2}^{\infty} \frac{\cos{n}}{n^\frac{2}{3} + (-1)^n}$,  I allocate two sequences of 1. cos n is bounded and  $\frac{1}{n^\frac{2}{3} + (-1)^n}$, where $(-1)^n$ irrelevant next to $n^\frac{2}{3}$ for large and, so I get sequence $\frac{1}{n^\frac{2}{3}}$, this sequence is monotonically decreases to $0$.
On the basis of Dirichlet, the series converges. Is it so?
But I don't have any ideas about the second number..
Comment: Note that for $n\to \infty$, $(\cos n)/n \to 0$. Hint: Taylor expansion
Answer: For the first series, even though $(-1)^n$ is neglible compared with $n^{2/3}$ as $n$ gets large, the monotone hypothesis of the Dirichlet test is not met and it cannot be applied directly.
However, we have
$$\sum_{n=2}^m \frac{\cos{n}}{n^\frac{2}{3} + (-1)^n}= \sum_{n=2}^m \frac{\cos{n}}{n^\frac{2}{3} + (-1)^n}\frac{n^\frac{2}{3} - (-1)^n}{n^\frac{2}{3} - (-1)^n} = \underbrace{\sum_{n=2}^m \frac{n^{\frac{2}{3}}\cos{n}}{n^\frac{4}{3} -1}}_{A_m}- \underbrace{\sum_{n=2}^m \frac{(-1)^n\cos{n}}{n^\frac{4}{3} -1}}_{B_m}$$
Now we can apply the Dirichlet test to show that the sequences of partial sums $A_m$ and $B_m$ on the RHS converges.
To handle $B_m$, note that $(-1)^n \cos n = \cos n\pi\cos n = \frac{1}{2}[\cos (n(\pi+1)) + \cos (n(\pi-1))]$, and use the fact that $\sum_{n=1}^m \cos nx$ is bounded for all $m$ and fixed $x$.
Answer: For the first series it would be desirable to replace $n^{2/3}+(-1)^n$ by $n^{2/3}.$ To this end observe that $${\cos n\over  n^{2/3}+(-1)^n}={\cos n\over  n^{2/3}}+{(-1)^{n+1}\cos n\over [n^{2/3}+(-1)^n]n^{2/3}}$$ The first terms are summable by the Dirichlet test. The second terms are absolutely summable as the denominator is greater than  $n^{4/3}/2$ for $n\ge 3.$
For the second series we have $$e^{\cos n/n}-\cos(1/n)\\ = \left [e^{\cos n/n}-1-{\cos n\over n}\right ]\\ +[1-\cos(1/n)]+{\cos n\over n}$$ The absolute value of the term in the first square brackets is less than $1/n^2$ because $$|e^x-1-x|\le x^2$$ The term in the second square bracket is equal $2\sin^2(1/n).$ The last terms are summable by the Dirichlet test.
Answer: For the first one you have
$$\frac{\cos(n)}{n^{2/3}+(-1)^n} = \frac{\cos(n)}{n^{4/3}-1}\,\left(n^{2/3}-(-1)^n\right) = \frac{\cos(n)}{n^{2/3}-n^{-2/3}} - \frac{(-1)^n}{n^{4/3}-1}$$
and so the first term converges by the Dirichlet-test, since $\left(n^{2/3}-n^{-2/3}\right)^{-1}$ is decreasing. The second term converges absolutely.
For the second you could argue as follows:
$$\sum_{n=1}^{\infty} \left(e^\frac{\cos{n}}{n} - \cos\frac{1}{n}\right) = \sum_{n=1}^\infty \left(1 + \frac{\cos(n)}{n} + O(1/n^2) - 1 - O(1/n^2) \right) \\= \sum_{n=1}^\infty \left( \frac{\cos(n)}{n} + O(1/n^2) \right)$$
The O-term converges clearly, while the first term is a convergent Fourier-series.


$Z$ is a random variable that follows a standard normal distribution. Is $X = Z^2$ independent from $Y = Z^3$?

Question: I think the title is pretty clear about the problem. Should I try to find the joint probability of $X$ and $Y$ and decide if $\, f_{X,Y}(x,y) = f_X(x) \cdot f_Y(y)$? If so, how am I going to find a joint distribution like this? Or is there some shortcut to prove it?
Answer: $EXY^{2} \neq EXEY^{2}$ so $X$ and $Y^{2}$ are not independent. This implies that $X$ and $Y$ are not independent. [Use a table of moments of $Z$ to see that $EXY^{2} \neq EXEY^{2}$. You can also argue analytically using that fact that 6-th moment is strictly smaller than the 8th moment].  Alternative proof: if $X$ and $Y$ are independent so are $X^{3}$ and $Y^{2}$. This makes $Z^{6}$ independent of itself which implies $Z^{6}$ is a constant random variable. This is obviously false.
Answer: Because both $X,Y$ depend on a single random variable $Z$, intuitively $X,Y$ are not independent. To prove this, sketch the parametric curve $(t^2,t^3)$ over all real $t$:

(This is the semicubical parabola $y^2=x^3$.) The joint pdf is non-zero at some $(x,y)$ iff that point lies on this curve. If $X,Y$ were independent, any vertical line (pdf of $Y$ conditioned on constant $X$) would be a multiple of any other line, but taking the vertical lines $X=1$ and $X=2$ clearly shows that they are not multiples of each other, so $X,Y$ are dependent.


$P$ vs $NP$ characterization confusion

Question: I know that $P \subseteq NP$, but for a problem in $P$, e.g. MST in a graph, is it a correct statement to say that:
The MST problem belongs in $NP-\text{Class}$.
(I mean, i think it is correct, but could someone classify that as wrong because he would expect $P$ instead of $NP$?)
Comment: Yes. Given any problem in $\mathsf{P}$, it is also correct to say that problem is in $\mathsf{NP}$. This is somewhat akin to saying that the function $f(n) = 2n$ is $O(n^2)$. It's correct, but not tight.
Answer: $P$ is the class of problems which can be solved by a deterministic Turing machine in polynomial time and $NP$ is the class of problems which can be solved by a non-deterministic Turing machine in polynomial time. Since every deterministic turing maching can be simulated by a non-deterministic Turing machine then you have the corresponding inclusion. You may view the deterministic Turing machine as a branch in the tree of computations given by the non-deterministic Turing machine.

$P$ vs $NP$ characterization confusion


Book recommendation for a third course in abstract algebra

Question: I completed an abstract algebra course on groups, and a second course on rings and fields a few semesters back and I want to take a third course next semester. For the previous two courses, I followed mainly I. N. Herstein and J. A. Gallian books (and also looked into Dummit & Foote and J. Rotman, but not in detail).
For the third course, I'm a little confused and I need some book recommendations. The syllabus covers these topics :

Rings, ideals, quotient rings, homomorphisms and isomorphisms, prime ideals, maximal ideals, integral domains, field of fractions. (recap)
Modules, submodules, quotient modules, morphisms, tensor product, flat modules.
Chain condition.
Completion, localization, valuation.
Regularity, introduction to dimension theory.
Comment: If there is a syllabus, and you are taking the course, then why exactly do you need book recommendations? Why can't you just ask the professor? Or just find whatever book interests you, if it will only be a supplement for the course?
Comment: What have you studied in Algebra 2 (and 1)? Algebra 3 looks like a basic introduction to commutative algebra, so you should look for books on commutative algebra. Big names are Atiyah-Macdonald, Eisenbud, Matsumura and e.g. the notes by Gathmann on Commutative Algebra are also excellent (as are all of his notes). All of these topics are covered in commutative algebra books.
Comment: @MorganRodgers this course will be done online and no regular classes due to the pandemic, so I have to rely mostly on self-study. And also I want to start early. I just wanted to know if anyone here have studied these topics and can help me in selecting a good book.
Comment: Most of these topics are in Dummit & Foote. Lang would fill in any gaps. The two books by Knapp would be an alternate that might be more approachable than Lang, depending on your level. But it will be pretty specialized to find a single book that covered all of these exact topics. I would reach out to your professor, it can be good to get in contact and let them know you are interested.
Comment: The terms "Algebra 1, 2, and 3" are localized course titles, and not universally understood terms with any mathematical meaning.  I have edited your question to make the language a little more universal.
Comment: @XanderHenderson Thankyou for your edit.
Comment: See https://math.stackexchange.com/a/1527485/589
Answer: Dummit and Foote will serve you in good stead for a long time in algebra, although no book is certainly perfect. With the exception of their treatment of tensor products which I am not a fan of, I think the rest of their explanations are quite nice and good for self studying. Ultimately, assuming cost is not an object (or if you are getting these from a library or libgen) it is helpful to have a few different books available so you can look to a different exposition of a topic if you get stuck. Having multiple books will also help expose you to a greater variety of notation, which while confusing at first will be helpful in the long run.


Linear first order PDE $u_x+u_t=u$ with the method of characteristics

Question: I miss something so that I can understand how my teacher finds the solution. I will write the exercise as it is written first.
$$u_x+u_t=u, x\in \mathbb{R}, t>0$$ $$ u(x,0)=\cos x$$
Then I have:
$$\frac{\partial x(s)}{\partial s}=1, x(0)=x_0 $$
$$\frac{\partial t(s)}{\partial s}=1, t(0)=t_0 $$
$$\frac{\partial z(s)}{\partial s}=z, z(0)=u(x_0,t_0) $$
I get
$$\frac{\partial t}{\partial x}=\frac{\partial t}{\partial s}\frac{\partial s}{\partial x}=1 \Rightarrow  t-x=c, t(x_0)=t_0$$
$$\frac{\partial z}{\partial x}=\frac{\partial z}{\partial s}\frac{\partial s}{\partial x}=z\Rightarrow z(x)c e^x$$
We conclude that $t-x$ is constant for all $s$, so $t-x=t_0-x_0$ and from initial conditions
$ z(x_0-t_0)=u(x_0-t_0,0)=\cos(x_0-t_0)$ and $z(x_0-t_0)=ce^{x_0-t_0}$ (I don't understand how I got the first equation)
So $z(x_0)=ce^{x_0}=e^{x_0-t_0}\cos(x_0-t_0)e^{x_0}=\cos(x_0-t_0)e^{t_0} \Rightarrow u(x_0,t_0)=\cos(x_0-t_0)e^{t_0}$ which means that $u(x,t)=\cos(x-t)e^{t}, x \in \mathbb{R}, t>0$
This is my teacher's solution. There is one other example, before this, that explains the method of characteristics which I think I have unsterstood (it's the linear transport equation). From research on the internet and some books I found, I got the idea that $u$ (any book I found doesn't explain why) is constant for $(x,t)$ belonging to the characteristic curve. Well I haven't yet understood why. My teacher says later in her notes that with the characteristics we create the surface of the solution (little-by-little for every value).  I found a video and some posts here like this that explain the method but in the examples $\frac{\partial z}{\partial s}=0$ and I can't see how to manage different and more complicates cases. It seems to me that some steps of the solution are missing and I have nowhere found the ideas. In the link above the steps are more clear but I don't understand why we supposed that $s=t$. I just need some explanation around the steps and the thinking I have to do every time (for linear first order PDE generally)and how we thought of  using $ x_0-t_0$ in $z(x_0-t_0)$. I think that everything else has been understood. Any explanation is very welcome because I am trying to understand this exercise since yesterday.
Comment: It's not true in your case that $u$ is constant along characteristics – after all, it's governed by the ODE $\partial z/\partial s = z$, not $\partial z/\partial s=0$.
Answer: $$u_x+u_t=u$$
Charpit-Lagrange characteristic ODEs :
$$\frac{dx}{1}=\frac{dt}{1}=\frac{du}{u}=ds$$
This is equivalent to the three equations that you correctly wrote.
A first characteristic equation comes from solving $\frac{dx}{1}=\frac{dt}{1}$ :
$$x-t=c_1$$
A second characteristic equation comes from solving $\frac{dx}{1}=\frac{du}{u}$ :
$$u\:e^{-x}=c_2$$
The general solution of the PDE expressed on implicit form $c_2=F(c_1)$ is :
$$u\:e^{-x}=F(x-t)$$
$F$ is an arbitrary function (to be determined later according to a specified condition).
$$\boxed{u(x,t)=e^xF(x-t)}$$
Condition : $u(x,0)=\cos(x)=e^xF(x)$
$$F(x)=e^{-x}\cos(x)$$
So the function $F(x)$ is determined. We put it into the above general solution where the argument is not $x$ but is $(x-t)$. Thus $F(x-t)=e^{-(x-t)}\cos(x-t)$ :
$$u(x,t)=e^xe^{-(x-t)}\cos(x-t)$$
$$u(x,t)=e^t\cos(x-t)$$
Comment: Yes. No need for mimic, just apply : https://en.wikipedia.org/wiki/Method_of_characteristics
Comment: The solutions that you and @EditPiAf game me are quite simpler (although I'm not sure if it is ok to use them in my exams). Is it possible to mimic them for first order quasilinear PDE's? Just a yes or no answer.
Answer: I think that your teacher's solution is a bit confusing. So let us apply the method of characteristics in parametric form (see the example in §2 of the Wikipedia article):

$\frac{d x}{d s} = 1$, letting $x(0) = x_0$ we know $x(s) = s + x_0$
$\frac{d t}{d s} = 1$, letting $t(0) = 0$ we know $t(s) = s$
$\frac{d z}{d s} = z$, letting $z(0) = \cos x_0$ we know $z(s) = \cos(x_0) e^s$

This system simply expresses the Cauchy problem for the PDE $u_x + u_t = u$ in differential form $$
\frac{d z}{d s} = u_x \underbrace{\frac{d x}{d s}}_{\equiv 1} + u_t \underbrace{\frac{d t}{d s}}_{\equiv 1} = \underbrace{u}_{\equiv z} \, ,
$$
where we have introduced the parametrization $z(s) = u(x(s), t(s))$ of the solution (${d z}/{d s}$ denotes a total derivative). The boundary condition $u(x_0, 0) = \cos x_0$ is enforced at $s=0$ by setting
$$
x(0) = x_0 ,\qquad
t(0) = 0 ,\qquad
z(0) = \cos x_0 .
$$ This condition represents the set of points where $u$ is already known, i.e. where characteristic curves $s \mapsto (x(s), t(s))$ actually 'start'. Here we note that $z = \cos(x_0) e^s$ is not constant along the characteristic curves: it increases exponentially with the parameter $s$. To express $u$ in terms of the coordinates $x, t$, we then use the first two equations above to eliminate $x_0=x-t$ and $s=t$: $$
u(x,t) = \cos(x-t)\, e^t .
$$
See the answer by @JJacquelin for the parametrization invariant form (Lagrange-Charpit system).
Comment: @ΝικολέταΣεβαστού We can do the same thing by setting the boundary at an arbitrary value $s=s_0$ along which $z(s_0) = \cos x_0$ and $(x(s_0), t(s_0)) = (x_0, 0)$. Doing so, we have $$
x = s-s_0+x_0, \qquad t = s-s_0, \qquad z = \cos(x_0) e^{s-s0}
$$
which yields the exact same final expression.
Comment: Why $t(0)=0$ and not $t_0$? And how do I get so quickly that $z(0)=\cos (x_0)$?
Comment: The explanation that I gave is right? I am still not sure. I understand yours. @EditPiAf
Comment: I was talking about the answer below. Sorry I wasn't clear. The one that I wrote.
Answer: Well I think that's what is missing.
We want the charactreristic to "meet" the boundary of the set $\{(x,t):x \in \mathbb{R}, t>0\}$ which is the $ x$- axis. So when we find the characteristic $t-x=t_0-x_0$ (here) we enforce $t=0$ and we find the point where they meet, which is $(x_0-t_0,0)$. This point is used in the initial condition $u(x,0)=\cos x$, because $z(s)=u(x(s),t(s)) \Rightarrow z(x)=u(x,t(x))$ (we usually omit the symbol that makes it possible to distinguish the new function that has $x$). We have
$$ z(x_0-t_0)=u(x_0-t_0,0)(=\cos (x_0-t_0))$$
We always want to find a quantity that has our variables (here $t,x$) and doesn't have $s$. So when we solve the ODEs we try to make $s$ to vanish from our equations. The way is up to us.
EDIT: Just for any future reader that struggles. On the internet there are some very good lecture notes for first order PDE's from Stanford university here.
Comment: The fact that $t-x = t_0 - x_0$ is constant along any characteristic curve follows from $\frac{d (t-x)}{d s} = 0$. That being said, this condition is not sufficient to complete the resolution, and the boundary condition at $t=0$ needs to be enforced. This can be done by noting that $u e^{-t}$ is constant too.


Why isn't this while condition reevaluated?

Question: I have two while conditions, one inside the other, with booleans to control them. Basically, one is for terminating a share and the other is to listen for a connection. A user can select to disable a share, and in this case, the server stops listening but it won't terminate. If a user selects to terminate then both booleans are set to false and the cycle ends.
This is my code:
        public void run() {
            while (!terminate) {
                while (listening) {
                    try {
                        // accept connection -> create a new thread for each client
                        ClientServerShareInstance clientServerShareInstance = new ClientServerShareInstance(serverSocket.accept(), ui);
                        Thread clientServerThread = new Thread(clientServerShareInstance);
                        clientSockets.add(clientServerShareInstance);
                        connectedClients++;
                        clientServerThread.start();
                    } catch (IOException ex) {
                    }
                }
            }
        }

        public void closeAllClientConnections() {
            for (Iterator it = clientSockets.iterator(); it.hasNext();) {
                ClientServerShareInstance clientServerShareInstance = (ClientServerShareInstance) it.next();
                clientServerShareInstance.closeAllConnections();
                it.remove();
            }
            try {
                this.serverSocket.close();
            } catch (IOException ex) {}
            this.setActive(false);
            this.connectedClients = 0;
        }

        public void openConnection() {
            try {
                serverSocket = new ServerSocket(portNumber, 0, Inet4Address.getLocalHost());
                setActive(true);
            } catch (IOException ex) {}
        }
    }

The closeAllClientConnections() method disables a share (does not terminate it), and the openConnection() reenables that share.
The problem is, if I disable a share, it should just loop the terminate while cicle indefinitely, testing the value of listening. When I set listening to true, it should re-enter that second while loop and start listening again, because I do open the server socket (although it's not related to that, I'm just saying it has to be initialized again because I close it when I disable the share). However, after disabling, it never renters the listening loop, even when openConnection() is called.
Anyone know what's wrong here?
Comment: `setActive(...)` sets the value of `listening`?
Comment: No, they're just declared as regular private booleans inside my class. I didn't use volatile because I thought objects were shared between multiple threads and I didn't require locks because it's not a complex operation where multiple threads are 'fighting' for access at the same time.
Comment: @Gray Yes, it does. It's just a setter for that variable.
Comment: I've moved my comments to an answer.
Comment: How about formatting your code properly...
Comment: @Bohemian: It's formatted properly. It's just missing the topmost method's head.
Comment: @Bohemian Exactly, it's inside the run() method.
Answer: There's not enough code shown to show any errors.  But here are some comments that might help.

Both the shutdown and listening booleans need to be volatile. Any fields shared between threads need to be somehow synchronized otherwise changes to their values will not be seen by other threads.
serverSocket will also need to be volatile since it seems to be created by the caller of openConnection() but consumed in the while loop. You might consider just setting active to the true in openConnection() and have serverSocket managed entirely by the accept thread.
clientSockets looks to be a collection.  That will need to be a synchronized connection since, again, it looks like it is accessed by multiple threads.  Again, a better pattern would be for the closeAllClientConnections()  call to just set a boolean and the thread itself would do the closing.  That removes any race conditions around using the collections, etc..
Looks to be that if you are ! terminating that your accept thread will spin.  At the very least you should put some Thread.sleep(100) or something to slow it down.   A wait/notify would even be better.

It is important to realize that it is not just about what happens "at the same time" in a threaded program.  It is also about memory caching. The accept thread could have added something to the clientSockets ArrayList1 a minute ago and another thread may not see those changes if the list is not synchronized somehow. Even worse is the prospect that certain portions of the ArrayList may have been updated in memory but not others which might cause an exception.  To get a synchronized collection, you should create your ArrayList like:
List<...> clientSockets = Collections.synchronizedList(new ArrayList<...>());

Sounds like you should read some of the documentation about why synchronization is necessary:

http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
Comment: @Lovato Please take 30 minutes at least and read the link I posted.  It is critical otherwise you are writing buggy code that may work sometimes but will fail spectacularly others.
Comment: serverSocket is created there, but it's mostly a re-instantiation, because it initializes first in the run() method (upon first creating that share).
Comment: Reinstantiation still needs to be synchronized @Lovato.  Any changes to any fields need to be synchronized if they are changed by multiple threads.  Also, there is a lot of complexity around constructor optimizations that may cause the socket to be constructed but not fully initialized.  You should avoid constructing it in one thread and consuming it in another if you can.
Comment: clientSockets is a ArrayList of client sockets. When I disable a share, I have to close any clients connected to that share, so I store them in a collection, call the closeAllConnections() and that closes all connections for each client and then remove them from the list.
Comment: I understand this @Lovato but because the accept thread is also adding to the `ArrayList`, any time you use the list you need to have it be in a `synchronized` block.  I've added some required reading to my answer.
Comment: Thank you, kind sir. This solved my issue, using `volatile` fixed that. The `ArrayList` is a public static collection, which other threads need to access to perform remove operations (only this thread adds anything). However, only one thread at a time can ever add or remove an object (because it's a JTable, and a button that provides that enable/disabling feature).
Comment: And yes, when I disable a share it just does a infinite loop, which is why I had the idea of using a `Semaphore` with initial value 0 if `listening` is false, so that it blocks immediately and waits until the openConnection() releases it.
Comment: Dude.  You aren't getting it.  It is not _just_ about what happens at the same time, it is about memory caching.  The accept thread could have added something to the `ArrayList` a minute ago and another thread may not see it.  Even worse is the prospect that certain portions of the `ArrayList` are updated but not others which might cause an exception.  You should create your `ArrayList` like: Collections.synchronizedList(new ArrayList<...>());`


How does graph classification work with graph neural networks

Question: I am reading the paper The Graph Neural Network Model by Scarselli et al. I understand how node classification works. I am having trouble understanding how graph classification works however. In particular, in the section titled The Learning algorithm, the authors mention that

Learning in GNNs consists of estimating the parameter such that w
  approximates the data in the learning data set

where qi is the number of supervised nodes in Gi. For graph focused
  tasks, one special node is used for the target (qi = 1 holds), whereas for
  node-focused tasks, in principle, the supervision can be performed on
  every node.

The node focused task approach makes sense to me; you would essentially compare the ground truth to each output of the "local output function" for each node, and backprop accordingly. However, based on the above description, I do not understand what you would do to classify the graph as a whole, given its label. What do they mean by "one special node is used for the target (qi = 1 holds)"? Why are they talking about a "special node"? Why is there no mention of the graph's label? Isn't that what we want to predict?
EDIT:
After reading through the entire paper, and specifically looking at the Mutagenesis example, I got a better understanding of how graph classification works (as described in this paper at least). However, my understanding is still not complete. I will explain what I understand, and raise a followup question below.
As the text above suggests, a particular node in the graph is chosen (I believe this can be done at random), and it will be the only node in the graph that is "supervised." All other nodes will be unsupervised (so we will not make any predictions on those nodes). We choose the local output function in such a way as to have it output a number between -1 and 1 (although I'm unsure as to whether or not you could pick a function that instead outputs a number between 0 and 1. I believe you can, and it's just a matter of what activation function you would like to choose i.e sigmoid vs tanh in this example). If the output is < 0, we predict the graph has label -1, and 1 otherwise.
Now we just do what we did with node prediction, except we only backpropagate on this single node that we chose.
This, however, raised a followup question for me. If you are training on multiple graphs (for graph classification), each of which has a different connectivity (which is usually the case, and is the case in the Mutagenesis example), how do you backpropagate? Each graph (in this case, molecule) represents a different neural network ...
Answer: I am aware of two typical strategies for outputting a "graph-wide" prediction.

Augment every graph with a special "root" node, and add an edge between the root and every other vertex of the graph. Use this as your "chosen" vertex.
Have every node output a prediction (typically logits, but could do direct probabilities as well), and average across all nodes in the graph.

I've not seen anyone try the "random node" approach but it sounds like a more stochastic form of (2).
I don't quite understand your question about backpropagation, as the algorithm doesn't require that the computation graph be fixed.
Answer: https://tkipf.github.io/graph-convolutional-networks/
I think one of the more easier GNNs to understand is the.
The data is separated into a adjacency and one feature matrix. Obviously, the adjacency matrix differs from Graph to Graph to due different number of nodes in the respective Graph. However, the number of features that are attributed to each node remain the the same for each Graph. And this GNN can work for different Graph Sizes.
For Graph Classification their is also the strategy of applying an invariant pooling function like the sum or mean over each feature. And the result will be a 1xf vector


Joomla 1.5 with Postgresql 8.4

Question: can anybody guide me to get to work Joomla 1.5.X with a postgres 8.4 database ?
Thanks
Answer: Postgresql is not supported by Joomla.
Answer: Joomla 1.5 has no support for PostgreSQl, only MySQL.
PostgreSQL support has been started since Joomla 3.0.
This may help.

Joomla 1.5 with Postgresql 8.4


How to make ossec send only one email for an alert?

Question: I installed ossec with local installation and is working fine. It is sending email alerts fine but seems to be sending the same email over and over for an alert.
For example, an alert email is sent for
Rule: 1002 fired (level 2) -> "Unknown problem somewhere in the system."
What I am trying to set up is to send email about this only once. Currently, it keeps sending email about this alert every 6 or 7 minutes.
The issue seems to be that rule 1002 will catch a bunch of cases and getting an alert is fine. But getting the same alert 100 times doesn't seem to make sense. Anyway to fix this?
Answer: I believe you can use the <email_maxperhour> directive globally in ossec.conf.  So if you set the value to 1, on the top of the hour it will group all the queued emails and send it together as one.
I'm not sure if that suits your need but it's an alternative.
Note, you can not apply this directive per rule, e.g. local_rules.xml and rule 1002 in your case.


Are there optimization methods for k-NN parameter $k$?

Question: Currently I am just go through from the min to the max, and determine $k$ by the performance. I am wondering if there's optimization approaches for selecting $k$? I am aware of there's question in this site asking for a practical method for selecting $k$, but I would like to know if there's any optimization strategy works for k-NN? My objective is make it more time efficient.
When I combine k-NN with another approach (with one parameter: ki) for a specific application, I found the objective function seems not smooth with respect to the two parameters: $ki$ and $item Neighborhood size$ ($k$). (See the pic)
How about the following method: I assume there are local maxima values of $k$.
In a case where I have the possible values of k between  [1, 1000].

I make a step size $s=$ 20, and then there will be 50 first-round $k$ values = {1, 20, 40,...,1000}. I evaluate them and get the results.
for each first-round $k$ values, I produce 50 second-round $k$ values by adding $s/2==10$. Then I will have second-round $k$ values={$10,30,50,...,900$}. Then I evaluate them and get the results.
I think in this way I can get a rough outline of the relation between performance and parameter $k$, and then next I can determine a most wanted range of $k$, then I can use a much smaller step size $s_2$ to continue the aforementioned process.

Does this method fall into the category of Monte Carlo methods?
Answer: You can use either cross validation(k-fold cross-validation) or brute force using methods such as grid search
See this paper:http://www.cs.cmu.edu/~rahuls/pub/icml2000-rahuls.pdf
and this one on grid search for details: http://www.jmlr.org/papers/volume13/bergstra12a/bergstra12a.pdf


Duplicate fields/values from JSON object array in php

Question: I am working on a website in which I want to remove duplicate fields from JSON object array.
The JSON object array which I have is:
"rental_rates": [{
    "rate_id": 170,
    "uuid": "a3a14d20-63d1-11e8-b047-89e5d3a9513d",
    "owner_id": 38,
    "item_id": 394,
    "name": "daily",
    "term": "daily",
    "currency": "dollars",
    "rate": "56.00",
    "min_charge": "56.00",
    "created_at": "2018-05-30 06:20:43",
    "updated_at": "2018-05-30 06:21:07"
}, {
    "rate_id": 172,
    "uuid": "a3a1c500-63d1-11e8-8740-8925bbb8ada8",
    "owner_id": 38,
    "item_id": 394,
    "name": "weekly",
    "term": "weekly",
    "currency": "dollars",
    "rate": "677.00",
    "min_charge": "56.00",
    "created_at": "2018-05-30 06:21:00",
    "updated_at": "2018-05-30 06:21:07"
}],

The code which I am using in order to pull fields/values form JSON object array is:
foreach ($data['item']->rental_rates as $rental_rate)
{
echo ''."minimum".'';
echo '$'.floatval($rental_rate->min_charge).'
';

}

The above code is pulling the following data and I want only one to be shown.
minimum $56
minimum $56

Problem Statement:
I am wondering what changes I need to make in the foreach loop so it pull only one field and value like this,
minimum $56

Answer: Two ways. Store what has already been displayed and check for it:
$shown = array();
foreach ($data['item']->rental_rates as $rental_rate)
{
    if(!in_array($rental_rate->min_charge, $shown)) {
        $shown[] = $rental_rate->min_charge;
        echo ''."minimum".'';
        echo '$'.floatval($rental_rate->min_charge).'
';
    }
}

Or create an array indexed by the min_value so there will only ever be one (only works on objects as of PHP >= 7.0.0):
$rates = array_column($data['item']->rental_rates, null, 'min_charge');
foreach $rates as $rental_rate)
{
    echo ''."minimum".'';
    echo '$'.floatval($rental_rate->min_charge).'
';
}

For PHP < 7.0.0, decode the JSON as an array passing true as the second argument and use $data['item']['rental_rates'] and $rental_rate['min_charge'] in the code above instead.


Is there a way to sort by taxonomy?

Question: On the the main content page: mysite.com/admin/content we are allowed to sort by a few criteria. Sort by content type, published date etc. but is there a way to sort by taxonomy? It seems like previous versions of drupal could do this. But not so in 7? I know you can create a view to handle this, but i am curious if its possible to accomplish the functionality via the content admin page.
Answer: There's no way to do it with the default content admin page, short of writing code to alter the form. Vocabularies aren't linked exclusively to nodes in Drupal 7, they can be linked to any type of entity using the field system, so having this functionality wouldn't make sense by default any more.
Creating a View is definitely the right way to go; personally I'd install the Administration Views module which replaces (amongst others) the default content admin page with a View.
The module page says it provides support for filtering by vocabulary out of the box, but even if it doesn't provide sorting you could easily just tweak the View to your own requirements.
Comment: Right on, thats what i thought. And thanks for the module tip. i'll check it out.

Is there a way to sort by taxonomy?


Imagem em listview com SqlLite / Drawable

Question: Tenho um App que efetua uma busca em telefones de empresas em um banco de dados SQLLite, .
Está funcionando normalmente, mas preciso inserir imagem em algumas dessas empresas.
O campo do banco de dados estaria somente o nome da imagem e a imagem estaria na pasta res/drawable...
Não vou utilizar campo blob.
Como faço pra mostrar essa imagem em imageview no meu listview de resultados. Veja meu código abaixo
String mostraTexto = params.getString("palavrachave");  // parametro para busca

    Cursor cursor = db.rawQuery("select nome,liberado,imagem,cidade,CIDADES._id,telefone,ddd,tipo,cid_nome,TELEFONES._id from TELEFONES INNER JOIN CIDADES ON TELEFONES.cidade = CIDADES._id where telefone like '%" + mostraTexto + "%' or nome like '%" + mostraTexto + "%' order by cid_nome,nome", null);

    String[] from = {"nome","telefone","cid_nome","ddd"};
    int[] to = {R.id.txt_nome, R.id.txt_telefone, R.id.txt_cidade, R.id.txt_ddd, R.dr};

    //vamos contas os resultados
    int id[]=new int[cursor.getCount()];
    if (cursor.getCount() < 1)
    {
     AlertDialog.Builder dialogo = new AlertDialog.Builder(Resultado.this);
     dialogo.setTitle("Aviso");
     dialogo.setMessage("Nenhuma resultado na sua pesquisa!");
     dialogo.setNeutralButton("Ok", null);
     dialogo.show();
    }
    if (cursor.getCount() > 0)
    {

    android.support.v4.widget.SimpleCursorAdapter ad =
            new android.support.v4.widget.SimpleCursorAdapter(
                    getBaseContext(),R.layout.buscar_ltw,cursor, from, to, 0);

    ListView ltw_listar = (ListView)findViewById(R.id.ltw_listar);

        ltw_listar.setAdapter(ad);

Comment: O nome da imagem é o id do recurso ou o "filename"? Não poderia guardar no banco o id ou a URI com o caminho absoluto? Porque o SimpleCursorAdapter trata o valor da coluna como o id do drawable nesse pasta e ou a URI.
Comment: Wakim
Recuperar o ID da imagem eu consigo tranquilamente. Só não estou conseguindo enviar para o campo ImageView presente no ListWiew.
Analise o meu código, onde eu poderia e como colocar o comando para enviar a imagem para o imageView.
Answer: use esse trecho para pegar o id da imagem
   String mDrawableName = "myImageName";
int id = mContext.getResources().getIdentifier(mDrawableName , "drawable", mContext.getPackageName());

e para setar a image é assim
imageview.setImageResource(id);