The parameter conversion from type 'System.String' to type 'RamalAguia.Models.Setor' failed because no type converter can convert between these types

Question: Durante a realização de um projeto me deparei com o seguinte erro:

System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'RamalAguia.Models.Setor' failed because no type converter can convert between these types.

Esse é meu Controller:
    [HttpGet]
    public ActionResult Create()
    {
        PreparaFormulario();
        return View();
    }
    [HttpPost]
    public ActionResult Create(RamalModel model)
    {
        if (ModelState.IsValid)
        {
            _db.Ramais.Add(model);
            _db.SaveChanges();
            return RedirectToAction("Index", new { id = model.ID });
        }
        else
        {
            PreparaFormulario();
            return View();
        }

    }

    [HttpGet]
    public void PreparaFormulario()
    {
        var setores = new List<Setor>();
        using (RamaDb db = new RamaDb())
        {
            setores = db.Setores.ToList();
        }
        ViewBag.ID2 = new SelectList(_db.Setores, "setorID", "setorNome");

    }

A View:
    @Html.DropDownListFor(model => model.setores, (SelectList)ViewBag.ID2)

E o Model:
 using System;
 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
 using System.Linq;
 using System.Web;

 namespace RamalAguia.Models
 {
 public class RamalModel
 {
    public int ID { get; set; }

    [Required(ErrorMessage = "O nome é obrigatório.")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "O número é obrigatório.")]
    public int Numero { get; set; }

    public Setor setores { get; set; }

Como posso arrumar?
Edit
Obs: eu consegui achar esse erro por meio de um breakpoint no    ModelState.IsValid, quando a aplicação vai salvar os dados passados, dentro dos values que eu uso para salvar o setor.
Model do Setor
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;

 namespace RamalAguia.Models
 {
    public class Setor
    {
       public int setorID { get; set; }

       public string setorNome { get; set; }

       public Area areas { get; set; }
    }
}

Edit2:
Classes:
RamalModel
    public class RamalModel
    {
    public int ID { get; set; }

    [Required(ErrorMessage = "O nome é obrigatório.")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "O número é obrigatório.")]
    public int Numero { get; set; }

    public int SetorId { get; set; }

    [ForeignKey("SetorId")]
    public Setor setores { get; set; }

Setores
    public class Setor
    {
    public int setorID { get; set; }

    public string setorNome { get; set; }

    public Area areas { get; set; }

E o dbcontext
    namespace RamalAguia.Models
    {
        public class RamaDb : DbContext
        {
             public DbSet<Usuario> Usuarios { get; set; }

             public DbSet<RamalModel> Ramais { get; set; }

             public DbSet<Setor> Setores { get; set; }

             public DbSet<Area> Areas { get; set; }
        }
    }

Answer: Seus relacionamento pelo visto estão errados, cade a chave da entidade Setor?
Seria mais ou menos isso, já que não colocou a outra classe da relação:
public class RamalModel
{
    public int ID { get; set; }

    [Required(ErrorMessage = "O nome é obrigatório.")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "O número é obrigatório.")]
    public int Numero { get; set; }

    public int SetorId {get;set;}

    [ForeignKey("SetorId")]
    public Setor setores { get; set; }
}

public class Setor
{
    public int ID { get; set; }

    [Required(ErrorMessage = "O nome é obrigatório.")]
    public string Nome { get; set; }

    [ForeignKey("SetorId")]
    public ICollection<RamalModel> RamalModel {get;set;}
}

Naquele DropDownList ficaria assim então:
@Html.DropDownList("SetorId", (SelectList)ViewBag.ID2)

ou faça assim que é mais usual:
No controller crie um ViewBag com o mesmo nome da chave da relação que é SetorId, siga o modelo:
ViewBag.SetorId = new SelectList(_db.Setores, "setorID", "setorNome");

e seu DropDownList com esse modelo:
@Html.DropDownList("SetorId")

Comment: Obrigado pela resposta, porém quando vou fazer update na base de dados aparece isso no Package Manager Console: Cannot insert the value NULL into column 'SetorId', table 'RamalAguia.Models.RamaDb.dbo.RamalModels'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
Comment: Como estão suas tabelas, me passe isso por favor. Você esta mandando item sem valor esse é o erro.
Comment: CREATE TABLE [dbo].[RamalModels] (
    [ID]              INT            IDENTITY (1, 1) NOT NULL,
    [Nome]            NVARCHAR (MAX) NOT NULL,
    [Numero]          INT            NOT NULL,
    [setores_setorID] INT            NOT NULL,
    CONSTRAINT [PK_dbo.RamalModels] PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [FK_dbo.RamalModels_dbo.Setors_setores_setorID] FOREIGN KEY ([setores_setorID]) REFERENCES [dbo].[Setors] ([setorID])
);
Comment: Tem erro na geração da sua tabelas o problema esta ai.
Comment: Coloque todas as classes e seu dbcontext para eu te ajudar
Comment: Vou colocar em uma nova resposta, melhor vou editar.


Question About Summation of Summations

Question: I am trying to figure out the value of $$\sum_{i=2}^4\sum_{j=2}^i j$$
I thought of having a two for loops, one nested inside of the other, so:
<code>for(int i = 2; i <= 4; ++i) {
    for(int j = 2; j <= i; ++j) {
        sum += j;
    }
}
</code>
So I got:
i = 2, j = 2: 2
i = 3, j = 2: 2 + 2
i = 3, j = 3: 2 + 2 + 3
i = 4, j = 2: 2 + 2 + 3 + 2
i = 4, j = 3: 2 + 2 + 3 + 2 + 3
i = 4, j = 4: 2 + 2 + 3 + 2 + 3 + 4 = 16
But I know this is the incorrect answer, and I'm not sure why.
Any help would be greatly appreciated!
Comment: Why are you so sure this is incorrect? I don't see anything particularly wrong.
Comment: what do you think is the correct answer
Comment: Note that $\sum_{j=2}^i j=\frac{i(i+1)}{2}-1$. So, you may use this.
Comment: the top answer in https://math.stackexchange.com/questions/238834/how-do-you-write-the-summation-of-a-summation is why I think my answer is incorrect
Comment: Better to use `i++` and similar.
Comment: How is that sum relevant? It's the sum of $1/j$ not $j$, and $n$ is arbitrary, not necessarily $4$.
Comment: I know, but I wanted to give an example without any arbitrary variables, and the idea is the same regardless whether its 1/j or j
Comment: Oh each line is being summed up!
Comment: Looks right to me
Answer: Your calculations are fine. Recall the sigma operator $\sum$ works as follows:
\begin{align*}
\sum_{i=a}^bf(i)=f(a)+f(a+1)+\cdots+f(b)
\end{align*}

We obtain by first expanding the outer sum and then the inner sum:
  \begin{align*}
\color{blue}{\sum_{i=2}^4}\color{blue}{\sum_{j=2}^i  j}
&=\sum_{j=2}^2j+\sum_{j=2}^3j+\sum_{j=2}^4j\\
&=(2)+(2+3)+(2+3+4)\\
&\,\,\color{blue}{=16}
\end{align*}

Question About Summation of Summations


Ring isomorphism between a quotient ring and its image under a homomorphism

Question: I've got this question on Atiyah Commutative Algebra (first chapter, "Ideals and Quotient Rings" section).
Given a ring $A$ and a ideal $a \subseteq A$, there is a natural projection $\pi: A \rightarrow A/a$, $\, \, \, x \mapsto \pi(x) = x+a$, which is surjective. Then, given a ring $B$ and a homomorphism $f \in Hom(A,B)$, we have $A/a \cong f(A)$.
I've tried to manipulate $f$ and $\pi$ to get to this isomorphism $\phi$, which, in my guest, would be like $\phi (x) := f(\pi^{-1}(x))$. But, I've got stuck on the "bijection part" of the proof.
I would appreciate any comment on this little part of the book :)
Comment: You seem to have neglected to mention this, but in your statement that $A/a \cong f(A)$, you must be assuming that $a = \ker(f)$.
Answer: Be careful with the map $\phi$ that you've defined since it actually isn't well defined! For instance, suppose that your ideal $a$ has two elements $x$ and $y$. Then, $x + a = y + a$, so $\pi^{-1}(x+a)$ is not a singleton (both $x$ and $y$ are in the pre-image). We also need to be careful about the ideal $a \subset A$ - it's not just any old ideal - in Atiyah's book, $a$ is stated to be the kernel of $f$!
Instead, define a map $g: A/a \to f(A)$ by sending $x + a \in A/a$ to $f(x)$. That is, $$g(x+a) := f(x)$$
We need to show this map is well defined. Indeed, if $y \in x+a$, then $y = x + m$ for some $m \in A$. Hence, $$f(y) = f(x+m) = f(x)+ f(m) = f(x)$$ as $m$ is in the kernel of $f$. So indeed, we will have $g(x+a) = g(y+a)$ and our map is well-defined. To show $g$ is injective, suppose $g(x+a) = g(y+a)$. Then, this says that $f(x) = f(y)  \implies 0 = f(x)-f(y) = f(x-y)$. Hence, $x-y$ is in the kernel of $f$ (i.e. $x-y \in a$). This will in turn, because of the axioms of an ideal, imply that $x + a \subset y + a$. But I could run the argument again by noticing that $0 = f(y) - f(x) = f(y-x)$, so $y-x \in a \implies y+a \subset x+a$. Thus, $x+a = y+a$, and we have shown injectivity.
To show surjectivity, suppose $b \in f(A)$. Then, there exists $x \in A$ such that $f(x) = b$. Then, $g(x+a) = f(x) = b$.
Comment: I've noticed my mistake. He states "the kernel of $f$ is an ideal $a \subseteq A$" and then "$f$ induces a ring isomorphism", between the quotient of $A$ by this same ideal $a = Ker\{f\}$. Thanks for the help ;D


Why are American teams always named in a certain format?

Question: American teams are always named as [city/region team is from] + [team's actual name]
Los Angeles Lakers, Denver Broncos, NY Yankees, Chicago Fire, etc.
Is there a specific reason for that?
Comment: @MichaelMyers Their name was Kansas City Wizards before that. They changed it in 2010, probably in an attempt to look more European-like just like how other MLS teams also do.
Comment: Most likely because these teams are trademarked names of a company property, not representatives of an associated sports group.
Comment: @Nij Companies being NFL or NBA I assume?
Comment: @leDominatre: There are some exceptions, such as Sporting KC, which are generally straight copies of English or European football club names.
Answer: The answer to why all the U.S. professional teams are named this way (Location Nickname) today is because it is tradition.  Baseball teams were named this way, and football, basketball, hockey, and soccer (in the U.S.) all came after baseball.
Baseball teams weren't always named this way, however.  The National Association of Professional Base Ball Players was the first professional baseball league (1871-1875).  A few teams in this league had modern sounding names (Boston Red Stockings, Chicago White Stockings), but many teams in this league had official names like Mutual Baseball Club of New York, Athletic Base Ball Club of Philadelphia, Union Base Ball Club Lansingburgh, Lord Baltimore Club, etc.  Box scores in the newspaper would shorten these club names to one word, based on either their city or their club name: Boston, Chicago, Mutual, Athletic, Troy, Lord Baltimore, etc.  The sportswriters would give the teams their own nicknames, usually based on the colors of their uniforms or the name of their field.  For example, the Union Base Ball Club Lansingburgh played at Haymakers' Grounds in Troy, NY.  As a result, their team was often called the Haymakers or the Trojans.  Lord Baltimore got the nicknames Canaries and Yellow Stockings, because of the uniforms.  Modern sportswriters, in writing about the history of these old teams, have retroactively assigned modern style names to some of these teams: they are now referred to with names New York Mutuals, Philadelphia Athletics, Troy Haymakers, and Baltimore Canaries.
In 1876, six clubs from the National Association broke off and started the current National League, including two teams with old style names: Mutual and Athletic.  Those two teams lasted only one season, and all that was left in this baseball league were teams with the modern name format.
There are several advantages of the Location Nickname format.  When reading or hearing about the team, you immediately know where the team is located.  It allows for there to be more than one team in a single city or more than one team with the same nickname, yet have unique names for each.  It also is an attempt to build a fanbase; having your city name (or region name) in your team name is supposed to signify that you are the official team of your city, and everyone who lives there should be a fan.
Comment: @Coach-D Maybe tradition isn't the best word, but my point in the first sentence is that this style of name was already established as the standard before football and basketball took off. That's why the rest of the answer focuses on baseball.
Comment: @Coach-D I think the reasons why are in your answer (which I upvoted) and in my last paragraph.  And yes, small rec leagues entirely contained in one town do not do this, for obvious reasons.
Comment: So you are saying the US started the tradition?
Comment: @Coach-D I don't know where/when this style of name started, but I would say that this is where the other style of name fell away in the U.S.
Comment: Just saying it isn't really tradition if it copies another region because of another reason.  By that logic everything is tradition then.
Comment: OK but why did baseball use this as a standard?  I gave you a plus one for the history but saying baseball just did it and the others followed.  Well that's not right.  If there was a hockey league with 10 teams in a town you would see something else.
Comment: I think if we combined ours there might be a better answer, whatever people can find it easy.
Answer: In most places in the world there is a considerable amount of space between different competing teams in the same league.  The naming convention used in the US is not just the US but is also many/most sports teams in the world.  I played a little basketball in France and yes all of the teams use that convention, albeit with more emphasis on the city name.
Really it is either about league rules or selling tickets or both.  You want to associate with a local city with a high population because most of the tickets will need to come from that fan base.  I would say that many teams in the big 4 sports in the US have stadiums that are not in the city of their name but often a town close to the bigger city.
A couple of examples:

New York Giants and Jets, which both play play in New Jersey.  The name New York though keeps allegiance with 95% of the regional population to those teams.
MLB's Angels changed their "city name" to California.  It is obvious they were done competing with the Dodgers at the time and wanted to appeal to people in cities outside of L.A. more.  Not sure it worked at all but that was the reason.
San Francisco 49ers wanted a new stadium.  SF is totally built out.  So they built a stadium in Santa Clara which by any means cannot be considered even a suburb of SF.  They kept the SF name due to the historical significance and population that would buy tickets.

Why Manchester United and other teams in the UK don't follow that trend is exactly the same reason.  There are a lot of teams competing for fans that can all drive to their games.  Also the actual cities where they play aren't that big comparatively to the US based metro areas.  So the last thing they want to do is put a city name in front and then possibly disengage fans from that team because they don't live in that city or don't like that city.
There are leagues that have naming rules but really I doubt a league would care unless there was vulgarity or some insensitivity in the name.  Really the league wants teams to be successful and has to respect a team's decision to name their team what they want to help sell tickets and stay afloat.
Note: In relation to Ben's answer, which is good, I would like to add that in many parts of Europe (I honestly don't know about Asia/Africa so chime in if you do) sports were regulated through local clubs.
In the US for the most part sports are denoted by town when growing up (you play for Smithsville little league), then by school (high school and college) then by town/mascot for professional.
This is very different from the club system which we have in the US (soccer and AAU basketball to name to biggies) but they are no where near as prominent as Europe where for the most part schools have nothing to do with sports and everything filters through club systems.
Comment: The irony of saying that [Manchester](https://en.m.wikipedia.org/wiki/Manchester) United don't want to put a city name at the front of their title is amusing.
Comment: Aside from some London based teams, of whom some do use names based on their location, it also doesn't quite hold up when looking at the bigger picture I'm afraid. The Man Utd example is a winner though :D


Probabilities of blown-away package ownership, based on frequency and distance

Question: Yesterday, because of high wind, a package got blown into our backyard.
We weren't sure whether the package belonged to us or to one of our five neighbors.
It occurred to me that if we knew the frequency with which each neighbor receives packages, we might be able to calculate the probability that the package was blown from each house's doorstep.
But because all of our doorsteps are different distances away from where the package was found, we would have to factor in not only the frequency, but also the distance from each doorstep to the location where the package was found.
I know how to compute the probabilities based only on frequency, but I'm not quite sure how to also factor in the distance.  Any tips?
P.S. In case you're curious, although our household probably receives more packages than any of our neighbors, the package that we found in our backyard belonged to the neighbor furthest away from us!
Answer: You are asking what is the probability that a package belongs to a certain neighbor given that it is in your yard? If $Y$ is the event a package is in your yard and $X$ is the random variable representing which neighbor it belongs to, then you are asking what is $P(X=i|Y)$, the probability that $X$ is a particular neighbor  $i$ given that $Y$. By Bayes formula,
$$P(X=i|Y) = \frac{P(Y|X=i) P(X=i)}{\sum_kP(Y|X=k)P(X=k)}$$
where the sum in the denominator is over all neighbors in your event space.
Each $P(X=i)$, the probability that a randomly selected package belongs to a certain neighbor regardless of where it is found, might be modeled as the relative frequency, call it $\pi(i)$, at which that neighbor receives packages compared to total package delivery to your neighborhood.
Each $P(Y|X=i)$, the probability that a package for neighbor $i$ ends up in your yard, might be modeled as a function of distance to your yard. A simple model would be that the probability is inversely proportional to the square of distance, that is, $P(Y|X=i) = \alpha / d_i^2$, for some constant of proportionality $\alpha$. However, this constant will cancel out, leaving the model
$$P(X=i|Y) \approx \frac{\frac{1}{d_i^2} \pi(i)}{\sum_k \frac{1}{d_k^2} \pi(k)} $$
Obviously, you could refine this model in all sorts of ways. For example, you might graph out the geometry of your neighborhood, including your yard, and model the path of the wind-blown package as a two-dimensional random walk. Then, the model becomes what is the probability that a random walk from a neighbors stoop is within your yard at a certain time? And then consider when in the day/week each neighbor typically receives packages with respect to when it was windy. You could devise models for wind speed and direction given weather patterns. You could considering fencing and walls both in permissible package paths and their effect in channeling wind. And so forth, and so on. However, it would probably just be easier to read the label.
Comment: > However, it would probably just be easier to read the label.

This cracked me up!  And thank you for your wonderful answer.


Melhor método para localizar valores em um DataTable

Question: Em uma tela de cadastro de unidade de medida, tenho que verificar se a unidade que o usuario esta querendo cadastrar, se ja existe, entao como tenho um DataGrid populado por um DataTable, pensei em percorrer o DataTable e verificar se esse ja existe.
Então fiz o codigo assim:
 //botão salvar
 private void simpleButton2_Click(object sender, EventArgs e)
    {
        //Verifico se os dois textbox estao preenchidos
        if (textBox1.Text != string.Empty && textBox2.Text != string.Empty)
        {
            // defino minha string de filtro
            string exp = "SIGLA = " + "'" + textBox2.Text + "'";
            // Executo a busca com base no meu filtro
            DataRow[] find_sigla = dat.Select(exp);

            // se o retorno da busca for 0 faz a ação
            if (find_sigla.Count() == 0)
            {
                //Insiro o valor no banco
                Classes.Cadastro.Cadastro_estqUn cad_estqun = new Classes.Cadastro.Cadastro_estqUn();
                if (cad_estqun.cadastro_unidade(textBox1.Text, textBox2.Text) > 0)
                {
                    textBox1.Text = "";
                    textBox2.Text = "";
                }
            }
            else
            {
                MessageBox.Show("Unidade de medida já cadastrada.", "Salvar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
    }

Então ouvi dizer, que esse método tenho perca de performance, procede? alguém tem alguma solução melhor?
Obrigado.
Comment: Seu dat está sendo carregador como?  E qual sua intenção!
Answer: Eu não confiaria no que está na DataGrid, mas sim no que está no banco de dados.
Um exemplo hipotético mas se aplica a outras situações reais:
"Seu sistema tem um servidor de banco de dados e 3 estações de trabalho. Seu usuário abriu essa tela e tinha 5 unidades de medidas, mas foi almoçar. Enquanto ele almoçava alguém cadastrou a unidade de medida que ele ia cadastrar. Vai duplicar no banco de dados se ele cadastrar depois do almoço, pois a DataGrid está desatualizada."
Nessa sua classe Cadastro_estqUn faça uma implementação que verifique no banco de dados se já existe o registro com a descrição. Seria algo assim:
public bool UnidadeMedidaUnica(string nome)
{
  string sql = "SELECT COUNT(*) FROM tbUnidadeMedida WHERE unidade_nome = @nome";
  SqlCommand cmd = new SqlComman(sql, connectionString);
  cmd.Parameters.AddWithValue("@nome", nome);
  SqlDataReader mySqlDataReader = cmd.ExecuteReader();
  int qtde = (int)cmd.ExecuteScalar();
  return qtde == 0;

}
Para melhorar ainda pode adicionar um "unique index", que vai garantir que até instruções SQL disparadas diretamente no banco de dados dupliquem registros.
CREATE UNIQUE INDEX idx_unidade_nome ON tbUnidadesMedida(unidade_nome)

Comment: Realmente Murilo, essa situação pode acontecer, e com certeza e frequente. Fiz a implantação realizando um `COUNT` na tabela de unidade de medida em questão.


$\int_{0}^{1}\frac{1}{x^p} \not= 1$?

Question: Is the following statement true: $\int_{0}^{1}\frac{1}{x^p} \not= 1$. This is for any $p \in \mathbb{R}$. I gave an counterexample with $p=-2$ then the integral is $\int_{0}^{1}\frac{1}{x^-2}=1$ exactly. But I'm bad at math, so I want to make sure is right.
Comment: @judgeKevin It's okay to feel stuck with problems sometimes; that doesn't mean you are automatically bad at math. Math just takes time; so power to you my friend to keep at it. Like you clearly see; people supposedly here to help you (aka me), slip up too! (like I did in my reply comment)
Comment: Hint: $\int_0^1 x^p dx = \frac{1}{p+1}$. Can you find a $p$ such that $\frac{1}{p+1} = 1$?
Comment: @ArunBharadwaj Note OP wants to integrate the *reciprocal* of $x^p$ over $[0,1]$.
Comment: The counter-example is when $p=0.$ Using your example $p=-2,$ the value of $1/(x^p)$ is $x^2$ and the integral is $1/3 \neq 1.$
Comment: Ok, so it's wrong again. See, I am bad at math.
Comment: @coffeemath oops! Thank you for catching that haha (It is too late into the night on this side of the globe).
Answer: The Power Rule of Integration states
$$\int x^p\,\text dx=\frac{x^{p+1}}{p+1}+C$$
So,
$$\int_0^1\frac{\text dx}{x^p}=\left[\frac{x^{-p+1}}{-p+1}\right]_0^1$$
$$=\frac{1^{1-p}}{1-p}-0=\frac{1}{1-p}$$
If this is to be one,
$$1-p=1\implies \boxed{p=0}$$
Hence, the statement is false for $p=0$.
Hope this helps. Ask anything if not clear :)
Comment: Note the antiderivative is actually $\ln(x)$ in case $p=-1.$ That doesn't affect your answer since you eventually get $p=0.$ [+1 on answer]
Comment: Ok, so it's wrong again. See, I am bad at math.
Comment: @coffeemath: Of course, because the fraction is not defined for $1+p\neq0$. Thanks for reminding!

$\int_{0}^{1}\frac{1}{x^p} \not= 1$?


Why the clear question was marked as unclear?

Question: Today I wrote the answer to an one-line simple question ("How to get product through api using product name" - which is totally clear for me) but some other people marked it as unclear. I cant understand how this one-line question can be unclear.
I pressed "reopen the question", but I can't understand by what these people are guided when they choosing a "close as unclear what you asking" on the totally clear question?
PS: Users who voted are not a newbies:

Manashvi Birla (6,084 rep)
Jai (3,375 rep)
Dhiren Vasoya (4,235 rep)
Murtuza Zabuawala (12,290 rep)
Sukumar Gorai (6,265 rep)
Comment: Sorry bro, many times you don't spend much time to read the details and follow what others had done previously, I will try to focus more in review queue
Comment: Only thing that I would add is that the question is not really formatted as a question, and could therefore be marked as unclear. "I want to get product information using product name in Magento 2" is more like a statement than a proper question as such. Changing it to "How can I get product information using the product name in Magento 2?" would improve it slightly.
Answer: Siarhey Uchukhlebau, Thanks for raising the concern.
Question is clear to me and also answer is OK. Now Question is Opened.
I guess that these people might do the mistake.
At some times, the people did the mistake on Harry. As a community member, I requesting all members to take your time to read the question and check what is the composition of the question and what would be the probable answers before creating the flag.
Comment: Thank you for your answer. But I can't understand how 5 not-a-newbie persons can make a mistake at one time?
Comment: I cannot answer this question.Might be they can :)
Comment: @SiarheyUchukhlebau I answer in your question about this
Answer: This is sadly a common issue when people try to keep the site clean from unanswerable questions.
The Issue lies in Questions which are short and direct. If you know the context, that's sometimes a very easy to answer question.
But for someone who does not know the context, because they never worked in this area, they don't understand what the question is about and only see that it is very short and does not contain much information. They don't realise, there is no need for more information.


Rust cannot borrow `var` as mutable, as it is behind a `&` reference using zip

Question: The code is:
fn iter_and_make_feature_dataframe(df: &DataFrame) {
    // iter over rows
    // let columns = columns.unwrap_or(vec![]);
    let col_len = df.shape().1;
    let columns = df.get_column_names();

    let mut df = df.clone();
    df.as_single_chunk();

    let mut iters = df.iter().map(|s| s.iter()).collect::<Vec<_>>();

    let mut row: Vec<Vec<String>> = Vec::new();
    for row_idx in 0..df.height() {
        let mut c_row: Vec<String> = Vec::new();
        for iter in &mut iters.iter().zip(&columns) {
            let (value_iter, col_name) = iter;
            let value = value_iter
                .next()
                .expect("should have as many iterations as rows")
                .to_string();
            c_row.push(value);
        }

        // process row
    }
}

rust analyzer said :
error[E0596]: cannot borrow `*value_iter` as mutable, as it is behind a `&` reference
  --> src/main.rs:24:25
   |
23 |               let (value_iter, col_name) = iter;
   |                    ---------- consider changing this binding's type to be: `&mut SeriesIter<'_>`
24 |               let value = value_iter
   |  _________________________^
25 | |                 .next()
   | |_______________________^ `value_iter` is a `&` reference, so the data it refers to cannot be borrowed as mutable

How can I fix this? I want to process a dataframe row by row and make a new dataframe with the processed rows.
Comment: First, run `cargo check` and if it suggests changes, do what it says. If you're still stuck, then post the whole error from `cargo check`.
Answer: You need to use iter_mut() instead of iter() to advance the iterators:
for iter in iters.iter_mut().zip(&columns) {
    // ...
}


Numpy Import "Aborted"

Question: I am working on a linux server with a root installed python2.7 (/usr/bin/python2.7). Then I tried to install Numpy into this by downloading the source and doing python2.7 setup.py build; python2.7 setup.py install --user. Numpy neatly installs to ~/.local/lib/python2.7/site-packages/numpy. I get:
$ python2.7
Python 2.7.2+ (default, Dec 22 2011, 12:26:43)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Aborted
$

Where do I even start? I've never seen this before!
(FYI, the default python (2.6), has a working numpy install in /usr/lib/pymodules/python2.6/numpy)
As requested, a stacktrace, (and thanks for the instructions on that!). Whole thing here on pastebin.
Program received signal SIGABRT, Aborted.
0x00002aaaabdb31b5 in *__GI_raise (sig=<value optimized out>)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
64  ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
    in ../nptl/sysdeps/unix/sysv/linux/raise.c
(gdb) bt
#0  0x00002aaaabdb31b5 in *__GI_raise (sig=<value optimized out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#1  0x00002aaaabdb5fc0 in *__GI_abort () at abort.c:92
#2  0x00002aaab03fb9bd in free () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#3  0x00002aaab03f8312 in ?? () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#4  0x00002aaab03f8924 in ffi_closure_alloc () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#5  0x00002aaab03f0af2 in _ctypes_alloc_callback () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#6  0x00002aaab03eee68 in ?? () from /usr/lib/python2.7/lib-dynload/_ctypes.so
#7  0x00000000004b6ed5 in ?? ()
#8  0x0000000000425cdc in PyObject_Call ()

Comment: A stack trace would go a long way, perhaps. You could also try running python directly in gdb: `gdb $(which python2.7)` then at the prompt `r` and then do your `import numpy`.  Then after it aborts, run `bt` and post the result here.
Comment: Looks like that numpy build is killing python. I would just try to install another version of numpy. If you feel investigative you could "ulimit -c unlimited" to make it create a coredump and then look at it using gdb.
Answer: This looks like a versioning issue. Make sure you are not inadvertently loading into Python 2.7 a module built for Python 2.6.
The first things to check would be $PYTHONPATH and sys.path.
Comment: I don't see anything pointing to 2.6. `sys.path == ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '~/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']`
Answer: I never found out what was causing this, but I had the admin install numpy as root and it works now.

Numpy Import "Aborted"


Por que existem tantas linguagens de programação?

Question: Há várias décadas, as linguagens de programação surgiram para facilitar a vida dos programadores e indiretamente, do público geral também.
No início, tudo era feito com botões que representavam números binários. Então as pessoas perceberam que acabavam sempre apertando os mesmos botões em sequência várias vezes, então vieram os cartões perfurados.
Depois elas perceberam que podiam escrever um programa em um computador que permitisse elas escreverem o código ali, surgindo então as primeiras linguagens de programação, como FORTRAN e LISP.
O tempo foi passando e cada vez mais linguagens foram surgindo como C, COBOL, BASIC, entre outras.
Mas por que cada vez mais linguagens foram surgindo? Mesmo sabendo que as primeiras linguagens eram complicadas, o que justifica o surgimento de novas nos dias de hoje? Atualmente, existem mais de 400 linguagens de programação, podendo existir até mais milhares de linguagens, e na maior parte do mundo, menos de 25% delas são usadas.
Sendo assim, por que existem tantas linguagens de programação?
Comment: Existem linguagens de programação mais ou menos indicadas para cada uma das múltiplas classes de problemas a serem resolvidos. Agora você está sendo muito modesta, a última vez que pesquisei existiam mais de 2.500 diferentes linguagens de programação
Comment: Li por cima as respostas, mas não vi comentarem, então vou comentar algo aqui, existem linguagens simplesmente criadas por algum "capricho" pessoal (php eu vejo como um exemplo disto) ou entretenimento (geralmente linguagens "esotéricas"). No caso do PHP, Rasmus a criou para seu uso pessoal e realmente era diferente do que é hoje, na verdade a ideia dele sobre linguagens as vezes era um pouco equivocada, mas não vou criticar, o foco é que a linguagem foi adotada por uma "comunidade" e eles evoluíram ela, ou seja, deixando de ser o que era [...]
Comment: [...] então seu motivo inicial não foi bem resolver algo que outra linguagem não conseguia, foi inicialmente para ser algo pessoal que ele muito bem poderia ter feito com outro interpretador, como era comum na época, talvez o Perl (na época geralmente se usava CGI (porta/protocolo))... Outros possíveis (sobre outras linguagens) motivos provavelmente são o "comercial/marketing", ou seja uma empresa de tecnologia que desenvolve a própria linguagem deve ser algo "incrível" aos olhos do "mundo" (ao menos assim as pessoas esperam)
Comment: Pra celebrar a pergunta, achei curioso porque vi esse vídeo ontem https://www.youtube.com/watch?v=Og847HVwRSI
Answer:
Um dos motivos é que existem muitos problemas diferentes, necessidades que não podem ser supridas por um só modelo de programação. Mas isso envolve o certo grau de falácia, falo mais abaixo. O motivo oficial é este, os demais são secundários. Para isso ser exercido de forma adequada a linguagem precisa ser de um paradigma diferente.
Salvo algo bem pontual linguagens não são melhoradas para atender evolução do hardware, pelo menos não por razões técnicas, já que por razões políticas do fornecedor do hardware pode haver a adoção ou crianção de nova linguagem. Também não existe isso por causa de sistema operacional.
Em algum ponto podemos dizer que é porque existe pregos e parafusos e por isso precisa de ferramentas diferentes, mas quando o cabo é de plástico ou madeira, ou metal, ou é curvado ou tem outras características é porque tem gente que gosta de jeito diferente, não porque é necessário.

Um ponto secundário deste é que linguagens sempre possuem falhas e uma nova vem para dar uma solução para estas falhas. Muitas dessas falhas são subjetivas, o que permite sempre alguém achar um motivo para fazer algo diferente. Não tem como fazer uma linguagem perfeita, uma característica positiva tende impedir uma outra ou cria um negativa.
Uma linguagem é difícil de gerenciar a memória? Cria outra que faz isso de forma mais simples. Uma linguagem exige escrever código demais e expressar com oas coisas realmente são? A linguagem não permite escrever códigos muito grandes com facilidade? Uma linguagem é legal mas na forma exatamente construída é ineficiente? Tudo isso pode ser resolvido usando a base do que já existe, ma mudando alguns detalhes que resolvem esse problema.

Outro motivo é que as pessoas querem ter um certo domínio de mercado ou marcar sua posição na história, então elas acham alguma coisa que pode ser feita de um jeito um pouco diferente mesmo que não seja tão diferente assim. Isto pode acontecer porque as pessoas tendem a gostar de coisas por causa de pequenos detalhes.
Por que existem tantas marcas e variedades de tantos produtos? Pelos motivos que falei acima, então linguagem de programação não é diferente. Por que você precisa de um carro branco e outro azul? Isso não muda nada na vida das pessoas.
É claro que uma nova linguagem resolve um problema encontrado em outra linguagem, mesmo que este problema não seja tão relevante, mas a maior questão é que as pessoas querem fazer coisas diferentes. Faria sentido ter algumas poucas linguagens muito diferentes, o resto é só briga por espaço. É até uma falácia parcial essa questão de que cada uma atende uma necessidade diferente. Claro que em parte isso é verdade, mas parte é só atender um gosto diferente. Salvo em alguns cenários faz pouca diferença usar uma coisa ou outra.
Então o motivo real é que as pessoas gostam de cosias diferentes e tem gente que quer suprir isso.

Por que existem vários tipos de computadores? Ou de carros? Muitos deles não existem de fato mais porque se tornaram obsoletos, eles eram bons na época que foram criados, mas hoje não mais. Com linguagem se dá o mesmo, com a diferença que ela não desgasta com o tempo e ainda pode ser usada.
Novamente, quem criou algo no passado tenta manter seu produto relevante e faz melhorias. Isto só funciona porque tem quem goste.

Em essência todas linguagens de programação conseguem fazer tudo o que é necessário e algumas são ligeiramente melhores em algum ponto específico. Muitas vezes você vê mais diferença na implementação de uma linguagem do que de uma linguagem para outra.
Linguagens são formas de expressão então cada um tem um jeito preferido de fazê-lo. Em alguns casos esse jeito pode ser mais fácil para certos cenários. Não é tão diferente de línguas naturais. Inclusive algumas servem melhor do que outras. Algumas servem melhor para assuntos técnicos outras servem melhor para cenários artísticos.
Já notou uma força muito grande das pessoas tentarem evangelizar sobre o uso de uma determinada linguagem? As pessoas sabem que maior adoção gera maior adoção e isso se faz necessário. A maioria das adoções são feitas pelo marketing, mesmo espontâneo, e não pela característica técnica real. Claro que é raro adoções muito fora de parâmetro, mas também é raro ter alguma coisa que seja muito complicado fazer em linguagens diferentes.
Atualmente existem milhares de linguagens de programação e cada um tem o direito de criar sua própria, o que vai determinar se ela será conhecida é o quanto se consegue divulgá-la e ter aderência de outras pessoas. E milhares são usadas, só varia a quantidade do uso.
Muitas linguagens não são criadas para serem produtos viáveis e sim experimentos ou evoluções de alguma existente.
Muitas vezes eu vi pessoas adotarem uma linguagem não por ela ser diferente mas por ela ter uma biblioteca que as pessoas queriam usar daquele jeito. Inclusive alguns acham que uma mudança na biblioteca cria outra linguagem quando isso não é verdade.
Fato é que existem literalmente infinitas combinações possíveis de se fazer em uma linguagem. Cada um enxerga uma combinação como melhor que outra.
Fica até mais fácil avaliar linguagem contra linguagem sobre isso. Por exemplo, existe um motivo para as pessoas usarem C ou C++ e não é performance como muitos acham, só pessoas ingênuas acham isto. Vou tentar colocar algumas motivações que vemos por aí para dar um visão geral de como as escolhas são feitas. Claro que estou fazendo simplificações.
C foi criada para ser um Assembly portável. E ser algo mais fácil de expressar que ALGOL que é uma linguagem fantástica mas muito chata de usar.
C++ foi inicialmente criada para adicionar classes em C, de dar melhores abstrações sem pagar nada por isso.
Java foi criada para ser um C++ melhor (nunca chegou nem perto disso, é pior que C++ em quase tudo que não envolve robustez).
C# foi criada para a Microsoft ter uma alternativa ao Java já que ela foi proibida de evoluir o Java. E também para ser o que Java disse que seria, ou seja um C++ melhor, então ela ficou no meio termo entre C++ e Java.
A grande diferença destas linguagens para C++ é o gerenciamento de memória.
VB.NET é o VB para o .NET. VB é o BASIC mais adequado ao Windows e que a Microsoft podia controlar a evolução. Tem uma quantidade incomensurável de dialetos BASIC. Esta linguagem surgiu para ser uma alternativa simples ao que existia por aí como FORTRAN ou COBOL.
F# existe para ter uma pegada funciona no .NET, baseada inicialmente em OCaml.
Pascal deveria ser ALGOL mais pragmática.
Delphi seria o Pascal com classes, uma tentativa da Borland de manter seu mercado em torno do Pascal em face das novidades que surgiam.
Objective C foi criada por descontentamento de alguns com a forma do C++ lidar com orientação a objetos. Swift foi criada porque Objective C tinha problemas demais e ainda mantinha o legado de C.
R foi criada para facilitar estatísticas. É uma das poucas linguagens que impõe uma diferença real que faz sentido existir além de gosto.
Rust foi criada porque C++ tem muitas falhas e Java e assemelhados possuem tracing garbage collector.
Go foi criada para ser C com GC e corrigir alguns erros dessas linguagem, além de permitir melhores abstrações (mas nem tanto em alguns casos), e também pra compilar rápido. Assim como acontece em outras linguagens, o mercado vai para outro lado e os objetivos mudam. Nem sempre o criador consegue manter a linguagem do jeito que ela pensou, as pessoas podem adotá-la, mas ter outras ideias.
D foi criada porque C++ era complexa de mais. Não deu tão certo e estão reformulando os objetivos.
Dart foi criada porque JS era muito ruim.
Scala nasceu para ter uma vertente mais funcional para Java
Kotlin surgiu para ter uma alternativa sem os problemas do Java rodando na JVM (tinha outros objetivos inicialmente, mas foram abandonados).
Eifell foi criada para demonstrar que é possível fazer herança múltipla e como é o uso de contratos.
Haskell surgiu para ensinar Haskell para as pessoas :P :D
Dizem que V foi criada para arrecadar dinheiro de incautos (não sou eu que disse isso :) ).
JavaScript surgiu para permitir customizar páginas web com comportamentos, e por isso deveria ser uma linguagem simples e fácil de usar, não para fazer aplicações. Boa parte das escolhas feitas para ela foram por falta de escolha, ou pelo menos falta de tempo para escolher fazer coisas melhores.
TypeScript foi criada para colocar tipos e mais organização em JS, permitindo assim aplicações.
PHP foi criada para facilitar o trabalho de criar páginas web onde o C que era usado pelo criador era muito complicado.
Python, Ruby, Perl e outras surgiram para serem algo parecido, ou pelo menos para serem capazes de fazer scripts de forma mais simples do que C, Pascal ou outra linguagem do tipo, mas mais poderoso que awk, bash e outros shells. Ruby queria por OOP em scripts, linda ideia.
Python por exemplo tentou dar um ar de linguagem funcional mas com o jeito imperativo que todo mundo está acostumado, que é uma receita para o sucesso, porque linguagens funcionais são simples e bonitas, mas ruins para certos padrões de uso. Daí vem a indentação para definir bloco.
Groovy existe para ser uma alternativa dinâmica ao Java.
Lua foi criada porque precisavam de um tecnologia brasileira para fazer scripts simples e com performance embarcando em outras aplicações.
Boo deveria ser um Python melhor rodando no .NET, mas morreu por falta de comunidade e comprometimento do criador, talvez porque C# melhorou boa parte das coisas que Boo trouxe.
Elixir deveria ser Erlang dinamicamente tipada entre outras "melhorias".
dBase foi criada para suportar um banco de dados simples. Clipper foi criada inicialmente como um compilador de dBase, mas depois preciso evoluir para poder criar aplicações completas. Harbour foi criada para atender quem ficou órfão de Clipper e acabou tendo uma evolução natural para atender novas demandas. FoxPro deveria ser o Clipper de outra empresa para ganhar um pouco dos rios de dinheiro que a Nantucket estava ganhando. Tem outros dialetos criados cada um por interesse de uma empresa.
Essas últimas linguagens costumam abrir mão de eficiência para dar mais facilidade. Algumas menos que outras, um exemplo é Lua que consegue ser fácil e simples sem ser muito ineficiente.
Tem umas linguagens que ninguém sabe porque foi criada porque ela só piora as coisas :) Em geral é só gosto do criador.
Eu acho curioso como algumas linguagens foram criadas com um objetivo claro e foi mudando, hoje é outra coisa e ninguém percebe. Muita gente defendia a linguagem como era e hoje defende o outro jeito indo contra sua argumentação inicial. As pessoas torcem por times, por partidos políticos e por empresas e tecnologias, tudo de uma forma religiosa mas com dogmatismo tendencioso com o discurso do momento. Isso dá espaço para surgir novas linguagens, as pessoas estão esperando um discurso que faça mais sentido para ela.
Algumas linguagens são verdadeiras frankensteins.
Coloquei no GitHub para referência futura.
Comment: Falou sobre o "marketing" e "mercado" +1
Comment: "Haskell surgiu para ensinar Haskell para as pessoas :P :D" KkKkkKkKkKKkk, rindo até 2030
Answer: Existem vários motivos:

Evolução natural das linguagens: da mesma forma que na linguagem humana, onde ela nasceu com simples fonemas e de acordo com a evolução do ser humano e sua migração e separação geográfica, ela foi se adaptando e evoluindo de forma conjunta. As linguagem de programação, como você mesmo mencionou, surgiram das formas mais rudimentares e conforme os programadores e desenvolvedores foram percebendo que coisas poderiam ser feitas de forma melhor, mais intuitiva e portanto mais rápida, foram criando suas próprias linguagens.
Adaptação com o momento histórico: até o final dos anos 70, por exemplo, reinavam os mainframes, as empresas (grandes) que os possuiam tinham enormes e complexas estruturas de desenvolvimento, envolvendo analistas de sistemas (que analisavam a necessidade, criavam fluxogramas - diagramas de blocos), que passavam este material para os programadores (que tentavam entender o que o analista queria e codificavam um programa em papel de 80 colunas), os quais passavam este material para os digitadores que fariam o digitação do código fonte no sistema operacional do mainframe, etc. Havia muita gente envolvida para gerar um simples programa (e muita coisa podia dar errado), desta forma, era necessário uma linguagem de programação que fosse mais prolixa, como o COBOL, para que tudo ficasse bem detalhado, nada subentendido.
A medida que foram desaparecendo estas mega-estruturas, com o surgimento do PC e a figura dos profissionais foram se sintetizando em apenas uma pessoa (que analisa, programa, digita, compila, testa, etc), o paradigma foi mudando e o foco ficou mais na inteligibilidade, objetividade, entre outros.
Novas tecnologias / hardwares: conforme foram evoluindo as tecnologias (como por exemplo o surgimento da internet, dispositivos móveis, etc), novos tipos de hardware, além de sistemas operacionais diferentes (Windows, Ios, Android, Linux) foi-se percebendo que cada caso tinha uma realidade específica. Algumas empresas criaram sistemas proprietários que não aceitavam linguagens pre-existentes e exigiam novas linguagens a serem usadas. Cada novo modelo de processador criado traz consigo novas regras, novos recursos que antes não haviam sido explorados. Teoricamente você poderia fazer tudo numa linguagem de baixo nível, mas isso levaria anos para se fazer algo que poderia ser reduzido a minutos numa linguagem de alto nível.
Idiossincrasia: com o passar do tempo e com a experiência, muitos programadores foram percebendo que "isso ou aquilo" em determinada linguagem poderia ser feito bem melhor de outra forma... então muitos se lançaram numa "aventura" de criar algo novo com a finalidade de facilitar e melhorar as dificuldades anteriores. E aí vêm junto as particularidades de cada ser humano que coloca sua forma de pensar e seu estilo pessoal nesta nova linguagem. Veja o exemplo do Python que leva consigo uma série de ideias do seu criador, que por sua vez repercutiram positivamente em várias pessoas que abraçaram esta nova forma, que por sua vez transformou-a numa linguagem de sucesso. Mas creia que para cada sucesso, existem milhares de fracassos desconhecidos por aí.
Futuro: não creio que um dia teremos uma linguagem universal como filosoficamente se deseja até para a humanidade. Ao contrário, penso que haverá cada mais especialização, ou seja, cada-macaco-no-seu-galho, cada linguagem cumprindo (bem) sua função.
Answer: Dentre os diferentes motivos temos:

Evolução tecnológica. O que foi inventado ontem pode não servir mais para o hoje. A necessidade de hoje pode ser diferente da necessidade de ontem. Esse é um dos motivos que levou a criação do Java.
As linguagens existentes podem ser insuficientes ou deficientes para atender-se a determinados requisitos. Foi isso que fez o paradigma orientado a objetos nascer e levar a criação de linguagens que seguem este paradigma.
Há nichos específicos que requerem linguagens especiais. Um exemplo óbvio disso é SQL. O JavaScript nasceu assim, para ser uma linguagem específica para rodar no navegador. O PHP também nasceu assim. Outro exemplo é a variante de C usada no Arduino ou a variante de C# usada no Unity.
Pessoas diferentes tem opiniões diferentes sobre detalhes da estrutura das linguagens de programação. Por exemplo, C tem ponteiros e aritmética de ponteiros, mas algumas pessoas consideram isso ruim, e isso foi um dos motivos que fez surgir o Java. Os Basics antigos foram muito atacados por não serem estruturados (era tudo baseado em GOTOs e GOSUBs). Existe uma "guerra dos 100 anos" em curso entre linguagens com tipagem estática e tipagem dinâmica. Uma das inspirações do Python foi a de usar a indentação para aninhar estruturas e considerar que as demais linguagens tinham uma estrutura muito complicada. Tem gente que é mais a favor de funcional, tem gente que prefere OO, tem gente que odeia OO, etc. E muitas outras coisas entram nessa categoria.
Fornecedores específicos. Existem várias linguagens de programação que são desenvolvidas por um único fornecedor. Daí vem um fornecedor diferente e sugere uma linguagem parecida, mas com algumas diferenças (umas pequenas, outras grandes). Depois vem mais um outro e pega o que havia dos predecessores e faz uma outra coisa similar para os seus produtos... Esse é um dos motivos de terem existido tantas variações de Cobol, Basic e C, por exemplo. Linguagens como D e C# nasceram assim. Em casos mais modernos isso tende a ser mais raro, mas ainda existe, tal como o React.js pode comprovar.
Answer: Teve uma palestra muito legal que vi na XConf desse ano do Luciano Ramalho e da Rosi Teixeira da TW que falaram um pouco sobre isso.
A estrutura básica de lógica de programação mudou muito pouco no decorrer dos anos.
Condicionais usam IF, laços usam FOR, While, para comparação usa-se >,< =, ==, && e por ai vai.
O que acontece é que os problemas mudam conforme os anos vão passando, os recursos vão melhorando e existe uma questão de experiência do desenvolvedor, dai os paradigmas vão surgindo. Assim como o tipo de comunicação (TCP/IP, SOAP, REST, Grpc).
Evoluções vão acontecer, linguagem que utilizam melhor os recursos vão surgir e isso é inevitável. Antes tínhamos arquitetura de cliente servidor, veio SOA, Microsserviços, serverless e isso nunca terá fim!
Imagina como seria o desenvolvimento de uma arquitetura serverless em cobol? sem chance.
Novas arquiteturas surgirão pois existem novas necessidades de negócio.
Como o time-to-market deve ser baixo, a experiência do desenvolvedor deve ser boa, pois a entrega deve ser ágil, a curva de aprendizado deve ser baixa.
Eu escuto todo dia gente falando que o Java é verboso demais e o Spring vem pra ajudar.
Hoje com meia dúzia de @ um dev consegue entregar um microsserviço de CRUD.
Enfim, novas linguagens surgem para suportar novas arquiteturas, necessidades de negócio e para atender a experiência do usuário.
Comment: O único motivo de algo"serverless" não funcionar com COBOL é fornecedores de servidores "serverless" não suportarem a tecnologia.
Comment: Ou seja, sem chance!
Answer: Cada tipo de linguagem é usada para algo especifico, por exemplo, a linguagem CSS é usada para estilizar layouts, a linguagem HTML5 é usada para desenvolver páginas da internet, algumas linguagens tem vários propósitos, como a C++ ou a Python que pode tanto ser usada para desenvolver uma automação residencial como uma IA, por exemplo.
Cada linguagem de programação tem um propósito diferente, mas a maioria foi desenvolvida para a resolução de problemas.
Comment: CSS e HTML não são linguagens de programação. Me cite uma linguagem que não foi criada para resolução de problemas.
Comment: @Maniero, Whitespace! Ela foi criada para **ser** o problema xD
Comment: @Maniero [BIRL](https://birl-language.github.io/)


Show that columns of PageRank matrix sum to 1

Question: Where the matrix A is replaced with
$$G=\alpha A+(1-\alpha)\frac{1}{n}ee^T$$
Is it a sufficient condition a matrix is  stochastic if the largest eigenvalue is 1? Or that in this case since A is stochastic and the largest eigenvalue of G is 1, that G is also stochastic, and thereby the  columns sum  to  1?
Answer: first the largest eigenvalue of a stochastic matrix is indeed $1$ but this is not a sufficient to prove that a matrix is stochastic (consider for instance add to zero. Take
$
M=\begin{bmatrix}1& 0 & 1\\0&1& 0\\0&0&1\end{bmatrix}
$ which has maximal eigenvalue 1 but isn't stochastic (see also e.g. Proof that the largest eigenvalue of a stochastic matrix is $1$)).
Now to show that $G$ is stochastic (assuming $A$ is stochastic), just apply the definitions:
$$
\begin{align*}
\sum_j G_{i,j} & = \sum_j  (\alpha A_{i,j} + {(1-\alpha)\over n} ee^{T}_{i,j})\\
&=  \alpha \sum_j A_{i,j} + {(1-\alpha)\over n} \sum_j  ee^{T}_{i,j}\\
&= \alpha \times 1 + {(1-\alpha)\over n} \sum_j  ee^{T}_{i,j} \\
&\text{(since $A$ is stochastic)}\\
&= \alpha + {(1-\alpha)\over n}  \sum_j 1 \\
&= \alpha + (1-\alpha) = 1
\end{align*}
$$
Does this answer your question?
Comment: It does, thanks!


Can I use AIC for path models and non-path models?

Question: I am testing competing hypotheses where one hypothesis contains a mediation effects that can be modeled using a path model. The other hypothesis does not include a mediation effect and therefore can be modeled using a simple linear regression. Both models will be run using the same dataset and will have the response variable (or exogenous variable in the path model's case).
Therefore, I am wondering if it is appropriate to utilize AIC to compare/rank these models? The path model is being built using the piecewiseSEM package. I have read papers where they have used AIC selection for different path models but never a case when comparing a path model to a non-path model.
Any thoughts would be appreciated.
Comment: Could you not formulate both models in the path-model nomenclature to make their AICs directly comparable?
Comment: Unfortunately, this doesn't work. When I run the non-mediation model with a basic glm the aic is 100+ . When the same glm is run inside the path-model the AIC goes to 6...
Answer: Assuming your mediation model is of the form $A \rightarrow B \rightarrow C$ and $A \rightarrow C$, where $C$ is your dependent variable and $B$ is the mediator, then you can indeed run a "non-path" model.  Simply break the mediation path and run the model $A \rightarrow B$ and $A \rightarrow C$.  This is accomplished by setting the path coefficient from $B$ to $C$ to zero.  This will give you comparable models to use for either $AIC$ comparison (using the same set of variables and the same data set), and it will also allow you to conduct a $\chi^2$ model comparison as well (as these are nested models).


Why does a sum of factorials behave differently from single factorials?

Question: The Brocard Problem shows three factorials that can be expressed as $n!+1=m^2$ or equivalently $n!=k(k+2)$. So any time a single factorial can be put in the form of $k(k+2)$, it will belong to Brocard Problem series. However the series has only three elements and extensive search has not uncovered new elements.
It turned out that it is much easier to generate sums of factorials that satisfy $(n! + i! +\ldots j!)=m^2-1$.
Here are some simple examples:
$4! + 4!= 48 = 6*(6+2)= 7^2 -1$
$5! + 5! + 5!=360= 18*(18+2)= 19^2 -1$
$5! + 6!= 840= 28*(28+2)= 29^2 - 1$
$4! + 4! + 5!= 168= 12*(12+2) = 13^2 -1$
$4! + 4! + 5! + 5!= 288 = 16*(16+2) = 17^2 -1$
$4! + 5! + 6! + 7! + 8!= 214*(214+2) =215^2 -1$
More can be generated, for example, we have:
$8! + 2! + 3! + 3*4!= 200*(200+2)= 201^2 -1$
$6! + 2! + 3!=26*(26+2)=27^2-1$
We start with expressing $10!$ as a difference of squares then we convert the smaller square into factorials:
$10!=1905^2-15^2$
$15^2=225=5! +4*4! +3! +2! +1$
so we get:
$10! +5! +4*4! +3! +2! =1905^2-1$
To generate these kind of relations involving sums of factorials, we start with a number $n=k(k+2)$ then we try to fit factorials that sum up to the desire number $m^2-1$. I suppose there is more than one way to express a given number as a sum of factorials especially for large numbers.
I think the reason we can't generate more Brocard factorials ( single factorials of the form $n!=m^2-1$) is because the pattern  is broken. Already we have a "discontinuity" of the pattern when going from $5!$ to $7!$ since $6!$ is not a Brocard factorial. Numbers of the form $k*(k+2)$ ( both even and odd ) can be found on the third diagonal of the multiplication table ( the diagonal starting with $3$). The number $6$ is already not of that form since $6!=6*10*12$. The simple multiplication by 6 destroyed the pattern $10*12=10*(10+2)=5!$. Larger number (single factorials) than $7!$ will not exhibit the pattern $k*(k+2)$ since we keep adding factors of the form $j*(j+i)$ with $i\gt2$. I am not saying it's a proof. I am just pointing out a pattern.
Question 0: Why is it much easier to generate sums of factorials that satisfy Brocard relation $n! + i! +\ldots+ j! =m^2 -1$
Question 1: Are there large number factorials that cannot be put as a sum of factorials satisfying $n! +i!+\ldots+ j!=m^2-1$?
Question 2: Will it be easier to settle Brocard problem if, instead of using the multiplications to evaluate $n!$, the factorials are expressed as polynomials with higher and higher degrees and open the door to using knowledge of the mathematics of polynomials?
Note: The quadratic equation $n!=k*(k+2)$ can be transform into the quartic $n!=m^4+2m^3-m^2-2m$. Solving the quartic for a given $n!$ will instantly tell if a single factorial is a Brocard's one just like the quadratic does.
Comment: Every natural number can be expressed as a sum of factorials $k!$ with coefficients in $\{0,1,\ldots,k-1\}$.  See [factorial base](https://en.wikipedia.org/wiki/Factorial_number_system).
Comment: "$n! = k *(k+2)$ can be transform into the quartic $n! = m^4 + 2 m^3 - m^2 - 2 m$"?  Why should $k$ be of the form $m(m-1)$??
Comment: in fact the numbers involved in $k∗(k+2)$ are $j(j+1)$, twice a triangular number $(2,6,12,20...)$ and the one aligned with is of the form $i(i+3)$ forming the diagonal $(4,10,18,28,...)$. It's in fact $k∗(k+2)$  should read $i∗(i+3)∗j∗(j+1)$. First, it's easier to deal with an equation with only one variable instead of $2$ but also because I noticed (by looking at the multiplication table) that $4!=4∗6$, $5!=10∗12$...so I started using $k∗(k+2)$. To get a one variable quadratic or quartic, $i∗(i+3)$ was converted to $(j−1)(j−1+3)$ so we get the quartic $(m−1)∗(m+2)∗m∗(m+1)$.
.
Comment: (cont); to make things simpler, I am not using $n!=n*(n-1)*(n-2)*...1$. I am using half the multiplications needed as shown in the post below so that $4!=4*6$. https://scicomp.stackexchange.com/questions/42510/what-are-the-benefits-of-cutting-by-half-the-number-of-multiplications-needed-to/42645#42645
Comment: Sorry, that should be $\{0,1,\ldots,k\}$.
Answer: Simply put, sums of a few factorials are a lot more common than factorials themselves, so it's likely that a lot more of them will have a particular form.
There are, for example, $1023$ natural numbers $< 11!$ that are sums of distinct factorials (not counting $0!$ and $1!$ as different).  $12$ of them are of the form $m^2-1$:
$$
\eqalign{3 &= 1! + 2! = 2^2 - 1\cr
8 &= 2! + 3! = 3^2 - 1\cr
24 &= 4! = 5^2 - 1\cr
120 &= 5! = 11^2 - 1\cr
728 &= 2! + 3! + 6! = 27^2 - 1\cr
840 &= 5! + 6! = 29^2 - 1\cr
5040 &= 7! = 71^2 - 1\cr
45368 &= 2! + 3! + 7! + 8! = 213^2 - 1\cr
46224 &= 4! + 5! + 6! + 7! + 8! = 215^2 - 1\cr
363608 &= 2! + 3! + 6! + 9! = 603^2 - 1\cr
403224 &= 4! + 8! + 9! = 635^2 - 1\cr
3674888 &= 2! + 3! + 6! + 7! + 8! + 10! = 1917^2 - 1\cr
}$$
Comment: That doesn't go in my list because of the $2 * 6!$ and $3 * 4!$: my list is for sums of **distinct** factorials.  But there is $ 2! + 3! + 7! + 8! + 9! + 10! + 11! + 12! + 13! + 14! + 15! = 1183893^2 - 1$.
Comment: I can add this one to the list: $10! + 12! = 21969^2 - 81^2$. Now we just express $81^2=6561= 7! +2*6! + 3*4! + 3! + 2! + 1$. So $10! + 12! + 7! + 2*6! + 3*4! + 3! + 2!=21969^2 - 1$


Inducing sparsity in a Bayesian model

Question: Can someone explain or point me to an introductory reference that deals with the notion of sparsity in Bayesian modeling? What does the idea of sparsity really mean? What does it mean to 'induce sparsity'? How are 'sparse priors' identified and used? In fact, what are they?
Comment: Maybe you can start with an old paper: Sparse Bayesian Learning and the Relevance Vector Machine http://jmlr.csail.mit.edu/papers/volume1/tipping01a/tipping01a.pdf
Answer: Imagine a Bayesian linear regression:
$$Y_i = x\beta_i + \epsilon_i$$
$$\beta_i \sim N(\beta_0,\Sigma_0)$$
One version of sparsity is to use a Laplace distribution (aka double exponential) as a prior for the $\beta$ coefficient in a Bayesian linear regression, as opposed to the Normal distribution one often uses. Here is a visual:

The double exponential places much more weight around zero which "pulls" in small $\beta_i$ values and makes them 0, while leaving large values of $\beta_i$ still nonzero. This effectively zeros out many values in your parameter matrix, and hence induces sparsity. This is similar to the frequentist lasso.
Comment: (+1) Think that should read "a Laplace distribution (aka double exponential)"
Comment: The Cauchy Distribution as defined in Wikipedia looks different. How do you define the Cauchy Distribution in the example above?
Answer: If you want to be truly Bayesian (sample from a posterior that gives you sparse parameterizations), the only way I know of is a spike-and-slab type prior. A Laplace prior gives sparsity only in the MAP estimate.

Inducing sparsity in a Bayesian model


Z test vs Wald Test in logistic regression

Question: I am looking at logistic regression output that shows Z test values. When can I use these to estimate the significance of coefficients, and when do I need to use a Wald chi-squared test?
Answer: They are almost certainly the same thing. The "Z test values" in your logistic regression output are probably Wald statistics, and the Wald chi-square statistic is probably just $Z^2$. This means that the Wald chi-squared test is the same as a two-sided test using the corresponding $Z$-value.
Comment: So just to be clear - if I need the Wald's Chi-Square value, all I need to do is take a square of the Z statistic from the output?


Can you control the host information returned by ping?

Question: I see that pinging my domain returns "n bytes from xyz.members.linode.com", which gives away too much for my taste. On the other hand, I've pinged plenty of domains that just return "something.domain.com". Is it possible to configure a VPS to have this behavior? If so, how?
Answer: If you register domain.com, whoever looks after the reverse mapping for your VPS' IP-address in DNS should be able to make the reverse DNS lookups for that IP-address resolve to something.domain.com.
Of course, people will probably still be able to work out that the IP-address of your VPS comes from a block of IP-addresses allocated to linode.com.
Comment: When a machine receives a packet, it does not know the name of the source. It knows only the IP address of it. So it must ask for the PTR record via DNS in order to learn the name associated with it. Therefore you must ask your hosting provider to configure "reverse DNS" for your server appropriately.
Comment: Thanks for your answer. (I'm not allowed to accept it yet.) I need to pick up some nice book on DNS... Out of curiosity, could the reverse DNS lookup resolve to the naked domain domain.com?
Comment: Yes it can resolve back to the "naked" domain. Start with "DNS for Rocket Scientists" http://zytrax.com/books/dns/
Answer: You can configure the PTR record for linode in their control panel.
In the "Remote Access" tab, look for a link labelled "Reverse DNS" in the "Public IPs" section.
The address would be https://manager.linode.com/linodes/rdns/[your linode name].


Mixed design nightmare

Question: I hope you can steer me in the right direction.
I'm helping a colleague analysing a dataset that consists of:

one dependent variable (value) measured 3 times (observation) by 3 people (evaluator) on the 2 sides (side - right/left) of an individual (~150 individuals)

several independent variables: one continuous (age), and 2 discrete (sex, ancestry).

the data also has NA has some evaluators skipped over a few individuals in one or more of the observation points.

His main questions concern the reproducibility of measurements and effect of independent variables:

for reproducibility I used intraclass correlation coefficients with relative success;
to look at the effect of independent variables, I would normally use some form of a linear model (ANOVA/ANCOVA).

However, I'm worried about the lack of independence between observations, basically the first assumption of a lot of these tests. I tried looking at mixed models (e.g. using 1 between subjects factor (sex) and 2 within subjects factors (evaluator & observation) ), but I couldn't find good examples of this application (particularly using R), and mixed models seem to focus on evaluating the impact of these within subject factors, when in fact I mostly just want to control for these and focus on the effect of the independent factors.
Questions: (1) Could I assume independence? (2) What would be an appropriate design model (@RobertLong 's correction)? (3 - slightly off topic) Any R pointers are welcome.

Update
Following Robert Long's answer, I'm now working with a mixed model that looks like this lme(value ~  sex * side + age + ancestry + evaluator, data = L, random = ~1|individual, method = "ML", na.action = na.exclude) (using Andy Field's book)
However, now I have more questions:
(1) How to follow up (especially considering that I want to understand the effect of sex while controlling for the effect of ´evaluator´. Would contrast be a good option?
(2) Reading on this, I realised that lack of independence will also be an issue for the ICC I calculated. Could I calculate them from the mixed model? (Based on this: Computing repeatability of effects from an lmer model)
Comment: How many individuals do you have ? What is the "evaluator" variable (is that the 3 different people doing the measurements ?) Is it the same 3 people all the time, or are the more than 3 people (ie 3 different people for other individuals) ?
Comment: I edited the question to include the very pertinent info you requested. In summary: around 150 individuals; Yes; Yes.
I appreciate any help. I'm used to the typical frequentist statistics but getting lost in a mixed model rabbit hole. Thank you.
Answer:
(1) Could I assume independence?

No, because you have repeated measurements. Observations within one individual are more likely to be similar to other observations within the same individual than observations on other individuals. One way to handle this is to fit random intercepts for individuals in a mixed model. It also seems that evaluator is crossed with individual, but you don't have enough evaluators to justify fitting random intercepts for that, so you will need to fit fixed effects for evaluator.

(2) What would be an appropriate design?

Perhaps you mean model, not design ? The (study) design is the experiment itself which apparently has already been done. As for the model, a mixed model may be appropriate.

3 - (slightly off topic) Any R pointers are welcome.

I would start with a model such as:
value ~ age + sex + ancestry + side + evaluator + (1 | individual)

You could use the lmer function in the lme4 package for that.
Comment: `observation` is the lowest level  - there are no repeated measures within in it right ? if so then you don't need to include it. `observation*evaluator` if you expect an interaction between them, though based on the description I can't see why what would be. Factors to numeric: that usually doesn't make sense. With a binary variable it doesn't matter but if it's categorical with more than 2 levels then it does not make sense. As for p-values please ask a different question about, but p-values for mixed models are not well defined to begin with so please try not to be too concerned with them.
Comment: So, to *"understand the effect of `sex` while controlling for the effect of `evaluator`"* you just need to fit a model that includes both `sex` and `evaluator` plus any other competing exposures, such as age and ancestry, so the model I suggested would be appropriat for that. As for the ICC, you can calculate that directly from the mixed model. As for independence, by fitting random intercepts for individual and fixed effects for side and evaluator, we are contolling for non-independence.
Comment: Got it for question 1 and 2. Thank you.
Re. R:
(1) Should I ignore `observation`? Maybe `+observation*evaluator` or is this not appropriate?
(2) is it okay to convert `factors` to `numeric`? To get a single p-value per variable
(3) [trickier as you don't have my data] I get a surprising significant p-value for `side` (absent visually and when ignoring data structure) prob bc `sex` is unbalanced so could include `sex*size` (significant btw)?
Comment: No repeated measures within `observation`; Factors to numeric: I was following Andy Field's book which suggests this as a way to evaluate effect of categorical variable overall rather than getting a different result for each factor level
Comment: Please ask a seperate question about treating categorcal variables as numeric as that is a different question.
Comment: I understood the categorical/numeric thing just browsing other SE questions and stuck with categorical. I updated the post with new questions because I tend to get overwhelmed when browsing SE questions and prefer when one post solves several issues, but can post separately if you prefer. Thank you!
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/127347/discussion-between-answer42-and-robert-long).

Mixed design nightmare


c# Dragging images inside canvas in windows store app fails

Question: I'm fairly new to C# and programming in general.
I'm building a dummy project to understand how drag and drop works. At first, I begun moving around rectangles, limiting their movements inside the canvas, and they moved just fine. After that, I tried to make it a bit more complex by adding PointerEntered/PointerExited and replacing the rectangles with images. Re-sizing the images when the events PointerEntered/PointerExited occur works, but when I try to drag my images nothing happens. I tried several things I've seen around SO and msdn but it still fails.
Here is my code:
MainPage.xaml
<code><Canvas  x:Name="MyCanvas" Width="800" Height="600">
        <Canvas.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF5E8B83" Offset="1"/>
            </LinearGradientBrush>
        </Canvas.Background>
        <TextBlock x:Name="someTB" FontSize="30" Canvas.Left="262" Canvas.Top="25" Height="28" Width="171"/>
        <Image x:Name="cauldron" Source="Assets/cauldron-md.png" AllowDrop="True" PointerExited="draggableItem_PointerExited" PointerEntered="draggableItem_PointerEntered" Width="210" Height="184" Canvas.Left="455" Canvas.Top="159"/>
        <Image x:Name="antidote" Source="Assets/alchemy-green-potion-no-label.png" ManipulationDelta="dragableItem_ManipulationDelta" PointerExited="draggableItem_PointerExited" PointerEntered="draggableItem_PointerEntered" Width="45" Height="89" Canvas.Left="72" Canvas.Top="263"/>
        <Image x:Name="poison" Source="Assets/alchemy-tree-poison-md-standing.png" ManipulationDelta="dragableItem_ManipulationDelta" PointerExited="draggableItem_PointerExited" PointerEntered="draggableItem_PointerEntered" Width="45" Height="89" Canvas.Left="202" Canvas.Top="159"/>
    </Canvas>
</code>
MainPage.xaml.cs
<code> public sealed partial class MainPage : Page
{
    double originalWidth;
    double originalHeight;

    public MainPage()
    {
        this.InitializeComponent();
        // Add clipping area to the canvas
        MyCanvas.Clip = new RectangleGeometry();
        MyCanvas.Clip.Rect = new Rect(0, 0, MyCanvas.ActualWidth, MyCanvas.ActualHeight);
    }

    private Boolean DetectCollisions(FrameworkElement rect1, FrameworkElement rect2)
    {

        var r1 = new Rect(Canvas.GetLeft(rect1), Canvas.GetTop(rect1), rect1.ActualWidth, rect1.ActualHeight);
        var r2 = new Rect(Canvas.GetLeft(rect2), Canvas.GetTop(rect2), rect2.ActualWidth, rect2.ActualHeight);
        r1.Intersect(r2);

        if (r1 != Rect.Empty)
        {
            return true;
        }

        return false;
    }

    private void dragableItem_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        Image dragableItem = sender as Image;
        dragableItem.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY;
        dragableItem.RenderTransform = new CompositeTransform();
        var transform = (CompositeTransform)dragableItem.RenderTransform;

        var newPosX = Canvas.GetLeft(dragableItem) + transform.TranslateX + e.Delta.Translation.X;
        var newPosY = Canvas.GetTop(dragableItem) + transform.TranslateY + e.Delta.Translation.Y;

        if (!isBoundary(newPosX, MyCanvas.ActualWidth - dragableItem.ActualWidth, 0))
            Canvas.SetLeft(dragableItem, newPosX);

        if (!isBoundary(newPosY, MyCanvas.ActualHeight - dragableItem.ActualHeight, 0))
            Canvas.SetTop(dragableItem, newPosY);

        if (DetectCollisions(dragableItem, cauldron) == true)
        {
            cauldron.Source = new BitmapImage(new Uri(@"Assets/cauldron-md-autoTone.png"));
        }
    }

    bool isBoundary(double value, double max, double min)
    {
        return value > max ? true : value < min ? true : false;
    }

    private void draggableItem_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        Image thatPic = sender as Image;
        if (thatPic != null)
        {
            originalWidth = thatPic.ActualWidth;
            originalHeight = thatPic.ActualHeight;

            thatPic.Width = thatPic.ActualWidth + 10;
            thatPic.Height = thatPic.ActualHeight + 10;
        }

    }

    private void draggableItem_PointerExited(object sender, PointerRoutedEventArgs e)
    {
        Image thatPic = sender as Image;
        if (thatPic != null)
        {
            thatPic.Width = originalWidth;
            thatPic.Height = originalHeight;
        }
    }
}
</code>
Answer: 1) You need to add ManipulationMode="All" to the Image controls.
2) The Image "cauldron" is missing the ManipulationDelta event handler assignment.
Comment: Actually I just came here to say I forgot ManipulationMode="All" :) I was so distressed I didn't notice...
The cauldron is a drop target  it doesn't move. Thank you for your time!


Show English when there is no translation

Question: I have a website for a client, with more than 5 languages (bg, en, ru, ch, de, it ...). The client wants to add a news section but the news should be only in en or ch and if the user selects a language which is different then en or ch, en should be shown.
Is it possible when you add a content with English language, automatically translations for all other languages to be created instead of adding one by one the translations via translate menu entry?
Comment: We love to help you but this question unfortunately is way too broad. There are at least 3 very different (and each quite complex) questions in it. Try to narrow down your problem to one question and update your question accordingly. Important for us also is to see what you've tried yourself so far and where exactly you are stuck. Thank you!
Comment: Mmm.. long time ago there was an option "When translation is missing, show content in default language" which I am looking for...
Comment: Right, this has been dropped from the 7.x version of the `i18n` module. See https://www.drupal.org/project/i18n/issues/1238138
Comment: Yes I read this already, but there is nothing that can help me there. thanks
Comment: For the last remaining question now we still need to know what you've tried so far and where exactly you are stuck.
Comment: I do not know what I can try to achieve this, otherwise I will not ask. Looks like the only solution I see is to force the client to do manually dummy translations for all languages every time. Thanks for your time
Comment: Maybe google for "drupal 7 create translation programmatically" and pick one, try to build that and then you may come back when something's not working.
Answer: Language fallback module
I haven't tried this module but it seems to do what you're asking for. You can edit bg, de, it etc languages and set English as the fallback.
Drupal 8 also has one extra module for this: Entity Language Fallback
Automate with Rules
You could probably come up with a Rule that automatically saves translation nodes of an English node under certain circumstances, with some custom code.
Quickly fill in translations
If you can't do custom code for what ever reason, you could enable Synchronize translations (which is a submodule of i18n) on your Content types. This way when you go to translate other languages you'd already have the English text filled in, images kept etc so you just Save the node and see English text on an Italian node.
Comment: thanks, I am using Synchronize translations already and it works as you write - when you add a translation, it by default is in English. But what I want to achieve is to skip all the steps of adding translation and saving for 9+ languages when the translations will be only for 2 of the languages.. If it is only one language from 9 I can exclude translations and all the content will be only once added in English for example and everything will be ok. But with 2 of 9 becomes a bit complicated..
Comment: Have you tried the Language fallback module? It gives you the behavior you want without any extra saving.


Any documentation for Surecom EP-824DX-CS?

Question: I must find some documentation for a Surecom EP-824DX-CS (24-Port 100/10M N-Way 19" Rach-Mount Smart Switch) in order to find the capabilities of the device, but the most important is the console port pinout (DB-9 male). Also, the device has some sort of administration method (telnet/http) ?
Comment: Have you tried contacting any of the vendors that still sell them?
Comment: I couldn't find any web site for Surecom, and the switch seems to be out of stock on every site I could find.
Answer: I found an FTP repository that has all their manuals: ftp://ftp.ral.ro/Public/Support/surecom/Manual/
More specifically, the EP-824DX-CS manual is split in the two following files:

ftp://ftp.ral.ro/Public/Support/surecom/Manual/824DXCS-1.pdf
ftp://ftp.ral.ro/Public/Support/surecom/Manual/824DXCS-2.pdf
Answer: Unfortunately it looks like the company no longer exists. If you are just trying to get into the admin mode I suggest you either try HyperTerminal through the serial port or the telnet admin. There is likely a reset button on the switch, hold that for a few moments and then let it 'boot' up.
If you are prompted for a password I would go through all the standard network device password lists. Most companies use 'admin' or 'password', or a combination.
Comment: It doesn't have any buttons, and I'm not sure what kind of cable is needed to connect to the console port. Thank you for the password list.
Comment: A standard Serial Cable (RS232) cable is the norm for a 9-pin connector. Port looks like http://www.aggsoft.com/rs232-pinout-cable/images/9-pinout.gif, cable looks like https://www.kellycontroller.com/shop/images/products/RS232Cable.jpg
Answer: I have something (pdf) but not for this model -not CS but FS. If You steel  need that I can send You on mail that instruction.I have manual for switch and instruction how login to switch ,config conection  etc.Manual is not to good but if you have something its better then nothing:-)
BTW Here I found circuit power block and how it repair .
http://www.radioamator.ru/publ/ehlektropitanie/remont_blokov_pitanija/remont_impulsnogo_bloka_pitanija_24_portovogo_svitcha_surecom/46-1-0-718
Google translator help You.
I`m from Poland
Bogdan


Is it possible to use dataBase.executeNonQuery and use a return value from a stored proc?

Question: I have done some research and found a few ideas on how we can use a return value from a stored proc like:
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

but i am using something like this:
Database.AddInParameter();

where i do not have to open and close connections..
Can some body help me to understand if it is possible to use Direction.Returnvalue using DataBase approach?
Sorry for a bit un-organized question :) please feel free to ask if anything is not clear
Comment: What about `cmd.ExecuteScalar()` ? I'm not sure what you're asking for. Do you specifically want to use a Return-Parameter or du you just want to access the return value from your proc?
Comment: i just want to access return value from my proc.. lemme check out cmd.ExecuteScalar if it suits my requirement.. Thanks in Advance!
Comment: @Patrik Eckebrecht 1  thanks for ur comment. Actually i wanted to use EnterpriseLibrary.Data.Database object  with execute non query method instead of command . execute

As the code is pre-written and i dont want to change it much
Comment: Ah ok. Not very clear. Maybe rephrase a bit for others to understand better.
Comment: i was in a bit hurry so could not format and phrase my question in a better way :) but i got a solution that worked perfectly fine for me i used DataBase.outParameter ..
Answer: use database.outParameter for parameters that return value


XML Schema For MBSA Reports

Question: I'm in the process of creating a script to run the command line version of Microsoft Baseline Security Analyzer (mbsacli.exe) against all of our servers.  Since the MBSA reports are provided as XML documents, I should be able to write a script or small program to parse the XML looking for errors / issues.
I'm wondering if anyone knows whether or not the XML schema for the MBSA reports is documented anywhere -- I have goggled this, and cant seem to find any trace of it. I've run across a few articles that address bits and pieces, but nothing that addresses the complete schema.
Yes, I could just reverse engineer the XML, but I would like to understand a little more about the meaning of some of the tags.
Thanks...
Comment: +1 for a really good idea, keeping an eye on this question.
Answer: I have been looking for ages for something to effectively parse through multiple MBSA results in a simple and effective manner. I have not necessarily found the MBSA (even the previous version, netchk) XML schema documented anywhere. The MBSA Sample Scrips might be a good resource as it includes XML files and Javascript files used the parse through results. This might be a good springboard for your script.
Personally, I have had good success importing all of the XML files into Excel. This process is mostly manually sorting and is far from perfect, but it's better then parsing everything by hand. I am sure you someone familiar with scripting could make this work like magic.
MBSA itself has not been updated in over two years. Hopefully in the wake of this new era of M$ they will create another product that will provide better functionality for audting multiple servers.

XML Schema For MBSA Reports


Writing PHPUnit tests for view plugins

Question: I am trying to test custom views field & filter plugins using PHPUnit, but I keep getting dependency issues. I am curious to know if:

It possible to Unit test View plugins?
Simulate DB interactions.
Is it possible to inject services e.g database, request, response etc via a constructor, setter or property injection?

Thanks in advance.
Answer: Views plugins are testable, and Drupal core has a lot of examples.  I believe most aren't UnitTestCase (or \PHPUnit_Framework_TestCase), but rather KernelTestBase tests.
KTB tests will boot a minimal Drupal setup so you don't have to set up extensive mocking for dependencies, especially config and database.
Views in particular has ViewsKernelTestBase, which does basic setup for testing Views plugins.  You can use your IDE to find usages of this for example, but I know some are in web/core/modules/datetime/tests/src/Kernel/Views/
Essentially, you make a test module that has YAML for your test views.  The test declares this in its <code>$modules</code> list, along with the module that is providing the plugin.  You also define the test views, and these get imported.  You can then use the Views API in your test methods.
Then, as long as you use the new ViewsKernelTestBase, you can run it directly through PhpUnit, assuming you have your phpunit.xml setup properly.
Comment: I think @larowlan has a good tutorial on KTB testing. Not sure if this was a blog post or a Drupal Watchdog article.  If I find it, I will edit it into the answer.

Writing PHPUnit tests for view plugins


Is there a way to find the length of an array in MongoDB without returning the entire array?

Question: I'm paginating a list of embedded documents, and I'm wondering if there's a cheap way to find out the length of that list, analogous to count() for documents . I know that
<code>array.length
</code>
works, but I'm guessing that's it's slow and inefficient.
Any advice would be much appreciated.
Answer: Maintain a dedicated counter of the array as part of the document. There is no other efficient way to determine the length of an array.


Is martingale problem interesting?

Question: Why is the Martingale problem interesting, or useful to areas outside of math like economics, game theory, physics, etc.?
As a reminder, the Martingale problem is about finding a process so that when a given linear operator is applied to it, you get a martingale.
http://www.ma.utexas.edu/mediawiki/index.php/Martingale_Problem
Impreciseness is fine, I'm only looking for intuition and scope of knowledge here. (For instance, that website is too advanced for me to understand technically.)
I know Gaussian processes and Markov Chains are useful to physics.  Are Martingales also useful to physics?
Answer: Lets start with the basics. Suppose that $X(t)$ is a time-homogeneous Markov process. We define the transition semigroup of this process by $S(t)f(x) = \mathbb{E}[f(X(t)) \,|\, X(0) = x]$. (i.e. we have $S(0)$ is the identity and $S(t) S(r) = S(t+r)$ by the Markov property).
We can calculate the infinitesimal generator of this semigroup, which is the derivative of the semigroup at $t=0$: $Lf = \frac{d}{dt}|_{t = 0} S(t)f = \lim_{t \rightarrow 0} \frac{S(t)f - f}{t}$ defined for $f \in \mathcal{D}(L)$, the set of functions for which this limit exists. See http://en.wikipedia.org/wiki/C0-semigroup.
Skipping technicalities, we get by the vector valued version of the fundamental theorem of calculus that for $f \in \mathcal{D}(L)$
$$
S(t)f - f - \int_0^t L S(r)f d r = 0,
$$
which implies that for $f \in \mathcal{D}(L)$
$$
f(X(t)) - f(X(0)) - \int_0^t L f(X(s)) d s
$$
is a martingale.
$L$ is an important object because $L$ tells you what the process is doing. For example we have a process $X(t)$ on $\mathbb{R}$ such that
$$
L^Xf(x) = f''(x) + b f'(x)
$$
then the process is a diffusion process with drift $b$. A process $Y(t)$ on $\mathbb{N}$ such that its generator satisfies
$$
L^Y f(n) = f(n+1) - f(n)
$$
is a Poisson jump process.
In other words, every(reasonably behaved) time-homogeneous Markov process gives you a generator $L$.
For applications, one might want go the other way around. Suppose you want to model a phenomenon that you expect to behave Markovian. A first step is to write down an operator $L$ that should serve as the generator of the Markov process.
However, a priori it is not clear that every operator $L$ corresponds to a Markov process. This is the Martingale problem: given an operator $(L, \mathcal{D}(L))$, find a process $X(t)$ such that for $f \in \mathcal{D}(L)$
$$
f(X(t)) - f(X(0)) - \int_0^t L f(X(s)) d s
$$
is a martingale. If you succeed in doing this, then you have a process that behaves as your operator $(L,\mathcal{D}(L))$ describes.
A strategy to solve the martingale problem is by taking approximating generators $L_n$, i.e. $L_n \rightarrow L$ for some topology on the space of operators, for which it is known that there are Markov process $X^n(t)$ solving the martingale problem for $L_n$(for example the $L_n$ are bounded). Associated to these Markov processes $X^n(t)$ there are probability measures on the trajectory space, lets denote them with $\mathbb{P}^n$. Now one has to do two things.
First, one shows that the sequence $\mathbb{P}^n$ has limit points[existence].
Second, one shows that there is at most one limit point[uniqueness].
The fact that $L_n \rightarrow L$ and some technicalities then implies that this unique limit point is a solution to the martingale problem for $L$.
Ps. One can also try to show that $(L,\mathcal{D}(L))$ generates a semigroup via the Hille-Yosida theorem, and then construct a Markov process from the semigroup. This is a different and approach, but gives essentially the same result. Depending on the operator one approach is easier than the other.
Answer: First of all, martingale problems often arise in the theory of Markov processes as they are related to the characterization. For example, let $(X_n)_{n\in \Bbb N}$ be a sequence of Markov processes with generators $\mathscr L_n$ and we would like to check whether they converge to a Markov process $X$ with a generator $\mathscr L$. In such a case, one can just check a certain convergence $\mathscr L_n\to\mathscr L$. However, to extend this result from $\mathscr L$ to $X$ one needs to show that a martingale problem for $\mathscr L$ has a unique solution. In general, one can define Markov processes as solutions of martingale problems.
Martingales themselves are not only (or almost not at all) about martingale problems (which themselves are more about operators). They often appear in optimal control problems thanks to their almost-constant structure, and are inevitable when dealing with SDEs or SPDEs. The latter often arise in evolutional dynamics and can have examples in all systems that evolve in time.
P.S. your reminder of what is a martingale problem, especially a linear operator applied to a process is misleading.
Comment: @user1 well, martingales do not have to exhibit Markov property, though I don't know of martingale solutions that are not Markovian
Comment: So martingales and markov processes are basically related via a generator? and soltuions to martingale problems are more general then markov processes?

Is martingale problem interesting?


Hiding arguments in http call

Question: I use this to pass an argument (fullname).

Is there a way to pass the argument such that it can NOT be seen in the http URL?
I know about POST.
$listboxselected = $_POST['listbox'];

I would use POST instead, so that the argument is not present in the URL, but I can't, because I'm using the javascript as an On Click event.
<select id="listboxid" name=listbox onChange="listbox_update()">

The On Click event works perfectly. But I don't like seeing all my variables in the URL.
Comment: http://stackoverflow.com/questions/14133502/post-variable-with-onclick
Comment: just use `XMLHttpRequest` object
Comment: Follow-up question.  On my desktop PC with Chrome a listbox appears as, well, a listbox.  On my Android smartphone Chrome browser a listbox appears as a popup listbox with checkboxes. I like the Android Chrome browser checkbox style, is there a way to force that style to come up on a Windows PC Chrome browser.  I assume not.
Answer: If you want to do that only by JS then you can go with Ajax.
 function listbox_update(){
  var fullname = document.getElementById("listboxid").value;
    $.ajax({
        data: { fullname: fullname },
        url: <?php echo $_SERVER["PHP_SELF"]; ?>,
        type: "POST",
        success: function(msg){
          //some function here
        }
    });
}

Answer: Wrap the <select> in a <form> and then in onchange submit the form.
<form id="form" method="post" action="<?=$_SERVER["PHP_SELF"]?>">
    <select id="listboxid" name="fullname" onChange="listbox_update()">
        <option>here the options</option>
    </select>
</form>

and the listbox_update
function listbox_update () {
    document.getElementById('form').submit();
}

Another option would be to use Ajax, but since your original script reloads the page, then the first approach follows this way.
Comment: Awesome.  I already had everything in a Form. So this approach took 20 seconds to implement. Thank you!
Answer: You have only 2 solutions for this:
1) Either you must implement AJAX like below:
  function listbox_update()
  {
     var fullname = $("#listboxid").val();
     $.ajax({
        data: "fullname="+fullname,
        url: <?php echo $_SERVER["PHP_SELF"]; ?>,
        type: "POST",
        success: function(msg){
          console.log("Message :"+msg);
        }
    });
}

2) Or go with form submission.
function listbox_update()
{
  $('#your_form_id').attr('action', <?php echo $_SERVER["PHP_SELF"]; ?>);
  $('#your_form_id').submit();
}

Hiding arguments in http call


Optimization application trying to understand the wording

Question:
This problem I encountered, and Im trying to figure out. what is the meaning of a channel?
Comment: See the first [definition](https://www.merriam-webster.com/dictionary/channel).
Comment: I think they mean something else in this problem for channel? Do they mean like a bridge ?
Answer: A short boat that can enter the channel

A long boat that cannot enter the channel

The maximum length of a boat?
Sorry that I drew boats as lines. Too much simplified. But it will help to solve the problem.