Data simulation in R for Measurement invariance

Question: I am trying to generate random data for an analysis of Measurement invariance. I will be looking at a one-factor model for two groups with 4 variables each.
I would need to generate a sample where I can control several parameters:

Sample size
number of categories (I will be using categorical variables)
distribution of answers (skewness, kurtosis)
Factor loadings and intercepts/thresholds (To induce measurement noninvariance)

While I can generate data based on the first three conditions I am struggling to find a way to control the fourth. So far, I have only found resources in Mplus that would cover this type of simulation or descriptive mentions in papers such as:

Measurement noninvariance was simulated by creating group differences in the factor loadings for some observed indicators. For the invariance condition, the difference in factor loadings between the groups was 0 (complete invariance). For the noninvariant cases, loadings were simulated to differ by 0.1, 0.2, 0.3, 0.4, or 0.5. The percent of indicators allowed to be noninvariant was 0, 10, 20, or 30%. As an example of how noninvariance was simulated, in the 10 indicators, 10% noninvariant, 0.1 noninvariance magnitude condition, the factor loading for indicator 2 was set to 0.9 in one group, and kept at 1.0 in the other group.
https://doi.org/10.1007/978-3-030-01310-3_21

I would be happy with any resources or even keywords that would guide me towards a better understanding of such simulations and how to practically implement them in R.
Answer: Simulating data with measurement invariance is easy with the lavaan package. See the R code below. To simulate measurement invariance, I simply specify two separate population models. Loadings for items 1-3 are the same in both population models. However, the loading for item 4 is different (0.5 for group 1 and 0.4 for group 2).
# Packages
library(lavaan)

# specify population model for group 1 and group 2
population_model_g1 <-'f1=~x1+.6*x2+.7*x3+0.5*x4'
population_model_g2 <-'f1=~x1+.6*x2+.7*x3+0.4*x4'

# Sumulate data
set.seed(1234)
model_data_g1<-lavaan::simulateData(population_model_g1,sample.nobs=500)
model_data_g2<-lavaan::simulateData(population_model_g2,sample.nobs=500)

# Add group label
model_data_g1$group <- "Group1"
model_data_g2$group <- "Group2"

# put data into one data frame
model_data_all <- cbind(model_data_g1,model_data_g2)

Finally, regarding resources, I recommend reading past simulation studies. Many of the more recent simulation studies will have code available online (e.g., Debelak et al., 2023 uploaded their code on OSF). Reading these studies will also help you better understand simulation studies as the rationale behind their design is often subtle, and not immediately apparent unless you have a strong understanding of the method(s) being evaluated.
References
Debelak, R., Appelbaum, S., Debeer, D., & Tomasik, M. J. (2023). Detecting Differential Item Functioning in 2PL Multistage Assessments. Psych, 5(2), 461-477.
Comment: This is perfect, thank you. I did not know Lavaan has a data simulation function and this is exactly what I was looking for.  I will have to read up on how to properly specify a model and figure out how to create discrete variables from the simulated data, but it is a great start.
Answer: You could also use the simDAG package. It allows you to define a directed acyclic graph with a possible mix of discrete / continuous / count variables and how they are related. See https://robindenz1.github.io/simDAG/


Register Assembly em asp.net MVC?

Question: Como usar o Register Assembly em asp.net mvc ?
Preciso criar um formulário que esta usando um reportviewer no mvc, sendo que o mesmo já existe em webforms. Irei passá-lo para outro projeto.
Answer: Tem um pacote pra isso, o ReportViewer por MVC.
Você pode instalar ele facilmente na sua solução ASP.NET MVC usando o seguinte comando no Package Manager Console (View > Other Windows > Package Manager Console) do Visual Studio:
<code>PM> Install-Package ReportViewerForMvc
</code>
Comment: Valeu @Cigano Morrison Mendez
Comment: como chamo o ReportViewer em uma página cshtml ?
Comment: O certo é chamar pelo *Controller*. [Veja este exemplo](https://reportviewerformvc.codeplex.com/wikipage?title=Getting%20Started).

Register Assembly em asp.net MVC?


Pegar o max value dentro de um while que está dentro de um cursor

Question: Minha duvida é a seguinte: tenho meu cursor para a interação linha a linha e dentro dele tenho um while para interação horizontal. Estou tentando popular uma tabela cuja PK não possui identity, usando o MAX e setando o valor +1 dentro do while, contudo está estourando erro afirmando que o valor inserido já existe na tabela.
DECLARE @RANGE_DE   INT,
            @RANGE_ATE  INT
    declare @MaxId int;
    declare @teste int;
    DECLARE C_REGISTROS CURSOR FOR
        SELECT
            RANGE_DE,
            RANGE_ATE
        FROM
            #TEMPPARAMETROS

        OPEN C_REGISTROS
        FETCH NEXT FROM C_REGISTROS INTO @RANGE_DE, @RANGE_ATE

        WHILE (@@FETCH_STATUS = 0)
        BEGIN
        set @teste = (select max(nroproposta) from propadesao);
        set @MaxId = (SELECT MAX(IdPropAdesao) FROM PROPADESAO);
                    while (@RANGE_DE <= @RANGE_ATE)
                    begin
                    INSERT INTO
                    PROPADESAO
                     (
                          IdPropAdesao
                         ,IdTpProduto
                         ,IdUnidade
                         ,DtStatus
                         ,IdCorretor
                         ,NroProposta
                         ,StatusAtual
                         ,IdMatDivulga
                     )
                    SELECT
                         @MaxId
                         ,IdTpProduto
                         ,1
                         ,GETDATE()
                         ,IDCORRETOR
                         ,@teste
                         ,CASE
                            WHEN IDCORRETOR is null THEN 2
                            WHEN IDCORRETOR IS NOT NULL THEN 3
                          END
                         ,idcontrato
                    FROM
                         #TEMPPARAMETROS

                        set @range_De += 1
                        SET @MaxId += 1
                        set @teste += 1
                    end
                FETCH NEXT FROM C_REGISTROS INTO @RANGE_DE, @RANGE_ATE
        END
    CLOSE C_REGISTROS
    DEALLOCATE C_REGISTROS

Segue o erro :
Msg 2627, Level 14, State 1, Line 21 Violation of PRIMARY KEY constraint 'PK_PropAdesao'. Cannot insert duplicate key in object 'dbo.PROPADESAO'. The duplicate key value is (5654054). The statement has been terminated. Msg 2627, Level 14, State 1, Line 21 Violation of PRIMARY KEY constraint 'PK_PropAdesao'. Cannot insert duplicate key in object 'dbo.PROPADESAO'. The duplicate key value is (5654055).

Comment: Olá! Bem-vindo ao SOpt! Poderia informar o erro completo?
Comment: Opa, obrigado meu querido!
Segue o erro :

Msg 2627, Level 14, State 1, Line 21
Violation of PRIMARY KEY constraint 'PK_PropAdesao'. Cannot insert duplicate key in object 'dbo.PROPADESAO'. The duplicate key value is (5654054).
The statement has been terminated.
Msg 2627, Level 14, State 1, Line 21
Violation of PRIMARY KEY constraint 'PK_PropAdesao'. Cannot insert duplicate key in object 'dbo.PROPADESAO'. The duplicate key value is (5654055).

E isso se repete por todas as interações do loop.
Comment: Opa! Edite sua pergunta e coloque o erro lá! Acrescente outras informações que achar pertinente e que nos possam te ajudar.
Answer: O problema está ocorrendo, pois é obtido o @MaxId da PROPADESAO e, sem incrementá-lo, é feito um INSERT na PROPADESAO. O incremento é feito só no final do loop. Como o INSERT é feito antes do final do loop, então o SQL Server levanta uma exception de chave primária duplicada.
Troque isso:
set @MaxId = (SELECT MAX(IdPropAdesao) FROM PROPADESAO);

Por isso:
set @MaxId = (SELECT MAX(IdPropAdesao) FROM PROPADESAO) + 1;

Faça o mesmo para o @teste:
set @teste = (select max(nroproposta) from propadesao) + 1;

Comment: essa interação já é feita nessas linhas :

SET MaxId += 1
SET teste += 1
Comment: sim, mas esses incrementos são feitos depois do primeiro Insert. Por isso dá a exceção. Você obtem o MAX e logo depois dá um INSERT, sem incrementar o valor obtido.
Comment: @A.M., você chegou a testar o que estou propondo nessa resposta?


What are the interesting models of this theory other than those of ZFC + (V=L)?

Question: Language: first order logic with equality, plus primitive binary relations: $=,\in, <$
Axioms:

Extensionality: $\forall z (z \in x \leftrightarrow z \in y) \to x=y$
Well ordering: $<$ is a well ordering on the universe
Membership: $x \in y \to x < y$
Replacement: if $\phi(x,y)$ is a formula in which $x,y$ are free that doesn't have the symbol $B$ free, then all closures of: $$ \forall A [\forall x < A \exists! y( \phi(x,y)) \to \\\exists B \forall y (y \in B \leftrightarrow \exists x < A: \phi(x,y))]$$; are axioms.
Infinity: $\exists x: \exists y (y < x) \land \forall y < x \exists z (y < z < x)$
Successor cardinals: $\forall x \exists y: |y| > |x|$

Where, well ordering is the schema:
$x < y \to y \not < x \\ x < y < z \to x < z \\ x \neq y \leftrightarrow [x < y \lor y < x] \\ \exists x \phi(x) \to \exists x \phi(x) \land \forall y (\phi(y) \to x \leq y)$
\theory definition finished.
Now my guess is that all models of $ZFC + (V=L)$ are models of this theory!
What are the examples of interesting models other than those of $ZFC+(V=L)$ can be models of this theory?
I've first posted this theory to Mathoverflow when I came to know that fine structural models can be an example of such models, but I transferred this topic here, because I think it is not research level question. Are there other known interesting models of this theory?
Comment: As was mentioned in the comments, any model of ZFC can be given a relation $<$ to turn it into the model of your theory. One interesting example is any model of V=HOD, since these have definable well-orderings.
Comment: Global choice is not a statement in first order language of set theory, so it doesn't make sense to ask if a model of ZFC satisfies global choice. However, given any model $(M,\in)$ of ZFC you can define a relation $<$ on $M$ such that $(M,\in,<)$ satisfies your theory.
Comment: @Zuhair Wojowu's right - the point is that we don't need $<$ to be definable here, and that opens the door for more general relations (which in fact every model of ZFC does wind up admitting).
Comment: @Wojowu, what does "give a relation to a model" mean here? There must exist models of ZFC in which global choice fail! Now for such a model how can I give a relation $<$ with above-mentioned axioms? Wouldn't that be inconsistent?
Answer: First, note that it's not quite right to say that all models of ZFC+V=L - or more generally, ZFC + "$V=HOD[x]$ for some $x$" - is a model of your theory; rather, any such model has a natural expansion to a model of your theory (the point is that we have to talk about expansions since the languages are different).
But "natural" expansions aren't the only kinds of expansions. Working in some $M\models$ ZFC, use the proper class forcing of partial well-orderings of set-sized fragments of the universe. The expansion $(M,\triangleleft)$ will satisfy your theory.
So your theory is conservative over ZFC in the strong sense that any model of ZFC can be expanded to a model of your theory. $V=HOD[x]$ comes in when we try to get a "natural expansion" - that is, where we want $\triangleleft$ to in fact be a class in the sense of $M$ - but isn't truly necessary.

Interestingly, replacement plays a crucial role here.


Grant permission to manage another users processes

Question: I have userA and userB who start processes:
userA@server:~$ ./some_command.sh &
[1] 30889

I then have a web app running as userC that manages those processes (suspending, resuming, terminating, and killing).
How can I give permission to userC to do this?
For security I want to avoid giving userC root privilege.
I have complete control over userC. One possibility is changing the user ID to same as userA, but then what about userB?
Update:
Process management is performed with a third party module so could not apply sudo without a significant rewrite.
Comment: what about SCREEN? http://library.linode.com/linux-tools/utilities/screen
Comment: how would screen apply to this case?
Answer: Having users share a uid is a very frowned upon practice.
Suggestions:

Look into the sudo command. This is the goto solution for "how do I run a command as another user": you specify entries in an /etc/sudoers file that indicate which users (or groups, etc.) are allowed to run commands as different users, and under what circumstances. Its configuration can also be placed into a LDAP directory.
If this is a production environment (or something that you plan to eventually place in a production environment), it's considered best practice for userA / userB to be an "application user". This is an account with a name that easily conveys its intended purpose (oracle, webapps, etc.) and not one that any user considers "their" personal account. Ideally no one should be able to log in as this user (i.e. disabled password), and if you wish for users to obtain shell access to that user it should be done via sudo abtraction. (i.e. a role that allows a user to execute sudo su - oracle to obtain an oracle shell) This forces users to log in as themselves before becoming the application user and leaves a better audit trail.
If neither of these solutions are feasible, you may want to go with @Hex's suggestion of using a terminal multiplexer like screen or tmux, though some abstraction between login and shared application accounts is still recommended. You should try to avoid this unless the processes have terminal interaction of some sort.
Comment: userA / userB / etc are real user accounts where terminal processes are started. Then the internal web app helps manage certain processes.
Comment: And the process management is performed by an existing third party library, so I don't see how sudo would be used.
Comment: Write a script/program that makes the library calls, then invoke it via sudo in order to have the correct effective UID at execution time. If this is not feasible, please update the question with more details. Avoiding the sudo abstraction would require it to be setuid root, which is generally asking for it.
Answer:
Setuid on the executables run by users A/B to user C.
?
Profit
Answer: I would suggest a combination of Monit and sudo for job control...
Monit would handle the start/stop/status of the app.
Sudo with Monit rights would give you the collaboration aspect.
See: allow a user to run specific monit action
Answer: Probably best to use a proxy process under userA/userB reading control files for each PID.
some_command.sh:
thecommand &
CTL=/var/run/%1.ctl
echo %1 > $CTL
while read -n 1 cmd; do
    case $cmd in
        k)
            kill %1
            exit $?
            ;;
        s)
            kill -TSTP %1
            ;;
        ...
done < $CTL

You could have the worker processes reading the control files... but then they wouldn't continue, would they.


Problema de impressão com C

Question: Bom dia. Estou com um problema pra solucionar um quesito de uma questão aqui da faculdade. Segue a questão.

O professor deu o código fonte (a seguir)
#include<stdio.h>
#include<stdlib.h>
#include <locale.h>
#define dimencao 10

typedef struct celula{
    int *endereco;
    int cont;
    int tam;
}Celula;

void menu();
void  verifica(int *espaco);
void liberarEspaco(Celula vetor[]);
void inicializa(Celula vetor[]);
void cria_vetor(Celula vetor[], int posicao);
void insere(Celula vetor[]);
void imprime(Celula vetor[]);
void imprimirIntercalado(Celula vetor[]);
int maiorTam(Celula vetor[]);

int main(){
    setlocale(LC_ALL, "Portuguese");
    Celula vetor[dimencao];
    int opcao;
    inicializa(vetor); // Inicializa todo o vetor com valor NULL
    menu();
    scanf("\n%d", &opcao);
    while(opcao != 0){
        system("PAUSE");
        system("cls");
            switch(opcao){
                case 1: insere(vetor); break;
                case 2: liberarEspaco(vetor); break;
                case 3: imprime(vetor); break;
                case 4: imprimirIntercalado(vetor);
                default: printf("\nValor inválido!\n"); break;
            }
        menu();
        scanf("\n%d", &opcao);
    }
    return 0;
}

void menu(){
    printf("********************* MENU *************************");
    printf("\n*\tDigite uma das opções abaixo:              *");
    printf("\n*\tDigite 1 para inserir elementos no vetor.  *");
    printf("\n*\tDigite 2 para liberação de espaço no vetor.*");
    printf("\n*\tDigite 3 para imprimir todo o vetor.       *");
    printf("\n*\tDigite 4 Imprimir intercalado inicial     *");
    printf("\n*\tDigite 0 para SAIR.                        *");
    printf("\n----------------------------------------------------\n");
    printf("Digite AQUI -> ");
}

void liberarEspaco(Celula vetor[]){
    int espaco;
    printf("Informe o vetor que deseja liberar: Faixa entre 1 - 10:");
    printf(" -> ");
    scanf("\n%d", &espaco);
    verifica(&espaco);
    if (vetor[espaco].endereco == NULL){
        printf("\nVetor %d VAZIO não é possível liberar espaço !!!\n\n", espaco);
    } else{
        int i = 0;
        for(i = 0; i < vetor[espaco-1].tam; i++)
            free (vetor[espaco-1].endereco[i]);
    }
}

void inicializa(Celula vetor[]){
    int i;
    for (i=0; i<dimencao; i++){
        vetor[i].endereco = NULL;
    }
}

void cria_vetor(Celula vetor[], int posicao){

    int size;
    printf("\nInforme o tamanho do vetor na posição %d: ", posicao);
    scanf("\n%d",&size);
    while(size <= 0){
        printf("\nTamanho deve ser maior que zero !!! ");  // validar a faixa
        printf("\nInforme novamente -> ");
        scanf("\n%d",&size);
    }
    vetor[posicao-1].endereco = (int *) malloc(size*sizeof(int));
    vetor[posicao-1].cont = 0;
    vetor[posicao-1].tam = size;
}

void insere(Celula vetor[]){

    int posicao, num;
    printf("\nQual posição você deseja inserir? Faixa entre 1 - 10: ");  // validar a faixa
    printf("-> ");
    scanf("\n%d",&posicao);
    verifica(&posicao);
    if(vetor[posicao-1].endereco == NULL){
        cria_vetor(vetor, posicao);
    }
    if(vetor[posicao-1].cont == vetor[posicao-1].tam)    //verificar se o vetor endereço está cheio
        printf("\nVetor %d está CHEIO !!! \n\n", posicao);
    else{
        printf("\nInforme o elemento: ");
        printf("-> ");
        scanf("\n%d",&num);
        vetor[posicao-1].endereco[vetor[posicao-1].cont] = num;
        vetor[posicao-1].cont++;
        printf("\n");
    }
}

void imprime(Celula vetor[]){

    int i, j;
     for(i=0; i<dimencao; i++){
        if (vetor[i].endereco != NULL){
            printf("\n------------");
            printf("\nVetor %d", i+1);
            printf("\n____________");
            for(j=0; j<vetor[i].cont; j++)
                printf("\n%d", vetor[i].endereco[j]);
            printf("\n\n");
        }else
          printf("\nVetor %d VAZIO", i+1);
     }
     printf("\n\n");
}

void verifica(int *espaco){
    while(*espaco < 1 || *espaco > 10){
        printf("\nPosição do vetor não corresponde! Faixa entre 1 - 10: ");  // validar a faixa
        printf("\nInforme novamente -> ");
        scanf("\n%d", &(*espaco));
    }
}

int maiorTam(Celula vetor[]) {
    int i = 0;
    int maior = 0;

    for(i = 0; i < dimencao; i++)
        if(vetor[i].tam > maior)
            maior = vetor[i].tam;

    return maior;
}

void imprimirIntercalado(Celula vetor[]) {
    int maior = maiorTam(vetor);
    int i, ic = 0, j;

    for(i = 0; i < maior; i++) {
        for(j = 0; j < dimencao; j++)
            if(vetor[j].endereco[0] != NULL)
                if(vetor[j].endereco[ic] != NULL)
                    printf("%d ", vetor[j].endereco[ic]);
        ic++;
    }

}

Todas as vezes que tento executar a opção 4 o programa trava.
Se puderem me dar essa força, agradeço. :)
Comment: Opção 4 = void imprimirIntercalado(Celula vetor[]);
Comment: Consegue ser mais específico no que deseja? Qual o problema?
Comment: Bigown, o que está acontecendo é que eu preencho os valores e na hora que peço pra imprimir intercalado trava. Tipo, fiz o teste de imprimir todo vetor (opção 3), mostra o valor preenchido, mas na hora do intercalado...

Eu tentei verificar se o vetor de Celula está NULL antes da leitura, mas o CodeBlocks não permitiu, dizendo que eu estava comparando um ponteiro com inteiro.
Comment: Não estará a comparar o endereço para que o pontriro aponta em vez do valor que armazena? Não vi o codigo. Já agora tente utilizar o debug step by step, passo a pasdo, do code blocks. Assim poderá saber qual a linha problemática.
Answer: Basta tentar compilar para achar os erros sem esforço, resolvendo o ponto b:
free (vetor[espaco-1].endereco[i]);

Isto está tentando liberar um inteiro como se fosse um endereço. Provavelmente o correto seria remover o sufixo de vetor [i].
if(vetor[j].endereco[0] != NULL)

Outro caso em que um inteiro está sendo encarado como endereço, provavelmente o [0] está sobrando.
if(vetor[j].endereco[ic] != NULL)

Mais um caso, provavelmente [ic] está sobrando também, porque NULL é do tipo ponteiro, então a intenção devia ser comparar com ponteiro.
Cada um destes erros pode causar a quebra do programa. No caso específico da pergunta, é o segundo problema que causa a quebra, porque se vetor[j].endereco é um endereço nulo ou inválido, tentar ler o conteúdo deste endereço com vetor[j].endereco[n] provoca a quebra.
Comment: Ajudou bastante. Grato.

Problema de impressão com C


window.scroll event does't work on android web view

Question: I've created a web view recently & everything seems to be working fine except the window.scroll event. I'm loading content in my mobile website once user reaches the end of the screen, unfortunately that doesn't work in Android Webview.
I've enabled javascript in Android Webview.
Here is the simple code I'm using in PHP:
$(window).scroll(function(){
  alert('H'); //This never happens
});

In main_activity.java, this line is included:
webSettings.setJavaScriptEnabled(true);

What could be the possible reason behind this? Any solution?
Comment: Have you added the jQuery lib?
If yes, is the jQuery loaded before your js file?
If yes, could you attach the screenshot of your console of the Web Developer tools of your browser?
Comment: Yes it's added & before my js file
Comment: As this is Android Webview, I've not yet set up dev tools for an App. For a mobile website, this works perfectly fine
Comment: Please check this post.
http://stackoverflow.com/questions/6253444/android-webview-scrollable
Make sure you enable the scrollbar in WebView.
Comment: That's not the thing I think. And that didn't help either
Answer: make sure jQuery loaded finish, then your code can work fine
put the code after  :

if alert "Yeah!", just replace alert("Yeah!") to your code.
Comment: Not getting any alerts, surprisingly.


Integrate a Welcome message in header in functions.php

Question: in my wordpress site https://suonareaorecchio.com I have a login/logout button in the header, created with this code in functions.php
add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
    function add_login_logout_link($items, $args) {
    ob_start();
    if ( is_user_logged_in() ) {
    wp_loginout('index.php');
    } else {
    wp_loginout( get_permalink( get_page_by_title( 'La mia pagina' ) ) );
    }
    $loginoutlink = ob_get_contents();
    ob_end_clean();
    $items .= '
'. $loginoutlink .'
';
return $items;
}
add_filter( 'login_url', 'my_login_page', 10, 2 );
    function my_login_page( $login_url, $redirect ) {
    $url = get_permalink( get_page_by_title( 'Login' ) );
    return $url . '?redirect_to=' . $redirect;
}

That creates correctly this Login/Logout button in the top right header.

I want to integrate a welcome message that says Hi user! (with link to a specific /profile/ page) and a sub menu with the logout link (with home page redirect).
To JUST create the welcome message I found this, but it creates a message in the page, not header.
add_action( 'loop_start', 'personal_message_when_logged_in' );
    function personal_message_when_logged_in() {
    if ( is_user_logged_in() ) :
    $current_user = wp_get_current_user();
echo 'Ciao ' . $current_user->user_login . '!';
else :
    echo 'Non personalize message (No clue what to put!)';
endif;
}

Basically the result I'd like to recreate would be this:

Do you know how can I integrate the two codes to have something like the second image? If you're kind may I have the final code to copy and paste since unfortunately I'm a noob?
Thanks so much for helping.
Comment: Open up your header.php or where ever your menu code and ask if user logged in with is_user_logged_in function. If so displays the message.
Comment: There is no hook available to to that. `wp_head()` adds such content right at the top and `loop_start` is to late. IMO, I see not other way that editing template files. You should do this in a child theme though
Answer: You have to edit you header.php (wp-blog-header.php) page instead of the function.php one. You also have a footer php page if you're interested in changing the footer of the page.
Take a look at this video .
The default location for header and footer should be : wp-content/themes/mytheme


UPDATE SET SELECT error "Operation must use an updateable query"

Question: I have an Access database with an item table "VendorItem" with (ID, Vendor, Price) Fields and another "ItemPrice" with (ItemName, AveragePrice) Fields.
I want to run an SQL query that will update the average price of the item from a specific vendor, let's say 'xxx'.
The error I get is "Operation must use an updateable query". This code is simple but I haven't been able to find the cause of this error.
How could I change the string to get what I want?
I have:
Sub MP()

Dim strSQL As String

strSQL = "UPDATE ItemPrice SET AveragePrice=(SELECT AVG(Price) FROM VendorItem WHERE Vendor='xxx') WHERE ItemName='xxx'"
DoCmd.RunSQL strSQL

End Sub

Comment: It looks like ms access doesn't like aggregate functions in update. See this question for more details: http://stackoverflow.com/q/871905/1385896
Answer: Access domain functions can be used to avoid the "must use updateable query" complaint.  In this case, use the DAvg Function.
First test this as a new query in the query designer.  Adjust as needed, then adapt your code to use the working SQL.
UPDATE ItemPrice
SET AveragePrice = DAvg('Price', 'VendorItem', 'Vendor="xxx"')
WHERE ItemName='xxx'


Agrupar dados mysql

Question: Dada duas tabelas grupos e processos. Onde cada grupo pode ter 0 ou N processos. QUal a melhor maneira de obter esse cruzamento.
Grupo
--------
id
Nome
bol_ativo = S

Processo
-------
id
numero
ativo  = S
encaminhado = N

o que desejo seria a quantidade de processos ativos e nao encaminhados de cada grupo ativo.
Caso o grupo nao possua nenhum processo, deveria aparecer como O na coluna total
Resultado
----------
NOME      Total
g1          0

g2          3

Answer: Assumindo a seguinte DDL de trabalho:
CREATE DATABASE `stackoverflow`;

CREATE TABLE `Grupo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Nome` varchar(85) DEFAULT NULL,
  `bol_ativo` char(1) DEFAULT 'S',
  PRIMARY KEY (`id`)
);

CREATE TABLE `Processo` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `numero` int(11) DEFAULT NULL,
  `ativo` char(1) DEFAULT 'S',
  `encaminhado` char(1) DEFAULT 'N',
  PRIMARY KEY (`id`)
);

E como resposta a seguinte DML consulta:
INSERT INTO `Grupo` (`id`,`Nome`,`bol_ativo`)
    VALUES  (1,'g1','S'),
            (2,'g2','S'),
            (3,'g3','S'),
            (4,'g4','N');

INSERT INTO `Processo` (`id`,`numero`,`ativo`,`encaminhado`)
    VALUES  (1,1,'S','N'),
            (2,1,'S','N'),
            (3,1,'S','N'),
            (4,2,'S','N'),
            (5,2,'S','N'),
            (6,1,'S','N'),
            (7,2,'S','N'),
            (8,2,'S','N'),
            (9,4,'S','S'),
            (10,2,'N','N'),
            (11,3,'N','N');

SELECT `g`.`Nome` AS `NOME`, COUNT(`p`.`id`) AS `Total`
FROM `Grupo` `g`
LEFT JOIN (
        SELECT * FROM `Processo` `p`
        WHERE 1=1
            AND `p`.`ativo` = 'S'
            AND `p`.`encaminhado` = 'N'
    )  p ON (`p`.`numero` = `g`.`id`)
WHERE
    `g`.`Bol_ativo` = 'S'
GROUP BY `g`.`Nome`;

Referência:
[Paul Dubois at al, 2005], MySQL® 5.0: Certification Study Guide

Agrupar dados mysql


Período variável data SQL Server

Question: Abaixo tenho o seguinte código onde busca em uma tabela todos os dados dentro do período especificado nas variáveis declaradas. Porém, um cliente em específico possui um fechamento de mês diferenciado, no caso, o mês dele inicia-se no dia 26, e termina no dia 25.
Estou tentando fazer as variáveis trazerem este período mas sem sucesso!
No caso, a variavel @periodoInicial teria que começar em 2017-07-26 e a variavel @periodoFinal em 2017-08-25, e terminando este período, as variaveis ja se alterassem para 2017-08-26 até 2017-09-25, é possível fazer isso?
Código:
declare @periodoInicial as date,
        @periodoFinal as date
set @periodoInicial = cast(dateadd(mm,-1,dateadd(dd,-day(getdate())+1,getdate())) as date)
set @periodoFinal = cast(dateadd(dd,-day(getdate()),getdate()) as date)

SELECT * FROM productionEnvironmentInvoiceData
where proposalDate between @periodoInicial and @periodoFinal

NOTA: ESTOU COM O SQL SERVER 2008
Comment: não entendi o " terminando este período, as variaveis ja se alterassem para 2017-08-26 até 2017-09-25"
Comment: Na realidade deveria ser criado uma coluna dia_de_fechamento na tabela de clientes, obter este "dia" e com base nele fazer o cálculo.
Comment: @RovannLinhalis por exemplo, o mes neste caso não é do dia 01 até o 30 ou 31, e sim inicia-se no dia 26 e acaba no 25, entende?
Comment: @Motta você diz colocar uma coluna 'periodoInicial' que repita 26 em todas as linhas e outra com 26 'periodoFinal' e seguir o calculo das variaveis dando select nesta tabela?
Comment: não, digo coluna diadefechamento na tabela de empresa o sql ficaria algo como
SELECT *
FROM productionEnvironmentInvoiceData  , EMPRESAS
where productionEnvironmentInvoiceData.CODEMPESA = EMPRESAS.CODEMPESA
AND proposalDate between CONVERT(DATETIME, ANO + MES-1 + diadefechamento+1)
                 and CONVERT(DATETIME, ANO + MES + diadefechamento)
Comment: @jvbarsou, só uma duvida, na tabela productionEnvironmentInvoiceData o campo é `Date` ou `Datetime` ? Se for `Datetime`, interessante utilizar do dia 26 ao dia 26, por que sendo a data final 2017-08-26, haverá a questão das horas e minutos.
Comment: Como está sua tabela de cliente?
Comment: @RicardoSouza o campo é `date`
Comment: como assim? @Sorack
Comment: @jvbarsou você pega o dia pelo cadastro de cliente, não é?
Comment: @Sorack se entendi bem oq vc quis dizer, não, na verdadeiro eu seto na variavel mesmo o periodo pois irei fazer uma procedure em especifico para este tipo de cliente. Tanto que esta tabela trata-se de dados apenas deles.
Comment: @jvbarsou você sabe a versão do seu SQL Server?
Comment: @Sorack no caso estou usando o sql server 2008
Answer: Caso esteja utilizando a versão 2012 ou superior do SQL Server o seguinte código irá atender a especificação:
DECLARE @dia    INT;
DECLARE @inicio DATE;
DECLARE @fim    DATE;

SET @dia = 26;

SET @inicio = DATEADD(DAY, @dia, EOMONTH(GETDATE(), -2));
SET @fim = DATEADD(DAY, -1, DATEADD(MONTH, 1, @inicio));

SELECT *
  FROM ProductionEnvironmentInvoiceData peid
 WHERE peid.proposalDate BETWEEN @inicio AND @fim;

Para versões anteriores ao 2012 o código adaptado ficaria assim:
DECLARE @dia int;
DECLARE @inicio date;
DECLARE @fim date;

SET @dia = 26;

SET @inicio = DATEADD(day, @dia - 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(MONTH, -1, GETDATE())), 0));
SET @fim = DATEADD(day, -1, DATEADD(month, 1, @inicio));

SELECT *
  FROM productionenvironmentinvoicedata peid
 WHERE peid.proposaldate BETWEEN @inicio AND @fim;

DATEADD
Retorna uma date especificada com o intervalo number especificado (inteiro assinado) adicionado à datepart especificada dessa date.

EOMONTH
Retorna o último dia do mês que contém a data especificada com um deslocamento opcional.
Comment: Funcionou perfeitamente @Sorack, muito obrigado!
Comment: para versão 2008, como posso adaptar o codigo?
Comment: @jvbarsou adicionei para versões anteriores
Answer:
No caso, a variavel @periodoInicial teria que começar em 2017-07-26 e a variavel @periodoFinal em 2017-08-25, e terminando este período, as variaveis ja se alterassem para 2017-08-26 até 2017-09-25, é possível fazer isso?

Se quer coletar períodos mensais, considerando-se um período maior de meses, eis uma abordagem. Primeiro deve-se definir o período completo de emissão, que envolve vários meses. O código se encarrega de gerar cada mês, definindo então os valores das variáveis @periodoInicial e @PeriodoFinal, conforme solicitado.
-- código #1 v3
--> informe o dia inicial do período completo de emissão (formato dd/mm/aaaa)
declare @MêsInicial date, @MêsFinal date;
set @MêsInicial= convert(date, '26/7/2017', 103);
set @MêsFinal= convert(date, '26/8/2017', 103);

-- variáveis para emissão mensal
declare @periodoInicial date, @periodoFinal date;

-- início do primeiro mês
set @periodoInicial= @MêsInicial;

while @periodoInicial <= @MêsFinal
  begin
  -- calcula o final do mês
  set @periodoFinal= dateadd(day, -1, dateadd(month, +1, @periodoInicial));
  -- processamento do mês
  SELECT colunas
    from productionEnvironmentInvoiceData
    where proposalDate between @periodoInicial and @periodoFinal;
  -- próximo início de mês
  set @periodoInicial= dateadd(month, +1, @periodoInicial);
  end;

Período variável data SQL Server


how to declare a pipe translate only once for all my jest test files?

Question: I have an angular project in which I use jest as test runner.
I use the pipe 'translate' for internationalisation, but in consequence in most of my test spec I have to add:
@Pipe({
    name: 'translate'
})
export class TranslateMockPipe implements PipeTransform {
    public name: string = 'translate';

    public transform(query: string, ...args: any[]): any {
        return query;
    }
}
  declarations: [..., TranslateMockPipe],

My issue is, I have to add this code in all my spec file.
Any idea how I can do it automatically in all my spec? ( maybe by putting it in the setup-jest.ts ? )
Comment: Does this answer your question? [How to mock Pipe when testing Component](https://stackoverflow.com/questions/39293258/how-to-mock-pipe-when-testing-component)
Comment: You don't have to add that to every test. Just do it once and re-use it.
Comment: What's *the pipe 'translate'*? Do you mean [angular-l10n](https://github.com/robisim74/angular-l10n) or another library. There is no inbuilt translate pipe in angular
Answer: Below is an example of how I test a pipe that transforms bytes into presentable strings, if that helps.
import { FormatBytesPipe } from '@jfs/shared/pipes/format-bytes.pipe';

describe('Pipe: Format Bytes', () => {
  let pipe: FormatBytesPipe;

  beforeEach(() => {
    pipe = new FormatBytesPipe();
  });

  it('should transform 0 to "0 Bytes"', () => {
    expect(pipe.transform(0)).toEqual('0 Bytes');
  });
  it('should transform 1024 to "1 KB"', () => {
    expect(pipe.transform(Math.pow(1024, 1))).toEqual('1 KB');
  });
  it('should transform 1024^2 to "1 MB"', () => {
    expect(pipe.transform(Math.pow(1024, 2))).toEqual('1 MB');
  });
  it('should transform 1024^3 to "1 GB"', () => {
    expect(pipe.transform(Math.pow(1024, 3))).toEqual('1 GB');
  });
  it('should transform 1024^4 to "1 TB"', () => {
    expect(pipe.transform(Math.pow(1024, 4))).toEqual('1 TB');
  });
  it('should transform 1024^5 to "1 PB"', () => {
    expect(pipe.transform(Math.pow(1024, 5))).toEqual('1 PB');
  });
  it('should transform 1024^6 to "1 EB"', () => {
    expect(pipe.transform(Math.pow(1024, 6))).toEqual('1 EB');
  });
  it('should transform 1024^7 to "1 ZB"', () => {
    expect(pipe.transform(Math.pow(1024, 7))).toEqual('1 ZB');
  });
  it('should transform 1024^8 to "1 YB"', () => {
    expect(pipe.transform(Math.pow(1024, 8))).toEqual('1 YB');
  });
});

Comment: Please don't ask questions in answers. If you need clarification you should add a comment when you have enough reputation
Comment: @Liam Thanks, I wasn't aware I could comment as I couldn't find the button "comment" . I was just trying to help the poster
Answer: You might consider using a third-party testing library like ng-mocks, which allows you to mock easily services, components, pipes and many other things.
Have a look at official documentation on how to mock pipes.


Chamar Subreport no Relatório principal

Question: Galera, tenho 2 relatórios, o sub relatório e o Relatório principal, porém quando dou um preview só consigo visualizar o principal, como faço para exibir o sub relatório também?
Estou usando JasperSoft Studio.

Tenho um relatório que é preenchido por uma lista e por parâmetros, porem encontrei um problema e recebi ajuda aqui no fórum, a pessoa que me ajudou disse que a melhor forma de solucionar esse problema seria criando um SubReport.
O problema é o seguinte, eu quero deixar o meu relatório da seguinte forma:

Como pode ver, um Beneficiário tem mais de 1 procedimento. Atualmente eu consigo listar todos os procedimentos e beneficiários, porém os procedimentos se repetem. Isso é o que eu consigo atualmente:

O meu o Nome do Beneficiário se repete, e mostra o outro procedimento, não fica tudo junto em apenas um lugar.
Estou tentando colocar um SubReport com o Nome do Beneficiário e Identificador em um Group Header, e os procedimentos (Data Realização, Descrição do Serviço, cod Tab..) dentro do Detail. Acho que dessa forma iria funcionar, porém nao estou conseguindo chamar o SubReport dentro do meu relatório.
Comment: O relatório secundário precisa estar compilado num arquivo `.jasper` em algum diretório específico. E aí no componente do subrelatório no relatório principal você precisa especificar um caminho para o arquivo compilado do subrelatório. Caso precise de mais ajuda, clique em [edit] na sua pergunta e acrescente mais informações sobre o seu relatório. Abraço!
Comment: Entendi, mas como passo esse caminho, qual o tipo do parâmetro?
Comment: editei a pergunta
Comment: Dá uma olhada [aqui](http://community.jaspersoft.com/wiki/subreports-jaspersoft-studio).
Comment: já olhei porem não entendi, ali ele passa um ID como parametro e suponho que seja por conexão JDBC, utilizando listas como data source funciona da mesma forma?
Comment: Diego Tem como vc me passar o seu relatório para eu usar como modelo ?
Comment: @FillipeDesenvolvedor nossa, não tenho mais acesso a ele faz um tempão hehe.
Answer: Você precisa especificar o caminho para o subrelatório de dentro do relatório principal.
Isso deve ser feito no componente de subrelatório, em seu atributo Subreport Expression, conforme a imagem abaixo:

Aí você pode especificar o caminho para o arquivo .jasper do subrelatório através de um dos tipos String, File, InputStream, URL e JaspeReports.
Comment: Fiz isso mas ainda não carrega o Subreport, tenho que configurar alguma coisa no SubReport?
Comment: Olha como está:

http://i.stack.imgur.com/EZpcV.png
Comment: @DiegoAugusto Não tem erros na aba *Output*?
Comment: Nenhum, acho que não está sendo exibido por retornar tudo nulo, vou tentar chamar por código pelo ImputStream
Comment: @DiegoAugusto Pode ser que não esteja exibindo nada pela falta de dados. Você está passando os parâmetros para o subrelatório? Tente colocar uma query fixa e veja se aparece algo.
Comment: Eu estou tentando passar uma lista, ai que está a dificuldade. Tentei passar o sub report como parametro e deu esse erro: `net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
 Source text : $P{sub}`
Comment: @DiegoAugusto Verifique se o tipo de `${sub]` é compatível com o tipo informado no outro campo que informa o tipo. Por exemplo, se for uma String, deve estar `java.lang.String`.
Comment: Estava enviando por InputStream da seguinte forma:
`InputStream sub= this.getClass().getResourceAsStream("/br/com/xml/relatorio/subRelatorio.jrxml");`
Comment: E depois usava `filtro.put("sub", sub);`
Comment: Mas acho que está dando erro pois estou tentando passar uma lista para o sub relatório e não sei se estou fazendo de forma correta. Resumindo eu preciso passar uma lista para o relatório principal, isso eu já consigo fazer, agora preciso passar uma lista para o sub report e logo em seguida chamar meu Relatório principal com o sub report dentro.

Chamar Subreport no Relatório principal


EM for mixture of negative binomial distributions in R

Question: I'm having problems with a fairly basic EM algorithm for a mixture of negative binomial distributions. Given the mean-dispersion parametrisation of the negative binomial distribution,  we have a model of the form
$$ y_n | \pi_n = c \sim \mathcal{NB}(\mu = m \lambda_c, \phi) $$
for $n = 1, \ldots, N$, where $\pi_n$ signifies which cluster ($c$) sample $n$ comes from. In other words, the mean of $y$ is a global mean $m$ times a component specific mean $\lambda_c$, where $\lambda$ is known.
The basic EM algorithm proceeds as:

E-step: compute $\gamma_{nc} = p(\pi_n = c | \cdot) = \frac{\mathcal{NB}(y_n | m \lambda_c)}{\sum_{c'} \mathcal{NB}(y_n | m \lambda_{c'})}$
M-step: Maximise $Q(\theta|\theta^{(t-1)}) = \sum_n \sum_c \gamma_{nc} \log \mathcal{NB}(y_n | m \lambda_c, \phi)$ wrt $(m, \phi)$

Because no closed form MLE of a negative binomial exists, I've been using L-BFGS-B optimisation using optim in R. However, when I do this the $Q$ function does not increase at every iteration - there's a big jump at the first iteration, then it slowly decreases (though converges to a value fast).
Is there anything obviously wrong with this scheme?
Comment: The package `countreg` on R-Forge (https://R-Forge.R-project.org/R/?group_id=522) also provides a plugin for the `flexmix` package to estimate a negative binomial finite mixture model. See `help("FLXMRnegbin", package = "countreg")` for a detailed worked example from the supplements of Kleiber & Zeileis (2016, The American Statistician, https://dx.doi.org/10.1080/00031305.2016.1173590).
Answer: After several days thinking about this, the answer is - $Q$ function shouldn't increase at every iteration, but the (log) marginal likelihood, which in this case is given by
$$ \log p(Y, \lambda) = \sum_n \log\left[ \sum_c \mathcal{NB} (y_{n} | m \lambda_c, \phi) \right]. $$
Comment: Preprint describing the model now online at - https://www.biorxiv.org/content/early/2018/06/11/344309
Comment: Can you post the code for your solution as well? I'm struggling with a similar problem


Lista de estados onde cada nó estará ligado a uma árvore de busca binária de cidades

Question: Boa tarde,
Queria saber como fazer uma lista encadeada de estados onde cada nó estado está ligado a uma árvore de busca binária de cidades a partir das informações extraídas de um arquivo.
Minha dúvida surgiu após sucessivas tentativas de gerenciar minha estrutura usando ponteiros serem frustradas por erros [Error] dereferencing pointer to incomplete type.
Pelo erro emitido supus que o problema estaria na declaração do tipo de ponteiro, já que meu compilador poderia não estar associando o typedef struct celCidade apontadorCidade; a um ponteiro para struct celCidade por exemplo, então tentei utilizar cast através do malloc();, porém o erro persiste.
Na função insereCidade(); está o erro apontado.

Onde está o erro?
Como posso corrigi-lo?
Tem como simplificar o código?

Código completo para teste:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

typedef struct celCidade apontadorCidade;
typedef struct celEstado apontadorEstado;

typedef struct{

    char nome[30];
    int populacao;
    int beneficiarios;
    int qtdCidades;
    float idh;
    apontadorCidade *Arv;
    apontadorEstado *proxEstado;
}celEstado;

typedef struct{

    char nomeCidade[30];
    char nomeEstado[30];
    int populacao;
    int beneficiarios;
    float idhm;
    apontadorCidade *esq;
    apontadorCidade *dir;

}celCidade;

typedef struct{

    celEstado *inicioLista;

}tipoListaEstado;

int insereCidade(celCidade newCidade, celEstado *auxEstado){

    if(auxEstado->Arv == NULL){
        auxEstado->Arv = (apontadorCidade*)malloc(sizeof(celCidade));
        auxEstado->Arv->beneficiarios = newCidade.beneficiarios;
        auxEstado->Arv->idhm = newCidade.idhm;
        auxEstado->Arv->populacao = newCidade.populacao;
        strcpy(auxEstado->Arv->nomeCidade, newCidade.nomeCidade);
        strcpy(auxEstado->Arv->nomeEstado, newCidade.nomeEstado);

        return 0;
    }

    if(auxEstado->Arv->nomeCidade[0] >= newCidade.nomeCidade[0]){
        insereCidade(newCidade, auxEstado->Arv->dir);
    }else if(auxEstado->Arv->nomeCidade[0] < newCidade.nomeCidade[0]){
        insereCidade(newCidade, auxEstado->Arv->esq);
    }

    auxEstado->qtdCidades++;
    auxEstado->beneficiarios += newCidade.beneficiarios;
    auxEstado->populacao += newCidade.populacao;
    auxEstado->idh += newCidade.idhm;
    strcpy(auxEstado->nome, newCidade.nomeEstado);

    return 0;
 }

bool buscaEstado(tipoListaEstado *listaEstado, celEstado *auxEstado,
celCidade newCidade){

bool retorno;
auxEstado = listaEstado->inicioLista;

    do{
        retorno = false;

        if(strcmp(newCidade.nomeEstado, auxEstado->nome) == 0){
            return true;
        }else{
            auxEstado = auxEstado->proxEstado;
            }
          }while(retorno == false || auxEstado->proxEstado != NULL);

    return false;
}

void carregaArquivo(FILE *arquivo, tipoListaEstado *listaEstado){

    celEstado *auxEstado;
    celCidade newCidade;

    while(fscanf(arquivo, "%[^;],%[^;],%d;%f;%d", &newCidade.nomeCidade, &newCidade.nomeEstado, &newCidade.populacao, &newCidade.idhm, &newCidade.beneficiarios) != EOF){

        if(listaEstado->inicioLista == NULL){
            listaEstado->inicioLista = (celEstado*)malloc(sizeof(celEstado));
            strcpy(listaEstado->inicioLista->nome, newCidade.nomeEstado);
            auxEstado = listaEstado->inicioLista;
        }

        if(strcmp(newCidade.nomeEstado, auxEstado->nome) == 0){
            insereCidade(newCidade, auxEstado);
        }

        if(buscaEstado(listaEstado, auxEstado, newCidade) == false){
            auxEstado->proxEstado = (celEstado*)malloc(sizeof(celEstado));
            auxEstado = auxEstado->proxEstado;
            insereCidade(newCidade, auxEstado);
        }

    }

}

int main() {

    FILE *arquivo;

    tipoListaEstado listaEstado;

    arquivo = fopen("data.csv", "r");

    if(arquivo == NULL){
        printf("Erro ao abrir o arquivo");
    }

    return 0;
}

Comment: Você está passando apenas o valor da sua struct, quando finaliza a função a memória é devolvida para o sistema e seus ponteiros são perdidos. Recomendo utilizar ponteiro de ponteiro, assim você passa a struct por referencia e não por valor
Comment: no caso transformar o `typedef struct celCidade apontadorCidade` em `typedef struct celCidade *apontadorCidade`? e depois declarar um `apontadorCidade *auxCidade`?
Comment: a struct está correta. Na hora que você chama a função insereCidade, passa assim: insereCidade(&newCidade, &auxEstado). E a sua função ficaria int insereCidade(celCidade **newCidade, celEstado **auxEstado). Ao invez de utilizar apenas auxEstado passa a utilizar *auxEstado. Onde **auxEstado vai ser um ponteiro que aponta diretamente para auxEstado da sua função carregaArquivo, assim não perde os dados ao termino da função.
Comment: O problema não está na perda de dados, pelo menos não que eu tenha notado, o problema é de compilação mesmo. o erro `[Error] dereferencing pointer to incomplete type` está impedindo o programa de ser compilado e testado
Comment: Ao invez de utilizar typedef struct celCidade apontadorCidade; tenta colocar direto na struct assim:
typedef struct celCidade{
    char nomeCidade[30];
    char nomeEstado[30];
    int populacao;
    int beneficiarios;
    float idhm;
    struct celCidade *esq;
    struct celCidade *dir;
}apontadorCidade;
Comment: Dá erro de tipo não conhecido por causa dos ponteiros de celCidade, já tentei isso kkkk
Answer: Uma solucão seria:
typedef struct celCidade apontadorCidade;
typedef struct celEstado apontadorEstado;

struct celEstado{

    char nome[30];
    int populacao;
    int beneficiarios;
    int qtdCidades;
    float idh;
    apontadorCidade *Arv;
    apontadorEstado *proxEstado;
};

typedef struct celEstado celEstado;

struct celCidade{

    char nomeCidade[30];
    char nomeEstado[30];
    int populacao;
    int beneficiarios;
    float idhm;
    apontadorCidade *esq;
    apontadorCidade *dir;

};

typedef struct celCidade celCidade;

Mas não consigo entender porquê você declara os tipos apontadorCidade e apontadorEstado. Porquê não usar celEstado e celCidade diretamente??


Debugger does not start, but working fine start without debugging

Question: I am a bit stuck with my project in c#, .net 4.5.2, using VS2017 debugger does not start, when debugging but starts when start without debugging is selected.
Also, application does not work (unable to login) in start without debugging.
Things I have tried:

Clean, Rebuild, Restart solution
Updated with new version (thought it was error for old version)
Check with break point and log for loading vs symbol servers

Still not working.
Comment: So your application doesn't run when you `start with debugging`, yet it does run when you `start without debugging` ?
Comment: Right. Shows unable to connect in browser but debugging process keeps on running.
Comment: Sounds like you might have set a breakpoint in the site's startup code. BTW is it a site? You should tag `ASP.NET` or whatever tech you're using.
Comment: Does firewall blocks debugging of code?
Comment: If you want to eliminate the firewall as a possible issue, check your [IIS W3C logs](https://learn.microsoft.com/en-us/iis/manage/provisioning-and-managing-iis/configure-logging-in-iis). If you see traffic, the issue isn't the F/W.
Comment: Issue was solved, In project properties->web->debuggers, native debugger was checked. After unchecking that and building the project, the application was able to debug, hitting the break points. Thanks btw.
Comment: @Manoj Glad to hear that, you could post your solution and mark it as answer to help more people.Thanks!
Comment: Sure. Will you help me with this.
https://stackoverflow.com/questions/49464030/gdi-error-saving-files-to-clients-temp-folder
Dynamically created images in Temp folder of server(remote) gets excluded from project.
Answer: Issue was solved,
In project properties->web->debuggers, native debugger was checked. After unchecking that and building the project, the application was able to debug, hitting the break points.


onmouseover em menu dropleft

Question: Olá, sou novo na área de programação e minha dúvida pode parecer um pouco boba para quem temmais experiência, mas não estou conseguindo fazer o efeito mouseover funcionar no menu dropleft (bootstrap).
Já tentei usar tags de javascript e até mudar a função das variáveis, mas não tive sucesso.
Vou deixar aqui um exemplo do que estou tentando fazer.
PS: Não estou usando a tag UL pois é para o menu de ícones aparecer todo a esquerda, e não em lista, abaixo.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>

Dropleft

  <button type="button" class="btn btn-secondary" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

  </button>

Comment: Fiz um esforço para responder, mas sua pergunta precisaria ser mais clara. O comentário do colega acima pode não ter te ajudado, mas a intenção era sim ajudar. Ele não entendeu a pergunta porque ela está apresentada de maneira confusa.
Comment: Se vc está usando Bootstrap, vc tem que seguir o que diz a documentação dele, usar as mesmas tags e os mesmo atributos se não não vai funcionar https://getbootstrap.com/docs/4.0/components/navbar/ essa é a documentação que vc deve seguir!
Comment: Eu li a documentação amigo, não fala nada sobre o comando onmouseover na referência de dropdown e nem em outras referências, pois pesquisei o site todo antes de vir aqui pedir ajuda... Se fosse simples, pode ter certeza que eu não estaria aqui...
Answer: É com CSS que você faz isso, não com JavaScript:
.dropleft .dropdown-menu a {
    display: inline-block; /* para a imagem afetar a altura do a */
}

.dropleft .dropdown-menu a:hover {
    background-color: red;
}

onmouseover em menu dropleft


What are some math books written in dialogue or story form, e.g., a teacher explaining to a student?

Question: Good examples would be The Square Root of 2 by David Flannery or Math Girls by Hiroshi Yuki.
Comment: Calculus by LV Tarasov.
Comment: It's about programming rather than math, but you might be interested in [The Little Schemer](http://www.amazon.com/The-Little-Schemer-4th-Edition/dp/0262560992) and other books in the series (such as [The Little Prover](http://www.amazon.com/gp/product/0262527952/ref=pd_lpo_sbs_dp_ss_2/178-9870897-6077865?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=lpo-top-stripe-1&pf_rd_r=03E4CK6S4HKMH5M2E3YG&pf_rd_t=201&pf_rd_p=1944687662&pf_rd_i=0262560992)).  They're written in dialogue form.
Comment: I also recommend checking out [Who is Fourier?: A Mathematical Adventure](http://www.amazon.com/Who-Fourier-Mathematical-Adventure-Edition/dp/0964350432).
Comment: Stories About Sets by N.Y. Vilenkin.
Comment: In French, you have Serge Lang, "Des jeunes et des mathématiques".
Answer: I don't know if there are any particular topics you're interested in, or at what level of detail you want them presented, but Knuth's Surreal Numbers is an example of the sort of book you mean:

B. You mean we're actually using the New Math to decipher this old
  stone tablet?
A. I hate to admit it, but that's what it looks like. Here the first
  rule says that every number $x$ is a pair of sets called the left set
  $x_L$ and the right set $x_R$: $$x=\langle x_L,x_R\rangle.$$
B. Hold it, your notation mixes me up. I don't know what's a set and what's a number.
Answer: The Number Devil: A Mathematical Adventure Is very good; It explains complex concepts in ways simple enough that young children can understand them, yet complex enough to maintain an adults attention with the revelations and connections it provides.
Answer: I don't know if it counts as a math book, but Hofstadter's "Gödel, Escher, Bach" contains a large number of very entertaining dialogues that help to explain concepts in logic such as Gödel's incompleteness theorems, usually disguised in the form of some kind of fable involving Achilles and the tortoise.
Answer: Flatland by Edwin A. Abbot comes to mind. It is an "easy" introduction to higher dimensions.
Flatterland is probably more mathematical, though.  It introduces many modern concepts like topology, hyperspace, etc. and is indeed like a teacher (the "Space Hopper") explaining to a student (the 2D being Victoria Line).
Comment: Flatterland is wonderful. I learnt a lot from it and had to take regular breaks after each chapter to find out more about what was covered.
Answer: Barron's has 3 books that are in story form. The story in these actually builds on each other and they can be read in this order:

Algebra The Easy Way
Trigonometry The Easy Way
Calculus The Easy Way
Comment: I've read/studied Calculus The Easy Way and found it to be good. Haven't seen the first two.
Comment: These books are literally my childhood.
Answer: Galileo's Dialogue Concerning the Two Chief World Systems is the patriarch of this genre.
There is a math book (not the Lockhart essay, but I do not remember the title), that uses Galileo's antagonists Simplicio and Salviati to explain the material through a series of dialogues.
Comment: Also Galileo's *Discourses and Mathematical Demonstrations Relating to Two New Sciences* is in a similar dialogue form.
Answer: I'm not sure if they they have the exact form that you want, but they have mathematics, dialogue and story:

The Manga Guide to Statistics
The Manga Guide to Linear Algebra
The Manga Guide to Calculus

Remark 1: There are other titles on Databases, Electricity, Physics, Molecular Biology, Relativity, Universe, Biochemistry.
Remark 2: I didn't read these books and I have no idea if they are a good. The only thing that I know about them is that they do exist.
Comment: I had no idea they translated this stuff into English.
Comment: I've read the statistics book, the first 1/2 of it was pretty good. When they got to hypothesis tests I think the author really dropped the ball. Overall I would recommend it to my students (I teach a lab course where statistics has to be picked up on the fly).
Answer: Don' t forget Euclid and his Modern Rivals by  Charles Lutwidge Dodgson (1832–1898), better known as Lewis Carroll.
https://en.wikipedia.org/wiki/Euclid_and_his_Modern_Rivals
It is sometimes said that it was a play , not sure if it was ever preformed on stage
Comment: Typo: *pReformed*.
Answer: I would recommend "Proofs and Refutations" by Imre Lakatos. It is not so much a real story as a series of dialogs between students in a classroom, nicely illustrating much of the mathematician's handiwork.
Answer: A Certain Ambiguity is a book by Gaurav Suri and Hartosh Singh Bal. Although it is a novel, it addresses some very deep parts of mathematics, including Euclid's Fifth Postulate and the concept of infinity. Because it is a novel, most of the mathematics is explained in the dialogue from one character to another.
Comment: A Certain Ambiguity is one of the best treatments of infinity that I've come across. Plus it has a nice story...literally couldn't put the book down
Comment: Agreed. Still holding out hope for a sequel!
Answer: They are written in Italian, so I don't know how many people may enjoy them, but Roberto Zanasi wrote two books in form of a dialogue between a Vero matematico ("True mathematician") an an apprentice:
Verso l'infinito, ma con calma (To the infinite, but with ease), about infinity in mathematics
Un punto fermo (An anchor), about invariants.
Answer: Heyting's Intuitionism: An Introduction begins with a dialogue between proponents of different schools of mathematical philosophy.
Answer: I quite like the Life of Fred Math books.  The math is all taught by having the main character, Fred, encounter situations where he requires the math principle.
Answer: The Man Who Counted
From Wikipedia:
The Man Who Counted (original Portuguese title: O Homem que Calculava) is a book on recreational mathematics and curious word problems by Brazilian writer Júlio César de Mello e Souza, published under the pen name Malba Tahan. Since its first publication in 1938,[1] the book has been immensely popular in Brazil and abroad, not only among mathematics teachers but among the general public as well.
The book has been published in many other languages, including Catalan, English (in the UK and in the US),[2] German, Italian, and Spanish, and is recommended as a paradidactic source in many countries.
Answer: I just came across Math Dialogue: Functions which states that it «is a very gentle introduction to the concept of the function, written in form of a dialogue.» I did not read it, though.
Answer: I know I'm a bit late, but I recently came across the lovely book Treks into Intuitive Geometry, which consists of a series of conversations between Gen and Kyu, as can be seen in the image below. The whole book appears to be written in this format.
Answer: Lawvere and Schanuel, Conceptual Mathematics: A first introduction to categories has many such passages, reflecting the classroom atmosphere from when the material was first taught.


How to change directory

Question: How to change directory from: articles/article.php to: articles/article/ (without filename)
Is it directory with hidden index.php or something else?
I think it's related with .htaccess but I'm not sure. How can I do this?
Comment: Google "mod rewrite htaccess" - 1st result > http://www.branded3.com/blogs/htaccess-mod_rewrite-ultimate-guide/ - one of *About 304,000 results (0.30 seconds)*
Comment: If you're using a framework like Zend or Code Igniter, most have a way of customizing routes.
Comment: It's seems you're looking for URL Rewriting, maybe helpful if checking This: http://stackoverflow.com/a/16389034/3878932
Comment: You may want to make your title a little more descriptive. Also, all five of the tags/keywords you chose have nothing to do with what you're trying to solve.
Answer: You can use .htaccess to remove the file extensions as follows:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Where it says .php change that to your file extension. Keep in mind that for example if your file is about.php and you have a folder called "about", it won't work.
The route I see most people use is to have a huge directory of folders and index pages, that will work just fine, however search engines will have a hard time indexing your site.
This is a really popular question, probably didn't need to come here to ask haha
Answer: Option 1 - Mod rewrite htaccess
You're probably looking for mod rewrite with an htaccess file. With this, you can point these types of URL's:
mydomain.com/articles/article/1001
mydomain.com/articles/1001
mydomain.com/1001

to this:
mydomain.com/articles/article.php?id=1001

Option 2 - Using index.php
Alternatively, you can create a sub-directory in articles called article and rename article.php to index.php - this will allow you to use the following:
mydomain.com/articles/article

Option 3 - Hide PHP extensions
Or turn off PHP file extensions in PHP configuration file, which would also give you:
mydomain.com/articles/article

How to change directory


Page table fast growth

Question: Not long ago I've spotted very interesting tool RamMap.
I found on several servers running our x32 software that PAGE TABLE grows very quickly – 1.2 GB per day (of 10GB all). Also NONPAGED POOL grows 300MB per day.

Can anybody explain usual reasons for this?
How can i get size of PAGE TABLE from code (for exaple API function or WMI class)?
Can it be decreased, cleared or ... to free up RAM?

We have programming and executing platform called 1C (Russian business oriented platform). One process is like a manager over the others, which are launched on the schedule and are terminated by rules and perform different kinds of data processing including exchange with another data bases using COM. In other words i can't tell what is happening on the platform level (it is hidden from us). We have some not fast (=)) support from platform developers – they still not answered on our questions for this issue.
We have different OS configurations (2003 and 2008 Server, x32 and x64). Everywhere page table grows. Speed of growth is proportional to number of processes running simultaneously (on the main server 30-40). When PAGE TABLE reaches 50-70% of RAM server begins to fail in different ways.
Comment: It seems I just made one step forward to solve the problem. See new topic about memory leak suspicion http://serverfault.com/questions/254908/process-managment-leak-in-windows-server-x64
Answer: Looks like a virtual memory fragmentation issue; memory is being allocated and deallocated continuously, and each time new Page Table Entries (PTEs) are being created in order to keep track of memory pages; your assertion that lots of processes are being created and terminated and that this page table increase is proportional to the number of running processes really points in this direction. Also, PTEs are usually kept in nonpaged memory (they're vital to the memory menager, so should always reside in memory); this also explains the increase in the nonpaged pool usage.
Some links about this:
http://www.dabcc.com/article.aspx?id=10571
https://learn.microsoft.com/en-us/archive/blogs/david.wang/more-on-virtual-memory-memory-fragmentation-and-leaks-and-wow64
These are also very helpful in understanding what could be going on:
http://blogs.technet.com/b/markrussinovich/archive/2008/07/21/3092070.aspx
http://blogs.technet.com/b/markrussinovich/archive/2008/11/17/3155406.aspx
http://blogs.technet.com/b/markrussinovich/archive/2009/03/26/3211216.aspx
Unfortunately, there isn't much you can do about this; this page is Exchange-specific, but maybe it can give you some tips:
http://support.microsoft.com/kb/325044
This is a kind of problem no application restart can fix; only a full server reboot can clear virtual memory fragmentation.
Using a x64 system can help here, as the virtual address space is considerably bigger; but it will not fix the fragmentation issue, so it won't fix the increased PTE usage, either.

Page table fast growth


Explain conditional distribution given sufficient statistics.

Question: I understood proof of sufficient statistics by factorization theorem.
But I can't solve fllowing two questions about conditional distribution.

When $X_1, X_2, ..., X_n \sim N(0, \sigma^2)$ are i.i.d., expain conditional distribution of $X=(X_1, X_2, ..., X_n)$ given $T=\sum_{i=1}^{n}X_i^2$.
When $X_1, X_2, ..., X_n \sim N(\mu, \sigma^2)$ are i.i.d., expain conditional distribution of $X=(X_1, X_2, ..., X_n)$ given $T=(\bar{X}, \sum_{i=1}^{n}(X_i-\bar{X})^2)$.

I was given a hint of Q1, "Consider uniformaly distribution on a hyper-sphere  $\sum x_i^2=t$."
Comment: @TheBluegrassMathematician I tried to use definition of conditional distribution. $X\sim N(0, \sigma^2I_n)$, $\sum(X_i/\sigma)^2\sim\chi^2(n)$, $f_{X, T}(x, t) = \frac{1}{{(2\pi\sigma^2)}^{n/2}}\exp(-\frac{1}{2\sigma^2}\sum x_i^2)I(\sum x_i^2=t)$, $f_T(t)=\frac{1}{(2\sigma^2)^{n/2}}\frac{1}{\Gamma(n/2)}t^{n/2-1}\exp(-\frac{1}{2\sigma^2}t)$. And I used $f_{X|T=t}(x) = f_{X,T}(x, t)/f_T(t)$, I got my answer "If $\sum x_i^2=t$, then $f_{X|T=t}(x)=\Gamma(n/2)/(\pi^{n/2}t^{n/2-1})$". But I can't explain this distribution.
Answer: The point in $\#1$ is that the conditional density of $(X_1,\ldots,X_n)$ given the value of $X_1^2+\cdots+X_n^2$ does not depend on $\sigma.$
Suppose you're given that $X_1^2+\cdots+X_n^2 = r^2.$ The joint density of $(X_1,\ldots,X_n)$ is proportional (as a function of $(x_1,\ldots,x_n)$ to $$ e^{-(x_1^2+\cdots+x_n^2)/(2\sigma^2)}. $$ When restricted to the set on which that sum of squares is $r^2,$ that becomes $e^{-r^2/(2\sigma^2)}.$ Now the crucial point is that that value, $e^{-r^2/(2\sigma^2)}$, does not change as the point $(x_1,\ldots,x_n)$ moves about on the sphere $x_1^2+\cdots+x_n^2=r^2.$ So we have
$$
\int\limits_\text{sphere} e^{-r^2/(2\sigma^2)} \, dA = e^{-r^2/(2\sigma^2)} \times \text{surface area}.
$$
For this to be a density, we need to multiply it by a normalizing constant $c,$ so that
$$
\big(c e^{-r^2/(2\sigma^2)} \times \text{surface area} \big) = 1.
$$
Then the density is
$$
ce^{-r^2/(2\sigma^2)} = \left( \frac 1 {e^{-r^2/(2\sigma^2)} \times \text{surface area}} \right) e^{-r^2/(2\sigma^2)} = \cdots
$$
and this does not depend on $\sigma^2.$
I.e. the conditional distribution of $(X_1,\ldots,X_n)$ given $T$ does not depend on $\sigma^2.$
Comment: Thanks. All I had to do was explain dependency of $\sigma^2$. By the way I have a question. According to your answer, density is 1/surface area $= \frac{\Gamma(n/2)}{2\pi^{n/2}t^{n-1}}$. But my result is $\frac{\Gamma(n/2)}{\pi^{n/2}t^{n/2-1}}$. What's wrong my idea?
Comment: @tanio : As far as the question you asked is concerned, all one needs is that you end up with something that doesn't depend on $\sigma.$ Maybe your last comment is worth a separate question.
Comment: Thank you for your advice!


Change of variables and Jacobian in double integral

Question: I am supposed to evaluate a double integral using change of variables. The integral is: $ \int_{0}^{1}\int_{0}^{x}\frac{(x+y)e^{(x+y)}}{{x^{2}}}dydx $
I am given these equations to switch between variables:
$ u=\frac{y}{x}$ and $v=x+y$
Calculations:
The first thing to calculate is the Jacobian:
$dxdy$ = $\begin{bmatrix}
\frac{\partial u}{\partial x} & \frac{\partial u}{\partial y}\\
 \frac{\partial v}{\partial x}& \frac{\partial v}{\partial y}
\end{bmatrix}$
$\frac{\partial v}{\partial x}=\frac{\partial v}{\partial y}=1$
$\frac{\partial u}{\partial x}=\frac{-y}{x^{2}}$ and $\frac{\partial u}{\partial y}=\frac{1}{x}$
Therefore the Jacobian = $dxdy$ = $\frac{-y}{x^{2}}-\frac{1}{x}$
=  $\frac{-y-x}{x^{2}}$
and the integral becomes $ \int_{0}^{1}\int_{0}^{x}\frac{(x+y)e^{(x+y)}}{{x^{2}}}(\frac{-y-x}{x^{2}}) dudv $
Since $v=x+y$,
the integral becomes $ \int_{0}^{1}\int_{0}^{x}\frac{(v)e^{(v)}(-v)}{{x^{2}}}dudv $
$ \int_{0}^{1}\int_{0}^{x}\frac{(-v^{2})e^{(v)}}{{x^{2}}}dudv $
At this point I am confused how to substitute for the x in the integral bound and the denominator as well as changing the boundaries in the integrals. I know I want the entire integral in terms of u and v. I was thinking about using $x=v-y$ but that leaves it in terms I don't want.
The answer is $e^{2}-e-1$
Thanks for the help.
Comment: You need to solve your current variables first in terms of $u$ and $v$ and then calculate the Jacobian of $\frac{\delta x}{\delta u}$, etc.
Comment: Brent, I already calculated the Jacobian. I don't see how to solve for x without getting a y back.
Comment: In addition to the above point, I guess it makes more sense to leave $x$ untouched (or let $v=x$) than $v=x+y$.
Comment: In you COV $y=ux$, so $v=x+ux=(1+u)x$, so $x=v/(1+u)$.
Answer: 1.) Transform differentials:
$$\begin{gathered}
  (x + y){e^{x + y}}\frac{1}{{{x^2}}}dydx \hfill \\
  u = \frac{y}{x},v = x + y \hfill \\
  du =  - \frac{y}{{{x^2}}}dx + \frac{1}{x}dy \hfill \\
  dv = dx + dy \hfill \\
  du \wedge dv =  - \frac{y}{{{x^2}}}dx \wedge dy + \frac{1}{x}dy \wedge dx \hfill \\
  du \wedge dv =  - \frac{{x + y}}{{{x^2}}}dx \wedge dy = \frac{{x + y}}{{{x^2}}}dy \wedge dx \hfill \\
  \frac{1}{v}du \wedge dv = \frac{1}{{{x^2}}}dy \wedge dx \hfill \\
  \frac{1}{{{x^2}}}dydx = \frac{1}{v}dudv \hfill \\
  (x + y){e^{x + y}}\frac{1}{{{x^2}}}dydx = {e^v}dudv \hfill \\
\end{gathered}$$
2.) Find inverse function:
$$\begin{gathered}
  u = \frac{y}{x},v = x + y \Rightarrow uv - y = x\frac{{{y^2}}}{{{x^2}}} = x \cdot {u^2} \hfill \\
   \Rightarrow uv - x - y = x \cdot {u^2} - x \hfill \\
   \Rightarrow uv - v = x \cdot ({u^2} - 1) \hfill \\
   \Rightarrow x = \frac{{v(u - 1)}}{{{u^2} - 1}} = \frac{v}{{u + 1}} \hfill \\
  v = x + y \Rightarrow  \hfill \\
  y = v - x = v - \frac{v}{{u + 1}} = v(1 - \frac{1}{{u + 1}}) = v \cdot \frac{u}{{u + 1}} \hfill \\
  x = v \cdot \frac{1}{{u + 1}} \hfill \\
  y = v \cdot u\frac{1}{{u + 1}} \hfill \\
\end{gathered} $$
3.) Transform boundaries:
$$\begin{gathered}
  x = 0 \Rightarrow v = 0 \hfill \\
  x = 1 \Rightarrow v = u + 1 \hfill \\
  y = 0 \Rightarrow v \cdot u = 0 \Rightarrow u = 0 \vee v = 0 \hfill \\
  y = x \Rightarrow u = 1 \hfill \\
\end{gathered}$$
4.) Integrate:
$$\begin{gathered}
  \int\limits_0^1 {\int\limits_0^x {(x + y){e^{x + y}}\frac{1}{{{x^2}}}dydx = \int\limits_0^1 {\int\limits_0^{u + 1} {{e^v}dvdu} } } }  = \int\limits_0^1 {({e^{u + 1}} - 1)du}  \hfill \\
  \int\limits_0^1 {({e^{u + 1}} - 1)du}  = {e^2} - e - 1 \hfill \\
\end{gathered}$$
Answer: $ \int_{0}^{1}\int_{0}^{x}\frac{(-v^{2})e^{(v)}}{{x^{2}}}dudv $
$ y=u x,  v=x + u x= (1+u)x,  x=v/(1+u) , $  plug in for x
$ \int_{0}^{1}\int_{0}^{x} -e^v (1+u^2) du dv $


Why is the 'values' array not set on an unsaved entity? Is there a way to make it get populated?

Question: When I load an entity, its protected 'values' property contains all of its field values.
But when I create a new entity with MyEntityClass::create($array_of_values), its 'values' property is not set until I have saved it.
Is there a way to get that set, for the purposes of debug output?
Answer: The code comments in ContentEntityBase say that $values always hold the original, unchanged values of the entity:
/**
 * The plain data values of the contained fields.
 *
 * This always holds the original, unchanged values of the entity. The values
 * are keyed by language code, whereas LanguageInterface::LANGCODE_DEFAULT
 * is used for values in default language.
 *
 * @todo: Add methods for getting original fields and for determining
 * changes.
 * @todo: Provide a better way for defining default values.
 *
 * @var array
 */
protected $values = [];

Quick glance through the code suggests that the public method updateOriginalValues() would do the trick:
/**
 * Updates the original values with the interim changes.
 */
public function updateOriginalValues() {
  if (!$this->fields) {
    return;
  }
  foreach ($this->getFieldDefinitions() as $name => $definition) {
    if (!$definition->isComputed() && !empty($this->fields[$name])) {
      foreach ($this->fields[$name] as $langcode => $item) {
        $item->filterEmptyItems();
        $this->values[$name][$langcode] = $item->getValue();
      }
    }
  }
}

Comment: Calling $entity->updateOriginalValues() works perfectly! Thanks!


Show that $Y$ is not first-countable at $[0]$

Question: (a) Show that $X := \{0, 1\}^{\mathbb R}$ is not first-countable.
(b) Let $X := \bigcup_{n=0}^∞ [2n, 2n + 1]$ be a union of countably many disjoint closed intervals. Let $Y$ be the quotient of $X$ obtained by gluing all the points $0, 2, 4, 6, \ldots$ together.
Show that $Y$ is not first-countable at $[0]$ (the equivalence class of $0$). Use a diagonalization argument.
My attempt:
$(a)$ I proceeded indirectly by showing that there exists a real-valued function on some subspace of $[0,1]^{\mathbb R}$ that is sequentially continuous but not continuous. It is the case of $F(f) = \int_0^1 f(t) \, dt$ where $f$ is measurable.
$(b)$ But I don't know how to prove this part. Any help please?
Comment: See [this answer](https://math.stackexchange.com/questions/3907734/let-x-be-the-disjoint-union-of-copies-of-a-subspace-of-mathbbr-is-the-qu/3907748#3907748), which gives a fairly significant hint for proving that a certain subspace of your $X$ is not first countable at $[0]$. The same argument works here.
Comment: What is $Y$ in (a)?
Comment: Twice the same question: https://math.stackexchange.com/q/3915809
Answer: For (b): If $V=\{U_j:j\in \Bbb N_0\}$ is a countable set of nbhds of $[0]$ in $Y$ then for each $j$ there is a function $f_j:\Bbb N_0\to (0,1)$ such that $ U_j\supset (2n,2n+f_j(n))$ for every $n.$ Then $[0]\cup(\cup_{n\in \Bbb N_0}(2n, f_n(n)/2)\,)\,)$ is a nbhd of $[0]$ which is not a subset of any member of $V.$


Getting started with projection analysis

Question: For one of my grad school classes I am working on a projection analysis. The data includes projected year-end balances. These balances are projected every month of the fiscal year (starting in July and ending in June) to see how much approximately is the Y-T-D amount going to be. I'd like to analyze the projected balances vs. the actual Y-T-D balance.
I'd like to find a way to estimate at which month we are comfortable at saying that this is approximately what the Y-T-D amount is going to be. I thought of using confidence interval and normal distribution, but I can't figure out how to approach this.
Thank you.
Comment: To make sure I understand: you are projecting the end-of-fiscal-year balance each month and obviously the projection becomes more accurate as the fiscal year progresses (and you have fewer months to project to the end of the year)? And you want to determine how far into the fiscal year you have to be to have a "firm" estimate of that year's ending balance?
Answer: If you are projecting financial reports, look at this book.
If you are forecasting a time series, try an ARIMA or ETS model. The auto.arima(), ets(), bats() and tbats() functions in R's "forecast" package are pretty automatic.


Why can not we use Lagrange multiplier in mathematical (in particular linear) programming?

Question: I am studying linear programming right now. And I can not explain to myself why I can not solve any linear programming task using the Lagrange multiplier method.
Could you help me understand that, please?
Comment: Can you elaborate how you are going to do it in more detail?
Comment: Keep studying LP- you'll find that Lagrange multipliers do appear (with the new name of "dual variables.")
Answer: The basic method of Lagrange multipliers only works for maximizing over a set given by a system of equations. Any interesting linear program, on the other hand, will contain some inequalities, even if it's only the domain constraints of the form $x \ge 0$.
In a multivariable calculus class, you might learn to use Lagrange polynomials to deal with inequalities by doing casework: to deal with an inequality $ax \le b$, you can either set $ax=b$, or ignore the inequality and later check if it's satisfied. This corresponds to the "brute force" approach to linear programming, where we check all possible intersections of the inequalities and find which vertex is optimal.
You may have also seen the Karush-Kuhn-Tucker method, which generalizes the method of Lagrange multipliers to deal with inequalities. It can indeed be used to solve linear programs: it corresponds to using the dual linear program and complementary slackness to find a solution.
The special case of linear programming, however, is much nicer than the general case of the KKT method for solving nonlinear programs. It is better to first learn linear programming, and then see what features of the method do and do not extend to nonlinear programming.
Comment: `Any interesting linear program, on the other hand, will contain some inequalities` It is not a problem to move from inequalities to equalities. For example, if we have $\leq$ we can add a bogus positive variable to have an equality.
Comment: @hellohowdoyoudo The key word in your sentence is "positive": you will still need an inequality to enforce that your bogus variable is $\ge 0$. We still often introduce these variables, because it's convenient to only have *one* kind of inequality; however, you can't get rid of inequalities entirely.
Comment: Thank you. I got it.
Comment: So, the only difference between Lagrange multiplier method and mathematical programming is that in the latter we can have inequalities, while in the former we can have only equalities. Am I getting it correct?
Comment: The other major difference is that while we can optimize over all systems of equations with Lagrange multipliers, we need additional conditions to optimize over systems of inequalities. (See Wikipedia on the [KKT conditions](https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions).) So only some classes of problems can be solved in this way. (For example, the first condition, LCQ, is the condition saying that we can solve linear programs.)
Comment: Is it correct to say that Lagrange (KKT) method is applicable to all LP problems, however in large instances (multiple variables and constraints) it's inefficient?
Comment: this doesn't seem to be a good answer- inequalities are not the issue - I believe the issue is because we cannot enforce decision variables to be positive
Answer: I cannot give a complete answer, but I believe the accepted answer is not accurate.
Inequalities are not the issue - linear programs with inequalities are converted to equalities using slack and surplus variables.
I believe the issue is because we cannot enforce decision variables to be positive, using Lagrange. The principle advancement made by the Simplex method was to ensure positive values for decision variables, which is imperative for the algorithm to produce meaningful results.
Without enforcing positivity, one variable can shoot way positive and another variable can shoot way negative. As an example, given this:
x + y = 1;

we want something like 0.3 and 0.7, but with a smooth system we could get (-139393 + 139394), or literally any combination.
You might think, well we could solve this with slack variables:
x >= 0;
y >= 0;
which translates to:
x - s1 = 0;
y - s2 = 0;

but then we are back to square one, because we need to enforce s1 and s2 to be positive.
*note that in reality, by positive, we really mean non-negative, since variables can take on value of 0 in Simplex algorithms.
Comment: I think you missed my point. Nonnegativity constraints *are also inequalities*.
Comment: Your answer is misleading at best, just be honest with yourself for a second. If what you mean by inequalities is "non-negativity constraints on decision variables" then sure, but you need to edit your answer to make that more clear.
Comment: I *literally* mentioned "domain constraints of the form $x \ge 0$" in my answer.
Comment: Ok great, we can leave everything as is. The subtlety, is that in Simplex, it is not a formal constraint, it is an informal constraint, the algorithm simply does not visit negative values of decision variables.
Comment: You said "Nonnegativity constraints are also inequalities" - they are not the same, because in the Simplex algorithm, it's not a formal mathematical inequality - it's that the algorithm starts with a feasible non-negative point and never visits any negative values.
Comment: I know how the simplex method works. I have just finished teaching a semester-long class on how the simplex method works. What you're saying is more or less true (I would argue that it *is* a formal mathematical inequality, just one that the simplex method handles differently) but it is irrelevant to this question, which is asking about whether we can use *Lagrange multipliers* to solve linear programs, and those do not distinguish between these kinds of inequalities.
Comment: I think we are in agreement. I believe that Lagrange can solve almost all LPs, as there is some relationship between interior point algorithms and Lagrange methods. The difference has nothing to do with inequalities, because the equations are identical in both methods. Your answer is therefore misleading. Simplex and Lagrange/IPM operate on the same equations, but use a different algorithm. There are no inequalities when the algorithms start, just the same equations.
Comment: There *are* inequalities! If I tell you "maximize x subject to x+y=1" or "maximize x subject to x+y=1 with x,y>=0" then these are **two different problems**. You do not appear to understand this. Your answer is all about criticizing my answer for calling an inequality an inequality even though an unrelated algorithm treats that inequality in a special way. You are not really even answering the question that is actually being asked. (Anyway, I am bowing out of this discussion. Come back when your answer actually addresses Lagrange methods at all.)
Comment: Sorry for being critical, I am trying to be constructive.

There are no inequalities, they are always converted to equalities with slack variables and surplus variables. Your very first sentence is "The basic method of Lagrange multipliers only works for maximizing over a set given by a system of equations." The same is true for Simplex, etc.


Custom citation style with Jekyll Scholar

Question: I use Jekyll with Jekyll Scholar to serve a personal blog.
For a specific use case, I would like to show citations in-line in the text with the style: Authors (Year) Title and nothing else. So for example I want to get the following citation style:

Gu et al. (2017) Non-Autoregressive Neural Machine Translation

from the bibtex entry in my bibliography shown below.
Is there a Citation Style Language style that allows me to do exactly this? Is this available for example in github.com/citation-style-language/styles/?
More generally, is there a way I can generate inline citations with arbitrary custom styles by specifying the fields I would like to include and in what format/order?

@misc{https://doi.org/10.48550/arxiv.1711.02281,
  doi       = {10.48550/ARXIV.1711.02281},
  url       = {https://arxiv.org/abs/1711.02281},
  author    = {Gu, Jiatao and Bradbury, James and Xiong, Caiming and Li, Victor O. K. and Socher, Richard},
  keywords  = {Computation and Language (cs.CL), Machine Learning (cs.LG), FOS: Computer and information sciences, FOS: Computer and information sciences},
  title     = {Non-Autoregressive Neural Machine Translation},
  publisher = {arXiv},
  year      = {2017},
  copyright = {arXiv.org perpetual, non-exclusive license}
}

Answer: To show citations in-line in your Jekyll blog using the style "Authors (Year) Title", you can use the cite filter provided by Jekyll Scholar

For the key of the bibliography entry:
{% cite gu2017non-autoregressive %}
For the URL of the bibliography entry:
{% cite https://doi.org/10.48550/arxiv.1711.02281 %}

You can create a custom CSL style file and use it with Jekyll Scholar to generate citations in your blog posts as follows:

Create your custom CSL style file

Save this file as custom.csl.

Install the jekyll-scholar-csl gem and add it to your Gemfile

In your _config.yml file, set the csl option to the path of your custom CSL style file:
scholar:
 csl: /path/to/your/custom.csl

Use the {% cite gu2017non-autoregressive %} filter to display citations in your blog posts using the custom CSL style.


Code to count times to get all heads or all tails is returning only times to get heads

Question: I am pretty happy to say I think I have my first coin flip problem running. I am counting how many times it takes to get all heads or all tails in a trial of 7 flips. In theory it should take around 64 times to get either all heads or all tails.
coin.counter = 0                         ## initialize global counting variable
heads.tails = 0                          ## initialize global variable
while(heads.tails != 7|0){               ## do while not 7 or 0
  heads.tails = rbinom(1,7,.5)           ## 1 trial, 7 flips
  if(heads.tails != 7|0)                 ### NOT equal to 0 or 7
    coin.counter = coin.counter + 1
  else
    break
}

Unfortunately, I think that I am only getting one value because as I continue to run this script I keep getting coin.counter values in the mid 100s.
What can I try to fix this?
Comment: Questions asking "if this code is correct" are unfortunately considered off topic. When working with random function it's hard to check if answers are "correct." You to solve the problem mathematically and see if what your code returns seems roughly correct. But parts like `heads.tails != 7|0` don't look correct to me. You can't test for more than one value that way. You need `heads.tails != 7 & heads.tails != 0` or `!(heads.tails %in% c(0,7))`
Comment: BTW: while `heads.tails != 7|0` is technically legal R code, it's not what you want/think. What it's doing is `(heads.tails != 7) | (0)` which reduces to `heads.tails != 7` (since `0` is equivalent to `FALSE`). So is your function mathematically correct? Sorry, no, not until you follow @MrFlick's suggestino of using `%in%` or two comparisons (I prefer `%in%` personally). (`?Syntax` gives the order of operator precedence, and `!=` is above/before `|` and `||`.)
Comment: I tried so hard to make sure I had everything for my first post too.

Added R tag
Comment: ... and since that conditional is in an `if` block, don't use single `&`; while it'll work, it's misleading. `&` works with `logical` vectors (arbitrary length) while `if` blocks require length exactly 1. Also, `&` doesn't short-circuit, `&&` has the ability to short-circuit.
Comment: This is outstanding feed back. Thank you both very much. I ran it quite a few times this morning and consistent returns over 100 gave me the feeling I was closer to 1/128 instead of 1/64.

Also, to be a better patron of the forum, you mentioned this thread is off topic. Did I include the wrong tags?
Comment: I don't know that it's [*explicitly* off-topic](https://stackoverflow.com/help/on-topic), but it's not perfectly "on", either. Typically SO is about programming problems (errors, warnings, misbehavior), but you did not frame it that way. One way to reword this to bring it back into the intended realm is *"the results are wrong: I expect 1/128 but instead I get 1/64"* (and that would have been good information to know in the question itself).
Comment: Thank you r2evans! Title changed, target added and wishy washy talk removed.
Answer: Solution to the issue was to set the Heads.tails to NOT 0. Each time I added 0 to the loops as decision criteria the program instantly stopped because the variable was then already 0. I'm not a smart person but I try hard.
Posting the solution and hopefully it helps someone else down the line.
coin.counter = 0
### This was globally set to 0 and consistently shorting my program
heads.tails = 10  ## <- Set to dummy value so it quits messing with me

#####Loops#####
while(heads.tails != 7 & heads.tails != 0){    ## Courtesy 2revans and MrFlick
  heads.tails = rbinom(1,7,.5)                 ## 1 trial, 7 flips
  print(heads.tails)
  if(heads.tails != 7 & heads.tails != 0){
     coin.counter = coin.counter + 1           ### NOT equal to 0 or 7
  }
  else {
   break
  }
}


Usage StringBuffer and String?

Question: As known String is immutable in Java. I have the following method's body which return String:
Partner partner = context.getComponent(ComponentNames.PARTNER_COMPONENT_NAME);
String lastAccesDate = partner.getLastAccessDate();
if(lastAccesDate == null) {
    return "";
}
lastAccesDate = new SimpleDateFormat(DATE_PATTERN).format(); //1
return lastAccesDate;

The thing is because of string immutability, a new String object will be created at //1, so actually I'll have two String Objects, the first one contains partner.getLastAccessDate();, the second one new SimpleDateFormat(DATE_PATTERN).format();. The overhead is not good, how can I avoid it?
Comment: Use StringBuilder instead of String
Comment: @Sharpedge Why don't a StringBuffer? One's mutable, so we can modify the string it contains.
Comment: from java docs **"Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization."**
Comment: What does `lastAccesDate = new SimpleDateFormat(DATE_PATTERN).format();` do? The `format` method must have a `Date` as an argument. Also, although it is true that a new `String` is created when using the format (I looked at the Java source code) this is not because of String immutability, but **despite** immutability. It is theoretically possible that the `format` method would call `String.intern(String)` in order to save memory since the `String` cannot be changed anyway.
Answer: Use StringBuffer in case of multithreading(i.e. if you need a thread-safe, mutable sequence of character) otherwise use  StringBuilder
Comment: This method is from the web application, so I do use StringBuffer, don't I?
Comment: @St.Antario it depends if you are creating the Object inside the method something like `public void foo() {StringBuilder sb=//....}` then `StringBuilder` is the choice to go because the object will be created on stack and every thread will have it own so no problem. But if you need to declare the object outside the method i.e. on the heap then StringBuffer is must
Answer: see when you assign second time string to the String object lastAccessDate, there is no overhead as automaticaly garbage collector will free the space which occupied by first object because no object has reference to the same. so no need to worry about overhead

Usage StringBuffer and String?


Como subir arquivo via ajax com Rails 4?

Question: Quero transferir um arquivo pdf para processar no meu controlador e depois retorná-lo, enquanto ele fica sendo processado no backend, gostaria que aparece uma barra ou círculo de carregando. Entretanto, estou tendo problemas em como enviar o arquivo assincronamente. Como eu faço para enviar um arquivo assíncrono através do Rails 4?
Answer: https://www.sitepoint.com/asynchronous-file-uploads-rails/
https://github.com/JangoSteve/remotipart
https://medium.com/rails-ember-beyond/ajax-file-upload-in-rails-using-dropzone-and-carrierwave-6f5436fdfdb0#.4paxrz751
Existe várias soluções para fazer isso. Hoje eu utilizo a solução a CarrierWave + DropDzone

Felipe,
O método do POST/PUT do HTTP permite você fazer uma conexão client & server de arquivos binários.
Para que você consiga fazer o seu controlador aceitar esse tipo de arquivo você terá que preparar um MODEL faça a captura deste arquivo para o transforme no arquivo desejado "PDF, JPG,PNG....
model/asset.rb
class Asset < ActiveRecord::Base
  belongs_to :assetable, polymorphic: true
  mount_uploader :file, FileUploader
end

lembra de olhar como configurar o carrierwave

http://railscasts.com/episodes/253-carrierwave-file-uploads
model/nfes.rb
has_one :asset, :class_name => "Asset", as: :assetable, dependent: :destroy

NfesController.rb
respond_to :html, :xml, :json, :js
...
private
def nfe_params
  params.require(:nfe).permit(:build_id, :due_at, asset_attributes:[:id, :file])
end

views/new.html.slim
form_for @nfe, html: { multipart: true, class: "dropzone"}, method: :post do |f|
  div.fallback
  - f.object.build_asset if f.object.asset.blank?
  = f.fields_for :asset  do |asset|
  = asset.file_field :file
  = f.submit "Upload"

Comment: Olha que diferença...
Comment: Minha dúvida é como ele faz pra subir o arquivo e quando eu clico no `submit`, ele mudar o conteúdo da página, você poderia dar um exemplo aqui?
Comment: @Breno Perucchi evite postar apenas links como respostas, coloque as partes relevantes na sua resposta.
Comment: @magicHat A pergunta foi muito genérica. Não envolvia, como resolver isto ou estou com problema nisso e sim gostaria de uma solução para isso. Não sabia que links não eram apropriados para respostas.
Comment: Eu penso quando for assim melhor colocar no comentário... Sei lá...Mas o fato de colocar os links, é pq se sai do ar, ai fica quebrado,,,
Comment: @MagicHat postei algo consistente
Comment: @FelipeAvelar funcionou?


Connecting to Db2 on z/OS via JDBC using IBM JDK vs OpenJDK

Question: I am able to connect to Db2 on z/OS with the IBM universal JDBC driver file db2jcc4.jar using IBM JDK 1.8 that is bundled with WebSphere 9. Every thing works fine and I can browse the catalog and execute queries. I used Squirrel SQL version 4.0.0.
But when I switch my JDK to the Open JDK 8 or 12 while keeping everything else the same, I get the following error. What should be done to fix this error? What is the difference between IBM JDK and Open JDK, which causes the DB2 connection to work with one JDK and fail with the other?
Comment: Is the z/OS database using `DATA_ENCRYPT`? Is this a direct connection or via Db2 Connect?
Comment: This question is more about configuration than programming. Ensure the openjdk has the unlimited cryptographic key length enabled. Ensure the required security providers are enabled in the java.security.  Don't hide error codes/error messages in graphics, they are not searchable, instead copy paste as plain text in your question.
Comment: Probably server certificate is not present in the keystores that comes with non-IBM JDKs.
Comment: @kkuduk : I do not know that. Since I at least have a way to connect to the database using the IBM JDK and Squirrel SQL; Is there a way I can find out if it is DATA_ENCRYPT?
Answer: Here is one of matching articles of your case:
JDBC application may receive error "Security mechanism not supported"
https://www.ibm.com/support/pages/jdbc-application-may-receive-error-security-mechanism-not-supported
Resolving The Problem
Set the following property :
securityMechanism = ENCRYPTED_USER_PASSWORD_AND_DATA_SECURITY (13)
Alternatively you can set property retryWithAlternativeSecurityMechanism to YES(1).
Hope this helps.
Comment: I tried both the properties. But neither of them solves my issue of connecting to the Db2 on z/OS using OpenJDK.
Comment: Sad news.  Now, the issue may be related to OpenJDK so it is recommended to use IBM JDK.
Answer: According to IBM's documentation for their IBM Data Server Driver for JDBC and SQLJ, error code -4214 is an "Authorization failed" error -- and you know that much. But you can get more specific information about the problem if you call SQLException.getMessage. I think you may have done that already, but it's not entirely clear.
My semi-educated guess is that you haven't yet followed the configuration steps in IBM's driver documentation in the section "Configuring the Java Runtime Environment to Use SSL":
https://www.ibm.com/support/knowledgecenter/SSEPGG_11.5.0/com.ibm.db2.luw.apdv.java.doc/src/tpc/imjcc_t0054066.html
You'll have to apply some common sense knowledge to those instructions to adapt them for the OpenJDK, and this might not be an IBM supported combination depending on what/how you do it. If you can somehow use the IBMJSSE2 Provider, that'd be nice.
I think Mao and Mustaccio probably have the right ideas, and probably you're just missing the server certificate in your truststore. The instructions linked above walk you through how to configure that.