Check em Radio button com dados de BD

Question: Estou tendo problemas ao pegar os dados do banco e passar via session para meu form, todos os dados inputados estão vindo corretamente, somente não consigo passa-los como check para os meus radios... testei de varias formas, umas delas foi:

                    <input type='radio' tabindex="1" class="tipo_pessoa" checked="checked" name='tipo_pessoa' id='fisica' value='fisica' />Pessoa Física

                    <input type='radio' tabindex="2" class="tipo_pessoa" name='tipo_pessoa' id='juridica' value='juridica' />Pessoa Jurídica

<?
$value=$row['tipo_pessoa'];

$checked1=($value=="fisica")?'checked':'';
$checked2=($value=="juridica")?'checked':'';
?>

<input type="radio" name="tipo_pessoa" value="fisica" <?php echo $checked1; ?> />
Fisica

<input type="radio" name="tipo_pessoa" value="juridica" <?php echo $checked2; ?> />
Juridica
Answer: Apenas adicione o checked
checked="<?php echo $checked1; ?>"

Vai ficar assim:
<input type="radio" name="tipo_pessoa" value="fisica" checked="<?php echo $checked1; ?>" />
Fisica

<input type="radio" name="tipo_pessoa" value="juridica" checked="<?php echo $checked2; ?>" />
Juridica

Comment: O navegador interpreta o mesmo resultado para os dois tipos de sintaxe . OR  Se existir alguma diferença, explique-me por gentileza
Comment: está apresentando mesmo problema de antes... ele fica com o checked sempre somente no juridica mesmo quando o user está como pessoa fisica
Answer: Verifiquei que se você carregar a página pelo F5 no Firefox, ele não obedece a regra estipulada, e sim deixa selecionado sempre o último(deve armazenar em cache). Mas se você recarregar com ENTER ou CTRL+F5, ele obedece a regra. Já no Chrome, funcionou normal.

Segue abaixo um exemplo:
 <?php
        $row['tipo_pessoa'] = 'juridica';
        ?>

                        <input type="radio" name="tipo_pessoa" value="fisica" <?= ($row['tipo_pessoa'] == 'fisica') ? 'checked' : '' ?> />Fisica

                        <input type="radio" name="tipo_pessoa" value="juridica" <?= ($row['tipo_pessoa'] == 'juridica') ? 'checked' : ''  ?> />Juridica

Minha sugestão: se continuar a persistir o "problema", faça a manipulação pelo DOCUMENT.

Check em Radio button com dados de BD


How do professional electronic musicians/sound engineers combat listening fatigue?

Question: As an amateur bedroom composer working in a DAW on my song, I might have a general idea of how something ought to sound, but through endless 'random walking through knob space' - i.e. tweaking different values on the synth while listening to the same part on repeat - eventually I get hyper-familiar with the tune and everything sounds much of a muchness. I reach a point where I think the sound is good enough and leave the project for a few hours. Once I've forgotten the tune, I come back to it and play it from the beginning and it sounds awful.
I'm wondering how professional electronic musicians or sound engineers deal with such effects when they become hyper-accustomed to what they're listening to. These people presumably operate under deadlines, and so taking multi-hour breaks to 'forget' the recent piece of work just can't be feasible.
Is it just a matter of taking regular short breaks and being disciplined about stopping when you can no longer tell if you're making a positive difference? Or are there other tricks involved, like listening to similar/totally different music to 'reset'?
Comment: There's nothing unique in this question to electronic producers/composers, specifically.
Comment: I mean, yes it is possible to continually play an analogue instrument to fatigue, but that requires physically playing it each time, and furthermore analogue instruments don't have that infintesimal control over various aspects of their precise sound. It is altogether far too easy to set your electronic composition to repeat a single bar, then tweak knobs until all memory of silence has left you.
Comment: @b3ko Exactly, and the second group's solution to listening fatigue is invariably to turn up the volume.
Answer: One of the most common pieces of advice I hear about this is to take breaks. You're right that in some situations (extremely tight deadlines, for example) this may not be practical, but in reality, it's the best way to achieve the results you hope for.
Listening fatigue is a real thing, and the phenomenon you describe, coming back to a song you liked only to discover it's awful, is very common. It's so common, in fact, that I often hear advice stressing to leave the project for days, not just hours, and come back to listen to it again with "fresh ears."
Comment: In my experience taking breaks actually helps you make the deadline. The delays caused by not taking breaks are longer than the breaks.
Comment: I do that. It's recommendable, more if you are working on related songs, say, all belonging to the same album, where you want to sound coherent, that approach can make you try things which can later somehow be translated to another song, and that you would not see otherwise.
Comment: Interesting, this is kind of what I expected. I wonder if working on two completely separate songs and dividing your workflow between them whenever your ears get tired is an approach that anybody uses.
Answer: Taking breaks has been mentioned, and is obviously a good idea!
Other ideas:

A change is as good as a rest: work an a different project for a while, and come back to the first one
listen to other music in a similar style - or even a different style - to  get your bearings again, and tune yourself back in to what's normal
listen on different systems, and at different volume levels. If you're feeling tired, that might be a good moment for the 'how does it sound in the car?' check.
don't listen too loud for too long - temporary hearing loss won't help you, and nor will permanent hearing loss
pay attention to more general health stuff: nutrition, hydration, sleep, exercise. It's possible to die playing video games for days on end; I'm not sure I've heard of it happening from tweaking a mix for days, but you don't want to be the first!
Answer: 3d12 and topo morto covered most of it, but having a good set of (correctly positioned) studio monitors also makes a huge difference. You can mix more effectively and at a lower volume, and you tend to spend less time wandering down the wrong path because you can identify problems more precisely.
I make somewhat bottom-end heavy industrial electronica but with vocals and a more rock-like format. I recently upgraded to a pair of Yamaha HS-8s that have good even frequency response down to 40Hz. Suddenly I realized that a lot of my problem was being unable to properly hear the separate components of the track to be able to mix correctly and get bits out of the way of each other, and that my old speakers and headphones had terribly uneven EQ (even the best headphones start to lose their highs within a few years), but in opposite directions - so a mix done on speakers would sound terrible in headphones, and vice versa.
Comment: Agreed.  I tend to spend most of my mixing time trying to get to a point where I can hear each track clearly.  I treat it like a hearing test and use the lowest possible volume where I can still hear all the tracks.  As I turn down the master fader even more, the first track to drop out of the mix is the one that is lower than all the others.

Once I'm able to at least hear everything and have some rough sense of balance among the tracks, I can make a second -- much shorter -- pass at a moderate / high volume to check if any track is overly emphasized.

I'm not a professional; YMMV.
Comment: @KyleKrull that's a very interesting technique! But I'm not sure if it's really good for all styles. In many tracks there are elements that you don't really _hear_ except at ideal conditions, but they nevertheless contribute to the result in important ways.


Existe diferenças entre Post e Request?

Question: Quando eu leio a respeito do request sempre me aparece o termo post junto, e isso me gera uma dúvida. Eu compreendo que o request serve para fazer um pedido de algo para o servidor e depois o servidor envia uma resposta após processar o tal pedido, e ao ler a respeito do post me parece que ele faz a mesma coisa, e é neste ponto que gera a dúvida, eu não consigo entender a diferença entre eles.

Pergunta
Eu gostaria de saber se existe diferença entre Request e Post, caso exista, gostaria de saber quais são as principais diferenças entre eles e também a principal finalidade do Post?
Fiquem a vontade para dar exemplos práticos em qualquer linguagem de programação caso queiram.
Comment: Algumas coisas relacionadas: http://pt.stackoverflow.com/q/118213/101, http://pt.stackoverflow.com/q/49322/101, http://pt.stackoverflow.com/q/93308/101, http://pt.stackoverflow.com/q/9419/101, http://pt.stackoverflow.com/q/92870/101
Comment: No PHP pelo menos, `$_POST` é os dados vindo do formulário (método `POST`). `$_REQUEST` é a mistura dos dados `Post`, `Get`, `Cookie`. É a primeira coisa que vem a mente :D
Comment: Será que a tua duvida é entre Post e Get? Ou ambas?
Comment: @Sergio estou estudando Http, ainda sei sei o que é Get, se para entender a diferença entre Post e Request seja necessário entender o que é Get, pode explicar sobre ele tbm :).
Comment: post e um metodo de requisicao existe outros varios tipos de de metodo como get put header se voce quiser vc pode ate criar o seu acho qu e isso requisicao e o que todos clientes http fazem entre outros protocolo agora post e so um metodo dessa requisicao voce pode testar suas requisicoes nesse site https://httpbin.org/
Answer: O request é uma forma genérica de se referir ao assunto, podemos usar a tradução que será tão bem ou melhor entendido que é uma requisição de informação ao servidor. Tem diversas maneiras de realizar uma requisição. O termo poderia ser usado em outros contextos e indicar a mesma coisa, ele não tem um significado específico na tecnologia, é só uma palavra necessária para dar entendimento ao que está sendo usado. Nesse contexto é uma requisição usando HTTP.
Em HTTP, entre as diversas formas de realizar a requisição, tem o verbo usado para requisitá-lo. Cada verbo tem sua semântica própria de funcionar. Um desses verbos é o POST. Então esse termo é uma forma bem específica, com regras próprias de como fazer a requisição. Então esse é um termo com significado técnico definido em especificação.
Eu dei uma resposta diferenciando sobre POST e PUT que mostra os principais detalhes do POST.
Tem outra com informações básicas sobre os demais verbos. E a importância de usar os verbos corretos. Todos esses verbos são métodos de requisição.
Pode entender melhor todo esse funcionamento na pergunta sobre CGI.
Coloquei no GitHub para referência futura.
Answer: Complementado a resposta com um exemplo em PHP.

POST
O post utiliza a URI (Uniform Resource Identifier) para envio de informações ao servidor, que por não ser retornável ao cliente, torna o método mais seguro, pois assim não expões os dados enviados no navegador.
A partir do post é criada toda a estrutura do formulário necessária para o funcionamento das aplicações web. Com ele é possível obter os dados de um determinado campo:
<FORM NAME="form1″ METHOD="post" ACTION="pagina.php">
   Campo 1:
   <INPUT TYPE="text" NAME="campo1″>

   Campo 2:
   <TEXTAREA NAME="campo2″></TEXTAREA>

   <INPUT TYPE="submit" VALUE="Enviar">
</FORM>

<?php
   echo("O valor do primeiro campo é " . $_POST['campo1']);
   echo("O valor do segundo campo " . $_POST['campo2']);
?>

REQUEST
$_REQUEST, por padrão, contém o conteúdo do $_GET, $_POST and $_COOKIE. Ele é chamado de coleção genérica, pois nele é retornado o valor da
variável, de acordo com a configuração do arquivo php.ini:
<FORM NAME="form1″ METHOD="post" ACTION="pagina.php?x=1″>
   <INPUT TYPE="text" NAME="txtCampo1″ VALUE="Valor do Campo Texto">
   <INPUT TYPE="submit" VALUE="Enviar">
</FORM>

<?php
   echo($_REQUEST['v']);
?>

Veja essa resposta do stackoverflow em inglês.

Referências:

Diferença entre os métodos GET e POST
GET, POST, REQUEST

Existe diferenças entre Post e Request?


Preencher Data Grid View com propriedade de objetos

Question: Tenho um formulário onde preciso preencher um DataGridView com os dados de uma lista de usuários. Para gerar esses dados, usei 3 classes:
Classe Usuário
namespace TesteDataGridView
{
    public class Usuario
    {
        public int id { get; set; }
        public string login { get; set; }
        public string nome { get; set; }
        public Perfil perfil { get; set; }

        public Usuario()
        {
            //Cada usuario que eu crio obrigatoriamente já cria seu perfil
            perfil = new Perfil();
        }
    }
}

Classe Lista Usuario
using System.Collections.Generic;

namespace TesteDataGridView
{
    public class ListaUsuarios : List<Usuario>
    {
    }
}

Classe Perfil
namespace TesteDataGridView
{
    public class Perfil
    {
        public int id { get; set; }
        public string descricao { get; set; }
    }
}

Arquivo do Formulário:
using System;
using System.Windows.Forms;

namespace TesteDataGridView
{
    public partial class Form1 : Form
    {
        ListaUsuarios lstUsr; //Cria uma lista de usuários

        public Form1()
        {
            InitializeComponent();

            //Instancia a lista de usuários
            lstUsr = new ListaUsuarios();

            //Não habilita a geração a
            dgv.AutoGenerateColumns = false;
        }

        private void btnCriaListaUsuarios_Click(object sender, EventArgs e)
        {
            //cria alguns usuários e adiciona na lista
            Usuario u1 = new Usuario();
            u1.id = 1;
            u1.login = "usr1";
            u1.nome = "usuario1";
            u1.perfil.id = 3;
            u1.perfil.descricao = "operador";

            lstUsr.Add(u1);

            Usuario u2 = new Usuario();
            u2.id = 2;
            u2.login = "usr2";
            u2.nome = "usuario2";
            u2.perfil.id = 2;
            u2.perfil.descricao = "lider";

            lstUsr.Add(u2);

            Usuario u3 = new Usuario();
            u3.id = 3;
            u3.login = "usr3";
            u3.nome = "usuario3";
            u3.perfil.id = 1;
            u3.perfil.descricao = "administrador";

            lstUsr.Add(u3);
        }

        private void btnPreencheGrid_Click(object sender, EventArgs e)
        {
            dgv.DataSource = null; //Limpa o grid;
            dgv.DataSource = lstUsr;
            dgv.Refresh();
        }
    }
}

No meu DataGridView, na propriedade DataPropertyName, eu configuro da seguinte forma o nome das colunas e o que deve ser apresentado nelas:
Column1 -  ID do Usuário     => DataPropertyName: id;
Column2 -  Nome do Usuário   => DataPropertyName: nome;
Column3 -  Login do Usuário  => DataPropertyName: login;
Column4 -  Perfil do Usuário => DataPropertyName: perfil.descricao;

Com as 3 primeiras colunas, tudo bem, mas a coluna de perfil, não é preenchida deixando o meu datagridview ficando assim:

Achei uma solução, onde falavam para fazer um override no método toString da classe Perfil e configurar o DataPropertyName da coluna 4 como "perfil", mas não achei muito legal, vejam:
namespace TesteDataGridView
{
    public class Perfil
    {
        public int id { get; set; }
        public string descricao { get; set; }

        // Solução encontrada, fazer um override no método ToString()
        // Não achei muito legal...  :(

        public override string ToString()
        {
            //return base.ToString();
            return descricao.ToString();
        }
    }
}

Onde estou errando?
Answer: O seu problema deve-se ao facto da DataGridView, quando está a popular as TextBox, invoca o método .ToString() dos objectos que a vão popular. Daí a solução que encontrou consiste em fazer override de .ToString() de forma a devolver o que pertende mostrar.
A solução ideal seria a DataGridView mostrar dados de duas datasources diferentes, o que no entanto não é possivel.
Assim, uma forma de resolver o seu problema seria, na altura de popular a DataGridView criar um novo tipo anonimo com recurso a LINQ e preencher a DataGridView com o tipo anónimo.
var newList = lstUsr.Select(usuario => new
{
    Id = usuario.id,
    Nome = usuario.login,
    LoginNome = usuario.login,
    PerfilDescricao = usuario.perfil.descricao
}).ToList();

Alterando o seu método:
    private void btnPreencheGrid_Click(object sender, EventArgs e)
    {
        var novaListUsuario = lstUsr.Select(usuario => new
            {
                Id = usuario.id,
                Nome = usuario.login,
                LoginNome = usuario.login,
                PerfilDescricao = usuario.perfil.descricao
            }).ToList();

        dgv.DataSource = null; //Limpa o grid;
        dgv.DataSource = novaListUsuario;
        dgv.Refresh();
    }

Para esta alteração funcionar é necessario editar a DataGridView e mudar a DataSource para (none) no editor, assim como editar cada uma das colunas que pertende.
Ou seja, em cada uma das colunas, altere a DataPropertyName para coincidir com o nome da propriedade no tipo anónimo criado com que pertende popular a coluna.
(Pergunta similar no SO)
Comment: Perfeito Omni, funcionou exatamente como eu precisava.


CFA: chi-square value is 0 but with degrees of freedom

Question: I want to do a SEM analysis with an actor-partner interdependence model in Mplus. I managed to calculate it and everything seems right if I look at the means, SD's, effects, etc. But I have a problem with the model fit.
The fit indices are weird, and too good... So there must be something wrong with it. I read that if one has a chi-square value of 0 as well as 0 degrees of freedom, the model is saturated and therefore a model fit test isn't done. But even though my chi-square value is 0, my df is 12. Also all other model fit indices are perfect. This can't be right.. Does anyone know what the problem might be, or what this tells me? Because to be quiet frank, I have no plan. And I can't seem to find any information on it...
Please, please, please help me!
Best,
Annie
This is the output:
MODEL FIT INFORMATION
Number of Free Parameters                       15
Loglikelihood
      H0 Value                        -927.087
      H1 Value                        -927.087

Information Criteria
      Akaike (AIC)                    1884.173
      Bayesian (BIC)                  1928.082
      Sample-Size Adjusted BIC        1880.627
        (n* = (n + 2) / 24)

Chi-Square Test of Model Fit
      Value                              0.000
      Degrees of Freedom                    12
      P-Value                           1.0000

RMSEA (Root Mean Square Error Of Approximation)
      Estimate                           0.000
      90 Percent C.I.                    0.000  0.000
      Probability RMSEA <= .05           1.000

CFI/TLI
      CFI                                1.000
      TLI                                1.000

Chi-Square Test of Model Fit for the Baseline Model
      Value                             90.763
      Degrees of Freedom                    14
      P-Value                           0.0000

SRMR (Standardized Root Mean Square Residual)
      Value                              0.000

Comment: What is your model? What are your variables? 15 is a lot!  Are they continuous or categorical? Have you looked for complete separation?
Comment: @PeterFlom: There are 15 parameters as I am estimating an APIMeM, with two people in one model. The variables are 2x interpersonal mindfulness as independent variable (1x actor, 1x partner), 2x  coworker exchange as mediators (actor, partner) and 2x work engagement (actor, partner). The APIMeM includes dyadic covariances between independent variables, error terms of the mediators and between the dependent variables. It also specifies the following effects of the dyad to be equal: actor effects, partner effects, predictor means, predictor variances, outcome intercepts, and residual variances...
Answer: You are correct to conclude that a $\chi^2$ value of 0 is odd when df > 0, though that does not mean it is impossible. From your description of the model in the comments, your model does appear to be quite complex. I would first check your mplus syntax to see if a mistake was made, and if not, I would consider a simpler model. My reasoning for this is that it is possible your model is misspecified. Try freeing or fixing paths you believe are not central to your research question and see how it changes your results. Additionally, you could check if any of your sample variables have constant values (i.e., everyone in your dataset has the same value for a particular variable), as this can often lead to odd results (this has happened to me!). Finally, you could try to use Bayesian estimation, which is easy to implement in mplus. If you do this, be cautious. First, because the use of Bayesian methods does not "fix" any potential issues related to misspecification, and second, because the mplus default priors$^1$ may not be appropriate for your data (e.g., MacCallum, Edwards, & Cai, 2012).
$^1$ Note that naive use of default priors is not only an issue with mplus but with all Bayesian software packages that don't require explicit prior specification.
References
MacCallum, R. C., Edwards, M. C., & Cai, L. (2012). Hopes and cautions in implementing Bayesian structural equation modeling.


Checking health of Kafka Stream Threads

Question: When some of the stream threads die (because of an exception for example), I don't want to continue, but restart the process.
In order to do this, I need to identify this state.
I know I can use kafkaStream.state(), but it checks the state of the whole kstreams. Meaning if only one StreamThread has died, it will not be discovered by kafkaStream.state().
What is the best way for me to know in the code that all StreamThreads are alive and working?
Answer: Update : adding timeout to KafkaStreams#close() as it can cause deadlock as Matthias stated in the comment
If you want to detect if any StreamThreads has dies then you can use KafkaStreams#setUncaughtExceptionHandler(), you can stop streaming and exit app:
kafkaStreams.setUncaughtExceptionHandler((t, e) -> {
    logger.error("Exiting ", e);
    kafkaStreams.close(10);
    System.exit(1);//exit with error code so container can restart this app
});

Comment: You should not call `close()` without timeout in the handler! It might result in a deadlock (Cf. https://issues.apache.org/jira/browse/KAFKA-4366)

Checking health of Kafka Stream Threads


How to make a slideshow of Views?

Question: i want to make a slideshow block of two views.
view 1 is 'most popular blog posts', showing 10 titles with date and no. of times viewed.
view 2 is 'most commented blog posts', showing 10 titles with date and no. of comments.
I'll put the slideshow block on the front page, it will show view 1 first then after 5 seconds, it will show view 2.
How?
Answer: By using the Views slideshow module.

Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
Answer: Use this and all your problem get solved: https://www.drupal.org/project/views_slideshow_jcarousel
Answer: You can do this by using jCarousel module.

This module allows developers and themers to make use of the jCarousel
  jQuery plugin. It includes a developer API that other modules can use,
  as well as Views integration in the 2.0 version so that you can turn
  any list of content or images into a carousel.

Enable the module
Goto View -> Select Format of type jCarousel
Configure the settings
Answer: You can use Views Slideshow module for views sliding.
click here for module installation SlideShow Module
and  Click Here and follow those steps to how to install slideshow module and configure the module in your site.

How to make a slideshow of Views?


Getting Google map to properly load before jQuery Mobile page is shown

Question: Issue:
I have a dialog page in a jQuery Mobile document which contains a small Google map to show a location. I want to load the map before loading the dialog page. As in:
$("#dialogPage").bind("pagebeforeshow", function() {
    initializeSmallMap();
});

However, Google Maps works incorrectly whenever the div the map is contained in is has a display proprety of none (see Google Maps Display:None Problem). And since this function is executed before the page is actually loaded, the containing div naturally has a display property of none.
Now, obviously, there's a simple solution to this. All I need to do is initialize the map after the page has been shown, which makes the div have a display property of block:
$("#dialogPage").bind("pageshow", function() {
    initializeSmallMap();
});

However, since the dialog has already been loaded, there is an annoying, noticeable flicker when the map appears.
Question:
How do I get rid of the described flicker?
Possible Solutions:
Making the div containing the map have a display property of block before the dialog is loaded. If I wasn't using jQuery Mobile, it would be simple and painless to implement this effect while still hiding the map until needed:
position: absolute;
left: -10000px;
display: block;

However, since jQuery Mobile automatically overrides page styles, I don't know how I could get this to work.
Explicitly telling the Google Maps API the size of the div containing the map. I Googled this option and had no luck, but considering my terrible Googling skills, I would not be completely surprised if this was actually possible.
Others - I'm open to any ideas on how to get rid of the flicker effect. The above are just some possible solutions.
Answer:  $("#dialogPage").promise().done(function() {
   //Code to execute when map is loaded.
 });

You could try it out. Just hide the element with the attr() and display it with attr() when promise().done is executed :) And you should be in no use of display properties.
Ref - Promise
Comment: I'm not sure how I would use this or whether not it could work. If I put it in the `pagebeforeshow` event, there will be no queued actions on the dialog page, and would therefore execute immediately. If I put it in the `pageshow` event, the page will have already loaded, and the flicker effect would therefore be noticeable.


Converting large symbolic Jacobian to LaTeX

Question: I have generated an 8x8 Jacobian, containing a few variables and several zeros as elements. I would like to translate this to LaTeX code. How can I first simplify what I have, to make it tractable?
Here is the Maple code:
eq_1 := Lambda-mu*S-(beta*(H+C+C1+C2)*S+tau*(T+C)*S)/(S+T+H+C+C1+C2+C1M+C2M);
eq_2 := (-beta*(H+C+C1+C2)*T+tau*(T+C)*S)/(S+T+H+C+C1+C2+C1M+C2M)-(mu+mu[T])*T;
eq_3 := (beta*(H+C+C1+C2)*S-tau*(T+C)*H)/(S+T+H+C+C1+C2+C1M+C2M)-(mu+mu[A])*H;
eq_4 := (beta*(H+C+C1+C2)*T+tau*(T+C)*H)/(S+T+H+C+C1+C2+C1M+C2M)-(mu+mu[T]+mu[A]+lambda[T])*C;
eq_5 := lambda[T]*C-(mu+mu[A]+rho[1]+eta[1])*C1;
eq_6 := rho[1]*C1-(mu+mu[A]+rho[2]+eta[2])*C2;
eq_7 := eta[1]*C1-(mu+rho[1]+gamma)*C1M;
eq_8 := eta[2]*C2+rho[1]*C1M-(mu+rho[2]+gamma*rho[1]/(rho[1]+rho[2]))*C2M;
J := VectorCalculus:-Jacobian([eq_1, eq_2, eq_3, eq_4, eq_5, eq_6, eq_7, eq_8], [S, T, H, C, C1, C2, C1M, C2M]);

JQDFE := eval(J, [S = Lambda/(beta-mu[A]), T = 0, H = Lambda*(beta/(mu+mu[A])-1)/(beta-mu[A]), C = 0, C1 = 0, C2 = 0, C1M = 0, C2M = 0]);

Thanks.
Answer: The Maple command simplify, with its size option supplied, reduces the length of the Matrix considerably.
You can also "factor" out a diagonal Matrix (scalars, from each row), and make a simple substitution of a sum of two variables, to get the length down by half again. That produces two Matrix factors f1 and f2 such that f1.f2=Q after resubstitution of R=mu+mu[A]. You might find that Matrices f1 and f2 prints ok. I'm not sure how "tractable" you need it.
restart:
eq_1 := Lambda-mu*S
        -(beta*(H+C+C1+C2)*S+tau*(T+C)*S)/(S+T+H+C+C1+C2+C1M+C2M):
eq_2 := (-beta*(H+C+C1+C2)*T+tau*(T+C)*S)/(S+T+H+C+C1+C2+C1M+C2M)
        -(mu+mu[T])*T:
eq_3 := (beta*(H+C+C1+C2)*S-tau*(T+C)*H)/(S+T+H+C+C1+C2+C1M+C2M)
        -(mu+mu[A])*H:
eq_4 := (beta*(H+C+C1+C2)*T+tau*(T+C)*H)/(S+T+H+C+C1+C2+C1M+C2M)
        -(mu+mu[T]+mu[A]+lambda[T])*C:
eq_5 := lambda[T]*C-(mu+mu[A]+rho[1]+eta[1])*C1:
eq_6 := rho[1]*C1-(mu+mu[A]+rho[2]+eta[2])*C2:
eq_7 := eta[1]*C1-(mu+rho[1]+gamma)*C1M:
eq_8 := eta[2]*C2+rho[1]*C1M
        -(mu+rho[2]+gamma*rho[1]/(rho[1]+rho[2]))*C2M:

J := VectorCalculus:-Jacobian([eq_1,eq_2,eq_3,eq_4,eq_5,eq_6,eq_7,eq_8],
                              [S, T, H, C, C1, C2, C1M, C2M]):
JQDFE := eval(J, [S = Lambda/(beta-mu[A]), T = 0,
                  H = Lambda*(beta/(mu+mu[A])-1)/(beta-mu[A]),
                  C = 0, C1 = 0, C2 = 0, C1M = 0, C2M = 0]):

length(JQDFE);
                                6483

Q:=simplify(JQDFE,size):

length(Q);
                                1421

F := Matrix(8,scan=diagonal,[beta/(mu+mu[A]),beta/(mu+mu[A]),
                             beta/((mu+mu[A]-beta)),beta,1$4]):

R = mu+mu[A];

f1:=map2( algsubs, (mu+muA) = R, subs(mu[A]=muA,F^(-1)) ):

f2:=simplify(subs(muA=mu[A], map2( algsubs, (mu+muA) = R,
                                   subs(mu[A]=muA,F.Q) )),size):

length(f2);

                                 781

LinearAlgebra:-Norm(simplify( subs( R=mu+mu[A], f1.f2 ) - Q ));
                                  0


Getting an image from an URL

Question: I'm trying to get an image from an URL in swift. The exact same method works in Xamarin (C#), but not anymore in swift. Other answers I've found don't work either (probably swift has been updated).
Debugging shows that the data is nil, but I can't understand why it would be..
This is my code in C#:
NSUrl url = new NSUrl ("https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t31.0-8/10688014_10152768605283809_1207583377417036990_o.jpg");
        NSData data = NSData.FromUrl (url);
        imageView.Image = new UIImage (data);

And this is my code in swift:
let url = NSURL(fileURLWithPath: "https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t31.0-8/10688014_10152768605283809_1207583377417036990_o.jpg")
    let data = NSData(contentsOfURL: url!, options: nil, error: nil)

    let imageView = UIImageView(frame: frame)
    let image = UIImage(data: data!)
    imageView.image = image

Can someone explain me what I'm doing wrong?
Comment: That error option is there for a reason. Try passing an error and see if it is populated after trying to create the NSData object.
Answer: NSURL fileURLWithPath takes path and not url. From NSURL documentation:

path should be a valid system path

Try using:
NSURL(string: "https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t31.0-8/10688014_10152768605283809_1207583377417036990_o.jpg")

Getting an image from an URL


Constructive proof of a statement about a property of a Lebesgue-null set

Question: I was studying some measure theory and upon searching for additional exercises on the internet I came upon one that said:

Given $H$ a Borel set subset of the real numbers, prove that if
$\lambda(H)=0$ (its Lebesgue measure) then there exists a number
$\alpha$ such that $\alpha + H$ , the set of all the reals of the form
$\alpha + h$ where $h \in H$, is a subset of the irrational numbers.

I had no problems in proving this statement, but the proof that I came up with is by contradiction and thus does not find the wanted number (which is not even unique, since it's provable that the set of all such real numbers is a Borel set with measure $+\infty$).
My question is, is it possible to find a constructive proof of this statement? Or maybe is it possible to find such a number for a special non trivial (like one made only of irrational or rational numbers) null set, for example the Cantor set?
Comment: For the Cantor set in particular, you can definitely write down an explicit $\alpha$ by thinking about base-$3$ expansions. There are some examples [here](https://mathoverflow.net/q/158378).
Comment: $H'=\cup_{r \in \mathbb Q}(r-H)$ has measure $0$, so there is a  point $\alpha$ which does not belong to it. This $\alpha$ does the job. [$r-H\equiv \{r-h: h \in H\}$].
Comment: That's basically my proof summarised, my question is it possible to give a proof which, in some sense, ables one to compute a number with the said property? Or if such a thing is not generally possible, if there is a specific null set for which such a number can be computed?
Comment: If $H=\{0\}$ then $\alpha =\sqrt 2$ will do.
Comment: Yea I guess I should edit my question to  exclude such trivial examples ahaha
Comment: Thanks, I will definitely look it up
Answer: (Of course it depends a bit on what exactly 'constructive' should mean, but)
Take for example $H :=$ all the computable (or arithmetical, or analytical, ...) real numbers, which is countable, so of course Borel and having measure $0$. Then, since rationals are computable and $H$ is a field, $\alpha$ must not belong to $H$, so existence of $\alpha$ is in particular existence of a non-computable number, which can be considered non-constructive


How is it possible for users to submit a node without a required image field?

Question: I am using Drupal 7 and I have defined a custom content type, Picture, which has only one required field, an image field.  I am using the default core image field with the Manual Crop module.  The number of images to be added is limited to one.  The field is marked as required.
If it matters, the title is not required because it is automatically generated by the Automatic Node Titles module.
I created this content type to allow users to upload their pictures to the site.  However, sometimes users are somehow able to create nodes of this content type that do not have any image file attached.  Since the image field is marked as required, I do not understand how Drupal can permit the creation of the node without such a file attached.  However, when I click edit, there is no file in the image file dialog box.
I have tried to debug this problem, but I am unable to create a node without an image file myself.  What kind of situation can cause this problem, or how can I debug it?
Comment: The automatic node titles probably unsets "required" on title. Could it have a bug that messes this up on other fields perhaps?
Answer: A contributed module was to blame-- the Manual Crop module.  Thankfully, the issue is already fixed.


parsing URL ?a=b params with VB.NET from plain string

Question: I am using a string to store key=value pairs, it has same format as QueryString
How can I easily parse it to array?  or can I somehow use interal class QueryString("paramname") to access it?
Answer: You could use the System.Web.HttpUtility.ParseQueryString, this will give you a NameValueCollection. You can then access your values easily
Dim keynameValue As String = nameValueCollection.Get("Keyname")

Answer: String.Split() probably will work for you....
Answer: ' parse to pairs
                Dim resultarray As Array = allresultdata.Split("&")
                Dim result1 As String
                Dim keyvals2 As Array
                For Each result1 In resultarray
                    keyvals2 = result1.Split()
                    keyvals.Set(keyvals2(0), keyvals2(1))
                Next

Answer:
or can I somehow use interal class
  QueryString("paramname") to access it?

If you need to access querystring from another class other then page code behind, use this :
HttpContext.Current.Request.QueryString("parameterName")


How to debug gunicorn failure issues? (Worker failed to boot)

Question: I have a Django web application that uses Gunicorn and runs good locally, but when I deploy app on EC2, I see that Gunicorn is failing:
 $ gunicorn_django -b 127.0.0.1:8000 --settings=myapp.settings.dev --debug --log-level info
 2012-09-16 17:39:24 [28333] [INFO] Starting gunicorn 0.14.6
 2012-09-16 17:39:24 [28333] [INFO] Listening at: http://127.0.0.1:8000 (28333)
 2012-09-16 17:39:24 [28333] [INFO] Using worker: sync
 2012-09-16 17:39:24 [28336] [INFO] Booting worker with pid: 28336
 2012-09-16 17:39:24 [28336] [INFO] Worker exiting (pid: 28336)
 2012-09-16 17:39:24 [28333] [INFO] Shutting down: Master
 2012-09-16 17:39:24 [28333] [INFO] Reason: Worker failed to boot.

I tried logging with --spew but it keeps on running and no error is shown.
How can I debug this issue?
Answer: Try running with --preload as an argument to gunicorn_django - it should show you the error the workers are having when starting. See this bug
Comment: I have been try to debug my service for hours, you just saved my day!
Comment: Glad to hear it :)
Answer: You need --debug --log-level debug
Comment: --debug is deprecated in gunicorn 19.0. See http://gunicorn-docs.readthedocs.org/en/latest/news.html#id28.
Comment: updated link for deprecated is: http://gunicorn-docs.readthedocs.io/en/latest/2014-news.html#id7
Answer: In my case I had to run gunicorn_django --bind example.com:8001 from the same folder as my manage.py file.


Could not find matching constructor error in my Builder Pattern

Question: I'm trying out Effective Java book and enjoying it. I read Builder pattern and I tried to play with it. I have a code like this (in Groovy):
public class Anto {
    public static void main(String[] args) {

            def testing = new Java.Builder(1).author("antoaravinth").build()
            println testing.author
        }
}

class Java {
    int version
    def author
    int release_number

    public static class Builder {
        int version

        def author = ""
        int release_number = 0

        public Builder(int version) {
            this.version = version
        }

        public Builder version(int version)
        {
            version = version
            return this
        }

        public Builder author(def author)
        {
            author = author
            return this
        }

        public Builder release_number(int release_number)
        {
            release_number = release_number
            return this
        }

        public Java build() {
            return new Java(this);
        }

        private Java(Builder builder)
        {
            version = builder.version
            author = builder.author
            release_number = builder.release_number
        }

    }
}

But I get error like this :
Caught: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Java(Java$Builder)
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: Java(Java$Builder)
    at Java$Builder.build(Anto.groovy:43)
    at Java$Builder$build.call(Unknown Source)
    at Anto.main(Anto.groovy:4)

I don't know why this happens! Where I went wrong?
Comment: Why not write a groovy builder rather than a fluent java style one? ;-)
Comment: @tim_yates: sure will give it a try... :)
Answer: This is your build() method:
public Java build() {
    return new Java(this);
}

Look at your Java class (not the Builder) - it doesn't have any explicitly-declared constructors, so the only constructor it has is the public parameterless one declared automatically for you.
You need to move this:
private Java(Builder builder)
{
    version = builder.version
    author = builder.author
    release_number = builder.release_number
}

outside the Builder class. (I'm slightly surprised Groovy didn't complain earlier, but I'm pretty sure that's the problem...)
EDIT: Now that it's not throwing an exception, look at your "setter" methods:
public Builder version(int version)
{
    version = version
    return this
}

The version = version line doesn't do anything. You need to differentiate between the parameter and the field, e.g.
public Builder version(int version)
{
    this.version = version
    return this
}

... or by giving the parameter a different name, e.g.
public Builder version(int value)
{
    version = value
    return this
}

Comment: Yes, that's a silly mistake. Now it works. But when I create a object using the `build` method: `new Java.Builder(100).author("aa").release_number(90).build()`, I guess there is some error in it. When I tried to print `author` value, I get **nothing** printed.


Pigeonhole Principle for 2 element subsets of X = {1,2,3,4,5,6 }

Question: "Consider the set $X = \{1,2,3,4,5\}$ and suppose you have two holes. Also suppose that you have 10 pigeons: the 2-element subsets of $X$. Can you put these 10 pigeons into the two holes in a way that there is no 3-element subset $S = \{a,b,c\} \subset X$ for which all pigeons go in the same hole? The answer the same question if $X = \{1,2,3,4,5,6\}$ with $15 = C(6,2)$ pigeons"
Currently working through Trotter & Keller and came across this problem. I can show the 10 pigeon case is possible but am unsure how to approach the 15 pigeon case with $$X = {1,2,3,4,5,6}$$
By the pigeonhole principle, there exists a hole with at least 8 pigeons but I am not sure how this is relevant to the question. I am conjecturing it has something to do with the fact that 8 is more than half the # of pigeons, while in the 10 pigeon case we had 5 pigeons in a hole by the PHP, where 5 is NOT more than 1/2 the total # of pigeons...
Comment: @BenjaminWang done thanks
Comment: Please copy the text into your question instead of using an image.
Comment: Can you post your solution to the $|X|=5$ case?
Answer: Hint: Did you know that in a complete graph of 6 vertices, with edges colored red or blue, there exists at least one (actually two) monochromatic triangles?


Python 3 Syntax Error with lambda

Question: I'm getting a syntax error following along side a tutorial. It feels like a Python 3 getcha. Thank you in advance!
def lda_description(review_text, min_topic_freq=0.05):
"""
accept the original text of a review and (1) parse it with spaCy,
(2) apply text pre-processing steps, (3) create a bag-of-words
representation, (4) create an LDA representation, and
(5) print a sorted list of the top topics in the LDA representation
"""

# parse the review text with spaCy
parsed_review = nlp(review_text)

# lemmatize the text and remove punctuation and whitespace
unigram_review = [token.lemma_ for token in parsed_review
                  if not punct_space(token)]

# apply the first-order and secord-order phrase models
bigram_review = bigram_model[unigram_review]
trigram_review = trigram_model[bigram_review]

# remove any remaining stopwords
trigram_review = [term for term in trigram_review
                  if not term in spacy.en.STOPWORDS]

# create a bag-of-words representation
review_bow = trigram_dictionary.doc2bow(trigram_review)

# create an LDA representation
review_lda = lda[review_bow]

# sort with the most highly related topics first
review_lda = sorted(review_lda, key=lambda (topic_number, freq): -freq)

for topic_number, freq in review_lda:
    if freq < min_topic_freq:
        break

    # print the most highly related topic names and frequencies
    print ('{:25} {}'.format(topic_names[topic_number],)
                            round(freq, 3))

The Error that pops up is this:
  File "<ipython-input-62-745b97e51bcb>", line 31
review_lda = sorted(review_lda, key=lambda (topic_number, freq): -freq)
                                           ^

SyntaxError: invalid syntax
Comment: Possible duplicate of [Understanding lambda in python and using it to pass multiple arguments](https://stackoverflow.com/questions/10345278/understanding-lambda-in-python-and-using-it-to-pass-multiple-arguments)
Comment: It's not a duplicate of the linked question. This one has to do with the removal of [Tuple Parameter Unpacking](https://www.python.org/dev/peps/pep-3113/).
Comment: Possible duplicate of [Nested arguments not compiling](https://stackoverflow.com/questions/10607293/nested-arguments-not-compiling)
Answer: In Python 3 you can't use tuple parameter unpacking anymore. You could rewrite the lambda in this way:
review_lda = sorted(review_lda, key=lambda topic_and_freq: -topic_and_freq[1])

Comment: I didn't know that Python 3 doesn't support tuple unpacking. This fixed my problem. Thank you so much!
Comment: BTW, better use the `reverse=True` argument of `sorted` instead of the minus.

Python 3 Syntax Error with lambda


Adicionar ou Remover Inputs com JS

Question: tenho uma dúvida?! no link abaixo:
Problema de compatibilidade do jQuery1.7.2 para o jQuery 3.3.1
eu tenho um código que me calcula algumas inputs com base no preço, quantidade, subtotal (preço * quantidade) e total geral (soma dos subtotais das inputs), conforme exemplo abaixo:

Acontece que eu gostaria de esconder todas as inputs e ir mostrando conforme eu clicar em um botão, para adicionar novos produtos (inputs). Eu fiz com base no projeto:
Adicionar / remover campos dinamicamente
Porém, como as inputs são geradas no JS eu não consegui fazer funcionar.
Alguém poderia me ajudar? É possível?
Segue meu exemplo:

<!doctype html>

<form name="form1" action="" method="post">

Total:

Total: <input class="value_total" readonly></input>

 <input type="button" value="Adicionar campos" onclick="AddCampos()">

<input type="text" name="hidden1" id="hidden1">
 <input type="hidden" name="hidden2" id="hidden2">

</form>

Acontece que consigo mostrar/esconder as inputs, porém não calcula!
Agradeço muito.
Comment: Poderia adicionar o seu código na pergunta? Pode utilizar o snippet (botão `` do editor) para mostrar funcionando.
Comment: Se você disponibilizar o código fica mais fácil de encontrar o problema
Comment: Pela Lógica do que precisa, Valor unitário, quantidade e subtotal precisa ser feito via javascript?
Tu poderia pensar em deixar esses inputs fixos para preenchimento e passar o valor preenchido para o novo campo quando submetido e então após cada submição é calculado o total e caso o total é zero nada aparece e outras condições podem ser feitas, caso não tenha Valor uniario não aparece quantidade nem subtotal e quando quantidade é 0 não aparece subtotal.
Comment: Então...esse é um sistema de serviços de auto mecânica, e conforme vai colocando as peças a serem usada, o sistema já vai calculando. nesse caso preciso acompanhar quão caro vai ficando a 'compra' para poder repassar para o cliente ou revisar algum item, antes de fechar a ordem de produção e dar baixa no sistema. Aceito alguma sugestão!
Answer: É só criar uma função que faz os cálculos e chamá-la quando você adiciona ou remove linhas. A função irá calcular os valores dos inputs visíveis e colocar os subtotais nos respectivos campos e o total geral no campo dele.
Veja abaixo que criei uma função calcula() que percorre todas as linhas visíveis fazendo os cálculos. Foi preciso também fazer várias alterações no código, resultando num código bem mais enxuto e legível do que o anterior:

function calcula(){

   var total = 0;
   $("span[id^=linha]:visible").each(function(){

      var val_unit = parseFloat($(".class_unit input", this).val().replace(",", "."));
      var qnt = $(".class_quant input", this).val();
      var sub_total = val_unit * qnt;

      if(!isNaN(sub_total)) $(".class_total input", this).val(sub_total.toFixed(2).replace(".", ","));

      total += parseFloat($("input[id^=total]", this).val().replace(",", "."));

   });

   if(!isNaN(total)) $("#total input.value_total").val(total.toFixed(2).replace(".", ","));

}

//Total máximo de campos que você permitirá criar em seu site:
var totalCampos = 10;

//Não altere os valores abaixo, pois são variáveis controle;
var iLoop = 1;
var iCount = 0;
var linhaAtual;

function AddCampos() {
   var hidden1 = document.getElementById("hidden1");
   var hidden2 = document.getElementById("hidden2");

   //Executar apenas se houver possibilidade de inserção de novos campos:
   if (iCount < totalCampos) {

      //Limpar hidden1, para atualizar a lista dos campos que ainda estão vazios:
      hidden2.value = "";

      //Atualizando a lista dos campos que estão ocultos.
      //Essa lista ficará armazenada temporiariamente em hidden2;
      for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
         if (document.getElementById("linha"+iLoop).style.display == "none") {
            if (hidden2.value == "") {
               hidden2.value = "linha"+iLoop;
            }else{
               hidden2.value += ",linha"+iLoop;
            }
         }
      }
      //Quebrando a lista que foi armazenada em hidden2 em array:

      linhasOcultas = hidden2.value.split(",");

      if (linhasOcultas.length > 0) {
         //Tornar visível o primeiro elemento de linhasOcultas:
         document.getElementById(linhasOcultas[0]).style.display = "block"; iCount++;

         //Acrescentando o índice zero a hidden1:
         if (hidden1.value == "") {
            hidden1.value = linhasOcultas[0];
         }else{
            hidden1.value += ","+linhasOcultas[0];
         }

         /*Retirar a opção acima da lista de itens ocultos: <-------- OPCIONAL!!!
         if (hidden2.value.indexOf(","+linhasOcultas[0]) != -1) {
         hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
         }else if (hidden2.indexOf(linhasOcultas[0]+",") == 0) {
         hidden2.value = hidden2.value.replace(linhasOcultas[0]+",","");
         }else{
         hidden2.value = "";
         }
         */
         calcula();
      }
   }
}

function RemoverCampos(id) {
   //Criando ponteiro para hidden1:
   var hidden1 = document.getElementById("hidden1");

   //Pegar o valor do campo que será excluído:
   var campoValor = document.getElementById("valor_unitario"+id).value;
   //Se o campo não tiver nenhum valor, atribuir a string: vazio:
   if (campoValor == "") {
      campoValor = "vazio";
   }

   if(confirm("O campo que contém o valor:\n» "+campoValor+"\nserá excluído!\n\nDeseja prosseguir?")){
      document.getElementById("linha"+id).style.display = "none"; iCount--;

      //Removendo o valor de hidden1:
      if (hidden1.value.indexOf(",linha"+id) != -1) {
         hidden1.value = hidden1.value.replace(",linha"+id,"");
      }else if (hidden1.value.indexOf("linha"+id+",") == 0) {
         hidden1.value = hidden1.value.replace("linha"+id+",","");
      }else{
         hidden1.value = "";
      }

      calcula();
   }
}

$(document).ready(function(){
   $('span[id^=linha] input').on("input", calcula);
});

//Escrevendo o código-fonte HTML e ocultando os campos criados:
for (iLoop = 1; iLoop <= totalCampos; iLoop++) {
   document.write("
Valor Unitário "+iLoop+":<input type='text' name='valor_unitario"+iLoop+"' id='valor_unitario"+iLoop+"' />

Quantidade "+iLoop+": <input type='text' name='qnt"+iLoop+"' id='qnt"+iLoop+"' value='0' />

SubTotal "+iLoop+": <input type='text' name='total"+iLoop+"' id='total"+iLoop+"' readonly='readonly' />
 <input type='button' value='Remover' onclick='RemoverCampos(\""+iLoop+"\")'>");
}

<form name="form1" action="" method="post">

Total: <input class="value_total" readonly></input>

   <input type="button" value="Adicionar campos" onclick="AddCampos()">

<input type="text" name="hidden1" id="hidden1">
   <input type="hidden" name="hidden2" id="hidden2">

</form>
Comment: A W3S tem um bom material pra inciante.
Comment: Exatamente isso! vou estudar o funcionamento antes de implementar, para poder aprender e não copiar ;). Tem alguma sugestão de leitura sobre JS? Agradeço a atenção.

Adicionar ou Remover Inputs com JS


Heading for comment section

Question: I would like to have a heading over my comments that only appears after a comment has been left... I tried the code below but it doesn't seem to be the answer:
<?php if ($comment): ?>

Comments

<?php endif; ?>

Answer: This is the default behavior of Garland. Have a look in the themes/garland/template.php file:
function garland_preprocess_comment_wrapper(&$vars) {
  if ($vars['content'] && $vars['node']->type != 'forum') {
    $vars['content'] = '
'. t('Comments') .'
'.  $vars['content'];
  }
}

Where did you put your code? Depending on your theme, you most probably want to theme comment-wrapper.tpl.php, which only gets output when there are comments to be displayed. Which what you want. :-)
Comment: Thanks, I was hoping for something a tad easier to implement but I guess there is no such solution at this time. Think it would be something good to include in future Drupal core releases though.
Answer: seems that you can add your conditional in a preprocess function, please see "Altering the 'Post new comment' heading" part in: http://www.systemseed.com/blog/how-customise-comment-form-drupal-6

Heading for comment section


data analysis tools to integrate with node red and robo mongo

Question: node red is a gui tool,  using which we can wire hardware devices, APIs online,services together. I have a node red instance running,  which is an mqtt client that accepts messages from broker which are published from various sensors. All the data is being stored in monogodb. Now, i want to implement some kind of analysis on the data that is being sent from all the sensors. is there any data anlaysis tools that can be integrated with node red and anlayse the data that is being stored in monodb database.
Answer: For the data analysis I would suggest "MongoDB with R".
https://datascienceplus.com/using-mongodb-with-r/
You also speak about integration with node-red but is it not sufficiently that the data analysis tool is integrated with the MongoDB (which is populated by node-red) ?  If not then you should clarify what kind of integration you need with node-red.
Answer: So in assumption you can acces the DB from node-RED:
Its how far you want to analyze the data:

You can simply do it with function nodes and calculate means, standard deviation etc.
There is a node called node-red-contrib-statistics wich has many standard statistic test, like t-test, implemented.
You can just write a your analysis in a third party language, like python or R, and call it with the exec or node-red-daemon node


Virtual environment error: "The term 'source' is not recognized as the name of a cmdlet ..."

Question: I have successfully created a virtual environment (using venv), but I get an error when trying to activate it.
PS C:\Users\...> python -m venv projects
PS C:\Users\...> source venv/bin/activate
source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

At line:1 char:1
+ source venv/bin/activate
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (source:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Why do I get this error, and how do I fix it?
Comment: Your question is? `source` isn't a PowerShell thing, you should be following the instructions for activating the virtual environment in PowerShell.
Comment: When you wrote `source venv/bin/activate`, how did you decide to write that? Please make sure that you are following a guide that is suitable for your operating system. This command only makes sense on Linux.
Answer: There are two issues:

You have created a virtual environment named projects (here: python -m venv *projects*), but you're trying to activate an environment named venv (here: source *venv*/bin/activate).
source is not a powershell command - you cannot use it. Instead, use the powershell script that venv provides: .\projects\Scripts\activate


Forecasting: Different Model for 1 month, 2 month, 6 month forecasts?

Question: I'm still trying to expand my statistics and forecasting technique knowledge.
Right now I'm forecasting seasonal contact patterns, so the simplest model I can understand with seasonality is a Holt-Winters/ Triple exponential smoothing model.
For many of our decisions, we not only need predictions for one month out, but also two months out, and even as far as 6 months out, or more.
Obviously accuracy increasingly goes out the window as you try to forecast 6 months out, but, I guess we do what we can.
The first thing I immediately noticed after creating the triple exponential smoothing model and initiated the seasonal/ trend values -- is that there are certainly different 'optimal' alpha (level), beta (trend) and gamma (seasonality) values, depending on whether you are forecasting one month out, or 6 months out.
As you might have guessed, the 1-month forecast has far greater accuracy for a test data set with a higher alpha value (stronger recent values) -- and the 6 month is better with a lower alpha value.
Not that it matters much, but the 2 month is closer to the 1 month model, and the 3-4-5 seems to be closer to the 6 month, but they all have their local 'optimal' values.
So if I need a rolling forecast for the next 6 months --- am I to use one model, or am I supposed to use a different set of alpha-beta-gamma values depending on how far out the predicted value is?
I have a minor background in statistics, but I know it's easy to misuse/ misread them. I don't know if using two or three different models like this can lead to mistakes.
Answer: What you are talking about is using a "direct" forecasting strategy rather than the more popular "recursive" forecasting strategy.
In a recursive strategy, one model is fitted, usually based on minimizing the one-step forecast mean squared error, and the forecasts for all future horizons are estimated by iterating the equations over time. If the model is linear, and the same as the data generating process, this is optimal. But in reality, the model is at best an approximation to whatever generated the data, and most real-world phenomena are non-linear.
Contrary to what @Tom Reilly asserts, there is considerable academic literature on this problem, but very little software implements alternatives to the recursive approach. The problem is addressed, and some of the associated literature is referenced, in my recent paper with Souhaib Ben Taieb: https://robjhyndman.com/publications/boostingar/
The bottom line is that you should try different approaches and choose what works best for your problem. In this case, I suggest you try the direct approach (with different parameters for different horizons) and compare the forecast accuracy with what you get using the recursive approach.
Comment: Thanks for the help Rob. I suppose I do not often look back at these questions, but I will definitely take a look at your paper, and am glad to hear there is literature on this and I'm not taking crazy pills. I think at the time, I did eventually find an article on this topic: http://www.sciencedirect.com/science/article/pii/S0169207002000109                 -I'm not an expert on the topic by any means, so I can't debate the merits, but at least it seemed to imply that multiple models may be better in some cases. I of course have more reading to do.
Comment: The link to paper is broken, it resides here now: https://robjhyndman.com/papers/rectify.pdf
Comment: Actually, that's a different paper. I've updated the link in the answer with the correct paper.
Answer: This is a very common issue in business forecasting, where we want sensible forecasts for the short term without sacrificing long term performance.
You can test your data to see this by going back over multiple lags and holdout periods to see which models work best at different lags-- maybe one model does well 1-3 periods out, but another does much better over a longer horizon.
The forecast and accuracy functions from the forecast package in R make doing this sort of thing quite straightforward.
Once you have that data, you will have some more subjective choices to make-- is using a single model that has some connection to explaining the data preferable, even if it has more error than a mixed approach that would use different models for different time horizons?
Answer: John,
I am not sure who is feeding you these theories about model parameters being optimal for periods out, but it just isn't right. Please share the source of your comments(books, web pages, software, etc.)  I would like to read more about this.  You want a model to describe the historical variations and also the periods that are outliers and then forecast it. That's it.
Comment: No one is feeding me these theories -- I may have come to the conclusions myself. I mean, I have a few books on forecasting, but none of them mention creating a model for multiple t+1, t+2, t+3... t+n ... periods out forecasting. The truth of the matter is, when using the test data, there may be greater accuracy (in this case MAPE) with a higher alpha value when you are forecasting one period ahead, and a lower alpha value when you are forecasting 6 periods ahead. Whether or not this has to do with overfitting the model, I'm not sure. But that's what I've found.
Comment: I'm not using an alpha 'solver' -- mostly trial and error - but I'm pretty certain the 'solver' would come up with different alpha values for the the t+1 forecast vs the t+6 forecast. For the sake of simplicity you can use one model to forecast every period, but would this not be less accurate?
Comment: Ok, I understand why you are trying to do what you are doing now, but there is no support for this in a "book" so you are "freestyling" here :).  You can't use a "goal seek" approach to minimize MAPE for time series problems.  The "goal" here is to think about the data and the causal variables that are driving it and then include them and the forecasts of those to drive your forecasting process all the while checking for outliers, changes in level/trend/seasonality/parameters/variance andof course making sure the residuals are random.
Comment: I agree that you definitely need to include casual variables, account for outliers, etc from time series forecasts. Checking if the residuals are random of course is important - yes. But primarily, I am looking for prediction accuracy (which can be aided with casual variables, or detecting systematic bias, of course) --- I am in a business setting and forecast accuracy pretty much IS the end goal. In terms of prediction, my method may be wrong, possibly, but I cannot quite see why right now. Why are there different optimum alpha values for each horizon? Why only pick one set for all horizons?
Comment: You are using a model to go against data when you should be modeling your data.  "Let the data speak".  The steps are Identification, Estimation, Diagnostic Checking and then Forecasting.  None of those steps entail "hey is it optimized for two periods out?" I would be happy to discuss off-line.  See my profile.


Dimensional analysis in combinatorics

Question: From HMMT:

Fifteen freshmen are sitting in a circle around a table, but the course assistant (who remains to stand) has made only six copies of today's handout. No freshman should get more than one handout and any freshman who does not get one should be able to read a neighbor's. If the freshman are distinguishable but the handouts are not, how many ways are there to distribute the six handouts subject to the above conditions?

The solution starts by considering the expected number of handouts to be received by any individual student. By linearity of expectation, there are 15 students and 6 handouts, so each student is expected to individually receive 6/15 handouts.
Then, for an arbitrary individual student S, we compute the number of distributions of handouts in which S receives a handout, called $y$. Also, let $x$ be the answer; $x$ is the number of ways to distribute the six handouts subject to the conditions of the problem.
Now, the solution states that $y=\frac{6}{15}x \Longleftrightarrow x = \frac{15}{6}y$, which is how we shall find the answer. This feels nearly obvious because with $y=\frac{6}{15}x$ we're multiplying the # distributions by the expected number of handouts per student, but if we apply some kind of "dimensional analysis" to this, the multiplication does not turn out to something like "# distributions per student".
In particular, what would be the resulting meaning if we divided $x$ by the number of students as in $\frac{x}{15}$, rather than dividing $x$ by the number of students, then multiplying by the number of handouts, as we do with the equation $y=\frac{6}{15}x$?
Comment: @BrianTung: There aren't $\binom{15}6$ ways to distribute the handouts that ensure that each freshman either gets one or has a neighbor who gets one; $x<\binom{15}6$.
Comment: Ahh, OK.  I got the condition for the *answer*; what I didn't get was that that condition also applied to the count of $y$: "Then, for an arbitrary individual student S, we compute the number of distributions of handouts in which S receives a handout, called $y$."
Comment: I must not be understanding something about the solution.  There are $\binom{15}{6} = 5005$ ways to select $6$ out of $15$ students to receive a handout.  For any particular student $S$, $y = \binom{14}{5} = 2002$ ways result in $S$ receiving one of the handouts.  How can the correct answer be $x = \frac{15}{6}y = 5005$?
Comment: There are more conditions in selecting 6 out of the 15 students. "No freshman should get more than one handout and any freshman who does not get one should be able to read a neighbor's".
Answer: Well, $\frac{6}{15}$ can be thought of as n expected value, but in the solution, it is the probability that a student receives a handout, and probability is unitless.
Here's an equivalent way to phrase it, which may be easier to accept.
Let $x$ be the overall number of solutions, and let $x_1, x_2, \dots, x_{15}$ be the number of solutions in which student $1, 2, \dots, 15$ respectively gets a handout. The solution shows that $x_i = 50$ for any $i$.
If we add up $x_1 + x_2 + \dots + x_{15}$, then each solution is counted $6$ times, because in each solution, $6$ students get handouts. Therefore
$$
     x_1 + x_2 + \dots + x_{15} = 6x \implies 15 \cdot 50 = 6x \implies x = \frac{15}{6} \cdot 50 = 125.
$$
Comment: I'm a little confused. Why must we do anything more past finding that the $x_i=50$ for $1 \le i \le 15$? This number takes into account the conditions of the problem; the fact that each student must be able to view a handout is accounted for. Why is the answer not 50?
Comment: The number $x_i$ is not the number of solutions in which student $i$ *is able to view* a handout; it's the number of solutions in which student $i$ *is physically holding* a handout. There are other solutions in which student $i$ doesn't have a handout, but is looking at a neighbor's.

Dimensional analysis in combinatorics


Push changes to bitbucket from server

Question: I want to edit files on server with ftp and then use my source tree git client to push changes to bitbucket repository.
I've got a deploy key on server but its read only so I can use ssh to pull down changes but not push to bitbucket from the server.
Answer: If you want to push something you must have a sufficient privileges to do so.
How do you want to push if you don't have credentials to do so?
If you can pull using ssh you should be able to push as well since SSH is a secures connection, it does not "care" if you read or write data (as long a you have the right permission on the machine regardless the ssh protocol.)
Comment: Im using deploy key and its read only on bitbucket. And the second part is that I want to use my local git client and edit code on server and push from server with local git client.
Comment: As far as i know (I'm working with sourcetree since the first release) its not possible even form command line. You will not be able to push if you have a read only key doesn't matter if you use GUI tool or CLI
Comment: Exactly. What do I need to do to give my server write access to bitbucket?
Comment: Depend on your system, you might need to generate pem fire for source tree or to deploy a new ssh key to you bitbucket account.

Push changes to bitbucket from server


Using django filer out of admin area (or an alternative library)

Question: Django filer is an awesome tool for managing files, it detects duplicates and organizes files based on their hashes in folders, has great UI for managing files and folders and handles file history and permissions.
I read some of the source code and realized it extensively uses django admin features in code and in templates; is there any way to use these features for non-staff members that are logged in? To give them tools for uploading and managing their own files and folders in their personal upload area (without reinventing the wheel)?
If there isn't an easy way, what alternatives are there and you suggest to provide such functionality with minimum changes in code?
Answer: According to this django-filer is not supposed to work outside of the admin, but with some "glue" i was able to make the uploads work in a "normal" template. Here is some of my code:
    # forms.py

    class PollModelForm(forms.ModelForm):
        uploaded_image = forms.ImageField(required=False)

        class Meta:
            model = Poll
            fields = ['uploaded_image']

    # views.py
    # I used django-extra-views but you can use a normal cbv
class PollCreateView(LoginRequiredMixin, CreateWithInlinesView):
    model = Poll
    form_class = PollModelForm
    template_name = 'polls/poll_form.html'
    success_url = reverse_lazy('polls:poll-list')
    inlines = [ChoiceInline]

    # Powered by django-extra-views for the inlines so a bit different
    @transaction.atomic
    def forms_valid(self, form, inlines):
        # It's more secure this way.
        form.instance.user = self.request.user

        uploaded_file = form.cleaned_data['uploaded_image']
        image = Image.objects.create(
            name=str(uploaded_file), is_public=True, file=uploaded_file,
            description='Poll Image', owner=self.request.user
        )
        form.instance.image = image

        log.info('Poll image uploaded'.format(**locals()))

        return super(PollCreateView, self).forms_valid(form, inlines)

    # HTML

                                <input type="file" name="uploaded_image" id="id_uploaded_image">

Upload image here.


JAVA Code to print SQL Server to CSV returns with incomplete data

Question: I have a JAVA code to out put SQL Server Table to CSV. The printing is stopping in the middle and I am getting only partial data as CSV output. Below my code.
public class SQLServerConnection {

    public static void main(String[] args) throws IOException, SQLException {
        // TODO Auto-generated method stub

        Connection conn = null;
        SQLConnection cnn = new SQLConnection();
        FileWriter fw = new FileWriter(cnn.fileName);

        try {conn = DriverManager.getConnection(cnn.dbURL);

        if (conn != null) {
            DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
        }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        String sql = String.format(cnn.Query);
        assert conn != null;

        PreparedStatement preStatement;
        preStatement = conn.prepareStatement(sql);
        ResultSet result = preStatement.executeQuery();
        ResultSetMetaData rmsd = result.getMetaData();
        int Columncount = rmsd.getColumnCount();

      //Get the column name and print the column name
        for (int iterator=1; iterator<= Columncount; iterator++) {
            fw.append(rmsd.getColumnName(iterator)+",");
        }
        fw.append('\n');

        while(result.next()){
            try {
                for (int jterator=1; jterator<=Columncount; jterator++){
                    fw.append(result.getString(jterator));
                    fw.append(',');
                }
                fw.append('\n');
             } catch (SQLException e)
            {
                e.printStackTrace();
            }}
        conn.close();
    }}

Class for DB and Excel Parameters
public class SQLConnection {
    public String ServerName = "Server1";
    public String DBName = "DB1";
    public String FileLoc = "Location of the file";
    public String dbURL = "jdbc:sqlserver://"+ServerName+";databaseName="+DBName+";integratedSecurity=true";
    public String Query = "SELECT * from [scdHSBCHK]";
    public String fileName = (FileLoc + DBName +"_QueryResult.csv");
}

The actual db returns 57 records but the csv returns only 29. I tried with different db names as well same issue though. When I output the results in the program window, the data is displaying correctly.
Comment: Google for "try-with-resources", learn what it's about, and use it for all the resources that **must** be closed: Connection, PreparedStatement, and of course, FileWriter. Also, use a BufferedWriter as explained in the Java IO tutorial. Writing with a FileWriter like this is slooow.
Comment: Did you try debugging?
Comment: Yes. Did a debug and found that the issue is with the file writer as the data coming correct when I did a print within eclipse. After that I couldn't progress on anything.
Comment: How many Columns from first loop do you have?
Comment: Note that Windows users would expect a CSV file to have `"\r\n"` line endings. To make it platform-independent, you should use `System.lineSeparator()` instead of `'\n'` or use `BufferedWriter.newLine()`.
Comment: @AlexGera I have 22 columns from the first loop
Answer: I would make sure that you close the FileWriter. This will ensure that all buffers are flushed to the file. Make sure that all Closeable resources are closed (Connection, PreparedStatement, ResultSet, FileWriter), by using try with resources.
My suggested implementation would be something like:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.*;

public class SQLServerConnection {

    private static final String LINE_SEP = System.lineSeparator();

    public static void main(String[] args) throws IOException {
        SQLConnection cnn = new SQLConnection();
        try (Connection conn = DriverManager.getConnection(cnn.dbURL, cnn.user, cnn.pass);
             PreparedStatement preStatement = conn.prepareStatement(cnn.Query);
             ResultSet result = preStatement.executeQuery();
             Writer fw = new BufferedWriter(new FileWriter(cnn.fileName))) {
            ResultSetMetaData rmsd = result.getMetaData();
            int columnCount = rmsd.getColumnCount();
            //Get the column name and print the column name
            for (int iterator = 1; iterator <= columnCount; iterator++) {
                fw.append(rmsd.getColumnName(iterator)).append(",");
            }
            fw.append(LINE_SEP);
            while (result.next()) {
                try {
                    for (int jterator = 1; jterator <= columnCount; jterator++) {
                        fw.append(result.getString(jterator)).append(',');
                    }
                    fw.append(LINE_SEP);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

}

Comment: Closing the FileWriter also implicitly flushes it. Also the Class.forName call is unnecessary. It was only needed in versions of JDBC drivers that were written 10-20 years ago.
Comment: Excellent, I am getting the correct data after closing the File Writer. Thanks @DodgyCodeException


Problem with martingales and zero-one law

Question: This is a problem from Leo Breiman- probability. Given a process $X_1,X_2,...,$ abbreviate $\mathcal{F}_n=\mathcal{F}(X_n,X_{n+1},...)$. Show that the tail $\sigma$-field $\tau$ on the process has the zero-one property iff for every $A \in \mathcal{F}(X_1,X_{2},...)$ $$\lim_n \sup_{B \in \mathcal{F}_n}|P(A \cap B)-P(A)P(B)|=0 $$
We can use the fact that if $Z,X_1,...$ are random variables and $\tau$ is the tail $\sigma$-field  on the process $X_1,X_2,...$. Then $$\mathbb{E}(Z|X_n,X_{n+1},...) \rightarrow_{a.s \text{ or first mean} }  \mathbb{E}(Z|\tau)$$.
I'm having trouble with the $\Rightarrow$ part. This is kind of a converse of the zero-one law, but I know that the converse is not true in general. Actually the term limsup confuses me. I tried with $Z=1_A$ but then I don't know how to connect this with the limsup of the expression
Answer: Let $Y_n=E(I_A|\mathcal F_n)$. Then $(Y_n)$ is a uniformly integrable martingale and it converges a.s. and in $L^{1}$ to $I_A$. Now $|E[I_B E(I_A|\mathcal F_n)-P(A\cap B)]|=|E[I_B E(I_A|\mathcal F_n)-EI_B I_A| \leq E|Y_n-I_A|$ for all $B \in \mathcal F_n$. Take sup ober all $B \in \mathcal F_n$ to finish the proof.


Render entity from entity reference field

Question: (Drupal 8) So I have a content type called Browse, then I have created a paragraph which is a entity reference field for content of Blog. So now when I create a piece of content in Browser I can add multiple blog posts to this page with the entity reference field from paragraphs. I can not figure out how to render the blog data into my twig template. Maybe I am using the wrong twig template file? I am trying with a field--paragraph--blog.html.twig. Does this need to be done in the theme_preprocessor?
Answer: You can enable Twig Debugging in sites/default/services.yml. If services.yml does not yet exist; copy default.services.yml and rename it to services.yml.
Set the debug variable to true:
parameters:
  twig.config:
    debug: true

Now clear cache and refresh your page. Look in the html source and you should see some template suggestions.
Comment: Ah your content isn't being displayed yet? When you go to `Manage display`, can you change the `Format` to `Rendered entity`?
Comment: I have that enabled but that doesn't help me figure out how to display a rendered blog from the entity reference field. I already have the twig template that I am using. And it works. But can't display the rendered blogs on this page.
Comment: That is not an option. Just says
Field--------Label-------Format
   Blog Reference----> Above---->Label Link to the reference entity


Função apply, extrair dados da regressão

Question: Tenho a seguinte amostra:
x <- structure(list(POP = structure(c(1L, 12L, 15L, 16L, 17L, 18L,
19L, 20L, 21L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 13L,
14L), .Label = c("pop1", "pop10", "pop11", "pop12", "pop13",
"pop14", "pop15", "pop16", "pop17", "pop18", "pop19", "pop2",
"pop20", "pop21", "pop3", "pop4", "pop5", "pop6", "pop7", "pop8",
"pop9"), class = "factor"), a1 = c(91, 26.7, 51.9, 14, 0, 15.3,
34.4, 19.1, 10.2, 52.5, 43.6, 13.1, 47.1, 34.7, 0, 58.9, 66.8,
0, 0, 0, 0), a2 = c(92.9, 27.7, 54.1, 14.3, 0, 16.2, 35, 19.1,
11.1, 52.5, 44.6, 13.4, 48.7, 34.4, 0, 59.5, 72.3, 0, 0, 0, 0
), a3 = c(92.6, 27.4, 54.7, 13.7, 0, 16.2, 36, 0, 11.1, 53.2,
45.2, 13.7, 49.3, 0, 0, 59.5, 74.5, 0, 0, 0, 0), a4 = c(95.5,
28.3, 57.3, 14.6, 0, 16.9, 36.9, 0, 11.8, 56.3, 47.1, 14, 53.2,
0, 0, 62.7, 84.4, 0, 0, 0, 0), a5 = c(97.4, 28.6, 61.4, 14.3,
0, 17.5, 36.9, 0, 12.4, 55.7, 47.4, 14.6, 53.8, 0, 0, 62.4, 0,
0, 0, 0, 0), a6 = c(97.7, 29.3, 63.3, 14.6, 0, 18.5, 38.8, 0,
13.1, 57.3, 49, 15.3, 55.4, 0, 0, 62.7, 0, 0, 0, 0, 0), a7 = c(102.2,
0, 68.1, 14.6, 11.1, 20.1, 43.3, 0, 14.6, 64.9, 53.2, 0, 60.5,
0, 0, 62.7, 0, 0, 0, 0, 0), a8 = c(106.3, 0, 71.9, 14.3, 0, 19.7,
45.8, 0, 15.9, 70.7, 57.3, 0, 67.8, 0, 10.5, 0, 0, 0, 10, 0,
0), a9 = c(113.2, 0, 75.5, 15, 0, 21.7, 49, 0, 18.5, 73, 59.8,
0, 0, 0, 14.7, 0, 0, 0, 10.4, 0, 0), a10 = c(114.9, 0, 75.2,
15, 0, 22.6, 49.6, 0, 19.8, 73.8, 59.9, 0, 0, 0, 16.6, 0, 0,
10.5, 10.5, 0, 0), a11 = c(114.9, 0, 75.5, 15.1, 0, 23.2, 50.6,
0, 19.8, 74.6, 59.2, 0, 0, 0, 18.2, 0, 0, 10.5, 10.6, 0, 0),
    a12 = c(115, 0, 76, 15.9, 0, 26.1, 0, 0, 22.7, 75.4, 60.8,
    0, 0, 0, 21, 0, 0, 10.3, 11.1, 0, 0), a13 = c(115.2, 11.6,
    76, 16, 0, 26.6, 0, 0, 23.3, 75.5, 61.3, 0, 0, 0, 22.6, 0,
    0, 10.7, 11.1, 0, 0), a14 = c(0, 11.6, 77.6, 0, 0, 29.5,
    0, 0, 25.3, 76.2, 64, 0, 0, 0, 25.5, 0, 0, 11.6, 11.8, 10.2,
    11)), class = "data.frame", row.names = c(NA, -21L))

E os dados anuais:
temp <- structure(list(ano = structure(c(1L, 7L, 8L, 9L, 10L, 11L, 12L,
13L, 14L, 2L, 3L, 4L, 5L, 6L), .Label = c("a1", "a10", "a11",
"a12", "a13", "a14", "a2", "a3", "a4", "a5", "a6", "a7", "a8",
"a9"), class = "factor"), temp = c(0L, 2L, 2L, 6L, 2L, 3L, 13L,
8L, 7L, 3L, 2L, 5L, 2L, 5L)), class = "data.frame", row.names = c(NA,
-14L))

Aqui eu crio listas para receber os valores de interpolação, que será feito por um loop (for)
model_list <- list()
x_list <- list()
y_list <- list()
y <- temp$temp

log_x <- apply(x[-1], 2, log)

E elimino as linhas que não tem nenhuma observação válida
# linhas em log_x com -Inf em todas as lacunas
 linhas <- c(3,6,9,10,11)
 # Linhas com Algum Valor (LAV)
 lav <- (1:21)[-linhas]
 lav
 # [1]  1  2  4  5  7  8 12 13 14 15 16 17 18 19 20 21

Agora eu crio um loop que i) remove as posições sem observação, tanto no arquivo log_x como no y também; ii) Faz as interpolações.
Também uso uma função if else para colocar NA nas observações que tiveram o comprimento menor que 3
for(i in (lav)){ # loop por linha
  # indices de coluna com valores -Inf
  indice_com_inf <- which(log_x[i,]<0)
  # criar lista de x sem os -inf
  x_list[[i]] <- log_x[i,-indice_com_inf]
  # novo y1 em lista, sem os indices de valores -Inf
  y_list[[i]] <- y[-indice_com_inf]
  # condição
  if (length(x_list[[i]]) >= 3) { #condição comprimento >=3
    #rodar regressão
    model_list[[i]] <- lm(x_list[[i]] ~ y_list[[i]])
  } else {
    model_list[[i]] <- NA #se não atender a condição, não fazer nada
  }}

Depois disso gostaria de extrair os dados com uma função apply
da seguinte forma:
coef_list <- t(sapply(model_list, coef))

model_smry <- lapply(model_list, summary)

R2_list <- sapply(model_smry, '[[', 'r.squared')
pval_list <- t(sapply(model_smry, function(LM){
  LM[['coefficients']][, 4]
}))

f_list <- t(sapply(model_smry, '[[', 'fstatistic'))

Mas obtenho o erro Error: $ operator is invalid for atomic vectors
eu entendo que seja o valor NA, como posso fazer para extrair os dados, e gostaria que os valores NA não fossem retirados, pois eu preciso deles para inserir o nome das observações na ordem e no length da amostra.
como fazer esse processo agora?
tem como as observações que não foram calculadas as regressões, ficarem com um valor zero e ir seguindo, linha por linha, extraindo os dados.
Answer: O problema é que sua lista model_list tem elementos do tipo list, que são o resultado de lm, elementos tipo NULL, onde o if não fez nada, e elementos tipo NA, onde ela passou para o else.
Uma opção seria você mudar como você criou essa lista, para evitar isso. Aí você usa model_list_novo nos sapply.
model_list_novo <- model_list[lengths(model_list)>1]

Mas como você pode achar importante saber as posições em que não foram calculados os coeficientes, você pode testar dentro do apply para só os elementos que vierem do lm sofrerem alguma operação:
coef_list <- t(sapply(model_list, function(M){
    if(is.list(M)) coef(M)
}))

R2_list <- sapply(model_smry, function(M){
    if(is.list(M) > 3) M[['r.squared']]
})

pval_list <- t(sapply(model_smry, function(LM){
    if(length(LM)>3) LM[['coefficients']][, 4]
}))

f_list <- sapply(model_smry, function(M){
    if(length(M) > 3) M[['fstatistic']]
})

Pra cada apply teria que ter um if assim.


How apply migrations to the production server using Visual Studio 2015?

Question: Apply code first migrations is easy working locally. Just type "update-database" into Package Manager Console to update the local database.
However, what about to update the remote database? How can I apply migrations to it?
Answer: You can change the connection string in your web.config file to point to the remote sql server, and then run the same update-database command.
Alternatively, you can generate the sql script with the -Script flag when running the Update-Database command. (Update-Database -ProjectName NameOfProject -Script)  This will generate the script needed to run on the remote database


PHP and Android GCM push notification - How to store users

Question: I have my Android client application that wait for a push message from the GCM Google server... on the server side, my web must store the registration ID of the device, in order to send the push notification to this specific device (calling the GCM Service with a specific PHP class).
The question is, how can I refresh the registration Id of the device every time It is registreted on the Google GCM servers? How can I associate to each users on the web app to a specific registration Id of the android app?
Answer: You can use PHpmyadmin tool to creat the data base and use the php script to open,store registration Id  and close the db.
Comment: Ok, but my doubt is about the registration ID... the Android application must every time updates the Id send It to the web app?


Is there a syntax for creating an anonymous subclass in C#?

Question: Can I create instance of abstract class in C#/.net like in Java ?
Additional Info
I think a lot of us does not understand what do I mean?
So, In java I can create abstract class like this :
Simple abstract class :
/**
 * @author jitm
 * @version 0.1
 */
public abstract class TestAbstract
{
    public abstract void toDoSmth();
}

Code where I've create instance of abstract class
/**
 * @author jitm
 * @version 0.1
 */
public class Main {
    public static void main(String[] args) {
        TestAbstract testAbstract = new TestAbstract() {
            @Override
            public void toDoSmth() {
                System.out.println("Call method toDoSmth");
            }
        };
    }
}

Can I to do in c# something like this ?
Comment: Currently your question is *far* too vague. In particular, you've mentioned abstract classes in the title and in the tags, but not in the body of the text. If you have a particular piece of Java code in mind, please post it.
Comment: You're not really instantiating an abstract class in the Java example either, although it looks that way. What really happens is that you are implicitly defining a new, _concrete_ class that derives from `TestAbstract` and overrides a specific method.
Comment: If you need to instantiate an abstract class, it probably should not be an abstract class
Comment: He mentioned a class named "Abstact".  Might be relevant.
Comment: No, class Abstract equals abstract :)
Comment: 2romkyns I understood but I do not need to create new class directly only anonymous.
Comment: 2 baultista, Probably Yes  :), but my abstarct class contains some common functionality and I need to test how it works ...
Answer: Neither in Java nor in C# you can create an instance of an abstract class.
You will always need to create a concrete class that inherits from the abstract class.
Java lets you do it without naming the class, using anonymous classes.  C# does not give you that option.
(Edited to show a delegate as a replacement. I don't have access to VS here, so it may not compile, but this is the idea )
Usually in Java when you use an abstract class with a single abstract method (SAM) what you are really trying to achieve is to pass some code as a parameter.
Let's say you need to sort an array of objects based on the class name, using Collections.sort(Collection, Comparator)
(I know Comparator is an interface, but it is the same idea)
Using an anonymous class to avoid extra typing, you can write something like
   Comparator<Object> comparator = new Comparator<Object>{
        @Override
        public int compare(Object o1, Objecto2) {
            return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName()));
        }//I'm not checking for null for simplicity
   }
   Collections.sort(list, comparator)

In C# 2.0 and beyond you can do pretty much the same using the Comparison<T> delegate. A delegate can be thought as a function object, or in java words, a class with a single method. You don't even need to create a class, but only a method using the keyword delegate.
Comparison<Object> comparison = delegate(Object o1, Object o2)
{
    return o1.class.Name.CompareTo(o2.class.Name);
};

list.sort(comparison);

In C# 3.0 and beyond you can write even less code using lambdas and type inference:
list.sort((o1, o2) => o1.class.Name.CompareTo(o2.class.Name))

Anyway, if you are migrating code form java to c# you should read about delegates...in many of cases you will use delegates instead of anonymous classes. In your case, you are using a method void toDoSmth(). There is a delegate called Action which is pretty much the same thing, a method with no parameters and no return.
Comment: In some (most?) cases, you should replace anonymous classes with delegates and you will write even less code...Specially with one method classes.
Comment: Yes, my question was can I create instance like in java (using anonymous) currently I understood that I cannot.
Thanks.
Comment: 2 Pablo: Could you post example how to do it, because currently I've created simple class from abstract and use it.
Answer: No. Not directly. The closest you can come (assuming you have the following class structure):
public abstract class AbstractClass
{
}

public class ChildClass : AbstractClass
{
}

Is:
AbstractClass instance = new ChildClass();

Answer: Alternative: An init property of type Func<>
I needed to unit test a class that used a TcpClient (which is hard to mock). This is what I used...
In the class to be tested:
public Func<string, int, CancellationToken, Task> CheckConnectivityAsync { get; init; } =
    async (host, port, cancellationToken) =>
    {
        using var tcpClient = new TcpClient();
        // etc.
    };

In the unit test class constructor:
    _testSubject = new MyClass(context)
    {
        CheckConnectivityAsync = _mockCheck.Object
    };

With the right package names you could tighten the accessibility of the property (instead of using public).
Answer: Your example uses an anonymous implemention for an abstract class. C# does not support the anonymous implementation, so you need to create another one that extends it.
public abstract class TestAbstract {
}
public class AnotherTest : TestAbstract {
}
Comment: In Java I can, only I need it is implement abstract methods, but, I can to do it like anonymous implementation.
Comment: In that case, then no - C# (as far as I know doesn't allow you to create an anonymous implementation of an abstract class).
Comment: You still aren't instantiating the abstract class, you are instantiating an anonymous subclass.
Comment: Yes, I understood, but without creating new type only anonymous implementation of abstract body.
Comment: @jitm: It still creates a new type.


Prompt Multiplo WorkWithPlus exemplo em Trasações

Question: Bom dia,
Estou tentando usar o promptmultiple do work with plus para preencher o grid do level de uma transação.
Mas ao selecionar os dados ele não atualiza o grid
Answer: Bom dia,
O PromptMultiple de WorkWithPlus é para usar como filtros de pesquisa (usando o filtro FilterMultiple com type: prompt), nos objetos Selection, Prompt, etc mas não é para usar na transação para inserção de dados.
Tem um exemplo de uso no seguinte link: http://www.workwithplus.com/eng/help/index.htm?Page=SelectionFilter.htm na seção: Prompt Filter Multiple.
Qualquer outra dúvida pode nos escrever a nossa conta de suporte: firstname.lastname@example.com
Att,
Eugenia


How do I extract sentences in regex that are separated by a word followed by a semicolon?

Question: I'm trying to write some regex pattern to take out the location, features, and payment accepted sections from a block of text. I'm making a website that shows food options and in the API, they have a description section that includes more than enough information which is why I want to extract specific text.
I looked into positive and negative lookahead in regex but I still wasn't able to solve my problem. I'm able to select everything up to the second section but only if in this case I was selecting the location. If i was selecting the features, I would be also selecting the previous section, location. See the below text as an example.
Here's the text from which I want to extract from:

Location: Village 1 \r\n\r\nFeatures:  A multitude of
  offerings, including entrees, hot meals, wood-fired pizza, salad bar,
  grill items, made-to-order deli sandwiches & wraps, convenience
  items and much more\r\n\r\nPayment accepted: cash, Watcard
   \r\n\r\nThis is a great place to meet your friends! The aroma of
  fresh baked breads and pastries from our in-house UW Bakery will
  surely make you take a deep breath. Mudie's offers a large
  selection of vegetarian foods, grab n' go items, salad bar,
  grill items, made-to-order deli sandwiches and pitas, full breakfast,
  and convenience foods. A hot entrée item and side dishes are available
  every lunch and dinner hour.\r\n\r\nMeal hours for Mom's
  Counter*:\r\n\r\nBreakfast: 7:30 - 11:00 am\r\n\r\nLunch:11:30 am
  - 2:00 pm\r\n\r\nDinner: 4:30 - 8:00 pm \r\n\r\n*please note, these hours are subject to change without notice "

I wrote this so far:
  /.+?(?=Payment accepted)/

which selects everything up to Payment Accepted section. I also wrote
/(Location|Features|Payment accepted):\s{1,4}?[A-Z]+\s?\d?/

where it selects the section of my three desired places. I'm not able to connect the two or to come up with anything that is able to select what I need without including another section.
Any help would be appreciated.
So in the above case, my extracted parts would be:
Location: Village 1
Features:  A multitude of offerings, including entrees, hot meals, wood-fired pizza, salad bar, grill items, made-to-order deli sandwiches & wraps, convenience items and much more
Payment accepted: cash, Watcard

Answer: You can use this regex for extracting those three sections of text,
/Location:\s*([^\v]*)\s*Features:\s*([^\v]*)Payment accepted:(.*?)(?=\r\n)/

Here is the JS code for same.

    var myString = "Location: Village 1 \r\n\r\nFeatures:  A multitude of offerings, including entrees, hot meals, wood-fired pizza, salad bar, grill items, made-to-order deli sandwiches & wraps, convenience items and much more\r\n\r\nPayment accepted: cash, Watcard  \r\n\r\nThis is a great place to meet your friends! The aroma of fresh baked breads and pastries from our in-house UW Bakery will surely make you take a deep breath. Mudie's offers a large selection of vegetarian foods, grab n' go items, salad bar, grill items, made-to-order deli sandwiches and pitas, full breakfast, and convenience foods. A hot entrée item and side dishes are available every lunch and dinner hour.\r\n\r\nMeal hours for Mom's Counter*:\r\n\r\nBreakfast: 7:30 - 11:00 am\r\n\r\nLunch:11:30 am - 2:00 pm\r\n\r\nDinner: 4:30 - 8:00 pm \r\n\r\n*please note, these hours are subject to change without notice "; // I want "abc"

    var arr = /Location:\s*([^\v]*)\s*Features:\s*([^\v]*)Payment accepted:([^\r\n]*)/.exec(myString);

    console.log("Location --> "+arr[1]);
    console.log("Features --> "+arr[2]);
    console.log("Payment accepted --> "+arr[3]);
Answer: If I'm understanding this correctly and you're sure that the sections come in the same repeating order, then you can just put those regex back to back for each section.
Is something like this what you were looking for?
Location:\s?([\w\d ]+)\s{1,5}Features:\s+(.+)\s{1,5}Payment accepted:\s?(.+)
Comment: Could you include the regex itself in the answer instead of a link only?


Printing Int in struct prints address

Question: I'm reading an algorithms book and I found myself stuck on this bit. I create a doubly linked list and when I try to print out its contents it prints out what I believe is address or some other value that is not relevant to what I want. Here is the code:
typedef struct double_element *dElement;
struct double_element
{
    int value;
    dElement prev;
    dElement next;
};

dElement createNewDListWithElements(int count)
{
    dElement element = malloc(sizeof(dElement));

    element->value = 1;
    element->next = NULL;
    element->prev = NULL;

    dElement previous = element;

    for (int i = 1; i < count; i++) {

        dElement el = malloc(sizeof(dElement));

        el->value = i;
        el->next = NULL;
        el->prev = previous;
        previous->next = el;

        previous = el;
    }

    return element;
}

void printDList(dElement node)
{
    printf("printing doubly linked list:\n");

    while (node) {

        printf("%i\n", node->value);

        node = node->next;
    }

    printf("end printing double linked list\n");
}

Here is the output:

printing doubly linked list:
1
1070320
1070336
1070352
1070368
1070384
1070400
1070416
1070432
1070448
end printing double linked list

Comment: Please post the code where you call `createNewDListWithElements(int count)`. And your code is good, the only observation is that I would check that `malloc()` didn't return `NULL` before dereferencing the pointers.
Comment: ... i.e. post a whole program that demonstrates this behavior that others can simply compile and run.
Answer: Your problem is that you are trying to allocate space for a struct double_element, but you only ask for enough space to store a struct double_element*.
Comment: From what code did you end up with this conclusion?
Comment: @iharob  `typedef struct double_element *dElement; ... dElement el = malloc(sizeof(dElement));` --> `dElement el = malloc(sizeof( * el));`
Comment: I didn't understand the answer at first, it's not clear what it's trying to say, and yes it is correct.
Answer: The problem is that you are allocating space for a pointer instead of the struct itself, the reason the dangerous typedef of the pointer, if you want to guarantee the allocation is correct regardless of the typedef's in your code you can do this
dElement element = malloc(sizeof(*element));

that would allocate space for the struct, just as if you had called
dElement element = malloc(sizeof(struct double_element));

you can see that the typedef is harmful, a pointer should be explicitly a pointer, so the correct way to write the code without falling in this kind of issue is
struct double_element *element = malloc(sizeof(struct double_element));
/*                    ^ don't skip this no matter what */

also, you should make clear what the struct names are and how you name your variables, you could for example use CamelCase for the struct names, and lower case with underscores for your variables, something like this
struct DoubleElement *element = ...

it would make it clear that DoubleElement is the name of a struct, and even though you can leave the struct instead of tyepdefing it, because that makes it even clearer.

Printing Int in struct prints address