Como enviar array Json do Jquery para o PHP

Question: Tenho uma tabela onde constantemente as linhas mudam de ordem, preciso gravar essa tabela no banco. A partir do momento que não irei mais modificar a tabela eu clico em um botão "Confirmar Grid", nesse momento salvo essa tabela em um array dentro do jquery, e quando eu quiser mandar pro php clico para submeter no formulario.
Porém não consigo receber estes dados no back, recebo um "Notice: Undefined index: pilotos"
html:

      {foreach from=$pilotos item=row}

               {$row.numero}

             {$row.nome}

    {/foreach}

    <input type="button" id="add" value="Confirmar Grid" >
    <form name="form_insert" method="post" id="form_insert">
       <fieldset style="display: none;"></fieldset>

           <input type="submit" id="confirmar" name="confirmar" value="Cadastrar grid" />

    </form>

jQuery:
    var pilotos = [];

$("#add").click(function () {
    $('#tabelaPilotos tbody tr').each(function () {
        var colunas = $(this).children();
        var piloto = {
            'numero': $(colunas[0]).text(),
            'nome': $(colunas[1]).text()
        };
        pilotos.push(piloto);
    });
    console.info(pilotos[0]);
});

$("#form_insert").submit(function () {
    $.ajax({
        type: 'POST',
        cache: false,
        data: pilotos,
        dataType: "json",
        url: 'cad_corrida.php',
        success: function (msg) {
            alert(msg);
        }
    });

});

php:
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
       $pilotosarray = $_POST["pilotos"];
       echo "";
     }

Como recuperar este array?
Comment: Isso que você está tentando fazer não existe, não dá pra enviar um echo de alert através do PHP, quando se usa smarty, a saída é enviada através de um array compilado que gera uma template de visualização desse compilamento, o que será visto é enviado numa view através de um elemento chamando `$smarty->assign('variavel', $dados)`. Observe que pelo layout da sua view isso é [smarty](http://www.smarty.net/).
Comment: Aqui tem a [documentação do smarty](http://www.smarty.net/docsv2/pt_BR/)
Comment: Eu só usei este echo para testar se estava recebendo informações do front. Ele na verdade não me interessa.
Comment: É preciso colocar o código correto então do PHP, para que alguém possa te ajudar nisso. Porque me parece muito incompleta sua pergunta.
Answer: Para receber a informação no post como "pilotos" é preciso passar o índice e valor no data do ajax, é importante no back-end utilizar o "isset($_POST['pilotos'])", para verificar se realmente há um índice com valor sendo recebido, e tratar o possível warning.
Caso o retorno do back não seja em formato JSON é necessário alterar o "dataType", de acordo com o retorno esperado.
$("#form_insert").submit(function () {
    $.ajax({
        type: 'POST',
        cache: false,
        **data: { pilotos: pilotos}**,
        **dataType: "ValorRetorno"**,
        url: 'cad_corrida.php',
        success: function (msg) {
            alert(msg);
        }
    });

});

Comment: Quando faço a verificação isset($_POST['pilotos']), ele não entra no if.

Oque seria o "ValorRetorno"?
Comment: O fato dele não acessar o isset é exatamente pq o indice ['pilotos'] está vindo com valor vazio, pra debugar isso coloque antes do if :
echo "";
die(var_dump($_POST));
Answer: O conteúdo que é enviado ao servidor vai no corpo da requisição. Ou seja, você pode lê-lo assim:
$conteudo = file_get_contents('php://input');

Pode-se também usar a constante STDIN, que equivale a php://input:
$conteudo = stream_get_contents(STDIN);

Depois basta transformar esse conteúdo em um array:
$conteudo = json_decode($conteudo, true);

Answer: Gabriel,
Voce pode usar o JSON.stringify no javascript pra poder transformar seu objeto em uma string e passa essa string no seu "data" do ajax e no PHP você usa a função json_decode pra transformar de volta essa string em um array/objeto.
Não testei com código, mas teoricamente essa idéia funciona.
Referência:

JSON.stringify:
  https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
json_decode: http://php.net/manual/pt_BR/function.json-decode.php

Espero que ajude.
Vlw


What is the difference between Microsoft VPN and Cisco VPN

Question: What is the difference between Microsoft VPN and Cisco VPN? Are they just separate implementations of the same protocol?
I seem to remember hearing somewhere that they were not compatible with each other, and I have never seen any one connect to a given network with both clients...
Answer: Microsoft VPN is usually PPTP, Cisco uses IPSEC.  These are completely different protocols so a client won't typically support both.
Microsoft also support L2TP and more recent versions do support IPSEC, although the implementation is a bit clumsy (imho).
PPTP has had several bad security problems in the past, but the latest version is reasonably secure and is easier to set up than IPSEC.
IPSEC is more of an industry standard and is very secure when configured properly.
Comment: In your experience, is there a speed difference?
Comment: How about a little light on these points...

"Microsoft VPN is usually PPTP"  -  No sorry.  Microsoft supports PPTP, L2TP, and SSTP tunnels based on the RFC standard.

"...the implementation is a bit clumsy (imho)"  - Microsoft's implementation is completely integrated with the Windows platform with full support for Group Policy configuration, certificate auto-enrollment (for L2TP), and Network Access Protection (included & integrated with Windows XP SP2 and above clients).


Interesting overlapping UIScrollView conundrum

Question: Say you have two scrollviews, one vertical and one horizontal, that intersect in a "plus sign" pattern. Say you have one object (a UIImageView for example) in the center of the plus. If you touch the object and scroll upward, you want the object to scroll upward in the vertical scrollview. But if you touch the object and scroll sideways, you want it to scroll within the horizontal scrollview.
Problems:

Which scrollview is the object initially in? Or is it in neither? You don't know which scrollview the object is in until you detect which scrollview began scrolling.
If the vertical scrollview is on top, the horizontal scrollview would not receive touches in the center area where the scrollviews overlap.

Can anyone think of any solutions to this problem? (Change the design is not a solution)
Another way to think about it is this: You have a 100x100 grid of tiles, but you can only see a 10x10 grid on the screen at once. You want to be able to scroll each row sideways, but you also want to be able to scroll each column vertically. Obviously the scroll position would have to lock to the nearest multiple of tile size before each new touch/scroll began. But it means that at any given time any tile could be in either a horizontal or vertical scrollview.
Answer: Use a (single) scroll view (with directionLockEnabled = YES) for its physics, but don't actually make it the superview of your tiles.
See the WWDC2012 video "Enhancing User Experience with Scroll Views" for more on this technique.


Deciding rows and columns in a two-way table with the key dependent var and another

Question: In a two-way table of percentages that analyzes what will be in later models the key dependent and key independent variable, which variable is placed on the left to define rows and which variable is placed across the top to define columns?
Comment: Why would it matter?  Since you haven't stated how this table will be used, on the face of it it's purely a matter of personal choice how you lay out the values within it.
Answer: What can bite first and most obviously is that many columns are usually much more awkward than many rows for almost any kind of display. That is true for books, journals, monitors, smart phones, and so forth. So you need to avoid the more awkward possibility, and this mundane fact may outweigh anything else.
That said, it is generally easier with tables to compare down columns than across rows -- especially if (as is good practice) numbers are aligned on the decimal point (or where it would be). So
<code>1
23
456
7890
</code>
is dopey and
<code>   1
  23
 456
7890
</code>
is recommended. So, what kind of comparisons are more interesting or useful? If reading the table both ways is equally interesting or useful, this won't settle the matter.
Perhaps too trivial to mention, yet what I do most often is try one or both possibilities and change my mind quickly if one looks horrible. That calls for changing details in a single command or function call in any software I want to take seriously. It's easier to do that than to consult some abstract principle from some expert somewhere on what you should do. You don't have to define horrible before you can recognise it.


compactness of sets in euclidean topology and product topology

Question: Which sets are compact in euclidean topology and product topology ?

$\{(z_1,z_2,z_3):z_1^2+z_2^2+z_3^2=1)\}$ in the euclidean topology.
$\{z\in \mathbb C:|re(z)|\leq a\}$ in the euclidean topology for some fixed positive real number $a$.
$\prod A_n$ with product topology , where $A_n=\{0,1\}$ has discrete topology for n=0,1,........

I think (1) is not bounded in $\mathbb C$ ,so not compact . Are (2) and (3) compact or not? someone help.
Thanks.
Comment: What does (2) look like, as a subset of $\Bbb C \cong \Bbb R^2$?
Comment: is it a strip whose real part bounded
Comment: so (3) is true,am i right?
Comment: Nice.................+1
Answer: $1.$ The set is not bounded since $(1,n,ni)$ is inside for every $n\in\mathbb{N}$ and has norm equal to $\sqrt{1+2n^2}$ which goes to $+\infty$ as $n$ grows to $+\infty$. Hence, the set is not compact.
$2.$ The set is not bounded since $a+in$ is inside for every $n\in\mathbb{N}$ and has norm equal to $\sqrt{a^2+n^2}$ which goes to $+\infty$ as $n$ grows to $+\infty$. Hence the set is not compact.
$3.$ First, notice that $\{0,1\}$ is compact for the discrete topology. It his indeed Hausdorff, since $0$ and $1$ admits disjoint open neighborhoods, namely $\{0\}$ and $\{1\}$. Besides, let $(U_i)_{i\in I}$ be an open-cover of $\{0,1\}$, for every $i\in I$, one has $U_i\in\{\{0\},\{1\},\{0,1\}\}$ and since $\bigcup\limits_{i\in I}U_i\supseteq\{0,1\}$, there exists  $(i,j)\in I^2$ such that $U_i\cup U_j=\{0,1\}$, in other words $(U_i,U_j)$ is a finite open-subcover of $(U_i)_{i\in I}$. Otherwise, one gets: $$\bigcup\limits_{i\in I}U_i=\{0\}\not\supseteq\{0,1\}\textrm{ or }\bigcup\limits_{i\in I}U_i=\{1\}\not\supseteq\{0,1\}.$$ Hence, every open-cover of $\{0,1\}$ admits a finite open-subcover.
Using Tykhonov's theorem, $\{0,1\}^{\mathbb{N}}$ is compact for the product topology.
Reminders:

If $X$ is equipped with discrete topology, then every subset of $X$ is both open and close.
If $X$ is a topological space, $A\subseteq X$ is compact if and only if the topology induced by $X$ on $A$ makes $A$ be a Hausdorff space and from every open-cover of $A$ one can extract a finite open-subcover.

Remark. Have a look to your definition of a compact space, since it appears some people does not ask compact space to be Hausdorff.
Comment: Any finite space is compact trivially. Hausdorff is not needed.
Comment: That might be a French convention. I took a look on Wikipedia article on compactness and the French article ask for the Hausdorff condition but not the English one. I am adding a remark to my post to clarify this point! Besides, I agree with you, any (Hausdorff) finite space is trivially compact, since the question features the (general-topology) tag I wanted to use the open-cover at least one time.


Morera's Theorem proof involving mean value theorem

Question: I was reading the proof of Morera's Theorem on Arfken's book and in it he glossed over one part of the proof.
Here it says that given a function $f(z)$ that is continuous and satisfies $\oint_C \! f(z) \, dz = 0$, integrating it from z_1 to z_2 would result in:
$$F(z_2) - F(z_1) = \int_{z_1}^{z_2} \! f(z) \, dz$$
which results in:
$$\frac{F \left(z_2 \right) - F \left(z_1 \right)}{z_2 - z_1} - f \left(z_1 \right) = \frac{\int_{z_1}^{z_
2} \, \left[ f \left(t \right) - f \left(z_1 \right) \right] \, dt}{z_2 - z_1}$$
Using the variable $t$ as another complex variable. If we take the limit $z_2 \to z_1$ this gives:
$$ \lim_{z_2 \to z_1} \frac{\int_{z_1}^{z_
2} \, \left[ f \left(t \right) - f \left(z_1 \right) \right] \, dt}{z_2 - z_1} = 0$$
Since $f \left( t \right)$ is continuous. This is the part where I am confused in since he only remarked that he used the mean value theorem to prove that it is zero. However it is my understanding that using the mean value theorem on the previous equation would result in:
$$\begin{align}
lim_{z_2 \to z_1} \frac{\int_{z_1}^{z_
2} \, \left[ f \left(t \right) - f \left(z_1 \right) \right] \, dt}{z_2 - z_1} & = 0 \\
lim_{z_2 \to z_1} \left[ \frac{\int_{z_1}^{z_2}\, f \left(t \right) \,dt}{z_2 - z_1}  - \frac{\int_{z_1}^{z_2} \, f \left(z_1 \right) \, dt}{z_2 - z_1}\right] & = 0 \tag{1}\\
f \left(c \right) - lim_{z_2 \to z_1} f \left(z_1 \right) \frac{z_2-z_1}{z_2-z_1} & = 0 \tag{2}\\
f \left(c \right) - f \left(z_1 \right) & = 0 \\
\end{align}$$
Which wouldn't result in zero unless of course $f \left(c \right) = f \left(z_1 \right)$ which I think is not the case here. Is my application of the mean value theorem incorrect here or is it really $f \left(c \right) = f \left(z_1 \right)$?
Comment: $c$ is related to $z_2$.
Comment: @C.Ding What do you mean? $c = z_2$?
Comment: $\lim_{z_2 \to z_1} \frac{\int_{z_1}^{z_2}f \left(t \right) \,dt}{z_2 - z_1} =\lim_{z_2 \to z_1} f(c_{z_2})$
Comment: Can you add some information about what are $f, z_1, z_2, F$?
Comment: @Gribouillis $f$ is any function that is continuous and satisfies $\oint_C \! f(z) \, dz = 0$, $z_1, z_2$ are points in the region and $F$ is the antiderivative of $f$.
Comment: Sorry for the confusion, I'll add that into the question.
Answer: The $c$ (In fact, it should be writen as $c_{z_2}$) in the equation (2) is in the line  segments $z_1 z_2$, so   $c\to z_1$ as $z_2\to z_1$ and $ \lim_{z_2\to z_1} \frac{\int_{z_1}^{z_2}f(t)dt}{z_2-z_1}=\lim_{z_2\to z_1}f(c)= f(z_1).$
Comment: Thank you. However I still don't understand how $c$ is related to $z_2$. Is it because from the mean value theorem that $c \in \left[z_1, z_2 \right]$ such that taking the limit $z_2 \to z_1$ would restrict the value of $c$ to $c=z_1=z_2$?


Grep by block of text\lines

Question: I have the text, that contains some lines. So, i need to make GREP of several lines. For example, i have repeating text and i should GREP get lines, that have this repeating key-words.
grep -o "test|test2" textfile

My text:
123|never for your|test
123421|never for your|test2
123412|never for your|test3
12341|never for your|test4
12311|never for your|test2
123312312|never for your|test
123321312|never for your|test2

I should have:
123|never for your|test
123421|never for your|test2
123312312|never for your|test
123321312|never for your|test2

It works, but it doesn't work how i want. It searchs in text, all words "test" & "test2". But i want to get textblocks, like some pattern, where only after "test" comes "test2".
Have you got any ideas ?
Comment: test the new code
Comment: I'm voting to close this question as off-topic because it is http://serverfault.com/questions/827736/grep-of-several-lines-one-by-one question asked in a different way.
Answer: Brief shell script using sed.  Makes a list of line numbers for the second case, and compares against line numbers for the first case.  Prints matching pairs.  Uses the first argument as the file name.  Could easily be extended to take second and third arguments as patterns to match.  Could save as findnext.sh, and run:
$ sh findnext.sh testfile

Should be quick as it only involves two passes over the file, and has the advantage of being completely portable.
#!/bin/sh
# Line numbers matching test1
mt2=$(sed -ne '/test1/=' < $1 | tr '\n' '/')

for l in $(sed -ne '/test/=' < $1); do
    nextline=$(expr $l + 1)
    [ "${mt2#*$nextline/}" != "$mt2" ] && sed -ne $l,${nextline}p <$1
done

Answer: You can try grep -E or egrep.
Please try it like this
#this will show lines that have test or test2
    grep -E "test|test2" file

If you want to show line that has test and test2 like this test|test2 do this
# This will show lines that has test|test2
    grep "test\|test2" file

Comment: @valeriu You where doing it correct just use -E instead of the -o so you can use regular expression like test|test2 means "test or test2" with the option -o  you will show only the matching wich is test or test2
Comment: i have tried, but it doesn't work. i am sorry
Comment: @valeriu can you paste few lines so I can see the pattern
Comment: just a moment. i will pastle it in above text
Comment: yes, it works. but in my text, i have repeat test2. i have tested same commands, that you have written above. i want to have test and test2 together & get lines with this together words/lines
Comment: and i have written, that i have used same command: grep -o "test|test2" textfile
Answer: awk may be your tool for this:
awk '/test$/, /test2$/' < block-text-lines.txt

the general form is:
awk '/start-pattern/, /end-pattern/{command}'

But since the command block defaults to print, just the start and end patterns do the trick.
Check out man awk or the Gnu Awk User's Guide for way more detail.
Comment: thanks. but it doesn't work. i have tried all this commands. i have in output repeat test2. but i want to have test2 only before test. and i have test2 before test4. look at my file above
Comment: Sorry, I do not understand.  I run your input through that awk command, above, and get the output your questions says "I should have" in your second quote. Your output has repeated `test2`.

Can you provide a more detailed "after" example of what you are looking to get?
Answer: grep -A 1 "test$" in.txt | grep -B 1 "test2$"

In grep manual

-A NUM Print  NUM  lines  of  trailing  context after matching lines.
-B NUM Print NUM lines of leading context before matching lines.

The command grep -Pzo ".*test$\n.*test2$" in.txt also works, but in the manual is "This  is highly experimental and grep -P may warn of unimplemented features."

Grep by block of text\lines


tabela dinamica javascript gravar no banco de dados mysql

Question: Como eu faço para pegar as inserções da tabela e gravar no banco de dados ?.
Segue meu código.

function addItens ()
{
  // Elemento textarea:
  const texto = $("#texto");
  // Elemento table:
  const table = $("#products-table");
  // Divide o conteúdo de textarea em linhas:
  let linhas = texto.val().split("\n");
  // Percorre todas as linhas:
  for (i in linhas)
  {
    // Verifica se a linha não está vazia:
    if (linhas[i])
    {
      // Divide o conteúdo da linha em colunas:
      let retorno = linhas[i].split(" ");

      // Cria uma nova linha na tabela:
      let newRow = $("
");

      // Percorre todas as colunas:
      for (j in retorno)
      {
        // Verifica se a coluna não está vazia:
        if (retorno[j])
        {
          // Cria a nova coluna na tabela:
          let newCol = $("");
          // Adiciona o conteúdo na coluna:
          newCol.html(retorno[j]);
    // Adiciona a coluna na linha:
          newRow.append(newCol);
        }
      }

      // Cria a coluna de ação:
      let action = $("");
      // Adiciona a classe "actions":
      action.addClass("actions");
      // Adiciona a coluna na linha:
      newRow.append(action);
      // Adiciona a linha na tabela:
      table.append(newRow);
    }
  }
}

      <textarea id="texto" class="materialize-textarea">
      </textarea>
      Copie e Cole os Dados do Excel

       <button class="btn waves-effect waves-light" id="enviar" onclick="addItens()">Enviar</button>

Obrigada
Comment: você quer salvar o texto ou a tabela formatada? ja pensou em usar o firebase?
Comment: eu quero usar a tabela formatada, nunca tentei rs, meu sistema todo já esta em mysql.
Comment: Então você não quer o valor da tabela, quer a tabela em si, é isso?
Comment: Por favor poste a resposta no campo abaixo, somos um Q&A e em seguida clique em "Publicar sua resposta".
Answer: acrescentei no js o seguinte código.

$.post("gravarBanco.php", {retorno:retorno}, function(retorno){         })

e fiz o insert pelo arquivo gravarBanco.php dos resultados via POST.
Obrigada.


Retain client side use of RequiredFieldValidator when using Script manager

Question: Retain client side use of RequiredFieldValidator when using Script manager
I have the following in a asp.net forms (vs2013, net4.5, vb.net)
<form id="form1" runat="server">

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
        runat="server" ControlToValidate="TextBox1" ErrorMessage="Required text box">
    </asp:RequiredFieldValidator>

    <asp:Button ID="Button1" runat="server" Text="Button" />

</form>

Above runs just fine and does NOT post back until a value is entered into text box). This is GOOD and makes perfect sense (large numbers of applications use the above approach).
However if I add the script manager control or the  Ajax ToolKit Script manager to the form, then ALL CLIENT side validation RequiredFieldVAlidators STOP using clinet side validation. This is rather large cost for the simple introduction of the script manager into a web form.
So adding this to the above web form is the bad guy:
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

The end result is now all EXISTING RequiredValidators NEVER run client side – only server side.
Is there a workaround to the above, namely that of adding the Script manger (or Ajax Tool Kit Manager from the ajax tool kit) to a form and continuing to enjoy client side validation in web forms?
Answer: A bit of digging and some BinGoogle I have found the problem.
Unfortunately when using .net 4.5, placing the script manager control into a form will disable client side validation.
The solution is to add this appSettings to the web.config
appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
 </appSettings>

The above will force a loss of HTML5 client side validating, but the result is client side validation will return to your forms that use the script manager.


Using Doctrine 2 Annotation reader for customized annotations

Question: I'm pretty new to Doctrine 2 and am using annotations to do my database mapping. I want to take things a little bit further and use some custom annotations. The aim is to be able to make forms and such that can have settings created through annotations. I'm having trouble reading ANY annotations - even class ones such as @Table aren't being returned from the parser.
I am using Codeigniter 2 and Modular Extensions. In my controller I have:
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$reader->setDefaultAnnotationNamespace('MyCompany\Annotations');
$reflClass = new ReflectionClass('models\User');
$classAnnotations = $reader->getClassAnnotations($reflClass);
print_r($classAnnotations);

Which returns an empty array.
I then have a file in my libraries/annotations folder, Bar.php:
namespace MyCompany\Annotations;

class Bar extends \Doctrine\Common\Annotations\Annotation
{
    public $foo;
}

and lastly, my user model:
/**
* @Entity
* @Table(name="user")
* @MyCompany\Annotations\Bar(foo="bar")
* @MyCompany\Annotations\Foo(bar="foo")
*/

class User {

}

I am trying to follow this example:
http://www.doctrine-project.org/projects/common/2.0/docs/reference/annotations/en#setup-and-configuration
Thanks for your help in advance!
Mark.
Comment: Which version of Doctrine are you using, 2.0 or 2.1?
Comment: Figured it out. Super simple - you have to manually include the class files whereever you want to use annotations, in my case, in my controller file
Answer: use
Doctrine\Common\Annotations\AnnotationRegistry

AnnotationRegistry::RegisterLoader($universalClassLoader);
AnnotationRegistry::RegisterFile(__DIR__ . ' PATH_TO_DoctrineAnnotations.php ');

Answer: As you've figured out, you need to include your custom annotation files/classes before you can use them.
Though including them in your controller would work, why not do it the Doctrine way!
Doctrine2's ORM has a file called DoctrineAnnotations.php in the Doctrine/ORM/Mapping/Driver/ folder. It looks like this:
...
require_once __DIR__.'/../GeneratedValue.php';
require_once __DIR__.'/../Version.php';
require_once __DIR__.'/../JoinColumn.php';
require_once __DIR__.'/../JoinColumns.php';
require_once __DIR__.'/../Column.php';
...

So, what I've done is created a similar file in my library and load my annotations by including this "driver" (eg. in your bootstrap).
In my ZF-based app (using Guilherme Blanco's fabulous Zf1-D2 set-up), I just added my "annotations driver" to my application.ini, like this (all on one line):
resources.doctrine.orm.entityManagers.default
  .metadataDrivers.annotationRegistry.annotationFiles[]
  = APPLICATION_PATH "/path/to/my/library/ORM/Mapping/Driver/MyAnnotations.php"


Basic question about showing bijection when a function is defined piece wise

Question: Hello there everyone,
I was told that the standard proof for showing that
$$| \mathbb{N} | = | \mathbb{Z} |$$
is to define $$f: \mathbb{Z} \to \mathbb{N}$$ as $$f(x)= \begin{cases} 2x &\text{ if $x \ge 0$} \\ -2x-1 &\text{ if $x \lt 0$} \end{cases}$$
Now, I am a bit confused. I am used to working with non piece wise functions, were we must show that $f(x_1)=f(x_2)$ implies $x_1=x_2$ and that for every $n \in \mathbb{N}$ there must exist a $z \in \mathbb{z}$ such that $f(z)=n$
But I am not sure how to do this for this type of function.
Can anyone please help shed some light on this for me?
Thank you all
Comment: Do it by cases. Case 1: $x_1\ge0,x_2\ge0.$ Case 2: $x_1\ge0,x_2\lt0.$ Case 3: $x_1\lt0,x_2\ge0.$ Case 4: $x_1\lt0,x_2\lt0.$
Answer: For a positive integer, $x$, $2x$ is even and positive. For a negative integer, $x$, $-2x-1$ is positive and odd.
So the function maps zero to zero, the positive integers to even positive integers, and negative integers to positive odd integers.
Answer: I always liked the visual presentation:
${\color{red}0},{\color{blue}{-1}},{\color{red}1},{\color{blue}{-2}},{\color{red}2},{\color{blue}{-3}},{\color{red}3},...,{\color{blue}{-n}},{\color{red}n},... \longrightarrow {\color{red}0},{\color{blue}{1}},{\color{red}2},{\color{blue}{3}},{\color{red}4},{\color{blue}{5}},{\color{red}6},...,{\color{blue}{2n-1}},{\color{red}{2n}},...$
Answer:
Assume $f(x_1) = f(x_2)$ and wlog assume it to be an even number, then clearly $x_1 = x_2$ because we know the function $x \mapsto 2x$ to be a bijection.
For the reverse direction, consider the function $g(n) = n/2$ if $n$ is even and $-(n+1)/2$ if $n$ is odd.


MySQL allows zero date(0000-00-00 00:00:00) after I enabled strict mode

Question: I want to configure a MySQL db instance not to accept zero dates(0000-00-00 00:00:00) because the software running on top of it fails to run if it encounters such a field.
The server is running MySQL version 5.5.40.
I added the following lines in the my.cnf file, in the [mysqld] section:
sql-mode="NO_ZERO_DATE,NO_ZERO_IN_DATE"
innodb_strict_mode="ON"

After a restart, if I check from the command line I get the following:
mysql> SELECT @@GLOBAL.sql_mode;
+------------------------------+
| @@GLOBAL.sql_mode            |
+------------------------------+
| NO_ZERO_IN_DATE,NO_ZERO_DATE |
+------------------------------+
1 row in set (0.00 sec)

mysql> SELECT @@GLOBAL.innodb_strict_mode;
+-----------------------------+
| @@GLOBAL.innodb_strict_mode |
+-----------------------------+
|                           1 |
+-----------------------------+
1 row in set (0.00 sec)

But if I connect with a client app to the database and try to fill in a zero date, it still works. I tried to recreate the database, still no luck. Any ideas why this is?
Thank you.
Comment: Does the app do an `INSERT IGNORE` ?
Comment: Also does the client have any SESSION settings? As the client can specifiy `innodb_strict_mode=0` for its own session..
Comment: I'm voting to close this question as off-topic because it should have been migrated to [dba.se].
Answer: From reading the documentation on MySQL server modes:

The MySQL server can operate in different SQL modes, and can apply these modes differently for different clients, depending on the value of the sql_mode system variable. DBAs can set the global SQL mode to match site server operating requirements, and each application can set its session SQL mode to its own requirements.

and later on

Setting the GLOBAL variable requires the SUPER privilege and affects the operation of all clients that connect from that time on. Setting the SESSION variable affects only the current client. Each client can change its session sql_mode value at any time

Basically, the setting in the configuration file only controls the default. Individual clients and applications are still free to do whatever they want if they are willing to work to set the session settings. If you turn on the general_log you can actually watch this happening as clients connect and run queries.
As an aside, I think the responsibility of validating the data should be in application code and not in the data-store. You add a thin layer to your overall application structure that ensures that INSERTS comply with your requirements.


Rounding x to the nearest 1/n.

Question: I'm trying to come up with a way to solve this problem:
Assume x and y are rational numbers in the range (0, 1].
Given x, what is the nearest y to x such that yn=1 for some integer n?

Or put another way,
Round x to the nearest 1/n.

What I'm trying to do is find a good interval for a table I'm creating. I've computed the optimal interval, x, but I also want the table to land on every whole integer as well.
I'm trying to find the function that performs this transformation.
Examples:

f(x) = y

f(0.3168705857) = 1/3
f(0.2141233120) = 1/5
f(0.9583990664) = 1
f(0.2426311964) = 1/4
f(0.8125500321) = 1
f(0.3569497599) = 1/3
f(0.0539263572) = 1/19

Comment: "What I'm trying to do is find a good interval for a table I'm creating." Could you elaborate on this?
Comment: Not sure how to describe it succinctly. But the above function will compute the column headers I'll use for the table. I them to always to contain 1, 2, 3, etc.. when it crosses over them but if the values are small I want the columns to be 1, 1.5, 2, etc or 1, 1.2, 1.4, 1.6, 1.8, 2, etc. If I don't compute this function I could end up with ex 1, 1.4, 1.8, 2.2, 2.6, etc (it skips "2" so I would want to round the 0.4 x to 0.5 instead)
Answer: $0 < x \le 1$ so
$1 \le \frac 1x$ so
$n \le \frac 1x \le n + 1$ for some integer $n \ge 1$.  $n = \lfloor \frac 1x \rfloor$.  $n + 1 = \lceil \frac 1x \rceil$.  So
$\frac 1{\lceil 1/x \rceil} \le x \le \frac 1{\lfloor 1/x \rfloor}$.
Example:  if $x = e^{-3} = 0.04978706836786394297934241565006$
Then $\frac 1x = 20.085536923187667740928529654582$ and
$\frac 1{21} < x < \frac 1{20}$
$\frac 1{20} - x =0.000212931632136057020657584349938$
and $x - \frac 1{21} = 0.00216802074881632393172336803101$
so closest is $\frac 1{20}$.

Rounding x to the nearest 1/n.


Classification vs clustering

Question: I am beginner to data mining.
This is my understanding, regression is used to predict continuous values. It is a type of classification.
Classification is Supervised and Clustering is unsupervised.
In classification we have predefined classes, whereas in clustering there are no classes defined.
What does this exactly mean? But in both of them we do have training data, which tells which output the set of features should belong to. Then how can we say that clustering does not have per-defined classes?
Please explain when to use classification and clustering.
Can clustering also predict continuous values?
Thanks. Please help.
This post has been edited.
Comment: By definition, unsupervised learning does not take training data, and clustering is usually considered unsupervised. However, you could use some hybrid technique where items are clustered without training data, but then those clusters are compared to a set of known data. If that's the case though, it likely means you have a pre-defined set of categories, and you might be better off using a supervised learning technique for classification.
Comment: Except for your last question, you will find useful clues by considering [supervised](http://en.wikipedia.org/wiki/Supervised_learning) vs. [unsupervised](http://en.wikipedia.org/wiki/Unsupervised_learning) learning.
Comment: There are regression methods for all sorts of variables - logistic, Poisson, Cox PH, etc.
Comment: @user904522 you don't need training data for clustering
Comment: Thanks for the reply.
So does that mean clustering never takes training data?
Answer: Clustering: In clustering you group(cluster) the data based on some variables into some number of groups (cluster).
Classification: In classification, you have certain groups & you want to know how different variables are related to the groups.
Comment: Thanks for the reply. So clustering never takes training data? If it does what does the training data contain?
Answer: As @chl says, there are good threads on this site regarding supervised versus unsupervised learning. In regards to your bolded question: you're misunderstanding what data is supplied to supervised versus unsupervised methods. Supervised methods will always include an additional piece of information for each sample: the correct answer.
Comment: Yes, clustering algorithms are not trained: you don't run them on training data to have them adjust their parameters to maximize their chance of getting the correct answer (which is provided in supervised learning). But that doesn't mean that clustering algorithms don't have parameters that need to be chosen. You might use a set of data to figure out what algorithm and what parameters you intend to use in the future. (One example of a common parameter in clustering algorithms is the number of clusters it will seek to create.) This is not training and the data would not be called training data.
Comment: Thanks for the reply. So I understand from this that  clustering never takes training data. Is it true?
Answer: These video lecture's are really a good if you bring some time to listen to them. Particularly your questions about supervised vs. unsupervised should all be covered.

Classification vs clustering


DataTables Server-side Processing for large JSON files with dynamic columns

Question: I have a process that generates a JSON file with a large amount of entries and then gets read into a Datatable and displayed to the user. I'm having trouble figuring out how to transform my current method of creating the datatable to allow for server side processing. I am trying to avoid the entire file loading before displaying in the browser.
JS

Comment: Just to check, when implementing `serverSide: true` for the first time: Are you familiar with [the JSON structure](https://datatables.net/manual/server-side#Returned-data) that your server is expected to use when sending data to DataTables? And the [related JSON structure](https://datatables.net/manual/server-side#Sent-parameters) that DataTables automatically sends to the server whenever there is a paging/sorting/filtering request? Those can be good places to start.
Comment: _avoid the entire file loading before displaying in the browser_  - A key point here is that with server-side processing, you no longer send the entire data set to the browser in one go - you send manageable subsets (maybe 1,000 rows, out of your total 1 million rows) each time.
Comment: @andrewjames the JSON structure is unknown as the file is generated by a query that is ran against multiple databases. Could be different every time
Comment: Yes, agreed - that's the "dynamic columns" of the question's title. That requirement can co-exist with server-side processing. These may be worth looking at: [server-side example](https://stackoverflow.com/questions/60801535/how-can-i-load-a-set-number-of-rows-from-a-table-on-pageload-and-only-load-furth/60804184#60804184) and [dynamic JSON](https://stackoverflow.com/questions/61713887/query-datatable-from-rest-api-without-pre-defining-the-table-in-html/61718192#61718192).
Answer: I'm surprised this old question got no practical answer yet. I went through this post (also mentioned among the comments above as "server-side example") and experimented a bit using node.js as a server, and here's what I got: a working example. I'd strongly recommend reading that original post before getting into my codes. I'm basically making a realization out of what's written in that post:
The data: (put this at the root of where you have the working directory of node.js service)
[
   {
      "id":1,
      "name":"widget_1",
      "description":"This is a description for widget 1"
   },
   {
      "id":2,
      "name":"widget_2",
      "description":"This is a description for widget 2"
   },
   {
      "id":3,
      "name":"widget_3",
      "description":"This is a description for widget 3"
   },
   {
      "id":4,
      "name":"widget_4",
      "description":"This is a description for widget 4"
   },
   {
      "id":5,
      "name":"widget_5",
      "description":"This is a description for widget 5"
   },
   {
      "id":6,
      "name":"widget_6",
      "description":"This is a description for widget 6"
   },
   {
      "id":7,
      "name":"widget_7",
      "description":"This is a description for widget 7"
   },
   {
      "id":8,
      "name":"widget_8",
      "description":"This is a description for widget 8"
   },
   {
      "id":9,
      "name":"widget_9",
      "description":"This is a description for widget 9"
   },
   {
      "id":10,
      "name":"widget_10",
      "description":"This is a description for widget 10"
   },
   {
      "id":11,
      "name":"widget_11",
      "description":"This is a description for widget 11"
   },
   {
      "id":12,
      "name":"widget_12",
      "description":"This is a description for widget 12"
   },
   {
      "id":13,
      "name":"widget_13",
      "description":"This is a description for widget 13"
   },
   {
      "id":14,
      "name":"widget_14",
      "description":"This is a description for widget 14"
   },
   {
      "id":15,
      "name":"widget_15",
      "description":"This is a description for widget 15"
   },
   {
      "id":16,
      "name":"widget_16",
      "description":"This is a description for widget 16"
   },
   {
      "id":17,
      "name":"widget_17",
      "description":"This is a description for widget 17"
   },
   {
      "id":18,
      "name":"widget_18",
      "description":"This is a description for widget 18"
   },
   {
      "id":19,
      "name":"widget_19",
      "description":"This is a description for widget 19"
   },
   {
      "id":20,
      "name":"widget_20",
      "description":"This is a description for widget 20"
   }
]

The HTML: (put this under your working directory/public)
<!DOCTYPE html>

    <title></title>

    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <link href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.css" rel="stylesheet" type="text/css">

And the server:
    const fs = require('fs');
    const data = JSON.parse(fs.readFileSync("data.json", 'utf8'));

    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser')
    app.use( bodyParser.json() );       // to support JSON-encoded bodies
    app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
      extended: true
    }));

    app.use('/static', express.static(__dirname + '/public'));
    app.post('/data', function(req, res){
        var resp = {"recordsTotal": 20,"recordsFiltered": 20,"start":0,"length":5}
        if(req.body.start){
            resp.draw = JSON.parse(req.body.draw);
            resp.data = data.slice(JSON.parse(req.body.start),
                                    JSON.parse(req.body.start)+JSON.parse(req.body.length));
        }else{
            resp.draw = 1;
            resp.data = data.slice(resp.start,resp.start+resp.length);
        }
        res.end(JSON.stringify(resp))
    })

    app.listen(3000, function () {
        console.log('listening on port 3000');
    });

Then you'd be able to just start the server, and browse the result at http://localhost:3000/static/dtable.html
Read through these codes, or probably dig in to a few intermediate outputs, and you'll have a better idea of how DataTable works under a minimum setup for server-side processing.


Unir duas tabelas com PHP e recuperar os dados no mesmo elemento select do html

Question: Estou tentando listar no mesmo elemento select do html os resultados da consulta de tabelas diferentes, porém não estou conseguindo.
Segue abaixo o código para que alguém possa me dizer onde estou errando.

    Selecione a turma:
    <select name="id_disciplina_turma_facul">
        <?php
            $consulta = \MySql::conectar()->prepare("SELECT tb_turma_facul.id_turma_facul as turma,
                                                 tb_turma_facul.id_disciplina_turma_facul,

                                                tb_disciplina_facul.id_discip_facul,
                                                tb_disciplina_facul.nome_discip_facul as dnome,
                                                 tb_turma_facul.id_professor_turma_facul,
                                                 tb_professor_facul.nome_professor as pnome

                                                   FROM tb_turma_facul

                                          INNER JOIN (tb_disciplina_facul, tb_professor_facul)

                                          ON (tb_turma_facul.id_disciplina_turma_facul =
                                          tb_disciplina_facul.id_discip_facul

                                          AND tb_turma_facul.id_professor_turma_facul =
                                          tb_professor_facul.cpf_professor)");

            $consulta->execute();
            $consulta = $consulta->fetchAll();
            foreach ($consulta as $key => $value) {
        ?>

            <option value="<?php echo $value['dnome'] ?>">
                <?php echo $value['pnome']; ?>
            </option>

        <?php } ?>

    </select>

    <input type="submit" name="acao" value="Matricular em turma">

As colunas das tabelas estão descritas abaixo.
Sendo, que a tabela turma possui as chaves estrangeiras das tabelas disciplina e professor.
Colunas da tabela tb_disciplina_facul:

id_discip_facul
nome_discip_facul
carga_horaria_discip_facul

Colunas da tabela tb_professor_facul:

nome_professor
endereco_professor
complemento_professor
cep_professor
bairro_professor
cidade_professor
estado_professor
telefone_professor
formacao_professor
titulacao_professor

Colunas da tabela tb_turma_facul:

id_turma_
id_disciplina_turma_facul
id_professor_turma_facul
Comment: Sao quantas tabelas amigo?eu posso fazer um exemplo basico e voce adapta em quantos casos achar melhor
Comment: Observe que as colunas de cada tabela está descrito abaixo do código, dessa forma você poderá se basear para ficar semelhante a minha.
Comment: São 3 tabelas, a primeira das disciplinas, a segunda dos professores e a terceira chama-se turma. Essa última possuirá as chaves estrangeiras das duas primeiras.
Answer: Se as colunas descritas estão fieis ao que se encontra no seu banco de dados, você tem dois erros de digitação em seu select: id_turma_ está como id_turma_facul e id_discip_facul está como id_disciplina_facul.
Fiz essas adaptação e obtive o resultado desejado.
SELECT
  tb_turma_facul.id_turma_facul as turma,
  tb_turma_facul.id_disciplina_turma_facul,
  tb_disciplina_facul.id_discip_facul,
  tb_disciplina_facul.nome_discip_facul as dnome,
  tb_turma_facul.id_professor_turma_facul,
  tb_professor_facul.nome_professor as pnome
FROM tb_turma_facul
   INNER JOIN (tb_disciplina_facul, tb_professor_facul)
ON (tb_turma_facul.id_disciplina_turma_facul = tb_disciplina_facul.id_discip_facul
AND tb_turma_facul.id_professor_turma_facul = tb_professor_facul.cpf_professor)

O PHP também teve sucesso no resultado.
Comment: Resolveu o problema, mudei apenas id_disciplina_facul para id_discip_facul. Em relação a outra coluna, o nome é id_turma_facul mesmo, pois fui eu que coloquei o nome incompleto.


Add-in for Outlook 2010 does not get installed on Win7 machine that does not have SP1

Question: We created an Add-in for Outlook 2010. While it works well on Win7 machine that has SP1 however it doesn't appear in the ribbon on machines that does not have Service Pack 1 installed. There is no error during or after installation just that the add-in goes into Inactive State. Any fix we could do that the add-in works on both the types?
Answer: Set the LoadBehaviour of the Addin to 3 .


Verilog: access a variable bits in a register

Question: I want to get the variable bits in a register in each clock cycle.
The code as shown below can't work , I know that the problem is get_bits is not a constant,
but I don't know how to fix it. Does anybody know how to solve it?
    input [423:0]A;
    input [5:0] get_bits;
    output reg[423:0] B;

    always @(posedge clk or negedge rstn)begin
        if(!rstn)begin
            B<=0;
        end
        else
           B<=A[423:get_bits];
    end

`
Answer: A logical right shift would be the equivalent of what you're trying to do with the variable slicing of A since the upper most bits of B would be 0 when get_bits is anything greater than 0:
B <= A >> get_bits;

Comment: Thanks for your reply. But when **get_bits** becomes larger, would it be a problem when synthesizing?
Comment: If you mean if you grow `get_bits` to more than 6 bits, then it does become bigger but the shift should scale linearly with the number of bits in `A` and `B` and logarithmically as `get_bits` with the number of bits  (if using a barrel shifter). The only way I can see to make it more efficient is if you don't move the bits of `A` wrt the bits in `B` (ie, bit 423 of `A` is always 423 of `B` no matter what `get_bits` is); that way you can just use `get_bits` to pass through a mask. The value of `get_bits` doesn't matter.


Primefaces Probleme?

Question: I have created a complexe dataTable for my DiplomeBean and it shows Correctly
The deal is whene i select a row from the list ,nothing happend
I want whene i select a row it shows me the elements of the diplome.
My Bean
package com.beans;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.bo.DiplomeBo;
import com.converter.DiplomeDataModel;
import com.model.Collaborateur;
import com.model.Diplome;

public class DiplomeBean  {

    public Integer idDiplome;
    public String ecole;
    public String typeEcole;
    public String typeDiplome;
    public Integer promotion;
    private Set<Collaborateur> collaborateurs = new HashSet<Collaborateur>(0);

    public Diplome selectedDiplome;

    public Diplome getSelectedDiplome() {
        return selectedDiplome;
    }

    public void setSelectedDiplome(Diplome selectedDiplome) {
        this.selectedDiplome = selectedDiplome;
    }

    public Integer getIdDiplome() {
        return idDiplome;
    }
    public void setIdDiplome(Integer idDiplome) {
        this.idDiplome = idDiplome;
    }

    private DiplomeBo diplomeBo;

    public String getEcole() {
        return ecole;
    }
    public void setEcole(String ecole) {
        this.ecole = ecole;
    }
    public String getTypeEcole() {
        return typeEcole;
    }
    public void setTypeEcole(String typeEcole) {
        this.typeEcole = typeEcole;
    }
    public Integer getPromotion() {
        return promotion;
    }
    public void setPromotion(Integer promotion) {
        this.promotion = promotion;
    }
    public Set<Collaborateur> getCollaborateurs() {
        return collaborateurs;
    }
    public void setCollaborateurs(Set<Collaborateur> collaborateurs) {
        this.collaborateurs = collaborateurs;
    }
    public void setDiplomeBo(DiplomeBo diplomeBo) {
        this.diplomeBo = diplomeBo;
    }

    public String getTypeDiplome() {
        return typeDiplome;
    }
    public void setTypeDiplome(String typeDiplome) {
        this.typeDiplome = typeDiplome;
    }

    public String AddDiplome(){
        Diplome diplome =new Diplome();
        diplome.setEcole(getEcole());
        diplome.setPromotion(getPromotion());
        diplome.setTypeDiplome(getTypeDiplome());
        diplome.setTypeEcole(getTypeEcole());
        diplomeBo.addDiplome(diplome);
        clearForm();
        return "Ajout Bien Fait !!";
    }

    public List<Diplome> getAllDiplome(){
        return diplomeBo.findAllDiplome();
    }

    private void clearForm(){
        this.setEcole("");
        this.setPromotion(0);
        this.setTypeEcole("Choisir type..");
        this.setTypeEcole("Choisir type..");

    }

}

My Page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head></h:head>

<f:view>
<h:outputLink value="Admin/default.xhtml">Go to your app</h:outputLink>

        <h:form>

        <f:facet name="header">
            Diplome Liste
        </f:facet>

            <f:facet name="header">
                <h:outputText value="Model" />
            </f:facet>
            <h:outputText value="#{d.idDiplome}" />

            <f:facet name="header">
                <h:outputText value="Ecole" />
            </f:facet>
            <h:outputText value="#{d.ecole}" />

            <h:outputText value="id:" />
            <h:outputText value="#{diplome.selectedDiplome.idDiplome}" />

            <h:outputText value="Ecole:" />
            <h:outputText value="#{diplome.selectedDiplome.ecole}" />

</h:form>

</f:view>

Thank's :)
Answer: Perhaps try modifying it slightly to be more like the Primefaces showcase example. For example, try something like this:
...

<h:form id="form">

    ...

        ...

    ...

        <h:panelGrid id="display">

           ...

        </h:panelGrid>

</h:form>

...

I can't test this right now, but it seems like it should work since it is essentially the same as the showcase's example.

Primefaces Probleme?


"Easy" FTP acces for Google Compute Engine?

Question: I'm setting up hosting on the Google Compute Engine with a LEMP stack, and from time to time the need arises to allow a third-party developer access to the server.
To have to explain to every customer service how the gcloud tool installs and configures is simply not done.
I recently found that a simple ssh user@[ipadress] can work, but I'm not sure what the proper workflow is to add the keys to the VM first.
My question is, what is the best way to manage this? And/or is there a way to just generate a basic FTP user (without any need for SSH keys) to give someone temporary access to the fileserver?
Answer: I think you can "fake" a FTP client by using Google Cloud Storage. I imagine the steps would be:

create a new bucket
mount that bucket and it will appear as a folder on that machine
point the web server to serve from that folder
finally, create a new user that will have read-write access only to that bucket. They can now login and use the web UI for uploading and managing the files.
Answer: You can use CrossFTP or CloudBerry
both will work like FTP client.


selecting hierarchical select values during migration

Question: I want to select the values of a taxonomy which is being shown by heirachical select. These values are to be selected while importing the data through csv by  using migration module.
right now i am passing the values but it not picking up the hierarchical select list.
Any help would be useful..
thanks
Comment: HS stores the config in variables with names like `hs_config_taxonomy-x` where `x` is the vocabulary ID. I haven't used migrate but maybe you can migrate variables as well?
Comment: Could you please point out how can we migrate taxonomy, seems like i was migrating taxonomy by using field mapping only.
    $this->addFieldMapping('field_user_class', 'user_class')
      ->defaultValue('')
      ->description(t('The class name for the user'));
Answer: Dunno why my last message has been deleted but well I founded the answer alone :
In order To make it work, you have to pass an array of values containing the terms tid values and their parent's tid.
You might have to use a callback that retrieve the parent tid from the children one.
I am migrating contents from drupal 6 to 7, not from a csv, but I've declared a static function containing the mapping between the old tids and the new ones like so :
public static $hierarchicalThemesToTheme1TidsMap = array(
  '1'     => array('tid' => '13', 'parent' => '0'),
  '1797'  => array('tid' => '14', 'parent' => '13'),
  '14993' => array('tid' => '15', 'parent' => '13'),
  '1801'  => array('tid' => '16', 'parent' => '13'),
  '59'    => array('tid' => '17', 'parent' => '13'),
  '1795'  => array('tid' => '18', 'parent' => '13'),
  '1796'  => array('tid' => '19', 'parent' => '13'),
  '1798'  => array('tid' => '24', 'parent' => '13'),
  '1799'  => array('tid' => '23', 'parent' => '13'),
  '1811'  => array('tid' => '42', 'parent' => '0'),
  '1812'  => array('tid' => '42', 'parent' => '0'),
  '1813'  => array('tid' => '42', 'parent' => '0'),
  '1800'  => array('tid' => '20', 'parent' => '42'),
  '1802'  => array('tid' => '21', 'parent' => '42'),
  '1803'  => array('tid' => '22', 'parent' => '42'),
  '1804'  => array('tid' => '18', 'parent' => '13'),
  '1805'  => array('tid' => '18', 'parent' => '13'),
  '62'    => array('tid' => '25', 'parent' => '0'),
  '1806'  => array('tid' => '26', 'parent' => '25'),
  '1807'  => array('tid' => '27', 'parent' => '25'),
  '64'    => array('tid' => '28', 'parent' => '25'),
  '1808'  => array('tid' => '29', 'parent' => '25'),
  '1809'  => array('tid' => '30', 'parent' => '25'),
  '61'    => array('tid' => '32', 'parent' => '0'),
  '1723'  => array('tid' => '33', 'parent' => '32'),
  '1724'  => array('tid' => '34', 'parent' => '32'),
  '1725'  => array('tid' => '35', 'parent' => '32'),
  '1726'  => array('tid' => '36', 'parent' => '32'),
  '1727'  => array('tid' => '37', 'parent' => '32'),
  '1728'  => array('tid' => '38', 'parent' => '32'),
  '1729'  => array('tid' => '39', 'parent' => '32'),
  '1730'  => array('tid' => '40', 'parent' => '32'),
  '1731'  => array('tid' => '41', 'parent' => '32'),
  '1810'  => array('tid' => '43', 'parent' => '13'),
  '4401'  => array('tid' => '44', 'parent' => '13'),
);

I had to do that because we didn't use migrate for the taxonomies. I guess there's a better way if you had use migrate to import your taxonomies.
Then I've declared a callback which use that static array to retrieve the tids and their parent tid :
public function getHierarchicalThemeByTids($tids) {
  $mapped_tids = array();

  foreach($tids as $tid) {
    $mapped_tid = FOMigration::getMappedId(self::$hierarchicalThemesToTheme1TidsMap, $tid, NULL);
    if($mapped_tid !== NULL) {
      $mapped_tids[] = $mapped_tid['tid'];
      if (!in_array($mapped_tid['parent'], $mapped_tids)) {
        $mapped_tids[] = $mapped_tid['parent'];
      }
    }
  }
  return $mapped_tids;
}

Finally I just tell migrate he has to use that callback to get the values :
$this->addFieldMapping('field_types', 'field_theme')->callbacks(array($this, 'getHierarchicalThemeByTids'));
$this->addFieldMapping('field_types:source_type')->defaultValue('tid');


Problem Dealing w/ Optimization

Question: this problem in my Calc one class is really giving me a hard time. Any help would be much appreciated.
Find the number of units that must be produced and sold in order to yield the maximum profit, given the following equations for revenue and cost:
$R(x)= 20x - 0.5x^2$
$C(x)= 7x + 4$
Comment: Profit = Revenue - Cost. Set up a formula for profit in terms of units produced.
Answer: Hint: Profit is revenue - cost. Write this in terms of R(x) and C(x). Look at the profit function's derivatives and recall the rules you've been given for finding global maximums
Answer: Okay! Thank you guys very much.
Here's what I got:
$R'(x)= 20 - x$
$C'(x)= 7$
$R'(x)= C'(x)$
$20 - x= 7$
$x= 13$
Okay thanks. That turned out to be a pretty simple problem. Just another one I over analyze.

Problem Dealing w/ Optimization


É possível adicionar uma condicional às opções de uma combobox? VBA

Question: 0
Estou desenvolvendo um formulário pelo UserForm do VBA e gostaria de gerar uma condicional nele.
Tenho duas ComboBox. A primeira permite escolher entre apenas dois casos, o A e o B. Gostaria que a segunda apresentasse um set de opções diferentes dependendo da escolha do usuário da primeira comboBox, A ou B.
Exemplo: Caso o usuário escolha A na comboBox 1, a comboBox 2 pode ser preenchida com os numeros de 1 a 10. Caso ele escolha B na comboBox 1, a comboBox 2 pode ser preenchida com os numeros de 20 a 30.
Answer: Ola Leandro segue o exemplo. Mas gostaria de avisa-lo que este é um problema simples e peço que tome um pouco mais de tempo procurando pela solução. É muito provavel que esta solução/pergunta seja fechada em detrimento a ser um codigo onde não adc. a comunidade. (fique aqui claro que não falo pela Stackoverflow) Espero que entenda que não quero apontar e nem criticar ninguem, somente um aviso.
No mais desejo lhe sorte!
<code>Private Sub cmb_Set01_Change()
    cmb_Set02.Clear

    If cmb_Set01.Value = "A" Then
        cmb_Set02.AddItem "1"
        cmb_Set02.AddItem "2"
        cmb_Set02.AddItem "3"
        cmb_Set02.AddItem "4"
        cmb_Set02.AddItem "5"
    ElseIf cmb_Set01.Value = "B" Then
        cmb_Set02.AddItem "6"
        cmb_Set02.AddItem "7"
        cmb_Set02.AddItem "8"
        cmb_Set02.AddItem "9"
        cmb_Set02.AddItem "10"
    End If

End Sub

Private Sub UserForm_Initialize()

    cmb_Set01.AddItem "A"
    cmb_Set01.AddItem "B"

End Sub
</code>


Can explanatory variables be non-Gaussian?

Question: I am conducting a logistic regression. However, the Shapiro-Wilk test has determined that one of the X variables is non-Gaussian.
Do the explanatory (X) variables need to be Gaussian? If so what are the usual transformations that can be done?
Comment: There's no distributional requirement on the explanatory variables (IV's, $x$'s) in logistic regression or any other GLM, nor in ordinary regression. Even when you are in a situation where something is assumed to be Gaussian, conditioning your analysis on a formal hypothesis test isn't necessarily helpful. It doesn't really answer a useful question (the useful question is about impact on your analysis -- and the hypothesis test really doesn't answer that).
Comment: Things like: how much the violation of these assumptions might bias coefficients or standard errors, change significance levels from their intended values, reduce power, impact coverage of, or width of, confidence or prediction intervals. In fact you're *most able* to reject normality exactly when it matters the least... when sample sizes are large.
Comment: Further, such a conditional approach (test normality and choose a procedure making a normal assumption conditional on failing to reject the hypothesis test) *itself* has an impact on those things.
Comment: When you say impact on the analysis, what would you be referring to?
Answer: Regression models are typically set up to model the conditional mean $E(Y|X=x)$, or some function thereof (for logistic regression, you are modeling the logit of $E(Y|X=x) \equiv P(Y=1 | X=x)$).
The implication of modeling the conditional mean is that the predictors $X$ are viewed as fixed, not random, so that one makes no assumptions about their distributions. This is in contrast to the outcome $Y$, whose (assumed) distribution plays an important role in determining which model to fit and which assumptions to make.
There are, however, some instances where you might want to transform the $X$ value:
1) It is scientific convention to report effect sizes on the transformed scale (e.g., $X$ is temperature in Fahrenheit but it is more usual to report the effect of a one-degree Celsius change on the outcome of interest).
2) The conditional mean (or function thereof) is better described as a linear function of the transformed $X$ than on the original scale (e.g., for linear regression, a straight line fits the scatterplot of $Y$ vs. $\log(X)$ better than one of $Y$ vs. $X$).


Entity Framework: Como realizar o insert de uma tabela com relação 1..n sem que os filhos também sejam inseridos?

Question: Estou utilizando Dotnet Core 3.1 com EF Core.
Possuo três classes em meu contexto:
public class Sale
{
    public Sale()
    {
        this.Cars = new List<Car>();
        this.CarSeller = new Seller();
    }

    [Key]
    public int Id { get; set; }
    [Required]
    public DateTime Date { get; set; }
    [Required]
    public ProcessStatusEnum Status { get; set; }
    [Required]
    public Seller CarSeller { get; set; }
    public virtual List<Car> Cars { get; set; }

}

public class Car
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Brand { get; set; }
    [Required]
    public string Type { get; set; }
    [Required]
    public int Year { get; set; }
    [Required]
    public string Fabrication { get; set; }
    public Sale Sale { get; set; }

}

 public class Seller
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Cpf { get; set; }
    [Required]
    public string Email { get; set; }

}

A minha dúvida está ocorrendo quando tento inserir uma nova venda:
 public ActionResult<int> SaveVehicleSale(SaleDTO newSale)
    {
        try
        {
            newSale.Id = 0;
            newSale.Status = ProcessStatusEnum.ConfirmingPayment;

            if (Functions.IsAnyNullOrEmpty(newSale))
                new ApiException(StatusCodeEnum.BadRequest, MsgException.ObjectAtributeNull);

            _context.Sale.Add(ConvertType.To(newSale)); //Converte o SaleDTO para o Sale
            _context.SaveChanges();

            return _apiResponse.ResponseRet<int>(StatusCodeEnum.OK, newSale.Id);
        }
        catch (ApiException e)
        {
            return _apiResponse.ResponseRet<int>(e);
        }
        catch (Exception e)
        {
            return _apiResponse.ResponseRetWithoutEnumerable(e);
        }
    }

Ao inserir, ele também está tentando adicionar um novo Carro. Como faço para ele apenas referenciar um carro já existente? Isso já ocorre com a Classe Seller, mas não sei como fazer isso com um tipo List<>.
Agradeço muito, desde já!
Comment: se Carro já existe, pode recuperar para que o EF tenha track disso: algo assim (vou fazer o exemplo como se fosse um objeto só): `newSale.Carro = carroContext.Get(newSale.Carro.Id)`
Comment: Entendi. Irei tentar isso daqui a pouco, obrigado!
Comment: Funcionou perfeitamente, muito obrigado!
Comment: @RicardoPontual posta essa resposta para não deixarmos essa pergunta em aberto
Answer: Você precisa informar ao EF que o(s) carro(s) já existe(m) (dar um tracking no EF). Você deve atribuir os carros na lista public virtual List<Car> Cars { get; set; } da classe Sale.


rails how can you convert / to \ in a file name

Question: I am working on selecting files to email and then passing them to the user's notes email client.
The string I want to send to the system command should be in the format of:

"C:\Program Files (x86)\IBM\Lotus\Notes\notes.exe"
  Mailto:email@example.com?Subject=MailSubject?Attach=C:\test.bat

However, the code
<code> $attached_files =   $attached_files + "?Attach="+ Rails.root.to_s + "/public/images/" + document.id.to_s + "/" + document.doc_file_file_name
</code>
gives me forward slashes instead:

C:/Users/cmendla/RubymineProjects/technical_library/public/images/2/High_Durability.pdf

When that is passed to system() it won't launch the notes email. I think that the problem is that the server looks for / and the windows pc looks for \
Is there any way to easily change / to \ at least for the time being for testing?
Comment: you could try `$attached_files.gsub! '/', '\'` but I thought Rails was aware of what it is running on.
Answer: Have you tried
<code> Rails.root.join("public","images", document.id, document.doc_file_file_name)
</code>
?


What's the difference between tag.class and tag .class?

Question: What's the difference between
tag.class and tag .class
or
tag#id and tag #id?
Answer: tag.class matches all elements with name tag and with the class class, e.g.:

div.foo { color: red; } matches

tag .class matches all .class elements that are descendants  of tag elements (note the space between tag and .class):
(Remember that "descendants" includes all children, their children, and so on - whereas, in comparison, the > (child selector) only selects immediate children and not any grandchildren.)

div .foo { color: red; } matches the  in

tag#id and tag #id are similar to the above, except matching on the id attribute instead of the class attribute[1]

div#foo { color: red; } matches

div #foo { color: red; } matches the  in

Remember that because id="" attributes are meant to be unique that additional selectors may be superfluous, e.g. div#bar could be simplified to just #bar (unless you're reusing the same CSS rules on different pages where #bar may have different element tag names).
[1]: This is true in HTML, in other SGML and XML languages using CSS the .class and #id selectors can be mapped to other attribute names.
Answer: tag.class would mean a tag with class='class'. Something like this:

<tag class="class">
    ...
</tag>

tag .class would mean an element whose class='class', and is a descendant of a <tag>. Something like this:
<tag>
    ...

    ...
</tag>

In general, something like selector1 selector2 would mean an element that matches selector2 and is a descendant of an element that matches selector1. Consider this example:
CSS:
/*
   div.face matches a div with class="face"
   div.eye#left matches a div with class="eye" and id="left"

   Hence, this would select an element with class="eye" and id="left" which is
   inside a div with class="face"
*/

div.face div.eye#left {
}

HTML:

Comment: Descendant, not child. `tag > .class` would be a child.
Answer: Space () is a descendant selector, see documentation: http://www.w3.org/TR/CSS2/selector.html#descendant-selectors
Long story short tag.class applies to a tag element with class class, whereas tag .class applies to any elements with class class that are within tag element.


How to get the full host name in Javascript including HTTP?

Question: I have a problem with getting the host name in Javascript, I have used the code below:
document.location.replace("http://"+ document.location.host + "/another-page")

The code works fine, it gets the host name and replaces the documents URL with the new one.
The problem is with the document.location.host, it only returns the host like this: www.xxx.com without the http part. This is not a scalable way of doing it, cause locally the site runs on http and on the server it runs on https. I don't want to manually change the http part.
So is there a better sollution to automaticly get the full name of a host including http(s)?
Answer: is this location.origin what you are looking for?
or you can get protocol only using this location.protocol
See more here - https://developer.mozilla.org/en-US/docs/Web/API/Location

console.log('location.protocol -', location.protocol);
console.log('location.origin -', location.origin);


Proof that addition preserves order

Question: Definition: Let $a$ and $b$ be natural numbers. We say that $a \geq b$ (or $b \leq a$) iff we have $a = b + m$ for some natural number $m$.
Claim: $a \geq b$ iff $a + c \geq b + c$ for any natural number $c$.
Proof: We must show that $\forall c, (a \geq b \implies a + c \geq b + c)$ and that $\forall c (a + c \geq b + c \implies a \geq b)$
First we prove $a + c \geq b + c \implies a \geq b$. By definition, $a + c = b + c + m$ for some natural number $m$. By cancellation law, $a = b + m$ which means $a \geq b$.
Next we prove $a \geq b \implies a + c \geq b + c$. We induct on $c$. When $c=0$, we see that $a \geq b \implies a + 0 \geq b + 0$ which is true. During the inductive step we assume $a \geq b \implies a + c \geq b + c$ and need to show that $a \geq b \implies a + c + 1 \geq b + c + 1$. I'm not 100% sure where to go from here.
Edit: Maybe this: $a + c + 1 \geq b + c + 1$ means $a + c + 1 = b + c + 1 + m$ for some $m$. By cancellation law, $a = b + m$. Therefore $a \geq b \implies a + c \geq b + c = a \geq b$ which is true. I guess this also means we didn't need induction since I didn't even use the inductive hypothesis.
Comment: $$\small\forall m\in\Bbb N~a\geq b\iff a+c=b+c+m\iff a+c+1=b+c+1+m\iff a+c+1\geq b+c+1$$
Answer: Suppose that $a\geq b$, then $a=b+m$ for some natural $m$. If $c\in\mathbb{N}$, then $a+c=b+c+m$, so $a+c\geq b+c$, because $m\in\mathbb{N}$, and the definition is met. No need for induction.
Comment: Is there a name for this? I can show the cancellation law with induction but I don't know if there's something for the reverse of this (adding a number to both sides of an equality)
Comment: @user525966 If $a=b+m$, then $a+c=(b+m)+c=b+c+m$. For these simple properties of group operations, induction is not necessary (since they don't only apply in the ring of integer numbers, and induction doesn't exist elsewhere). If your hypothesis is that two objects are equal, then those objects are interchangeable everywhere, from where follows the equality above.
Comment: @user525966 If $a=b$ then you can get $a+c=b+c$ as follows: it is a logical truth that $a+c=a+c$, and so if $a=b$ you can substitute $b$ for the second $a$ in $a+c=a+c$ to get $a+c=b+c$
Answer: If $a \ge b$ then $a= b+m$ for some $m$.
But since $a+1=a+1$ we thus have that $a+1= b+m+1 =b+1+m$, and so $a+1 \ge b+1$
Comment: Is this technically an inductive argument? (I also edited my post, not sure if that resolves the issue any)
Comment: @user525966 I wrote just the step of the inductive argument.  And it's true that  you don't need induction for this one.
Comment: I'm not sure how you do it without induction though, unless there's an anti-cancellation law (the cancellation law I used induction for)
Comment: @user525966 Yes, you will need induction for the cancellation law, but pnce you have that, this proof of addition preserving order does not need induction. ... not sure what you mean by 'anti-cancellation' ....
Comment: Cancellation meaning you remove the same quantity from both sides, anti-cancellation (or whatever it would be called) being that you add a quantity to both sides.
Comment: @user525966 Oh! I just explained in the comment below Alvaro's post that that is trivial!

Proof that addition preserves order


rails, rest, render different action with responds to

Question: Maybe my logic is not restful or know if this is how you would do it but this is what I am trying to do.
I'm getting a category inside a category controller and then once I get that category I want to return to an index page in a different controller but keep that @category and the Category.busineses.
Before rest I would have just done this:
render :controller => "businesses"
and it would have rendered the view of the index action in that controller.
now in my respond_to block I have this
   format.html {redirect_to(business_path)} # index.html.erb
   format.xml  { render :xml => @businesses }

but of course with a render it looses the instance variable and starts with a new action.
So what I want to do is render the action instead of redirecting to that action.
is this possible?
Should i just replace the respond_to with render :controller => ?
Comment: Sam, you mean `render :action => "foo"`? Your explanation is very confusing.
Comment: +1 to confusing q ... :P
Comment: I'm sorry for the confusing part but rest is a whole new paradigm for me and I'm not sure where to start
Answer: I think what you are trying to do (if I understand it correctly) would be best achieved using nested resources. If there are businesses separated into categories, and you want to display a listing of all businesses in a specific category, you could set up your application like this:
Models
class Category < ActiveRecord::Base
  has_many :businesses
end

class Business < ActiveRecord::Base
  belongs_to :category
end

Routes
map.resouces :businesses

map.resources :categories do |categories|
  categories.resources :businesses
end

Controller
class BusinessesController < ApplicationController
  def index
    @category = Category.find(params[:category_id]) if params[:category_id]
    conds = params[:category_id] ? { :category_id => params[:category_id] } : nil
    @businesses = Business.all(:conditions => conds)
  end
end

Then simply access the list of a category's businesses like this: /category/1/businesses
Comment: @Sam - Check out my edit for an example of how to use the same action for both `/businesses` and for `/category/1/businesses`.
Comment: so what about if I just want to get the index action with a full list of businesses not by categories. check for params[:category_id] ?
Comment: Thanks really great. BTW - What do you think is the best resource for learning rest on rails?
Comment: The guide on the official site is quite good if you haven't seen it already: http://guides.rubyonrails.org/routing.html There are also several good Railscasts in the routing category including nested routing and custom REST actions: http://railscasts.com/tags/14
Comment: def index is missing a closing parenthesis on params[:category_id]
Answer: I am not 100% clear of what you are trying to do, but you have several options for presentation in a RESTful app.
You can pass a parameters in a redirect. In this case we pass the category id as a parameter in the HTTP GET. The page on the end of the redirect can then handle this appropriately:
format.html {redirect_to( business_path(:category_id => @category.id) }

You can also render the view of a specified action or template. In this case we render the view defined in "{current_controller}/business.html.erb":
format.html { render :action => "business" }

Comment: format.html { render :action => "index" } was what I was looking for
Answer: You cann't use redirect_to if you want instance variable as it is use render as follows.
format.html { render :controller=> 'buisness'  ,:action => "index" }

OR JUSt
format.html { render :controller=> 'buisness'}

Comment: it's ok Sam. but remember format.html { render :action => "business" }
as in Toby's Answer must be format.html { render :controller => "business" } otherwise it will look for the page at the categories/buisness.html.erb. I know it's just typo or may be in hurry but take a look at it. else is fine.
Comment: Thanks, that was what I was looking for. I think you answered just after Toby otherwise I would have given you the check instead of a vote


Is there a way to call model while creating controller in laravel?

Question: I want to make 'use App\Models\Model-name' in any controller i create..is there a way to do this ?!
I searched for this and found something like use auto-load file but didn't get the idea.
Comment: Can you explain a little more? Extending a controller that has this won't do it?
Comment: Hello, You want to have a global acces to a model across all the controllers instead of calling it one by one or you want the controller to have the model defined at the controller when you create it?
Comment: @kerbh0lz I want to when i creating new controller,,In this controller i want to use the model that related to this controller like this 'use App\Models\ModelName'.
Comment: @DanielaC.Montenegro yes the second one i want.
Comment: We're not discussing IDEs, OP was trying to get the single line command. He can declare them manually if he needs more models.
Answer: Yes this is possible! As per the Laravel documentation, you can use the following command:
php artisan make:controller PhotoController --resource --model=Photo
Comment: @onlineThomas Yes but it will "use App\Photo" (or whatever the model is) when you create the controller. If the model already exists, it will not create another model.
Comment: That's about creating the model at the same time as the controller, not using a model in all controllers.
Comment: @onlineThomas Exactly that what i looking for.
Comment: @SawyerClever Thanks for help but not this what i looking for.
Comment: @AhmedHassan If that is _not_ what you're looking for you need to edit your question and be more specific in what you actually want. "_yes the second one i want_" That's what this answer solves.
Answer: To declare a controller with the model try:
php artisan make:controller YourModelController --model=Models/YourModel


Alguém poderia me ajudar a enxergar onde estou errado na minha alocação de fila

Question: #include <stdio.h>
#include <stdlib.h>

typedef struct _fila {
   int ini;
   int fim;
   int tam;
   int *vetor;
} Fila;

Fila* criar_fila (int tamanho) {
   Fila* fila = (Fila *) malloc (tamanho*sizeof(int));
   fila->ini = 0;
   fila->fim = 0;
   fila->tam = tamanho;
   fila->vetor[fila->tam];

   return fila;
}

void destruir_fila (Fila *f) {
   free(f->vetor);
   free(f);
}

void enqueue (Fila *f, int elemento) {
    if (f->fim < f->tam){
        f->vetor[f->fim] = elemento;
        f->fim++;
    }
}

int dequeue (Fila *f) {
   int elemento = f->vetor[f->ini];
   f->ini++;
   return elemento;
}

int main () {

   /*Inicializando a estrutura de dados fila!*/
   Fila *fila = criar_fila (10);

   /*Tentando inserir o elemento 1 na fila!*/
   int elem = 1;
   enqueue (fila, elem);

   /*Tentando inserir o elemento 2 na fila!*/
   elem = 2;
   enqueue (fila, elem);

   /*Tentando inserir o elemento 3 na fila!*/
   elem = 3;
   enqueue (fila, elem);

   /*Tentando inserir o elemento 4 na fila!*/
   elem = 4;
   enqueue (fila, elem);

   /*Tentando retirar e imprimir o elemento 1 na fila!*/
   printf("%d\n", dequeue (fila));

   /*Tentando retirar e imprimir o elemento 2 na fila!*/
   printf("%d\n", dequeue (fila));

   destruir_fila (fila);

   return 0;
}

Estou retornando fila, no método criar_fila(int tamanho) , porém está compilando mas da Segmentation fault.
Comment: Na função `criar_fila` você faz `fila->vetor[fila->tam]`, mas o que isso deveria fazer? Se o vetor é também um ponteiro, não deveria alocar a memória dele também?
Answer: O problema ocorre em dois lugares, dentro da sua função criar_fila.
O primeiro é o fato de estar fazendo a alocação de memória suficiente para uma certa quantidade de ints, mas não para a sua estrutura Fila:
Fila* fila = (Fila *) malloc (tamanho*sizeof(int));

Sendo que o correto seria:
Fila* fila = (Fila *) malloc (sizeof(Fila));

Veja que removi a variável tamanho também da alocação de memória da sua estrutura Fila. Como está usando apenas uma estrutura com um vetor dentro não precisa alocar memória suficiente para 10 (dez) estruturas, apenas uma.
O segundo problema ocorre no uso do seu vetor a partir de um ponteiro. Veja que na função destruir_fila você tenta chamar free no seu vetor; mas em nenhum momento malloc foi chamado para alocar memória e permitir que seu ponteiro tenha para onde apontar:
Fila* criar_fila (int tamanho) {
   Fila* fila = (Fila *) malloc (sizeof(Fila));
   fila->ini = 0;
   fila->fim = 0;
   fila->tam = tamanho;
   fila->vetor[fila->tam];

   return fila;
}

Nesse caso, você pode inicializar seu ponteiro com o malloc e o tamanho que o vetor terá:
Fila* criar_fila (int tamanho) {
   Fila* fila = (Fila *) malloc (sizeof(Fila));
   fila->ini = 0;
   fila->fim = 0;
   fila->tam = tamanho;
   fila->vetor = malloc (tamanho * sizeof(int));

   return fila;
}

O resultado da execução do código agora é:
1
2

Comment: "não precisa alocar memória suficiente para 10 (dez) estruturas, apenas uma" técnica também conhecida como Rest Assurance Memory Allocation Pattern (https://desciclopedia.org/wiki/Gambi_Design_Patterns#Rest_Assurance_Memory_Allocation_Pattern)


How to connect to multiple Databases in Drupal 7?

Question: I'm building an encyclopedia website. There are about 20 subjects that must be stored in the Database (media,library,article,translations,...) and we want to create 20 databases and allocate one DB for every subject. is it possible to do such thing? The main site has 3 sub domains and every sub domain covers specific rows of the subjects. for example the library is a subject and math.mainsite.com must have access only to the math type of the library subject.
the sub-domains must not have not any data, they all should get their data from the 20 above mentioned DBs, so every site must connect to 20 DB.
We selected this strategy because the subjects are subdomain as well, I mean library.mainsite.com and article.mainsite.com and ... are valid urls.
thanks
Answer: Two steps:

Add database credentials to the $databases array in settings.php file. You can have as many additional databases as you want. Example code:
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_DEFAULT_DATABASE',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_second_db_alias' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_SECOND_DB',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Use the following code to change the database and run queries. Note that you must switch back to the original database afterwards.
// Change active database.
db_set_active('your_second_db_alias');
// Run queries.
$query = db_query("SELECT * FROM yourtable");
// IMPORTANT: return current active database to the default one. If you
// don't do this, everything after that point will be executed against the
// above database, and cause errors most probably. If you are connecting
// multiple Drupal installations, you can cause a pretty big mess if data is
// partially saved in the other database.
// Always double check that you have this line!
db_set_active();

Hope this helps!
Comment: If you are having issues with views and multiple DBs, post it as a separate question. Have a look at [this](http://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data) thread first.
Comment: So how do I can create views for different databases?
Comment: Aram - the linked thread is missing.
Comment: Well that page says that *This question was removed from Drupal Answers for reasons of moderation.*. I suggest posting your problem as a separate question.


The value at the integral lattice of a positive definite quadratic form is discrete

Question: A (real) quadratic form is a homogeneous plynomial of degree 2 (with real cofficients), in any number of variables. A quadratic form is positive definite if it is takes only nonnegative values. Now assume that $Q$ is a positive definite quadratic form of $n$ variables, then what I want to show is that $Q(\mathbb{Z}^n)$ is dicrete.
My idea is to assume that $Q(\mathbb{Z}^n)$ is not discrete then for any $\epsilon>0$ we can always find two distinct points $x,y\in\mathbb{Z}^n$ such that $0<|Q(x)-Q(y)|<\epsilon$ and then use this to make a contradiction with the fact that $Q$ only takes nonnegative value. But I do not know how to proceed. Thanks for any help.
Answer: Hint. Let $\lambda=\lambda_\min(Q)$. Then $\lambda\|v\|^2 \le Q(v)$ for every vector $v$. If some sequence $\{Q(y_n)\}$ converges to some $Q(x)$, eventually we must have $Q(y_n)\le 2\max(1,Q(x))$ and in turn
$$
\|y_n\|^2 \le \frac{2\max(1,Q(x))}{\lambda}.
$$
How many integer vectors are there inside any sphere?
Comment: I get it. Thank you very much.


Is there an easy for my authenticated users to search other authenticated users?

Question: I would like to allow my authenticated users the option to search through other authenticated users profiles (like when you allow people to change the filters on a view of content).
I've been searching through modules and documentation for a while now and can't seem to figure out how to solve this problem.
I was hoping that maybe their would be someway to create a view of users? Is that possible? If not, how can this be achieved?
Answer: There is a default user search. You can go to "your_site/search/user" to try that out. You can set the permissions at "admin/people/permissions" to allow only authenticated users to use this search.


difference in differences estimation using regression

Question: How do I differentiate between independent variables and control variable in difference in differences estimation using regression model.
Comment: What is the difference in your mind? These are usually synonyms.
Answer: Regardless of the model you're using, independent variables and control variables are the same. They're synonyms. If what you meant was what the difference between dependent variables and control variables, the dependent variable is the one whose behavior you want to study. In order to do that, you ask how this dependent variable changes as a result of changes in your independent/control variables.


Will fseek back to the previous location be faster than seeking to a new location?

Question: If I have a C code
off_t off = ftello(f);
fseeko(f, some_location);
// do some work
fseeko(off);

Is the second fseeko as slow as the first one? I had thought the file blocks are always cached, so the second one could be much faster.
In my profiling results on Linux, the second fseek takes similar cost. Is this expected?
Comment: It is not the seek that will be faster, but eventually next IOs...
Comment: Yes - It would be more surprising if it wasn't
Answer: In most implementations, the fseek call is almost free since all it does is set the position in the FILE object. The cost will be incurred when you actually read data. At that point, it is very likely that rereading an already read block will benefit from the buffer cache. But it is also quite possible that the OS is doing speculative read-ahead so that blocks following recently read blocks are also in the buffer cache (as could be the case with your second seek).
For writing, measuring times is even more complicated because the blocks written are not necessarily committed immediately to permanent storage; the write system call returns as soon as the data has been copied into the buffer cache.
Answer:
Is the second fseeko as slow as the first one?

It can be.
You see what you say about caching holds, but only cases where you deal with multiples of the FS block size.
I would suggest to read more in How is fseek() implemented in the filesystem?, since "The fseeko() function is identical to fseek(3)(see fseek(3)), respectively, except that the offset argument of fseeko().", as the ref suggests.


How to show if $H,K$ are normal subgroups in a group $G$ then $[H,K] \leq H \cap K$

Question: How to show if $H,K$ are normal subgroups in a group $G$ then $[H,K] \leq H \cap K$.
Here $[H,K]$ is the commutator subgroup.
I have tried to start it but instantly failed:
I want to show firstly that $[H,K]\subseteq H \cap K$ but I don't understand what an arbitrary element of $[H,K]$ would even look like so I have something to work on.
I thought it could look something like $h^{-1}k^{-1}hk$ but then I thought that we are working with the smallest subgroup containing elements of this form but that might not be what the actual elements are?
Could anyone help?
Comment: It is sufficient to show that $h^{-1}k^{-1}hk \in H \cap K$ for all $h \in H$, $k \in K$. If the generators of a subgroup all lie in $H \cap K$ then so does the subgroup itself.
Answer: Recall that:
$$[H,K] = \langle [h,k] = hkh^{-1}k^{-1}\ |\ h\in H,\ k\in K\rangle.$$
It suffices to show that the generators of $[H,K]$are contained in $H$ and $K$. From the above, a typical generator of $[H,K]$ looks like $hkh^{-1}k^{-1}$. Since $K$ is normal, you have $hkh^{-1} = k'$ for some $k'\in K$. Hence,
$$hkh^{-1}k^{-1} = k'k^{-1}\in K.$$
Can you take it from here?
Comment: Okay so we apply the same argument to get $hkh^{-1}k^{-1}=hh' \in H$ in particular it is in both $H$ and $K$ so it would be in $H \cap K$?
Comment: @RyanS This follows from the fact that $H$ and $K$ are subgroups. By the above, if $a,b\in [H,K]$, then $a,b\in H$ and $a,b\in K$. Hence, $ab\in H$ and $ab\in K$. Therefore $ab\in H\cap K$. Since any product of generators of $[H,K]$ is in $H\cap K$, all of $[H,K]$ must lie in $H\cap K$.
Comment: Thanks I think I get it now!
Comment: @RyanS Happy to help!
Comment: Can I ask one last question now we have shown it is a subset is it automatically a subgroup of $H \cap K$ since $[H,K]$ is a subgroup of $G$ by definiton?
Comment: @RyanS That's absolutely right.


Check if Git repo correctly setup

Question: One of our clients has an already existing git repository.
Are there some steps to follow to check if this repository is setup correctly?
Thanks,
Answer: Simply start to work with it.
Add files, commit and push them.

Verify that the central repository is opened to external users
Verify to see if the user has access to the central repo
Verify that the user has the required settings: (username,email ssh keys etc)
Push commits to see if you have the git users has write access to the files

Basically you need to start work on it and verify that all the workflow is working.
Comment: Np. Usually the problems is not with the git setup (using Unix) but the read/write access to files and acess to the machie itself.

Check if Git repo correctly setup


How to find the conditional CDF based on observed data in R

Question: If we have two samples (generally their distribution is not known),say $X\sim N(0,1)$, $Y|X\sim N(X,X^2/2)$. Can we recover the conditional CDF of $Y|X$ based on the observed samples in R?
n=1000
x=rnorm(n)
y=rnorm(n,x,x^2/2)

Comment: conditional PDF and CDF can be estimated nonparametrically. There is supposedly at least one package available for those purposes.
Comment: Thank you for your kind comment! Do you have the reference for the method of nonparametric estimation and the R package?
Answer: You can't determine the CDF from samples, but you can easily get an empirical estimate:
set.seed(1359)
n <- 1000
x <- rnorm(n)
y <- rnorm(n, x, x^2/2)

LM <- lm(y ~ 0 + x) # no intercept because you know this, though usually you won't
coef(LM)

Gives me $\hat{\beta} = 1.076$, or $\hat{y} = 1.076 \cdot x + \epsilon$ (about $1\times x$, as you specified).
Similarly, you can get an empirical estimate of the standard deviation you supplied with sd(resid(LM)).

If you don't know anything about their distributions, you could try a non-parametric approach.
Comment: Thank you for your answer! Do you have the reference for the nonparametric approach?
Answer: Finding the conditional distribution of a variable $Y$ conditional on another observed variable $X$ is the entire subject matter of regression analysis (construed in its wide sense to include linear and nonlinear regression models, GLMs, GLMMs, etc.).  This is a huge subject and a core part of statistical education.  If you would like to learn more about it, I would recommend starting with some material on linear regression analysis, and then building up from there.


How to check if php mysqli_fetch_array is empty before while loop

Question: I wanted to make sure there are results before running the while loop but all the methods I am trying seem to remove the first result.
$nearbyResult = mysqli_query($con,$sqlNearby);

if(mysqli_fetch_array($nearbyResult) == 0) {
    echo '
No results found, Add your property here.
';
} else {
    while($rowNearby = mysqli_fetch_array($nearbyResult)) {
    }
}

Comment: IF you just just have one loop where you fetch the results, it won't go into the loop if they are no records fetched. There's no need to check if it is empty before the loop.
Comment: `if(mysqli_num_rows($con)){/*Code to execute if rows are returned*/}else{echo "Nothing to show!";}`
Answer: This line will take the first row of your result set and chuck it in the bin:
if(mysqli_fetch_array($nearbyResult) == 0) {

Change to:
if( ! mysqli_num_rows($nearbyResult) ) {

And check your freakin function returns:
if( ! $nearbyResult = mysqli_query($con,$sqlNearby) ) {
    echo "Mysql error: " . mysqli_error($con);
}

Comment: Probably shouldn't do page echoing right in the middle of some data access code, but yes.. check your data returns...
Answer: You can use the mysql_row_count method to count how many rows are returned in your query http://php.net/manual/en/mysqli-result.num-rows.php
Answer: Try assigning the results to a variable as part of your if statement.  If mysqli_fetch_array() has no result set to work with it will return false.
if($rowNearby = mysqli_fetch_array($nearbyResult)) {
    //There was a result, work with it here
    doStuffWith($rowNearby);
} else {
    //No records in your result set, handle as desired
}


How to feed image sequences to convolutional layers and apply conv-lstm cells after?

Question: I'm currently trying to implement the following paper: https://research.nvidia.com/sites/default/files/publications/dnn_denoise_author.pdf
I have troubles in adapting my network, which currently processes only single images, to processing image sequences.
My data has the following shape: (7, 512, 512, 1), where 7 is the number of frames in my sequence, 512 is the width and height of an image and 1 the number of channels.
My question is how to pass a sequence through convolutional layers? (the conv3d suggestion that I saw for other questions of this type seems weird, since I have 7 frames).
Then, I wish to pass the result of the convolutional layers to a ConvLSTM block, however, is this even possible given the feature maps obtained after convolutions and maxpooling? (Other answers for using ConvLSTM block refer only to applying them on the sequence directly). The result of this operations will be again fed to convolutions and maxpooling and so on.
I have also checked the other questions involving CNN and RNN and I was thinking of using the TimeDistributed(...(...)) type of functions, but I am not sure if I'm going in the right direction. Any piece of advice is more than welcomed.
Thank you for your time!
Answer: I am facing similar situation where I have n frame sequence and I would like to predict the next frame after given sequence, the solution would be to forward image n through network and get loss from frame n+1 and repeat(n+1, n+2 etc.). Hope I understand this right.
Comment: For my first question, I took after the answer from this: https://stackoverflow.com/questions/50786077/how-to-feed-batched-sequences-of-images-through-tensorflow-conv2d . However, I am not sure if it's what you need, if you want to forward one image from a sequence at a time..


Exibir imagem salva em BLOB

Question: Gostaria de saber como faço para exibir uma imagem salva no banco de dados em BLOB:
codigo:
$nome = $_POST["nome"];
$preco = $_POST["preco"];
$cor = $_POST["cor"];
$descricao = $_POST["descricao"];

if(is_uploaded_file($_FILES['imagem']['tmp_name']))
{
 $imgData = file_get_contents($_FILES['imagem']['tmp_name']);
 $sizeData = getimagesize($_FILES['imagem']['tmp_name']);
 $imagem = $imgData;
}
if(insereProduto($conexao, $nome, $preco, $imagem, $descricao, $cor)) {

    ?>
Produto  <?=$nome ?>, que custa <?=$preco?> adicionado com sucesso!
<?php

}

function insereProduto($conexao, $nome, $preco, $imagem, $descricao, $cor) {
   $query = "insert into produtos (nome, preco, imagem, descricao, cor) values
   ('{$nome}', '{$preco}','{$imagem}', '{$descricao}','{$cor}')";
   echo $query;
   $resultadoDaInsercao = mysqli_query($conexao, $query);
   return $resultadoDaInsercao;
}

Comment: Possível duplicada de http://pt.stackoverflow.com/questions/48325/slideshow-com-imagens-blob-do-mysql
Answer: Para exibir imagens a partir do BD você tem que alterar o header da página para o navegador entender que é uma imagem. Para tal crie um arquivo gera.php que será responsável por gerar a imagem de forma que o navegador a entenda como imagem e chame essa página no atributo src da tag html img. Dessa forma:
Gera.php
  <?
//RECEBE
PARÂMETRO
$id = $_GET["id"];

//CONECTA
AO MYSQL
$conn = mysqli_connect("localhost", "usuario",
"senha", "base de dados ");

//EXIBE
IMAGEM
$sql = mysqli_query($conn, "SELECT foto,tipo FROM
fotos WHERE id = ".$id."");

$row = mysqli_fetch_array($sql,
MYSQLI_ASSOC);
$tipo = $row["tipo"];
$bytes = $row["foto"];

//EXIBE
IMAGEM
header("Content-type: ".$tipo."");

echo $bytes;
?>

Exibir:
  echo "<img src="gera.php?id=".$id.""";

Answer: vc tem pode printar diretamente na imagem codificando em base64
echo base64_decode($data);
echo '';

onde o $data he a imagem que veio direto do db
Comment: Pra isso funcionar: `echo '';` (**caso o BLOB não esteja codificado em base64**) ou `echo '';` (**caso o BLOB esteja codificado em base64**). Nenhuma das duas formas precisa do `echo base64_decode($data);`.

Exibir imagem salva em BLOB