Erro ao adidicionar a Controler no ASP.NET MVC

Question: Uma duvida ao criar uma controller.
Pois ao tentar criar a mesma tem apresentado o erro da imagem em anexo.
Criei 3 classes pequenas: Dependentes, Tipobenef, TitularPlano e ProvaContext
[Table("dependentes")]
public class Dependentes
{
    public int Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Nome { get; set; }
    //public Tipobenef Tipo { get; set; }
    [Required]
    [ForeignKey("TitularesPlano")]
    public int IdTitularPlano { get; set; }
    public virtual TitularPlano Titular { get; set; }
    public virtual List<Tipobenef> Tipobenefs { get; set; }

}

public enum Tipobenef
{
    Filho,
    Conjugue,
    Pai,
    Mae
}

[Table("Titularesplano")]
public class TitularPlano
{
    public int Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Nome { get; set; }
    public DateTime DataNascimento { get; set; }
    [Required]
    [MaxLength(11)]
    public string CPF { get; set; }
    [Required]
    [MaxLength(8)]
    public string RG { get; set; }
}

public class ProvaContext:DbContext
{
    public ProvaContext():base("Prova")
    {

    }
    public DbSet<TitularPlano> Titulares { get; set; }
    public DbSet<Dependentes> Dependentes { get; set; }

}

Já aqui vai a parte do WebConfig:
<add name="Prova"
     providerName="System.Data.SqlClient"
     connectionString="Data Source=Localhost\DESKTOP-T8VEK67; Initial Catalog=DbProva; Integrated Security=True;"/>

Em que já tentei também todos os nomes possíveis do localhost
Imagem 1:

Imagem 2:
Answer: Oi, Bruno, existe um erro na declaração da sua chave estrangeira.
Você declara sua coluna e coloca a FK para a entidade designando a anotação para o atributo que faz a ligação. No caso você designou uma anotação que não existe no atributo errado.
...
public int IdTitularPlano { get; set; }

[ForeignKey("IdTitularPlano")]
public virtual TitularPlano Titular { get; set; }
...

Espero que ajude.
Comment: Não esqueça de marcar a resposta como solução. Qualquer coisa a comunidade está à disposição. Abraço.
Comment: Muito Obrigado amigo, funcionou.


What determines if a hyperbolic tiling with ideal vertices is regular?

Question: I'd like to say I need this community's help in clearing my mind of the clutter that leads me to this contradiction:
As an example, the Wikipedia article for the Infinite-order triangular tiling provides this image as a coloring of this tiling, but also provides this image, but with the comment "nonregular".
However still, the Wikipedia page for ideal triangles claims that

All ideal triangles are congruent to each other.
The interior angles of an ideal triangle are all zero.

As such, I see no reason for one tiling to claim to be regular, while the other one is supposed not to be regular.
It seems to me to answer this question would require a more sophisticated definition of "regular" than I hold. Additionally, I think I might also lack knowledge of how distinct ideal point are, if there is a notion of distance between them and how to represent them notationally.
Can someone help?
Answer: If it was just a matter of congruent ideal triangles, then there could be a lot of "regular" ideal triangle tesselations. The key idea, I think, is that the tiling should have symmetries such as hyperbolic reflections, rotations or translations which preserve distances and angles. The ideal triangle points all have angles of zero and distance between them is meaningless, but it is important for non-ideal points. Although the "alternated color tiling" and recursive non-regular tiling look somewhat similar, there is a key difference. Notice how the pattern along the boundary of the disk is different between them. In the non-regular tiling the pattern is very homogeneous, whereas in the other tiling there are different spacing of the ideal vertices along the boundary. The result of a hyperbolic reflection, rotation or translation of the non-regular tiling makes the boundary pattern non-homogeneous while the other tiling will just be similar to what it was before because it is symmetric under hyperbolic reflections, rotations  and ranslations. That is what makes it "regular".
The process that created the recursive non-regular tiling did not use hyperbolic reflections, rotations and translations while the other tiling did.
Answer: Here's another answer which identifies the extra feature that must be preserved in a "regular" tiling of the hyperbolic plane $\mathbb H$ by ideal triangles.
Consider an ideal triangle $\Delta(\xi \eta \zeta) \subset \mathbb H$ with ideal vertices $\xi,\eta,\zeta \in \partial\mathbb H$. There exists a unique point $x \in \overline{\eta\zeta}$ such that the ray $\overline{x \xi}$ is perpendicular to the line $\overline{\eta\zeta}$; let's refer to this point $x$ as the "footprint" of the triangle $\Delta(\xi\eta\zeta)$ on its side $\overline{\eta\zeta}$. The footprints $y$ and $z$ of $\Delta(\xi\eta\zeta)$ on its sides $\overline{\xi\zeta}$ and $\overline{\xi\eta}$ are similarly defined.
One can characterize footprints by an intrinsic property of the ideal triangle: the footprint of an ideal triangle on one of its sides is the unique point $x$ on that side which is the finite endpoint of an infinite geodesic ray $R$ entirely contained in the interior of that triangle. By uniqueness of $R$, the footprint $x$ and the ray $R$ must be fixed by any reflection isometry of the triangle which fixes the opposite vertex, and it follows that the ray $R$ must meet the side at right angles at the point $x$.
If an ideal triangular tiling of $\mathbb H$ is to be regarded as "regular", then there should be many isometric symmetries of the tiling.
For example, consider an edge $\overline{\xi\eta}$ of the tiling. This edge is a side of two different triangles of the tiling, which I'll denote $\triangle(\xi\eta\zeta_1)$ and $\triangle(\xi\eta\zeta_2)$. Let $z_1,z_2$ be the footprints on $\overline{\xi\eta}$ of the two triangles  $\triangle(\xi\eta\zeta_1)$ and $\triangle(\xi\eta\zeta_2)$, respectively.
If this tiling is regular, then there should be an isometric symmetry of the tiling which reflects across the line $\zeta_1,\zeta_2$, interchanging $\xi$ and $\eta$. But a little thought suggests that this is impossible in general, unless $z_1 = z_2$ in which case it is possible.
In fact, this gives a necessary and sufficient condition for an ideal hyperbolic tiling of $\mathbb H$ to be regular:

An ideal triangular hyperbolic tiling of $\mathbb H$ is regular if and only if for each edge of the tiling, the footprints on that edge of the two adjacent triangles are the same point on that edge.

If you look at the tiling in the second link you provided, you can find an edge whose two adjacent triangles have unequal footprints: not one of the sides of the central triangle, but instead a side of one of the triangles adjacent to the central triangle.


What to do with comments that imply wrong answers?

Question: On a number of questions, I have seen comments that seem of low if any scientific value.

Difference-in-Difference on State Sales Tax Rates
How does the core relate to strong equilibrium?

How to deal with such comments, that in both cases seem to get the OP mistaken about his original question? In the second case, it was possible to formulate an answer that hopefully could levy the ambiguity, but in the first case, it's just comment vs comment, with no possibility to downvote.
I'm having a hard try figuring out whether to close this question or not. I don't believe the burden of proof, resisting trolls or whatever should lie on new users and people with dim knowledge of economics, and the issue I wish to adress here goes beyound trolling. However, I'm sceptic about my ability to fight trolls under the bemused eye of trolls themselves...
Comment: The first case is an issue, but not a frequent one. So far, it has only happened to me with exactly that user, who has been trolling throughout several questions/answers. I decided for my own mental health to not interact any more.
Comment: @Foobar I would love to do so, but I'm afraid we'll leave a large number of credulous users following his credible yet false reasoning...
Answer: I guess one way would be to forbid these kind of comments. They're not clarifying anyways, but rather attempts at answering the question.
Hence, forbid these type of comments but allow them only as answers, and hope that voting results correspond to the truth [tm]
Comment: Am I allowed to accept this kind of answers on meta?
Comment: I don't think accepting it "means" anything. Upvotes imply agreement, down votes disagreement. If there is a highly up voted answer, moderators typically take that into account when setting up "guidelines".


How to pass a JSON array value into a Jasper Reports subreport?

Question: Having a problem with Jasper Reports and Subtables.
I'm working with the following JSON format:
[
  {
    "dataObjects": [
      {
        "objectId": "025b3873ebe640aa9d6a34f9306548ae",
        "employeeFullName": "John Smith",
        "employeeGrade": "GS12"
      },
      {
        "objectId": "08b9300f62dc498f86c675ac5897b4c9",
        "employeeFullName": "Bill Johnson",
        "employeeGrade": "GS14"
      }
    ]
  },
  {
    "dataObjects": [
      ...
    ]
  },
  {
    "dataObjects": [
      ...
    ]
  },
  {
    "dataObjects": [
      ...
    ]
  }
]

The data returns as an array of four JSON objects. Each object contains the result of a query under .dataObjects
I need to be able to display this data as four separate subreports, charts, in this case.
I'm not seeing a way to pass the data from the parent to the subreport in the case of an array.
Playing with reformatting the data gives me:
{
  "report0": {
    "dataObjects": [
      {
        "objectId": "025b3873ebe640aa9d6a34f9306548ae",
        "employeeFullName": "John Smith",
        "employeeGrade": "GS12"
      },
      {
        "objectId": "08b9300f62dc498f86c675ac5897b4c9",
        "employeeFullName": "Bill Johnson",
        "employeeGrade": "GS14"
      }
    ],
  },
  "report1": {
    "dataObjects": [
      ...
    ]
  },
  "report2": {
    "dataObjects": [
      ...
    ]
  },
  "report3": {
    "dataObjects": [
      ...
    ]
  }
}

and this works fine using this:
<subreport>
  <reportElement x="20" y="10" width="260" height="260" uuid="6a319da0-bd78-4f44-8445-e03b9a62cc0f"/>
  <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("report0.dataObjects")]]></dataSourceExpression>
  <subreportExpression><![CDATA["quad_1.jrxml"]]></subreportExpression>
</subreport>

But I need to be able to do it without reworking the data, I need something like this, which does not work:
<subreport>
  <reportElement x="20" y="10" width="260" height="260" uuid="6a319da0-bd78-4f44-8445-e03b9a62cc0f"/>
  <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("[0].dataObjects")]]></dataSourceExpression>
  <subreportExpression><![CDATA["quad_1.jrxml"]]></subreportExpression>
</subreport>

Extensive Googling has not found anything about working with a json-list. Thoughts?
This was marked as a duplicate, but the duplicate does not address the issue I'm having.
I need to pass the data to subreports, each entry in the array goes to a separate subreport. I could work around the problem, possibly, as described, but the requirement is for subreports.
Comment: Alex, I looked at that one, and the other suggested duplicates. None seem to address the problem I'm having. I need to pass the data to subreports, each entry in the array goes to a separate subreport. I could work around the problem, possibly, as described, but the requirement is for subreports.
Answer: This could be achieved with JSONQL, a more capable replacement of the initial JSON language.
Your main report could look like this(I'm reusing the same subreport just for brevity):
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Report" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="749076bd-1ea5-4847-85e1-cf88b11c9ef6">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="DataAdapter.xml"/>
    <queryString language="jsonql">
        <![CDATA[[0]]]>
    </queryString>
    <background>
        <band splitType="Stretch"/>
    </background>

        <band height="160" splitType="Stretch">
            <subreport>
                <reportElement x="0" y="0" width="550" height="40" uuid="33bba077-fd38-4db3-b2ad-56c21a18105f"/>
                <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonQLDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("dataObjects")]]></dataSourceExpression>
                <subreportExpression><![CDATA["SubReport.jasper"]]></subreportExpression>
            </subreport>
            <subreport>
                <reportElement positionType="Float" x="0" y="40" width="550" height="40" uuid="bb8ab5c7-0fe8-4398-8efc-6d648e6a3a2c"/>
                <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonQLDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("^[1].dataObjects")]]></dataSourceExpression>
                <subreportExpression><![CDATA["SubReport.jasper"]]></subreportExpression>
            </subreport>
            <subreport>
                <reportElement positionType="Float" x="0" y="80" width="550" height="40" uuid="001d79d0-e850-41a9-8995-f55d6e96bc45"/>
                <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonQLDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("^[2].dataObjects")]]></dataSourceExpression>
                <subreportExpression><![CDATA["SubReport.jasper"]]></subreportExpression>
            </subreport>
            <subreport>
                <reportElement positionType="Float" x="0" y="120" width="550" height="40" uuid="4d7d085b-1694-40b2-9e10-81428b1a9165"/>
                <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonQLDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("^[3].dataObjects")]]></dataSourceExpression>
                <subreportExpression><![CDATA["SubReport.jasper"]]></subreportExpression>
            </subreport>
        </band>

</jasperReport>

The important parts here are the queries:

the main query, [0], is pretty obvious, it just selects the first item in the array so that for the first subreport you only need to apply subDatasource() with the dataObjects key
the subsequent queries only travel up the JSON tree(^) to select the appropriate source object to be passed to its respective subreport
Comment: The best answers are simple ones. Worked a treat. Thank you


variables in expressjs views

Question: I want to make session variables (or any others) usable in the views without repeating myself all over again.
I came up with this:
  res.render('index', viewVariables(req, res, params, {});

And the viewVariables function:
function viewVariables(req, res, params, options) {
  var returnObject = options || {locals:{}};
  var locals = {
    currentUser: req.currentUser ? req.currentUser : false
  };
  returnObject.locals = mergeObjects(locals, returnObject.locals, true);
  return returnObject;
};

Thats not working in the latest expressjs version (different render method).
Is there a simpler or more elegent solution for that? (well I'm sure there is!)
Answer: Have you looked at dynamichelpers?
From the website:
app.dynamicHelpers(obj)

Registers dynamic view helpers.
  Dynamic view helpers are simply
  functions which accept req, res, and
  are evaluated against the Server
  instance before a view is rendered.
  The return value of this function
  becomes the local variable it is
  associated with.

app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

Most of the times I like to make it a function instead. This way it will be only called when you call the function in your views.
Answer: Express v2.x
app.dynamicHelpers({
  session: function(req, res){
    return req.session;
  }
});

Express v.3
app.use(function(req, res) {
  res.locals.session = req.session;
});

variables in expressjs views


Como criar atalhos com JavaScript

Question: O Script que segue abaixo deveria permitir ao usuário digitar a combinação ALT+C onde abriria um prompt e a seguir o mesmo digitaria uma código para redirecionar para a página conforme o condigo numerico informado. O Script abre a janela de prompt do navegador e faz o redirecionamento correto mas em contrapartida bloqueia as demais teclas, assim o usuario não consegue digitar nada. Segue abaixo o código.
$(document).on('keydown', function(e) {
    console.log(e.which); // Retorna o número código da tecla
    console.log(e.altKey); // Se o alt foi Pressionado retorna true
    if ((e.altKey) && (e.which === 67)) {// Pesquisar (Alt + P)
     var comando = prompt('Entre com o Comando:');
     var codigo = parseInt(comando);
    }else{return false;}
/***************************************************************** */
/*Converte para Inteiro*/
if (!isNaN(codigo) === true) {

var url = "http://localhost/juridico/dashboard/";

  var meu_array = [
    /* MENU DE CADASTRO*/
    {"cod":201,"arquivo":"clientes"},
    {"cod":202,"arquivo":"fornecedores"},
    {"cod":203,"arquivo":"precos"},
    {"cod":204,"arquivo":"metas"},
    {"cod":205,"arquivo":"usuarios"},
    {"cod":206,"arquivo":"escritorio"},
    {"cod":207,"arquivo":"processos"},
    {"cod":208,"arquivo":"advogados"}
];

var indice = meu_array.indexOf(meu_array.filter(function(obj){
return obj.cod == codigo;
  })[0]);

  if(indice >= 0){
            var destino = meu_array[indice]["arquivo"];
            window.open(url+destino, '_self');

  }else{
    alert('Código Inválido! Tente Novamente precionando ALT+C');
    return false;
  }

}
/*SENÃO FOR NUMÉRICO*/
else{
    alert('Código Inválido! Tente Novamente precionando ALT+C');
    return false;
}
/***************************************************************************************/
});

Comment: Não consegui perceber o problema. O atalho e consequente procura está a funcionar. Que parte especifica não está a funcionar ? [Veja o seu codigo a correr neste fiddle permitindo várias pesquisas seguidas com Alt+c](https://jsfiddle.net/jbz7z8jq/)
Answer: O problema está no return false caso o usuário digite qualquer coisa que não o alt+c e no escopo do restante do seu tratamento.

$(document).on('keydown', function(e) {
  console.log(e.which); // Retorna o número código da tecla
  console.log(e.altKey); // Se o alt foi Pressionado retorna true
  if ((e.altKey) && (e.which === 67)) { // Pesquisar (Alt + P)

    var comando = prompt('Entre com o Comando:');
    var codigo = parseInt(comando);

    /***************************************************************** */
    /*Converte para Inteiro*/
    if (!isNaN(codigo) === true) {

      var url = "http://localhost/juridico/dashboard/";

      var meu_array = [
        /* MENU DE CADASTRO*/
        {
          "cod": 201,
          "arquivo": "clientes"
        },
        {
          "cod": 202,
          "arquivo": "fornecedores"
        },
        {
          "cod": 203,
          "arquivo": "precos"
        },
        {
          "cod": 204,
          "arquivo": "metas"
        },
        {
          "cod": 205,
          "arquivo": "usuarios"
        },
        {
          "cod": 206,
          "arquivo": "escritorio"
        },
        {
          "cod": 207,
          "arquivo": "processos"
        },
        {
          "cod": 208,
          "arquivo": "advogados"
        }
      ];

      var indice = meu_array.indexOf(meu_array.filter(function(obj) {
        return obj.cod == codigo;
      })[0]);

      if (indice >= 0) {
        var destino = meu_array[indice]["arquivo"];
        alert("Redirecionar para: " + url + destino);
        //window.open(url+destino, '_self');

      } else {
        alert('Código Inválido! Tente Novamente precionando ALT+C ');
        return false;
      }

    }
    /*SENÃO FOR NUMÉRICO*/
    else {
      alert('Código Inválido! Tente Novamente precionando ALT+C _');
      return false;
    }

  }

});

<input type="text" />

Como criar atalhos com JavaScript


Is there a notion in mathematics saying that, in a sense, all finite dimensions are actually infinite dimensional?

Question: So then every ordered pair or triplet and so on would be actually represented by an infinite sequence of numbers, and what we think of as 3 dimensions would mean that the point has an infinite number of zeros in its sequence starting with the 4th term. Only the first 3 terms of the sequence are not necessarily 0. For instance the point $(1,2,3)$ could be written instead as $(1,2,3,0,0,0...)$
In other words, in n dimensions, the first n terms would correspond to the standard notion of a coordinate in $\mathbb R^n$, and the rest are zero. Does anyone use this, or something similar, in mainstream mathematics? I feel as though I've heard of it somewhere.
Comment: You might have seen combinatorialists defining integer partitions as weakly decreasing sequences of nonnegative integers such that all but finitely many entries of the sequence are zero, and then writing these sequences as tuples composed of only their nonzero entries (thus throwing the zeroes away). This is a fine convention for partitions, but it *is* an abuse of notation, and you should be aware of its limits when you are using it.
Answer: It is possible to force this perspective, but it would be incorrect to say that the mathematics "actually" is this way.
To be more specific, yes, you can choose to consider the inclusions $j_n\colon \mathbb{R}^n\longrightarrow\mathbb{R}^\infty$ defined by
$$j_n(x_1,\ldots,x_n)=(x_1,\ldots,x_n,0,0\ldots)$$
However, the objects $\mathbb{R}^n$ have their own independent existence - in no way are they "really" subspaces of $\mathbb{R}^\infty$, and the maps $j_n$ aren't special.
Comment: As I said, one can certainly *choose* to consider them as such, and it may even (sometimes) be *useful* to consider them as such. However it is factually incorrect to say that, for example, a triple of real numbers is simultaneously a quadruple of real numbers.
Comment: Why are they not really subspaces of $\mathbb R^\infty$? To me it looks like they are. If I remember correctly, Munkres uses these embeddings  $\mathbb R\subset \mathbb R^2\subset \mathbb R^3\subset \dots\subset \mathbb R^\infty$ in *Elementary Differential Topology*.
Comment: @WarmFuzzies: A subspace is a subset...When you say "$\mathbb{R}$ is a subspace of $\mathbb{R}^2$" you really mean something like "The set of vectors of the form $(x,0)$ are a subspace of $\mathbb{R}^2$ isomorphic to $\mathbb{R}$".
Comment: One could just as well look at the maps $k_n\colon\mathbb{R}^n\to\mathbb{R}^\infty$ defined by
$$k_n(x_1,\ldots,x_n)=(x_1,x_1+x_2,\ldots,x_1+\cdots+x_n,0,0,\ldots)$$
Why not think of them as subspaces that way?
Comment: Yep, I was answering the first comment :p
Comment: @fretty: Apologies :D
Comment: Two comments: (1) it is the embeddings $\Bbb R^n\to\Bbb R^m$ that are compatible with each other, not the embeddings $\Bbb R^n\to\Bbb R^\infty$ (for which no compatibility can even be formulated); (2) the vector space $\Bbb R^\infty$ is not the direct limit of the finite dimensional spaces $\Bbb R^n$ (it is not the union of their embedded images).
Comment: @Marc: You're quite right on both counts. I'll edit.
Answer: No, just because a finite dimensional space can be embedded in an infinite dimensional space does not make it "actually infinite dimensional". Dimension is well defined, and preserved under embedding.
If you are wondering if any people use standard embeddings of $\Bbb R^n$ into each other (like the conventional $\Bbb N\subset \Bbb Z\subset \Bbb Q\subset\Bbb R\subset\Bbb C$) or into a common infinite dimensional space, the answer is no. For linear algebra purposes making such identifications would only be confusing.
However, there are rather standard injective linear maps from $\Bbb R^n$ into the vector space $\Bbb R[X]$ of polynomials, where coordinates give polynomial coefficients in increasing order. The image of $\Bbb R^n$ is the subspace* $\Bbb R[X]_{<n}$ of polynomials of degree strictly less than$~n$. Now the images of the various $\Bbb R^n$ form a "standard flag", a chain of successively included subspaces of $\Bbb R[X]$, and their union is all of$~\Bbb R[X]$.
Note that $\Bbb R[X]$ is a much smaller space than the space denoted by $\Bbb R^\infty$ or $\Bbb R^\Bbb N$ of unrestricted infinite sequences of real numbers, which has uncountable dimension; the latter space could serve to embed everything in, but it would be quite wasteful.

*By some conspiracy almost all authors that mention it seem to denote this space instead by $\Bbb R_{n-1}[X]$ or by $P_{n-1}(X)$, so as mask the fact that is has dimension$~n$. And none seem to ever need the image of $\Bbb R^0$.
Comment: @DrewN all but finitely many of the coefficients of a polynomial are 0.
Comment: Hmm. I'm not yet sure how $\mathbb R[X]$ is any smaller than $\Bbb R^\Bbb N$. How are real coefficients of a polynomial more restricted than a sequence of real numbers?
Answer: First you have to understand that the way you formulated the question is vague enough to permit answers you may find unsatisfactory.
Second, yes, there is something like what you want. For example, take the set of real valued sequences $$\mathbb{R}^\mathbb{N}= \{ (a_n)_{n\in\mathbb{N}} : a_n \in \mathbb{R} \}$$
and give it the standard $\mathbb{R}$ vector space structure. Now, consider for every $k \in \mathbb{N}$ the subspace $$\mathbb{E}_k = \{ (a_n)_{n\in\mathbb{N}} \in \mathbb{R}^\mathbb{N}  : a_n = 0 \; \; \; \forall n > k\}$$
For every  $k \in \mathbb{N}$ you have that $\mathbb{R}^k$ and $\mathbb{E}_k$ are isomorphic as $\mathbb{R}$ vector spaces. This way, you can say in a formal fashion that there is a copy of every finite dimensional $\mathbb{R}$ vector space inside $\mathbb{R}^\mathbb{N}$, which is infinite dimensional.


How to change text every 5 seconds

Question: I have a line of text, with a span. I wanted to the text in span change every 5seconds.
I made a script :

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('#cookie-alert .col h3 span').html(texts[point]);
  if(point < texts.length){
    point ++;
  }else{
    point = 0;
  }
  setInterval("changeText", 5000)
}

changeText();

So the array contains all the texts.
So with this, the first text appears but not others.
I have an error:

"ReferenceError: changeText is not defined" at line "setInterval("changeText", 5000)"

I don't understand where is my mistake
Comment: try `setInterval(changeText, 5000)` Pass it as function and not a text
Comment: Don't work, same error...
Answer: setInterval takes as its first argument the function, not the function's name as string like this:
setInterval(changeText, 5000)

But you really should be using setTimeout in the function like this:

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('h3').html(texts[point]);
  if(point < texts.length - 1){
    point ++;
  }else{
    point = 0;
  }
  setTimeout(changeText, 5000)
}

changeText();

or simply setInterval like this:

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('h3').html(texts[point]);
  if(point < texts.length - 1){
    point ++;
  }else{
    point = 0;
  }
}
changeText();
setInterval(changeText, 5000)

Edit: To work flawlessly you wanna have the if be if(point < texts.length - 1) so it repeats at the same rate.
Comment: Yeah thank you, first solution work. But i want to replay this when the last word is showing...
Comment: Note that I updated my answer to include a fix for the counter. And also if an answer solved your problem you can accept it by checking the checkmark on the left - this will give you rep a +2 boost.
Answer:
You have to pass the changeText as a function and not a text.
You have to call setInterval outside the fuction changeText
As suggested, need to use texts.length - 1 coz you start counting from 0.

var texts = new Array();
texts.push("Text1");
texts.push("Text2");
texts.push("Text3");

var point = 0;

function changeText(){
  $('#cookie-alert .col h3 span').html(texts[point]);
  if(point < ( texts.length - 1 ) ){
    point++;
  }else{
    point = 0;
  }

}

setInterval(changeText, 5000); /*Call it here*/
changeText();
Comment: @sinisake You are correct. Added on the answer. Thanks alot.

How to change text every 5 seconds


multiple instances of httpd24 RHSCL

Question: I need to create a second apache instance (same version) on Redhat 7.9. The reason for this is that I want to create a second development environment where apache restart will not affect the other apache instance. I am using httpd24-httpd 2.4.34 RHSCL and I am not able to find any related documentation.
Do you know if multiple apache instances is supported for httpd24-httpd RHSCL on RH 7.9 and if there is any documentation I can follow?
Thank you in advance
Answer: It's a bit of a guess tbh, but what about installing the second instance into a container? See here https://catalog.redhat.com/software/containers/rhscl/httpd-24-rhel7/57ea8d049c624c035f96f42e

multiple instances of httpd24 RHSCL


postfix restrict smtp sender based on ip address

Question: I have a postfix server that I inherited many years ago.  Originally it successfully controlled the sending of messages through authentication and IP addresses - if an authenticated user was sending from an IP address in 'mynetworks', it was allowed.  Since then it's been through two major upgrades, from Lenny to Jesse in 2017 and from Jesse to Bullseye in 2022.  It seems the IP address restriction requirement was lost with the Bullseye upgrade, and now authenticated users can send from any IP address.
All of the smtpd checks and restrictions in main.cf have historically been under smtpd_recipient_restrictions, with smtpd_helo/sender/data_restrictions all being empty.  Here is are the current settings:
smtpd_recipient_restrictions =
        reject_unlisted_recipient,
        permit_mynetworks,
        check_client_access    hash:/etc/postfix/GEN000_override,
        check_client_access  regexp:/etc/postfix/fqrdns.regexp,
        check_helo_access      hash:/etc/postfix/access,
        check_helo_access    regexp:/etc/postfix/helo_blacklist.regexp,
        check_sender_access    hash:/etc/postfix/blacklist,
        check_sender_access  regexp:/etc/postfix/sender_blacklist.regexp,
        check_sender_mx_access cidr:/etc/postfix/mx_access.txt,
        check_sender_access    hash:/etc/postfix/bdwl
        check_client_access    hash:/etc/postfix/broken_helos,
        reject_invalid_hostname,
        reject_non_fqdn_sender,
        reject_unknown_sender_domain,
        reject_unknown_recipient_domain,
        reject_non_fqdn_hostname,
        reject_non_fqdn_recipient,
        reject_unauth_destination,
        check_recipient_access hash:/etc/postfix/restricted,
        reject_unknown_client,
        reject_unknown_hostname,
        reject_rbl_client zen.spamhaus.org,
        reject_rbl_client bl.spamcop.net

Although I've learned a lot about postfix over the years, I still find the system daunting.  Needless to say, lots of packages were replaced and perhaps of significance, we had to move from SquirrelMail to RoundCube for our web-based clients (most use Thunderbird).  FWIW I did try...
smtpd_client_restrictions = permit_mynetworks, reject

...and this worked, but had the undesired side effect bouncing all incoming mail from external sources (e.g. gmail.com) with 554 5.7.1 errors.  I am hoping something simple was moved or lost during the upgrade.  Pointers welcome!!
Comment: Assuming you are using debian's default packages, jessie shipped with postfix 2.11.3 but postfix megred "smtpd_client_restrictions" with relay in 2.10. So the problem was probably not caused when you upgraded to Bullseye  Please read postifx documentation to have a better understanding about the changes. https://www.postfix.org/postconf.5.html#smtpd_recipient_restrictions
Comment: Look at the [tag descriptions](https://serverfault.com/tags/postfix/info); I suspect you have different smtpd_mumble_restrictions for general exchange service on 25 and on a submission port such as 465 - that would be clearly visible in a config dump using postconf -n/-M.
Answer: Well, I had to set this aside for awhile, but I was able to get back to it this week and have found the answer.  Prior to the Bullseye upgrade, master.cf contained the following:
submission  inet  n     -       n       -       -       smtpd
  -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o smtpd_client_restrictions=permit_mynetworks,reject

After the upgrade this was changed to:
submission  inet  n     -       n       -       -       smtpd
  -o smtpd_recipient_restrictions=
  -o smtpd_relay_restrictions=permit_mynetworks,permit_sasl_authenticated,reject

So recipient_restrictions were replaced with relay_restrictions.  With this configuration, any authenticated user could send mail regardless of location/IP address.  For some reason (by design or user error, I don't know), the client_restrictions line was missing after the upgrade.  Restoring it...
submission  inet  n     -       n       -       -       smtpd
  -o smtpd_recipient_restrictions=
  -o smtpd_relay_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o smtpd_client_restrictions=permit_mynetworks,reject

...solved the "send from anywhere" problem.
Comment: It's worth noting that this addition of `smtpd_relay_restrictions` was announced in Postfix release notes.


Exception follows-org.apache.flume.FlumeException: Unable to load source type: com.cloudera.flume

Question: I am trying to do twitter analysis using Flume. For getting the tweets from the twitter i have set all the required params (consumerKey, consumerSecret, accessToken and accessTokenSecret) in the flume.conf files .
TwitterAgent.sources = Twitter
TwitterAgent.channels = MemChannel
TwitterAgent.sinks = HDFS

TwitterAgent.sources.Twitter.type = com.cloudera.flume.source.TwitterSource
TwitterAgent.sources.Twitter.channels = MemChannel
TwitterAgent.sources.Twitter.consumerKey = xxxxxxxxxxxxxxxxxxxxxxxxxx
TwitterAgent.sources.Twitter.consumerSecret = xxxxxxxxxxxxxxxxxxxxxxxxxx
TwitterAgent.sources.Twitter.accessToken =  xxxxxxxxxxxxxxxxxxxxxxxxxx
TwitterAgent.sources.Twitter.accessTokenSecret = xxxxxxxxxxxxxxxxxxxxxxxxxx
TwitterAgent.sources.Twitter.keywords = hadoop,opensource,iamsrk,onairwithaib,ihrithik
TwitterAgent.sinks.HDFS.channel = MemChannel
TwitterAgent.sinks.HDFS.type = hdfs
TwitterAgent.sinks.HDFS.hdfs.path = hdfs://localhost:8020/elections/tweets/%Y/%m/%d/%H/
TwitterAgent.sinks.HDFS.hdfs.fileType = DataStream
TwitterAgent.sinks.HDFS.hdfs.writeFormat = Text
TwitterAgent.sinks.HDFS.hdfs.batchSize = 10
TwitterAgent.sinks.HDFS.hdfs.rollSize = 0
TwitterAgent.sinks.HDFS.hdfs.rollCount = 10000

TwitterAgent.channels.MemChannel.type = memory
TwitterAgent.channels.MemChannel.capacity = 10000
TwitterAgent.channels.MemChannel.transactionCapacity = 100

Classpath in flume-env.sh
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
FLUME_CLASSPATH="home/nick/Downloads/apache-flume-1.6.0-bin/lib/flume-sources-1.0-SNAPSHOT.jar"

When I run flume agent
`apache-flume-1.6.0-bin/bin$`  ./flume-ng agent -n TwitterAgent -c conf -f ../conf/twitter.conf

    INFO source.DefaultSourceFactory: Creating instance of source Twitter, type com.cloudera.flume.source.TwitterSource
15/10/30 01:44:19 ERROR node.PollingPropertiesFileConfigurationProvider: Failed to load configuration data. Exception follows.
org.apache.flume.FlumeException: Unable to load source type: com.cloudera.flume.source.TwitterSource, class: com.cloudera.flume.source.TwitterSource
    at org.apache.flume.source.DefaultSourceFactory.getClass(DefaultSourceFactory.java:69)
    at org.apache.flume.source.DefaultSourceFactory.create(DefaultSourceFactory.java:42)
    at org.apache.flume.node.AbstractConfigurationProvider.loadSources(AbstractConfigurationProvider.java:322)
    at org.apache.flume.node.AbstractConfigurationProvider.getConfiguration(AbstractConfigurationProvider.java:97)
    at org.apache.flume.node.PollingPropertiesFileConfigurationProvider$FileWatcherRunnable.run(PollingPropertiesFileConfigurationProvider.java:140)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.cloudera.flume.source.TwitterSource
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:195)
    at org.apache.flume.source.DefaultSourceFactory.getClass(DefaultSourceFactory.java:67)
    ... 11 more

can anyone say why this error is thrown when i set the flume source.jar already.Please help me out on this .
Answer: flume configuration path needs to be mentioned properly  instead of ../conf/twitter.conf. Try to point the conf to right path in the parameter and execute it.


Get value from msg.payload return from a mysql query Node-RED

Question: i am starting with using Node-RED. i have no JS experience.
in 1 node for the mysql DB i have to query with msg.topic.
the return msg looks like this.
{ "topic": "SELECT sum FROM log WHERE id = 2", "payload": [ { "sum": 15 } ], "_msgid": "c93094ee.36cf68" }

How do i extract the number 15 in the example out msg.payload?
thanks.
Answer: in  function node following the query.
var sum  = msg.payload[0].sum;
...

the [] in the payload signify and array of answers so the [0] says take the first element from the array.
Comment: I wish it was that simple but Thank you.
Comment: According to the debug output the object and array returned as a string not as an object / array. Since your answer would be the correct in the case of an object / string and the problem was my mistake i will mark your answer as correct. thank you.


Apache Camel : The right way to build a XML parsing batch?

Question: I am trying to code a Camel batch :

process all files inside a specific directory and for each file :
validate the XML with a XSD schema
unmarshall different parts and process data
don't stop on exception
if a least one error occurs, move to failed dirrectory at the end, move to done otherwise

The difficulties I encounter :

File Component allow to automatically move file on done/failed directory but as soon as you use of split/aggregator, the file is
always moved in done and don't even wait the aggregation finished.
Managing Exception is not intuitive
Split and aggretors are nightmare and there is not enough "real world" examples in documentation
XML tokenization on complex structure brings us to something beyond understanding

Of course, I meet these problems because I am new to Apache Camel :)
The idea of what I am trying to do :

File Component (ok)
XSD validation (ok, if error, File component move to failed)
make many splits/multicast to read XML, when a error occurs, we ignore exception, keep a header in error, and continue  (not really ok, I can read but don't manage to aggregate correctly)
we aggregate (in fact nothing to aggregate,
we just want to check all headers)
if error, we explicitely move
to a failed directory

Simplified XML for this example :
<root>
    <library></library>
    <books year="2015">
        <book></book>
        <book></book>
        ... many
    </books>
    <books year="2016">
        <book></book>
        <book></book>
        ... many
    </books>

   ... many years

</root>

How would you construct the batch with such an XML ?
Moreover, let's say you have to read "library" before anything else (and use pipeline). Also, is the idea of saving error in header (boolean) good ?
Note: Special thanks to Claus Ibsen who responds to many Camel posts on SO, but also, please try to not just give a simple link on the Apache Camel documentation :) Really, for newbies, Apache Camel documentation sux.
Thanks
Answer: Did you read "Camel in Action" book?
This boils down on how big your XML are. If the files are "small" enough (where small depends on how much RAM you have) you don't need to stream them.
I would start with a route like this:

Validate XML (see How can I validate xsd using apache camel? )
Unmarshal to a Java object
Process <library> value
Split on each book (basically a for loop)
Process each book and "remember" in some header if an Exception happened
After the split, if exception happened then raise it again so file component will move to failed folder

Example (not tested code):
<route>
    <from uri="file:yourInputDir" />
    <to uri="validator:file:books/schema.xsd"/>
    <unmarshal>
        <jaxb contextPath="package.of.your.java.pojo" />
    </unmarshal>
    <to uri="bean:libraryProcessor" />
    <split strategyRef="saveExceptionInHeader">
        <simple>${body.getBooksList}</simple>
        <doTry>
            <to uri="bean:processBooks" />
            <doCatch>
                <exception>java.lang.Exception</exception>
                <setHeader headerName="RemeberLastException">
                    <simple>${exception}</simple>
                </setHeader>
            </doCatch>
        </doTry>
    </split>

    <to uri="bean:throwExceptionIfRemeberLastExceptionHeaderPresent" />
</route>

The name of each bean suggest what it does, it should not be a difficult task to implement it.
Add a lot of log statements to get some feedback on what Camel does.
Comment: Thank you, but your link shows an exemple which is too basic (and is too old). The initial need may include a multicast and nested splitters/aggregators. I really expect to see the almost exact answer. It is CRAZY that we can find absolutely nothing on all the Internet on "how to parse an XML" with Apache Camel, and I mean, with a minimum complex XML. I quickly search in Camel in Action, always the same : no real life example.
Comment: The idea was precisely to not load all in memory at once, but using sax parsing and partial unmarshalling :)
Comment: @user2668765 Use a `streaming` splitter with an XML tokenizer, then unmarshal the single object. See http://www.davsclaus.com/2011/11/splitting-big-xml-files-with-apache.html
Comment: @user2668735 I agree with you. There is a lack of "how to handle a huge XML file in Camel", I'll see if I can prepare a more complete example.


How to execute some js code after click on exposed filter AJAX enabled submit?

Question: I have tried to update the input value of an exposed filter field before submit of the exposed filter through Js.
What I have tried
<code>$('#edit-submit-phrases').on('click', function() {
  alert('check');
});
</code>
No alert message.
I also tried:
<code>jQuery('#edit-submit-phrases').mousedown()
</code>
Answer: You can use the ajaxStart() function, to execute something before  Ajax request begins:
<code> Drupal.behaviors.<themename/modulename> = {
  attach: function (context, settings) {
    $('#edit-submit-phrases').on('click', function() {
      $( document ).ajaxStart(function() {
        alert('check');
      });
    });
  }
};
</code>
Comment: Thanks for quick reply. Still getting the same issue. No alert message.
Comment: Are you using drupal.behaviours or just jquery ready?
Comment: i am using drupal.behaviours.
Comment: Works if i remove "$('#edit-submit-phrases').on('click', function() {
      $( document ).ajaxStart(function() {           });
    });
Comment: but you need it on that event only, right?
Comment: yes you are right.
Comment: For me its working, but not the first time. I will try to find out some solution
Comment: Thanks for your help it works now if remove $( document ).ajaxStart(function() {  }); . Even if on first time. Only the issue is that it Not working inside the panel page. working for other view page.


How do I get a column from an SQLAlchemy result using a column variable?

Question: How can I get at the column of a result if I have a variable for the column?  The below is a simplified example. I have a variable that contains the column I want, which will be used in the query. I now want to get the same column from the result.
col_id = some_table.id
query = session.query(col_id)
for row in query:
   id = row ?? col_id

I don't want to have to know the name of the column, as the actual code structure is more like this:
col_id, query = build_query()
for row in query:
  id = row ?? col_id

Answer: You can access it using the key attribute of the column.
for row in query:
    id_ = row[col_id.key]

but this approach is deprecated and will be removed in SQLAlchemy 2.0.  The recommended approach is to use the row's _mapping attribute.
for row in query:
    id_ = row._mapping[id_col.key]

or you could output the rows as dictionaries:
for row in query.mappings():
    id_ = row[id_col.key]


Jest ignorando especificações do package.json

Question: Estou implementando testes em minha aplicação web em react com o jest. Como ele foi iniciado com o "create-react-app" foi fácil configurar o ambiente.
Mas por algum motivo o jest parece ignorar especificações do package.json...
<code>{
  "jest": {
    "collectCoverageFrom":[
      "src/**/*.{js,sx}",
      "!src/index.js",
      "!src/BooksAPI.js"
    ],
    "snapshotSerializers": ["enzyme-to-json/serializer"]
  }
...
}
</code>
Embora eu tenha acrescentado ao collectCoverageFrom para ignorar os arquivos index e BooksAPI eles persistem quando rodo testes com a flag --coverage ativa. Alem disso, apesar de eu declarar especificamente que quero usar o serializer do pacote 'enzyme-to-json' o snapshot permanece como o padrão do jest.

Alguém sabe o que possivelmente eu poderia estar fazendo errado? Já chequei a digitação com atenção e acho que está correto. Segue o link do projeto caso seja necessário: https://github.com/Matheusbafutto/reactnd-project-myreads-starter
Comment: Podes ter também `collectCoverage: true`. Já testaste essa configuração?
Comment: Já testei mas não chegou a resolver...
Answer: Parece que era um problema no próprio react-scripts. O erro ocorria quando usava a versão 0.9.x do react-scripts. Ao fazer o update para a versão 1.0.13 o problema desapareceu.


Undefined references while using ffmpeg 2.1.1 for Android

Question: I'm building ffmpeg following the same pattern as halfninja's build: make the ffmpeg's main available from Java through JNI. I built ffmpeg with the following options:
./configure \
    --prefix=$PREFIX \
    --disable-shared \
    --enable-static \
    --disable-doc \
    --disable-ffmpeg \
    --disable-ffplay \
    --disable-ffprobe \
    --disable-ffserver \
    --disable-doc \
    --disable-symver \
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
    --target-os=linux \
    --arch=arm \
    --enable-cross-compile \
    --sysroot=$SYSROOT \
    --extra-cflags="-Os -fpic $ADDI_CFLAGS" \
    --extra-ldflags="$ADDI_LDFLAGS"
$PREFIX, TOOLCHAIN, … being set to corresponding folders from my NDK. $ADDI_CFLAGS is set to -marm and $ADDI_LDFLAGS and $ADDITIONAL_CONFIGURE_FLAGS are both unset. The resulting static libraries are created:
$ ls -1 android/arm/lib/
libavcodec.a
libavdevice.a
libavfilter.a
libavformat.a
libavutil.a
libswresample.a
libswscale.a
pkgconfig
I expose them with an Android.mk file, ffmpeg being built in $NDK/sources/ffmpeg-2.1.1:
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavdevice
LOCAL_SRC_FILES:= lib/libavdevice.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavcodec
LOCAL_SRC_FILES:= lib/libavcodec.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavformat
LOCAL_SRC_FILES:= lib/libavformat.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libswscale
LOCAL_SRC_FILES:= lib/libswscale.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavutil
LOCAL_SRC_FILES:= lib/libavutil.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libavfilter
LOCAL_SRC_FILES:= lib/libavfilter.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE:= libwsresample
LOCAL_SRC_FILES:= lib/libswresample.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_STATIC_LIBRARY)
So, up to there, everything looks good. Now, I try to build the ffmpeg binary equivalent as a static library. I copied (and didn't change a single character for now) ffmpeg.c, ffmpeg.h, cmdutils.c, cmdutils.h, ffmpeg_opt.cand ffmpeg_filter.c in my jni folder. I also have two directly JNI-related files in this folder (copied from halfninja's build, I just changed the package name). Here's the relevant Android.mk:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_C_INCLUDES := /Applications/android-ndk-r9b/sources/ffmpeg-2.1.1
LOCAL_CFLAGS := -Wdeprecated-declarations
LOCAL_MODULE := videokit
ANDROID_LIB := -landroid
LOCAL_LDLIBS += -llog -ljnigraphics -lz
LOCAL_SRC_FILES := videokit/com_rfc_video_ffmpeg_Videokit.c videokit/ffmpeg.c videokit/cmdutils.c videokit/ffmpeg_opt.c videokit/ffmpeg_filter.c
LOCAL_SHARED_LIBRARIES := libavdevice libavformat libavfilter libavcodec libwscale libavutil libswresample libswscale libpostproc
include $(BUILD_SHARED_LIBRARY)
$(call import-module,ffmpeg-2.1.1/android/arm)
Everything compiles fine, but doesn't link. Here are the first errors:
[armeabi] SharedLibrary  : libvideokit.so
/Applications/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/objs/videokit/videokit/cmdutils.o: in function print_all_libs_info.constprop.5:jni/videokit/cmdutils.c:1063: error: undefined reference to 'swresample_version'
/Applications/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/objs/videokit/videokit/cmdutils.o: in function print_all_libs_info.constprop.5:jni/videokit/cmdutils.c:1063: error: undefined reference to 'swresample_configuration'
/Applications/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/objs/videokit/videokit/cmdutils.o: in function opt_default:jni/videokit/cmdutils.c:558: error: undefined reference to 'swr_get_class'
/Applications/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/objs/videokit/videokit/cmdutils.o: in function opt_default:jni/videokit/cmdutils.c:561: error: undefined reference to 'swr_alloc'
/Applications/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/objs/videokit/videokit/cmdutils.o: in function opt_default:jni/videokit/cmdutils.c:563: error: undefined reference to 'swr_free'
/Applications/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/darwin-x86_64/bin/../lib/gcc/arm-linux-androideabi/4.6/../../../../arm-linux-androideabi/bin/ld: ./obj/local/armeabi/objs/videokit/videokit/ffmpeg_opt.o: in function show_help_default:jni/videokit/ffmpeg_opt.c:2464: error: undefined reference to 'swr_get_class'
What I don't understand is that these functions are defined and available in libswresample.a, which I'm linking to:
arm-linux-androideabi-nm /Applications/android-ndk-r9b/sources/ffmpeg-2.1.1/android/arm/lib/libswresample.a  | grep -i -e swr_get_class -e swresample_version
000001d4 T swr_get_class
00000178 T swresample_version
What am I doing wrong? Is there another, maybe simpler way to expose ffmpeg as a static library available via JNI? (I don't use halfninja's because I need at least ffmpeg 1.1, while his is in 0.9).
Answer: Your names got a bit scrambled: in one place, you called it libwsresample, elsewhere libswresample.
Check all names for consistency.
Comment: Actually, thank you for a clear description of up-to-date build procedure, people have been looking for this, e.g. http://stackoverflow.com/questions/20194696/how-to-use-android-ndk-r9b-to-compile-ffmpeg-for-android
Comment: Just for completion: here's a complete how-to I wrote to get latest FFmpeg release working on Android. https://enoent.fr/blog/2014/06/20/compile-ffmpeg-for-android/
Comment: Nice catch, thanks! I left work for now, will keep you up to date tomorrow.
Comment: @AlexCohn Could you look at http://stackoverflow.com/questions/27519462/ndk-undefined-reference-error-can-not-create-shared-library


Can I configure custom name for http trigger based azure function of version 2.x runtime?

Question: My HTTP Trigger azure function is version 2.x runtime based.
Is it possible to supply function name via application settings so that it can be changed later as per need?
[FunctionName("%FunctionName%")]
       public static async Task<IActionResult> Run(
          [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ExecutionContext context)
    {
       //function logic
    }

Comment: Some response would be helpful. Thanks
Answer: No, that is not possible because attrtibute values always need to be a constant expression. They must be fully evaluated at compile time.
I'm intrigued why you would have this requirement.
Since I always have one function definition per class I do the following:
[FunctionName(nameof(MyFunction))]
Where MyFunction is the name of the class. More info on function naming in this blogpost.
Comment: I know the requirement is weird but that is customer's demand. Now I can go back inform them accordingly.Thanks & appreciate your help.


Get the parent items of a menu item

Question: How can I get the parent items of a menu item for a view?
I added a Global: null argument in the view and I need to get the parent items of this view. The view is set to belong to a menu in admin/build/menu-customize/primary-links.
I tried these in the argument to examine the parent items:
$menuParent = menu_get_active_trail();
dsm($menuParent);
However, it's not resulting in the output I hoped. I tried to look for a right function in http://api.drupal.org/api/drupal/includes--menu.inc/group/menu/6 but I get confused with all these functions: menu_tree, menu_tree_data, menu_get_ancestors etc.
I am using Drupal 6.
Answer: There is not an easy way to get the parent of a specific menu item. The problem is that a path can be in many menus so you need to not only know the path of the item whose parant you want to find, but also which menu to look for them.
The menu_links table hold the info and with a few queries you could find info about the parent. If you actually want to change anything in the menu being printed, that's a completely different story, and can be quite tricky in Drupal 6.
To get menu item you could do something like this:
$path = 'foo';
$menu = 'bar'
$mlid = db_result(db_query("SELECT plid FROM {menu_links}
          WHERE link_path = '%s'
          AND menu_name = '%s'";, array($path, $menu)));

$menu_item = menu_get_item($mlid);
// $menu_item is now the parent menu_item of the menu in bar with path foo

Get the parent items of a menu item


Inverted Paradiddle

Question: I've been learning paradiddle variations and I've come across one called the "Inverted Paradiddle".
I'm not sure if this is a standard naming convention but what it means is instead of a normal single paradiddle.
Rlrr Lrll
We have this "Inverted" version.
Rllr Lrrl
My question is how is this an "Inversion"?
There are four different variations of the single paradiddle you can get by shifting where the accents are and by the resource I'm going from they are:
Single: Rlrr Lrll
Inverted: Rllr Lrrl
Reverse: Rrlr Llrl
Outward: Rlrl Lrlr

Reverse kind of makes sense since it's sort of played backwards.
Comment: Few things, 1) can you post notation or at least use case (RlrrLrll) to indicate accents?  2) Where did you get these definitions from?  3) A lot of "hybrid" rudiments are just called whatever by whoever came up with them.  I guess we could still reason why someone might call it "inverted", but I don't think that's a standard musical term.
Comment: The only thing I can tell is if you start the normal on the 4th or 8th stroke you have a regular paradiddle but that's more like displacement.
Comment: Is this from Drumeo -  Dorothea Taylor?
Comment: To 'invert' a chord means to change the order its notes are played in. CEG - root, EGC - 1st inversion, GCE - 2nd inversion. It's the same concept with paradiddles. Move the 1st note from the start to the end, 1st inversion. Move the next, 2nd, and so on.
Comment: @Edward, This was just on a sheet that my drum teacher had. I am curious if anybody else has seen this term. Not surprised it may not be standard.
Comment: @Tim then they would all be inversions yes?
Comment: Except the 'root', yes. I suggest you find the Drumeo video, it explains all. 'Why paradiddles are so important'.
Comment: 'Rotated' may be more apposite.
Answer: "Inversion" in music is sometimes closer to "rotation" ("chord inversions" in particular). The difference in the various paradiddles is the starting place, which is equivalent to changing the position of the accents.

RLRR LRLL
^ ^^  ^
| ||  |
Single|
  ||  |
  ||  Inverted
  ||
  Reverse
   |
   Outward

Or, put another way:

Single:   RLRR LRLL RLRR LRLL = RLRR LRLL
Inverted:       RLL RLRR L    = RLLR LRRL
Reverse:    RR LRLL RL        = RRLR LLRL
Outward:     R LRLL RLR       = RLRL LRLR

This begs the question of the remaining "inversions". Note first that all would start with the left hand.

LRRL RLLR = inverted, starting on second group
LRLL RLRR = single, starting on second group
LLRL RRLR = reverse, starting on second group
LRLR RLRL = outward, starting on second group
Comment: This is an interesting way to generate the variations. I was doing it by shifting the pattern of 4 around but this picks a right hand to start on based on the whole set of 8. Inverted is the standout by being in the second group here. I think this is the most likely answer into the brain of the person who thought of these names.
Comment: "Inversion" in music is more like "permutation": that statement is overbroad.  It's certainly not true of the inversion of a contrapuntal theme or of a serial tone row.  Further, it seems to me that "rotation" better describes the operation you're writing about than "permutation." While rotations are a subset of permutations, a permutation that isn't a rotation would yield a figure that isn't a paraddidle (for example, a strict alternation between right and left).
Answer: Paradiddle
RLRR LRLL
The Inverted version, can be though of as:

first shifting the starting position of the paradiddle pattern by one position to the right :
LRRL RLLR

but then, because we want to start with the right hand, we have to swap Lefts and Rights ("inverting"):
RLLR LRRL

The Reverse is a shift of the original pattern by two position to the right.  And the Outward is a shift by three.
Both the Reverse and Outward patterns don't need to swap Lefts and Rights compared to the original, because they already begin on a Right.
Comment: So to sum up, this is the only shift that causes the set of 8 hits to be led by a left? I like it. Not that I play it by starting with my left but it seems believable.
Comment: @Nick - that's one of the points of paradiddles - to create independence for *both* hands. Not always 'leading with the right' -which I'm trying hard to correct. And by varying which hit/s get the emphasis, paradiddles cover an awful lot - especially when they're not all done on one drum.
Comment: Shifting by 4,5,6,7 is equivalent to shifting by 0,2,1,3 and swapping Lefts and Rights
Answer: In my mind rudiment inversions are akin to chord inversions. For example, with a C Major 7 chord (for an equal number of notes to invert) you would have C-E-G-B. Hopefully the following table illustrates my way of thinking clearly:

C7 chord
Paradiddle
Inversion

CEGB
Rlrr Lrll
None

EGBC
Lrrl Rllr
1st Inv.

GBCE
Rrlr Llrl
2nd Inv.

BCEG
Rlrl Lrlr
3rd Inv.

At which point it wraps back around. The 1st, 2nd, 3rd, etc. inversion names aren't really used in my experience when it comes to rudiment terminology (i.e. I've never heard anyone refer to "Rrlr Llrl" as the 2nd inversion of a paradiddle), but hopefully that at least makes it clear where the terminology might have come from.

Inverted Paradiddle


Limit of the $y(x)$

Question: I have the following equation:

$$ y=(c_1+c_2x)e^{3x} + \frac{10}{b^2}e^{bx} $$

which its solution satisfies $$\lim_{x \to \infty} y(x) =0$$
and diverges as $x \to \infty$
Thank you.
Comment: So what's the question?
Comment: I was going to try and format your equation, but its meaning is ambiguous. Can you please reformat it?
Comment: Thanks a lot for your interest ,

Mr Avatar has solved it.
Answer: For $c_1=c_2=0$ and $b\lt 0$, $\lim_{x\to\infty}y(x)=0$ and and for $b,c_1,c_2\gt 0, \lim_{x\to\infty}y(x)=\infty$

Limit of the $y(x)$


What is the scope of copyright?

Question: I was studying My Favorite Things by John Coltrane to play on piano, while listening to it and its other versions I have learned that this Jazz standard was actually from a motion picture called Sound of Music.
John Coltrane version:

Sound of Music version:

And then on comments I have seen that

Ariana Grande's 7 rings is also the same.
My question is, these songs are obviously same with some differences and how copyrights work on this issue? Or are there any musical theory background makes them different from each other?
I also know that most of the jazz standards are like this but still could not understand why all these versions are allowed by the original composer.
Comment: I'm voting to close this question because business and legal questions are explicitly off-topic as outlined in the help center. Copyright questions are usually on topic at law.stackexchange.com.
Answer: It's actually from the broadway stage show, The Sound of Music (1959). As the Movie didn't come out til 1965 it would be a bit of a time warp for Coltrane to have covered it in 61 ;)
Song copyright is a tortuous, torturous & sometimes tort-urous game of legalese.
Basically, it boils down to "Once a song is written & published it can then be covered by anyone who wants to; subject only to correct accreditation & payment of appropriate royalties."
If a song is "substantially modified" from the original then special permission can be needed, but not always & it was less insisted on in the past.
Obviously, someone like Coltrane is going to fairly "substantially modify" a piece, but who would deny him permission, when sales are guaranteed? Once a piece has been significantly covered by many, then that aspect of modification tends to get ignored. By the time you're covering something 60 years after the fact, no-one cares any more. Just release the cover, pay the royalties.
As Ariana Grande's cover is a partial re-write, negotiations will have taken place as to who owns what percentage of any part of the original vs new. If you look at the credits, you will never find percentages, but you will see it has shared credit.
Songwriters: Ariana Grande / Njomza Vitia / Richard Rodgers / Taylor Monet Parks / Charles Michael Anderson / Kimberley Anne Krysiuk / Michael David Foster / Oscar II Hammerstein / Thomas Lee Brown / Victoria Monet McCants
The original composer/author team, if you weren't aware, was Richard Rodgers & Oscar II Hammerstein.
Comment: "… sometimes tort-urous …" Ooo, that's cruel and unusual pun-ishment.
Comment: Rodgers was the composer, Hammerstein the lyricist.
Comment: @AndyBonner - sometimes, I just can't resist the urge ;))
Comment: OOT, but, can you explain the tort-urous pun?
Comment: @justhalf - Look up the meaning of the word 'tort'.
Answer: In the United States ...
To make a recording of a copyrighted song, one first contacts the rights holder and pays for the mechanical and distribution rights to the song. The cost varies according to the format or formats the song is to be distributed in and the number of copies to be made. A typical agreement can cover all existing formats as well as those that may be invented in the future. It's also a standard part of such agreements that the original composer(s)/lyricists(s)/rights-holders must be credited, along with the date of copyright and which rights are covered.
This is required regardless whether the recording is to be commercial or not.  For a commercial recording, in addition to any purchase of mechanical and distribution rights, there would be a negotiation of royalties.
For example, I paid Horace Silver's agency for the right to make a demo recording that included "Song for My Father". The recording was not intended for sale, so I didn't have to pay any royalties, but I did have to pay a fee for the mechanical rights based on the number of copies I intended to make.
Comment: That's interesting. My answer is based on UK law & practices. If you want to cover a song, you just cover it, correctly accredit it & you're off. It then ticks up any royalties via PRS/MCPS, just the same as the original. Looking at the details [behind a members only PRS wall], it seems the mechanical license is 'just done' as part of the accreditation process & require no actual 'Can I do this?' 'Yes' as a separate process. [I admit to being an amateur at this, I've always had record companies to do the paperwork ;)
Answer: "The sky is full of sounds … !" (s. lyrics of Sound of Music).
There are so many similar songs with the same harmonic, melodic and rhythmic patterns, maybe some have been transformed in different countries by migration etc. or transcultural transport. Often songs that ponder on copyright have a same root, and the original may be have gone lost.
The question of copyright in such cases is obsolete. (If you don't sell the "Moldau" by Smetana as your own composition view they are ridiculous.)
(I know there are always fights among pop musicians about stolen ideas. In my

What is the scope of copyright?


How Programmatically can I Compute Path Length by Injecting numerical value to a node in an RDF Graph Using Jena Ontology API?

Question: Building from the previous asked question (How can I programmatically compute path length using Jena RDF/Ontology API?), I need to multiply a numerical value (e.g. 3.5) to one of the specific class (its class size as detailed in the previous question) and be able to compute the overall path length(s) in an RDF Graph. Note that each path that fall-under this specific node will produce a new path weight result.
What I tried to do is to create a method called nValue and passed to it the classSize and the this numerical value variable then added it to the pathSize method for computing the pathLength, the method is as follows:
public static double nValue (int classWeight, double nv )
{
  double numValue = classWeight*nv;
  if ( nv < 1 ){
    numValue = 1.0;
  }
  return numValue;
}

Then tried to call this method in the pathSize method to vain. My problem is that I'm new to Jena. So I have a problem in getting a single class in an RDF graph and perform the multiplications to it and combine it to the pathLength computation.
Comment: According to the FAQ, "Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist".  The previous answers have given you a fair amount of code, and an answer to this question doesn't require all that much modification to the last answer.  So, what have you attempted (show us!), what didn't work (show us the bad results!), and what did you expect (mock up some fake, but good, results for us!)?
Comment: Please don't paste code in the comments;  the need to see your code is not mine alone.  Please edit your question to include the codes that you've written to attempt to solve this problem, to include the output that is generated, and to explain the results that you were expecting.
Answer: The code for the answer from the previous question was
public static int classSize( final Resource klass ) {
    return klass.getModel().listSubjectsWithProperty( RDFS.subClassOf, klass ).toList().size();
}

public static double pathSize( final List<Resource> path ) {
    int prevSize = classSize( path.get( 0 ));
    double pathSum = prevSize;
    for ( int i = 1; i < path.size(); i++ ) {
        int currSize = classSize( path.get( i ));
        double linkWeight = currSize < prevSize ? 0.5 : 1.0;
        pathSum += linkWeight + currSize;
        prevSize = currSize;
    }
    return pathSum;
}

It's not exactly clear to me what it is that you're trying to do, but it sounds like you're  trying to adjust the currSize in pathSize for certain classes (i.e., the value of returned by path.get( i ), but that you're having trouble comparing whether or not the class is one of the classes for which this should happen.  If I'm understanding correctly, you can do something like this:
private static Resource specialClass = ResourceFactory.createResource( "http://.../specialClass" );

public static double pathSize( final List<Resource> path ) {
    // ...
    for ( int i = 1; i < path.size(); i++ ) {
        final Resource klass = path.get( i );
        int currSize = classSize( klass );
        if ( specialClass.equals( klass ) ) {      // When klass is specialClass
          currSize = ...; // something different   // do the additional modification
        }
        // ...
    }
    // ...
}

Comment: Joshua thank you. Exactly, that's what I was trying to do and it has worked as I expected.


Prove that the quantity is an integer

Question: I want to prove that $\frac{n^3}{3}-\frac{n^2}{2}+\frac{n}{6} \in \mathbb{Z}, \forall n \geq 1$.
I have thought to use induction.
Base Case: For $n=1$, $\frac{n^3}{3}-\frac{n^2}{2}+\frac{n}{6}=\frac{1}{3}-\frac{1}{2}+\frac{1}{6}=0 \in \mathbb{Z}$.
Induction hypothesis: We suppose that it holds for $n=k$, i.e. that $\frac{k^3}{3}-\frac{k^2}{2}+\frac{k}{6} \in \mathbb{Z}$.
Induction step: We want to show that it holds for $n=k+1$.
$$\frac{(k+1)^3}{3}-\frac{(k+1)^2}{2}+\frac{k+1}{6}=\frac{k^3}{3}+\frac{k^2}{2}+\frac{k}{6}$$
Is everything right? If so, then we cannot use at the induction step the induction hypothesis, can we?
Or can we not get the desired result using induction?
Comment: Why would you think those expressions would be equal?  The induction step would be to show that the integrality of the right hand implied that of the left hand.
Comment: Side note:  I think it is easier to first argue that it's enough to check $n\in \{0,1,2,3,4,5\}$ and then check those cases.  Or, alternatively, note that your expression is $\frac 16 \times n(n-1)(2n-1)$ and show, by cases, that at least one of the terms in $n$ is even and at least one is divisible by $3$.
Comment: (I've put an answer as it is almost done already.)
Comment: You could also rewrite it as $2 \binom{n}{3} + \binom{n}{2}$ (inspired by the theorem that numerical polynomials are linear combinations of $\binom{-}{k}$).
Answer: Yes, we can. If $f(n)=\frac{n^3}{3}-\frac{n^2}{2}+\frac{n}{6}$, then $f(n+1)-f(n)=n^2$.
Comment: And since $f(n)$ is an integer and also $n^2$, we deduce that their sum, $f(n+1)=f(n)+n^2$, is also an integer, right? @metamorphy
Comment: Exactly. There are other approaches noted above - I've just followed your way.
Comment: Nice, thank you :)
Answer: If you want to use induction you want to show that
$$\frac{(k+1)^3}{3}-\frac{(k+1)^2}{2}+\frac{k+1}{6}$$ is an integer.  You can expand all the terms and use the known fact about the expression for $k$ to get there.
Another approach is to note that $6$ is a common denominator and say you want to prove that the numerator $2k^3-3k^2+k$ is divisible by $6$.  But $2k^3-3k^2+k=(2k-1)(k-1)k$ and one of $k$ or $k-1$ is even and one of the terms is a multiple of $3$.
Comment: Just try the three possibilities for $k \bmod 3$.  If it is $0$, then $k$ is a multiple of $3$.  If $1$, then $k-1$ is.  And if $2$, then $2k-1$ is.
Comment: Why is one of the terms a multiple of $3$ ?
Comment: Ah, I see... And so we have that $2 \mid (2k-1)(k-1)k$ and $3 \mid (2k-1)(k-1)k$ and thus $2 \cdot 3=6 \mid (2k-1)(k-1)k$, right?
Comment: That is correct.
Comment: Great, thank you :)
Comment: The first paragraph would benefit from actually showing the procedure described.
Answer: If you put everything over a common denominator you get $$f(n)=\frac {2n^3-3n^2+n}6=\frac {n(n-1)(2n-1)}6$$
Now it is easier, I think, to see what is going on for a straightforward induction, or you can write $2n-1=2n-4+3$ and split up into different fractions viz $$f(n)=\frac {n(n-1)(2n-4+3)}6=\frac {n(n-1)(n-2)}3+\frac {n(n-1)}2$$ and this is easily the sum of two integers since the product of $r$ successive integers is divisible by $r$ (easily proved by induction), or you can do the induction on $n$ based on this form of $f(n)$, which will should work easily.
Comment: I like this approach. Thanks a lot :)
Answer: To prove $$\frac{n^3}{3}-\frac{n^2}{2}+\frac{n}{6} \in \mathbb{Z}, \forall n \geq 1$$
We take common denominator and prove the numerator is a multiple of $6.$
The numerator factors as $$n(2n-1)(n-1)$$
One of $n$ or $n-1$ is even so the product is multiple of $2$
The remainder of n in dividing by $3$ is either $0$ or $1$ or $2$
In either of these cases the product  $$n(2n-1)(n-1)$$  is divisible by $3$
Thus the numerator is always a multiple of $6$ which makes the fraction an integer.
Comment: We have $n(n-1)(2n-1)$. For$ n=3k$ , $n$ is a multiple of $3$ so the product is a multiple of $3$. For $n=3k+1$ , $n-1$ is a multiple of $3$ and for $n=3k+2$, $2n-1 =6k+3$ which is a multiple of $3$.
Comment: I haven't understood why the product is divisible by 3. Could you explain it to me?
Comment: I see... Thanks :)
Answer: After writing it in the form $\,a_n/6$ we need only show that $a_n\equiv0\pmod 6$ for all $n,\,$ doable by testing all values $\,n\equiv 0,\pm1,\pm2,3\pmod 6.\,$ Equivalently we can test all values mod $2$ and $3$ and then we need only test values $\equiv 0,\pm1,$ which we can do quickly as below, in a way that generalizes.
$n\equiv\pm1\Rightarrow \color{#c00}{n^2\equiv 1}\Rightarrow  \underbrace{\overbrace{ 2n\color{#c00}{n^2}\!-\!3\color{#c00}{n^2}\!+\!n}^{\Large a_n}}_{\Large{\rm OP}\ =\ a_n/6}\equiv 3(n\!-\!1)\equiv 0\,$ mod $\,2$ & $3,\,$ so $\,2,3\mid a_n\Rightarrow 6\mid a_n$
Remark $\ $ More generally, as above, breaking $f(x)\in\Bbb Z[x]$ into odd and even parts shows
$$ \bbox[7px,border:1px solid #c00]{6\mid f(n) = g(n^2)n+h(n^2)\iff 6\mid h(0),\,\ 3\mid g(1),h(1),\,\ 2\mid g(1)+h(1)}\qquad\ \  $$
e.g. in OP $\ f(n) = (2n^2\!+\!1)n - 3n^2\ $ & $\ 3\mid g(1)\!=\!3,\,\ 3\mid h(1)\!=\!-3,\,\ 2\mid g(1)\!+\!h(1)=0$
For any polynomial $f(n)$ we can quickly mentally perform this test by computing $\!\bmod 6$ the values $\,g(1) \equiv $ sum of odd degree coefs, and $\,h(1)\equiv $ sum of even degree coefs, then apply the above tests.
Comment: This is different from other answers. Now I am thinking about it. Anyhow thank you so much for new kind of answer, Sir.
Comment: Agreed I think this is a very powerful approach
Answer: A different appraoch:
Note that
\begin{align}
\frac{n^3}{3}-\frac{n^2}{2}+\frac{n}{6} &= \underbrace{\frac{n(n+1)(2n+1)}{6}}_{\displaystyle=\sum_{k=1}^n k^2 }-2\,\underbrace{\frac{n(n+1)}{2}}_{\displaystyle=\sum_{k=1}^{n}k}+n=\sum_{k=1}^n(k^2-2k+1)\in\Bbb Z
\end{align}
Answer: $$F=\frac{n^3}{3}-\frac{n^2}{2}+\frac{n}{6}=\frac{n(n-1)(2n-1)}{6}$$
You can see that for any n(odd or even) the numerator is always a multiple of 6, so the sum of fractions is an integer; in fact we may have:

$n=6k  ⇒ F=6m/6=m $
$n=6k+1  ⇒ F=(6k+1)(6k+1-1)(12k+2-1)=6m/6=m$
$n=6k+2  ⇒ F=(6k+2)(6k+2-1)(12k+4-1)=6t/6=t$
$n=6k+3  ⇒ F=(6k+3)(6k+3-1)(12k+6-1)=6s/6=s$
$n=6k+4  ⇒ F=(6k+4)(6k+4-1)(12k+8-1)=6v/6=v$
$n=6k+5  ⇒ F=(6k+5)(6k+5-1)(12k+10-1)=6u/6=u$

Where m,t,s,u and v are integers.
Comment: I see... Thanks :)
Comment: Yeah. It's very simple answer. Thank you.
Answer: Let's continue from your last step.
$$\frac{(k+1)^3}{3}-\frac{(k+1)^2}{2}+\frac{k+1}{6}=\frac{k^3}{3}+\frac{k^2}{2}+\frac{k}{6}$$
$$=\frac{k^3}{3}-\frac{k^2}{2}+2\frac{k^2}{2}+\frac{k}{6}$$
$$=\frac{k^3}{3}-\frac{k^2}{2}+\frac{k}{6}+k^2$$
By induction hypothesis, first three terms yileds an integer and $k^2$ is an integer.
Thus finally we have showed that $$\frac{(k+1)^3}{3}-\frac{(k+1)^2}{2}+\frac{k+1}{6}$$ is an integer.
Comment: +1. For showing how to continue and end the proof the OP asked.
Comment: @farruhota thank you sir.

Prove that the quantity is an integer


if $|f'(x)|\le 4/5$ then is there a unique x such that $f(x)=x$

Question: Let $f:\mathbb{R} \to \mathbb{R}$ be continuously differentiable and such that $|f'(x)|\le \frac{4}{5}$ for all $x \in \mathbb{R}$ then does a unique $x\in \mathbb{R}$ exists such that $f(x)=x$?
My approach:- For $f(x)$ being equal to $x$, $f'(x)$ should be equal to $1$ which is against $|f'(x)|\le \frac{4}{5}$ so there does not exist $x\in \mathbb{R}$ such that $f(x)=x$.
Comment: Since $|f'(x)|\leq 4/5 < 1$ then f is a contraction map on $\mathbb{R}$ which is completed space with euclidean distance. Then we can use contraction map theorem to prove this problem.
Comment: @MayankDeora This not my point. I mean $lim_{x\to y}f'(x)=f'(y)$ and $f(x_0)=x_0$ does not imply $f'(x_0)=1$.
Comment: An easier way to see that your answer is off: consider constant functions.
Comment: How did you get "$f′(x)$ should be equal to 1" ?
Comment: @Akatsuki since$ f'(x) $ is continuously differentiable so $\lim_{x \to y}f'(x)=f'(y)$ that's why i think that $f'(x)$ should be equal to $1$ for $f(x)=x$
Comment: @MayankDeora How? There is little connection between what you said. Think carefully.
Comment: @Akatsuki sorry i correct my words :- $f(x)$ is continuously differentiable.
Comment: One way you can see the problem with your approach is this: consider $f(x)=x/2$. It is continuously differentiable. Also $f(0)=0$, yet $f'(0)=0.5$
Answer: Let $g(x)=f(x)-x$. According to Bolzano's theorem, it is enough to show that there exist $x_1$ and $x_2$ such that $g(x_1)g(x_2)\leq0$.
It is obvious that $-\frac{9}{5} \leq g'(x) \leq -\frac{1}{5}$, because $g'(x)=f'(x)-1$.
Hence, if $x_2 \geq x_1$ then $g(x_2) \leq g(x_1) - \frac{1}{5}(x_2-x_1)$ and if $x_2 \leq x_1$ then $g(x_2) \geq g(x_1) + \frac{9}{5}(x_1-x_2)$.
Therefore, if $g(x_1) \geq 0$ then there is an $x_2 \geq x_1$ which $g(x_2) \leq 0$ and if $g(x_1) \leq 0$ then there is an $x_2 \leq x_1$ which $g(x_2) \geq 0$. In both cases $g(x_1)g(x_2)\leq0$.


Total geral não soma

Question: Estou montando este formulário de orçamento. Quase tudo está perfeito. Só a soma total, que por mais que ajuste não está somando.

$(".real").maskMoney({
  prefix: 'R$ ',
  thousands: '.',
  decimal: ',',
  affixesStay: true
});

function rePlace(i) {
  return parseFloat(i.replace(/[^\d.,]/g, "").replace('.', '').replace(',', '.'));
}

Number.prototype.formataReal = function(c, d, t) {
  var n = this,
    c = isNaN(c = Math.abs(c)) ? 2 : c,
    d = d == undefined ? "," : d,
    t = t == undefined ? "." : t,
    s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
//any time the amount changes
$(document).ready(function() {
  $('input[name=r],input[name=p]').change(function(e) {
    var total = 0;
    var $row = $(this).parent();
    var rate = rePlace($row.find('.r').val());
    var pack = $row.find('.p').val();
    total = parseFloat(rate * pack);
    //update the row total
    $row.find('.amount').val('R$ ' + (total).formataReal(2, ',', '.'));

    var total_amount = 0;
    $('.amount').each(function() {
      //Get the value
      var am = rePlace($(this).val());
      console.log(am);
      //if it's a number add it to the total
      if (IsNumeric(am)) {
        total_amount += parseFloat(am);
      }
    });
    $('.total_amount').val(total_amount);
  });
});

function IsNumeric(input) {
  return (input - 0) == input && input.length > 0;
}

  <input name="r" class="rate r real" type="text" value="" />
  <input name="p" class="pack p" type="text" value="" />
  <input class="amount" type="text" value="" />

  <input name="r" class="rate r real" type="text" value="" />
  <input name="p" class="pack p" type="text" value="" />
  <input class="amount" type="text" value="" />

  <input name="r" class="rate r real" type="text" value="" />
  <input name="p" class="pack p" type="text" value="" />
  <input class="amount" type="text" value="" />

<input class="total_amount" type="text" value="" />
Answer: O problema está na sua função de verificação de numéricos IsNumeric:
function IsNumeric(input) {
  return (input - 0) == input && input.length > 0;
}

O .length sobre um Number vai dar undefined e por isso a comparação vai dar sempre false.
Altere a sua função IsNumeric para:
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Usei como referência a função de validação desta pergunta no SOen.
Analisando-a vemos que o isNaN devolve se não é um número. Por isso começamos por testar o inverso !isNaN para perceber se é um numero. No entanto utiliza também o isFinite para conseguir fazer com que inputs específicos como 1/0 que dão infinito não passem no teste.
Veja este exemplo sobre o isFinite:

console.log(1/0)
console.log(isFinite(1/0));

Veja como o seu código já funciona com essa alteração:

$(".real").maskMoney({
  prefix: 'R$ ',
  thousands: '.',
  decimal: ',',
  affixesStay: true
});

function rePlace(i) {
  return parseFloat(i.replace(/[^\d.,]/g, "").replace('.', '').replace(',', '.'));
}

Number.prototype.formataReal = function(c, d, t) {
  var n = this,
    c = isNaN(c = Math.abs(c)) ? 2 : c,
    d = d == undefined ? "," : d,
    t = t == undefined ? "." : t,
    s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
    j = (j = i.length) > 3 ? j % 3 : 0;
  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
//any time the amount changes
$(document).ready(function() {
  $('input[name=r],input[name=p]').change(function(e) {
    var total = 0;
    var $row = $(this).parent();
    var rate = rePlace($row.find('.r').val());
    var pack = $row.find('.p').val();
    total = parseFloat(rate * pack);
    //update the row total
    $row.find('.amount').val('R$ ' + (total).formataReal(2, ',', '.'));

    var total_amount = 0;
    $('.amount').each(function() {
      //Get the value
      var am = rePlace($(this).val());
      //console.log(am);
      //if it's a number add it to the total
      if (IsNumeric(am)) {
        total_amount += parseFloat(am);
      }
    });
    $('.total_amount').val(total_amount);
  });
});

function IsNumeric(input) {
  return !isNaN(parseFloat(input)) && isFinite(input);
}

  <input name="r" class="rate r real" type="text" value="" />
  <input name="p" class="pack p" type="text" value="" />
  <input class="amount" type="text" value="" />

  <input name="r" class="rate r real" type="text" value="" />
  <input name="p" class="pack p" type="text" value="" />
  <input class="amount" type="text" value="" />

  <input name="r" class="rate r real" type="text" value="" />
  <input name="p" class="pack p" type="text" value="" />
  <input class="amount" type="text" value="" />

<input class="total_amount" type="text" value="" />
Comment: Eu me esqueci e agora que fui fechar a tela me deparei com a situação: o cliente pode alterar o valor total. Mesmo se eu trocar o $('.valor_total_orc').each(function() para change, não refaz o cáculo. Seria possível recalcular o valor geral, depois de alterar o valor da linha?
Comment: @RogérioPancini Mas se o total é calculado e não indicado pelo cliente então fará mais sentido torna-lo *readonly* que simultaneamente resolve o problema

Total geral não soma


Train a model on batches with multiple epochs vs. each batch with multiple epochs

Question: In traditional supervised learning, say we split the data into $B$ batches, we will go through all these batches with $E$ epochs. The computational cost is $E\times B$.
But what if on each batch, we train the model for $E$ epochs, and then fetch the next batch till we go through all the batches. The computational cost remains the same. I tried it empirically on a neural network, the first method is better than the second one. But will it cause any difference mathematically?
Answer: This idea was discussed on r/MachineLearning here a few years ago. It was pointed out there that Fischetti et al. (2018, unpublished) proposed doing exactly this, and found good results for one very limited setting, training AlexNet on CIFAR-10. Other commenters said that it performed poorly for them.
Some thoughts:

If you use a very low learning rate, this is basically the same as multiplying the learning rate by $E$. But this is not true for reasonably-large learning rates.
If you're using Adam / other adaptive optimizers, if you're using momentum, or if you're using batch norm / etc, you're really breaking the iid assumption and things could maybe go a little wonky.
If you would have trained your minibatch algorithm for 100 epochs, you probably don't want to repeat each batch 100 times. Probably better to repeat each batch 2-5 times, and then run through that whole process (re-shuffling the batches) 20-50 times.
As a pure optimization problem for the training error, I think (but am not 100% sure) that theoretically, this method should converge to low training error in roughly the same situations as the standard minibatch SGD, and perhaps not much slower. I'm not really an optimization expert, though, this is entirely a guess.
It is likely that, at least in some settings, it will converge to a different training-error solution than standard SGD. (The "implicit regularization" is different.) I'm not aware of anyone having studied this theoretically; it seems unlikely, since mathematical understanding of the implicit bias of the standard algorithm people actually use is still pretty limited (for deep networks) at this point.
It might encourage overfitting to each training batch more than standard SGD, which could be bad.

Overall, though, I don't think anyone's really mathematically studied this setting. In "usual" single-machine training regimes, if you do data loading in parallel and pin CUDA memory / etc, loading the data isn't really the computational bottleneck, and so there doesn't seem to be a ton of reason to do this. In some regimes, though, it might be faster to run, and so could be worth exploring with a fairly small amount of "persistence."


Error showing "The variable 'uLS1' appears to change size on every loop iteration. consider preallocating for speed."

Question: % 3. Calculation of strain energy density
% CALCULATION OF STRAIN-ENERGY-DENSITY FOR EACH LOAD CASE
% u=1/2*sigma*epsilon

for p = 1:N_ele
    uLS1(p) = 1/2*(sigma_1(p,2:7)*epsilon_1(p,2:7)');
    uLS2(p) = 1/2*(sigma_2(p,2:7)*epsilon_2(p,2:7)');
    uLS3(p) = 1/2*(sigma_3(p,2:7)*epsilon_3(p,2:7)');
end
% AVERAGE OF ALL LOAD CASES
sed(:,a) = (uLS1' + uLS2' + uLS3')/3;       %11 ...    line

Error on command window:

"Unrecognized function or variable 'uLS1'."
Error in main_file (line 86)
sed(:,a) = (uLS1' + uLS2' + uLS3')/3;
Comment: It seems like you mix 2 sources of error. The first when you execute the script (Unrecognised function or variable error), and the second one that appears when the script is analysed for performance enhancement (loop iteration). Both are totally unrelated. Fix the first one by declaring uLS1 before using it, like uLS1 = [];. The second error is just a warning.
Comment: after using this uLS1 = zeros(1:N_ele); , uLS2 = zeros(1:N_ele);, uLS3 = zeros(1:N_ele); preallocation error is not coming but error still showing in sed(:,a) = (uLS1' + uLS2' + uLS3')/3;   - "Unable to perform assignment because the indices on the left side are not compatible with the size of the right side."    How do I prelallocate this sed as there is no loop here?
Answer: Regarding the error: The variable sed must have N_ele rows such that size(sed,1) = N_ele. If the number N_ele changes with every iteration a, then you can use a cell instead an array, i.e., sed{a} =  (uLS1' + uLS2' + uLS3')/3;.
Regarding the warning: Preallocate the arrays uLS1, uLS2, and uLS3 before the for-loop when you know the size they will have, i.e.,
uLS1 = zeros(1, N_ele);
uLS2 = zeros(1, N_ele);
uLS3 = zeros(1, N_ele);

If you don't know their sizes in advance, you have the choice to ignore Matlab's warning and proceed as is.


CSS- background color doesn't fill to top of scrolling div

Question: I have a div (sub area of page with scroll bar) that has some text, an image and a table.
The background color defined for the div -

does not fill the area to the top, the top arrow of the scroll bar is above the area filled with the background color (by about the width of one line).  Adding a br at the top fixes it, but moves stuff too far down.
I read two potential solutions.  One suggested I set a fixed height for the div.  That would require changing the height by trial-and-error every time I changed the content of the page. Next.  The other suggestion said to add this at the end, just before the /div -

but that has no effect.
There are several different pages that get loaded into the scrolling area, using SSI's, and some of those included pages use divs, and some of those are floats and some absolutes.
Thanks for any help.
EDIT
Adding the following, which I didn't realize was needed with the "clear", still doesn't work

Ad
Comment: The example code is full of errors, incompletions, etc. Can you point us to a page?
Comment: Not sure if you just copied this wrong, but there is a typo: ``
Comment: As stated, we need more info here. The suggestion you got was to make sure the DIV clears all floats. However a class all by itself is useless unless you've also declared .clear {clear: both} in your css.
Comment: I fixed the two code typos. I'm not using CSS of the style { }, but rather the declarations are in the  Where would a clear:both go using the syntax form I'm using? Thanks.
Answer: I just wrote this up and it seems to keep the background color no matter how much content you put in it...

a bunch of content goes here

you can, of course, set a height to that but more likely it would be in some div wrapper...
Comment: Adding "overflow:auto" to the div solves the problem. Thanks.
I'm using "background-color" - not "background" - interchangeable?
Comment: Yea, background will let you do all background properties in a single statement. The first piece is the color. Thus, as long as you aren't declaring other background properties, background:#fff will function the same as background-color:#fff


O que é Tabela Associativa?

Question: Bem, vejo alguns exemplos de códigos utilizando tabelas associativas. Porém não sei ao certo o que significa este termo, sua aplicabilidade, o conceito etc...
O que é uma tabela associativa?
Comment: Da uma olhada aqui http://pt.stackoverflow.com/questions/14880/entidade-associativa-entity-framework-update-e-delete
Answer: A cardinalidade N para N leva para o modelo lógico a necessidade de definição de mais um entidade. Chamamos isto de ASSOCIATIVA.
Ou seja isso ocorre em casos onde voce pretende realizar um relacionamento N para N.
De uma olhada http://www.macoratti.net/cbmd1.htm
Answer: A tabela, ou entidade associativa (depende de como o modelo está sendo definido), também chamada de tabela de ligação ou amarração ou ainda agregação, é uma tabela usada para intermediar duas tabelas que se relacionam em ambos os sentidos, geralmente em N : N, mas ao contrário da crença popular. ela pode ser usada para lidar com tabelas de outras cardinalidades.
Pense nela como uma tabela extra com uma lista de referências através de chave estrangeira. Mas ela ocorre dos dois lados ligando duas tabelas em vez de apenas uma.
É muito comum que essas tabelas possuam apenas colunas com referências para uma tabela e a outra, além do identificador de chave primária (ele pode ser evitado usando uma chave composta pelos identificadores das duas tabelas). Mas algumas podem ter alguma informação adicional, eventualmente descrevendo até mesmo indiretamente a motivação da relação.
É possível resolver de outras formas, mas frequentemente terão outros problemas, por exemplo um uso excessivo de colunas com valor nulo e/ou espaço desperdiçado junto com limitação de quanto o N vale.
Ela dá mais flexibilidade, mas complica um pouco por exigir um JOIN extra em grande parte das situações.
Imagem da Wikipedia demonstrando como o mapeamento funciona:

Desta forma você consegue achar os filmes que um ator fez e os atores que estão presentes em um filme. Sem esta tabela teria que usar duas tabelas para listar, o que complicaria muito várias operações, tornando tudo ineficiente, ou colocar a lista do que cada um participa na própria tabela das entidades principais.
Justamente porque é o padrão e tende ser mais fácil fazer tudo sem uma tabela auxiliar muitas pessoas preferem usar NoSQL. O que é um erro, porque é possível fazer o mesmo com SQL, elas só não aprenderam como faz, elas só seguem as receitas de bolo mais comuns que usam tabelas associativas. Mas também é um erro porque isso tem lá sua ineficiência, criando problemas futuros se não tomar muito cuidado para manter os dados sincronizados.
Um exemplo de tabelas também da Wikipedia (se você acha isso difícil, provavelmente programação não é para você):
CREATE TABLE Users (
    UserLogin varchar(50) PRIMARY KEY,
    UserPassword varchar(50) NOT NULL,
    UserName varchar(50) NOT NULL
);

CREATE TABLE Permissions (
    PermissionKey varchar(50) PRIMARY KEY,
    PermissionDescription varchar(500) NOT NULL
);

-- Tabela associativa.
CREATE TABLE UserPermissions (
    UserLogin varchar(50) REFERENCES Users (UserLogin),
    PermissionKey varchar(50) REFERENCES Permissions (PermissionKey),
    PRIMARY KEY (UserLogin, PermissionKey)
);

Coloquei no GitHub para referência futura.
Dei exemplos em outras respostas como essa e essa.

O que é Tabela Associativa?


find if exist element with webdriverjs

Question: We have problems when checked if a element exist in the page
Example
return driver.wait(function() {
                driver.findElement(By.css(".class")).then(function(element){
                                      if(element){
                                        return true;
                                      }
                                    },function(error){
                                        if(error){
                                          return false;
                                        }
                                  });
                }, 2000);

In this function the 2000 seconds timeout never is executed and we obtains timeout from webdriver
Thank you very much :)
Answer: Are you trying to check that an element exists, or wait until the element exists? These are two different things.
Check Element Exists:
driver.isElementPresent(webdriver.By.css('.class')).then(function(present) {
   console.log(present);
});

Wait For An Element To Exist
driver.wait(webdriver.until.elementLocated(webdriver.By.css('.class')), 2000);

Comment: i couldn't find an `isElementPresent` method in the selenium docs. is this answer still valid?

find if exist element with webdriverjs


how to import server app for chai request()?

Question: I want to run tests on my node express server however this application is starting the server like this:
createServer()
.then(server => {
    server.listen(PORT);
    Log.info(`Server started on http://localhost:${PORT}`);
})
.catch(err => {
    Log.error("Startup failure.", { error: err });
    process.exit(1);
});

and I know the chai.request() needs to have a parameter that is pointing toward the server app, how can I export/import this createServer() function and pass it in the request method of the chai object?
Answer: You can use require.main to distinguish between your files being run directly by Node or imported as modules.

When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.

E.g.
server.js:
const express = require('express');

const PORT = 3000;
async function createServer() {
  const app = express();
  app.get('/', (req, res) => {
    res.send('hello world');
  });
  return app;
}

if (require.main === module) {
  createServer()
    .then((server) => {
      server.listen(PORT);
      console.info(`Server started on http://localhost:${PORT}`);
    })
    .catch((err) => {
      console.error('Startup failure.', { error: err });
      process.exit(1);
    });
}

module.exports = { createServer };

When you import the createServer from the server.js file, the if statement block will not execute. Because you want to create the server instance in the test case.
server.test.js:
const { createServer } = require('./server');
const chai = require('chai');
const chaiHTTP = require('chai-http');
const { expect } = require('chai');
chai.use(chaiHTTP);

describe('70284767', () => {
  it('should pass', async () => {
    const server = await createServer();
    chai
      .request(server)
      .get('/')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res.text).to.be.equal('hello world');
      });
  });
});