Column header background color changing when scrolling vertically in a DataGrid Material UI

Question: I'm working in a React(NextJS) project using material UI. I have some tables (DataGrid component from material UI) with different background colors in the column headers like this:

My problem is when I scroll horizontally very fast (not slowly but very fast), the color moves 1 space/column, so in the previous image you can see that the column "rank" for example, should be yellow and if I scroll horizontally very fast, it changes to red:

As you can see the colors move 1 space/column, this seems like a material UI bug to me but I'm not sure...
This is my React component:
import React, { useState, useEffect } from 'react'
import { css } from '@emotion/react'
import PropTypes from 'prop-types'
import { cardCss } from '../CavMortal/grid/Grid'
import { fullHeight } from '../CavMortal/ScoreItem'
import { CardElevation } from '@findep/mf-landings-core'
import Grid from '@material-ui/core/Grid'
import { DataGrid } from '@mui/x-data-grid';
import { splitString} from '../../helpers/splitString'

const customCardCss = css`
  ${cardCss}
  ${fullHeight}

  & [class*="MuiCardContent-root"] {
      ${fullHeight}
  }
`

function TablaSubdireccion({ dataSubdirecciones, headerStyles }) {
  const [columnsName, setColumnsName] = useState([])
  const [rows, setRows] = useState([])

  const getColumns = () => {
    let columns = []
    for(let i = 0; i < dataSubdirecciones.length; i++){
        for(let j = 0; j < dataSubdirecciones[i].datosAgrupadorList.length; j++){
          columns.push({
            field: dataSubdirecciones[i].datosAgrupadorList[j].nombreDato,
            headerName: dataSubdirecciones[i].datosAgrupadorList[j].nombreDato,
            width: 130,
            renderHeader: (params) => (

                {
                  splitString(dataSubdirecciones[i].datosAgrupadorList[j].nombreDato).map((word) => (
                    <React.Fragment key={word}>
                      {word}

                    </React.Fragment>
                  ))
                }

            ),
          })
        }
    }
    return columns
  }

  const getRows = () => {
    let rows = []
    for (let i = 0; i < dataSubdirecciones.length; i++) {
      let rowData = { id: i }
      for (let j = 0; j < dataSubdirecciones[i].datosAgrupadorList.length; j++) {
        rowData[dataSubdirecciones[i].datosAgrupadorList[j].nombreDato] = dataSubdirecciones[i].datosAgrupadorList[j].valorDato
      }
      rows.push(rowData)
    }
    return rows
  }

  useEffect(() => {
    setColumnsName(getColumns())
    setRows(getRows())
  }, [dataSubdirecciones])

    return(
        <Grid item css={css`flex-grow: 1;`}>

            <CardElevation fullWidth noPadding css={customCardCss}>
              <DataGrid
                sx={headerStyles}
                rows={getRows()}
                columns={getColumns()}
                hideFooterPagination={true}
                hideFooter={true}
                headerHeight={50}
                pageSize={10}
              />
            </CardElevation>

        </Grid>
    )
}

TablaSubdireccion.propTypes = {
  dataSubdirecciones: PropTypes.array,
  headerStyles: PropTypes.object,
}

export default TablaSubdireccion

And this is the object headerStyles, which is received as props and contains the colors for every nth child/column:
const MAIN_TABLES_HEADER_STYLES = {
  '& .MuiDataGrid-columnHeaderTitleContainer': {
    lineHeight: 1.5,
  },
  '.MuiDataGrid-columnSeparator': { display: 'none' },
  '&.MuiDataGrid-root': { border: 'none' },
  '& .MuiDataGrid-columnHeader:nth-child(1)': {
    backgroundColor: '#000000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(2)': {
    backgroundColor: '#000000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(3)': {
    backgroundColor: '#9e9e9e',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(4)': {
    backgroundColor: '#9e9e9e',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(5)': {
    backgroundColor: '#9e9e9e',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(6)': {
    backgroundColor: '#9e9e9e',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(7)': {
    backgroundColor: '#6f0000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(8)': {
    backgroundColor: '#0075ad',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(9)': {
    backgroundColor: '#d20000',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(10)': {
    backgroundColor: '#ffd600',
    color: '#000000',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(11)': {
    backgroundColor: '#ffd600',
    color: '#000000',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(12)': {
    backgroundColor: '#ffd600',
    color: '#000000',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(13)': {
    backgroundColor: '#70b7bc',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(14)': {
    backgroundColor: '#70b7bc',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(15)': {
    backgroundColor: '#009f94',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(16)': {
    backgroundColor: '#1e9a00',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(17)': {
    backgroundColor: '#1e9a00',
    color: '#ffffff',
    fontWeight: 'bold',
  },
  '& .MuiDataGrid-columnHeader:nth-child(18)': {
    backgroundColor: '#1e9a00',
    color: '#ffffff',
    fontWeight: 'bold',
  },
}

Does anybody knows why this happens or how to fix it?
Thanks.
Answer: Using nth-child styling isn't going to be reliable when horizontal scrolling is in play. The data grid does virtualization of columns when you scroll horizontally, so not all columns are always being rendered which will then throw off the nth-child styling.
You can see this in action in this extreme example with 30 columns with customized colors on the 3rd and 4th via nth-child CSS selectors: https://codesandbox.io/s/horizontal-scrolling-tlmqeh?file=/demo.tsx.
In that example the styling is done similar to your CSS:
        <DataGridPro
          sx={{
            "& .MuiDataGrid-columnHeader:nth-child(3)": {
              backgroundColor: "red",
              color: "#ffffff",
              fontWeight: "bold"
            },
            "& .MuiDataGrid-columnHeader:nth-child(4)": {
              backgroundColor: "purple",
              color: "#ffffff",
              fontWeight: "bold"
            }
          }}
          apiRef={apiRef}
          onCellClick={handleCellClick}
          hideFooter
          {...data}
        />

You can fix this by instead using headerClassName in the column definitions as shown in the documentation here: https://mui.com/x/react-data-grid/style/#styling-column-headers.
Here's a modification of my earlier example that uses headerClassName: https://codesandbox.io/s/horizontal-scrolling-087h4m?file=/demo.tsx
  const { data } = useDemoData({
    dataSet: "Commodity",
    rowLength: 100
  });
  // data.columns[0] is the hidden id column, so data.columns[1] is the column
  // definition for the first visible column.
  data.columns[3].headerClassName = "red-header";
  data.columns[4].headerClassName = "purple-header";

...

        <DataGridPro
          sx={{
            "& .MuiDataGrid-columnHeader.red-header": {
              backgroundColor: "red",
              color: "#ffffff",
              fontWeight: "bold"
            },
            "& .MuiDataGrid-columnHeader.purple-header": {
              backgroundColor: "purple",
              color: "#ffffff",
              fontWeight: "bold"
            }
          }}
          apiRef={apiRef}
          onCellClick={handleCellClick}
          hideFooter
          {...data}
        />

Comment: Thanks for your quick answer, it works. I did not know about virtualization.


Bootstrap Collapsing Table

Question: I am trying to make several rows collapse when I click on the parent row. currently, i am only able to collapse a single row, but i need to be able to close +2 rows at the same time.
Below is my current code, in this code I cannot figure out how to collapse both the "HIDDEN" and "HIDDEN 2" rows when I click on the first row.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi" crossorigin="anonymous">

        test

HIDDEN

HIDDEN 2

Comment: where's your JS?
Comment: what do you mean? this is just an html page, no scripts aside from jquery and bootstrap
Answer: Instead of id="main" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne" use this example.  https://jsfiddle.net/ayang10/DTcHh/33622/

  +
  1001
  9/29/2016
  $126.27

  1

  Shirt
  $12.27

  1

  Shoes
  $62.27

Comment: you can change the html to `

        test

HIDDEN

HIDDEN 2

`
Comment: The JS fiddle works exactly how i need mine to work, however, when i move it into an HTML file it is only showing the first hidden element, and I'm very unsure as to why it is unable find the second hidden element
Comment: The same happens when I use the html you added in your comment
Comment: do you have `` in the second tr tag as well?
Comment: yes, i copied the code exactly from the JS fiddle, to check if it worked in my HTML file

`
1

Shirt
$12.27

1

Shoes
$62.27
`
Comment: I figured out what the error was, it was an error with the placement of my jquery script (it was below the bootstrap script)
Comment: Glad I can help
Answer: Because it seems that bootstrap is using the href to call the collapse function, it isn't possible to collapse more than row at a time. This is because the href can only hold one link, which in this case is the id for the row that is successfully collapsing. I tried a few hacks, such as using an inline onclick="location.href = '#collapseOne #collapseTwo'" to give the href two links on the fly, but this didn't work. Also tried to switch from using the href as the collapser to data-target, which should work with data-toggle to define multiple targets, but also unsuccessfully. This looks like it's an open issue for bootstrap:
https://github.com/twbs/bootstrap/issues/19813
This means that the best way is to either use some CSS magic i.e. #main:active {.collapse {display:none}} (only works with a preprocessor like less or sass) or to write some jquery to easily achieve the effect.
$(document).ready(function() {
    $("#main").on("click", function(){
        $("#collapseOne, #collapseTwo").hide();
    });
});

This implementation only hides the targeted id's, something like .toggle() instead of .hide() would be bidirectional.
Another method would be to nest a table inside of the row that is successfully collapsing, which should collapse the entire table inside of the row. But this is just a spitball and I haven't tested.
Here are some duplicates seeking to solve the same problem!
Expand/collapse multiple table rows with a more elegant solution
expand/collapse table rows with JQuery

Bootstrap Collapsing Table


String split based on repetitions

Question: I have a string value ("11112233"). I want to split this string and separate it to 3 different value.
Val 1 = 1111
val 2 = 22
val 3 = 33

I searched a lot, its possible with characters like (/) or other symbols.
Something else, My number is always different, so i cant split it by enter the exact string.
I want to do something like this:
var myVal = "11112233";
var lastVal = myVal.split(0 , 3); // split from index 0 till index 3

How i can do it?
Thanks
Comment: simply you can do like this '11112233'.split(/(1+|2+|3+)/). but need regex improvements
Answer: Try this regular expression:
'121112233'.match(/(\d)\1*/g) // ["1", "2", "111", "22", "33"]

\1* means "same as previous match, zero or more times".
Answer: Try like this
myVal='11112233'
myVal.match(/(\d)\1+/g); //["1111", "22", "33"]

Answer: You can use object to solve this.
var str = '11112233';

var strObj = {};

for(var i = 0; i < str.length; i++){
     if(strObj[str[i]]) {
         strObj[str[i]]+=str[i];
     } else {
        strObj[str[i]] = str[i];
     }
}

for (var key in strObj) {
  if (strObj.hasOwnProperty(key)) {
    alert(key + " -> " + strObj[key]);
  }
}

JsFiddle : https://jsfiddle.net/nikdtu/7qj3szo2/
Comment: it should be more efficient in terms of time and space complexity.
Comment: Not sure: http://jsperf.com/regexp-vs-hardcoded, as far as jsperf is reliable :-D
Answer: There is the substr() function.
You can use it like you've written in your question:
var myVal = "11112233";
var lastVal = myVal.substr(0, 3); // "1111"

Comment: Actually, the question is pretty unclear saying "some thing like this". It's still a valid answer imho.
Answer: To complement above answers, here's solution not using regex.
function partition(acc, value){

  var last = acc[acc.length-1];
  if(last && last[0] == value) acc[acc.length-1] += value;
  else acc = acc.concat(value);

  return acc;
}

var toInt = parseInt.bind(null, 10)

var x = ([[]]).concat("112233".split(''))
              .reduce(partition).map(toInt);

// [11, 22, 33]

String split based on repetitions


como esconder uma progressBar apos determinado tempo

Question: Estou usando o seguinte código
   new Thread(new Runnable() {
        public void run() {
            while (cont < 100) {
                cont += 1;

                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            progressBar.setVisibility(View.GONE);
        }
    }).start();

O problema é que na hora de setar a Visibility aparece o seguinte erro
FATAL EXCEPTION: Thread-1087                                                                           Process: br.alphatec.ms_cliente_alpha1, PID: 23000                                                                           android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
E quando o código estava assim executava, porem muito rápido, e se eu aumentar o valor(100) que esta no while ele para de funcionar
   new Thread(new Runnable() {
        public void run() {
            while (cont < 100) {

               cont += 1;
            }

            progressBar.setVisibility(View.GONE);
        }
    }).start();

Answer: Achei estranho a segunda solução funcionar, porque ainda sim está violando a restrição de single threading do framework.
O mais certo seria o primeiro caso pois não está fazendo uma espera ocupada.
Voltando ao problema, você não pode modificar Views estando em uma Thread separada da Main Thread.
Para resolver o problema você precisa continuar o processamento na Main Thread após a espera na Thread separada.
O primeiro exemplo ficaria:
new Thread(new Runnable() {
    public void run() {
        while (cont < 100) {
            cont += 1;

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        progressBar.post(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }
}).start();

Para coisas um pouco mais avançadas, recomendo que dê uma olhada no conceito de AsyncTask.
Usando AsyncTask seu exemplo ficaria:
new AsyncTask<Void, Void, Void> {
    @Override protected Long doInBackground(Void... args) {
        while (cont < 100) {
            cont += 1;

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override protected void onPostExecute(Void result) {
        progressBar.setVisibility(View.GONE);
    }
}

No AsyncTask o método doInBackground é chamado num ThreadPoolExecutor e o método onPostExecute na Main Thread.
Existem outras funcionalidades no AsyncTask, mas não é o escopo da pergunta.


Can PHP load a encrypted file?

Question: For example, I would like to:
require('encrypted.php')

"encrypted.php" contains php code that was encrypted with base64, and I have the key to decrypt it. Is there a way to first decrypt the file and then just load the decrypted code into PHP?
Comment: base64 is encoding, not encryption.
Comment: Encrypted with `base64`... is this a joke?  You have the key to decrypt it?  You realize base64 is not an encryption method, right?  It is simple encoding, and no key is required.
Comment: http://stackoverflow.com/questions/3701291/how-to-decode-eval-gzinflate-base64-decode
Comment: base64 or not is not important, I just made up the scenario. The main question I'm asking is about loading a encrypted file into PHP that I have the key to decrypt.
Answer: The first way that jumps to mind is:
eval("?".">".base64_decode(file_get_contents("encrypted.php"))."<"."?php");

However that's probably not a good idea (evil eval).
Why have you encrypted a PHP file anyway? Nobody can see the source code unless you mess around with things.
Comment: +1 Forgot about closing the existing open ``. Shows how often I would want or need to `eval()` a file...
Comment: Ha ha this looks like a virus so much.
Answer: You would need to load the file's contents with file_get_contents() or similar, then call base64_decode() on it and eval() it as PHP.  Only do this if you are certain of the contents of the file and you trust its source.
// Only do this is the file is trusted!!!
$phpcode = base64_decode(file_get_contents("trusted_encoded_file.php"));
eval($phpcode);

Note: See @Kolink's implementation if the encoded file contains <?php ?> open/close tags.
Answer: you don't need any key to decode base64 data , use base64_decode().
Comment: Thanks but that's not what I'm asking. base64 or not is not important, I just made up the scenario. The main question I'm asking is about loading a encrypted file into PHP that I have the key to decrypt.
Answer: It is not professional solution, but take  look at this : http://www.zend.com/en/products/guard/

Can PHP load a encrypted file?


How to deal with Bubbleable Metadata when there's no rendering context and no render array

Question: Since Drupal 8.0.0-beta12 "all rendering must happen in a render context", as stated by this change record.
This is to avoid bubbleable metadata lost. So far, so good.
Let's say I'm implementing a Commerce payment notification. The important part is a server calls a Drupal URL to notify something. The controller, as far as I know, doesn't need any rendering context because the answer is simple (almost just a status response). Good.
Let's say I want to send an email on this event. I create an EventSubscriber that subscribes to the payment event that happens on this callback. I hook on the event, gather the email data, and call the send function. During sending, Drupal renders the content (is an HTML email!) and I got the error: since there's no rendering context Drupal throws an exception. The point the error is triggered is when Token::replace() is called:
$body = $this->token->replace($this->getBody(), $this->getTokenData());

How to fix this?
Option 1:
Use the BubbleableMetadata $bubbleable_metadata fourth param of Token::replace(). This param docs states:

An object to which static::generate() and the hooks and functions that
  it invokes will add their required bubbleable metadata.
To ensure that the metadata associated with the token replacements
  gets attached to the same render array that contains the
  token-replaced text, callers of this method are encouraged to pass in
  a BubbleableMetadata object and apply it to the corresponding render
  array.

But because $body is just a plain string I guess the bubbleable metadata is lost, so what's the point of caring?
Option 2:
Follow the change record suggestion and use RenderContext::executeInRenderContext(). In that case I'd wrap the whole process:
$renderer = \Drupal::service('renderer');
$context = new RenderContext();
$that = $this;
$response = $renderer->executeInRenderContext($context, function() use ($that, $recipient) {
  $that->mailer->send($recipient);
  });

Again, I'm discarding the cacheable metadata.
I guess discarding that cacheable data is ok because the email is totally uncacheable, the whole body and its parts (because the replaced strings with tokens have URLs that would change on every email).
Are both approaches ok? Is one better than the other? Is there a third approach more suitable for this problem? I guess the problem can be summarized as how to deal with Bubbleable Metadata when there's no rendering context and no render array.
Answer: Yes, when rendering email data you have to take care that you don't bubble up metadata to the render context of the main response.
There is a third option, and in most cases the best option: The method Renderer::renderPlain, which not only discards bubbleable metadata, but also makes sure your email doesn't contain leftover placeholders:

Renders final HTML in situations where no assets are needed.
Calls ::render() in such a way that placeholders are replaced.
Useful for instance when rendering the values of tokens or emails,
  which need a render array being turned into a string, but do not need
  any of the bubbleable metadata (the attached assets and cache tags).
Some of these are a relatively common use case and happen within a
  ::renderRoot() call, but that is generally highly problematic (and
  hence an exception is thrown when a ::renderRoot() call happens within
  another ::renderRoot() call). However, in this case, we only care
  about the output, not about the bubbling. Hence this uses a separate
  render context, to not affect the parent ::renderRoot() call.
(Can be executed within another render context: it runs in isolation.)

And it's always a good idea to build a render array to produce HTML. For example if you have a formatted text field then build a processed text render element: How to safely render node body on a custom variable?
Comment: Not all tokens discard metadata, but you can do this if they are only used in emails.
Comment: Thanks for your answer! It happens that on the token replace we are using custom tokens, and those custom tokens use renders. I understand that we should use renderPlain() method tu render our custom tokens instead of just render. This what Token module seems to do.


Resultado indesejado - Query SQL

Question: Olá. Estou um problema e não enxergo uma forma de resolver.
Meus dados da tabela movimentacao:

Minha query:
select avg(m.valor) from Movimentacao m where m.tipo='SAIDA' group by m.data;

Meu resultado:

Eu não consigo agrupar a média por data(dia). Mesmo se eu usar distinct. Sempre retorna todas as datas. Se caso eu agrupo por titular funciona, menos com data. Isso ocorre efetuando a busca pelo JPA e também via banco de dado.
A tabela foi gerada pelo JPA/Hibernate usando Calendar para a data.
@Temporal(TemporalType.TIMESTAMP)
private Calendar data;

Alguém enxerga o problema?
Answer: AVG é uma função de agregação, então ela fará uma agregação do valor que você colocou na função. No seu caso a media do valor. O que você quer é agregar a media dos valores pelo dia, da forma como você fez, você estará tentando agrupar por meio da data que é timestamp(Ano/Mes/Dia/Hora/Minuto/Segundo/Milissegundo).
Para agrupar pelo dia, você tem varias formas:
A primeira forma, que eu recomendo, é transformar sua coluna em um tipo Data(Dia/mes/ano)
Utilizando a seguinte anotação:
@Temporal(TemporalType.DATE)
private Date data;

Para maiores informações: https://docs.oracle.com/javaee/6/api/javax/persistence/TemporalType.html
Outra forma é pegar a data por meio de alguma função SQL.
No caso do MYSQL:
SELECT avg(m.valor)
FROM Movimentacao m
WHERE m.tipo='SAIDA'
GROUP BY DATE(m.data);

Para maiores informações: https://stackoverflow.com/questions/21151335/select-date-from-timestamp-sql
E por ultimo, a ultima maneira seria pegar via HQL, recomendo criar uma função, ou declarar alguma função para extrair apenas a data, semelhante ao DATE() do MYSQL.
Para maiores informações: https://stackoverflow.com/questions/17826241/hql-query-based-on-date-on-a-timestamp-column
Comment: Deu certo. User `date(m.data)`.

Resultado indesejado - Query SQL


What is faster: hook_form_alter or hook_form_FORM_ID_alter?

Question: I want my Drupal site be as fast as it can.
So I'm considering whether to use hook_form_alter with an if statement inside or hook_form_FORM_ID_alter.
I know that it's a bit more convenient to use the latter but I'd prefer to use the faster method.
Does somebody know which is faster and how much? And I don't only mean form_alter, but all hooks with an ID in it.
Comment: Hook implementations are cached, so it really doesn't make a difference. When that cache is rebuilt, every module is tested for every version of hook_form_alter AND hook_form_FORM_ID_alter anyway, so technically you can save a bit of time (microseconds) by lumping everything for one module into a single form_alter hook. But then when that's invoked, you have to check the form ID anyway, which is another OP, and that happens at 'runtime' (no cache). Benchmark that difference if you really care, but you're in classic premature optimisation mode here :)
Answer: The hook_form_FORM_ID_alter is faster than hook_form_alter.
Modules can implement hook_form_FORM_ID_alter() to modify a specific form, rather than implementing hook_form_alter() and checking the form ID, or using long switch statements to alter multiple forms.
Form alter hooks are called in the following order:

hook_form_alter()
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()

I hope this helps :)
Comment: Thank you for the answer, but you just declared which option would be the faster without giving explanation why. How do you refer t Clive's comment who states that it would be hook_form_alter that would be faster?


Combining the partial Derivatives

Question: Suppose I have a column matrix $x = \begin{pmatrix}x1\\x2\\x3 \end{pmatrix}$ and another column matrix $y = \begin{pmatrix}y1\\y2\\y3 \end{pmatrix}$. I know all the partial derivatives of $y$ with respect to $x$. Lets say they are
$$\frac{\partial}{\partial x_i}y = \begin{pmatrix}y'_i1\\y'_i2\\y'_i3\end{pmatrix}$$ for $i \leq 3$.
Now my question is how can I get $\frac{d}{dx} (y)$, i.e., I want to differentiate $y$ with respect to $x$. How can I get that?
P.S. I am not a mathematics major so this may be a very lame question. But I want to know that. This is actually a subproblem that I need to solve for my original problem.
Answer: If $$\mathbf{y}=\begin{bmatrix}
y_1 \\
y_2 \\
\vdots \\
y_m \\
\end{bmatrix}
$$
and
$$
\mathbf{x} =
\begin{bmatrix}
x_1 \\
x_2 \\
\vdots \\
x_n \\
\end{bmatrix}
$$
Then
$$
\frac{\partial \mathbf{y}}{\partial \mathbf{x}} =
\begin{bmatrix}
\frac{\partial y_1}{\partial x_1} & \frac{\partial y_1}{\partial x_2} & \cdots & \frac{\partial y_1}{\partial x_n}\\
\frac{\partial y_2}{\partial x_1} & \frac{\partial y_2}{\partial x_2} & \cdots & \frac{\partial y_2}{\partial x_n}\\
\vdots & \vdots & \ddots & \vdots\\
\frac{\partial y_m}{\partial x_1} & \frac{\partial y_m}{\partial x_2} & \cdots & \frac{\partial y_m}{\partial x_n}\\
\end{bmatrix}.
$$
Comment: Thank you so much for the answer.

Combining the partial Derivatives


I'm having trouble with with improper integral convergence

Question: i am having though time trying to find if $\int_2^\infty \frac{\cos(x^2)}{x\ln(x)}dx$ converges.
does it converge or absolutely converging?
i am sorry that i am not writing with the correct symbols as i an not used to it yet.
any help will be greatly appreciated
thank you.
Answer: Change variables with $u = x^2$ to obtain
$$\int_2^c \frac{\cos x^2}{x \ln x }\, dx = \int_4^{c^2} \frac{\cos u}{2u \ln \sqrt{u} }\, du =  \int_4^{c^2} \frac{\cos u}{u \ln u }\, du $$
By the Dirichlet test, the improper integral is at least conditionally convergent.
However, the integral fails to converge absolutely since
$$\int_4^{\infty} \frac{|\cos u|}{u \ln u }\, du \geqslant \sum_{k=2}^\infty\int_{\pi/2 + k \pi}^{3\pi/2 + k \pi}\frac{|\cos u|}{u \ln u }\, du \\ \geqslant \sum_{k=2}^\infty\frac{2}{(3\pi/2 + k\pi) \ln (3\pi/2 + k \pi) } \\  \geqslant \sum_{k=2}^\infty\frac{2}{(2k\pi) \ln (2k \pi) }  \\ = \frac{1}{\pi}\sum_{k=2}^\infty\frac{1}{k (\ln k + \ln(2\pi)) }$$
Comment: @evgniytayarov: You're welcome.


O que é indireção?

Question: Leio em alguns lugares sobre programação que algo faz ou deveria fazer uma indireção.
O que é isto e para que serve?
Answer: É o ato de fazer referência para alguma coisa indiretamente, ou seja, através de algo que não seja o seu valor. É uma forma de delegação. Usamos isso em programação o tempo todo sem perceber.
Uma variável é uma indireção. Poderíamos acessar uma posição da memória, mas usamos um nome que nos leva a essa posição da memória. Isso dá uma flexibilidade bem grande, podemos até mesmo trocar o endereço de memória dessa variável e ela permanecer a mesma referência. Não que sempre seja possível, mas é uma possibilidade.
Uma função é outra das mais usadas. A função nada mais é que um nome que referencia uma posição de memória onde tem um código. O uso direto é acessar o código logo ali, mas o que fazemos é indicar onde o código está. É um acesso indireto, portanto é uma indireção.
Um delegado é uma indireção da indireção. Ele é uma variável ou objeto mais complexo que possui um endereço onde tem a informação que indica qual é a função a ser executada, portanto é um nível de indireção em cima de outro.
O polimorfismo (pelo menos um dos tipos) é outra forma de indireção da indireção, já que para saber o que chamar, precisa consultar uma tabela do que deve ser executado. A primeira referência é onde está a tabela daquele tipo e depois pega a referência para o método correto.
Um objeto em memória dinâmica é uma indireção porque você acessa um valor que indica onde está o objeto.
Quando você não sabe o tamanho do objeto até a sua criação durante a execução, precisa criar uma indireção, o que é muito comum em strings.
Um array simples é uma indireção. Ele funciona como uma variável de uma variável. A variável primária é o array como um todo, a variável secundária é o elemento individual dele.
Um array de objetos variados pode fazer uma indireção para compatibilização dos tipos. Na verdade isso vale para qualquer estrutura. Uma linguagem de tipagem dinâmica faz isso.
Sabe os famosos getters e setters? É uma indireção onde se usa uma função no lugar de uma variável. Já sabemos que a variável é uma indireção. A função é outro tipo de indireção sendo usada com um objetivo específico de nova abstração.
Uma classe ou método recebe um objeto para parametrizá-lo. Este objeto é que tem a implementação concreta que a classe ou método precisa. Inversão de dependência é só mais um exemplo de indireção.
Linkagem dinâmica precisa da indireção para fazer a ligação.
Estes são apenas alguns exemplos óbvios.
A indireção pode evitar desvios condicionais que podem ter um custo de processamento alto.
Em geral a indireção ocorre através de um ponteiro, mesmo que não pareça um.
Com ela produzimos código mais DRY. Você tem a informação em um lugar e pode fazer várias referências a ela.
OOP usa e abusa de indireção. Especialmente quando usa os famosos padrões de projeto criados para solucionar os problemas que OOP causou. A indireção vem para salvar a pátria.
A indireção pode ocorrer em níveis mais abstratos. O uso de uma biblioteca, de um webservice, de um driver, tudo pode ser um indireção. O acesso à memória e a todo hardware pelas aplicações é uma indireção. O acesso é indireto através de um mecanismo intermediário disponibilizado.
A indireção é fundamental para criar abstrações, desde as mais simples, como a variável, até as mais complexas. É tão importante que é chamado de "Teorema Fundamental da Engenharia de Software".

Não existe problema na computação que não possa ser resolvido com um nível extra de indireção
-- David J. Wheeler

Na verdade a frase ficou famosa na mão do Butler Lampson. Portanto a citação é uma indireção... :)
É óbvio que existem exageros no seu uso, até porque em geral não pensamos muito na indireção, estamos só à procura de uma solução para o problema. Não pensamos em não causar outro problema. Quando você delega demais começa ter duplicação de esforços e começa aumentar a complexidade. Por isso costuma-se complementar a citação acima com:

... exceto para o problema de níveis demais de indireção

Coloquei no GitHub para referência futura.

O que é indireção?


List of function calls in static code analyzer tools

Question: In an embedded C project which is using a SDK's source and header files, I want to have a list of functions, definitions, and variables that a specific source file is using across the project. In other words, a tool that statically analyzes and lists dependencies of a specific source code without the need to execute functions ( not dynamic) of the source file.
I checked static code analysis tools, but they are mostly linters and do not give me a list of dependencies.
I think this type of work is not being explored by the community and any answer will help a lot.
Thanks
Comment: What about pointers? file1.c: int a; file2.c: int *p = &a file3.c: *p = 1;
Answer: You can try CppDepend and its code query language, here's an example of a cqlinq query to get all methods with their files used by a source file.
<code>from m in JustMyCode.Methods where  m.SourceDecl.SourceFile.FileName=="test.cpp"
from mc in m.MethodsCalled
select new { m,mc,mc.SourceDecl.SourceFile.FileName}
</code>


centos 6.6, sh: zip: command not found

Question: Centos 6.6 64bit on OpenVZ VPS.
I tried a phpinfo.php file using only the following code:
<?php
var_dump( exec('zip -r domains.zip "domains"') );
// phpinfo();
?>

.
The php error log is now: [Sat Jul 04 17:44:27 2015] [error] [client xxx.xxx.xxx.xxx] sh: zip: command not found

.
[root@server ~]# yum install zip
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.atlanticmetro.net
 * extras: mirror.trouble-free.net
 * rpmforge: repoforge.mirror.constant.com
 * updates: mirror.cogentco.com
Setting up Install Process
Package zip-3.0-1.el6.x86_64 already installed and latest version
Nothing to do

.
[root@server ~]# php -m
[PHP Modules]
bcmath
bz2
calendar
Core
ctype
curl
date
dom
ereg
exif
fileinfo
filter
ftp
gd
gettext
hash
iconv
ionCube Loader
json
libxml
mbstring
mcrypt
mysql
mysqli
mysqlnd
openssl
pcre
PDO
pdo_mysql
pdo_sqlite
Phar
posix
Reflection
session
SimpleXML
soap
sockets
SPL
sqlite3
standard
tokenizer
xml
xmlreader
xmlrpc
xmlwriter
xsl
zip
zlib

.
[root@server ~]# php -v
PHP 5.4.27 (cli) (built: Jul  3 2015 18:06:21)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies
    with the ionCube PHP Loader (enabled) + Intrusion Protection from ioncube24.com (unconfigured) v5.0.11, Copyright (c) 2002-2015, by ionCube Ltd.

MORE INFO
I want to add /usr/bin/zip to the executable path for the web server.
I've tried:
export PATH=$PATH:/usr/bin/zip

AND
cd /usr/bin
sudo ln -s /usr/bin/zip zip
But neither one worked.
Comment: Can you show us what *which zip* produces
Comment: Result: /usr/bin/zip
Comment: See what happens if you do /usr/bin/zip instead of just zip
Comment: Ok. I changed "zip" to "/usr/bin/zip" in phpinfo.php and the out come was: string(42) "updating: domains/-----.co/ (stored 0%)"
Comment: What are you trying to zip?
Comment: @Cazzette So specifying the full path solved the problem then?
Comment: Yes I believe it did.  Now, how do I do change this in the VPS so that path is always defined and able to be called by any script without having to manually define the full path? Please see my updated post for more details/outcome. @kasperd
Comment: @MichaelBailey I use this method to backup and deploy my websites.
Comment: @Cazzette would it solve this if you stored /usr/bin/zip as a PHP variable $zip? This would work if you have a PHP include on like every script you're calling. Common in a few situation, like db authentication.
Answer: Just so I can make it an actual answer so this can be marked solved:
After running which zip and locating zip, /usr/bin/zip triggered successfully while zip did not.
As for the new part:
I'd personally store it as a PHP variable (like $zip = /usr/bin/zip) and call it if that solves it. There may be a better solution.
Comment: Hi @Michael Bailey. It's not my software to modify, it's obfuscated. So I cannot edit it's own files like that unfortunately.
Comment: can you clarify this php variable? I'd like it web server wide, so somewhere within php.ini I assume. What would this line look like? I don't want to screw this up.
Comment: I just mean a lot of PHP web apps have a header.php that they include in all their pages. Kinda a non-answer.

centos 6.6, sh: zip: command not found


Algorithm for scoring co-varying traits

Question: I am sure this has been done, but I can't find quite the right approach.
EDIT:
Trying to explain better.
The rows of colored boxes below are columns of molecular sequence data -- positions in a protein. The circles represent individuals (species, etc) which have that amino acid at that position. An actual data set consists of many of these positions for the same set of taxa. I want to quantify how well each position (set of traits, A1,A2, etc) is correlated with the trait shared by the species (black or white color of dots, e.g., indicating habitat or other external factor). There is an underlying relationship between the species which is going to drive the major pattern of similarity, and I am trying to find where things differ from that pattern, being instead correlated to the trait (black/white).
In the diagrams and question below tried to reduce this question down to what seems to be the underlying statistical question: generate a score for how well correlated the colored squares are with the black and white circles, without regard to the actual color of the square. (The correlation could be the opposite one position over, as in B1 and B2, but that is still strongly linked to the black/white trait.)

Original description below:
I am trying to find a way to score a suite of traits (colored boxes in figure) by how well they coincide with another categorical trait (black and gray circles below). The categorical traits are shown as binary, but would ideally scale to 3 or more.
One approach would be to generate expected frequencies based on the number of traits and the number of categories, and compare the actual frequencies for each.
To get expectations, for example in scenario A1 one state is present in 1/3rd of the cases, its expectation would be the number of each category times that probability.

My questions are (1) whether this is an accepted way to generate the expected probabilities and (2) what the metric should be for assessing them. I want to have a value for each black/white trait state indicating how strongly it is linked to the colored state.
There is no way to get a zero observed in this situation, because one or the other trait will be found in each category. (For example, in B1 and B2, they should both score as high as possible because the traits sort perfectly to the categories, even though they are in opposite order.) Scenario A4 and B4 should score as low as possible and A1 should also have the highest score.
To put it another way, I am not testing direct correlations ("Do females prefer Democrats?") but rather for each potential preference, which ones separate by category ("What topics of conversation show male/female differences?"). The expectation has to take into account that the associations should score high with either association.
Another thing that might/might not be relevant for summing the trait scores is that, they are not independent: If A and B are traits, then there is an expectation that individual samples (all the 0 and 1 circles) will have an underlying pattern of similarity that is not driven by one- or zero-ness. The point of this metric is to sort out which sets of traits show the most influence of category, even if the majority are driven by some other relationship.
Currently I am assuming I would compare the expected total and the observed for each category using a Chi-squared calculation of <code>(O - E)^2/E</code> and then sum them for each trait?
Does this look like a standard test? I would greatly appreciate any links or suggestions.
Comment: I really can't follow this. Can you state what you are trying to do more plainly & w/o the jargon that you might expect statisticians want to hear? What are the states & traits here? If you had these scores & metrics, what would you want to do with them? What are your actual data & what is your end goal?
Comment: Thanks @gung. You are right I was trying to put it in stats terms that I am not that familiar with. I tried a more up-front explanation.
Answer: If I understand you right, you have two categorical variables ("box colour" and "dot colour") and you want to know to what extent one predicts the other. If that's right, then a simple evaluation measure here is the mutual information between the box colour and the dot colour.
Mutual information is easy to calculate (see first eqn in the linked page), and it has exactly the property that you want: it doesn't care about which category predicts which other category (it doesn't care whether "orange" predicts "black" or "white"), it only cares whether knowing box-colour reduces your uncertainty about dot-colour.
Pearson's chi-squared test (as you mention) would also work fine, and also has that property. Your wording is a bit difficult but I think you've got the idea right for the "expected" counts that you would use for that.
Comment: Been digesting this a bit and figuring how to apply the mutual information formula. It has me on the track of creating contingency tables, which has helped clarify things, I think. I appreciate the help, and will "check" back as I get it implemented.
Comment: This metric didn't actually work for my exact question, but was a good lead to some tests to try.

Algorithm for scoring co-varying traits


Memory Management Confusion C++

Question: I'm having trouble understanding some basic memory management principles in C++.  This code is part of a loop that is part of a function that reads in a maze file into a 2D vector.
According to Valgrind, the following code is causing memory leaks...
Note that t is a MazeNode object and verts is a vector within the t class that holds pointers to node objects (not to be confused with MazeNode objects):
node* top = new node(TOP, rowCount, i, t.type);
node* bot = new node(BOTTOM, rowCount, i, t.type);
node* left = new node(LEFT, rowCount, i,  t.type);
node* right = new node(RIGHT, rowCount, i, t.type);

t.verts.push_back(top);
t.verts.push_back(bot);
t.verts.push_back(left);
t.verts.push_back(right);

temp.push_back(t);

top = NULL;
bot = NULL;
left = NULL;
right = NULL;
delete top;
delete bot;
delete left;
delete right;

Initially I did not set each of the pointers to NULL before deleting them, but would get allocation errors.  So I just set them to NULL and my code works.  I guess I'm just really confused why this would cause memory leaks and why I would need to set the pointers to NULL.  There is probably a way easier non-pointer way to do this, but maybe this problem will help me understand memory management better.
Thanks everyone.
EDIT: Here's the MazeNode class (which is what 't' is) (also excuse my lazyness in writing this class, making everythign public like a struct)
class MazeNode
{
public:
    void setType(char c);
    char getChar();

    NodeType type;
    vector<Direction> visitedFrom;

    vector<node*> verts;
};

And the node class:
class node
{
public:
    node();
    node(Direction d, int r, int c, NodeType t);
    ~node(); //empty definition
    node(const node* n);
    node& operator=(const node& n);

    void addAdj(node* a, int w);
    void printAdj() const;
    string direction() const;

    void print() const;
    bool operator<(const node& n) const;

    int distance; //from start
    bool visited;
    node* prev;
    vector<Edge> adj;
    Direction dir;
    int row, col;
    NodeType type;
};

EDIT2:  Thanks everyone.  I understand the problem now.  I changed my vectors of pointer objects so that I wasn't using pointers anymore.
Comment: [Don't use `new`, don't use `delete`](http://stackoverflow.com/questions/8839943/why-does-the-use-of-new-cause-memory-leaks-in-c/8840302#8840302). Those features of C++ are not suited for most code.
Comment: Please post the definition of your `t` and `temp` variables.  I'm pretty sure that it's more than just setting to NULL that's causing the leak, but I need variable definitions to show what's "all" wrong here.
Comment: You don't need to set the pointers to NULL. That seems to be exactly what is causing a leak.
Comment: Please add the definition of t.verts.
Comment: That's what I thought, but then why am I getting errors if I just use delete?
Comment: Ok give me a sec I'll add that stuff.
Comment: R. Martinho is quite right. Use std::make_shared :).  Also, it looks as though you're pushing a pointer into an array of pointers and then releasing the memory the pointer are pointing to.  The end result will be an array of pointers to free memory and almost certainly a segment fault when you try to access any of them.
Comment: The `node` class seems to be in violation of the [rule of three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). You may want to fix that.
Answer: Prior to adding the null assignment, your code had a problem different (worse) than a memory leak: storing and probably also using a stray pointer, that is, a pointer pointing into de-allocated memory.
Making it a memory leak by adding the null assignment makes it better, but not much.
The real solution is not to keep any pointers anywhere after you have called delete on them.
That is, do not push_back or do not delete here.
Comment: "The real solution is not to keep any pointers anywhere after you have called delete on them." .... Well, depends. That may be a nice rule of thumb for simple scenarios, but for complex ones you'll end up having arrays of pointers that you reuse and such. You may want to make your wording a bit more lenient as to not be absolute where there is no absolute.
Comment: Sorry I'm kind of new at this, but how can I have a vector of pointers then, without pushing back?  Should I just not use a vector of pointer objects?
Comment: @Kaganar - It's certainly simplification, but a practical one while looking at a  SIGABORT for maybe the first time.
Comment: @Slims - You can definitely have a vector of pointers.  However, I suspect that either `t` or or `temp` in your example are not shown in their full scope.  If either of these variables (or any copy of either) survives and is used past the `delete`, you are walking on a minefield.  The pointers become dangerous to dereference.  Post more code perhaps to show what you do with them, or to which library you ever pass them.
Answer: You are placing the pointers into a container, then deleting the pointers. When your code later tries to use those pointers they are invalid and cause a crash.
By setting the pointers to NULL before you delete them, you end up not deleting them at all - deleting a NULL pointer doesn't do anything. But now there's nothing to delete the objects later, and you get a memory leak.
You need to find some spot in the code where you're not using the pointers anymore, and delete them there.
Edit: Of course I should have mentioned that a smart pointer such as std::shared_ptr eliminates this hassle altogether, because it deletes the object automatically.
Answer: You are setting the values to NULL before deleting them, so you are trying to delete NULL and nothing is being deleted. Try moving the delete calls above the NULL calls.
Answer: This confusion is exactly why I create a macro for these kind of things:
#define delobj(obj) (delete obj, obj = NULL)

And you would use it like this:
delobj(top);
delobj(bot);
delobj(left);
delobj(right);

Answer: The error is using the vector of pointers.  According to you, verts is this:
vector<node*> verts;

But what it should be is this:
vector<node> verts;

In the first case, when you push_back() the pointer, that's OK, but when you pop_back or otherwise re-size the vector, the pointer is the "contents" of the vector, and is de-allocated, but not what the pointer points to, which is the node.  Hence the node leaks.  But in the second case, the node is "part" of the vector, and is allocated/deallocated as part of re-sizing the vector.
Your pattern here probably indicates a Java/C# background, as "new-ing" into a container is very very common in those languages, but to do that in C++, you need a container of smart pointers (like vector<shared_ptr<node>> or something), which is probably beyond the scope of the question.  But in those languages, every reference to a reference type is a "smart pointer" (more or less) and so this is done automatically.  C++ isn't like that.
You either need to change your code to use a vector<node> (and change how you're pushing back on to it) or you need to explicitly de-allocate your nodes when the vector shrinks.
Comment: I see.  Well the vector next shrinks.  It is used for the entire program; it's just a structure to hold the maze.  It should never shrink.
Answer: Change to:
delete top;
delete bot;
delete left;
delete right;

top = NULL;
bot = NULL;
left = NULL;
right = NULL;

And it should work.

Memory Management Confusion C++


How to convert T-SQL to LINQ?

Question: How can I convert the following T-SQL query, that produces correct results, to LINQ expression in C#?
WITH    CTE
          AS ( SELECT RN = ROW_NUMBER() OVER ( PARTITION BY dbo.Product.ID ORDER BY dbo.Picture.UpdatedDate ASC )
                   ,Product.ID
                   ,Product.Name
                   ,Picture.Path
                FROM Dbo.Product
                INNER JOIN dbo.Product_Picture_Mapping
                    ON dbo.Product_Picture_Mapping.ProductID = dbo.Product.ID
                INNER JOIN dbo.Picture
                    ON dbo.Picture.ID = dbo.Product_Picture_Mapping.PictureID)
    SELECT ID AS 'ID'
           ,Name AS 'Name'
        FROM CTE
        WHERE RN = 1

I have tried the following code.
var result= (from c in cd.Product
              join pp in cd.Product_Picture_Mapping
                            on c.ID equals pp.ProductID
                        join pcc in cd.Picture
                            on pp.PictureID equals pcc.ID
                        select new ProductViewModel() { PicturePath = pcc.Path, ProductName = c.Name, ProductID = c.ID}).ToList();

Comment: What do you get?  An exception?  Wrong data?  Your column outputs are different between the two queries for starters.
Comment: so, i have only one picture which name is product1.
product1 is have 4 pictures, i get only 1 row via sql query (this is what i want)
but i get 4 rows via lambda expression this is problem for me. i want only 1 row
Comment: possible duplicate of [Row\_number over (Partition by xxx) in Linq?](http://stackoverflow.com/questions/9980568/row-number-over-partition-by-xxx-in-linq)
Answer: See if the following works:
var result= (from c in cd.Product
              join pp in cd.Product_Picture_Mapping
                            on c.ID equals pp.ProductID
              let pcc = pp.Pictures.FirstOrDefault()
              select new ProductViewModel()
              {
                  PicturePath = pcc.Path,
                  ProductName = c.Name,
                  ProductID = c.ID
              }).ToList();

Looking at your table names, it looks like you have a many-many table (product_picture_mapping) which EF may be able to optimize away giving you the option of doing something like:
var result = from c in cd.Product
             let ppc = c.Pictures.FirstOrDefault()
             select new ProductViewModel
             {
                 PicturePath = pcc.Path,
                 ProductName = c.Name,
                 ProductID = c.ID
             };

How to convert T-SQL to LINQ?


É possível fazer uma requisição POST falsa?

Question: Estou criando um sistema central que valida as informações vindas de outros sistemas clientes via post e gostaria de saber se seria possível que alguém fizesse uma requisição post false se passando por um desse clientes? Usando, por exemplo o HTTP_REFERER de um cliente?
Se sim, o que posso fazer para me proteger?
Comment: Creio que seja recomendável o uso de algum tipo de autenticação (login e senha)... Ou algum sistema que a requisição inicial seja um código para obter os dados reais, o seu servidor recebe esse código e faz a requisição ao domínio do cliente, se ela for falsa o cliente vai recusar...
Answer: Sim, é possível forjar tudo numa requisição HTTP. Nunca confie em dados vindos do lado cliente.
Independentemente da sua arquitetura, se seu servidor está se comunicando com outros sistemas é imprescindível que esses sistemas estejam autenticados. A maneira mais garantida de se fazer isso é via SSL/TLS, com certificados tanto no lado servidor quanto no lado cliente. Dessa forma garante-se tanto a autenticidade da comunicação como também sua confidencialidade.
Em um cenário web (http server + browser) costuma-se usar um certificado de segurança no lado servidor, esse assinado por uma Autoridade Certificadora (CA). No lado cliente, o usuário se autentica com um nome de usuário e senha. Alternativamente, usando também um certificado, mas isso é raro. A forma como isso é feito é autenticando somente o servidor durante o aperto-de-mão (handshake) do SSL/TLS e - estabelecido um canal seguro de comunicações - usa-se esse canal para transmitir os dados adicionais de autenticação (usuário e senha do cliente). Uma vez que este esteja também autenticado, ambos compartilham uma chave secreta (session key) que é verificada a cada requisição individual (no browser, essa chave fica normalmente num cookie).
Esse é o modo mais comum de operação, mas não é o mais adequado para casos em que um sistema se comunica com outro sistema. Se você possui controle sobre todos os sistemas envolvidos, em primeiro lugar você não precisa pagar a uma CA para assinar seu certificado - você o instala manualmente em cada cliente que for se comunicar com seu servidor. Além disso, cada máquina cliente pode também ter o seu próprio certificado, esse registrado na máquina servidora. Ao estabelecer a conexão segura, tanto o cliente valida o certificado do servidor, quanto o servidor valida o certificado do cliente. Uma vez estabelecida essa conexão, pode-se então confiar 100% nela, e usar todos os métodos HTTP à vontade, não importa se é GET, POST, ou outra coisa.
Verifique na sua plataforma como é o suporte a SSL/TLS e autenticação por certificados. A título de exemplo, Java possui o SSLSession e C# o SslStream. Como exatamente implementar isso é algo que infelizmente não tenho experiência suficiente para ajudar. De todo modo, independentemente de você seguir ou não essa sugestão, é importante que a autenticação dos clientes seja feita de algum modo, não confiando no Referer ou em qualquer outro parâmetro da conexão.


Combobox traz somente um resultado da tabela do Mysql (NodeJS + JavaScript)

Question: Estou conseguindo trazer no combobox somente um valor que está na tabela do mysql, preciso que sejam listados os dois itens na mesma combobox. Está aparecendo um em uma combobox e o na outra logo abaixo.

    <% if(busca.length > 0) { %>
        <% for(var i = 0; i < busca.length; i++) {%>
            <select>
                <option value="0"selected="selected"><%=busca[i].category_name%></option>
            </select>

Answer: Basta colocar as tags select fora do loop:
<% if(busca.length > 0) { %>
    <select>
    <% for(var i = 0; i < busca.length; i++) {%>
            <option value="0"selected="selected"><%=busca[i].category_name%></option>
    <% } %>
    </select>

Comment: Guilherme Costamilam Muito obrigado!!  Funcionou como eu precisava!


Select parents data and children count in SQL-Alchemy

Question: I have a parent and a child table. It is a one-to-many relationship: a parent can have many children, a child can only have one parent.
I'm trying to create a query in SQLAlchemy that will give me all the parents' data, plus their children count.
So far I have this:
db.session.query(func.count(models.Child.id), models.Parent)\
  .select_from(models.Parent).join(models.Child).group_by(models.Parent.id)

This will produce SQL like this:
SELECT count(child.id) AS count_1, parent.id AS parent_id, parent.name AS parent_name
FROM parent
INNER JOIN child ON parent.id = child.parent_id

This gives me the desired results, except if a parent has no children. Then that parent is entirely omitted from the results, whereas the desired outcome is to have a row with its id, name, and a 0 count.
Answer: This is known as an outer join.
In SQLAlchemy, use the outerjoin method instead of join, and you'll get the desired results.


Add Reference option missing from Dependencies in Xamarin Forms (.NET Standard 2)

Question: I am trying to add a reference to my Xamarin Forms project but the option is missing for some reason.
I am  using Visual Studio 2019 version: 16.6.2

click to enlarge
Answer: If you have the dll file, simply browse for it and peform a manual reference.
Comment: I do have the DLL file, but the "Add Reference" button isn't there. I'll upload a screenshot.
Comment: https://stackoverflow.com/a/56371166/11731800 - Check this out. Might help you out.
Comment: Nope, the option isn't there either.
Comment: Add Project Reference - Browse - Select the dll - OK


got SIGSEGV while calling 'require ("lsqlite3")' with lua 5.1.5

Question: I had built lua 5.1.5 and lsqlite3-0.8.1. all of them run well on my RedHat Linux.
and then I ported them to my MIPS development board. lua and other modules (such as luafilesystem, md5, cgilua and wsapi) run well. but lsqlite3 does not work.
when I execute require("lsqlite3") in lua command line, it returns error messages in below:
lua
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio

require("lsqlite3")
  do_page_fault() #2: sending SIGSEGV to lua for invalid read access from
  00000000 (epc == 00000000, ra == 2ac36144)
  Segmentation fault

can any one give me any help to fix it? Thanks!
I got few progress in solving this problem, I rebuilt the LUA with gcc compile option '-Wl,-E' and rebuilt lsqlite3 later. I executed require ("lsqlite3") in lua command line, and it didnt print any message. I continued running some other database operation commands and found them all been successfully executed. As it seemed the problem had been solved, I should be very happy about it.
but another more strange problem raised.
If I put sentence require("lsqlite3") into a file, and then execute the file in this way:

lua file

it still printed  error messages like this:

do_page_fault() #2: sending SIGSEGV to lua for invalid read access from
  2ada054c (epc == 2ada054c, ra == 2abdceac)

If I put more database operation sentences into a file, and then run this file by lua. Lua can give correct result of query operation and insert values to table correctly, but always print error messages showed above.
If I run sentences in the file one by one in lua command line interface, it never print this error message.
It seems to give the error message when executing the 'require' function. But if I put require("lfs") into a file and run this file by lua, it never print error message.
I am confused that whait is the difference between the lua command line execution and lua script.
Comment: Can you run it under gdb, or another debugger, and get a backtrace from the thread interrupted by the SIGSEGV?
Comment: Also, is sqlite3 installed and usable from the command line?
Comment: Thanks, sqlite3 has already been installed into the development board , and I can create database and tables from the sqlite3 command line.
Comment: I think I had found the problem.
Comment: I think I had found the problem.  I tried to use luasql-sqlite3 for replacement, but got the same error. while compiling luqsql-sqlite3, it gave a warning  "sqlite3.h:253: warning: ISO C90 does not support `long long'"  . so I went back to lsqlite3 and compiled it again with option '-petantic' enabled. it gave the same warning. The Sqlite3 may need type long long, but the gcc I used for my board seems not support this feature.  even though how can I solve this problem if I was unable to change the toolchain for this board?
Answer: There are three places in lsqlite3.c where sqlite_int64 is used (never long long directly). When you build sqlite3 some type will be used for 64 bit integers; lsqlite3 will use the same type by including sqlite3.h for the definition of the type.


Getting different results when plotting 95% CI ellipses with ggplot or the ellipse package

Question: I want to visualize the results of a clustering (produced with protoclust{protoclust}) by creating scater plots for each pair of variables used for classifying my data, colouring by classes and overlapping the ellipses for the 95% confidence interval for each of the classes (to inspect which elipses-classes overlap under each pair of variables).
I have implemented the drawing of the ellipses in two different ways and the resulting ellipses are different! (bigger ellipses for first implementation!)
A priori they differ only in size (some diferent scaling?), as the  centers and angle of axes, seem to be the similar in both.
I guess I must be doing something wrong by using one of them (hope not with both!), or with the arguments.
Can anyone tell me what I am doing wrong?
Here the code for the two implementations; both are based on the answers to How can a data ellipse be superimposed on a ggplot2 scatterplot?
### 1st implementation
### using ellipse{ellipse}
library(ellipse)
library(ggplot2)
library(RColorBrewer)
colorpal <- brewer.pal(10, "Paired")

x <- data$x
y <- data$y
group <- data$group
df <- data.frame(x=x, y=y, group=factor(group))

df_ell <- data.frame()
for(g in levels(df$group)){df_ell <- rbind(df_ell, cbind(as.data.frame(with(df[df$group==g,], ellipse(cor(x, y),scale=c(sd(x),sd(y)),centre=c(mean(x),mean(y))))),group=g))}

p1 <- ggplot(data=df, aes(x=x, y=y,colour=group)) + geom_point() +
  geom_path(data=df_ell, aes(x=x, y=y,colour=group))+scale_colour_manual(values=colorpal)

### 2nd implementation
###using function ellipse_stat()
###code by Josef Fruehwald available in: https://github.com/JoFrhwld/FAAV/blob/master/r/stat-ellipse.R

p2 <-qplot(data=df, x=x,y=y,colour=group)+stat_ellipse(level=0.95)+scale_colour_manual(values=colorpal)

Here is the two plots together (left graph is p1 implementation (ellipse()):

The data are available here: https://www.dropbox.com/sh/xa8xrisa4sfxyj0/l5zaGQmXJt
Comment: This might not matter, but when I run your code I get a warning           `Warning message: In cov.trob(cbind(data$x, data$y)) : Probable convergence failure` is this also happening when you run the code?
Comment: @atiretoo Yes, it also happens when i run the code. I dont know why. Maybe anyone else knows? jose
Answer: You're not doing anything wrong, the two functions are making different underlying assumptions about the distribution of the data. Your first implementation is assuming multivariate normal, and the 2nd a multivariate t-distribution (see ?cov.trob in package MASS). The effect is easier to see if you pull out one group:
#pull out group 1
pick = group ==1
p3 <- qplot(data=df[pick,], x=x, y=y)
tl = with(df[pick,],
     ellipse(cor(x, y),scale=c(sd(x),sd(y)),
             centre=c(mean(x),mean(y))))
p3 <- p3 + geom_path(data=as.data.frame(tl), aes(x=x, y=y))
p3 <- p3 + stat_ellipse(level=0.95)
p3 # looks off center
p3 <- p3 + geom_point(aes(x=mean(x),y=mean(y),size=2,color="red"))
p3

So although it is close to the same center and orientation they are not the same. You can come close to the same size ellipse by using cov.trob() to get the correlation and scale for passing to ellipse(), and using the t argument to set the scaling equal to an f-distribution as stat_ellipse() does.
tcv = cov.trob(data[pick,2:3],cor=TRUE)
tl = with(df[pick,],
          ellipse(tcv$cor[2,1],scale=sqrt(diag(tcv$cov)),
                  t=qf(0.95,2,length(x)-1),
                  centre=tcv$center))
p3 <- p3 + geom_path(data=as.data.frame(tl), aes(x=x, y=y,color="red"))
p3

but the correspondence still isn't exact. The difference must be arising between using the cholesky decomposition of the covariance matrix and creating the scaling from the correlation and the standard deviations. I'm not enough of a mathematician to see exactly where the difference is.
Which one is correct? That's up to you to decide! The stat_ellipse() implementation will be less sensitive to outlying points, while the first will be more conservative.
Comment: Thanks a lot for taking your time solving this question! Its clear to mee now. jose
Comment: I like ellipses in plots, so this was fun to see these functions in action.


jQuery UI and invite form

Question: I am using the following invite code on my facebook app:
    <fb:serverFbml>

    </fb:serverFbml>

It works fine when I am using it inside a DIV, but if I try to use jQuery UI and turn the DIV into dialog(), when a user opens the dialog it is empty (the fb:serverFbml tag does not generate the invitation form).
Has anyone encountered this issue?
Thanks,
Joel
Answer: I think it won't work.
The quick and dirty solution is: use an iframe instead of a div.
Answer: Which platform you are using??(Iframe or FBML??)
I am also facing the same problem. Then i shift to fbml application and use FB:Dialog to do the same and I got it working..

jQuery UI and invite form


Margem relativa com variação grande entre browsers

Question: Estou com problemas com margens CSS que levam porcentagem em um projeto responsivo.
Tem objetos que levam margem de 15% referente ao contâiner, e no IE10 e Safari a diferença chega a ser 10% a mais do que deveria. No Chrome e no Firefox esta tudo normal.
Alguém já teve esse problema? e como resolveu?
No jsfiddle não vai conseguir visualizar.
Ex:
objeto {
  margin: 15% 0 0 0;
}

O resultado é o dobro da distância nos navegadores citados e não ha nenhum objeto div anterior a esse para explicar isso.
Comment: ajude nos a responder postando seu código
Comment: @JonathanSampson por incrivel que pareça sua resposta aparenta ter resolvido o problema, hahaha apesar que ela destruiu todo o layout em porcentagem mas os objetos estão se mantendo no lugar, colocar como resposta vou terminar ajustar o layout novamente e faço as devidas considerações, Valeu a todo mundo.
Comment: Tem cara de discrepância de box model. Seu HTML tem um doctype no topo? Qual?
Comment: Voce poder da uma exemplo no http://jsfiddle.net?
Comment: @bfavaretto tinha esquecido da parte da discrepância heheh quase dormindo aqui. Bom, assim sendo, acredito que não há como responder o problema da discrepância sem um maior detalhamento da parte do Helton.
Comment: To usando HTML5
Comment: @HeltonSS, um exemplo mínimo que reproduza seu problema vai te ajudar a conseguir respostas de mais qualidade.
Comment: Voce esta usando `* { box-sizing: border-box }` tambem?
Comment: Não estou usando to tentando ver uma forma de demonstra aqui o problema
Comment: Adicionar `* { box-sizing: border-box }`; touvez essa vai ajuda.
Comment: Apenas como teste, inclua o [CSS do Bootstrap](http://getbootstrap.com/dist/css/bootstrap.min.css) e veja o que acontece.
Answer: No passado, o modelo do box era diferente para o Internet Explorer e todos os outros navegadores. Hoje, para todos os teus projectos, é inteligente adicionar o seguinte:
*, :before, :after, ::before, ::after {
    box-sizing: border-box;
}

Esta declaração vai-te resolver muitos problemas com o layout nos teus projectos.
Comment: Hi there Jonathan, nice to see you around here :) (big fan here) _(comentário a ser removido em breve...)_
Comment: Obrigado, Zuul. Estou tentando melhorar meu Portuguese. Tem nada melhor dq Stack Overflow em Portuguese :)
Answer: tenta usar hacks para navegadores
HACK PARA IE 10

.ie10 .objeto{
 margin-top:5%;  /*para tirar a diferença que esta dando a mais*/
}

hack para Safari e Chrome
/* Somente para Chrome e Safari */

@media screen and (-webkit-min-device-pixel-ratio:0) {
 .objeto{ margin-top:5%; } /*para tirar a diferença que esta dando a mais*/
}
Answer: Você pode tentar dar um CSS Global Reset, todo browser tem prioridades para definir o CSS de uma página.
A ordem é:

CSS inline
Através do uso do atributo style cujo mesmo não recomendo:

CSS na página
Outra coisa que não recomendo, e não vejo necessidade. É quando coloca a TAG style dentro da TAG head:

CSS externo
Esse é o CSS normal, quando invocamos dentro do head:
<link href="home.css" type="text/css" rel="stylesheet"/>

CSS definido pelo browser
Sim, isso existe e é isso que nos causa problemas.

Quando nenhum CSS é encontrado para um elemento (div, p, h1, img, etc..), o navegador coloca por sua conta, qual vai ser o tamanho dos títulos, dos parágrafos, a margin entre elementos, a fonte padrão, o padding da página, bordas dos elementos, etc…
É aí que entra o CSS Global Reset, que são uma série de propriedades CSS atribuídas a todos os elementos HTML, justamente para retirar o CSS definido pelo browser, deixando as propriedades de todos os elementos iguais. Assim reduz drasticamente a diferença entre Firefox, Safari, Internet Explorer, Opera, etc.
Existem diversos CSS Global Reset (normalmente as pessoas colocam alguma coisa a mais para facilitar no seu projeto), mas todos eles variam pouco.

Eu uso esse aqui:
{outline-color:invert;outline-style:none;outline-width:medium;}
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote,
pre,a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-weight: normal;
  font-style: inherit;
  font-size: inherit;
  font-family: inherit;
  vertical-align: baseline;
}
:focus { outline: 0; }
body { line-height: 1; color: black; background: white; font-size:100.01%;}
ol, ul { list-style: none;}
table { border-collapse: separate; border-spacing: 0;}
caption, th, td { text-align: left; font-weight: normal;}
blockquote:before, blockquote:after,
q:before, q:after { content: "";}
blockquote, q { quotes: "" "";}
strong{ font-weight: bold; }
body,input,select,textarea { font-size: inherit; }

Comment: Mano ja tentei isso tbm.


Warning ao usar ibase_fetch_object()

Question: Tenho uma aplicação PHP que sincroniza dados de um banco para outro, em um dado momento, quando consultando um banco de dados Postgre, após preencher devidamente as variáveis $db e $sql  tenho o seguinte trecho de código:
$query = ibase_query($db, $sql);
while ($row = ibase_fetch_object($query)) {
...
}

O problema acontece na linha 2, no ibase_fetch_object($query), o log diz:

Warning: ibase_fetch_object(): operating system directive WriteFile
  failed There is not enough space on the disk.

Não encontrei nada a respeito de WriteFile nesse método na documentação.
Alguém pode me dizer o porquê desse erro e como resolvê-lo?
Answer: Consegui resolver o problema e foi da maneira mais óbvia possível, resolvendo a falta de espaço em disco.
Para contextualizar, o servidor onde a aplicação em questão roda ainda tinha 20GB de espaço livre, então quando apresentei o erro e disse que o problema era a falta de espaço fui refutado.
Não cheguei a descobrir se é por padrão ou é configurável, contudo acredito na segunda opção, mas no Linux, quando a percentagem de armazenamento livre chega a 5%, somente o usuário ROOT e mais alguns previamente autorizados podem escrever em arquivos. Nesse caso, a aplicação conseguia criar seus arquivos de LOG, mas não conseguia escrever neles. Essa situação se estendeu até o que o próprio PHP não conseguisse escrever em seus arquivos de sessão, então minha teoria foi aceita e resolvemos o problema com limpeza de disco e aumento de armazenamento.

Warning ao usar ibase_fetch_object()


Dyslexia or Dyscalculia in Reading Music

Question: Do either of these have any relationship with finding difficulty in sight-reading music? Have there been any studies related? Or is learning to sight-read well very simply down to loads of practice despite having (or not having) either of these problems?
Comment: Related post: [Dyslexia and sheet music](https://music.stackexchange.com/q/17508/70803).
Comment: Just a personal anecdote: I've taught one piano student with significant dyslexia, and reading music was exceptionally difficult for reasons clearly related to the dyslexia.
Comment: My brother self-reports as being dyslexic when it comes to reading sheet music (perhaps as bad a reader as me when I'm reading music with 4 or more ledger lines, except this occurs for him with no ledger lines) and math notation, but pretty much nothing else (i.e. his reading skills are fine everywhere else).
Comment: I have dyscalculia. I can play music "by ear" but I was unable to read music no matter how hard I tried.
Answer: Reading text vs numbers and mathematical symbols vs music appear to use different subsystems in the brain, so any problems reading one of them does not necessarily affect the others.

While text and music reading share some networks, they are largely independent. The pattern of activation for reading musical symbols and letters is different across the brain.

Some of the evidence comes from localized brain damage:

Ian McDonald, a neurologist and amateur pianist, documented the loss and recovery of his own ability to read music after a stroke, though his ability to read text was unaffected. Oliver Sacks described the case of a professional pianist who, through a degenerative brain disease, first lost her ability to read music while retaining her text reading for many years. In another case, showing the opposite pattern, a musician lost his ability to read text, but retained his ability to read music.

Differences in reading ability can occur even within musical notation. Cases have been reported where musicians have lost their ability to read pitch, but retained their ability to read rhythm, and vice versa. fMRI studies have confirmed that the brain processes pitch (spatial information) and rhythm (symbol recognition) differently.

From https://theconversation.com/how-the-brain-reads-music-the-evidence-for-musical-dyslexia-39550
There has also been research on dyslectic children vs music (not reading, just musical skills in general):

Results also indicated that dyslexic children showed difficulties with musical timing skills while showing no difficulties with pitch skills.

https://pubmed.ncbi.nlm.nih.gov/14681173/
So in general, it's complicated. Both reading and performing music uses many different and rather specialized skills. It's possible to have a learning disability that is limited to one domain, while the others are unaffected. But it's very common to be better at some aspects of music than others (say better at pitch than rhythm, or better at playing by ear than by reading, or the opposite), it doesn't necessarily imply that everyone has a learning disability of some sort.
A quote from The Conversation to round it off:

Inabilities to read music are not generally treated as a serious concern. Many gifted musicians are able to function at a professional level purely learning music by ear. Among musicians, there is a wide range of music reading proficiencies. This is especially apparent with sight reading.
Comment: I'd imagine that "difficulties with musical timing skills", which dyslexic children are indicated to have in one of your quotes, would really get in the way of learning music by ear.
Answer: Are you asking whether someone with dyslexia should anticipate similar problems when reading music?   It seems pretty well established that they needn't.   Try, and cross bridges as and if you come to them.
If problems ARE encountered, this may be of interest.
https://pdfcoffee.com/colour-staff-pdf-free.html


How to close previous infoWindow in Google Maps

Question: Please see following screenshot.

My code is
function get(position, html, resultsMap){

    //alert(position);
     var getDirection = new google.maps.InfoWindow({
        content: '',
        position: position
    });
    getDirection.close();
     getDirection.setContent(html);
       getDirection.open(resultsMap);
    }

Function call is
get(position, html, resultsMap);

All this working fine except above issue. I want to close previous infoWindow and display only new Infowindow, when click another link ( all links has same class).How to fix.
Comment: I didnt downvote, but I think you deserve it. Please see some more well-asked questions and try to understand the difference.
Comment: Only thing they can do is reduce my reputation :)
Comment: possible duplicate of [Auto close InfoWindow in googlemap](http://stackoverflow.com/questions/28138468/auto-close-infowindow-in-googlemap)
Comment: possible duplicate of [close InfoWindow before open another](http://stackoverflow.com/questions/14321808/close-infowindow-before-open-another)
Answer: Why not just reuse the infoWindow you already have for the new location?
HandleInfoWindow(self.places()[p], contentString, p);
map.setCenter(marker.location);

var HandleInfoWindow = function(place, content, index) {
      var position = {
        'lat': place.lat(),
        'lng': place.lng()
      };
      infoWindow.setContent(content);
      infoWindow.setPosition(position);
      infoWindow.open(map);
};
// Closes infoWindow
infoWindow.close();

Yes there is alot more code needed to get this all to work, but these parts will center your infoWindow and allow the reuse of it rather than creating who knows how many.
I've included also close code for you.


Como posso tirar a primeira diferença do PPC para cada país?

Question: eu estou fazendo um trabalho de econometria e gostaria de tirar a primeira diferença da Paridade do Poder de compra para os países em que estou analisando. O problema é que a base está em formato long, agrupada para os países, mas agora não sei como posso realizar o diff condicionando as informações?
# Dados
library(readxl)
PPC.World.Bank <- read_excel("Desktop/FGV EESP/Econometria 2/Data_Extract_From_World_Development_Indicators.xlsx")
View(PPC.World.Bank)

#Pacotes
library(dplyr)
library(tidyverse)
library(ggplot2)
library(ggthemes)
library(reshape2)

#Filtragem e Organização dos dados

  #Renomeando colunas
colnames(PPC.World.Bank) <- c(
  "Series Name", "Series Code", "Country Name", "Country Code","1994","1995",
  "1996","1997","1998","1999","2000","2001","2002","2003","2004","2005","2006",
  "2007","2008","2009","2010","2011","2012","2013","2014","2015","2016","2017",
  "2018","2019","2020","2021","2022")

  # Reovendo linhas em branco
PPC.1 = slice(PPC.World.Bank, 1:4)
View(PPC.1)

  #Formato long
PPC.long <-melt(PPC.1)
View(PPC.long)

  #Renomeando colunas
colnames(PPC.long) <- c(
  "Series Name", "Series Code", "Country Name", "Country Code","Ano", "Paridade do Poder de Compra")
Ano = PPC.long$Ano
PPC = PPC.long$`Paridade do Poder de Compra`

#Gráficos
graf.1.ppc = ggplot(data = PPC.long, mapping =aes(x = Ano, y = PPC, group = 1))+
  geom_line(size = 0.5)+ #queremos um gráfico de linhas
  geom_point(color = "Dark Red", size = 0.8) + facet_wrap(~PPC.long$`Country Name`, scales ='free_y') +
  scale_x_discrete(breaks =c('1994','1999','2004','2009','2013','2017', '2021'))+
  xlab('Ano')+
  ylab('')+
  ggtitle('Variação da Paridade do Poder de Compra na América Latina')+
  theme_hc() +
  theme(legend.key.width = unit(1, 'cm'))

    #Gráfico Interativo
library(plotly)
graf.1.ppc <- ggplotly(graf.1.ppc)
graf.1.ppc

#Aplicando a primeira diferença (??????)
PPC.long$D.PPC <- c(diff(PPC.long$`Paridade do Poder de Compra`[PPC.long$`Country Name` == 'Brazil']))

#Dados

  Country Name Country Code  Ano Paridade do Poder de Compra
1         Brazil          BRA 1994                   0.5186519
2       Colombia          COL 1994                 416.0606291
3          Chile          CHL 1994                 318.0708270
4         Mexico          MEX 1994                   2.5233760
5         Brazil          BRA 1995                   0.8375032
6       Colombia          COL 1995                 489.2790238
7          Chile          CHL 1995                 332.0346800
8         Mexico          MEX 1995                   3.2874370
9         Brazil          BRA 1996                   0.9418661
10      Colombia          COL 1996                 574.2037233
11         Chile          CHL 1996                 337.8788510
12        Mexico          MEX 1996                   4.2009140
13        Brazil          BRA 1997                   0.9841012
14      Colombia          COL 1997                 664.6783632
15         Chile          CHL 1997                 344.2524390
16        Mexico          MEX 1997                   4.8611370
17        Brazil          BRA 1998                   1.0000209
18      Colombia          COL 1998                 776.7906741
19         Chile          CHL 1998                 353.3377630
20        Mexico          MEX 1998                   5.4995960
21        Brazil          BRA 1999                   1.0261538
22      Colombia          COL 1999                 842.8132316
23         Chile          CHL 1999                 357.2808230
24        Mexico          MEX 1999                   6.2246400
25        Brazil          BRA 2000                   1.0625565
26      Colombia          COL 2000                 890.4723000
27         Chile          CHL 2000                 363.4930230
28        Mexico          MEX 2000                   6.7508860
29        Brazil          BRA 2001                   1.1040372
30      Colombia          COL 2001                 935.0151684
31         Chile          CHL 2001                 373.5080360
32        Mexico          MEX 2001                   6.9152720
33        Brazil          BRA 2002                   1.1786367
34      Colombia          COL 2002                 978.8812648
35         Chile          CHL 2002                 381.0144050
36        Mexico          MEX 2002                   7.2375840
37        Brazil          BRA 2003                   1.3220601
38      Colombia          COL 2003                1025.4050898
39         Chile          CHL 2003                 382.5364820
40        Mexico          MEX 2003                   7.3441190
41        Brazil          BRA 2004                   1.3725329
42      Colombia          COL 2004                1057.6024091
43         Chile          CHL 2004                 380.3494520
44        Mexico          MEX 2004                   7.4658230
45        Brazil          BRA 2005                   1.4186871
46      Colombia          COL 2005                1074.5689477
47         Chile          CHL 2005                 387.3600000
48        Mexico          MEX 2005                   7.6483310
49        Brazil          BRA 2006                   1.4318482
50      Colombia          COL 2006                1085.6711396
51         Chile          CHL 2006                 338.4908630
52        Mexico          MEX 2006                   7.7403490
53        Brazil          BRA 2007                   1.4428266
54      Colombia          COL 2007                1114.0917494
55         Chile          CHL 2007                 343.1078220
56        Mexico          MEX 2007                   7.9550070
57        Brazil          BRA 2008                   1.4683860
58      Colombia          COL 2008                1147.9895518
59         Chile          CHL 2008                 360.3642160
60        Mexico          MEX 2008                   8.1585910
61        Brazil          BRA 2009                   1.5456568
62      Colombia          COL 2009                1200.4853878
63         Chile          CHL 2009                 367.5612430
64        Mexico          MEX 2009                   8.4331810
65        Brazil          BRA 2010                   1.5973411
66      Colombia          COL 2010                1207.9398723
67         Chile          CHL 2010                 373.2912300
68        Mexico          MEX 2010                   8.7250210
69        Brazil          BRA 2011                   1.6512214
70      Colombia          COL 2011                1210.9931641
71         Chile          CHL 2011                 370.1987370
72        Mexico          MEX 2011                   8.9402120
73        Brazil          BRA 2012                   1.6626555
74      Colombia          COL 2012                1189.5036621
75         Chile          CHL 2012                 391.5723640
76        Mexico          MEX 2012                   9.2234710
77        Brazil          BRA 2013                   1.7916766
78      Colombia          COL 2013                1220.9112549
79         Chile          CHL 2013                 390.1613030
80        Mexico          MEX 2013                   9.1808920
81        Brazil          BRA 2014                   1.9007571
82      Colombia          COL 2014                1249.0191650
83         Chile          CHL 2014                 410.6707420
84        Mexico          MEX 2014                   9.3536260
85        Brazil          BRA 2015                   2.0829582
86      Colombia          COL 2015                1305.7772217
87         Chile          CHL 2015                 447.2666320
88        Mexico          MEX 2015                   9.4335910
89        Brazil          BRA 2016                   2.2490232
90      Colombia          COL 2016                1403.3064550
91         Chile          CHL 2016                 452.9225690
92        Mexico          MEX 2016                   9.4599330
93        Brazil          BRA 2017                   2.3273771
94      Colombia          COL 2017                1467.2812320
95         Chile          CHL 2017                 463.2314130
96        Mexico          MEX 2017                  10.1353830
97        Brazil          BRA 2018                   2.3551456
98      Colombia          COL 2018                1464.4117980
99         Chile          CHL 2018                 458.3124900
100       Mexico          MEX 2018                  10.3514900
101       Brazil          BRA 2019                   2.3995772
102     Colombia          COL 2019                1516.4399870
103        Chile          CHL 2019                 465.2358790
104       Mexico          MEX 2019                  10.7914090
105       Brazil          BRA 2020                   2.4464668
106     Colombia          COL 2020                1529.9317530
107        Chile          CHL 2020                 469.0956380
108       Mexico          MEX 2020                  10.7418270
109       Brazil          BRA 2021                   2.5306766
110     Colombia          COL 2021                1567.4466590
111        Chile          CHL 2021                 477.8180280
112       Mexico          MEX 2021                  11.0856900

Answer: Aqui estão duas maneiras diferentes de calcular as diferenças anuais de PPC.
suppressPackageStartupMessages(library(dplyr))

res1 <- PPC.long %>%
  group_by(Name) %>%
  arrange(Ano) %>%
  mutate(DiffPPC = `Paridade do Poder de Compra` - lag(`Paridade do Poder de Compra`, default = 0))

res2 <- PPC.long %>%
  group_by(Name) %>%
  arrange(Ano) %>%
  mutate(DiffPPC = c(first(`Paridade do Poder de Compra`), diff(`Paridade do Poder de Compra`)))

identical(res1, res2)
#> [1] TRUE

Created on 2022-09-21 with reprex v2.0.2

Dados
PPC.long <- read.table(text = "
 Country Name 'Country Code'  Ano 'Paridade do Poder de Compra'
1         Brazil          BRA 1994                   0.5186519
2       Colombia          COL 1994                 416.0606291
3          Chile          CHL 1994                 318.0708270
4         Mexico          MEX 1994                   2.5233760
5         Brazil          BRA 1995                   0.8375032
6       Colombia          COL 1995                 489.2790238
7          Chile          CHL 1995                 332.0346800
8         Mexico          MEX 1995                   3.2874370
9         Brazil          BRA 1996                   0.9418661
10      Colombia          COL 1996                 574.2037233
11         Chile          CHL 1996                 337.8788510
12        Mexico          MEX 1996                   4.2009140
13        Brazil          BRA 1997                   0.9841012
14      Colombia          COL 1997                 664.6783632
15         Chile          CHL 1997                 344.2524390
16        Mexico          MEX 1997                   4.8611370
17        Brazil          BRA 1998                   1.0000209
18      Colombia          COL 1998                 776.7906741
19         Chile          CHL 1998                 353.3377630
20        Mexico          MEX 1998                   5.4995960
21        Brazil          BRA 1999                   1.0261538
22      Colombia          COL 1999                 842.8132316
23         Chile          CHL 1999                 357.2808230
24        Mexico          MEX 1999                   6.2246400
25        Brazil          BRA 2000                   1.0625565
26      Colombia          COL 2000                 890.4723000
27         Chile          CHL 2000                 363.4930230
28        Mexico          MEX 2000                   6.7508860
29        Brazil          BRA 2001                   1.1040372
30      Colombia          COL 2001                 935.0151684
31         Chile          CHL 2001                 373.5080360
32        Mexico          MEX 2001                   6.9152720
33        Brazil          BRA 2002                   1.1786367
34      Colombia          COL 2002                 978.8812648
35         Chile          CHL 2002                 381.0144050
36        Mexico          MEX 2002                   7.2375840
37        Brazil          BRA 2003                   1.3220601
38      Colombia          COL 2003                1025.4050898
39         Chile          CHL 2003                 382.5364820
40        Mexico          MEX 2003                   7.3441190
41        Brazil          BRA 2004                   1.3725329
42      Colombia          COL 2004                1057.6024091
43         Chile          CHL 2004                 380.3494520
44        Mexico          MEX 2004                   7.4658230
45        Brazil          BRA 2005                   1.4186871
46      Colombia          COL 2005                1074.5689477
47         Chile          CHL 2005                 387.3600000
48        Mexico          MEX 2005                   7.6483310
49        Brazil          BRA 2006                   1.4318482
50      Colombia          COL 2006                1085.6711396
51         Chile          CHL 2006                 338.4908630
52        Mexico          MEX 2006                   7.7403490
53        Brazil          BRA 2007                   1.4428266
54      Colombia          COL 2007                1114.0917494
55         Chile          CHL 2007                 343.1078220
56        Mexico          MEX 2007                   7.9550070
57        Brazil          BRA 2008                   1.4683860
58      Colombia          COL 2008                1147.9895518
59         Chile          CHL 2008                 360.3642160
60        Mexico          MEX 2008                   8.1585910
61        Brazil          BRA 2009                   1.5456568
62      Colombia          COL 2009                1200.4853878
63         Chile          CHL 2009                 367.5612430
64        Mexico          MEX 2009                   8.4331810
65        Brazil          BRA 2010                   1.5973411
66      Colombia          COL 2010                1207.9398723
67         Chile          CHL 2010                 373.2912300
68        Mexico          MEX 2010                   8.7250210
69        Brazil          BRA 2011                   1.6512214
70      Colombia          COL 2011                1210.9931641
71         Chile          CHL 2011                 370.1987370
72        Mexico          MEX 2011                   8.9402120
73        Brazil          BRA 2012                   1.6626555
74      Colombia          COL 2012                1189.5036621
75         Chile          CHL 2012                 391.5723640
76        Mexico          MEX 2012                   9.2234710
77        Brazil          BRA 2013                   1.7916766
78      Colombia          COL 2013                1220.9112549
79         Chile          CHL 2013                 390.1613030
80        Mexico          MEX 2013                   9.1808920
81        Brazil          BRA 2014                   1.9007571
82      Colombia          COL 2014                1249.0191650
83         Chile          CHL 2014                 410.6707420
84        Mexico          MEX 2014                   9.3536260
85        Brazil          BRA 2015                   2.0829582
86      Colombia          COL 2015                1305.7772217
87         Chile          CHL 2015                 447.2666320
88        Mexico          MEX 2015                   9.4335910
89        Brazil          BRA 2016                   2.2490232
90      Colombia          COL 2016                1403.3064550
91         Chile          CHL 2016                 452.9225690
92        Mexico          MEX 2016                   9.4599330
93        Brazil          BRA 2017                   2.3273771
94      Colombia          COL 2017                1467.2812320
95         Chile          CHL 2017                 463.2314130
96        Mexico          MEX 2017                  10.1353830
97        Brazil          BRA 2018                   2.3551456
98      Colombia          COL 2018                1464.4117980
99         Chile          CHL 2018                 458.3124900
100       Mexico          MEX 2018                  10.3514900
101       Brazil          BRA 2019                   2.3995772
102     Colombia          COL 2019                1516.4399870
103        Chile          CHL 2019                 465.2358790
104       Mexico          MEX 2019                  10.7914090
105       Brazil          BRA 2020                   2.4464668
106     Colombia          COL 2020                1529.9317530
107        Chile          CHL 2020                 469.0956380
108       Mexico          MEX 2020                  10.7418270
109       Brazil          BRA 2021                   2.5306766
110     Colombia          COL 2021                1567.4466590
111        Chile          CHL 2021                 477.8180280
112       Mexico          MEX 2021                  11.0856900
", header = TRUE, check.names = FALSE)

str(PPC.long)
#> 'data.frame':    112 obs. of  5 variables:
#>  $ Country                    : int  1 2 3 4 5 6 7 8 9 10 ...
#>  $ Name                       : chr  "Brazil" "Colombia" "Chile" "Mexico" ...
#>  $ Country Code               : chr  "BRA" "COL" "CHL" "MEX" ...
#>  $ Ano                        : int  1994 1994 1994 1994 1995 1995 1995 1995 1996 1996 ...
#>  $ Paridade do Poder de Compra: num  0.519 416.061 318.071 2.523 0.838 ...

Created on 2022-09-21 with reprex v2.0.2
Comment: Muito obrigada!!!! Só mais uma dúvida, onde eu teria que alterar no código pr tirar a segunda diferença?
Comment: @CarolHesser Com a função `dplyr::lag` é o argumento `n = 2`; com a função base `diff` é `lag = 2`.