POST fica vazio dependendo do site que uso

Question: Tenho um projeto em Codeigniter que fica em uma pasta dentro do domínio. A estrutura de pastas está da seguinte forma:

/dominio/Web/projeto/

Chamarei de domínio e projeto devido ao nome do cliente/site
Consigo acessar o site de duas formas: www.meudominio.com.br/projeto ou www.projeto.com.br.
Porém, em todos os forms que faço, a variável $_POST fica vazia quando preencho pelo site www.projeto.com.br (o que deveria ser o correto pois o cliente deseja acessar como um site isolado de sua raiz). Se eu preencher os forms pelo site www.meudominio.com.br/projeto a variável $_POST recebe os dados normalmente e consigo prosseguir com a navegação.
Há alguma forma que eu possa fazer para que as duas URLs recebam o POST normalmente, como se fossem uma só?
Seguem os códigos do form e do controlador, para um form de login:
<form method="POST" action="sac/nova_conversa">
    <input type="hidden" name="lojaID" id="lojaID" value="<?= @$lojaID; ?>" />

            Nome:
            <input type="text" name="nome" id="nome" />

            Telefone:
            <input type="text" name="telefone" id="telefone" />

            E-mail:
            <input type="text" name="email" id="email" />
            <input type="submit" value="Entrar" class="entrar" />

        <?PHP if ($this->session->flashdata('errors')) { ?>

<?= $this->session->flashdata('errors'); ?>

        <?PHP } ?>
    </form>

Controller:
public function nova_conversa() {
    if ($_POST) {
        $data["nome"] = $this->input->post("nome");
        $data["telefone"] = $this->input->post("telefone");
        $data["email"] = $this->input->post("email");

        if (($data["nome"] == "") or ($data["telefone"] == "") or ($data["email"] == "")) {
            $this->session->set_flashdata('errors', 'Digite seus dados');
            redirect("sac");
        } else {
            $usuarioID = $this->sac_model->novo_usuario($data);

            $data["lojaID"] = $this->input->post("lojaID");
            $conversaID = $this->sac_model->nova_conversa($usuarioID, $data["lojaID"]);

            $this->session->set_userdata('chat_usuarioID', $usuarioID);
            $this->session->set_userdata('conversaID', $conversaID);

            redirect("sac/abrir_conversa");
        }
    }
}

Obrigado!
Comment: Para este tipo de situação, onde está ``, você deve utilizar assim ``, aí o elemento será preenchido. Se inspecionar o código através do `F12` do Chrome irá ver que no método utilizado o valor está em branco, mas se utiliza o echo para imprimir o valor ele atribui ao html.
Comment: Assumindo Apache: podes adicionar o conteúdo do teu `.htaccess` que trata do _redirect_? Parece-me que estás a fazer um _redirect_ sem contemplar os valores do `$_POST`, por isso é que o formulário funciona numa localização mas não na outra.
Answer: No arquivo routes.php altere esta linha:
$route['default_controller'] = "projeto";

No seu arquivo config.php coloque o seguinte:
$config['base_url'] = '';
$config['index_page'] = '';

Uso o seguinte .htaccess no diretório que está o meu index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

Meu projeto está dessa maneira descrita acima, acredito que se alterar dessa forma irá funcionar do mesmo jeito que o meu funciona.
Notei que a URL é case sensitive então se o nome da pasta do site estiver maiúsculo, na URL também deverá ser maiúsculo
Se não houver duvida que toda esta configuração está correta então você pode verificar o seguinte, o $route['default_controller'] = "projeto"; é uma configuração que define que ao acessar o seu site o primeiro controller que vai ser carregado é o projeto.php e o método chamado dentro dele será o index, se este estiver redirecionando para outro método então você também deverá repassar seus dados $_POST e $_GET
Resumindo...
www.meudominio.com.br -> default_controller/index -> default_controller/projeto
www.meudominio.com.br/projeto -> default_controller/projeto

Essa provavelmente é a explicação para seu problema!


Adding/generating content automatically in Vim

Question: I have a huge list of numbers and I would like to add content on the end of each line. It's something like this:
Before:
123123
123123
13234
124125
12634
5234

After:
123123, 1
123123, 2
13234, 3
124125, 4
12634, 5
5234, 6

A couple of points:

I know that :range s/oldpattern/newpattern/ will substitute the oldpattern by the new one.
I know that for i in range(begin, end) | something | endfor can generate those extra numbers.

However, I don't know if it's possible to combine them to do what I want (or if there's a different way to do it). Does anybody knows how can I add those extra values automatically? I'm quite sure that it's possible using Vim, but I don't know how.
Answer: You can do this by visually selecting the area then typing
:s/$/\=', '.(line('.')-line("'<")+1)<CR>

(range is added automatically when you type : from visual mode). Visual mode is needed to get line("'<") thing, if you are fine with typing line number in place of it use any range.
Answer: I'd do
:%!nl
:%s/\v^\s*(\d+)\s+(.*)$/\2, \1/g

nl will (by default) skip numbering empty lines
Or as a oneliner
:exec "%!nl"|%s/\v^\s*(\d+)\s+(.*)$/\2, \1/g

Comment: Note that `nl` does not number blank lines, so it may be necessary to use `nl -ba`, depending on the desired behavior.
Answer: :%!awk '{print $0", "NR}'

or
:%!perl -lpe '$_.=", $."'


Modal Global Asp.net Webforms

Question: Criei um modal, que vou praticamente usar em todos os formulários do sistema, porém não sei como chamar esse modal nos formulários.
Este é o código do meu modal, a página chama Modal.aspx, e o modal é o #modalexclusao

<%@ Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Modal.aspx.cs" Inherits="web_academia.Modal" %>
  <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Dialog - Default functionality</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">

  </asp:Content>
  <asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="server">

Senha Exclusão teste form

  </asp:Content>

Como posso chamar ele no code-behind de outra página ?
Tentei desta forma:

$(document).ready(function() {
  $('#modalexclusao').modal({
    url: 'Modal.aspx'
  });
});

Porém não aparece o modal.
Comment: Tudo bem @DiegoSantos, estou pesquisando pra ver se encontro alguma solução.
Comment: Você já tentou usar o @RenderPage("~/Views/Shared/SampleView.cshtml") ?   Só tem que ver como var jogar isso numa condicional... Mas essa é a função desse cara...
Comment: Utilizo webforms @DiegoSantos, atualizei da forma que tentei fazer, porém não funciona corretamente.
Comment: Puts, me desculpa faltou atenção. Vamos pesquisar
Answer: Não tinha pensando na possibilidade, só colocar o modal na página Master, e deu certo, consigo chamar ele em qualquer página do projeto.

Modal Global Asp.net Webforms


Importing redux action makes other actions undefined

Question: This is one of the strangest things I have ever seen. It makes absolutely no sense to me. The short version is I have a Redux action creator function. If I import this function into this one particular component file, it makes every function imported from its file undefined.
So, let's start with the file filterInputModal.actions.js. This contains my Redux action functions, created using redux-starter-kit:
export const showAddCategoryModal = createAction('showAddCategoryModal');

That is the function I've been working with. Now, this function has long since been imported into my ManageVideoFilters.js component:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { showAddCategoryModal } from 'store/filterInputModal/filterInputModal.actions';

const ManageVideoFilters = (props) => {
    /* Component logic */
};

/* PropTypes and mapStateToProps */

const mapDispatchToProps = (dispatch) => bindActionCreators({
    showAddCategoryModal: () => showAddCategoryModal() // Done this way to avoid passing in a payload, since certain default event payloads cause Redux to print console errors
});

export default connect(mapStateToProps, mapDispatchToProps)(ManageVideoFilters);

So far so good. Before we go and break everything, let's take a look at my filterInputModal.reducer.js Redux reducer, also created using Redux Starter Kit:
import { createReducer } from 'redux-starter-kit';
import { showAddCategoryModal } from './filterInputModal.actions';

const initialState = {}; // The initial state for the reducer goes here

const handleShowAddCategoryModal = (state) => {
    /* handle updating the state */
    return state;
};

const actionMap = {
    [showAddCategoryModal]: handleShowAddCategoryModal
};

export default createReducer(initialState, actionMap);

The action map uses the action creator functions toString() as the key, and then I provide my own functions to handle updating the state. Again, at this point, everything is perfect. We will come back to the reducer in a sec, first let's break things.
Now we're going to my VideFileEdit.js component. If we add the following line to this component, everything breaks:
import { showAddCategoryModal } from 'store/filterInputModal/filterInputModal.actions';

So, how does it break?

The import of the showAddCategoryModal function in filterInputModal.reducer.js now is undefined.
Because the reducer is using the functions as the keys to handle actions, the reducer is no longer able to handle the action properly and update the state.

It gets weirder though. Here are some of the weird behaviors I'm seeing.

If I import this action into any other component, everything is fine. The import in the reducer is unchanged.
The import of the function in both ManageVideoFilters.js and VideoFileEdit.js is fine.

So, what can I try next? This is really strange and doesn't make any sense to me. I've never seen this before.
Comment: are there any recursive imports , in your files ?
Answer: As the commenter said, the problem was recursive imports. My filterInputModal.reducer.js exported some constants, which were imported into my filterInputModal.actions.js. The actions from filterInputModal.actions.js were then imported into filterInputModal.reducer.js. Hence the recursive import.
I moved the constants into a new file, filterInputModal.constants.js, and viola, problem solved.


SpringData paginação com PageImpl<> o size não funciona

Question: Criei um método dentro de uma classe de serviço para gerar uma lista de produtos paginada utilizando SpringData (aplicação Java Spring Rest) , segue o código:
public Page<ProdutoDTOVendedor> listarProdutos(String descricao, Boolean disponivel,
            Integer page, Integer size, String orderBy, String direction) {

        //Rotina para validação do usuário do end-point
        UserSS us = AuthService.authenticated();

        Optional<Vendedor> vendedor = vendedorRepository.findById(us.getId());
        if (!vendedor.isPresent()) {
            throw new ObjectNotFoundException("Vendedor não encontrado");
        }

        Pageable pageable = PageRequest.of(page, size, Direction.valueOf(direction), orderBy);

        List<ProdutoDTOVendedor> produtosVendedor = new ArrayList<>();

        Optional<List<ItemVendedor>> itensVendedor = itemVendedorRepository.findByIdVendedorEqualsAndIdProdutoDescricaoDetalhadaContaining(vendedor.get(), descricao);
        for (ItemVendedor item : itensVendedor.get()) {
            produtosVendedor.add(itemVendedorToProdutoDTOVendedor(item));
        }
        Page<ProdutoDTOVendedor> produtosPage = new PageImpl<ProdutoDTOVendedor>(produtosVendedor,pageable,  (pageable.getOffset() + pageable.getPageSize()));
        return produtosPage;
    }

O método gera a seguinte lista paginada:

Se vcs perceberem o atributo diz esta com o valor 24, por isso consegue trazer os 4 elementos da lista pois é o total que eu tenho cadastrado, porém se eu mudo este atributo size, a lista de itens deveria vir com a quantidade equivalente se o valor atribuído for menor do que eu tenho de produtos cadastrados:

Como podem ver coloquei na URI o parâmetro do size, o objeto pageable recebeu e reconheceu o parâmetro size corretamente, porém não surtiu efeito na lista de produtos, com o parâmetro no valor 1 deveria retornar somente 1 item e não a quantidade total. Acredito que não estou conseguindo trabalhar com o PageImpl<> da forma correta, como corrigir esta situação? Abaixo segue o código do método da classe resource responsável por chamar o método do serviço:
@GetMapping(value="/produtos/list")
    public ResponseEntity<Page<ProdutoDTOVendedor>> listarProdutos(

            @RequestParam(value = "descricao", defaultValue = "") String descricao,
            @RequestParam(value = "disponivel", defaultValue = "") Boolean disponivel,
            @RequestParam(value = "page", defaultValue = "0") Integer page,
            @RequestParam(value = "size", defaultValue = "24") Integer size,
            @RequestParam(value = "orderBy", defaultValue = "descricao") String orderBy,
            @RequestParam(value = "direction", defaultValue = "ASC") String direction) {
        Page<ProdutoDTOVendedor>  produtos = vendedorService.listarProdutos(descricao, disponivel, page, size, orderBy, direction);
        return ResponseEntity.ok().body(produtos);
    }

Answer: Eu acredito que o problema esteja na consulta do banco de dados.
Como você esta montando o page acredito que o controle de registro deva ser seu, o spring não fara isso automático.
Faça um teste recebendo um elemento Pageable no metodo get e utilize findAll para ver se funciona
Ex
public ResponseEntity<Page<ProdutoDTOVendedor>> pesquisar(Pageable pageable) {
    // ...
    return itemVendedorRepository.findAll(pageable)
}

Funcionando tente passar o pageable no seu metodo de busca
itemVendedorRepository.findByIdVendedorEqualsAndIdProdutoDescricaoDetalhadaContaining
Caso não funcione acredito que tenhas que fazer o controle manualmente.
Comment: Fala Marcelo, tudo bem? Devido o tempo da pergunta, acabei alterando a abordagem de consulta para conseguir trabalhar com paginação neste cenário. Antes como havia descrito, esta utilizando uma abordagem através do método de palavras-chaves (Keywords) no repository, então alterei para uma abordagem utilizando o EntityManager e consulta JPQL no próprio serviço. Vou colocar na resposta do que fiz, mas de qualquer forma muito obrigado.
Answer: para conseguir o resultado que precisava acabei alterando a abordagem da consulta, antes estava realizando a consulta criando uma instrução de palavras-chaves dentro do repository, porém quando convertia esta lista para outro formato não conseguia aproveitar o pageable, e nem implementar um pageable manualmente na nova lista criada, este era o problema.
Portanto, decidi criar a consulta do no próprio serviço utilizando EntityManager e JPQL, as querys criadas através desta abordagem que retornam listas suportam que vc trabalhe com paginação, para tal basta vc indicar o setFirstResult e o setMaxResults assim com esta informação sua lista poderá ser paginada. Vamos ao código referente a aplicação da consulta (simplifiquei a consulta para facilitar o entendimento), esta consulta ficou dentro do método de pesquisa do serviço:
String instrucao = "select prod from Produto prod order by descricaoDetalhada ";

Query jpql = em.createQuery(instrucao);

jpql.setFirstResult((page-1) * size);
jpql.setMaxResults(size);

@SuppressWarnings("unchecked")
List<Produto> produtos = jpql.getResultList();

As variáveis page e size continuam vindo de dentro da assinatura do método:
public List<ProdutoDTOList> listarProdutosParaVincular(String descricao, Long categoriaID, Integer page, Integer size)

Tendo a lista de produtos que foi gerado pela getResultList() já paginada, então faço a conversão dela para que seus elementos tenham a estrutura do meu DTO.


Why is my code not working properly? Is there something in STL-list which I am forgetting?

Question: This is my code:
#include <iostream>

#include <list>

using namespace std;

template <class T>

void display(list<T> l){

    list<int>::iterator i;
    for (i = l.begin(); i != l.end(); i++)
    {
        cout << *i << " ";
    }
}

void enter(list<int> l){

    list<int>::iterator i;
    int index = 1;
    for (i = l.begin(); i != l.end(); i++, index++)
    {
        // cout << "check" << endl;
        cout << "Enter element at index " << index << endl;
        cin >> *i;

    }

}

int main(){

    list<int> l;
    display(l);
    cout << endl;
    l.push_front(1);
    l.push_front(2);
    l.push_front(3);
    l.push_front(4);
    l.push_front(5);

    list<int> l2(3);
    enter(l2);
    display(l2);
    cout << "EXE";
    return 0;
}

The output of the following program is:
Enter element at index 1

1

Enter element at index 2

2

Enter element at index 3

3

0 0 0 EXE

Required Output:
Enter element at index 1

1

Enter element at index 2

2

Enter element at index 3

3

1 2 3 EXE

Comment: @SrijanSinha Please format your post properly next time so it's actually readable. While posting there is a preview so you can see how it looks. I did it for you this time.
Comment: @navyblue It does if you include the parts of the code that were obscured by the invalid formatting because they looked like HTML tags (e.g. ``). I fixed the formatting, now it compiles.
Comment: Can you put the exact code that you're compiling? What is written in the question doesn't compile.
Answer: The issue is that you pass the list by value in enter. When you update the list with cin >> *i, you are updating a copy of l2 instead of the l2 declared in main().
If you would like to update the list you will need to pass by reference instead.
void enter(list<int>& l){

  list<int>::iterator i;
  int index = 1;
  for (i = l.begin(); i != l.end(); i++, index++)
  {
      // cout << "check" << endl;
      cout << "Enter element at index " << index << endl;
      cin >> *i;

  }
}


Generating a log-normally distributed pseudorandomly generated data set

Question: The feedback I received from my initial post seemed to indicate that my question was ill-posed.  Hence, I would like to clarify what I am doing and how I hope to achieve it.
I'm running some simulations on models with a material parameter $g(x)$ whose values, according to the literature I've read, are log-normally distributed in the spatial.  The material parameter $g(x)$ corresponds to a physical property that is strictly positive and experimentally determined to be never larger or smaller than some threshold values $g_{\max},g_{\min}>0$.  When I run my simulations, I would like to generate a distribution of values $g$ over the spatial domain such that

All values of $g$ are strictly in the interval $[g_{\min},g_{\max}]$
The distribution of values of $g$ is as close to a log-normal distribution as possible for a given mean $\mu$ and standard deviation $\sigma$.

I have at my disposal a pseudorandom number generator that creates a vector of normally distributed values with a given mean $\mu$ and standard deviation $\sigma$.  I know that if the data set $X$ is normally distributed, then an exponential transformation of the data (in other words, $\exp(X)$) should produce a log normal distribution.
I hypothesize that I can create this log normal distribution by the following process:

Make a normal distribution of values X with mean $\mu$ and standard deviation $\sigma$.
Exponentiate the values to generate a new set $Y=\exp(X)$.
Rescale and shift the values of $Y$ so that the minimum value of the new set is exactly $g_{\min}$ and the maximum is $g_{\max}$.  I would do so by creating a new data set $Z=a + (b-a)Y$.

Would this give me the results I desire?  That is, in the end, would the set $Z$ be log-normally distributed with all values lying in the interval $[g_{\min},g_{\max}]$?
Comment: It all depends on what exactly you mean by a "normal" and a "lognormal" distribution. The conventional mathematical definition of "normal" makes nonsense of this question, because the only normal distributions supported on finite intervals are the degenerate ones: one might go so far as to say there is no such thing as a "normal distribution on the interval [0,1]." Do you want to *truncate* your distributions, perhaps? If so, then why do you propose truncating *twice* in your procedure, when once will do?
Comment: Rescaling it so all the values are between the limits means your $\mu$ and $\sigma$ no longer apply. Why specify them only to in effect destroy them? If the range is restricted, *it is not lognormal*. Why pound an infinite peg into a square hole?
Comment: Welcome to C.V. Paul. Let's start by 1. What do you mean 'make a normal distribution on the interval [0,1]'? Do you plan to generate generate $X\sim\mathcal{N}(0,1)$ and reject the 1/3 or so observations falling outside [-1,1] and square the rest?
Comment: http://en.wikipedia.org/wiki/Truncated_distribution
Comment: Check out some kind of beta distribution as a first approximation. Although you've revised your question, all the key comments on your first version still apply.
Comment: I meant 'fold' the rest, i.e. take the absolute value.
Comment: Paul, you'll really need to clarify what you mean here, because as written your question doesn't make sense. Can you maybe draw a picture of a 'normal distribution on the interval $[0,1]$' please, with the $0$ and $1$ clearly indicated as well as what the mean and standard deviation of the normal should be? It doesn't matter if it's a little rough, because at the moment we're just trying to make sure we understand what you're asking.
Comment: Thank you all for your suggestions.  From your feedback, I have determined that my initial question was a bit ill-posed and unclear.  I have edited it to explain the context of my proposed method.  If you need further explanation, feel free to ask me.
Comment: Again, thank you all for your feedback but I must apologize.  Implicit to my question was an erroneous assumption was that a log normal distribution could be constucted on a finite interval.  The literature does stipulate that the material property is log-normally distributed, but it is also true that the material property cannot be negative.  If I omit the upper bound constraint, the interval is semi-infinite and a log-normal distribution should be able to support it.
Answer: No. The data $Z$ clearly won't be distributed as log-Normal with parameters $\mu$ & $\sigma$; nor will they be distributed (conditional on $a$ & $b$) as any log-Normal, as you've introduced a location shift—which is not equivalent to changing a parameter value. Note also that you'll get a different distribution for each simulation of $Z$ & it will look very different at different sample sizes.
The discrepancy between the literature & experimental results should be the first thing to investigate. It could be that a truncated log-Normal is what you want, as @whuber suggested, & which you can easily get by discarding values of $Y$ outside $[g_\mathrm{min}, g_\mathrm{max}$]. Or perhaps another distribution entirely—@Nick's suggestion of a beta distribution  is worth following up.
Comment: +1. But given that the literature suggests a lognormal is appropriate, betas will not be good substitutes because of their very different tail behavior.
Comment: @whuber +1. But given that experiments suggest a log-Normal is inappropriate, betas might be good substitutes because of their very different tail behaviour.
Comment: +1 to everyone commenting. Poster has to decide: if the distribution is lognormal, it can't be confined to a finite interval; if the support is a finite interval, the distribution can't be lognormal. One assumption must be wrong.


Symmetrically distributed random variables

Question: Let $\{X_n\}$ be a sequence of iid random variables, and let $\{Y_n\}$ be another sequence of iid random variables.
Suppose that $P(X_n \leq c) = P(Y_n \geq -c)$ for every real number $c$.
Let $S_n = \sum_{i=1}^n X_i$ and $T_n = \sum_{i=1}^n Y_i$.
Then, how do I show that
$$\limsup \dfrac{S_n}{n}  \text { and } \limsup \dfrac{-T_n}{n}$$
are identically distributed?
Intuitively, I am guessing that the fact that the distributions of $X_n$ and $-Y_n$ are the same should give what I want to show, but I cannot figure out how to actually show it.
Comment: Let $Z_n=-Y_n$ for all $n$ and $P(Y_n\geq -c)=P(-Y_n\leq c)=P(Z_n\leq c)$ so $Z_n=X_n$ in distribution.
Comment: @SeyhmusGüngören But, how does that show limsups have the same distribution?As I wrote, I know that $X_n$ and $Z_n$  have the same distribution
Answer: The facts that the sequences $(X_n)_{n\geqslant 1}$ and $(Y_n)_{n\geqslant 1}$ are independent and that for each $n$, $X_n$ and $-Y_n$ have the same distribution show that the sequence $(X_n)_{n\geqslant 1}$ and $(-Y_n)_{n\geqslant 1}$ have the same distribution. It follows that
the sequences $(S_n/n)_{n\geqslant 1}$ and $(-T_n/n)_{n\geqslant 1}$ have the same distribution. Consequently, the sequence $\left(\sup_{n\geqslant N}S_n/n  \right)_{N\geqslant 1}$ and $\left(\sup_{n\geqslant N}-T_n/n  \right)_{N\geqslant 1}$ have the same distribution.
Comment: What do you mean by saying that the two "sequences of random variables " are identically distributed?
Comment: Do you know how the distribution of a sequence of random variables is defined?
Comment: Sorry; please ignore my previous comment. No, I do not know
Comment: I only know the definition of distribution of a single random variable


Hibernate entity manager looking for tables in different schemas

Question: I am implementing jpa persistence using hiberante-entity manager in a java web project.
I have set following property in in persistence.xml.
<property name="hibernate.hbm2ddl.auto" value="update"/>
I have a schema for each user. For e.g i have a schema for user1 and one for user2.
If the table 'ABC' is present in user1 schema but not in user2 schema & I deploy the application and it uses user2 db credentials, i get the message 'user1.ABC' table found so the 'ABC' table is not created in user2 schema.
When i tried with following property in the persistence.xml file the table is created in the user2 schema.
 <property name="hibernate.hbm2ddl.auto" value="create"/>

My question is
why hibernate is searching in another schema i.e user1 if the application is using user2 db credentials? and
I don't want to create the schema every time the server is started so how can i avoid using
the value 'create'.
EDIT: Below is my persistence.xml file
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="XXXXXX" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    <class>org.axonframework.saga.repository.jpa.SagaEntry</class>
    <class>org.axonframework.saga.repository.jpa.AssociationValueEntry</class>

    <properties>
        <property name="hibernate.archive.autodetection" value="class"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
</persistence-unit>
</persistence>

Thanks in advance
Comment: can you post your full persistence.xml?
Comment: could you post the `org.axonframework.saga.repository.jpa.SagaEntry` as well. Probably you are defining the Schema there , so it is defaulted no matter which DB credentials are being picked up
Answer: I am also facing the same issue, and after digging a lot, get to know that the bug is related to the Mysql Connector.
After changing MySql Connector 6.0.5 to 5.1.28 It works fine for me.
I hope It can help you. Cheers
Answer: Has the same problem.
After set <property name="hibernate.default_schema" value="MY_SCHEMA"/> the problem has been solved.
Answer: Check if you are calling user1 and user2 in your Hibernate Sessionfactory.
Comment: In my case there is only one user (no multi-tenancy) and behavior is the same as described by the author.
Comment: @Scadge having multiple schemas implicitly means multi-tenancy. Each schema is considered a tenant.
Answer: If you want to handle several schemas properly then use multi-tenant per schema also  if you want to update/create/migrate/handle columns/tables/schemas/databases then use flyway or liquibase
REFERENCES
Multitenancy  https://vladmihalcea.com/hibernate-database-schema-multitenancy/
Flyway https://flywaydb.org
Liquibase https://www.liquibase.org
Comment: In my case there's no multi-tenancy - only a single user and connection string to specific database, but instead of creating a table in this database, hbm2ddl updates the one in another schema which appears to have the same name.
Comment: @Scadge and please don't hijack other peoples' questions to ask your own.
Answer: The Hibernate documentation is clear about this, you need to enable multi-tenant operations as described in this answer and this example.
Basically you have to declare multiple persistence units and have each point to a different schema. Each can then use different login credentials as well.
Hibernate documentation link
To summarise:

Define your persistence unit
Define your mapping files per persistence unit

When using JPA add the following:
 3. Specifying tenant identifier from SessionFactory
 4. Implement a MultiTenantConnectionProvider


Ask a limit question from George & Casella Example 1.5.4

Question: I have a question from George & Casella Example 1.5.4.
The cdf of the random variable X is $F_X(x) = 1-(1-p)^x$, x=1,2,...
The textbook claims that if $0<p<1$, then $\lim_{x\to -\infty} F_X(x)=0$.
I am confused here. I google the figure such as $0.3^x, 0.7^x$, and I find when x is going to negative infinity, it tends to positive infinity. Then I find  $\lim_{x\to -\infty} F_X(x)=-\infty$.
Comment: $F_X(x)=0$ for $x <0$, $ F_X(x)=1$ for $x \geq1$ It makes no sense to take limit of $1-(1-p)^{x}$ as $x \to \infty$ because $F_X(x)$ is not given by this formula when $x >1$.
Comment: The formula for $F_X(x)$ is not supposed to be valid for all $x$. For any CDF we have $F_X(x) \to 0$ as $x \to -\infty$.
Comment: @geetha290krm I know your second sentence. That's why when I let x goes to negative infinity, I didn't get that F goes to 0.
Answer: I think they mean that for $x\le 0$ then $F$ is defined to be zero. The expression you have is the value of $F$ at natural numbers while for non-natural numbers $x>0$, $F(x)=F(n)$ where $n$ is the greatest natural number less than or equal to $x$. Finally, as $x\to\infty$ then I hope you agree that $(1-p)^x\to 0$ and so $F(x) \to 1$.
Comment: p is fixed between 0 and 1. We should view p as a constant.
Comment: Sorry my bad, I will edit my answer


Solving a quadratic system

Question: Just confused on method here, I have the following system
$3x^2-y=0\\-x-3y^2=0$
How would I go about solving this? I am aware of what the four solutions are but I can't see how I could personally find them.
Any help is appreciated!
Comment: Eliminate $y$ between the equations, then solve for $x$.
Answer: From the first equation we have that $y=3x^2$. Substituting this into the second equation we obtain, $x+3(3x^2)^2 = 0$ which simplifies to $x + 27x^4 = 0$, or equivalently, $x(1+27x^3) = 0$. One solution is thus $(x,y) = (0,3\cdot 0^2) = (0,0)$. Can you find the other three?
Answer: From first equation, $\;y=3x^2\;$ , and now substitute in the second one:
$$-x-3(3x^2)^2=0\implies x(1+27x^3)=0\implies x= 0,\,-\frac13$$
Take it from here...(if you want also complex roots add them in the above line already)
Answer: Substitute $y=3x^2$ in the second equation to get $$-x-27x^4=0.$$
Then
$$x=0\text{ or }x^3=-\frac1{3^3}.$$

Solving a quadratic system


Dynamic data loading is not working in java script

Question: What I have:
In index.html I have 4 form fields like Annual Salary, Annual Sal Increasement, Present Age, Retirement Age. using ids of those I am validating them in Valid.js
in the time of validating I am set those values in local storage.
//Index.html
 //After Submit
    function Validation()
{
//valid.js file using ids of forms

    var Ann=document.getElementById("Annsal").value;
    var Sal=document.getElementById("SalInc").value;
    var Page=document.getElementById("PreAge").value;
    var Rage=document.getElementById("RetAge").value;
    var Ys=document.getElementById("Yss").value;
    var Nn=document.getElementById("Noo").value;

            // Storing the value above into localStorage
            localStorage.setItem("Asal", Ann);
            localStorage.setItem("Asalinc", Sal);
            localStorage.setItem("Present", Page);
            localStorage.setItem("Retir", Rage);
            localStorage.setItem("Yssss", Ys);
            localStorage.setItem("Nnnn", Nn);

    if(Ann=="")
    {
        document.getElementById("user").innerHTML="**Please Enter the Annual Salary**";
        return false;

    }

Then I take another confirm.html and calculate.js to some do operations on that user entered data then I print in table format in another web page.
//Confirm.html

Now I am Facing issue in javascript file I retrieve those data using getitem of local storage function.
//calculate.js
/ Called on body's `onload` event
    function init() {

        // Retrieving the text input's value which was stored into localStorage

         var a=localStorage.getItem("Asal");
         var b=localStorage.getItem("Asalinc");
         var c=localStorage.getItem("Present");
         var d=localStorage.getItem("Retir");
         var e=localStorage.getItem("Yssss");
         var f=localStorage.getItem("Nnnnn");

        // Writing the value in the document
        document.write("

Age     	Annual Sal     	BiWeekly-Pre     	Monthly-Pre   	Cumulative-Pre     	Basic   	Total
")

        for(i=c;i<=101;i++){

            //calculate your formulas here
            // example-- calculating basic salary

            //use your own formula
            if(i<45)
            {
            basic= salary/2;
            }
            else
            {
            basic=salary*0.4;
            }

            //display the content

        document.write("
"+i+"	"+basic+"
")
        }

        document.write("
");

    }

But the values are storing but that for loop is not working properly the data is not printing only printing is those table headers why this error can anyone suggest fixing this... Thnx in Advance.
Comment: Have you checked the error console? What errors are you getting? Where are `basic` and `salary` defined and assigned values?
Comment: User enter those values like annual Salary, Annual sal increment, Present Age,Retirement Age ,a,b,c,d,f, those are storing these values only
Comment: #Jon I checked using the alert function in a basic variable its doesn't show any value There is no Error in console But only it Pritning Headers of table
Comment: Just noticed you have variables basic and salary, where do you define those ?
Comment: #noitse I didn't define them directly I'm using in my code
Comment: How are you using those variables. If `basic` is undefined you should be getting a console error: http://jsfiddle.net/uaqk5zhx/ .  What happens if you hard code values for the `a,b ....` variables? Please try to provide us a [MCVE]
Comment: Please see: http://jsfiddle.net/rLkbwxde/2/ . Your init function generates the following error "(index):60 Uncaught ReferenceError: salary is not defined" . Please use your browser tools to check then fix console errors.
Answer: The problem I immediately see is that you have a broken comment:
/ Called on body's `onload` event

This is near the top of your calculate.js file. Make it this:
// Called on body's `onload` event

And it'll be partially fixed. There are, however, many more errors that you'll find in the JavaScript console.
Comment: I think you'll find there is are more errors that are evident through the console.
Comment: I don't have access to the full code (`index.html` is missing) so I can't check all of it, but I'll check what I can.


How to fix 'Unresolved reference: HttpClient' with ktor-client-core targeting linuxX64

Question: I'm trying to build a Kotlin Multiplatform command line application targeting linuxX64 in a first step. Therefore I wanted to build a client based on Ktor which is used in the common module.
Here my fairly simple setup:
Version overview

Ktor 1.1.5
Kotlin Multiplatform 1.3.31
Gradle 5.3.1

build.gradle.kts
plugins {
    kotlin("multiplatform") version "1.3.31"
}

repositories {
    mavenCentral()
    maven { url = uri("https://kotlin.bintray.com/ktor") }
}

kotlin {
    linuxX64("linux") {
        binaries {
            executable()
        }
    }

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation(kotlin("stdlib-common"))
                api("io.ktor:ktor-client-core:1.1.5")
            }
        }

        val linuxMain by getting {
            dependsOn(commonMain)
            dependencies {
                api("io.ktor:ktor-client-curl:1.1.5")
            }
        }
    }
}

src/linuxMain/kotlin/Main.kt
fun main(){
    val client = MyClient()
    client.execute()
}

src/commonMain/kotlin/MyClient.kt
import io.ktor.client.*

class MyClient {

    private val client = HttpClient()

    fun execute() {
        //do something with Ktor client
    }
}

When I build the project I get the following build issue:
11:15:21: Executing task 'build'...

> Configure project :
Kotlin Multiplatform Projects are an experimental feature.

> Task :wrapper

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

> Configure project :
Kotlin Multiplatform Projects are an experimental feature.

> Task :compileKotlinLinux FAILED
e: .../src/commonMain/kotlin/MyClient.kt: (1, 8): Unresolved reference: io
e: .../src/commonMain/kotlin/MyClient.kt: (5, 26): Unresolved reference: HttpClient

I'm new to Kotlin Native/Mutliplatform and Ktor. So bear with me if this my setup is wrong...
Comment: Adding `enableFeaturePreview("GRADLE_METADATA")` to settings.gradle.kts fixed the build issue. I just made a successfull HTTP Call with linuxX64 binary using ktor-curl-client :-)
Answer: Adding enableFeaturePreview("GRADLE_METADATA") to settings.gradle.kts fixed the build issue.
I just made a successful HTTP call with a linuxX64 binary using ktor-client-curl :-)
Comment: Seems outdated: Exception is:
java.lang.IllegalArgumentException: There is no feature named GRADLE_METADATA
Comment: I got the same error.  Either my build is different or this is no longer a working solution.


Trying to set drush

Question: First, I installed Lando which also installs Docker Desktop. After installing Lando, I opened the Windows Terminal and created a folder called "Sites". Inside the "Sites" folder, I created another folder named "my-first-drupal10-app". Then, I navigated to the "my-first-drupal10-app" folder and executed the following command: lando init --source cwd --recipe drupal10 --webroot web --name my-first-drupal10-app.
Next, I ran the command lando composer create-project drupal/recommended-project:10.0.x-dev@dev tmp && cp -r tmp/. . && rm -rf tmp to create a Drupal project. Once the project was set up, I started Lando with lando start". I didnt have containers so it created new ones.
After that, I needed to install Drush, so I used the command lando composer require drush/drush. Although the installation was successful, I encountered an error when trying to execute a Drush command.
`C:\Users\Hya\Sites\my-first-drupal10-app>lando drush
PHP Fatal error:  Uncaught Error: Class "Symfony\Component\HttpKernel\Kernel" not found in /app/vendor/drush/drush/src/Preflight/Preflight.php:209
Stack trace:
#0 /app/vendor/drush/drush/src/Runtime/Runtime.php(84): Drush\Preflight\Preflight->loadSymfonyCompatabilityAutoloader()
#1 /app/vendor/drush/drush/src/Runtime/Runtime.php(51): Drush\Runtime\Runtime->doRun(Array, Object(Symfony\Component\Console\Output\ConsoleOutput))
#2 /app/vendor/drush/drush/drush.php(77): Drush\Runtime\Runtime->run(Array)
#3 /app/vendor/drush/drush/drush(4): require('/app/vendor/dru...')
#4 /app/vendor/bin/drush(120): include('/app/vendor/dru...')
#5 {main}
  thrown in /app/vendor/drush/drush/src/Preflight/Preflight.php on line 209

Fatal error: Uncaught Error: Class "Symfony\Component\HttpKernel\Kernel" not found in /app/vendor/drush/drush/src/Preflight/Preflight.php:209
Stack trace:
#0 /app/vendor/drush/drush/src/Runtime/Runtime.php(84): Drush\Preflight\Preflight->loadSymfonyCompatabilityAutoloader()
#1 /app/vendor/drush/drush/src/Runtime/Runtime.php(51): Drush\Runtime\Runtime->doRun(Array, Object(Symfony\Component\Console\Output\ConsoleOutput))
#2 /app/vendor/drush/drush/drush.php(77): Drush\Runtime\Runtime->run(Array)
#3 /app/vendor/drush/drush/drush(4): require('/app/vendor/dru...')
#4 /app/vendor/bin/drush(120): include('/app/vendor/dru...')
#5 {main}
  thrown in /app/vendor/drush/drush/src/Preflight/Preflight.php on line 209`

Comment: Lando has a support community: https://docs.lando.dev/drupal/support.html. It is difficult to answer this question not knowing anything else about what you did for setup.
Comment: Welcome to Drupal Answers! Please do not use screenshots to show error messages; instead, copy and paste those error messages.
Answer: For what it's worth, I've been working with Lando for only about a month. I've not had to install Drush separately.  The lando drupal recipe installs Drush for you.  Try just running "lando drush cr" to see if it works.

Trying to set drush


Decrypting a CipherInputStream results in an empty stream

Question: I seem to be have an issue with JCE. I create an CipherInputStream using an encrypting JCE cipher which I then use to create another CipherInputStream using a different decrypting JCE cipher.
When I try to read then second stream all I get is empty data. I found no documentation forbidding the above behavior. Does anyone know what the problem is?
This is the code which I am running, at the end plainText is empty (the same issue persists regardless of what SecurityProvider I use).
InputStream payload = new ByteArrayInputStream(payloadArray);
Cipher encryptCipher = Cipher.getInstance("AES", "SunJCE");
encryptCipher.init(Cipher.ENCRYPT_MODE, key, IV);
InputStream encryptStream = new CipherInputStream(payload, encryptCipher);

Cipher decryptCipher = Cipher.getInstance("AES", "SunJCE");
decryptCipher.init(Cipher.DECRYPT_MODE, key, IV);
InputStream decryptStream = new CipherInputStream(encryptStream, decryptCipher);

byte[] plainText = IOUtisl.toByteArray(decryptStream);

Thanks!
Answer: As you left out the parts for the key and the IV parameter find a small snippet, based on your provided code.
// add proper exception handling, left out only for the example
public static void main(String[] args) throws Exception {
    String transformation = "AES/CBC/PKCS5PADDING";
    String provider = "SunJCE";
    String algorithm = "AES";
    byte[] payloadArray = "secret text".getBytes();

    KeyGenerator keyGen = KeyGenerator.getInstance(algorithm, provider);
    keyGen.init(128);
    Key key = keyGen.generateKey();

    byte[] ivBytes = new byte[16];
    SecureRandom prng = new SecureRandom();
    prng.nextBytes(ivBytes);
    IvParameterSpec IV = new IvParameterSpec(ivBytes);

    Cipher encryptCipher = Cipher.getInstance(transformation, provider);
    encryptCipher.init(Cipher.ENCRYPT_MODE, key, IV);

    InputStream payload = new ByteArrayInputStream(payloadArray);
    InputStream encryptStream = new CipherInputStream(payload, encryptCipher);

    Cipher decryptCipher = Cipher.getInstance(transformation, provider);
    decryptCipher.init(Cipher.DECRYPT_MODE, key, IV);
    InputStream decryptStream = new CipherInputStream(encryptStream, decryptCipher);

    for (int i = decryptStream.read(); i >= 0; i = decryptStream.read()) {
        System.out.print((char) i);
    }
}

output
secret text


How can I persist an HTML file in my iOS application?

Question: I have registered my app to be able to open HTML files. I would like the app to keep the last HTML file it opened... If I open a new HTML file, I would like it to overwrite the last one opened.
I have attempted to user the Documents directory and its not working for me. I have also tried using NSUserDefaultsto no avail. Here is what i currently have:
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    ViewController *vc = (ViewController *)self.window.rootViewController;
    [vc loadFileWithUrl:url];

    [[NSUserDefaults standardUserDefaults] setURL:[url fileReferenceURL] forKey:@"amd"];
   return YES;
}

I kill the application entirely, then - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions is called. Here is how that method looks:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *url = [[NSUserDefaults standardUserDefaults] URLForKey:@"amd"];
    if (url)
    {
        ViewController *vc = (ViewController *)self.window.rootViewController;
        [vc loadFileWithUrl:url];
    }

    return YES;
}

url is always nil :(
PS: I have also tried storing the HTML file in its string representation, and I am able to get that to persist in the Documents folder, but when I try to load that string using:
[webView loadHTMLString:htmlString]; the page never loads. I think that has something to do with the Javascript but I'm not too sure.
Answer: The user defaults are saved when the app goes to the background, or when you call -synchronize on the user defaults. When developing, you often don't put the app into background, but just kill it through XCode, in which case nothing gets saved. You can save the user defaults by pressing the home button on your iPhone/iPad, and killing the app in XCode 1second later.
Also, you should put a log statement into your first method, like NSLog(@"saving amd to %@", [url fileReferenceURL]); to be sure that it really gets saved!
Answer: It seems that you forgot to call
[[NSUserDefaults standardUserDefaults] synchronize];

Docs:

Writes any modifications to the persistent domains to disk and updates
  all unmodified persistent domains to what is on disk.


What is wrong with WITH statement in JavaScript?

Question: I seem to remember there is a problem with WITH. I don't miss it; I prefer each line of my code to stand on its own.
I started wondering about this when I learned (at SO) that people consider chaining one of their favorite features of jQuery. JavaScript's WITH and jQuery's chaining is, basically, the same feature, right?
Comment: You've asked two different questions here: 1. What's wrong with using the WITH statement, and 2. Is the WITH statement like chaining? You should consider separating the two questions.
Answer: No, they aren't the same thing...
With is a shorthand to reference a class's members without the need to fully qualify their names.
with o
{
   x = y;   // where x is a member of o. But how can you tell for sure?
}

Read what Douglas Crockford has to say about With. He encourages avoiding it--says its error prone and ambiguous. I agree with him.
jQuery chaining is a way to implement a fluent interface that allows you to pipe the result fro one method directly into another method. That is the output of a given method serves as input into the next. jQuery chaining can indeed look like with if you use lots of whitespace. The example below is from John Resig shows this.
jQuery("div").hide("slow", function(){
  jQuery(this)
    .addClass("done")
    .find("span")
      .addClass("done")
    .end()
    .show("slow", function(){
      jQuery(this).removeClass("done");
    });
});

Read about jQuery chaining here and here
Answer: With and chaining aren't quite the same. With affects scope, while chaining doesn't. Consider:
a.b.c = foo;

or:
with(a.b) { c = foo; }

In the second case, you've got no idea if c exists outside the with block, so if it's possible that you're just clobbering something another part of the program is relying on.
Answer: fwiw, I strongly disagree with crockford and the whole anti-with movement. Yes, I enjoy flogging deceased equestrians too.
The point where I agree with the anti's is that with should never be used as a crutch for object creation/assignment which in effect means never used directly:
BAD
with(a.b)
{
  c = x;
}

GOOD
with(a)
{
  b.c = x;
}

I believe the second form actually increases readability because it both indicates a block (the with itself) and removes whitespace (less text = less brainache) without recourse to redundant declarations/assignments. My argument is that with is only dangerous when you don't know what you're doing, and my follow on from that is if you don't know what you're doing you shouldn't be doing it. As I said, I realise I'm against the grain here.
Comment: I disagree with the philosophy that it makes it easy to make mistakes - so does C++ and you'd have a hard time fighting that one. Poor use of with is what causes the problems, using it in a non-risky way affords more readable code. (imho)
Comment: "My argument is that with is only dangerous when you don't know what you're doing"
But isn't that the point that Crockford makes... With makes it easy to do what you think you aren't doing! I like the explicitness that avoiding with provides. I've also got a sweet spot for deceased equestrian floggers, too.
Comment: There are cases where 'with' makes sense, for example when reading values from an object. However, IIRC I heard that Google Crome is slower when using 'with', and they recommend that you assign the object to a new variable and use that variable instead. I think it had something to do with caching. In other languages, like Pascal, 'with' can speed things up since the compiler can optimize the code, but that is not the case in javascript.
Answer: You should read with Statement Considered Harmful for a good explanation as to why you should avoid with.
No, with is not the same as chaining:

JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects.
Answer: I think the question has been answered above, just wanted to add my two cents on the topic of 'with.' The example almost all of you bring up are ambigious class and variable names, which with with or without with are hard to maintain and understand. If you name your variables, classes, objects with some kind of meaning with can be golden.
var car = {
           wheels: {radius: 5, rim: 'gold', shape: 'circle'},
           body: {color: 'black', windows: 'tinted'}
           };

and Now:
with (car){
    wheels.shape = square;
    body.color = blue;
}

Point being, with can be powerful and save a lot of time for the programmer after you. It works well only if you use it correctly and already have a habit of verbose naming of variables and sufficient commenting. Furthermore, someone said that if you do:
with(a){
    x = 3;
}

that somehow a variable that is not a member of the class will somehow gets overridden. Correct me if I am wrong but if there is a global variable x and a property a.x, in the with block, only the a.x get's overridden since that is the current scope.
Comment: The argument the anti's make about your "x" example is that reading it you don't know whther x is global or not, and the behaviour may not be as expected if a does not have an x member.
Comment: I just think anyone with knowledge of how *with* works, would be able to figure out. Especially if variable names are verbose.
Comment: yeah, I'm not entirely unsympathetic :)
Comment: You're absolutely correct, only the a.x gets overridden. It's still ambiguous, though. In your more verbose example, you may well have a "wheels" variable outside the "with" scope. If you've got an undiagnosed bug in that code, it's difficult for someone coming along later to tell what you actually meant. "With" then imposes a higher comment burden than code without it.

I'm taking a leaf out of Python's book here: explicit is better than implicit.
Comment: I understand the viewpoint, it's just I believe that when debugging one will not overlook looking up a couple of lines and seeing with. I guess to each their own. I do want to say I see both viewpoints, I am just more sympathetic to *with*.
Answer: Or you can reference from Mozilla here get more information.
The following is a fragment of the article
'with' makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:
  function f(x, o) {
    with (o)
      print(x);
  }

only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error -- just unexpected results.
Answer: You can use with statement for following operation
a.b.c.d.e.foo=somevalue;
a.b.c.d.e.doo=somevar;
as
with(a.b.c.d.e)
{
     foo=somevalue;
     doo=somevar;
}
but you have good option in javascript
var v=a.b.c.d.e;
v.foo=somevalue;
v.doo=somevar;
This will make procedure simple :)


Are $\frac18$-th root transformations recommended?

Question: My colleague wants to analyze some data after transforming the response variable by raising it to the power of $\frac18$ (that is, $y^{0.125}$).
I'm uncomfortable with this, but struggling to articulate why. I can't think of any mechanistic rationale for this transformation. Nor have I ever seen it before, and I worry that perhaps it inflates Type I error rates or something -- but I have nothing to support these concerns!
Additionally, my colleague finds that these transformed models outperform untransformed models in an AIC comparison. Does this, in itself, justify its use?
Comment: Just fyi, $y^{1/8}$ looks a *lot* like $\log(y)$ for many ranges of $y$. The log transformation is often justified in many cases (but also often used in unjustified cases as well).
Comment: @CliffAB Is right.  The main practical difference between small positive powers and the logarithm is that you can take powers of zero.  When there are a few zeros in the data (perhaps because of imprecision in how the numbers were recorded), sometimes a small power (0.1 or even 0.01) works as a substitute for the logarithm. (Better yet: use the Box-Cox transformation $y=(x^p-1)/p$ for small $p$.) Since very few natural laws involve a 1/8 power, though, and many involve exponential phenomena, using a log can sometimes provide better insight and interpretability than a small power.
Comment: You cannot meaningfully compare AICs between models with transformed dependent variables. (Transforming the independent variable is fine.)
Comment: This is a small riff on the idea that this transformation may be a substitute for logarithms if zeros occur. A logarithmic link for generalized linear models says that mean responses vary exponentially but doesn't assume that all their values are positive. So it tolerates some zeros in the data. Roughly the implication is that they should or would be positive if they could: e.g. reported zeros (zero specimens in sample, zero concentrations according to the machine) sometimes mean not detected.  Despite its wonderful name Box-Cox seems oversold whenever there is a natural link in GLMs.
Comment: This is a [related discussion](http://andrewgelman.com/2007/01/02/the_14power_tra/)
Comment: Unless there was a specific theoretical reason to take eighth roots (there might be in some situation, perhaps) I'd be leaning toward something similar but easier to discuss -- a log transformation. (Exact zeros in the data might make me reconsider that advice, depending on circumstances)
Comment: I wanted to add this link to Gelman's blog on this topic. http://andrewgelman.com/2007/01/02/the_14power_tra/  Thank you to all who replied so far!
Answer: It is common practice to apply power transformations(Tukey, Box-Cox) with arbitrary values on the response. From that perspective, I see no particular concern regarding your value of 1/8 - if that transformation gives you good residuals, go for it.
Of course, any transformation changes the functional relationship that you fit, and it may be that 1/8 doesn't make sense mechanistically, but that would not be a concern to me when the purpose is not to extrapolate or fit parameters of a physical law, but to get a proper p-value on the sign of the effect (I'd argue that's the normal use case in a regression). For that purpose, your only concern is that the function fits to the data in the domain of your predictor values (wrt mean and residual variation), and that is easy to check.
If you are unsure about the best value for the power transformation, and want to compare between different options, you should not directly compare AIC / likelihood values because the power transformation changes the scale of the response. Fortunately, it turns out that it's relatively straightforward to calculate a correction for the transformation, such that different transformations can be compared via their (corrected) likelihood (see, e.g. here).
In R, this is implemented in MASS::boxcox - this is a convenient way to choose the right value for the power.


Display JSON data on a page as a expandable/collapsible list

Question: I need help with with displaying JSON data on a page like expandable/collapsible list.
Here is a valid JSON I`ve made converting from XML with Python:
JSON Data
And to display it I`m usig this:
<!DOCTYPE HTML>

    <title>JSON Tree View</title>

Paste JSON Into The Textarea Below and Click 'Build Tree'

<textarea id="json" style="width: 100%;min-height:300px;">

</textarea>
<button onclick="$('#output').html(json_tree(JSON.parse($('#json').val())));">Build Tree</button>

This is what I get:
Image
I need help "filltering" (or merge with upper node) those "0" and "1", and also - how to show only values of the attributes without the names (or if do you have some better idea how can I
dusplay this list)?
Comment: Please don't use image, but write the example code (a piece) in the question.
Comment: I don't know if it helps, but I'd use your browser's debugger and inspector to look at those object string representations and see what methods/properties are available for showing them more prettily.
Comment: To add to existing answers, and if jQuery is acceptable, i found the following to have comparably good design and features:  https://github.com/abodelot/jquery.json-viewer
Answer: a good-looking, compact, collapsible tree view
pgrabovets' json-view is amazingly clean and well designed.
Check out the demo
Answer: If you can consider using JS libraries , consider using JSON Formatter or Render JSON.
Both these libraries offer configuration options like themes, maximum depth and sorting.
To display simple JSON string in a collapsible form using Render JSON, you can use

Comment: the render json one works beautifully! thanks for this answer!!. for anyone looking for the script tag to add the script directly from github :
Answer: Some of the links to the questions are no longer accessible. I assume you are looking for how to make a collapsible JSON view.

TL;DR
you can jump to Full code.
the code is very short (200 lines↓, including JSDoc, comment, test code.)
Inspire you on how to solve the problem.
This question in some skill is very much like how to make the table of contents. (TOC)

First of all, JSON data is like an object. All we need to do is to add some more attributes (key, depth, children, ...)  for each item.

Once these actions are done, all left is to render, and here is the pseudo-code for rendering.
render(node) {
  const divFlag = document.createRange().createContextualFragment(`<div style="margin-left:${node.depth * 18}px"></div>`)
  const divElem = divFlag.querySelector("div")
  const spanFlag = document.createRange().createContextualFragment(
    `<span class="ms-2">${node.key} : ${node.value}</span>`
  )
  node.children.forEach(subNode => {
    const subElem = render(subNode)
    spanFlag.append(subElem)
  })
  divElem.append(spanFlag)
  return divElem
}

Full code
both CSS is not necessary.

bootstrap: ms-2 (margin start)
fontawesome: fa-caret-right, fa-caret-down if you don't want to use it, you can use ▸(25B8)▶(25B6)▾(25BE)▼(25BC) as the before contents

<link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossOrigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"
      integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ=="
      crossOrigin="anonymous" referrerpolicy="no-referrer"/>

vanilla JavaScript
Comment: Cool, thanks for sharing stuff. Little addition. When a value is null it throwing exception. So it may be added after `switch (typeName)` - `if(node.value) ...`
Answer: I used Carson Reply And it Work Like charm but null object problem as woto says.
change in script.
const getValue = (node) => {
        const typeName = node.type
        switch (typeName) {
          case "object":
            if (node.value !== null)
                return `object {${Object.keys(node.value).length}}`
            else
                return 'null'
          case "array":
            if (node.value !== null)
                return `array {${Object.keys(node.value).length}}`
            else
                return 'null'
          default:
            if (node.value !== null)
                return node.value
            else
                return 'null'
        }
      }

Comment: Also change out the line with 'arrowIcon' to prevent unwanted arrows appearing: ```const arrowIcon = ["object", "array"].includes(node.type) ? node.value !== null ? `` : "" : ""```


How to get the Mean squared error of LassoLarsIC?

Question: lassoLarsIC give a predict methods but it does not give a MSE method, can someone specify the reason why it is not considered by SKlearn  ?
Using both the AIC and BIC method I was able to get the predictions , however I was trying to understand which method is giving the  Least mean squared error or how to understand which algorithm I need to use .
<code>import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LassoCV, LassoLarsCV, LassoLarsIC
from sklearn import datasets

diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target

model_bic = LassoLarsIC(criterion='bic')
model_bic.fit(X, y)
alpha_bic_ = model_bic.alpha_

# The coefficients / Intercept
print('Coefficients: \n', model_bic.coef_)
print('Intercept: \n', model_bic.intercept_ )

# Make predictions using the testing set
diabetes_y_pred = model_bic.predict(X)
print ("predict",diabetes_y_pred)
print (diabetes_y_pred.shape,type(diabetes_y_pred))
</code>
Comment: Barely qualifies as a question, please provide much more information.
Comment: Sure , I am adding more details to the thread.
Answer: Basically reading this article I got the answer.
As you know, AIC and BIC are both penalized-likelihood criteria. They are sometimes used for choosing best predictor subsets in regression and often used for comparing nonnested models, which ordinary statistical tests cannot do. The AIC or BIC for a model is usually written in the form [-2logL + kp], where L is the likelihood function, p is the number of parameters in the model, and k is 2 for AIC and log(n) for BIC.
AIC is an estimate of a constant plus the relative distance between the unknown true likelihood function of the data and the fitted likelihood function of the model, so that a lower AIC means a model is considered to be closer to the truth. BIC is an estimate of a function of the posterior probability of a model being true, under a certain Bayesian setup, so that a lower BIC means that a model is considered to be more likely to be the true model. Both criteria are based on various assumptions and asymptotic approximations. Each, despite its heuristic usefulness, has therefore been criticized as having questionable validity for real world data. But despite various subtle theoretical differences, their only difference in practice is the size of the penalty; BIC penalizes model complexity more heavily. The only way they should disagree is when AIC chooses a larger model than BIC.
AIC and BIC are both approximately correct according to a different goal and a different set of asymptotic assumptions. Both sets of assumptions have been criticized as unrealistic. Understanding the difference in their practical behavior is easiest if we consider the simple case of comparing two nested models. In such a case, several authors have pointed out that IC's become equivalent to likelihood ratio tests with different alpha levels. Checking a chi-squared table, we see that AIC becomes like a significance test at alpha=.16, and BIC becomes like a significance test with alpha depending on sample size, e.g., .13 for n = 10, .032 for n = 100, .0086 for n = 1000, .0024 for n = 10000. Remember that power for any given alpha is increasing in n. Thus, AIC always has a chance of choosing too big a model, regardless of n. BIC has very little chance of choosing too big a model if n is sufficient, but it has a larger chance than AIC, for any given n, of choosing too small a model.
So what's the bottom line? In general, it might be best to use AIC and BIC together in model selection. For example, in selecting the number of latent classes in a model, if BIC points to a three-class model and AIC points to a five-class model, it makes sense to select from models with 3, 4 and 5 latent classes. AIC is better in situations when a false negative finding would be considered more misleading than a false positive, and BIC is better in situations where a false positive is as misleading as, or more misleading than, a false negative.
AIC vs. BIC


Any Tutorials for Win32 SDK Programming?

Question: What are some good websites for Win32 SDK programming tutorials?
Answer: The generally accepted bible for Win32 is the Petzold book:
http://www.amazon.com/Programming-Windows%C2%AE-Fifth-Microsoft/dp/157231995X
It's not online, but worth purchasing if you're serious about Win32, IMHO.
Comment: Note that Mr. Petzold has released a 6th edition, but the 6th edition has removed the content related to Win32.  (Win32 hasn't changed, anyway) So, you'll need to get a hold of the 5th edition, NOT the 6th edition.
Comment: In my experience most of the MSDN docs assume you've read Petzold already, even for .NET framework. For example, a lot of the documentation on threads in .NET assumes you understand how they worked in Win32; without Petzold, I would have been utterly lost. If you look around, you can get used copies really cheap.  And he's a great writer.
Answer: The best online tutorial with regards to native Win32 programming would have to be The Forger's Win32 API tutorial.
Answer: This is my favorite: Win32 Programming by Rector & Newcomer It is massive and goes through all the basic concepts down to the nuts and bolts about Win32 programming.
BTW: Newcomer has a website also with examples (although more related to MFC) here
Answer: Absolutely Programming Windows, 5th edition by Charles Petzold.
Answer: If you really need a simple starter that will guide you through the basics. You can read "Windows Programming from the Ground Up" by Herbert Schildt. It will be a good forerunner to Charles Petzold. I read Herb Schildt first and then Charles Petzold, and I really was able to understand what Petzold was talking very easily.
Comment: While old, stuff like this:  has made at least me very weary of Schildt. Just thought I'd mention it.
Answer: Yes, Petzold book (98), Richter book (4), Win32 group for undocumented apis and Windows source code (wine, etc), and Russinovich book also..
Answer: Autohotkey source code: http://www.autohotkey.com/download/
Answer: Avoid tutorials (by kids for kids)
Read the Petzold + Richter + Adv. Win32 Group (news://nntp.aioe.org/comp.os.ms-windows.programmer.win32)
And avoid Newcomer (newbie in Win32, knows MFC only...)
Comment: Domi, you've got a serious attitude problem.  Are you going to answer everyone's questions like this?
Answer: You can find all the references and getting started tutorials for Win32 SDK programming at MSDN.
Comment: A more direct link:
http://msdn.microsoft.com/en-us/library/windows/desktop/ff381399.aspx


Replicate nt:unstructured nodes in AEM

Question: I am storing a quite a lot of metadata in the JCR which is accessed via OSGi services from Sightly pages and when rendering adaptive forms. The metadata are all stored in a tree of nt:unstructured nodes on the publish instance.
Ideally I'd like to reverse-replicate these nodes to my author on a continuous basis, and then potentially use tree-activation to push from the author back to publish.
The problem is this: It seems that AEM's replication capability does NOT pick up nt:unstructured nodes. I assume this is by design, but I'd like to confirm.
Also, what would be an appropriate work-around? Should I change my nt:unstructured nodes to cq:Page nodes? That feels wrong.
Comment: You could try to introduce your own node type, similar to `cq:Page` or `cq:Component`. I am not aware of all the restrictions of the product's replication service, but checking out the service's configurations in Felix might be a good idea as well. Perhaps it is configurable what can be replicated an what not.
Comment: I've confirmed that the replication OSGi service does allow replication of nt:unstructured nodes, but unfortunately there are some further complications :)
Answer: Just to close this out:
The com.day.cq.replication.Replicator package contains an OSGi component called Replicator.
By using this component, you can replicate nt:unstructured nodes as well with a call like:
<code>replicator.replicate(session,ReplicationActionType.ACTIVATE, nodePath);
</code>

Replicate nt:unstructured nodes in AEM


Prove using mathematical induction that $n^2 > n+1$ for all $n \ge 2$

Question: I have proved for the initial case $P(2)$ that this is true, but I'm stuck at substituting in $n=k+1$, $(k+1)^2 > (k+1)+1$ = $k^2 + 2k + 1 > k+2$, where do I go from here or have I made a mistake?
Thanks guys :)
Comment: Advice for the future: do _not_ use the equals sign ($=$) to indicate that two statements are equivalent. You inadvertently wrote in your question that $(k+1)+1 = k^2 + 2k + 1$ (which I know you did not mean--but it came out looking that way nevertheless). You can use $\iff$ to indicate equivalence; in cases like this it may be even better to just use words.
Comment: also apologies about the greater than or equal to sign, not sure how to do that yet, I'm new, if someone could fix that it would be appreciated.
Comment: We have $k\ge 2$ and $k^2+2k+1=k(k+2)+1$... Can you continue?
Comment: @AidanLeith Here is a tutorial of MathJax: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: @abiessu I don't understand how you can get $k(k+2)+1 > k+2$, we were only really taught induction for equalities.
Comment: Note $k(k+2)\ge k+2$ whenever $k\ge 1$...
Answer: Assume that $k^2>k+1$. Then
$(k+1)^2=k^2+2k+1>k+1+2k+1=3k+2>k+2,$ because $k>0$.
Comment: This is correct. On pretty much every induction question, you need to utilize the assumption for P(k).
Comment: @AidanLeith $k^2+2k+1>k+1+2k+1$, because $k^2>k+1$ by an inductive assumption. $3k+2>k+2$, because $k\ge 2>0$.
Comment: Could you just show more steps on how you got to each point?
Comment: @AlexRavsky but how did you get the LHS to equal $3k+2$.
Comment: @AidanLeith Which expression you mean by LHS?
Comment: @AlexRavsky Left Hand Side
Comment: @AidanLeith Which Left Hand Side, $k+1+2k+1$ or $k^2+2k+1$?


Counting form fields using js

Question: I have the form that looks like this:
<form method="post" action="">
   Count:
   <input id="id_count-count" type="number" name="count-count">

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

Depending on number of field count i add or delete new couple of fields item and item2. For example: if value of field count will be 2, it will generate two couples of fields item and item2.
There is this fields:
Item:
<input id="id_items-0-item" type="number" name="items-0-item">
Item2:
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="0">

Then, depending on each value of field item2 i add new fields that calls childrenage. There is how looks childrenage field:
ChildrenAge 1
<input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">

Here is fiddle link .
And here is imgur of what i want and what i've got link.
Depending of value of item2 the id of childrenage is changing too. For example if i have '3' as value of item2, then i have id_childrenage-0-childrenage, id_childrenage-1-childrenage and id_childrenage-2-childrenage. And if i have several item2 i have new examples of childrenage that count their id from the start for each item2:
Item2:
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="2">

   ChildrenAge
   <input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
   ChildrenAge
   <input id="id_childrenage-1-childrenage" type="number" name="childrenage-1-childrenage" value="0">

Item2:
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="1">

   ChildrenAge
   <input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">

In example above i have 2 fields item2, on one of it value '2' and on another value '1'. According to this i have two fields of childrenage for the first item2 with id id_childrenage-0-childrenage and id_childrenage-1-childrenage, and one field childrenage for the second with id id_childrenage-0-childrenage. But i need that count of id childrenage go on from the first item2 to the last, this is example:
Item2:
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="2">

   ChildrenAge
   <input id="id_childrenage-0-childrenage" type="number" name="childrenage-0-childrenage" value="0">
   ChildrenAge
   <input id="id_childrenage-1-childrenage" type="number" name="childrenage-1-childrenage" value="0">

Item2:
<input id="id_items-0-item2" class="children_age" type="number" name="items-0-item2" value="1">

   ChildrenAge
   <input id="id_childrenage-2-childrenage" type="number" name="childrenage-2-childrenage" value="0">

Here is js code that realize this:
$(function(){
   $('#id_count-count').on('change', function(e){
      var n = $('#id_count-count').val() || 0;
      var html = "<input id='id_items-TOTAL_FORMS' type='hidden' value='" + n + "' name='items-TOTAL_FORMS'>"
         + "<input id='id_items-INITIAL_FORMS' type='hidden' value='0' name='items-INITIAL_FORMS'>"
         + "<input id='id_items-MIN_NUM_FORMS' type='hidden' value='0' name='items-MIN_NUM_FORMS'>"
         + "<input id='id_items-MAX_NUM_FORMS' type='hidden' value='15' name='items-MAX_NUM_FORMS'>";

      for (var i = 0; i < n; i++) {
         html += "
Items" + (i + 1) + "
"
            + "
Item:"
            + "<input id='id_items-" + i + "-item' type='number' name='items-" + i + "-item'/>"
            + "Item2:"
            + "<input id='id_items-" + i + "-item2' type='number' value='0' name='items-" + i + "-item2' class='children_age'/>"
            + "

";
      }
      $(".extrafieldWrapper").html(html);
   });
   $(".extrafieldWrapper").on('change', '.children_age', function(e){
      var n = $(this).val() || 0;
      var html = "<input id='id_childrenage-TOTAL_FORMS' type='hidden' value='" + n + "' name='childrenage-TOTAL_FORMS'>"
         + "<input id='id_childrenage-INITIAL_FORMS' type='hidden' value='0' name='childrenage-INITIAL_FORMS'>"
         + "<input id='id_childrenage-MIN_NUM_FORMS' type='hidden' value='0' name='childrenage-MIN_NUM_FORMS'>"
         + "<input id='id_childrenage-MAX_NUM_FORMS' type='hidden' value='15' name='childrenage-MAX_NUM_FORMS'>";

      for (var i = 0; i < n; i++) {
         html += "
ChildrenAge "+(i+1)+""
            + "<input id='id_childrenage-" + i + "-childrenage' type='number' value='0' name='childrenage-" + i + "-childrenage' />";
      }
      $(this).next('.extrafieldWrapperChAge').html(html);
   });

});

Hope you you understand what i mean.
I am newbie in java-script, can you help me to write the code in the right way. Thanks a lot!
Comment: I'm already edit the post and add JsFiddle. Sorry, but i don't know how to do text smaller.
Comment: This is simply my personal opinion but *holy crap* that is a lot of text. Let's see if we can clarify a few things: **1** what do you start with? **2** given very explicit instructions, what do you end up with? **3** could you *possibly* add your code to the snippet editor, JsFiddle, or Codepen with a working example of what you've got?
Comment: so what is your end goal -- what goal are you looking to accomplish here
Comment: A add new imgur link of what i have and what  need, it is a simple example.
Comment: Okay. I think I have a bit more of an idea as to what you want in particular. Give me a minute. I'm going to attempt to clean up your code (It's a little messy for my tastes and it is making it hard to read)
Comment: Thank you, @Jhecht
Answer: This particular answer was getting needlessly long, so I've decided to truncate it to just the current answer.
The Code

$(function() {
  var fieldset = $('<fieldset>');
  var legend = $('<legend>');
  var input = $('<input>').prop('type', 'number');
  var hidden = $('<input>').prop('type', 'hidden');
  var label = $('');
  var child_wrapper = $('
');
  /*
    Here we create a couple of new HTML elements. These elements are not a part of the
    HTML DOM yet and can therefore be manipulated without any visual changes.
  */
  var create_hidden_fields = function(str, fields_arr) {
    var ret = [];
    //return array;
    $.each(fields_arr, function(i, obj) {
      //Loops through each field to set up the hidden values
      var h = hidden.clone();
      //Clones the hidden fields
      h.prop('id', 'id_' + str + '-' + obj.name).prop('name', str + '-' + obj.name).val(obj.value);
      //Sets the ID, name, and value.
      ret.push(h);
    });
    return ret;
  };

  $('#id_count-count').on('change', function(e) {
    var n = $(this).val() || 0;
    //Gets the id count value, or 0;

    var hidden_fields = [{
      name: 'TOTAL_FORMS',
      value: n
    }, {
      name: 'INITIAL_FORMS',
      value: 0
    }, {
      name: 'MIN_NUM_FORMS',
      value: 0
    }, {
      name: 'MAX_NUM_FORMS',
      value: 15
    }];
    //Hidden fields pre-build, makes life easier, since there seems to be a pattern

    var h_arr = create_hidden_fields('items', hidden_fields);
    //Hidden Array created
    if ($(this.form).children(':hidden')) {
      $(this.form).children(':hidden').remove();
      //Removes all the current hidden fields, because lazy.
    }
    $(this.form).prepend(h_arr); //adds in our created hidden fields.

    var form = $(this.form).children('.extra-field-wrapper');
    //Gets the fieldset wrapper.
    form.empty();
    //Empties any children there already. Otherwise extra children are added.

    for (var i = 0; i < n; i++) {
      var fs_clone = fieldset.clone(); //clones the fieldset element
      var l_clone = legend.clone().text("Item " + (i + 1));
      // clones the legend element and adds text
      var la_clone_1 = label.clone();
      //label clone 1
      var input_clone_1 = input.clone();
      //Input clone 1
      var child_wrapper_clone = child_wrapper.clone().prop('id', 'parent-' + (1 + i));
      //We use clones to keep our initial values safe. This way we can alter the clones without changing our defaults

      fs_clone.append(l_clone);
      //Adds our legend up top for readability;
      la_clone_1.prop('for', 'id-items-' + i + '-item').html('Parent ' + (i + 1));
      //Adds the 'for' property with the correct ID, then sets the HTML. Item and Item2 were getting confusing
      input_clone_1.prop('value', 0).prop('id', 'id-items-' + i + '-item');
      //Sets the default value to 0, and the necessary ID for our label to work
      var la_clone_2 = label.clone().html('# of Children').prop('for', 'id-items-' + i + '-num-children');
      /*
       This is a lot in one line, it clones the label element, adds the HTML, and sets the property all in one.
      */
      var input_clone_2 = input.clone().prop('id', 'id-items-' + i + '-num-children').prop('value', 0).addClass('children_age');
      //See above comment. One difference is that this adds our class for our next function to work

      fs_clone.append([la_clone_1, input_clone_1, la_clone_2, input_clone_2, child_wrapper_clone]);
      //This could probably be cleaned up, but for now it works.

      form.append(fs_clone); //adds the fieldset clone to the form.
    } //End for

  });

  $(".extra-field-wrapper").on('change', '.children_age', function(e) {

    var n = $(this).val() || 0;
    // the current value of the item
    var append_array = [];
    //Add an HTML append array, lessens calls to the $(this).next().append();

    $(this).before(h_arr);
    //Adds the hidden elements before this element

    $(this).next('.child-wrapper').empty();
    //Clears the child elements

    for (var i = 0; i < n; i++) {
      var l_clone = label.clone().html('Children Age' + (i + 1));
      var i_clone = input.clone().addClass('child-age').prop('value', 0);

      append_array.push(l_clone);
      append_array.push(i_clone);
      //Adds the elements to the append_array since we are now done with them.
    }

    $(this).next('.child-wrapper').append(append_array);
    //Adds all created elements;

    var children_age = $('input.child-age').each(function(i, el) {
      var self = $(el);
      //Lazy handle
      var label = $(el).prev();
      //The label is the element in front of our current element.
      label.text("Child Age " + (i + 1)).prop('for', 'id_childrenage_' + i + '_childrenage');
      //Gives correct label number /re does the for property;
      self.prop('id', 'id_childrenage_' + i + '_childrenage');
      //give correct id now that changes have been made to the dom.
    });

    var hidden_fields = [{
      name: 'TOTAL_FORMS',
      value: children_age.length
    }, {
      name: 'INITIAL_FORMS',
      value: 0
    }, {
      name: 'MIN_NUM_FORMS',
      value: 0
    }, {
      name: 'MAX_NUM_FORMS',
      value: 15
    }];
    //We have to redeclare this function here in order for the value: n  to work correctly.
    if ($('#id_childrenage-TOTAL_FORMS').length == 0) {
      //This element does not exist yet in the DOM
      var hidden_fields = [{
        name: 'TOTAL_FORMS',
        value: children_age.length
      }, {
        name: 'INITIAL_FORMS',
        value: 0
      }, {
        name: 'MIN_NUM_FORMS',
        value: 0
      }, {
        name: 'MAX_NUM_FORMS',
        value: 15
      }];
      //We have to redeclare this function here in order for the value: n  to work correctly.

      var h_arr = create_hidden_fields('childrenage', hidden_fields);
      //creates the hidden fields
      $(this.form).prepend(h_arr);
    } else {
      $('#id_childrenage-TOTAL_FORMS').val(children_age.length);
    }

  });

});
label {
  font-weight: 800;
}
input[type="number"] {
  width: 50px;
}

<form method="post" action="">
  Count:
  <input id="id_count-count" type="number" name="count-count">

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

The Explanation
I did a few things here, and there is more than likely a better way, but I did the best with my own time constraints.

I create the items to copy into the with jQuery because I'm old school and I just do not remember anything about how the template tag works so I stay away from it's particular variety of magics. The fieldset and legend are there solely for readability. In your actual code you can just delete their references as well as fs_clone and l_clone, instead attach the items directly to the form element.
I created a function that exists solely within the realm of our wrapping anonymous function called create_hidden_fields, as a programmer, mathematician, and all around lazy person I noticed the pattern in the naming convention and this appealed to me more than having to create and copy a bunch of items by hand every time I wanted to create a field.
I have the id_childrenage-TOTAL_FORMS (which is, by the way, the weirdest naming convention I've ever come across) to the form itself. Since we don't need more than 1 copy of the input.
The reason the hidden_fields array is redeclared in both functions is fairly simple: if it is declared before the variable n is, the TOTAL_FORMS input won't have the correct value. Not good.
Hopefully everything else can be answered by my comments in the code itself.

Happy Coding.
Comment: Thank you very @Jhecht it works very fine! I'm very Thakfull to you!
Comment: Thank you very much for your answer, it works very fine! But I have two remarks, I need to count `id-items-n-item`, `id-items-n-num-children` and `id_childrenage_n_childrenage` from '0'. And second i need to have `` where `n` is number of filled forms(parents and children), and , where n is number of filled childrenage fields. Its for my django framework. Sory for my pure js. And thank you once again
Comment: I've never used Django, but I must say that seems like a real pain to have to do that.
Comment: I've made an edit @ZagorodniyOlexiy, let me know if that helps you out. I'd be lying if I said I totally understood what all of this was for.
Comment: i'm sorry that disturbing you. But i found the bug can you help me with it? `` need to count how many couples of Parent and Children(only couples! without `childrenage`), and `` needs to count a sum of all Childrenage fields. Sorry very much! And thak you once again
Comment: So, the `id_items-TOTAL_FORMS` needs to count how many *couples* of parent and children? So the two forms that get populated originally, before we've added the children age form elements?
Comment: Yes. `id_items-TOTAL_FORMS` need to count just couples of parent and children. Like on this example https://jsfiddle.net/79gt20q3/3/ . Thank you very much
Comment: and is `id_childrenage-TOTAL_FORMS` supposed to give you the ***total*** amount of children age inputs, or just the ones for that ***specific*** wrapper?
Comment: just to confirm, in [this image](http://imgur.com/hpqZkVB), would `id_items-TOTAL_FORMS` be 3 or 6? and would `id_childrenage-TOTAL_COUNT` be 10?
Comment: yes, `id_items-TOTAL_FORMS` = 3, `id_childrenage-TOTAL_FORMS` = 10
Comment: Okay. Give me a second.
Comment: Yessss! It works! Thank you very much! If you will need help in django i will be glad to help you! Thanks once again!

Counting form fields using js


Is sign function continuous in complex plane?

Question: Is sign function continuous in the complex plane? Is it continuous everywhere except at $z = 0$ ? Is it continuous in a circle of unit radius and argument having $\exp(-i\theta)$ ?
Comment: How do you define $sign(x + iy)$? Do you define it as $sign(x)$?
Comment: You can define is as sgn(z) = |z|/z
Answer: $\frac{|z|}{z}$ is continuous in $\mathbb{C} \setminus \{0\}$ as it is the quotient of continuous functions. However, $\frac{|z|}{z}$ is obviously not defined in $z = 0$ (hence not continuous there either).
By the way, it is more common to use $\frac{z}{|z|}$ instead of $\frac{|z|}{z}$ because then you have $z = |z| \cdot \frac{z}{|z|}$ just like for the reals.
Comment: I don't think this is what you are saying, but I thought it was at first, so to avoid confusion: $\frac{|z|}{z} \neq \frac{z}{|z|}$.  For example $\frac{i}{|i|} = i \neq -i = \frac{|i|}{i}$
Comment: @Callus Thanks, I improved the wording.


why two keywords in c#: String and string

Question:
Possible Duplicate:
String vs string in C#

I see there are 2 different keywords (classes ?) one which starts with capital S and other with small in c#.
String and string
What is the reason ? is one not sufficient ?
Comment: 11 years later and still looking for the WHY part of this question
Answer: string is a C# language alias for the actual class System.String.
You can safely use either. I've seen most people prefer string. If I'm working on an API I'll typically use System.String instead although both are safe.
There's plenty of other aliases, too. For example int is an alias for System.Int32, bool for System.Boolean. The string example just happens to be a casing difference so this question comes up a lot.
Comment: @Antony Scott: Like BoltClock said, there aren't two. One is just an alias. `string` just refers to the `String` class definition in the BCL.
Comment: Same as int/Int32, bool/Boolean, double/Double etc.  Many common types are aliased to more familiar (C/C++) keywords.
Answer: string is a keyword and alias of System.String class, System.String is a class. Also there's more aliases than string:
object: System.Object
string: System.String
bool: System.Boolean
byte: System.Byte
sbyte: System.SByte
short: System.Int16
ushort: System.UInt16
int: System.Int32
uint: System.UInt32
long: System.Int64
ulong: System.UInt64
float: System.Single
double: System.Double
decimal: System.Decimal
char: System.Char

The best answer comes from Jeffrey Richter in his book CLR Via C#. Here are his 3 reasons:

I've seen a number of developers confused, not knowing whether to
  use    string or String in their code. Because in C# the string (a
  keyword)    maps exactly to System.String (an FCL type), there is no
  difference    and either can be used.
In C#, long maps to System.Int64, but in a different programming
  language, long could map to an Int16 or Int32. In fact, C++/CLI does
  in fact treat long as an Int32. Someone reading source code in one
  language could easily misinterpret the code's intention if he or she
  were used to programming in a different programming language. In fact,
  most languages won't even treat long as a keyword and won't compile
  code that uses it.
The FCL has many methods that have type names as part of their
  method    names. For example, the BinaryReader type offers methods
  such as    ReadBoolean, ReadInt32, ReadSingle, and so on, and the
  System.Convert    type offers methods such as ToBoolean, ToInt32,
  ToSingle, and so on.
Answer: Actually, there is only one keyword for string (all C# keywords are lowercase).  They mean the same thing.  They are only interchangeable, though, if you have a using System; import.
Answer: String is the actual class you are using. It is just another class, nothing more. However, since strings are so vital in programming, Microsoft decided to bake them into the language by creating a keyword string that was just an alias for System.String. There is no such thing as an instance of string because it is not a class.
This gave strings elevated status and made them a lot easier to find (imagine trying to write a hello world style programming and have to actually look around and find the String class...) :D


iterar valores em $.each aninhado Jquery

Question: Estou recebendo uma tabela completa do meu server side, procuro por td com uma informação que quero e salvo essa tr inteira em uma variável como abaixo:
var rowVoo;

$(table).find("tr td").each(function () {
      if ($.trim($(this).text()) == "Porto Velho - RO") {
           rowVoo = $(this).closest("tr");
      }
});

A variável rowVoo fica como fica como abaixo:

    Porto Velho - RO
    11
    1 ( 9.1 %)
    0 ( 0 %)
    0 ( 0 %)

Tenho uma lista como abixo:

 VOOS PREVISTOS

 ATRASADOS AGORA

 VOOS CANCELADOS

 ATRASADOS NO DIA

Preciso passar os valores que estão dentro dos td para os span que estão dentro da lista.
Procuro pelos span que estão dentro da list:
var list = $(".list-voos").find("li").find("span");

E tento iterar os valores:
$(rowVoo).find("td").each(function () {
     var that = $(this);
     $(list).each(function () {
         console.log($(this).text(that.text()));
         return null;
     });
});

Porém os valores são duplicados e os span da list sempre ficam com o último valor da td
Answer: Tens de usar o index que a função .each() passa/disponibiliza.
Testa assim:
var lis = $('ul.list-voos li');
$(rowVoo).find("td").each(function (i) {
     $(lis).find('span').eq(i).html(this.innerHTML);
});

function (index, value){

O método each permite uma função que te dá duas variáveis. A primeira é o indice do elemento na coleção, o segundo é o proprio elemento da coleção. No caso do jQuery, é o mesmo valor do this dentro dessa função.
Exemplo: http://jsfiddle.net/CrXD4/2/
Comment: Obrigado, funcionou perfeitamente!
Answer: maior desempenho[atualizado]:
var i, e, tableTeste = $("table").find("tr td"),
  ulLi = $(".list-voos").find("li span");

for (var i = 0, e = tableTeste.length; i < e; i++) {
  var tdValue = tableTeste[i].innerHTML;

  ulLi.eq(i).html(tdValue);

}

antes:
var i, e, tableTeste = $("table").find("tr td"),
  ulLi = $(".list-voos").find("li span");

for (var i = 0, e = tableTeste.length; i < e; i++) {
  var tdValue = tableTeste.eq(i).html();
  ulLi.eq(i).html(tdValue);

}

veja a comparação usando each(), for(){} e for(){} com innerHTML: http://jsperf.com/test-each-for-each/2