Explanation of ER model to functional dependencies solution

Question: I am trying to understand solution on one exercise that translates ER model to functional dependencies.

As you can see above, we only have relation names and nothing else besides that, and by solution, they somehow come up to conclusion that
 mother, daughter → father
 father, daughter → mother
 mother, son → father
 father, son → mother
And that moreover we can infer additional f dependencies to represent real world more accurately:
 mother, son → father
 father, son → mother
What I don't understand here is how can we base our translation to functional dependencies by just looking at the relation names, since  I always when I did translation from ER model to relational model, I did it by looking at attribute names. Is it possible that there is something wrong in this exercise, or that the task giver was just trying to make us translation to functional dependencies more closer to me as a student first time looking at it (i.e. by making in more educational)?
Comment: You are correct: a Functional Dependency is expressed in terms of the attributes of a single relation. That diagram doesn't show relations, and doesn't show any attributes. (We might guess at some.) In 'ER Model', the 'R' stands for *Relationship*, not relation. The lines - that is, the Relationships - connecting the Entities usually correspond to Foreign Keys between the relations in a data design. So there's nothing here on which you can "base a translation to functional dependencies". The material seems to have confused 'Relationship' with 'relation'.
Comment: @AntC You misuse "relationship" in an ER context. The R in ER stands for "relationship" as in n-ary association. But ER "relationships" are not participations or FKs, which get called "relationships" by methods & presentations that wrongly claim to be ER or relational but are not. A Chen ER diagram has a box per entity type, a diamond per relationship type & a line per participation. Each ER entity & relationship gets a representing relation. Hence a relation per box & diamond & a FK per line. A FD applies to a relation. So we can say a FD applies to a relationship/association.
Comment: There are many diagramming styles & that includes cardinality labelling styles. Give your textbook name, edition & section for this kind of diagram & how to read labels. In particular apparently this seems to be a Chen ER diagram but we don't know the participation/FK labelling convention you are using. PS Please [use text, not images/links, for text--including tables & ERDs](https://meta.stackoverflow.com/q/285551/3404097). Use images only for what cannot be expressed as text or to augment text. Include a legend/key & explanation with an image. Images cannot be searched for or cut & pasted.
Comment: Your last 2 FDs are already in the preceding list of FDs. Typo?
Comment: This is a great question. I am in the same predicament where **somehow** the book infers information that is not in the diagram itself **out of thin air**. I'm trying to understand if some extra notes are necessary apart from the diagram when modelling the problem.
Comment: @JoeDiNottra But as my answer explains, the question post is obviously wrong that "we only have relation names and nothing else" & it explains how the textbook claim follows from the diagram. (And the question does not give the claims correctly since the allegedly "additional" FDs are given ones.) Although proving or finding such a claim like all proofs/discoveries is in general not mechanical. Re "modelling the problem": It's not clear what you mean by that but by no means does an ERD contain (nor the ER method produce) everything one needs for a complete information modeling & DB design.
Answer: TL;DR

As you can see above, we only have relation names and nothing else besides that

Well, there are some lines, each with a name & a digit or letter.
There isn't anything strange about the assignment. Go to your textbook & find out exactly what every technical term & graphic element means. (In particular you might be confused by the meaning of "relationship" or your cardinality labels.) How the solution arises follows.

The R in ERM (for the Entity-Relationship Model) stands for "relationship" as in an n-ary association. Similarly the R in RM (for the Relational Model) uses "relation" per its connected meanings in mathematics as an n-ary relationship/association & as a set of tuples of values that participate in or satisfy such a relation, that are so related/associated. But these ER & RM "relationships" are not participations or FKs (foreign keys), which get called "relationships" or "relations" by methods & presentations that claim to be ER or relational but are not.
A Chen ER diagram has a box per entity type, a diamond per relationship type & a line per participation. A name on a line gives the attribute in the relationship for that participation. A 1 or N label on a line gives cardinality information for that participation.
Each ER entity & relationship type gets a representing relation. Hence a relation per box & diamond & a FK per line. A FD (functional dependency) applies to a relation. So we can say that a FD applies to a relationship.
Presumably the diagram's relationships/relations are like:
-- man [son] is the son of man [father] & woman [mother]
isSon(son, father, mother)
-- woman [daughter] is the daughter of man [father] & woman [mother]
isDaughter(daughter, father, mother)

There are many styles of information modelling methods & diagrams & cardinality labels. Your diagram seems to be one of the Chen styles of true ER. A cardinality label on a participation by an entity type in a relationship type says how many entities of that type can participate with or share a given instance/subtuple of the other participant types over all situations that can arise. A 1 means exactly one & an N means one or more. An n-ary relationship cardinality is a sequence of n such participation cardinalities, "X:Y:..." or "X to Y to ...".
Notice that such a sequence assumes a certain order of entities/attributes. Notice that for a binary relationship N:1 for one order means 1:N for the reverse order. (hasMother(child, mother) is N:1 when/iff isMother(mother, child) is 1:N.) Notice that every entity/attribute in X:Y:... asserts about "a given" or "one given" subtuple of others. That "one" is not from a cardinality label. It's from the phrase that the label is plugged into. In particular it's not from a 1 in a binary N:1 or 1:N.
From your lines we get:
isSon
    N sons participate with a given father-mother pair
    1 father participates with a given son-mother pair
    1 mother participates with a given son-father pair
isDaughter
    N daughters participate with a given father-mother pair
    1 father participates with a given daughter-mother pair
    1 mother participates with a given daughter-father pair

(Binary X:Y is often sloppily expressed as "X entities have Y of the other & Y entities have X of the other". It is intended to mean "a given 1st appears with Y of the other & a given 2nd appears with X of the other". That phrasing doesn't generalize to n-ary relationships or X:Y:.... (A given nth entity appears with how many of what?) That sloppy expression also intends to mean, using the nth letter with the nth entity, "X of the 1st appear with a given subtuple of the others & Y of the 2nd appear with a given subtuple of the others". Which is the Chen n-ary interpretation for n=2. You might think that we could use X:Y:... to mean "a given 1st appears with X subtuples of others & a given 2nd appears with Y subtuples of others & ...". However, that turns out not to be as useful & it contradicts the normal meaning of binary X:Y by taking it to mean what Y:X normally means.)
This particular form of cardinality constraint happens to tell us something rather directly about some FDs (functional dependencies) that hold & don't hold in the representing relations. Observe lines with 1s & Ns paralleling some FDs that hold & don't hold:
isSon
    {father, mother} → {son} does not hold
    {son, mother} → {father}
    {son, father} → {mother}
isDaughter
    {father, mother} → {daughter} does not hold
    {daughter, mother} → {father}
    {daughter, father} → {mother}

What we can determine about FDs per "the real world" depends on what we consider that to encompass & what exactly each relationship's/relation's meaning is--its tuple membership condition/criterion--its (characteristic) predicate. Constraints--including FKs & FDs--are determined by the predicates & the situations/states that can arise. In turn that depends on the meanings of words used in the specification including those expressing the predicates & business rules.
If the predicates above involve biological sons & daughters then we can reasonably expect the given cardinalities & also expect that {son} → {father, mother} & {daughter} → {father, mother}. (Note that those FDs imply the above FDs that determine {father} & {mother} & their cardinality labels.)
However for other predicates & business rules (per what expressions express them & what the words in them mean) & notions of "the real world" we might have different FDs. It all depends on what exactly is intended by "father", "mother", "son" & "daughter", or for that matter "man" & "woman", and what associated rules you assume re what situations/states can arise for your application--marriage, divorce, adoption, disinheritance, parenting, death, etc & just what people you are drawing from & when, etc. One really needs to be really clear.
But you don't clearly give the predicates or the business rules. (Or a legend for interpreting your diagram.) So it's hard to say what other non-implied FDs might hold or not hold.
So there isn't anything strange about the assignment.
PS When you are stuck go to your textbook & find out exactly what everything means & ask a question about where you are first stuck understanding or following a specific definition, axiom/assumption, theorem/fact or algorithm/method/process/heuristic. This question is not from being stuck creatively; here you are supposed to mechanically apply a method in your textbook.
PS Relational Schema to ER Diagram /cardinalities difference


Navegar tab input com valores

Question: Primeiramente não é a mesma pergunta que fiz anteriormente, é uma pergunta complementar.
Tenho atualmente o seguinte modelo no JSFiddle que funciona regularmente, você vai pressionando tab e o scroll horizontal vai navegando, trazendo o input que recebeu focus.
Porém, isso não funciona se o input tiver valor. Caso você atribuir um valor para todos os input´ e tentar usar otabele até dafocusmas oscroll` não trás o mesmo, ficando portando "escondido".
Como posso solucionar?
Comment: Vou tentar ver, eu arrumei o outro. Mas não tive tempo de testar todas possíveis falhas e até refiz ele. Vou postar no domingo que tenho mais tempo para auxiliar acaso ocorra problemas.
Comment: possível duplicada de [Navegar scroll horizontal ao pressionar tab](http://pt.stackoverflow.com/questions/69458/navegar-scroll-horizontal-ao-pressionar-tab) . Você poderia apenas mencionar isso na secção de comentários da resposta que lhe ajudou a solucionar o problema, que a resposta seria atualizada com esta opção, em vez de estar a arrastar a mesma pergunta para uma nova questão
Answer: Como o scroll navega apenas em input sem valor, resolvi da seguinte forma:
 $('input').focus(function () {
    var val = "";
    var attr = $(this).attr('placeholder');
    if (typeof attr !== typeof undefined && attr !== false) {
       val = $(this).attr("placeholder")
    } else {
       val = $(this).val();
    }
    $(this).val('');
    $(this).attr("placeholder", val);
 });

  $('.data').blur(function () {
        $('.data').each(function () {
            var attr = $(this).attr('placeholder');
            if ($(this).val() == "") {
                if (typeof attr !== typeof undefined && attr !== false) {
                    $(this).val($(this).attr("placeholder"));
                } else {
                    $(this).val(0);
                }
            } else {
                $(this).attr('placeholder', $(this).val());
            }
        });
});

A lógica é até que simples. No focus atribuo um valor nulo para o input e armazeno o valor antigo em um placeholder.
No blur vejo se houve uma entrada de valor, caso sim, atribuo esse novo valor ao placeholder.
Assim o input estará vazio toda vez que pressionar tab

Navegar tab input com valores


jquery validate plugin can't access label in the success callback

Question: I have a form that i'm trying to use the jquery validate plugin. My problem is that i can't access the label in the success callback. I can get label.attr('for'), but when i try label.attr('id'), or label.html(), i get undefined.
Here's my validate call:

Here's a piece of my html:
    Are you at least 18 years of age?

                     <input id="Age18_yes" type="radio" name="Age" value="Yes"  <?
                         if ($Age18 == "Yes") {
                               print "checked";
                         }
                      ?>/>
                     Yes

                     <input id="Age18_no" type="radio" name="Age" value="No" <?
                         if ($Age18 == "No") {
                                print "checked";
                         } ?>/>
                     No

When i click on one of the radio buttons, this is what appears in the firebug console:the
the label for = Age
the label id = undefined

You can see from the html snippet that the label tag with the "for" attribute of "Age", also has an "id" attribute of "age18"
Comment: Can you provide the link to the jquery validation library ?
Comment: http://docs.jquery.com/Plugins/Validation. I'm on an older version, but i tried updating to the latest version and it didn't help.
Comment: Can you show some working example where we can see this problem in action?
Answer: The label parameter passed to the success callback is not the label you think it is. The jQuery Validation plugin generates error labels for each element to display error messages. It is this generated label that is passed to the success callback. You can see this by adding console.log(label); as the first line of the callback. It will return the following:
[]

FYI, that label is created in the showLabel method of the validator. It is also the same element that is passed as the error parameter of the errorPlacement method. Generally, the error element would be appended to the form element that caused the error (i.e., failed to validate).
To access the original label from the success callback, you will need a more direct approach.
One solution, and very specific to this particular label, is to simply access it by it's ID, e.g.
if(label.attr('for') === 'Age') {
    $('#age18')...    // do something to the label
}

A more generic solution would be:
$('#personal_info').children('[for="' + label.attr('for') + '"]')...  // do something to label

I have included both solutions in the live demo linked below.
Live Demo
Comment: Thanks for your help on this. I used the specific solution that you posted.
Answer: This is the way I did it. To be able to place a custom image next to the input box and to remove it and to change border colors of the input box.

    <meta charset="utf-8">
    <title>error handling</title>
    <link rel="stylesheet" media="screen" href="css/screen.css">

<form id="someForm" action="#">

Register

Blah

Parameter
*

<input name="param1" id="param1" type="text" />

OID
*

<input name="param2" id="param2" type="text" />

</form>


Data Binding to the contents of a list

Question: I am trying to bind the properties of the items in a list to a data grid. I have the following code:
  <DataGrid Grid.Column="0" Name="LeftSettingsDataGrid" ItemsSource="{Binding Path=Data}">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Setting Name" Binding="{Binding Path=Settings.SettingName}" />
      <DataGridTextColumn Header="Setting Type" Binding="{Binding Path=Settings.SettingType}" />
    </DataGrid.Columns>
  </DataGrid>

But this produces an empty grid view.
Data is an object that has a list of Settings, which are objects that have two public properties: SettingName and SettingType.
Basically, the hierarchy is like this:
 1. Data
   1. Settings
     1. SettingName
     2. SettingType
The data  context is set in the main window's constructor, with LeftSettingsDataGrid.DataContext = Data;.
Why is the binding not working then?
Comment: Path=Data replace it by Path=Data.Settings and Path=Settings.SettingName by Path=SettingName and Path=Settings.SettingType by Path=SettingType
Answer: See this as a tree in your datacontext you have a list that you display as many items, your item source is Settings, your display member is item.SettingName etc
  <DataGrid Grid.Column="0" Name="LeftSettingsDataGrid" ItemsSource="{Binding Path=Settings}">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Setting Name" Binding="{Binding Path=SettingName}" />
      <DataGridTextColumn Header="Setting Type" Binding="{Binding Path=SettingType}" />
    </DataGrid.Columns>
  </DataGrid>

your ItemsSource is Data.Settings not Data
Comment: this is not the only way
Comment: of course, there are many ways to achive everything, but this is the way with the less code change in current example

Data Binding to the contents of a list


Transforming a permutation into a rotation

Question: Let $n\geq 3$ and $G=C_{n}=\{1,r,...,r^{n-1}\}$ be the cyclic group of $n$ elements where $r$ is the rotation of $360/n$ degrees.
Here, let us consider a vector $x\in\mathbb{R}^{n}$ as consisting of components as indexed by the group:
$x=(x_{g})_{g\in G}$. Then $G$ is acting on $\mathbb{R}^{n}$ by permutation: $h.x=h.(x_{g})_{g\in G}=(x_{gh^{-1}})_{g\in G}$.
On the other hand, $G=C_{n}$ acts on $\mathbb{R}^{2}$ directly by $g.x=g(x)$ where $g=r^{s}$ is given as a rotation by $s\cdot 360/n$ degrees.
My question is: Can we construct a map $R:\mathbb{R}^{n}\to\mathbb{R}^{2}$ such that this map is $G$-equivariant w.r.t. that action:
$R(g.x)=g.R(x), \quad \forall g\in G, x\in \mathbb{R}^{n}$
For $C_{4}$, such a map is given by $R:\mathbb{R}^{4}\to\mathbb{R}^{2}, x=(x_{1},...x_{4})\mapsto (x_{1}-x_{3},x_{2}-x_{4})^{T}$.
I struggle to find a general form and simply do not know whether it exists at all.
Moreover, I asked myself what if we consider the same scenario as above where replace $C_{n}$ with $D_{2n}$, i.e. the dihedral group of $2n$ elements.
Comment: You want some conditions on $R$; otherwise, the zero map works.
Comment: Thanks for the comment, yes, I want R to be non-zero.
Answer: Partial answer, too long for a comment.
For the cyclic group, if we let $g$ be the generator, note that it is acting as a linear transformation on both $\mathbb{R}^n$ and $\mathbb{R}^2$. If we let $T$ denote the linear transformation determined by $g$ on $\mathbb{R}^n$ and $U$ the rotation in $\mathbb{R}^2$, you are looking for a linear transformation $R$ such that
$RT = UR$. This will suffice, because the action of $g^k$ is given by $T^k$ and by $U^k$. For positive integers, we have inductively that
$$RT^{k+1}  = (RT)(T^k) = (UR)T^{k} = U(RT^k) = U(U^kR) = U^{k+1}R$$
so that we get $R(g^k\mathbf{v}) =g^kR(\mathbf{v})$ for all positive $k$; and since $g^{-1}$ acts like $g^{n-1}$, this proves the result will work for all integers $k$.
We know the matrix representations for $T$ and $U$:
$$T=\left(\begin{array}{cccc}
0 & 0 & \cdots & 1\\
1 & 0 & \cdots & 0\\
0 & 1 & \cdots & 0\\
\vdots & \vdots & \ddots & \vdots\\
1 & 0 & \cdots & 0\end{array}\right),\qquad U = \left(\begin{array}{cc}
\cos(\frac{2\pi}{n}) & -\sin(\frac{2\pi}{n})\\
\sin(\frac{2\pi}{n}) & \cos(\frac{2\pi}{n})
\end{array}\right).$$
If we let the matrix representation of $R$ be
$$R = \left(\begin{array}{cccc}
a_{11} & a_{12} & \cdots & a_{1n}\\
a_{21} & a_{22} & \cdots & a_{2n}
\end{array}\right)$$
and do the the products, and letting $\theta=\frac{2\pi}{n}$, you get
$$\left(\begin{array}{ccccc}
a_{12} & a_{13} & \cdots & a_{1n} & a_{11}\\
a_{22} & a_{23} & \cdots & a_{2n} & a_{21}\end{array}\right)\\
 = \left(\begin{array}{ccc}
a_{11}\cos\theta - a_{21}\sin\theta & \cdots & a_{1n}\cos\theta - a_{2n}\sin\theta\\
a_{11}\sin\theta + a_{21}\cos\theta & \cdots & a_{1n}\sin\theta + a_{2n}\cos\theta
\end{array}\right).$$
Which gives you a system of $2n$ linear equations in $2n$ unknowns.
For $n=4$, you have $U = \left(\begin{array}{cr}0&-1\\1&0\end{array}\right)$, which simplifies the system to
$$\begin{align*}
a_{12} &= -a_{21}\\
a_{13} &= -a_{22}\\
a_{14} &= -a_{23}\\
a_{11} &= -a_{24}\\
a_{22} &= a_{11}\\
a_{23} &= a_{12}\\
a_{24} &= a_{13}\\
a_{21} &= a_{14},
\end{align*}$$
which gives you a matrix of the form
$$\left(\begin{array}{rrrr}
a & -b & -a & b\\
b & a & -b & -a
\end{array}\right),\qquad a,b\in\mathbb{R}.$$
Your solution takes $a=1$, $b=0$, but it's not the only one (or even the only nonzero one).
This approach would give you a family of possibilities for $D_{2n}$, and then you would need to look at what the reflection does and use that to see if any of the solutions you have gives you a (nonzero) solution.
Comment: Thanks for sharing this! Thinking about this solution, I was not sure how we know that the linear equation system actually has a solution (in fact, it is given by the kernel of a matrix A with 2n columns and 2n rows). However, I implemented it and found numerically that non-zero solutions in fact exist up to n>250. What I was originally searching for is a better interpretable map but that seems to be more involved.


read specified range of lines from a file

Question: I have i file that contains 100000 line
how i can get the lines from line# 5555 to line# 7777 under linux.
Thanks for all.
Comment: @ibrahim, consider accepting Kyle's answer (by ticking the green checkmark on the left) if it helped you
Comment: A little bit of research throws at least http://stackoverflow.com/questions/83329/how-can-i-extract-a-range-of-lines-from-a-text-file-on-unix
Comment: you may precise if you want to use sed or if other tools are OK.
Answer: sed '5555,7777!d' <filename>

This will print lines 5555-7777 of the file inclusively.
Dennis Posted the following which I agree should be faster:
sed '5555,7777p; 7778q' filename
The following evidence that it should be faster:
$ n=1
$ while [[ n -le 100000 ]]; do echo $n >> sedtest2; n=$((n + 1)); done
$ strace -e trace=read -o sed1 sed '5555,7777!d' sedtest2
$ strace -e trace=read -o sed2 sed '5555,7777p; 7778q' sedtest2
$ wc -l sed1
149 sed1
$ wc -l sed2
14 sed1

In Bash only (for fun):
n=1
while read line; do
    if [[ ($n -ge 5555) && ($n -le 7777)  ]]; then
        echo $line
    elif [[ $n -gt 7777 ]]; then
        break
    fi
    n=$(( $n + 1 ))
done < file

Comment: I think your `$n -gt 3` should be 7777 perhaps? Also, you can do `if (( n >= 5555 ))` for more "natural" looking numeric comparison operators (and the ability to leave off the dollar sign). And you can do `((n++))`.
Answer: Quitting when you're done can speed things up:
sed -n '5555,7777p; 7778q' input_file

Comment: +1 , should be faster, updated my post to show why.
Answer: Either of these should work;

sed -n 'startnumber,endnumberp'
awk 'NR>=startnumber&&NR<=endnumber' file

Great question by the way ;)
Answer: I found that the sed option did not work on a mysqldump file, I'm guessing due to handling of quoted line feeds or multibyte characters. head and tail slice it using the same line numbers as grep which was what I needed. To get lines $j through $k, you need:
x=$(( $k - $j + 1 ))
tail -n +$j filename | head -${x}


Trocar botão após click em JSF

Question: Fala pessoal estou com o seguinte problema, tenho estes dois botões que fazem:
X : Retira o valor de um grafico
+ : Adiciona o valor de um grafico

Preciso que fique assim: Quando eu clicar no botão X

ele troque para o botão +, pois eles tem funções diferentes como podem notar.

Minha view está assim atualmente:

                    <f:attribute name="projetoSelecionadoNaView" value="#{projeto}" />

                    <f:attribute name="projetoSelecionadoNaView" value="#{projeto}" />

Answer: se entendi bem, você quer que quando o usuário clique em um botão ele desapareça e o outro fique no lugar. Você pode usar o atributo 'rendered do JSF ajunto com uma expressão ou variável booleana que alterne no momento que vocês desejar. Eu peguei mais ou menos o seu código e fiz uma exemplo já dentro de uma tabela:
 <h:form id="novoform">

                <h:outputText value="#{nome}" />

    </h:form>

ManagedBean:
public class TrocaBotaoBean {

private boolean adicionandoValor;

public TrocaBotaoBean() {

}

public void adicionar() {
    this.adicionandoValor = true;
}

public void retirar() {
    this.adicionandoValor = false;
}

public boolean isAdicionandoValor() {
    return adicionandoValor;
}

public List<String> getListaTeste() {
    List<String> nomes = new ArrayList<>();
    nomes.add("ZEUS");
    nomes.add("THOR");
    nomes.add("RÁ");
    return nomes;
}
}

Espero ter ajudado.
Comment: Tá mas por exemplo: Se eu adicionar um valor ali vai sumir o outro botão só daquela linha ? acho que ele vai sumir todos os botões de todas as linahs...não acha ?
Comment: sim, se vc quer fazer isso individualmente, vc precisará de um pouco mais de código, por exemplo, ajustar o datable, o selection, selection mode, rowKey, alem disso, precisará usar um  <p:ajax que vai capturar a linha com evento 'rowSelect'. esses botões, não precisarão se repetir, basta joga-los no footer ou header ja q eles alterar somente o q foi selecionado. Acredito q seja dessa forma.

Trocar botão após click em JSF


Angular2 cannot find router_providers, locationstrategy in @angular/router

Question: I user angular2 router and got problem with directly path.
If i write localhost:3000/container
Page will not be found. I knew if i include ROUTER_PROVIDERS it will be works. But i have not ROUTER_PROVIDERS and locationstrategy
Look at my screens
root.module.ts

package.json
Comment: Can you please add at least some of your code. And what do you mean with "But i have not ROUTER_PROVIDERS and locationstrategy"?
Comment: By your question, I have perhaps found a solution. Thank you!
Comment: ok, it was not the solution for my problem, but I find your question, though quite justified!
Answer: ROUTER_DIRECTIVES and ROUTER_PROVIDERS were removed when the old @angular/router-deprecated package was removed, so you can just remove these from your import line in the module.
As for the HashLocationStrategy and LocationStrategy, these are part of the @angular/common module so you will need to do the following:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';

However, if you are wanting to enable the hash location strategy the latest recommended way to do this is to simply put the following with the routes initialisation:
imports: [
    ...,
    RouterModule.forRoot(rootRoutes, { useHash: true })
]


C# 11 required member false positive

Question: The code below can not compile and reports a CS9035 error. Required member 'A.FieldA' must be set in the object initializer or attribute constructor.
This seems like a false positive. The required field is set. Is there any way to work around this? I don't want the users of record B to set the field.
public record A
{
    public A(string value)
    {
        FieldA = value;
    }
    required public string FieldA { get; init; }
}
public record B() : A("field a");

public static class Test
{
    public static void test()
    {
        var b = new B(); //Error    CS9035  Required member 'A.FieldA' must be set in the object initializer or attribute constructor.
        //var b = new B()  { FieldA = "field a" };
    }
}

Answer: Let's take a look at the documentation:

The required modifier indicates that the field or property it's applied to must be initialized by an object initializer.

So it's only for object initializers. What you do in your constructors does not matter. But then, if you're initializing it in the constructor, you probably want a read only property, not an init only one.
If you want to do it that way, you'll have to set the SetsRequiredMembers attribute to your constructor, but the documentation warns against that:

The SetsRequiredMembers disables the compiler's checks that all required members are initialized when an object is created. Use it with caution.
Comment: If it helps, you can read on the [motivation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-11.0/required-members#motivation) behind the feature. In short, it's intended as a _replacement_ for constructor positional arguments. You're not supposed to be using both at the same time.
Comment: Maybe my expectation for the required keyword is too high. Why distinguish between constructor and initializer?  I was hoping that as long as a field is initiated, it should satisfy the required keyword.
Answer: You can do this if you add SetsRequiredMembers to both A and B's constructors.
[SetsRequiredMembers]
public A(string value)
{
    FieldA = value;
}

[method: SetsRequiredMembers]
public record B() : A("field a");

Note that no checks are performed to make sure that you actually set all required members in the constructors. The compiler just trusts you.
Also, it is not possible to just want some required properties to be set in the constructor. See also this question, and this discussion about adding ways to say "this constructor only initialises the required members X, Y and Z".
The main argument against this is:

Our theory is that most people using init methods and constructor parameters aren't going to be using required members in the first place. I'm not particularly convinced that there will be a large number of users with required members that also want to have multiple constructors that set subsets of their members, much less a large number of users with enough of these constructors that they want to factor them into helper methods.
Answer: This is because the requirement is different to "it has to be set":
In the Required Members feature specification we can read:

All constructors in a type with required members, or whose base type specifies required members, must have those members set by a consumer when that constructor is called.
(emphasis mine)

The spec then follows to describe SetsRequiredMembersAttribute which removes the requirement.
Here's a setup that eliminates CS9035:
[method: SetsRequiredMembers]
public record A(string fieldA)
{
    required public string FieldA { get; init; } = fieldA;
}

[method: SetsRequiredMembers]
public record B(): A(fieldA: "field a");

(or)
public record A
{
    [SetsRequiredMembers]
    public A(string fieldA)
    {
        FieldA = fieldA;
    }
    required public string FieldA { get; init; }
}

C# 11 required member false positive


How to make Panel Page variant selection rules detect URL parameter?

Question: On D7 I have set up a new panel page variant and want to use it with a certain selection rule:
 String: URL path   Current path is "*/cars/*?buy"

Eg I want this panel variant to be used if the URL is new/cars/honda?buy.
However the above doesn't work. Adding ?buy to the url doesnt trigger it to be used.
Would anyone know a way to set selection rule so that I can use this page variant with a give parameter in the URL?
Answer: I found the Selection Rule Query string exists does this.
Comment: Did you mean that you want to 'show' (instead of 'use') a panel page when that string exists in the url, correct? If so, would you mind elaborating how you do this I need this too.


Como identificar um erro http (500) através do selenium web driver ou javascript

Question: Preciso montar um script que varra determinadas páginas e localize erros http, específico o 500. Pensei em fazer um script selenium, porém não sei um comando que eu consiga "ler" esse tipo de erro. Alguém sabe me dizer se o selenium tem algum comando para isso, ou javascript?
Comment: Qual linguagem você está usando para programar o Selenium?
Comment: Estou utilizando Python
Answer:
Alguém sabe me dizer se o selenium tem algum comando para isso, ou javascript?

O Selenium em si, não. O que você pode fazer é disparar uma requisição usando uma sessão compartilhada e recolher o status de erro.
O pacote que sei que faz isso é o selenium-requests. Um exemplo:
from seleniumrequests import *

browser = Firefox();
# Faça algumas ações aqui, como autenticar login, se for o caso.
retorno_requisicao = browser.request('GET', "http://sitequalquer.com")
if retorno_requisicao.status_code >= 500:
    # Trate os erros aqui.


How to avoid no-wrapper tags on regions?

Question: How do I make sure ALL regions are wrapped according region.tpl.php?
In a subtheme of Zen I have created my own regions and modified the page.tpl.php file to something like the following:

    <?php print render($page['header']); ?>
    <?php print render($page['content']); ?>
    <?php print render($page['footer']); ?>

Some of the regions get a region wrapper from region.tpl.php, others get the code from no-wrapper.tpl.php (no wrapper). How can have all regions receive a wrapper?
Answer: From the code it looks like Zen adds that template suggestion in zen_preprocess_region(), but only to the content region:
elseif ($variables['region'] == 'content') {
  // Allow a region-specific template to override Zen's region--no-wrapper.
  array_unshift($variables['theme_hook_suggestions'], 'region__no_wrapper');
}

If you're editing the Zen theme directly (which you shouldn't be :P) just remove those 4 lines; if you're creating a sub-theme, implement your own region preprocess function, copy the code from Zen's, and leave those lines out:
function MYTHEME_preprocess_region(&$variables, $hook) {
  // Sidebar regions get some extra classes and a common template suggestion.
  if (strpos($variables['region'], 'sidebar_') === 0) {
    $variables['classes_array'][] = 'column';
    $variables['classes_array'][] = 'sidebar';
    // Allow a region-specific template to override Zen's region--sidebar.
    array_unshift($variables['theme_hook_suggestions'], 'region__sidebar');
  }
}

Comment: Thank you Clive, but the content region is still receiving the wrapper code from no-wrapper.tpl.php.
Comment: Did you clear Drupal's caches since making the change?
Answer: To avoid region-content blocks from receiving the block--no-wrapper.tpl.php template, go to template.php in your sub-theme and unquote or add the final function:
function zen_expeditiedokter_preprocess_block(&$variables, $hook) {
    if ($variables['block_html_id'] == 'block-system-main') {
        $variables['theme_hook_suggestions'] = array_diff($variables['theme_hook_suggestions'], array('block__no_wrapper'));
    }
}

This will give the block.tpl.php template to the content region (without editing the Zen main theme) and thus avoiding the no-wrapper.


Find this Limit (Fourier series)

Question: Find the following limit:
$$\large\lim_{n\to\infty} \int_{-\pi}^\pi \biggl(x + \frac{\pi}{2}\biggr)^2 \frac{\sin\bigl(\bigl(n+\frac{1}{2}\bigr)x\bigr) + x \cos nx}{\sin \frac{x}{2}}\,dx.$$
We tried to use what we know about the Dirichlet kernel and the real version of the Riemann-Lebesgue lemma but we're stuck.
Thanks
Comment: Angle addition formula?
Comment: Split the fraction. For the one part, the Riemann Lebesgue lemma applies directly, for the other part, you have the Dirichlet kernel in it.
Comment: We tried it but don't you need $f(x)$ to be 2π periodic to use the Riemann-Lebesgue lemma?
Answer: The version of the Riemann-Lebesgue lemma we need here says that for an integrable function $f\colon [a,b] \to \mathbb{R}$, we have
$$\lim_{c\to \infty} \int_a^b f(x)\operatorname{trig}(cx)\,dx = 0,$$
where $\operatorname{trig}$ can be either of $\sin$ or $\cos$. It can be proved in many ways; we can extend the function trivially (setting $f(x) = 0$ for $x\notin [a,b]$) to $\mathbb{R}$ and appeal to the $L^1(\mathbb{R})$ version, or we can first show it for continuously differentiable $f$ by integration by parts, and then use that every integrable function can be approximated (in the integral sense) by continuously differentiable functions to obtain the result for all integrable functions on $[a,b]$.
Hence by the Riemann-Lebesgue lemma we have
$$\lim_{n\to\infty} \int_{-\pi}^\pi \biggl(x+\frac{\pi}{2}\biggr)^2 \frac{x}{\sin \frac{x}{2}}\cos nx\,dx = 0,$$
since $\bigl(x+\frac{\pi}{2}\bigr)^2\cdot\frac{x}{\sin (x/2)}$ is integrable on $[-\pi,\pi]$ - it is even continuously differentiable.
That leaves us to consider the part
$$\int_{-\pi}^\pi \biggl(x+\frac{\pi}{2}\biggr)^2\cdot \frac{\sin \bigl(\bigl(n+\frac{1}{2}\bigr)x\bigr)}{\sin \frac{x}{2}}\,dx.\tag{1}$$
The second factor in that is the Dirichlet kernel $D_n$. Now let us define
$$f(x) = \biggl(\frac{\pi}{2} - x\biggr)^2$$
for $x \in [-\pi,\pi)$, and extend that $2\pi$-periodically to $\mathbb{R}$. Then $f$ is a piecewise continuous and piecewise continuously differentiable function which is continuously differentiable on $\mathbb{R}\setminus (\pi + 2\pi\mathbb{Z})$. It has jump discontinuities at odd integer multiples of $\pi$. The general Fourier theory tells us that hence
$$f(t) = \lim_{n\to\infty} \frac{1}{2\pi} \int_{-\pi}^\pi f(t-x)D_n(x)\,dx\tag{2}$$
for all $t\in \mathbb{R}\setminus (\pi + 2\pi\mathbb{Z})$. But the integral in $(1)$ is just
$$\int_{-\pi}^\pi f(0-x)D_n(x)\,dx,$$
so by $(2)$ we have
$$\lim_{n\to\infty} \int_{-\pi}^\pi \biggl(x+\frac{\pi}{2}\biggr)^2\cdot \frac{\sin \bigl(\bigl(n+\frac{1}{2}\bigr)x\bigr)}{\sin \frac{x}{2}}\,dx = 2\pi\cdot f(0) = 2\pi\biggl(\frac{\pi}{2}-0\biggr)^2 = \frac{\pi^3}{2}.$$

Find this Limit (Fourier series)


cannot create div content dynamically

Question: What is wrong here?

var str = "

lorem

ipsum

";

$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}

.lorem{
cursor:cell;
background:gold;
}

.ipsum{
cursor:cell;
background:lightgreen;
}

Error:
Uncaught SyntaxError: Invalid or unexpected token...
lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
Comment: Your str variable is wrong. After each line close quotes and add + or use `` instead of ""
Comment: Possible duplicate of [Creating multiline strings in JavaScript](https://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript)
Answer: You can't have line breaks in strings unless you use a template literal.
var str = "

lorem

ipsum

";

should be
const str = `

lorem

ipsum

`;

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
In the case that you don't want to use this (I don't know why you wouldn't), you could also do these:
var str = "
lorem
" + "
" + "
ipsum
";

var str = ["
lorem
", "
ipsum
".join("
");

var str = `

lorem

ipsum

`;

$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}

.lorem{
cursor:cell;
background:gold;
}

.ipsum{
cursor:cell;
background:lightgreen;
}

Answer: Since your string is in multi-line, either you have to use string concatenation (+) or use Template literals:
Using Template Literals:

var str = `

lorem

ipsum

`;

$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}

.lorem{
cursor:cell;
background:gold;
}

.ipsum{
cursor:cell;
background:lightgreen;
}

Using String Concatenation (+):

var str = ""+
"
lorem
"+
"
"+
"
ipsum
"+
"";

$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}

.lorem{
cursor:cell;
background:gold;
}

.ipsum{
cursor:cell;
background:lightgreen;
}

Answer:

var str = '
lorem

ipsum
';
$('.parent').html(str);
.parent{
width:50%;
margin:14px auto;
background:#eee;
}

.lorem{
cursor:cell;
background:gold;
}

.ipsum{
cursor:cell;
background:lightgreen;
}

cannot create div content dynamically


$\lim_{n\to \infty} {1\over n}\sqrt[n]{(n+1)(n+2)\cdots(2n)}$

Question: $$\lim_{n\to \infty} {1\over n}\sqrt[n]{(n+1)(n+2)\cdots(2n)}$$
My attempt:
\begin{align}
\lim_{n\to \infty} {1/ n}\sqrt[n]{(n+1)(n+2)\cdots(2n)} &= \lim_{n\to \infty} \sqrt[n]{(1+{1/ n})(1+{2/ n})\cdots(1+{n/ n})}\\
 &= \lim_{n\to \infty}(1+{1/ n})^{n*{1/ n^2}}(1+{2/ n})^{n*{1/ n^2}}\cdots(1+{n/ n})^{n*{1/ n^2}}\\
 &=\lim_{n\to \infty}e^{{1/ n^2}}e^{{2/ n^2}}\cdots e^{{n/ n^2}}\\
  &= \sqrt{e}
\end{align}
I know that this is wrong answer. Could you please show me where my mistake is?
EDIT  I know the right solution, I just wanted to see where my mistake is. Thanks for your answers anyway!
EDIT 2 5 beautiful answers received already, but I dont think I can accept any of them, because my question was to show mistake in my own derivations. Anyway I learnt a lot especially that $\lim_{n\to \infty} \frac{b_{n+1}}{b_n}=\lim_{n\to \infty} \sqrt[n]b_n$. Thanks for everyone!
Comment: You're limiting with respect to $n$ only partway in one of your steps (making things into $e$'s, but keeping $n$ in exponents). That's not correct.
Comment: Thanks Arthur, now I see
Comment: I have tried to improve the readability of your question by introducing
[$\rm \LaTeX$](https://math.meta.stackexchange.com/a/5057/290189). It is
possible that I unintentionally changed the meaning of your question.
Please proofread the question to ensure this has not happened.
Comment: Its fine. Thanks!
Comment: @MarkoffChainz If you are ok, you can accept the answer and set as solved. Thanks!
Answer: $$\lim_{n\rightarrow+\infty}\ln{a_n}=\lim_{n\rightarrow+\infty}\sum_{k=1}^n\frac{1}{n}\ln\left(1+\frac{k}{n}\right)=\int\limits_{0}^1\ln(1+x)dx=$$
$$=\left((1+x)\ln(1+x)-x\right)_0^1=2\ln2-1,$$
which gives $\frac{4}{e}.$
Answer: Try using logarithms.
I.e. $$\ln ( \rm A)= \lim_{n \to \infty} \sum_{r=1}^{n} \frac 1n\ln \left( 1+\frac rn \right) =\int_0^1 \ln(1+x) \rm dx=\ln(4)-1$$
Implying $$A=e^{\ln(4)-1}=\frac 4e$$
Answer: (Other way )
Using $\lim \frac{|x_{n+1}|}{|x_n|}=L$ so $\lim \sqrt[n]{|x_n|}=L .$
take $x_n=\frac{(2n)!}{n!n^n}$, so $\frac{x_{n+1}}{x_n}=\frac{2(2n+1)}{n+1}\frac{1}{(1+\frac{1}{n})^{n}} \rightarrow \frac{4}{e}.$
Answer: I'm typing this for fun and to practise Stirling's approximation: $n! \sim (n/e)^n \sqrt{2\pi n}$.
\begin{align}
\frac1n \sqrt[n]{\frac{(2n)!}{n!}} &\sim
\frac1n \sqrt[n]{\frac{(2n/e)^{2n} \sqrt{2\pi(2n)}}{(n/e)^{n} \sqrt{2\pi(n)}}} \\
&= \frac1n \sqrt[n]{\frac{2^{2n} n^n \sqrt2}{e^n}} \\
&= \frac1n \frac{2^2n}{e} \sqrt[2n]{2} \\
&= \frac4e \sqrt[2n]{2} \xrightarrow[n\to\infty]{} \frac4e
\end{align}
Answer: Let indicate
$$a_n={1\over n}\sqrt[n]{ (n+1)(n+2)\cdots(2n) }$$
$$b_n=a_n^n=\frac{{(n+1)(n+2)\cdots(2n)}}{n^n}$$
then
$$\frac{b_{n+1}}{b_n}=\frac{{(n+2)(n+3)\cdots(2n+2)}}{(n+1)^{n+1}}\frac{n^n}{(n+1)(n+2)\cdots(2n)}=\left(\frac{n}{1+n}\right)^n\frac{(2n+2)(2n+1)}{(n+1)^2}=\frac{1}{\left(1+\frac1n\right)^n}\frac{(2n+2)(2n+1)}{(n+1)^2}\to \frac4e$$
thus (see also for reference)
$$\lim_{n\to \infty} \frac{b_{n+1}}{b_n}=\lim_{n\to \infty} \sqrt[n]b_n=\lim_{n\to \infty} a_n=\frac4e$$


Add a read more link to product list

Question: I have a view with a grid displaying rendered entity of product list for my product display index. Is it possible to add a read more link to the product list display with a link to the product. I have tried to create this in several different ways, by creating a link in the content type fields, however that would require manual completion. I appreciate that if I was using fields in views I could add the link there. I'm hoping there is a solution to adding to the product list. I have also looked at adding it manually to node.tpl.php, but I am unsure of where to define the variable instead of $teaser. Many Thanks in advance.
Comment: I'm using Commerce Kickstart, so Drupal 7
Answer: Fixed, I added all of the required fields from product list to teaser, then modified the css accordingly.

Add a read more link to product list


Postfix time in queue manager very high

Question: http://screencast.com/t/7Ok2PwDDj
I have been running Postfix 2.6.6 for the last 5 months. There has not been any server changes and the config allowed me to send 150,000 emails per hour with no problems.
Now, things have slowed down and are progressively getting slower since about a week ago.
The snapshot I linked shows my "delays" and you can see that the "Time in Queue Manager" has gone to 3 and 4 seconds which has choked my mail delivery down to about 20,000 mails per hour vs 150,000.
Does something need to be flushed or reset somewhere? I don't understand why, with no changes, that all of a sudden I begin to get these large delays after working beautifully for several months.
Answer: First you need to check your server ip address in DNSSBL for blacklist and check the /var/log/maillog and look at mail status that mail are getting delivered,bounce,differed or sent according to mai status if it is sent than no problem if it is bounce or differed than this may be the reason that your server has been blocked by receiving mail server's to deliver mails on their user's to stop spam sending.
Answer: I'd make sure that your local DNS server is responding correctly (even for your own domains), or it might just be that google is just throttling you.
Comment: DNS lookups are reported in the "connect setup time" according to the release notes, not the "in queue manager" metric - see also https://serverfault.com/questions/24121/understanding-a-postfix-log-file-entry

Postfix time in queue manager very high


How to refer to the name of an object in C#

Question: Is it possible to refer to an object's name in C# to avoid copying useless code like
public static void Main (string[] Args)
{
     Champion aatrox = new Champion("Aatrox");
     Champion ahri   = new Champion("Ahri");
     // and so on ...
}

Been looking for something that looks like
class Champion
{
    public string Name { get; set; }
    public Champion () => Name = nameOf(this);
}

But didn't find any way to do so.
Comment: -- or better yet: `List champions = new List { new Champion(...), new Champion(...) };` -- how should the `Name` be infered here?
Comment: Sorry, but I don't understand what you want to achieve - where do you want to get the name from? nameof(this) would be "Champion" for each champion. You need to define the name at some kind of place, the framework cannot generate names.
Comment: I think I understand what you want - you want the name of the variable to be the name of the champion. Not a good idea, I'll write an answer ;)
Comment: From right to left: `new Champion(...)` creates a new instance, `=` assigns that instance to a variable declared as `Champion aatrox`. A variable "holding" (or referencing) an instance is (for reference types) not the same thing as the instance. What should the value of `Name` be if you say `Champion maseltov = aatrox;`? Also, the variable is `aatrox` (lower case) but the name you give it is `"Aatrox"`(upper case). How should that work?
Answer: If you want to use the variable name inside your object-instance, that is not possible and also not a good idea. You can use an object instance in different places in your code where the variable could be named differently (or not named at all like Corak pointed out), so there is no single name available, making it impossible to create consistent logic out of this.
It also creates a dependency between your program logic and strings presented to the user - this can cause many more issues, e.g. if your name needs to contain spaces, if you want to use lower or upper casing different than your coding conventions, if you want to translate the names into different languages.
So what you want to achieve is not possible for good reasons.
Answer: Everything @CompuFreak said is correct, and you should probably mark his answer as accepted.
But, one thing you can do is this:
Champion Aatrox = new Champion (nameof(Aatrox));

That gives you the minor advantage that if you realize that you spelled Aatrox wrong (say it is supposed to have two "x"-es), you could rename the variable name, and that name would ripple into your code. I used "nameof" all the time, but I'm not sure I'd use it here.
But, as has been pointed out, the main reason you can't do what you describe is that the name you give a variable that references an object you create is not intrinsically known to the object; it's just a name you give to something that references the object (and many things can reference the same object). That reference name is only know in the scope where it's used.
Answer: I'm not sure if this can be done with fields, but it can be done with properties using the CallerMemberNameAttribute:
class Champion {
    public string Name { get; set; }
    public Champion([CallerMemberName] string name = "") {
        Name = name;
    }
}

This will pass the property name to the constructor. The folowing will print the expected names "Aatrox" and "Ahri":
class Program {
    static Champion Aatrox { get; set; } = new Champion();
    static Champion Ahri { get; set; } = new Champion();

    static void Main(string[] args) {
        Console.WriteLine(Aatrox.Name);
        Console.WriteLine(Ahri.Name);
        Console.ReadLine();
    }
}

If you are creating instances of the class in places you don't want to use properties you can wrap it in a class:
class ChampionContainer {
    public Champion Aatrox { get; set; } = new Champion();
    public Champion Ahri { get; set; } = new Champion();
}

And use it like this
static void Main(string[] args) {
        ChampionContainer champions = new ChampionContainer();
        Console.WriteLine(champions.Aatrox.Name);
        Console.WriteLine(champions.Ahri.Name);
        Console.ReadLine();
    }


How to append options and classes into a custom attribute in Twig?

Question: In our twig template we have a need to wrap certain fields with a Link field. In the existing twig template there already exist an attributes variable (accessed by adding attributes), but we have a need to have a custom one. Couldn't find any documentation on if you can pass options and attributes from one field to a custom twig attribute.
Is there a way to append all options and classes from a field's attributes into a custom attribute in a Twig template without any hook_preproceess_hook?
Existing node--article.html.twig

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

  {{ content.field_link }} /* has its own options and attributes */

Desired output
/* pass the options and attributes from field_link into the a_attr */
/* This did not result in what we wanted */
{% set a_attr = create_attribute(content.field_link.0['#attributes']) %}

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

 {{ content.field_link.0['#title'] }}

Comment: Did you see this section about `setAttribute`? https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
Answer: According to the syntax your declaration is a little off. The function is also create_attribute, not create_attributes.
The {{ attributes }} variable in a node twig template won't hold what you think it holds for the link tag. So, you will need to create a new one.
https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
You probably want something like this:
{% set link_attributes = create_attribute() %}
{% set link_href = content.field_link.0['#url'] %}
{% set link_title = content.field_link.0['#title'] %}

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

 {{ content.field_link.0['#title'] }}

Unfortunately, since you are wrapping fields with the value of a link field, this might be more manual than you would prefer. This is because Drupal is not rendering the field, you are creating html on the fly - link fields in particular are tricky because there is often the case of wrapping data with an anchor in say, a card display format or a clickable CTA. I am not sure if anyone has found better methods of achieving this.
I wonder if anyone has written an extension that will in fact let you render a link field but intake other fields in a tag like you mentioned in another question, so you could wrap them.


How to display media metadata infomation in the Media Switch output?

Question: I developed a media app with reference to UAMP, but I encountered the following problems.
The media switch output screen opened from the notification cannot display the media information being played.
But there is UAMP, not sure what I missed? Does anyone know the reason? Thank you
Answer: I found the reason myself.
Because I didn't set MediaSession to active correctly.


Why does this matrix have norm smaller than 1?

Question: Let $J_k$ be the $(k\times k)$-matrix
$$
J_k=\begin{pmatrix}
0 & & & & & 0\\
1 & 0 & & & & 0\\
 & 1 & 0 & & & &\\
 &   & \ddots & \ddots & &  &\\
 & & & \ddots &\ddots & \\
0 & & & &  1 & 0
\end{pmatrix}
$$
I guess this is a rather silly question, but it is said that
$$
\lVert J_k\rVert <1.
$$
I do not see that resp. do not know which norm is meant.
Comment: No, e.g. $\|J_k\|_{\infty}=\|J_k\|_{1}=1$.
Comment: When it is not specified, the $2-$norm is often, _though not necessarily_, meant. So that question can't be answered.
Answer: I hope you don't mind I rename your matrix $A$, for notational laziness. :)
$$||A||=\max_{||x||=1}{||Ax||}$$
Now, for $x=\left(\begin{array}{c}x_1\\\vdots\\ x_k\end{array}\right)$, we have:
$$Ax=\left(\begin{array}{c}0\\x_2\\\vdots\\ x_k\end{array}\right),$$
Now comparing $||Ax||$ and $||x||$, or
$$||\left(\begin{array}{c}0\\x_2\\\vdots\\ x_k\end{array}\right)||\ \mbox{ and }\ ||\left(\begin{array}{c}x_1\\\vdots\\ x_k\end{array}\right)||,$$
it follows that $||Ax||\leq||x||$, such that
$$||A||=\max_{||x||=1}{||Ax||}\leq\max_{||x||=1}{||x||}=1.$$
Note that whitout specifying which norm $||\cdot||$ is, we cannot arrive at $||A||<1$, but only at $||A||\leq1$, for example $||A||_1=1$.
Comment: Which norm is it? And since all norms are equivalent and, as Stef wrote, another norm is 1 - how does this fit together?
Comment: I cannot tell you which norm it is. The question should state that...


Gramian matrix of vector linearly independent vectors

Question: $M\in \mathbb{R}^{n,n}$ is Gramian matrix of some system of linearly independent vectors $x_1,...,x_n$ in euclidian space $\mathbb{R}^n$. Then:
a. if $M=I_n$ then $x_1,...,x_n$ is orthonormal.
b. if $x_1,...,x_n$ is orthogonal then $M$ is diagonal.
c. $M$ is nonsingular.
c. it is true, it is equivalent to linearly independent vectors (columns)
a. It is true - it is fairly obvious.
b. it if false,  look
$([1,1], [-1,1])$ is  linearly independent
$\langle [1,1], [-1,1]\rangle = 1\cdot (-1) + 1 \cdot 1 = 0 $  are orthogonal.
$
M=
  \begin{bmatrix}
    1 & -1 \\
    1 & 1
  \end{bmatrix}
$ is not diagonal.
Could you check my solution ?
Answer: Remark: I used $v_i$ instead of $x_i$.
Note that the entry of the Gramian matrix are given by
$$a_{ij}=\langle v_i,v_j\rangle,$$
so if you choose the vectors $v_1=(1,1), v_2=(1,-1)$ the entries are
$$a_{11}=\langle v_1,v_1\rangle=1^2+1^2=2,\\\  a_{12}=\langle v_1,v_2\rangle=1\cdot 1+1\cdot(-1)=0=a_{21}\\ a_{22}=\langle v_2,v_2\rangle=(-1)^2+(-1)^2=2.$$
So your calculation is incorrect.
I presume that the error in you interpretation is the following: $v_i$ refers to the $i$-th vector and not to the $i$-th component of the vector.
So returning to your original problem $b)$, it clear that if the $v_i$'s are pairwise orthogonal, then by the very definition of orthogonality $\langle v_i,v_j\rangle=0$ for $i\neq j$, which is the result claimed.
$a)$ is true
$c)$ you also need to reinterpret using the correct definition given above. So you need to provide a correct proof. But as https://en.wikipedia.org/wiki/Gramian_matrix suggests, it is indeed true.
Comment: what about a. and c.
Comment: c. is true due to following theorem:  $v_1,...,v_n$ is linearly independent if only and only Gramian matrix for $v_1,..,v_n$ is nonsingular. Yeah ?


Reboot VPS by reaching memory limit

Question: When a server uses memory more than available RAM, the system will shut down the virtual machine. Then, it is only possible to boot from outside (VPS control panel, e.g. vePortal or SolusVM). However, it should be possible to plan a reboot before possible shut down.
What is the best practical method to check the used memory, and reboot the system upon reaching e.g. 90% of the allowed RAM? Is there a common program or script to do so? I am using Debian/Ubuntu.
Comment: Who is this provider that shuts it down instead of rebooting?  Seems a bit of an odd way to handle the problem.
Comment: @Grant Most of budget VPS providers :-) they wish to find excuse to reduce overload on oversold servers.
Comment: No virtual memory and no caching?  It's a bit odd to defeat what Linux sets out to do by utilising all available memory.
Answer: Nagios could do it, but Monit is pretty much designed for exactly this problem and can be configured to restart services or the whole machine in low memory situations.
I use it on several servers to check for run away processes using excessive memory and restart them.  I find it a lot easier to configure than nagios actions.
It's also useful for checking if services have failed and restarting them.
The relevant part of monitrc would look like:
<code>check system myserver
  if memory usage > 90% then restart
</code>
Nice and simple :)
Answer: Instead of cutting the branches, you should cut the root of problem. Try to analyze that which process or activity eats up all the RAM. and fix that activity, instead of rebooting server everything when RAM files up 90%. you can use nagis for this purpose, that if RAM gets 90% fill, call an Event handler which will shutdown or reboots the server.
Comment: It is not a routine problem, it is rare overload or even attack or even unpredictable problem (which can be solved by reboot). It cannot be bad to make sure that the server will always go back online upon any failure.
Comment: Nagios server with Events handlers is the best solution
Answer: This is not advisable to reboot your VPS using script.
If your server goes out of memory at each boot time then your server never been up.
So, I will suggest you to use VPS management Control Panel for this.

Reboot VPS by reaching memory limit


CakePHP 2.4.4 How can I retrieve a User record excluding the password, except for Auth, in one place?

Question: This is the code I currently have:
public function afterFind($results = array(), $primary = false) {
    foreach($results as $key => &$value) {
        if(isset($results[$key][$this->alias]['password'])) {
            unset($results[$key][$this->alias]['password']);;
        }
    }
    return $results;
}

This is great when retrieving user data in general, but Auth obviously needs the password. Is there a way to run the above only if it's not Auth doing the find? I don't want to use some sort of field white/blacklist each time I have to find() to avoid retrieving the password.
Comment: Please don't forget to mention your exact CakePHP version!
Answer: I guess you could attempt to inspect the call stack to see if you're inside an Auth call, but that will be a big performance impact.
If you need to hide the password, the best way to do that is in the view. You could also have a helper that dumps user data and its careful not to dump the password. This way you can code this "suppression" only once.
And I think that the Cake debugger is smart enough not to dump a password field inside and array (but you should not rely on that in a production environment).
In view, dumping user data (not just only password) is not a good idea. Emails need to be protected as well. So I am very aware and careful of what and where I print out user information.


How to fix this error "Function CollectionReference.doc()"

Question: I'm creating a small react native app, when i add some code to delete data from firebase it shows me this error: " FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: undefined"
**that's my action:
import firebase from 'firebase/app'

const deleteChat = (id) => {
    return (dispatch, getState, getFirestore) => {
        if (id !== null) {
            firebase.firestore().collection('chat').doc(id).delete()
                .then(() => {
                    dispatch({
                        type: "DELETE_CHAT",
                        id
                    })
                })
        }

    }
}

Comment: The error message is telling you that you must pass a string to `doc()`.  You're passing something `undefined`.  You should log the value of `id` to be sure what it's receiving.
Answer: You are only checking if the id is not null. In your case the id is undefined.
You can solve this by writing
if (id !== null && id !== undefined)
or even better & shorter (it checks for both null and undefined)
if (id) {
 ...
}

Comment: @SoufienJAOUADI apparently you pass the id as number, not as string
Comment: it shows me now this "Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: 1557406283650"


JavaScript: Call function from child html document

Question: What's the best way to execute a javascript function in a child html document?
In my parent doc, I have this:
function validate() {
        debugger;
        var firstName = frm.FirstName.value;
        var lastName = frm.LastName.value;
        var email = frm.Email.value;

        if (!validateFirstName(firstName)) {
            return false;
        }
        if (!validateLastName(lastName)) {
            return false;
        }
        if (!validateEmail(email)) {
            return false;
        }

        var disp = window.open("results.html");
        disp.window.setData(firstName, lastName, email, frm.Comments);

        if (disp.confirm("Is this information correct?")) {
            disp.close();
        }
    }

in the child doc (results.html), I have this:

This is not working. Please tell me how I can do this with just plain javascript and html (no JQuery, etc).
Thanks
Comment: The .js function "setData()" in the second html document (child doc) which I want called after the parent doc's form is validated. It will set the data and the user will confirm whether OK or not. Note, this is not a real life problem (thankfully).. but is an unusual theoretical problem I have to solve for a course I am taking.
Answer: You should use the opener property. it returns a reference to the window that created the window.
When opening a window with window.open(), you can use this property from the destination window to return details of the source (parent) window.

Comment: Thanks, but I want to set the values from the parent form to the child form. I tried this:  window.onload = function () {
  frm.FirstName.value = opener.frm.FirstName.value;  //etc....  but it didn't work. Any ideas?
Comment: the variable `frm` references a `` element in the child doc too?
Comment: yes. I could change the "frm" name to make it less confusing I guess.. but there are 2 frm elements.. 1 in the parent and 1 in the child.. both docs have the same layout as well.. only difference is child doc is readonly (it is a confirmation screen)
Comment: Ok, So in the child doc you can do: `window.onload = function () { var childFrm = document.getElementById("theIdOfYourChildForm"); childFrm.FirstName.value = opener.frm.FirstName.value; //etc`
Comment: Sorry that doesn't work.. but don't worry; I've taken a different approach: `var disp = window.open("", "results");` and then I used `disp.document.write("`...etc.. so it's not ideal.. but it works and it will get me through the practical exam (if that comes up). Thanks anyway for trying.
Comment: NOTE: You didn't solve the problem, but the info was useful, so I've upvoted you. Thanks for your time.  :)
Comment: if you can post your code on jsfiddle.net, so i will take a look and try to solve your problem, because i can't understand why it doesn't work.


Design data structure for products

Question: I need to design the structure of the tables with the product data to meet the following requirements:
1. A product consists of the following fields: EAN, CN, description, pvp
2. There are several types of users that access the products. The user types are not stable, they can be added or deleted at any time.
3. Any of the fields of the products may vary depending on the type of user who views it. For example:

We have three users:
1 - John - guest
2 - David - client
3 - Vicent - vip

We have this product with this data by default:
8470001234567 - 123456 - Iphone X - $799

Guest users instead of seeing this data see the following:
8431239876547 - 987654 - Iphone X - $849

The client users see the data by default and the vip users see:
8470001234567 - 654321 - Iphone X Sale - $709

This means that a user sees the default data of a given product unless there is an exception for its type. The exception can affect any field (except the id).
I can think of this structure:

PRODUCTS: id, ean, cn, description, pvp
PRODUCT_EXCEPTION: product_id, user_type_id, ean, cn, description, pvp

I have verified that with this structure many queries are made, do you think of a way to optimize this so that it is not necessary to make so many queries?
Note 1: the products are contained within offers that have a certain number of products.
Note 2: I use Laravel. The Offer model has a relationship with products, that is, I obtain the products in the following way: $offer->products()
Answer: Looking at just the problem description, I ended up with this, which is equivalent to what you are proposing with your Product_Exception:

Reasoning:

Since user types vary, you cannot put the values directly in the Product table.  Ex. 3 user types == 3 prices.  Not here.  So you need a link table between Product and UserType.
The link table will contain the characteristics of 1 Product, for 1 UserType.
If you want to have a default value, you can put the characteristics in the Product table as well.  But then your queries become bigger!  Check if there is an exception value, if not use the default.

So your solution makes sense to me.

Design data structure for products


Migração do Blogger para domínio não carrega

Question: Tenho um blog no blogger.com, comprei um domínio e já está configurado(apontado), mas olhem o que está acontecendo.
Site SEM domínio:

Site COM domínio:

Alguém poderia me explicar o que está acontecendo e se isso é normal?
Comment: Como estão as configurações do `CNAME`, `A`, etc no seu servidor DNS?
Comment: Dê uma olhada nos passos para configurar o domínio no [artigo de suporte da google](https://support.google.com/blogger/troubleshooter/1233381?hl=en#ts=1734115)
Answer: Abrindo sua página No console do Chrome recebi os seguintes erros:
Refused to execute script from 'https://sites.google.com/site/3f2x4a/1/jquery.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Refused to execute script from 'https://sites.google.com/site/3f2x4a/1/bootstrap.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Refused to execute script from 'https://sites.google.com/site/3f2x4a/1/bootstrap-select.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Uncaught ReferenceError: $ is not defined
Refused to execute script from 'https://sites.google.com/site/3f2x4a/test/boostrap-blog.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Uncaught ReferenceError: AddFilm is not defined
Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

O que acontece é que você fez upload dos arquivos .js do Bootstrap e jQuery para esse endereço do Google Sites que está servindo os recursos com Content-Type: text/html e X-Content-Type-Options: nosniff. Essa combinação de cabeçalhos está efetivamente dizendo para seu navegador não abrir esses arquivos como se fossem JavaScript.
Para arrumar o problema você pode usar versões do jQuery e Bootstrap hospedadas em uma CDN ou em um servidor qualquer próprio para esse tipo de coisa. Exemplos:

jQuery na CDN da Google
Bootstrap na MaxCDN

Eu também recomendaria mover quaisquer outros recursos hoje hospedados em sites.google.com (style sheets, imagens, etc) para serviços próprios para hospedagem, evitando assim problemas posteriores.


How do I find the private or public key file that corresponds to a listing in `ssh-add -l`?

Question: When I run the ssh-add -l command, I do not get any filenames. How do I find the filenames or otherwise find the origin of keys that are listed in ssh-add -l?
Here is the output I get:
~/.ssh ssh-add -l
2048 SHA256:iQ2q8EE0sDPYp5icCTeXCi2iBWiqJEITqfnXRH1SOVA firstname.lastname@example.com (RSA)
2048 SHA256:nLrT5FirOWu3sDUvwS8ZWZq1TDy/VFCl+fcHzsf2AkQ  (RSA)
2048 SHA256:NdJXmNw7joMTSBwQG4OVY1kQLi8kagO1R1dKEvNzeYA  (RSA)
256 SHA256:lF1NWsr8K2wqOsbr94AJmRIRiJ/U/gDeZ7oZNz+jBDo email@example.com (ED25519)

Answer: Since keys you seen n ssh-add -l can come from an agent or the local filesystem there isn't really any way to map the from the public key hashes back to the associated public or private keys.
You can use ssh-add -L to get the public key in the format that you might find in filesystem.
If all your keys in the current directory you could possibly run a command like this to report which filenames of the public keys that have been in your agent.  It seemed to mostly work for me at least.
$ grep -f <( ssh-add -L) *.pub -l


Why is the database not updated before a next Rule is launched?

Question: I have two Rules (created with the Rules module) that are both launched when an article is flagged with the Flag Approved:

Rule 1. Publish the flagged article with the action Publish content.
Rule 2. Count the amount of published articles by the author of the flagged article. Display a message when this number is 5.

I'm using the following code in the condition of Rule 2:
return MYMODULE_count_articles($flagged_node->uid) == 5;

where my custom module contains the function
function MYMODULE_count_articles($uid) {
  $count = db_query("SELECT COUNT(*) FROM node WHERE uid=$uid AND status=1 AND type='article'")->fetchField();
  return $count;
}

The condition of Rule 2 is evaluated as FALSE when the 5th article is flagged with Approved, but evaluates as TRUE when a 6th article is flagged.
I suspect that this problem is caused because the database hasn't been updated yet when Rule 2 launches, because debugging the $count variable at the 5th flagging returns 4 instead of 5. Also, executing the condition's code afterwards yields the correct value 5.
Is this a know problem/phenomenon or a bug in the Rules module? Or is there an easy way to fix it (apart from changing the condition to ... == 4, which is really dirty)?
Comment: Could it be cache? See [here](http://drupal.stackexchange.com/a/47970/5284). I'm not sure what Rule 1 is doing to publish the node, but in case if it's not using `node_save` then that link could contain the answer: Flush the flagged node's cache before getting the count. Maybe in the same function or by doing a separate function call...
Comment: @Beebee: I've clarified in my question that Rule 1 publishes nodes with a default action *Publish content*. Adding a second action that evaluates the PHP code from your link didn't solve the problem. Neither did the usage of that code in the condition of Rule 2.
Answer: Have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).
A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rule 2 in a Rules Component, so that your Rule 1 "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Publish content" for sure completed, and your "number" will have been updated as expected.
Comment: I actually forgot about this question and only recently tried out your cool solution: I scheduled **Rule 2** 5 seconds after the current time. Since **Rule 2** should be executed as soon as possible, I would like to somehow force cron to run (it only runs once in an hour for the moment). Is there an easy way to do that or should I ask this in a new question?
Comment: @Jeroen : I am not aware of any Rules related solution to force cron to run. Though I'd be interested to learn/find out about that from anybody else. So maybe you should post a new question on that. Until some solution/answer for that comes up, you probably know about these 2 temporary work arounds: (a) run cron more frequently (every X mins) or (b) maybe "Elysia cron" may help somehow on this (not sure about that however).
Comment: Thanks Pierre. I asked http://drupal.stackexchange.com/questions/214769/how-to-force-a-cron-run-after-a-rules-component-is-scheduled and I will already have a look at Elysia cron, since that module might be what I am looking for.


Fixar navbar e dar scroll horizontal no conteúdo

Question: Estou tentando fazer um mapa com com uma navbar conforme imagem:

Só que ao mover a imagem no eixo X para ver o restante do conteúdo, a navbar move também conforme a imagem

Como faço para habilitar o scroll somente no eixo X para a div conteiner do mapa?
Segue css:
Mapa:
.mapa, .rota {
  position: absolute;
  height: 100%;
}

.mapa {
  z-index: 1;
}

.rota {
  z-index: 2;
}

Navbar:
nav{
    display: flex;
    height: 100%;
    position: relative;
    height: 70px;
    background-color: rgb(75, 87, 100);
    width: 100%;
    border-bottom: 5px solid rgb(233, 128, 99);
}
.arrow-back{
    width: 25px;
    position: absolute;
    left: 5%;
    top: 50%;
    transform: translateY(-50%);
}
.nav-search {
    flex-direction: column;
}

Comment: Seu objetivo é que a navbar esteja sempre visível, independente do usuário ter rolado a página pra baixo? Se sim, pode fixar sua navbar: `position: fixed; top: 0; left: 0; right: 0;`. Lembre-se de colocar o `z-index` com valor acima do conteúdo da sua aplicação (Costumo colocar 999).
Comment: Quero deixar a navbar fixa quando ele rolar para os lados e não para baixo
Comment: Amigo o principal que eu o html vc não colocou na pergunta. Edite e coloque o html e o CSS completo se possível. Vc esta usando algum framework tipo Bootstrap ou outro?
Answer:
Como faço para habilitar o scroll somente no eixo X?
(sic) Quero deixar a navbar fixa quando ele rolar para os lados e não para baixo

div.topo {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 70px;

    background-color: rgb(40, 40, 90);
    color: rgb(255, 255, 255);
}
div.conteudo {
    position: absolute;
    top: 70px;
    width: 50%;
    height: 200px;
    overflow-x: scroll;
    overflow-y: scroll; /* PODE ALTERAR PARA "hidden" CASO NÃO QUEIRA SCROLL VERTICAL */
    white-space: nowrap; /* IMPEDE A QUEBRA DE LINHA */
}
div.algo {
    display: inline-block; /* ALINHA OS ELEMENTOS */

    width: 200px;
    height: 150px;

    background-color: rgb(230, 230, 230);
    border: solid 1px rgb(230, 180, 180);
}
<!DOCTYPE html>

        <title>Scroll horizontal - LipESprY</title>

            Barra topo

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Alguma coisa...

Tome isto como um exemplo. Melhor que isto, só se você postar o código completo do seu projeto, ao invés de prints.

Fiz meu exemplo baseando-me em: How to make a DIV not wrap?
Comment: Exatamente isso! Obrigado


How can I import multiple CSVs to preset sheets?

Question: I have some CSV files on my G-drive that I want to import to preset sheets, based on file names. For example,

I have CSV files named: "REP1-abc", "REP2-bcd", "REP3-cde",...
I have spreadsheet with sheets named: "REP1", "REP2", "REP3",...

Target is to take first four letters of file name to match correct sheet name and import it to that sheet.
Im new in this so i will appreciate any tips on how to compare those two names.
Comment: Sharing your research helps everyone. Tell us what you've tried and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See [tag info page](https://stackoverflow.com/tags/google-apps-script/info) for official documentation, free resources and more details.
Answer: Loading CSVs
<code>function loadcsvs() {
  const fldr = DriveApp.getFolderById("Folder id");
  const files = fldr.getFileByType(MimeType.CSV);
  const ss = SpreadsheetApp.getActive();
  const shts = ss.getSheets().map(sh => sh.getName());
  while(files.hasNext()) {
    let file = files.next();
    let sname = file.getName().slice(0,4);
    let idx = shts.indexOf(sname);
    if(~idx) {
      let sht = ss.getSheetByName(shts[idx]);
      let vs = Utilities.parseCsv(file.getBlob().getDataAsString())
      sht.getRange(1,1,vs.length,vs[0].length).setValues(vs);
    }
  }
}
</code>


jQuery counter + each reset

Question: I'm using the code below to move images in a pair of sliders, but the first slider is jumping an extra step before resetting.
slider 1 = 5 images,
slider 2 = 6 images
function summarySlider(count) {
  var itemWidth = '20.2';
  var itemList = $('.summary-item-list');
  $(itemList).css('transform', 'translateX(-'+ (itemWidth * count) +'%)');
}
$(window).on("load", function () {
  $('.summary-v2-block').each(function(index){
    var count = 0;
    var limit = $(this).find('.summary-item').length;
    setInterval(function() {
      if (count === limit) {
        count = 0;
      }
      console.log(index, limit,  count);
      summarySlider(count);
      count++;
    }, 2500);
  });
});

I think what is going on is that index 0 is actually the second slider, and index 1 is the first slider. It's counting indexes backwards?
How can I make index 0 the first slider?
This is the console output
(index, limit,  count)
0 5 0
1 6 0
0 5 1
1 6 1
0 5 2
1 6 2
0 5 3
1 6 3
0 5 4
1 6 4
0 5 0
1 6 5
0 5 1
1 6 0
Comment: `var itemList = $('.summary-item-list');` is not instance specific
Comment: Because image counts are not equal? You said 1st has 5 images and 2nd one has 6 right? That means while 1st one reaches its end, 2nd one still has one more to go
Comment: sorry - but I am not seeing the issue - one slide is showing from 050 to 054 (which is expected cos it has 5 images) and the other one shows from 160 to 165 (which makes sense for a slide with 6 images. it seems to show what i would expect with the 5 image slider cycling with 5 images and the other with 6. but its late so i might be missing something
Comment: @gavgrif I know right, I've spent too long looking at this too. But like the first slider has length 5, which is correct, but I think the first slider is getting assigned index 1. and the Second slider is index 0. So one slider is finishing early, the other is resetting one late
Comment: @charlietfl what does that mean?
Comment: It means the count passed to `summarySlider()` from one slider instance will affect both instances of those elements
Comment: @charlietfl YES! You probably saved me hours, thank you
Answer: The issue isn't the timing but rather that your summarySlider function is looking for and manipulating elements that exist in both sliders.
You could pass in another argument for the parent slider element and use find() to make it instance specific
function summarySlider($slider, count) {
  var itemWidth = '20.2';
  var itemList = $slider.find('.summary-item-list');
  $(itemList).css('transform', 'translateX(-'+ (itemWidth * count) +'%)');
}
$(window).on("load", function () {
  $('.summary-v2-block').each(function(index){
    var count = 0;

    var $slider=$(this);// to pass to `summarySlider()`

    var limit = $(this).find('.summary-item').length;
    setInterval(function() {
      if (count === limit) {
        count = 0;
      }
      console.log(index, limit,  count);
      summarySlider($slider, count);
      count++;
    }, 2500);
  });
});

jQuery counter + each reset


Prove, that sequence $ b_n = \sin1/2 +\sin2/4 +\dots+ \sin(n)/2^n$ is Cauchy

Question: I do not know, how to start proving that this sequence $$b_n = \sin1/2 + \sin2/4 +\dots+ \sin(n)/2^n$$ is Cauchy.
Thanks for all your answers.
Answer: Hint: if $n > m$,
$$|b_n - b_m| = \left|\frac{\sin (m+1)}{2^{m+1}}+\dots+\frac{\sin n}{2^n}\right| \leq \frac{1}{2^m}$$


Way to determine Flex 3 Effect direction?

Question: Flex Effects include "isPlaying" property to check whether Effect is currently playing or not. But is there a way to find out what is the direction of playback (whether the play was started with playReversedFromEnd)?
Answer: Looking at the code; it looks like a playReversed property is added to the EffectInstance of the effect that reflects the playReversedFromEnd property of the play method.
So, you can check that property ( playReversed  ) on the effectInstances returned from the play method.


Is the process weakly stationary?

Question: $$y_t=5+ε_t,      ε_t |I_(t-1)~N(0,σ_t^2 ),σ_t^2=σ^2 y_t^2$$
Is this process weakley stationary?
How can I tell?
Comment: Welcome to CV. Since you're new here, you may want to take our tour, which has information for new users.
Please add the [self-study] tag and read its wiki. Then tell us what you understand thus far, what you've tried & where you're stuck. We'll provide hints to help you get unstuck. Please make these changes as just posting your homework & hoping someone will do it for you is grounds for closing.
Comment: @jbowman Thanks for the introduction, I know that this is the constant model, I know that it would be stationary by itself, but I get confused with the sigmat^2, will this impact the stationarity of the equation?
Comment: @jbowman does that answer work from your experience?
Answer: The process above shows a constant model with some ARCH/GARCH type conditional variance.
The important thing to note is that the definition of weak stationarity in terms of variance is that the unconditional variance is constant. Here it is, and it also meets the other two stationarity conditions.
The trick in the question is that the ARCH/GARCH type errors are only concerned with the conditional variance. Therefore, to answer the questions, ignore the conditional variance component, and conclude that it is weakly stationary.

Is the process weakly stationary?


Preciso de Ajuda com esse Código

Question: Pessoal eu escrevi o seguinte código simples no meu python:
nome = str(input("Qual o seu nome?"))
if nome == 'denise':
  print("Nome bonito")
elif nome == 'maria' or nome == 'pedro' or nome =='joao':
  print("Nome popular no brasil")
else:
  print("Seu nome é bem normal")

Se eu escrever Denise  o python imprime a ultima linha "Seu nome é bem normal" e seu eu escrever maria,pedro e etc... mesmo assim o python imprime a ultima linha " Seu nome é bem normal"
Vocês poderima me ajudar e me informar qual o erro desse código?
PS: A versão do meu python é 3.8.2
Answer: O problema é que a linguagem Python diferencia letras maiúsculas de letras minúsculas, logo a string "Denise" é diferente de "denise" e certamente você está escrevendo os outros nomes com letra maiúscula como por exemplo: "Maria", "Joao", "Pedro".
Para corrigir o problema, basta tornar a string retornada do input() em minúsculo utilizando o método de string lower(), dessa forma:
nome = input("Qual o seu nome?").lower() # Transforma em minúsculo

if nome == 'denise':
    print("Nome bonito")

elif nome == 'maria' or nome == 'pedro' or nome == 'joao':
    print("Nome popular no brasil")

else:
    print("Seu nome é bem normal")

Um outro detalhe importante a acrescentar, é que o Python não só diferencia letras maiúsculas de minúsculas, mas também ele diferencia letras com acento de letras sem acento.
Sendo assim, a string "joão" (com acento no A) é diferente de "joao" (sem acento no A).

E aqui está uma dica bônus para encerrar a resposta:
A função input() sempre (a não ser que tenha sobrescrito) retornará uma string mesmo se a entrada do usuário seja numérica. Logo, utilizar o str() neste caso é redundante e aumentará o seu código desnecessariamente :)
Comment: Então, eu fiz o que tu falou e mesmo assim não funciona: reduzi o código é escrevi apenas isso. nome= str(input("Digite o seu nome")) if nome =="Denise": print("Nome bonito") e mesmo eu escrevendo apenas isso o python não imprime, apenas pergunta "digite o seu nome" , contudo se eu mudar e colocar o número 1 no lugar de Denise ele imprime. Você sabe me dizer o motivo?
Comment: Não você não fez o que falei na resposta. Agora você verifica se o nome é `"Denise"` (com letra maiúscula), mas se você escrever `"denise"` minúsculo não vai funcionar. Que tal copiar o código da resposta em um arquivo separado, testar o código e estudá-lo para entender onde você está errando ?

Preciso de Ajuda com esse Código


Como aplicar a estratégia DRY (Don't Repeat Yourself) nesse código?

Question: Tenho várias tabelas, uma em cada página da minha aplicação e todas terão a mesma função de filtrar uma coluna, porém as colunas tem nomes diferentes e ordens diferentes.
Como escrever esse código sem que ficasse repetitivo?
$(document).ready(function(){
    // Filtro da tabela em fila
    var em_fila = $('#em_fila').dataTable({
                        "sDom":     "t",
                        "paging":   false,
                        "ordering": false,
                        "info":     false
                      }
                  );

    $('.select-category').change( function () {
        em_fila.fnFilter($('.select-category').val(), 0);
    });

    // Filtro da tabela digitação
    var em_digitacao = $('#em_digitacao').dataTable({
                               "sDom":     "t",
                               "paging":   false,
                               "ordering": false,
                               "info":     false
                           }
                       );

    $('.select-category').change( function () {
        em_digitacao.fnFilter($('.select-category').val(), 0);
    });

    // Filtro da tabela com erros
    var com_erros = $('#com_erros').dataTable({
                            "sDom":     "t",
                            "paging":   false,
                            "ordering": false,
                            "info":     false
                        }
                    );

    $('.select-category').change( function () {
        com_erros.fnFilter($('.select-category').val(), 0);
    });

    // Filtro da tabela com em_recebimentos
    var em_recebimentos = $('#em_recebimentos').dataTable({
                                  "sDom":     "t",
                                  "paging":   false,
                                  "ordering": false,
                                  "info":     false
                              }
                          );

    $('.select-category').change( function () {
        em_recebimentos.fnFilter($('.select-category').val(), 0);
    });

});

Answer: Olá!
Primeiramente ajudará bastante a identação do código.
Bom, você está utilizando repetidamente o datatable com configurações padrão. Você poderia fazer o seguinte. Nas tabelas que você utiliza, no html, você adiciona uma classe chamada 'datatable-defaults' (ou algo que remeta que isto é um datatables com esses ajustes padrão.
No seu código, faça o seguinte:
$('table[class~=datatable-defaults]').dataTable(
    {"sDom":"t",
     "paging":   false,
     "ordering": false,
     "info":     false
});

Isso fará com que todas aquelas tabelas que você precisa para tal já serão instanciadas com o datatable. O segredo está na query da DOM. No trecho:
table[class~=datatable-defaults]

Ele buscará qualquer "table" que tenha, dentro do atributo class, o texto datatable-defaults.
Ou seja,
(...)

(...)

...será encontrado através da query do Jquery, logo sendo submetido ao inicializador do datatables, por exemplo.
Documentação desse método: http://api.jquery.com/attribute-contains-word-selector/
Espero ter ajudado! =)
Comment: Porque você complicou tanto o seletor? Um simples `table.datatable-defaults` daria o mesmo resultado.
Answer: Você está usando a mesma configuração para todas as tabelas. Portanto, você pode simplificar selecionando todas as tabelas de uma só vez.
var tables = $('#em_fila, #em_digitacao, #com_erros, #em_recebimentos').dataTable({
        "sDom":     "t",
        "paging":   false,
        "ordering": false,
        "info":     false
    }
);

$('.select-category').change( function () {
    tables.fnFilter($('.select-category').val(), 0);
});

Comment: Gostei do avatar!


Is batching a way to avoid local minima?

Question: That is my question: is batching one way to prevent the model from falling in a local minima? What is the difference between bach=1 and batch=32 in those terms?
Answer: no rather the opposite. gradient descent -ie using whole dataset to compute gradient suffers from local minima.
taking a random sub sample (minibatch) can avoid local minima because you are adding noise- which effectively changes the error surface possibly removing the local minima (or introducing new one).  However, too much noise (eg batch =1) and you are just solving for one sample and then undoing effects to solve for the next (depending on learning rate).
a Minibatch eg 32 therefore is a compromise. In addition, there is a computational issue, using minibatch instead of full batch can give you almost the same gradient as using the full batch at much less computational effort. ( law of large numbers effect - std dev decreases with sqrt(samples)).
so if my gradient error is ~ x with 32 samples, then i need 3200 samples to get gradient error ~ 1/10 x.
Comment: @noober yes exactly
Comment: I've seen the claim in your first paragraph almost every time a question like this answered, but I can't find a definitive source for it. Do you have any references?
Comment: "std dev decreases with sqrt(samples)" – uh, that argument doesn't really work if the input space has much higher dimension than the number of samples.
Comment: @mhdadk - You should be able to find it in any neural net text book.  The error surface is not convex in a multlayer network (even with linear neurons! https://arxiv.org/pdf/1312.6120.pdf), therefore you can have the existence of local minima.
Comment: @leftaroundabout I don't see why it doesn't work.  In any case CNNs use weight sharing so the effective input space is smaller, no
Comment: so by using batch size, a model will have higher probabilities of avoiding local minimums and not throw to the can what it learned in previous iterations, right? @seanv507