Get the values of views fields in a Twig template

Question: I have created a view that outputs 3 fields for each row. Just using views, i can get the output to look something like this:

[Field1 Value] [field2 value] [field3 value]

I have a requirement to set a data-attribute on the list items to on of the field values. Also, I want to wrap an anchor linking to the detail view of the content around all three field values.
I've tried using a twig template like views-view-fields.html.twig (too generic i know, but for testing purposes) but the values dont seem to be there. I can do {{ dump (fields|keys) }} and i see my fields there, but if i do {{ dump (fields.my_field|keys) }} then its just an empty array.
I also tried using a template like page--[name of my page created by views].html.twig but couldn't seem to find the values for those fields there either.
Any help on advice as to where I should be looking, particulary which twig templates I might create/override and how to get the values would be very much appreciated!
Comment: Couldn't find a way round this, so ended up just rending the values using views and restructuring it using jQuery, not the nicest, but it worked.
Answer: In the template file (views-view-field), you can use

 {{ row._entity.field_name1.value }} {{ row._entity.field_name2.value }} {{ row._entity.field_name3.value }}

Or, in your theme, in the preprocess function you can overwrite the output:
function your_theme_name_preprocess_views_view_field(&$variables) {
    $view = $variables['view'];
    if ($view->storage->id() == 'your_view_name') {
        $variables['output'] = '
' .
          $variables['row']->_entity->field_name1->value .
          $variables['row']->_entity->field_name2->value .
          $variables['row']->_entity->field_name3->value .
        '
';
    }
}

Answer: Actually you can use views templates the way it was in Drupal 7. Although there is no theme info in the advanced part of views settings you can take basic templates from templates folder of the core views module.
To create a views template for each row name it views-view-fields--VIEW-NAME.html.twig where VIEW-NAME is a machine name of your view or views-view-fields--VIEW-NAME--DISPLAY-NAME.html.twig where DISPLAY-NAME is a display you are using(block, page etc). Add them in your templates theme folder.
Use template_preprocess_views_view_fields(&$variables) function to preprocess each row.
In your template fields are available this way {{ fields.field_name.content }}
Answer: Will $row get what you need instead of the processed field entity?
{{ kint(row.node_field_data_created) }}
Comment: You've put me onto kint and devel, which is really helpful thanks. I've been using kint to see what variables are available to me in the two templates, but unable to get the values i need out in these two templates.


Aplicação não salva dados e só salva código

Question: Estou desenvolvendo um software para uma videolocadora com design pattern MVC (Model-view-controller) e está ocorrendo o problema de não salvar as pessoas.
Só salva o código das pessoas e nem sei o porque que está acontecendo de não salvar os clientes pois o meu código-fonte não apresenta erros!
No banco de dados MySQL as pessoas não estão com a opção assinalada NOT NULL.
Classe VideoPessoa, da camada view:
public class VideoPessoa extends javax.swing.JFrame {

    PessoaController pessoaController;
    Pessoa pessoa;

    /**
     * Creates new form Pessoa
     */
    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
    }

private boolean salvarPessoa(){

     if (pessoaController.salvar(pessoa)) {
     JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");

    }else{

            JOptionPane.showMessageDialog(this, "Erro ao gravar os dados!", "ERRO", JOptionPane.ERROR_MESSAGE);

        }

    return true;

    }

Classe PessoaController:
  public class PessoaController {

    private final PessoaDAO pessoaDAO;

    public PessoaController() {
        pessoaDAO = new PessoaDAO();

    }

    public boolean salvar(Pessoa pessoa) {
  boolean retorno ;

    retorno = pessoaDAO.salvar(pessoa);

  return retorno;
}

Classe PessoaDAO, incluindo o método de salvar pessoas:
public class PessoaDAO {

    private Connection con;

    private final String SQLINSERT = " INSERT INTO pessoa(nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade)"
            + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ";

    private final String SQLPESSOAPELOCODIGO = "SELECT  nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade"
            + " FROM pessoa"
            + " WHERE codigo=? ";

    private final String SQLSELECT = " SELECT  codigo, nome, endereco, bairro, sexo, telefone, celular, CPF,  uf, cidade FROM PESSOA";

    private final String SQLUPDATE = " UPDATE pessoa"
            + " SET nome = ?, "
            + " endereco = ?, "
            + " bairro   = ?, "
            + " sexo     = ?, "
            + " telefone = ?, "
            + " celular  = ?, "
            + " CPF      = ?, "

            + " uf       =?, "
            + " cidade   =?, "
            + " WHERE codigo = ?";
    private final String SQLDELETE = "DELETE FROM pessoa"
            + " WHERE codigo = ?";

    private PreparedStatement psInsert, sqlPessoaPeloCodigo, sqlSelect, sqlUpdate, sqlDelete;

    public PessoaDAO() {

        con = Conexao.getConnection();
        try {
            psInsert = con.prepareStatement(SQLINSERT);
            sqlPessoaPeloCodigo = con.prepareStatement(SQLPESSOAPELOCODIGO);
            sqlSelect = con.prepareStatement(SQLSELECT);
            sqlUpdate = con.prepareStatement(SQLUPDATE);
            sqlDelete = con.prepareStatement(SQLDELETE);
        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

public Pessoa getPessoaPeloCodigo(int codigo) {

        Pessoa pessoa = null;

        try {
            sqlPessoaPeloCodigo.setInt(1, codigo);
            ResultSet rs = sqlPessoaPeloCodigo.executeQuery();

            if (rs.next()) {
                //Instancia o novo filme
                pessoa = new Pessoa();

                //Seta as informações no filme
                pessoa.setCodigo(rs.getInt("codigo"));
                pessoa.setNome(rs.getString("nome"));
                pessoa.setEndereco(rs.getString("endereco"));
                pessoa.setBairro(rs.getString("bairro"));
                pessoa.setSexo(rs.getString("sexo"));
                pessoa.setTelefone(rs.getString("telefone"));
                pessoa.setCelular(rs.getString("celular"));
                pessoa.setCPF(rs.getString("CPF"));

                pessoa.setUf(rs.getString("uf"));
                pessoa.setCidade(rs.getString("cidade"));

            }
        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return pessoa;
    }

 public boolean salvar(Pessoa pessoa) {
        boolean retorno = false;

        try {
            psInsert.setString(1, pessoa.getNome());
            psInsert.setString(2, pessoa.getEndereco());
            psInsert.setString(3, pessoa.getBairro());
            psInsert.setString(4, pessoa.getSexo());
            psInsert.setString(5, pessoa.getTelefone());
            psInsert.setString(6, pessoa.getCelular());
            psInsert.setString(7, pessoa.getCPF());
            psInsert.setString(8, pessoa.getUf());
            psInsert.setString(9, pessoa.getCidade());

            psInsert.executeUpdate();
            retorno = true;

        } catch (SQLException ex) {
            Logger.getLogger(PessoaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return retorno;
    }

Classe Conexao:
public class Conexao {

    private static Connection con;

    public Conexao() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sistemavideolocadora2", "root", "1234");

            System.out.println(" Conexão obtida!!! ");

        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);

            System.out.println(" Conexão estabelecida com sucesso!!! ");
        }
    }

    public static Connection getConnection() {
        return con;

    }

    public static void closeConnection() {
        try {
            con.close();

            System.out.println(" Conexão fechada!!! ");
        } catch (SQLException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);

            System.out.println(" Conexão finalizada com sucessso!!! ");
        }
    }

}

Answer: Você não setou valores no objeto pessoa, pelo menos não achei o métodos sets no código:
    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
    }

    private boolean salvarPessoa(){

     if (pessoaController.salvar(pessoa)) {
     JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");
ETC...

Portanto passa pessoaController.salvar(vazio), o correto seria:
    public VideoPessoa() {
        initComponents();

        new Conexao();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
        pessoa.setnome('alguem');
        pessoa.settelefone('(11) 999991111');
    }

    private boolean salvarPessoa(){

     if (pessoaController.salvar(pessoa)) {
     JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");
ETC...

Não sei se a syntax ta certa, qualquer erro na reposta favor informar, obrigado.
Comment: @Techies, Deve ser e só não retorna erro por que deve ser tudo not null e chave primária auto incremental no banco de dados.
Comment: @Techies dá desconto que sou iniciante ainda!
Comment: Creio que esse seja um dos problemas, como ele mesmo disse quando ele coloca um `sysout` no método salvarPessoa() isso é exibido: Pessoa: Pessoa{nome=null, endereco=null, bairro=null, sexo=null, telefone=null, celular=null, CPF=null, codigo=0, cidade=null, uf=null, pessoa=null} `
Comment: Sim eu pensei nisso também, mas o código dele está muito "bagunçado" não consegui entender direito
Comment: @TiagoOliveiradeFreitas isso mesmo, mas os atributos da pessoa está com a opção [tag:null] assinalada.
Comment: @TiagoOliveiradeFreitas Era o que estava faltando para salvar os atributos da minha pessoa e eu não sabia que precisa setar eles antes da minha inserção.Valeu cara pela resposta!
Answer: Dei uma refatorada no seu código. Sempre que possível, utilize a sintaxe try-with-resources com recursos que devem ser fechados adequadamente tais como Connection, PreparedStatement e ResultSet. Essa sintaxe garante que eles serão fechados de forma adequada com o mínimo de esforço de programação por parte do programador. Evite manter estes recursos abertos por tempo maior que o necessário a menos que você tenha uma razão muito forte para fazer isso (e no seu caso, não há nenhuma).
Também, a forma de notificar a ocorrência de um problema é com o lançamento de exceções. Não faça return true; se deu certo e return false; se deu um erro, pois a finalidade para a qual as exceções existem é exatamente para que você não precise fazer isso, então aprenda a usá-las. Além disso, a exceção pode transportar mais informações sobre o erro que não seriam possíveis somente com um simples false.
Também certifique-se de preencher todos os dados de Pessoa na view, tal como explicado por diversos colegas nos comentários na pergunta.
Desta forma, o seu código fica assim:
/**
 * Classe que sinaliza a ocorrência de uma falha na persistência da aplicação.
 */
public class PersistenciaException extends Exception {

    /**
     * Construtor da exceção.
     * @param message A mensagem de erro.
     * @param cause A causa do erro.
     */
    public PersistenciaException(String message, Throwable cause) {
        super(message, cause);
    }
}

public class Conexao {

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private Conexao() {
        throw new UnsupportedOperationException("Esta classe não deve ser instanciada.");
    }

    public static Connection openConnection() {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/sistemavideolocadora2", "root", "1234");
    }
}

public class PessoaDAO {

    private final String SQLINSERT = " INSERT INTO pessoa(nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade)"
            + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ";

    private final String SQLPESSOAPELOCODIGO = "SELECT nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade"
            + " FROM pessoa"
            + " WHERE codigo = ?";

    private final String SQLSELECT = "SELECT codigo, nome, endereco, bairro, sexo, telefone, celular, CPF, uf, cidade FROM PESSOA";

    private final String SQLUPDATE = "UPDATE pessoa"
            + " SET nome = ?,"
            + " endereco = ?,"
            + " bairro   = ?,"
            + " sexo     = ?,"
            + " telefone = ?,"
            + " celular  = ?,"
            + " CPF      = ?,"
            + " uf       = ?,"
            + " cidade   = ?,"
            + " WHERE codigo = ?";

    private final String SQLDELETE = "DELETE FROM pessoa"
            + " WHERE codigo = ?";

    public PessoaDAO() {
    }

    public Pessoa getPessoaPeloCodigo(int codigo) throws PersistenciaException {
        try (
            Connection con = Conexao.openConnection();
            PreparedStatement ps = con.prepareStatement(SQLPESSOAPELOCODIGO)
        ) {
            ps.setInt(1, codigo);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) return null; // Não encontrou.
                // Instancia a nova pessoa.
                Pessoa pessoa = new Pessoa();

                // Seta as informações na pessoa
                pessoa.setCodigo(rs.getInt("codigo"));
                pessoa.setNome(rs.getString("nome"));
                pessoa.setEndereco(rs.getString("endereco"));
                pessoa.setBairro(rs.getString("bairro"));
                pessoa.setSexo(rs.getString("sexo"));
                pessoa.setTelefone(rs.getString("telefone"));
                pessoa.setCelular(rs.getString("celular"));
                pessoa.setCPF(rs.getString("CPF"));
                pessoa.setUf(rs.getString("uf"));
                pessoa.setCidade(rs.getString("cidade"));
                return pessoa;
            }
        } catch (SQLException ex) {
            throw new PersistenciaException("Problema de SQL na consulta de pessoa por código.", ex);
        }
    }

    public void salvar(Pessoa pessoa) throws PersistenciaException {
        try (
            Connection con = Conexao.openConnection();
            PreparedStatement psInsert = con.prepareStatement(SQLINSERT)
        ) {
            psInsert.setString(1, pessoa.getNome());
            psInsert.setString(2, pessoa.getEndereco());
            psInsert.setString(3, pessoa.getBairro());
            psInsert.setString(4, pessoa.getSexo());
            psInsert.setString(5, pessoa.getTelefone());
            psInsert.setString(6, pessoa.getCelular());
            psInsert.setString(7, pessoa.getCPF());
            psInsert.setString(8, pessoa.getUf());
            psInsert.setString(9, pessoa.getCidade());

            psInsert.executeUpdate();
        } catch (SQLException ex) {
            throw new PersistenciaException("Problema de SQL na inserção de pessoa.", ex);
        }
    }
}

public class PessoaController {
    private final PessoaDAO pessoaDAO;

    public PessoaController() {
        pessoaDAO = new PessoaDAO();
    }

    public void salvar(Pessoa pessoa) throws PersistenciaException {
        pessoaDAO.salvar(pessoa);
    }
}

public class VideoPessoa extends javax.swing.JFrame {
    private final PessoaController pessoaController;
    private Pessoa pessoa;

    /**
     * Creates new form Pessoa
     */
    public VideoPessoa() {
        initComponents();
        pessoaController = new PessoaController();
        pessoa = new Pessoa();
    }

    private void salvarPessoa() {
        try {
            pessoaController.salvar(pessoa);
            JOptionPane.showMessageDialog(this, "Registro gravado com sucesso!");
        } catch (PersistenciaException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao gravar os dados!", "ERRO: " + ex.getMessage(), JOptionPane.ERROR_MESSAGE);
        }
    }

    // Resto da classe....
}

Comment: você me abriu os olhos e deu uma bela explicação para mim que muitos professores meus de faculdade não explicaram isso para mim durante minha faculdade.** Vou seguir seus conselhos e valeu cara! **
Comment: A palavra PersistenciaException  está dando erro e exibiu uma mensagenm que ela não tem javadoc e que tinha criar a classe para ela. Bem não sei como fazer isso.
Comment: @IgorContini Você não deveria ser obrigado a criar nenhum javadoc. Mas se por algum motivo você é obrigado a isso, atualizei a resposta com esse javadoc.
Comment: Beleza e valeu cara!
Comment: porque a classe não deve ser instanciada? Eu preciso que ela seja instanciada!
Comment: @IgorContini Esta pergunta é do ano passado, então não lembro direito o que você queria. Bem, a única classe que não é instanciável aqui é a `Conexao`, o motivo é porque uma instância dela não serviria para nada, uma vez que o único método desta classe que faz sentido ser chamado é estático. Entretanto, caso esta classe sofra algum tipo de alteração, ela pode vir a necessitar tornar-se instanciável.
Comment: Bem preciso que ela seja instanciada para meu DAO e quando rodo o meu sistema, dá esse erro: `throw new UnsupportedOperationException("Esta classe não deve ser instanciada.")`
Comment: @IgorContini Essa exceção é lançada de dentro do construtor. Se você realmente precisa instanciar isso, é só apagar a linha do `throw` que está dentro do construtor. Entretanto, lembre-se que normalmente só faz sentido instanciar-se uma classe se você for usar os métodos de instância (não-estáticos) dela. A finalidade desta exceção é apenas não deixar você fazer uma operação sem sentido (instanciar uma classe para a qual a instância não serve para nada). Entretanto, se agora as instâncias fizerem sentido, essa exceção não seria mais necessário ou desejável e daí bastaria retirar o `throw`.
Comment: Apaguei a linha e causou outro erro: ` java.lang.RuntimeException: Uncompilable source code - unreported exception util.PersistenciaException; must be caught or declared to be thrown `
Comment: @IgorContini Acho que você está usando o eclipse e fazendo hot-deploy. Recompile toda a aplicação e me diga qual é o erro de compilação e onde ele acontece.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/43481/discussion-between-igor-contini-and-victor-stafusa).


Can okhttp3.internal.http2.StreamResetException: stream was reset: INTERNAL_ERROR be caused by API call limit?

Question: I'm using Retrofit to request data from a websites API which has a limit of 50calls/minute (varies) but I'm repeatedly getting this error:
okhttp3.internal.http2.StreamResetException: stream was reset: INTERNAL_ERROR

Is it possible that I'm getting this error because I'm reaching that call limit which varies?
Comment: Did you check my answer?
Comment: yeah, but I'm still getting the error
Answer: This is a server error after the headers are sent.
You should restricting the request to use HTTP 1 like this :
JAVA :
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));

KOTLIN:
OkHttpClient().also {
        it.protocols().add(Protocol.HTTP_1_1)
 }


running sh script on travis CI: The command exited with 1

Question: I am running an sh script as part of my .travis.yml. It is giving me the error below although the shell script does not fail.

The command exited with 1.

I tried running the with bash -x to debug and there are no errors.
The problem is that travis thinks that the build failed although it passed.
Comment: What does your .travis.yml look like? what's in the script?
Comment: https://github.com/mosaadm/mooltipass/blob/master/.travis.yml
Answer: This change fixes it.
As explained in the man bash page:

Shell builtin commands return a status of 0 (true) if successful, and
  non-zero (false) if an error
         occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.
Bash  itself returns the exit status of the last command executed,
  unless a syntax error occurs, in which case it exits with a non-zero
  value.  See also the exit builtin command below.

The last command executed is:
[ "$BUILD_CHROMIUM" == 1 ] &&_build_chromium_crx "${zip_file}" "${BUILD_METADATA[${CHROMIUM_TARGET}]}"

And it is evaluated as false with exit status 1:
'[' 0 == 1 ']'

So adding || true at the end of this line fixes it. The exit status will always be 0.
Alternatively, use the fix that better suits the expected behavior of your code like exit 0, etc.
As explained here and here:

exit [n] Cause the shell to exit with a status of n. If n is omitted,
  the exit status is that of the last command executed. A trap on EXIT
  is executed before the shell terminates.

So your clean function trap _clean_chrome EXIT is not the last to be executed.
Further information about exit status here.


Estimating the standard deviation of the constituent parts of a combined variable

Question: I have a random variable $Z$. Each measurement in $Z$ is in reality the sum of two other random variables $X$ and $Y$.
Both $X$ and $Y$ are independent random variables. They should have the same standard deviation. They should also have similar means if that assumption needs to be made.
Given that I can only measure $Z$, can I estimate the standard deviation of $X$ and $Y$?
Comment: By your assumption, $\text{var}(Z) = \text{var}(X) + \text{var}(Y) = 2\sigma^2$. You can use the sample variance to estimate $2\sigma^2$, hence get an estimate of $\sigma$.
Answer: If you know $\text{Var}(X) = \text{Var}(Y)$, $X$ and $Y$ are independent, and that $Z = X + Y$, then $\text{Var}(X) = \text{Var}(Y) = \text{Var}(Z) / 2$.  So you can estimate both by estimating $\text{Var}(Z)$.
Comment: Then yes, $Z=X+Y$
Comment: Each sample of $Z$ is a sum of a sample of $X$ and sample of $Y$. Does this imply $Z=X+Y$? - I'm a little bit fuzzy on stats notation.
Comment: Gerald If you could observe the x-values and y-values, would $z_i=x_i+y_i$?
Comment: @Glen_b: Yes that's my situation.


How to window.scrollTo() with a smooth effect

Question: I can scroll to 200px using the following
btn.addEventListener("click", function(){
    window.scrollTo(0,200);
})

But I want a smooth scroll effect. How do I do this?
Comment: It is possible to do using. `window.scrollTo({ top: 200, behavior: 'smooth' });` I'd like to add it as anwer but question is closed.
Comment: Possible duplicate of [Smooth scrolling when clicking an anchor link](http://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link)
Comment: DOH! US English - behaviour: 'smooth' will get you nowhere...
Comment: Just a note for future generations (available from Chrome 61) "The CSSOM View Smooth Scroll API brings native smooth scrolling to the platform through a the scroll-behavior: smooth CSS property or by using the window.scrollTo() DOM scroll method, eliminating the need to implement this behavior with JavaScript"
Comment: Place an empty element in the top of your page, then you can use document.querySelector('your-element').scrollIntoView({behavior: 'smooth'});
Answer: 2023 Update
Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

const btn = document.getElementById('elem');

btn.addEventListener('click', () => window.scrollTo({
  top: 400,
  behavior: 'smooth',
}));
#x {
  height: 1000px;
  background: lightblue;
}

  <button id='elem'>Click to scroll</button>

Older solutions
You can do something like this:

var btn = document.getElementById('x');

btn.addEventListener("click", function() {
  var i = 10;
  var int = setInterval(function() {
    window.scrollTo(0, i);
    i += 10;
    if (i >= 200) clearInterval(int);
  }, 20);
})
body {
  background: #3a2613;
  height: 600px;
}
<button id='x'>click</button>

ES6 recursive approach:

const btn = document.getElementById('elem');

const smoothScroll = (h) => {
  let i = h || 0;
  if (i < 200) {
    setTimeout(() => {
      window.scrollTo(0, i);
      smoothScroll(i + 10);
    }, 10);
  }
}

btn.addEventListener('click', () => smoothScroll());
body {
  background: #9a6432;
  height: 600px;
}
<button id='elem'>click</button>
Comment: @PetrNagy yea `behavior: 'smooth'` also not working on iOS. I think we still need to use the old solution for WebKit on Mac and iOS.
Comment: Safari for OSX seems to ignore the `behavior: 'smooth'` parameter while using `window.scrollTo`.
Comment: For really smooth transitions you rather use `requestAnimationFrame` https://codepen.io/dsheiko/pen/XZEgXW
Comment: Is this an efficient method?
Comment: Seems to be a bug in Edge at the moment preventing ScrollTo from working: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/15534521/
Comment: Is there a way to stop the scrolling before it reaches it's end position? For example, you have a button click to initiate the scroll with a top position of 400. What about another button with a click event to stop the scroll wherever it currently is at it's current point in time? Say while it's scrolling and it's reached 250, you hit the button and it would stop the scroll at 250 instead of the initial 400 you currently set as the top param for the first button?
Comment: @Andrew You mean the solution with recursion? Not the `behavior` method?
Comment: in windows (win 10 edu v1909),  css `scroll-behavior: smooth` is not smooth if you disable `display animations in windows` in control panel. So you have to choose @kinduser 's  **old solution** if you want your smooth scrolling happens in any case
Comment: **but is there any way to set the rate at which it scrolls?** it seems always at some point when you increase the amount of scroll that it becomes "jumpy" instead of smooth :/
Comment: behavior: 'smooth' has never worked for me in any browser. Does this work for anyone?
Comment: If you use `getElementsByClassName` instead `getElementById`, will occur the error: `".addEventListener is not a function"`, to solve it use  `btn[0].addEventListener`. See more in [link](https://stackoverflow.com/questions/32027935/addeventlistener-is-not-a-function-why-does-this-error-occur)
Comment: to behavior works, use in the CSS `html:focus-within { scroll-behavior: smooth;}`
Comment: `window.scrollTo({ top: 0, behavior: 'smooth' })` seems to be working for me on Safari in Jun 2022, macOS Monterey, Safari 15.4
Answer: $('html, body').animate({scrollTop:1200},'50');

You can do this!
Comment: Is the problem, jQuery is simple.. And I don't like when is simple. I prefer to go deeper my knowledge in pure JS (Vanilla) and after that I can use jQuery. It's my philosophy
Comment: 1year after, I think the `scrollTo`are evolved, your script are deprecated for me because now, we can pass an object into `scrollTo` like that :

`window.scrollTo({ top: 0, behavior: 'smooth' });`
And we are the same effect with less line code, and it's supported by old and recent browser :)
Comment: Yes, I'm right with you, but you are using jQuery, and I want using only Vanilla. But I agree with you, with jQuery is more simple
Comment: yes bro. that's only jquery but you can use that. jQuery is very simple.
Comment: Not only that but jquery can cause some serious jank when scrolling while changing the height of elements (using `.show()` or `.slideDown()` while using `scrollTop()` for instance). jQuery can be nice for quick/trivial stuff, but it's just a facade for real js. Check this one out! https://pawelgrzybek.com/page-scroll-in-vanilla-javascript/
Answer: You can add on the css
* {scroll-behavior: smooth;}
the asterisk prolly means window idk but it works on mine


GCC, C11, How to display a macro calculated value in C?

Question: I'm trying to show this in C (gcc, C11)
<code>#define xstr(a) _str(a)
#define _str(a) #a

#pragma message "System clock = " xstr(SYS_CLOCK)
</code>
Now the SYS_CLOCK is a macro, computing from values of prescalers, dividers, etc
But the message is not calculated
<code>#pragma message: System clock= ((8000000u/4)*50)/4
</code>
Which is better than nothing :) but actually, I'd be very happy if I can show 25000000 Hz.
Can be done with some preprocesor magic?
Thanks,
Comment: Most probably it can't be done, because all preprocessors I know do no calculations. Did you look into the standard to see what is required? And additionally, what does the GCC documentation say? If its preprocessor would do calculations, I'd expect that it's documented.
Comment: See also https://stackoverflow.com/questions/1560357/can-the-c-preprocessor-perform-integer-arithmetic
Answer: Preprocessor does not calculate any values (except needed by the <code>#if</code>). It is done during the compilation. Everything is done at the token level.


Writing a function to run a F-test with two separate shapiro-wilks tests conducted inside the function

Question:
The function should perform as follows: The function takes the
arguments: x1, x2, alt = "two-sided", lev = 0.95, where the equality
indicates the default value.
•The arguments x1 and x2 are the X1 and X2 samples, respectively.
•The argument alt is the alternative hypothesis whose two other
possible values are "greater" and "less".
•The argument lev is the confidence level 1 −α. ii. The function
returns an R list containing the test statistic, p-value, confidence
level, and confidence interval.
iii. Inside the function, two Shapiro-Wilk tests of normality are
conducted separately for the two samples (note the normality
assumption at the beginning of the problem). If one or both p-values
are less than 0.05, a warning message is printed out explaining the
situation.

Here is what I have come up with so far but not sure how to create one function to run both:
library(stats)
x1 <- c(103, 94, 110, 87, 98, 102, 86, 98, 109, 92)
x2 <- c(97, 82, 123, 92, 175, 88, 118, 81, 165, 97, 134, 92, 87, 114)
var.test(x1, x2, alternative = "two.sided", conf.level = 0.95)

shapiro.test(x1)$p.value < 0.05|shapiro.test(x2)$p.value < 0.05

Answer: Some hints:

Your task is to write a function, so you should have something like this:

my_function <- function(x1, x2, alt = "two-sided", level = 0.95){
  # fill in the body of the function here
}

You can do whatever you need to do in the body of the function.

Recall that in R, the last evaluated line of a function is automatically its returned value. So, you might choose to have your last line be list(...) as described in the problem statement.

It will be useful to store results of tests, etc. as variables inside your function, e.g. test_output_1 <- ... so that you can reference those things later in the body of your function.
Comment: So is the body of the function supposed to be the steps of the f-test (finding variance, f-statistic, p-value, etc.)?
Comment: Reading your description of the problem, it looks like your function should first run Shapiro-Wilk tests of normality (and output a warning message if either vector appears to be sufficiently non-normal), then to execute `var.test()`. Note that you should use the parameters that got passed into your function, i.e. `var.test(x1, x2, alternative = alt, conf.level = level)`.


Automatically generate required Plotly data structure

Question: I wanted to generate an interactive scatter plot in Python3 using Plotly. Plotly requires the input for the data to be in a specific format. I would like to be able to generate the format automatically because I have a lot of data.
Plotly requires data for the scatter plot in the following format
fig = {
    'data': [
  {
        'x': sim_corr.AAK1,
        'y': sim_pas.AAK1,
        'text': sim_corr.index,
        'mode': 'markers',
        'name': 'AAK1'},
        {
        'x': sim_corr.ABL1,
        'y': sim_pas.ABL1,
        'text': sim_corr.index,
        'mode': 'markers',
        'name': 'ABL1'},
            {
        'x': sim_corr.ABL2,
        'y': sim_pas.ABL2,
        'text': sim_corr.index,
        'mode': 'markers',
        'name': 'ABL2'}
],
    'layout': {
        'title':'Correlation VS PAS',
        'hovermode':'closest',
        'xaxis': {'title': 'Correlations'},
        'yaxis': {'title': "PAS"}
    }
}

where sim_corr and sim_pas are two pandas data frames and AAK1 is a column name found in both data frames. Above is only 3 columns out of 207. I have generated the plot by manually inputting each column, but I am sure there is a more efficient way. I really do not have a clue to how this will be done.
Here is code to produce similar data frames on a smaller scale,
import pandas as pd
df1 = pd.DataFrame(data = [[1,2,3,4], [4,5,6,7], [7,8,9,10], [10,11,12,13]], index = ["a", 'b', 'c', 'd'], columns = ['col1', 'col2', 'col3', 'col4'])
df2 = pd.DataFrame(data = [[4,2,5,4], [1,5,3,7], [2,8,5,10], [3,11,7,13]], index = ["a", 'b', 'c', 'd'], columns = ['col1', 'col2', 'col3', 'col4'])

The expected results would be to automatically generate the data input in the required structure for all the columns in two data frames that share the exact same column names.
Answer: Okay so I found a way to creating this plot much faster than manually entering the data. First create a list of the column names in your first dataframe. using the example code provided above:
g = []
for i in range(0,len(df1.columns)):
    x = str("df1." + df1.columns[i])
    g.append(x)

second create a list of the column names in your second data frame.
h = []
for i in range(0,len(df2.columns)):
    x = str("df2." + df2.columns[i])
    h.append(x)

finally create a list of dictionaries while iterating over the column names in the two lists created in steps 1 and 2:
dics = []
for i in range(0,len(df1.columns)):
    d = {'x': g[i],
         'y': h[i],
         'text':df1.index,
         'mode':'markers',
         'name':str(df1.columns[i])}
    dics.append(d)

Now dics contains the data input in the format required. If anyone knows of an even more efficient way please add it below.
Comment: This the way to go for the moment. I'm doing this for every bigger project I'm building. :) Stil very inefficient for big data sets.


How do I manipulate a variable's property in Twig?

Question: I want to add classes to a link render element that's a property of the {{content}} variable in my template.
I can do this:
{% set link = content.my_link %}
{% set link = link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}

But I don't seem to be able to manipulate content.my_link directly. Why can't I do this:
{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ content.my_link }}

Answer: {% doesn't render, and merge doesn't operate by reference. With those two things in mind, this:
{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}

does nothing, except to waste CPU cycles; you're not rendering, nor saving, the result of the merge.
There are various ways to solve, this is probably the simplest:
{% set link = content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}


How can i attach my content type to level 1 taxonomies in multilevel taxonomy in drupal 7?

Question: I am using the default taxonomy of Drupal 7. I have a taxonomy like the following one:

Multilevel taxonomy (Vocabulary)

level 1 taxonomy  (Term)

level 2 taxonomy (Term)

I want my blog post have a field type of level 1 taxonomy.
Is there any module for this?
Answer: Checkout Hierarchical Select module. It offers many features.

Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!
Comment: Thanks for prompt reply, but it's not what i am looking for.
I want that text-field of term reference type to link with level 2 taxonomy


How can I use the same render cache but for json?

Question: I am working on REST API and I would really like to be able to use the same mechanism for responses as Drupal uses for cached content.
Unfortunately there is no render cache, everything is JSON responses. So there are no #ccache setting or page cache policy to be applied out of the box.
So I wonder if it is even possible and if so how should I approach it?
What I'm after basically is to cache the responses in the same manner as entities for example. So if the context is specific user and I am displaying entity information I would like to get fresh information if the entity is changed but the same content if not and the user is the same..and so on.
Answer: You have to use a cacheable response and then you can add cacheable metadata from a render array or from an object directly:
<code>use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;

  $response = new CacheableJsonResponse($json, 200);

  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));

  $response->addCacheableDependency($entity);
</code>
If you use the core REST API this should already be implemented.
Comment: Oh, didn't know about that. Will check it out. Thanks.
Comment: @4k4 Why I Can not render html first to be able to put in a JSON example to be printed?


Add two MKPolylineView

Question: i am having trouble to add two different MKPolylineView with diferent colors in a MKOverlayView. Any ideas on how to achieve this?
Thanks
Here is my code:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKOverlayView* overlayView = nil;
UIColor *mycolor;

self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];

mycolor = [UIColor colorWithRed:85.0/255.0 green:133.0/255.0 blue:255.0/255.0 alpha:0.6];
self.routeLineView.fillColor = mycolor;
self.routeLineView.strokeColor = mycolor;
self.routeLineView.lineWidth = 15;
[overlayView addSubview:self.routeLineView];

self.routeLineView2 = [[[MKPolylineView alloc] initWithPolyline:self.routeLine2] autorelease];
mycolor = [UIColor colorWithRed:85.0/255.0 green:19.0/255.0 blue:25.0/255.0 alpha:0.6];
self.routeLineView2.fillColor = mycolor;
self.routeLineView2.strokeColor = mycolor;
self.routeLineView2.lineWidth = 15;
[overlayView addSubview:self.routeLineView2];

return overlayView;
}

Answer: The viewForOverlay method will be called separately for each overlay you add to the map.  So in that method, you return just the overlay view for the overlay that it is currently being called for (ie. the overlay parameter).
Check which overlay it is requesting a view for and create and return a view only for that overlay.
For example:
if (overlay == self.routeLine)
{
    //create and return overlay view for routeLine...
    //set color, etc...
    return self.routeLineView;
}
else
if (overlay == self.routeLine2)
{
    //create and return overlay view for routeLine2...
    //set color, etc...
    return self.routeLineView2;
}

return nil;

Don't do any addSubview stuff.  Just create the overlay view and return it.

Add two MKPolylineView


CSS: Forcing blocks to appear under a float block if they overflow

Question: I'm creating a page with an image with several blocks of text next to it.  I don't want the blocks of text to wrap, because that looks bad.  But I also don't want to add "overflow: hidden" because that looks bad (specifically, the end of the block of text hangs past the image).
What I would like to do, and I don't know how, is to force the block to render under the floating element if it will overflow.  That way the block of text stays together (unlike allowing the overflow) AND it doesn't hang off the end all funny (like with "overflow:hidden").
Here's some html to demonstrate my problem.

Pretend there is an image here. Pretend there is an image
here. Pretend there is an image here. Pretend there is an image here. Pretend
there is an image here.

This is a paragraph.  It looks good next to the pretend image.

This is a paragraph.  It hangs off the pretend image and looks bad.  I wish that
if the paragraph was too long it would appear under the image.

Is there any way to solve this problem?  Perhaps I shouldn't use float?
Also: I'm making a general css.  I have no idea how big the image will be or how long the paragraphs will be.
Answer: here is the update -
css
.imgclass {background-color:336633;width:100px;color:00000;float:left}
p {
    width:100%;
}
.long{
    clear: left;
}

html

Pretend there is an image here. Pretend there is an image
here. Pretend there is an image here. Pretend there is an image here. Pretend
there is an image here.

This is a paragraph.  It looks good next to the pretend image.

This is a paragraph.  It hangs off the pretend image and looks bad.  I wish that
if the paragraph was too long it would appear under the image.

Comment: This doesn't answer my question.  I want to know how to make the blocks of text appear under the image if they will overflow.  Changing the width makes the particular example not overflow, but that's not what I'm asking.


Split document into two documents based on two fields (with aggregation)

Question: I have a document like this one:
{
  'name': 'douglas'
  'datetime_created': '2019-10-24',
  'datetime_expiration': '2019-01-12'
}

I want to split this document into two documents, by the fields datetime_created and datetime_expiration.
Expected output:
{
  'name': 'douglas'
  'datetime_created': '2019-10-24'
},
{
  'name': 'douglas'
  'datetime_expiration': '2019-01-12'
}

How can I do this with aggregation?
Comment: A bit interesting questions :-) :-) !! this as well : https://stackoverflow.com/questions/59906392/apply-uppercase-in-all-the-fields-of-all-documents-aggregate/59906528#59906528 :)
Comment: Yeah thanks! This was cool
Answer: In 3 steps:
Create array with 2 items + $unwind + $replaceRoot or $replaceWith
db.collection.aggregate([
  {
    $project: {
      data: [
        {
          name: "$name",
          datetime_created: "$datetime_created"
        },
        {
          name: "$name",
          datetime_expiration: "$datetime_expiration"
        },

      ]
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      newRoot: "$data"
    }
  }
])

MongoPlayground
Comment: Nice solution. Thanks!


Unable to call objects methods in django ''function' object has no attribute 'objects'"

Question: Im trying to display some objects from django. When I use the administrator my objects are created but when I try to display it is impossible.
I tryed to make a render but when I initialize the screen never is called, then i tryed to make it with a GET button, now the function is called but when arrives to alumnos = Alumno.objects.all() throws
'function' object has no attribute 'objects'.
models.py
class Alumno(models.Model):
    dni = models.CharField(max_length=9,primary_key=True)
    nombre = models.CharField(max_length=100)
    apellido1 = models.CharField('Primer apellido',max_length=50)
    apellido2 = models.CharField('Segundo apellido',max_length=50)
    email = models.EmailField("Correo electronico",null=True)
    repetidor = models.BooleanField()
    curs = models.ManyToManyField(Curso, blank=True, related_name="Historico_de_cursos")
    Nivel = models.ManyToManyField('Nivel', through = 'Completado',through_fields=('Alumno','Nivel'))
    Practica = models.ManyToManyField('Practica', through = 'Nota',through_fields=('Alumno','Practica'))
    Curso = models.ManyToManyField('Curso',through = 'Curso_alumno',through_fields=('Alumno','Curso'))

objects = models.Manager()

def __str__(self):
    return self.dni

class Meta:
    db_table = "Alumno"
    verbose_name = 'Alumno'
    verbose_name_plural = 'Alumnos'
    unique_together = ("nombre", "apellido1", "apellido2")

view.py
def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'alumnos': alumnos}

mostrar_alumnos.html
{% if alumnos %}

    {% for alumno in alumnos %}
    {{ alumno.dni }}
    {{ alumno.nombre }}
    {{ alumno.apellido1 }}

      Editar
     Esborrar
{% endfor %}

{% else %}

No hay alumnos disponibles.

{% endif %}

url.py
url(r'^mostrar_alumnos/$', TemplateView.as_view(template_name='mostrar_alumnos.html'),name='mostrar_alumnos'),
url(r'^mostrar_alumnos/$', views.mostrar_alumnos,name='mostrar_alumnos'),
url(r'^mostrar_alumnos2/$', views.mostrar_alumnos2,name='mostrar_alumnos2')

Comment: Did you by any change defined a function `Alumno` in your `views.py`? It looks llike you have "overwritten" the reference to that model. You need to check to what `Alumno` is refering, it is likely that there is a view in your `views.py` with the same name, or that you imported something else with that name.
Comment: yes I did that, I will check it
Comment: please do not give functions a name that starts with an uppercase, it is against PEP-8: https://www.python.org/dev/peps/pep-0008/.
Answer: Based on the error message, and your comment, you have constructed a view function with the name Alumno, as in:
# app/views.py

from app.models import Alumno

def Alumno(request):
    # ...
    pass

def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'Alumno': alumnos})
This means that if you write Alumno.objects, you are referring to the Alumno function, even if you imported the model, since you simply have set the Alumno identifier to that function when you defined it.
The simplest way to solve this is to rename your Alumno view to alumno, which is, according to PEP-8 the recommended way to name your function. In that case Alumno will thus refer to your imported model.
# app/views.py

from app.models import Alumno

def alumno(request):
    # ...
    pass

def mostrar_alumnos(request):
    alumnos = Alumno.objects.all()
    return render(request, 'mostrar_alumnos.html', {'alumnos': alumnos})
The name of the template variable probably should be 'alumnos' instead of Alumno, in your template you can then render this with:
{% if alumnos %}

    {% for alumno in alumnos %}
        {{ Alumno.dni }}
        {{ Alumno.nombre }}
        {{ Alumno.apellido1 }}

          Editar
         Esborrar
    {% endfor %}

{% endif %}
Note that you do not have to define an objects = models.Manager() in your models. If you do not specify another manager, Django will automatically add a manager named objects to it.
Comment: thank you, this was one of my problems but still not displaying the list, I'm printing the list and is full but the html seems not affected.

Really sorry for disturbing
Comment: Your `for` loop in the template should be `{% for alumno in Alumnos %}`, although again here naming might be improved.
Comment: seems not working don't know why, I tryed with a button with GET method and withouth, the html is entering in the function but is not displaying anything
Comment: @Victor: did you change the context to `{'alumnos': alumnos}`, so renamed it to `'alumnos'` like the edit said?
Comment: @Victor: of course you should also rename it in `{% if alumnos %}`.
Comment: i updated with the code in the OP views and html but as I see is the same
Comment: @Victor: are there any `Alumo` objects in your database?
Comment: yes I have a script to populate and i have like 100, the html get stuck in the first if
Comment: @Victor: I've tested this locally, and it seems to work, so perhaps something else in the template is blocking that part from rendering.
Comment: Yes, in the main post you can see the code and I changed everything with your names
Comment: Now it works, sorry for the disturb, the mistake was I got tons of error codes for try to solve this problem, thank you for your time, I was like 6 hours looking for the error.


Django haystack indexing after new entity added

Question: I'm wondering what operation should invoke after adding new entity to database to make this entity searchable with haystack:

should I only update the index?
should I rebuild the whole index?

What's problematic is that new entities will be added frequently and there might be potentially large amount of entities in db.
Comment: To be honest I'm not sure why somebody voted to close this question.
Answer: If you're adding new rows to your database then update_index should be enough.
From the haystack docs:

The conventional method is to use SearchIndex in combination with cron
  jobs. Running a ./manage.py update_index every couple hours will keep
  your data in sync within that timeframe and will handle the updates in
  a very efficient batch.

If you added a new field to your search index, then you would need to run rebuild_index:

If you have an existing SearchIndex and you add a new field to it,
  Haystack will add this new data on any updates it sees after that
  point. However, this will not populate the existing data you already
  have.
In order for the data to be picked up, you will need to run
  ./manage.py rebuild_index. This will cause all backends to rebuild the
  existing data already present in the quickest and most efficient way.


how to remove nginx modules?Using 32768KiB of shared memory for nchan

Question: Hi I have something problem with nginx. When I get restarted nginx I take this error in log and nginx does not start. Only recently i have encountered an error something below.
ON log file /var/log/nginx/error.log
[info]: Using 32768KiB of shared memory for nchan in /etc/nginx/nginx.conf:71
I don't think i would need nchan module for a simple wordpress site. I'm using ubuntu OS. My question is how do i remove nchan module?
Answer: On Debian derivatives the directory /etc/nginx/modules-enabled contains the configuration files used to load modules (or better symbolic links to the configuration files). You just need to delete the appropriate file and reload nginx:
systemctl reload nginx


Verify A Partition is Aligned in Linux With RAID and LVM

Question: Does anyone know the steps to verify that a XFS filesystem on top of LVM and md RAID is properly aligned on an array of 4096 Byte aka "Advanced Format" sectored disks?
Some references are:
http://www.ibm.com/developerworks/linux/library/l-4kb-sector-disks/index.html
http://thunk.org/tytso/blog/2009/02/20/aligning-filesystems-to-an-ssds-erase-block-size/
Also the context of this question is regarding Stack Overflow's new NAS: http://blog.serverfault.com/post/798854017/the-theoretical-and-real-performance-of-raid-10
Answer: Verification is a tricky one. My first thought was to do a series of direct-IO 4KB reads from the media and watch the blinkin-lights. If every xth read causes two drives to flash, it's a sign of misalignment (4kb read just spanned a RAID stripe boundary). However, you're 3000 odd miles away from the hardware so that won't work for you.
I'm assuming your RAID stripe width is larger than the 4KB sector size. The test I thought of a bit ago is to do a stride read/write test. This is where you read/write every x 4KB sectors. Vary the offset and you can change where in the RAID stripe you're testing. If certain offsets show different performance, I'd consider that a sign that the specific offset is spanning a RAID stripe for a 4KB operation. That would verify that XFS is aligning properly in the RAID config.
Verifying the RAID stripes are aligned correctly could be done with the same kind of stride test and keep an eye on the 'iostat' values for the individual drives. If you get the stride size right, you should only see activity on two drives at any given time. If the same test shows activity on all four drives, then you've got proof that something is misaligned.
I know for sure the storage benchmark IOZONE has the ability to do a stride test, and I'd be very surprised if the more common IOMETER couldn't do that. The ability to use direct-IO and bypass caching and write-combining is critical to these kinds of tests, though.
Answer: It's a personal thing but I think this alignment business is overplayed - I dare say there are low-single digit performance benefits to be had if you sweat the last details but given the size of modern day caches plus the complexity of disk to memory chains I wouldn't sweat it to much.
But that's me ;)
Comment: Mis-aligned sectors give sequential reads and writes, an operation that's actually very efficient on rotational media. The reason alignment is a big deal on SSDs is that writes are much more expensive than reads, so write-magnification needs to be kept to a minimum.


How to differentiate between Plagal and Perfect, and Imperfect and Interrupt cadences

Question: I'm trying to practise my aural skills except I really need some tips on how to properly differentiate and tell cadences. I know the basic characteristics of each cadence, perfect sounds complete, plagal the "Amen" one, interrupt a question mark sounding finish and imperfect the one that takes twist at the end. However, especially between the 2 pairs, plagal and perfect, imperfect and interrupt I'm still having trouble identifying them as often I get muddled with what counts as a "weaker" finish, an "Amen" etc. Is there any trick or tips to help identify these cadences apart? Thanks all
Comment: @piiperi - questions on cadences feature in many theory exams, and it's usefu on occasions to be able to communicate with other musos using proper terms. 'Let's try ending this number on an interrupted cadence'.
Comment: What do you do with this information? I mean, in what kind of situation is such classification useful for something.
Comment: Your "interrupt a question mark sounding finish and plagal the one that takes twist at the end" statement doesn't seem quite correct. Also, are you trying to identify these cadences by ear or in sheet music?
Comment: I can't imagine a situation where any actual musician I know would use the term "plagal cadence" except as a joke. But then again, I just play pop music.
Comment: @piiperi anyone who plays from a hymnal will play a 'plagal' cadence at the end of just about every hymn, not as a joke, but because it's written on the pages.
Comment: @MichaelCurtis Using such a fancy name for a trivial thing, that's the joke. :)
Comment: Ah, yes. I don't like the name either. It isn't really a cadence type. But that is a whole other can of worms.
Comment: @MichaelCurtis - just dug out my 'Hymns Ancient and Modern'. Not a sign of a written out Amen anywhere! Of course any organist/pianist will play that at the end of just about every hymn, but not because it's written on the pages. That would be superfluous. Seems the word originates from ancient Greek - *oblique* - don't see any relevance there!
Comment: @piiperi - why fanciful, and why trivial?
Comment: @Tim, not a sign of a plagal cadence anywhere?!? Look at the edit in my answer.
Comment: @Tim well, actually I meant, cadences are composite things - they are basically chord sequences, and I would think that identifying the chords is all that's needed. Whatever a particular combination might be called... could someone identify an entire sequence as a single entity, but not its individual components? On the other hand, identifying steps and changes in relation to a known reference point is important for listening, so maybe studying different types of cadences makes sense for developing more general hearing skills.
Comment: That's good evidence! Mine is Hymns Ancient and Modern (Revised) - can't find any date, but I had it in 1962 - the original H, A&M would have been round for 101 yrs at the time, and probably the publishers thought that players could manage amen without it being written down after that sort of time doing it. And that particular 'Morning' isn't included !
Answer: Cadences
Often confusion between them - especially with respect to perfect / imperfect.
Perfect Authentic Cadence goes V-I with both chords in root position and top voice resolving to tonic
Imperfect Authentic Cadence goes V-I but is not in root position; top voice does not resolve to tonic
Plagal Cadence goes IV-I; chord voicing does not matter
Deceptive Cadence most commonly goes V-vi, but really may go to any other chord besides I
Half / Interrupted Cadence stops on V.
All cadences may have any predominant chords precede the actual cadence itself. The last thing to remember is that cadences only happen at the ends of phrases. Simply going V-I within a progression is not in of itself a cadence, but rather, if the progression from penultimate chord to final chord for a given phrase is V-I, then it becomes a cadence.
Answer: Might be different than your terminology, but here's a tip on how I categorize things:

Authentic - V-I
Deceptive - V-VI
Plagal    - IV-I
Half      - ?-V

Those 4 are main categories.
What sounds weaker depends largely on the context, more specifically, whether the tonality has already been "confirmed" and to what degree...
I myself take imperfect/perfect to be related to chord inversion and voice movement - more melodic jumps combined with more interpolated harmonic movement will mostly yield a "stronger" cadence.
Comment: Yes, my fault, I was standing on the wrong part of the Moon... It's still woth mentioning that Authentic=Perfect, Deceptive=interrupted, Half=Imperfect, and Plagal, oh! authentic and Perfect seem to have differing voicings depending where in the world one plays..! And - there are quite a few different names for each - it's interesting just reading ome. Abrupt, Broken, Avoided anyone?
Comment: I guess you're to the left of the Atlantic Ocean. On the right, the OP's terms work well. Just looked - you're even further left !!
Comment: Suggestion of terminology is there to help clarify the simplification of categorization. I am not suggesting one is more accepted than the other, and I am fully aware of differences.

To tell you the truth, I have no idea which side of the Atlantic ocean I am.

You got a point though, I am rephrasing the top part of the answer
Comment: @Tim, I guess I am so left that I am actually right, but thankfully, I don't have a driving license :) On the serious side, I am in eastern Europe, and in my country we do by the German system.
Comment: Yes, synonyms are used on both sides. As you might figure, eastern Europe is stretched between western (German) and eastern (Russian) terminology, or "way of thinking". Abrupt - sure, Broken - idk, Avoided - definitely.
Answer: Using the OP's terms, which are prevalent in UK at least, they fall into two categories, looking at it one way.
Perfect and Plagal (both P...) finish on root chord. Imperfect and Interrupted (both I...) do not.
Looking at it another way, Perfect is exactly opposite to imperfect - as the very words suggest. and listening to each, the terms seem apposite.
Plagal (amen) pretty well speaks for itself, as does interrupted, which sounds like it's not actually reached a destination, but stopped for a rest. Imperfect can also sound thus, but the penultimate chord in each is different. With interrupted, it's often V>vi, whereas imperfect could be just about anything before V.
Bearing in mind there are only the four (which do also get sub-categorised) it's worth just playing them all, in different keys. By the time you've got through, they're probably all stuck in your brain!
Comment: I think your final paragraph is The Answer. Playing cadences is the best way to internalise them.
Answer: An exercise I have used is to play cadences in sequence to highlight their 'structural' use.
What I mean by structural is use ending cadences at the end, use continuation cadences in the middle, etc. Think of a musical period, perhaps a simple 16 bar piece like a minuet. the first 8 bars end with a half cadence, the second 8 end with the concluding perfect cadence. Playing a half cadence followed by a perfect cadence puts thinks in a sequence that reflects both common forms and highlights the difference in feeling.
From that structural perspective a deceptive cadence should precede a perfect cadence. Typical use of a plagal cadence is after a perfect cadence.
An example sequence might be: half cadence, deceptive cadence, perfect cadence, plagal cadence. All played in one key.
You have to decide what to play leading up to the various cadences, but a few beats of the tonic chord should be enough to set the tonal backdrop.
Pay attention to the barline! Placing the defining chord after the barline on beat one will make clear the cadence type. So, the V of a half cadence should be on beat one after the barline, the vi of a deceptive cadence should be after the barline, etc. That isn't a rule, but it should help contrast each cadence type. Plagal cadences are different in this regard. The IV usually comes on beat one.
Using typical chord leading to the cadence will help too. Use a subdominant before the dominant of a half cadence, like ii6 | V. Use a cadential 6/4 in a perfect cadence, like i6/4 V7 | i.
The use (or omission) of the seventh on the dominant can help highlight the difference in half and perfect cadences: don't use the seventh in half cadences, be sure to include the seventh in perfect cadences. This isn't a rule, but it reflects common treatment of the dominant chord in a lot of classical music.
Play in major and minor. Play on all twelve tonics.
If things become too rote, try some figuration (arpeggiation) of the chords, and change meters: duple, triple, and compound.
Sing out loud different parts: the bass, or the upper voices paying attention to the movements between TI and DO, and FA and MI.
Do this for a few months and you should end up really hearing and feeling the different cadences.

EDIT
Apparently there is some question about whether plagal cadences are written at the end of hymns. Example from Hymns Ancient and Modern, 1861:

...the so-called plagal cadence is written out like this for hymns through out the book. This is common in many other hymnals.
Comment: agreeing with @jjmusicnotes and others, cadences come at the end of phrases.

the A-men comes after the double bar, justifiably at that, i.e. it follows usually an authentic cadence, so one shouldn't confuse A-men with plagal cadence, except as a way to remember what it sounds like. Interesting to note here, the bar before A-men is missing a beat (BTW, why are those alto and bass half notes written mirrored and quarter notes the other way? I guess to line up vertically, but then *we* are doing it wrong...)


Let $\vert G \vert = p^n m$ where $m < 2p$. Show that $G$ has a normal subgroup of order $p^{n-1}$ or $p^n$

Question:
Let $G$ have order $p^n m$ where p is a prime and $p \nmid m$. Suppose $m < 2p$. Show that $G$ has a normal subgroup of order $p^{n-1}$ or $p^n$.

I have tried to apply the Sylow Theorems but I can't see how to continue in the case when the Sylow $p$-subgroup is not normal. Let $P$ be a Sylow $p$-group. Then $\vert P \vert = p^n$. If $P$ is normal in $G$ we are done, otherwise $k := \vert \operatorname{Syl}_G(p) \vert \ge 2$. By Sylow's Theorem $k \mid m$. Using our assumption that $m < 2p$ we get that $m/k < p$.
Am I on the right track? Since $m=[G:P]$, $k=[G:N_G(P)]$ and $[G:P]=[G:N_G(P)][N_G(P):P]$ we get that $m/k = [N_G(P):P] < p$. Not sure if this is useful.
I know that $P$, being a $p$-group, has a normal subgroup of order $p^{n-1}$. I don't see why it would be normal in $G$ though.
I prefer hints to full answers.
Comment: Assume that no Sylow subgroup is normal. Consider $O_p(G)$, intersection of all Sylow $p$-subgroups. $O_p(G)$ is the kernel of the action of $G$ on the cosets of a Sylow $p$-subgroup which has $p+1$ elements by the hint above by @MattSamuel . Then $[G:O_p(G)]$ divides $|S_{p+1}| = (p+1)!$. Say $O_p(G) = p^a$ and using number theoretic arguments to get $a = n-1$.
Comment: If the Sylow subgroup is normal then we're done. Otherwise the number of Sylow subgroups divides $m<2p$ and is congruent to $1$ mod $p$. It follows that $m=p+1$. That's seems like it'll be useful, so I guess you could call it a hint, but I don't have time to finish to find out how useful it is!
Comment: Can I ask where did you get this problem?
Answer: If $P$ is not normal and there are $p+1$ Sylow $p$ subgroups. Suppose there is a normal subgroup $Q$ of order $p^{n-1}$, then
$$Q=\bigcap_{P\in\operatorname{Syl}_p(G)}P.$$
Hence
$$\left|\bigcup_{P\in\operatorname{Syl}_p(G)}P\right|=p^{n+1}.$$
You should be able to show that if there is no such $Q$, then the union of the Sylow $p$ subgroups is too big and that the same is true if $G$ has more than $p+1$ Sylow $p$ subgroups.


The panel is not showing up

Question: I'm making my own custom panels layout using the Panels module for the front page of my site. This is how I have my page set up.
Two blocks will be displayed on all pages: a header, and a footer (each have their own navigation bar).  The header contains a few images (logo and two more) plus a customized login block (using the hook).  Now, I've decided to create my home page, which uses the clean URL /home. I've copied the files from the twocol folder in the modules/panels/plugins/layouts folder to a twocol-bottom folder in my layouts folder of my theme's root (I hope you guys can understand what that means: basically /sites/all/themes/my_theme/layouts/twocol-bottom).
I've renamed the twocol folder to twocol-bottom (because, I just want to add a bottom panel that extends the full length of the #main area (inside the #main-wrapper).  I've renamed all the files to twocol-bottom.css, twocol-bottom.inc, twocol-bottom.png, twocol-bottom.tpl.php. I've added the following line to my theme's info file:
plugins[panels][layouts] = layouts

twocol-bottom.inc
<?php

// Plugin definition
$plugin = array(
  'title' => t('twocol-bottom'),
  'category' => t('Columns: 2'),
  'icon' => 'twocol-bottom.png',
  'theme' => 'twocol-bottom',
  'css' => 'twocol-bottom.css',
  'panels' => array(
    'left' => t('Left side'),
    'right' => t('Right side'),
    'bottom' => t('Bottom pane')
  ),
);

?>

twocol-bottom.tpl.php
<div class="twocol-bottom-display panel-2col clear-block"
<?php if (!empty($css_id)) {  print "id=\"$css_id\""; } ?>>

<?php print $content['left']; ?>

<?php print $content['right']; ?>

<?php print $content['bottom']; ?>

I changed all the CSS classes to match the classes in the .tpl.php file.
When I flush my cache in Drupal and choose to change the layout of my first panel, the newly added panel isn't showing up. I'm not sure how to make the panel show up.
Comment: You've made the question complected.
Comment: What Nikhil said. All I see is a wall of text and not a clear question.
Answer: I think you're taking the wrong approach.  One of the main reasons for using the Panels module is to avoid writing custom code like this.
Instead of making your own custom panels layout in code for just your front page, use the "Flexible" layout builder provided by Panels.  You can then use the layout designer to add rows, regions, and columns however you want.  You can even add CSS classes and choose between fluid and fixed widths, setting the percentages as you like.
Given that you can do all of that within the Panels module itself, I would think twice before you try to code a layout just for one page.

The panel is not showing up


Swift and Xcode 6.0 Sizing Not Displaying Correcty

Question: My problem is that when I add constraints to images, they do not size correctly. So it looks really different when you try it on different devices.
Iphone 6 Image: http://sta.sh/027d5awmyin3
Iphone 4s Image: http://sta.sh/0245jhtb5hls
Has anyone else experienced this problem? This is really bugging me and I would really appreciate a thorough answer to this. I am a little new to Swift and Xcode so dumb it up for me :)
Comment: Your debugger console throws out constraint errors. Take a deep look at them to figure out where the problem is.
Comment: It says "2014-10-07 07:04:47.097 Lagniappe[16395:460225] Unable to simultaneously satisfy constraints.
 Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property"
Comment: Read further - the interesting part comes right after this text. Each constraint conflict is listed there to give you hints what's going wrong.
Comment: Check here lol: http://sta.sh/065uqolvmy5
Comment: The width contstraint (234) for a UIButton cannot be satisfied at runtime.
Comment: Why can't it be satisfied?
Answer: That means that you have multiple constraints set on the button and at least on of these constraints cannot be satisfied at runtime.
Example: When you set constraints for the left distance, right distance AND the width of the button. In that case, remove the width constraint because the width of the button is automatically determined be the left and right distances.
Comment: The pictures are waaaaay smaller on the iPhone 4s than on the iPhone 6. It's just a little frustrating .
Comment: Ok. So only use one type of constraint. Which one do you think will provide the best look on each build of the iPhone?
Comment: This is my problem: My images shrink but the buttons don't shrink, so I get a weird size on different builds of the iPhone. Images: http://sta.sh/020j4z6b8k4a | http://sta.sh/0nihmrwkmh0
Comment: For me it looks perfect! So what's the problem?


Mid Range Server Motherboard Recommendation (linux)

Question: I am looking for a mid price range motherboard for a Linux Server.
It should have support for ECC memory.
On all other aspects I am pretty open minded!
Any suggestions or recommendations?
Answer: People don't really build server-class systems from individual components these days. If this is something for production use, definitely try to go with a pre-built vendor-supported solution like Dell or HP.
If you need more customizability, you can look into Supermicro's offerings as well.


How to skip version in jar generated by maven-jar-plugin and clasifier

Question: <code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
                <execution>
                    <id>client</id>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                    <configuration>
                        <classifier>client</classifier>
                        <includes>
                            <include>**/com.service/**</include>
                        </includes>
                    </configuration>

                </execution>
            </executions>
        </plugin>
</code>
I want the version to be appended to end of the jar.Right now it is building jar like ship-service-0.1-client.jar,I want it like ship-service-client-0.1.jar and i need to add it as dependency in another project.
Comment: Possible duplicate of [Controlling maven final name of jar artifact](https://stackoverflow.com/questions/4238944/controlling-maven-final-name-of-jar-artifact)
Comment: A classifiier sounds like a design flaw. You should make a separate maven module of the classifier part...The naming is `ship-service-0.1-client.jar` which you can't change if this is a classifer artifact.
Answer: You can use
<code><build>
    <finalName>FinalNameOfYourProyect</finalName>
</build>
</code>
check this related question
Comment: If there is already an answered question in SO, don't give another one. Flag the question as a duplicate.
Comment: This will only change the name in `target` folder but will not change the name which is deployed. Simply cause it can't be renamed.


Does this chord fit D minor?

Question: Is it ok to play a g flat chord in a D minor scale?  Basically I wrote a song where one riff plays a G flat at the end of it then goes right back to a D minor chord.  It's a rock song.  It sounds cool and doesn't sound super dissonant but has a cool and different tone to it where it's placed briefly.  Just not sure if it's a G flat or an F# minor chord I'm playing considering that I'm playing it in a D minor scale?  Or is it some mode?
Appreciate any insight of what scale or mode I'm actually playing here.
Comment: Are you trying to play a major chord, a minor chord, or a power chord? With no other qualifiers, if I found a Gb chord on a lead sheet, I'd assume a major chord.
Comment: It's a power chord when played in drop D on my electric guitar.  Thanks!
Comment: I think you need to explain more what you're playing. Just tab it out. "One riff plays [an F#] at the end then goes right back to a D minor chord." How does that necessarily bring a full F# minor chord into the picture? A riff that plays back and forth with the scale third as minor and major is sort of bluesy/rock thing. Then again with chords of D minor and F# minor and a D minor scale, you could get some exotic sounding things. You wrote "one riff..." Are you hinting there are two parts playing together? The devil's in the details.
Answer: Consider that a lot of pieces modulate between parallel keys. So being in D minor at one point becomes being in D major at another.
Your G♭m (probably better called F♯m) is from key D major, rather than D minor. So it's not surprising that it sort of fits in your song.
It's a useful bit of theory to keep handy - because as well as the usual 3 majors and 3 minors usually found in the piece's key, that number can be doubled, giving a lot more freedom to experiment with those other chords - found in its parallel key.
And - by the way - we don't ever play in a scale - we play in a key or a mode of a key!
Comment: Hi Tim! Thanks so much for your reply and detailed explanation.  I am very rusty on my theory.  I've taken some theory classes but have forgotten the harder stuff.  That is starting to make sense but not fully.   So when you're saying parallel keys (my bad for calling them scales that's how rusty I am lol) are you referring  to relative keys? That's what I thought of first but the Gbm wasn't linking up in F Major.  I'm glad theory wise it makes sense b/c it's a song I'm gonna release sometime this year.  Thanks! Chris
Comment: @Songwriter - relative and parallel are not the same. Relative is C and Am (same key sig.), and parallel is same root note (A maj and Am).
Comment: @Songwriter - no song has to obey the 'rules'. Chances are that 'rules' can often be found that 'justify' what's been written. The old adage - *if it sounds good, it probably is...*.
Answer: Tim's answer above reinforces the fallacy that every chord must fit the scale of the key, so if it doesn't the music must have modulated to another key.
Not so.  There is a thing called Chromatic Notes/Chords.   This allows a progression like C - C♯dim7 - Dm7 - G7 - C  to exist completely within the key of C major.  It is not useful to consider the Dm as a 'temporary tonic' when it is so demonstrably ii7 in C major!  C♯ is just the note in-between C and D.  It smooths out the movement from I to ii7.  In no way does it challenge the characters of those chords within a C major tonality.
And there's another way to use chromaticism. Consider C - F♯ - C  (let's go the whole hog and have THREE 'outside' notes).  It's not a momentary modulation.  It's a violently contrasting chord to C major - possibly the MOST violently contrasting one possible!   And that's enough justification.  It doesn't become a new 'home' chord, it doesn't require any functional relationship to the home key, or to one of its related keys, its purpose is simply to clash with the existing home chord!  And that's OK. Don't try to make everything fit into that 'circle of 5ths' diagram.
Back to the actual question:  F♯m has one note (A) in common with all the common versions of the D minor scale (natural, harmonic and melodic) and another one (C♯) in common with two out of the three.  That's enough to make it sound not COMPLETELY 'outside'.  Though its F♯ challenges the F♮ which is what MAKES Dm minor rather than major, so it's still going to be quite an interesting jolt.
Comment: Tim did use the word "modulate" and yeah that over states it. But what is wrong the with terminology of secondary dominant, borrowed chord, tonicization to explain dressing up diatonic harmony with chromaticism, while not actually changing key? If `C#` in `C - C♯dim7 - Dm7` were merely an chromatic in-between note, then `Dm7 C#dim7 C` should work just as well. But in the reverse direction isn't `Dm7 Db7b5 C` more typical? My point is the `C#` ascending _does_ act and sound like a leading tone, and the descending `Db` does act and sound like a tritone-sub/augmented sixth resolution.
Comment: I'm sorry, I still have to agree with Tim there. The C#°7 *does* tonicize D minor - or the ii7 chord of C major - for a little bit. The more of these tonicizations, the shakier my label for what key the overall piece is gets (even if it actually never budges from C major). So, the C# *does* challenge the characters of those chords within a C major tonality.
Comment: In addition, your C-F#-C example reminds me of the roughly Cm-F#-Cm-F#(-etc.) chord progression of the Toad's Factory theme from *Mario Kart Wii* (which is jazz). The F# chords don't actually shift this theme from being in C minor (especially since F naturals show up in the melody), but they do increase the chromaticism of the piece markedly, which already makes my C minor label shakier (this theme is a *lot* less conservative than style galant and is an example of a C minor piece I would not have wanted to use when initially training my ability to find keys of music by ear).
Comment: @Dekkadeci  So, in your thinking, EVERY time a progression  passes through a tension - resolution moment a new tonality is established.    Every tension is a dominant, every resolution a tonic.  There's a certain logic to this, but it's not a very useful way to look at a passage of music.
Comment: Not quite. A lot of the time, a lot of the dominants (not all tensions are dominants - in the Toad's Factory example, the F# chords are non-dominant tensions) are for the exact same tonic/resolution chord. Therefore, the same tonality is used as last time and no new tonality is established. I guess it's a safe bet for me to say that, at least for me, the tonality does (however temporarily) shift with each dominant-tonic resolution where the dominant chord cannot be found in the previously established key (assuming common practice period harmony).
Comment: As for tonality changes that do not involve dominant chords (but inevitably *must* involve tonic chords), it's never felt like an exact science to me, but two examples I can think of off the top of my head are exact transpositions of previous passages and blatantly changing the most commonly played chord (e.g. the part of the final boss theme of *Banjo-Kazooie* where the chord progression changes from A-F-A-F-B-G-B-G to Em-Em-Em-Bb-Em-Em-Em-Bb involves a switch from an unknown, sharp-leaning tonality to E minor).

Does this chord fit D minor?


Converter código MySQL para MySQLi

Question: 3 Erros são apresentados:

Notice: Undefined variable: save in C:\xampp\htdocs\index.php on line 6
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\index.php on line 133
Notice: Undefined index: page in C:\xampp\htdocs\index.php on line 153

Segue-se o meu código abaixo:
index.php
1  <?php
2  include('connection.php');
3  include ('paginate.php');
4  extract($_POST);
5  if($save)
6  {
7  $q=mysql_query("select email from users where email='$e'");
8  $r=mysql_num_rows($q);
9  if($r)
10 {
11 echo "O email ' $e ' j&aacute existe!";
12 }
13 else
14 {
15
16 $img=$_FILES['img']['name'];
17
18 $dob=$yy."-".$mm."-".$dd;
19
20 $query="insert into users values('','$n','$e','$p','$add','$mob','$gen','$img','$hobbies','$c','$dob',now())";
21 mysql_query($query);
22
23 mkdir("image/$e");
24 move_uploaded_file($_FILES['img']['tmp_name'],"image/$e/".$_FILES['img']['name']);
25
26 echo "Atualizado com sucesso!";
27 }
28 }
29 ?>
130 <?php
131 $per_page = 5;
132 $result = mysql_query("SELECT * FROM users");
133 $total_results = mysql_num_rows($result);
134 $total_pages = ceil($total_results / $per_page);
135
136 if (isset($_GET['page']))
137 {
138    $show_page = $_GET['page'];
139    if ($show_page > 0 && $show_page <= $total_pages) {
140        $start = ($show_page - 1) * $per_page;
141        $end = $start + $per_page;
142    } else {
143
144        $start = 0;
145        $end = $per_page;
146    }
147 } else {
148
149    $start = 0;
150    $end = $per_page;
151 }
152
153 $page = intval($_GET['page']);
154
155 $tpages=$total_pages;
156 if ($page <= 0)
157    $page = 1;
158
159 //$query=mysql_query("select * from users");
160 for ($i = $start; $i < $end; $i++)
161 {
162     if ($i == $total_results)
163      {
164         break;
165      }
166 ?>
167

168     <?php echo mysql_result($result, $i, 'name');?>
169     <?php echo mysql_result($result, $i, 'email');?>
170     <?php echo mysql_result($result, $i, 'address');?>
171     <?php echo mysql_result($result, $i, 'mobile');?>
172     <img src="image/<?php echo mysql_result($result, $i, 'email')."/".mysql_result($result, $i, 'image');?>" width="40px" />
173     <?php echo mysql_result($result, $i, 'country');?>
174     <?php echo mysql_result($result, $i, 'dob');?>
175     <a href="edit.php?email=<?php echo mysql_result($result, $i, 'email');?>">Edit
176     <a href="delete.php?email=<?php echo mysql_result($result, $i, 'email');?>&image=<?php echo mysql_result($result, $i, 'image');?>">Delete
177

178
179 <?php }  ?>
180

181 <?php
182  $reload = "index.php" . "?tpages=" . $tpages;
183  if ($total_pages > 1) {
184      echo paginate($reload, $show_page, $total_pages);
185      }
186 ?>
187

188

connection.php
<?php
$mysqli = new mysqli('localhost','root','','bd') or die("ERROR CONECTION!");
?>

Comment: +1 @Chun com certeza!
Comment: Neste caso veio mesmo a calhar estes números de linhas, para ajudar a apontar o que está errado ou o que se deve modificar mencionando o número da linha para modificação, facilitando bastante o trabalho para os respondedores. Acho que uma característica assim deste género dava imenso jeito na revisão de código. +1!
Answer: Prefiro o uso de
$conn = mysqli_connect('localhost','root','','bd');

mysqli_connect é um alias para o construtor da classe, você pode testar a conexão, verificando $conn
if(!$conn){
 echo mysqli_connect_error();
}

agora você pode consultar e manipular o banco, mas é necessário o uso da variável $conn
$result = mysqli_query($conn, "SELECT * FROM users");

while($user = mysqli_fetch_assoc($result)) {
 echo $user['nome'];
}

Sobre os erros:
1 O erro diz que na linha 6 você está fazendo if em uma variável que não foi definida anteriormente;
2 Consequência de não haver uma conexão a função mysql_query() não retorna o valor que mysql_num_rows() precisa;
3 Diz que o index page em $_GET['page'] não existe, valores em $_GET são passados via URL (http://localhost?page=1) ou input form com o atributo method='get';

Sempre que for iniciar uma tecnologia comece por RTFM :D http://php.net/manual/en/book.mysqli.php

Converter código MySQL para MySQLi


How to save python list structure when importing from excel?

Question: I have excel file with a column like this
 [{'accident_number': '330002530', 'accident_date_time': '07.02.2017 11:06', 'accident_type': 'Столкновение', 'accident_place': 'Кировская область, Слободской район, Слободской', 'damage_points': ['01', '08'], 'vehicle_damage_state': 'Повреждено'}, {'accident_number': '330008496', 'accident_date_time': '23.08.2021 12:19', 'accident_type': 'Наезд на стоящее ТС', 'accident_place': 'Кировская область, Слободской район, Слободской', 'damage_points': ['117', '118'], 'vehicle_damage_state': 'Повреждено'}]

It's a list of dicts. When i'm importing this to pandas dataframe with pd.read_excel, i see it has type string. The question is how can i make python understand it's a list of dicts?
I thought maybe there's a way to create a new list variable and assign it to the contents of my excel column but cant find a way to do it. I'll appreciate any help.
Comment: as it is a string, you would have to use `split()` and work on each component to recreate the list of dicts.  The alternative would be to format the excel sheet appropriately...
Answer: You can try:
[{"a": 1}, {"b": 2}] # Your string in txt

file = open("dictionary_string.txt", "r")
contents = file.read()
dictionary = ast.literal_eval(contents)
file.close()

print(type(dictionary)) # Output <class 'dict'>
print(dictionary) # Output [{"a": 1}, {"b": 2}]

The other option is save the file as json:
import json

# Opening JSON file
f = open('data.json')

data = json.load(f)

for i in data['some_column']:
    print(i)

# Closing file
f.close()


How to calculate the memory consumed by hash map?

Question: How can i calculate the memory of hash map. The memory of hash map is what i want to get.
The size of hash map i can get through hashmap.size();
But i don't know how to get this.
Comment: https://stackoverflow.com/a/6160485/3615605
Answer: Try something like this, by using a couple of output streams from the java.io library:
import java.util.*;
import java.io.*;

HashMap<String, Integer> hashmap = new HashMap<>();
hashmap.put("vishal", 10);
hashmap.put("sachin", 30);
hashmap.put("vaibhav", 20);

try {
    System.out.println("HashMap Size: " + hashmap.size());
    ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
    ObjectOutputStream stream2 = new ObjectOutputStream(stream1);
    stream2.writeObject(hashmap);
    stream2.close();
    System.out.println("Memory Used: " + stream1.size());
} catch(IOException e) {
    e.printStackTrace();
}

You could also try to use external tools/APIs like ClassMexer or the Instrumentation interface.


How to determine actual size of an amazon snapshot?

Question: Amazon EBS snapshots capture changed blocks from a baseline, so snapshots will often be much smaller than the source volume.  Billing is based on the actual size, which is nice. However, I cannot find a way to determine the snapshot actual size.   ec2-describe-snaphots only provides the size of the volume that was snapshotted.
If for no other reason, I need this information to verify billing.  But I'd also like to have it because I may find that by reconfiguring my volumes, and what I do with them, I can reduce the size of my incremental snapshots.
Answer: Amazon does not currently provide a method to report on the storage used by snapshots other than the total usage and cost numbers for all snapshots in the account.
Snapshots of the same or related volumes can share storage (where blocks have not changed between snapshots) so this makes it difficult to define the size of a single snapshot.
A new snapshot only saves blocks that have been modified since the last snapshot, but it keeps pointers to the previously saved blocks that have not been modified.
If you delete a single snapshot, it would only free up the blocks that are not shared by any other snapshot (whether created before or after the one you're deleting).
Blocks on the EBS volume that have not been written to are not included in the snapshot.
Snapshot blocks are compressed before storage, further saving you in storage costs.
Comment: Thanks for the extensive answer. However, it must not be TOO difficult,  because amazon does it, so that they can bill it. If I thought that only 10% of my data was changing between snaps, but it was actually 90%, I'd like to know that (in a direct fashion.)
Comment: Amazon bills for the total storage used by all snapshots in the aggregate.  The difficulty is in *defining* what you mean by how much storage a single snapshot uses in such a way that it doesn't completely confuse people who don't understand the levels of indirection that are going on behind the scenes to save you money. What you ask for in your comment is actually a count of the blocks that are in one snapshot but not a specific other one.
Comment: Depending on how you define a snapshot size, you end up giving numbers that either don't add up to the total you're actually paying for (confusing) or that don't match how much less you pay when you delete a specific snapshot (also confusing).
Comment: Sad that the situation is the same 7 years later.  @EricHammond you said that it's hard to describe how much storage a snapshot uses in a way that's not confusing.  That's true, but it doesn't preclude from giving, say, per-volume snapshot prices.  I sure wish I knew which of my volumes' snaps are using the space and which aren't.
Comment: Where do I see the "total usage and cost numbers for all snapshots in the account"? I'm trying to determine how encryption affects snapshot size. If I encrypt an EBS volume using dm-crypt, will EC2 still be able to compress it when making a snapshot, and will incremental blocks still help for subsequent snapshots? The answer affects will affect my database backup strategy.
Comment: @markberry Please ask as new questions.
Comment: Done:  http://serverfault.com/q/606912/166311.
Comment: I suspect snapshots from multiple EBS volumes can share storage and cost if one volume was created from a snapshot of another or has a shared ancestry.
Answer: I wrote this small script for determining the snapshot's size. Right now doesn't take any params, it just gets all snapshots.
https://github.com/akirsman/Snapshots/blob/master/snapshotsSize.py
Comment: @mastov This specifically: https://github.com/akirsman/Snapshots/issues/2
Comment: This is great! For others reading, this is using the "EBS Direct APIs", available since Dec 2019, to get the number of changed blocks between each two snapshots. There are some issues with the script, but these APIs should give all the info needed.
Comment: @Ralf Would you mind clarifying the "issues" with the script? I'd like to use this script without reservations.