Como fazer vídeo iniciar mudo

Question: Queria saber como posso fazer para que meu vídeo inicie mudo. Consegui programar os controladores: tem um botão que muta e um que desmuta. Só que queria que ele já iniciasse mudo.
Codigo em html:

            <video id="Video1" width="100%" height="100%" loop>
                <source src="video/animacao-lol.mp4" type="video/mp4" />
            </video>

Lorem ipsum Dolor

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at risus neque.
Cras sit amet ligula
            ut justo commodo porta id ut enim. Nulla est lectus, mollis sit amet vehicula id, volutpat eget mauris.

        <button id="volDn"></button>
        <button id="volUp"></button>
        <button id="mute"></button>

o JS:
function init() {
    var video = document.getElementById("Video1");
    if (video.canPlayType) {
        document.getElementById("buttonbar").style.display = "inline";

        function setVol(value) {
            var vol = video.volume;
            vol += value;
            if (vol >= 0 && vol <= 1) {
                video.volume = vol;
            } else {

                video.volume = (vol < 0) ? 0 : 1;
            }
        }
        document.getElementById("volDn").addEventListener("click", function () {
            setVol(-.1); // down by 10%
        }, false);

        document.getElementById("volUp").addEventListener("click", function () {
            setVol(.1);  // up by 10%
        }, false);

        document.getElementById("mute").addEventListener("click", function (evt) {
            if (video.muted) {
                video.muted = false;
                evt.target.innerHTML = ""
            } else {
                video.muted = true;
                evt.target.innerHTML = ""
            }
        }, false);
    }
}

Answer: Por gentileza, verifique se isso funciona. Caso, não, estarei editando a resposta.
function init() {
var video = document.getElementById("Video1");
if (video.canPlayType) {
    document.getElementById("buttonbar").style.display = "inline";

    function setVol(value) {
        var vol = video.volume;
        vol += value;
        if (vol >= 0 && vol <= 1) {
            video.volume = vol;
        } else {

            video.volume = (vol < 0) ? 0 : 1;
        }
    }
    document.getElementById("volDn").addEventListener("click", function () {
        setVol(-.1); // down by 10%
    }, false);

    document.getElementById("volUp").addEventListener("click", function () {
        setVol(.1);  // up by 10%
    }, false);

    document.getElementById("mute").addEventListener("click", function (evt) {
        if (video.muted) {
            video.muted = false;
            evt.target.innerHTML = ""
        } else {
            video.muted = true;
            evt.target.innerHTML = ""
        }
    }, false);
}
            video.muted = true;
}

Comment: Uma sugestão: Destacar a solução no código, apenas para facilitar o acesso à informação para quem acessar esta pergunta :)
Comment: funcionou "vlwwwwwwwww"

Como fazer vídeo iniciar mudo


Trying to understand lists in recursive ways step by step

Question: concatenar([], Xs, Xs).
concatenar([X|Xs],Ys,[X|Zs]) :- concatenar(Xs,Ys,Zs).

?- concatenar([a, d, c], [s, a, d], Z).
Z = [a, d, c, s, a, d]

?- concatenar(T, [s, a, d], [a, d, c, s, a, d]).
T = [s, a, d]

% Mínimo elemento de una lista
%Ejemplo: minimo([1,5,3,-2],X). X=-2

minimo([X], X).
minimo([X|Xs], X) :- minimo(Xs,Y), X =< Y.
minimo([X|Xs], N) :- minimo(Xs,N), N < X.

Comment: `concatenar([], Xs, Xs).` means that if you concatenate `[]` and `Xs` you get `Xs`. `concatenar([X|Xs], Ys, [X|Zs]) :- concatenar(Xs, Ys, Zs)` says that `[X|Zs]` is the result of concatenating `[X|Ys]` and `Ys` *if* `Zs` is the result of concatenating `Xs` and `Ys`. Follow the same kind of logic in understanding `minimo`. Think of the predicate clauses as rules.
Comment: You should write your questions in English. At any rate, recursion through lists is not very complicated. You can only remove elements from the front and you have no idea how many elements are in the list in total, so removing 1 is the safest. That way you can split a list in `functor([FirstElement|TheRest],_) :- not(some_check(FirstElement)), functor(TheRest).` and if an element does match your check you can return it `functor([FirstElement|_],FirstElement)`. Please write out your question English and specify what you want to know exactly, or just read Learn Prolog Now! online.
Comment: thank you to respond and sorry, I forgot to translate in English. I was watching some videos and reading but I don't find somebody that explain an example step by step recursivity with lists. I want to know step by step how recursivity is happening with an axample. for example with it
Comment: concatenate([ ], Xs, Xs).
concatenate([X|Xs],Ys,[X|Zs]) :- concatenate(Xs,Ys,Zs).

?- concatenate([a, b, c], [s, a, d], Z).
Z = [a, b, c, s, a, d]
Comment: step 1: Xs have inside [b,c] and X [a]                                                  step2:    Xs have inside [c] and X [a,b]
 step 3: Xs have inside [ ] and X [a,b,c]     ys have inside [d,e,f]                                              step4: and then what happend?             I don't understand how [s,a,d] go inside X to have finally Z=[a,b,c,s,a,d]
Comment: You shouldn't elaborate in comments. If you want  to add more clarity to your question, please edit your question. Also, did you try using `trace` to watch execution? Use `trace` on a simple example, like `concatenar([a,b], [c,d], L).` Per one of your comments about step 1, initially, yes `Xs = [b, c]` in your example, but `X = a`, not `X = [a]` since the list is `[a,b,c]` which could be written, `[a | [b,c]]`. Your step 2 is incorrect. In Step 2, `X = b` and `Xs = [c]` since you are calling `concatenar([b,c], [s, a, d], Zs)`.
Comment: Sorry, I tried but I can't edit my post because have problems in add text, I have no idea. I am new using it.      thank you lurker!! and what happened in step 4, 5 and 6? because these steps I don't know how is
Answer: I'll help you through your first example. This should give you enough information to tackle the second on your own...
Here's your predicate:
concatenar([], Xs, Xs).
concatenar([X|Xs], Ys, [X|Zs]) :- concatenar(Xs,  Ys, Zs).

Now consider the query:
?- concatenar([a,b,c], [x,y,z], L).

Prolog will start at the beginning of your "database" (asserted facts and predicates) trying to unify the query term with the facts and predicate heads. The first attempt is with concatenar([], Xs, Xs). Prolog is unable to unify the query term with this rule because [] does not unify with [a,b,c]. So Prolog moves on to the next predicate head, concatenar([X|Xs], Ys, [X|Zs]) .... Here it can unify [a,b,c] = [X|Xs] via X = a and Xs = [b,c], it can unify [x,y,z] = Ys as is, and it unifies L = [X|Zs] as is. Since it matched the head of this predicate clause through unification, Prolog will proceed with the body of the clause and call concatenar(Xs, Ys, Zs) which, through the unification of the  head, is concatenar([b,c], [x,y,z], Zs).
Now you repeat the process over again. You have a new query, concatenar([b,c], [x,y,z], Zs) which attempts to unify with the first head, concatenar([], Xs, Xs). No match, since [b,c] does not unify with []. As before, Prolog moves on to the next clause and unifies concatenar([b,c], [x,y,z], Zs) with concatenar([X|Xs], Ys, [X|Zs]) via X = b, Xs = [c], Ys = [x,y,z], and Zs = [X|Zs'] (note, I used Zs' to distinguish the fact that this is a different variable than the other Zs). Again, as before, Prolog will proceed with the body of the clause and call concatenar([c], [x,y,z], Zs').
If you continue this process to the next step, you'll finally match concatenar([], Xs, Xs) with concatenar([], [x,y,z], [x,y,z]). Then you have to unwind the recursion...
How did we get to the call to concatenar([], [x,y,z], Zs)? It came from a call to concatenar([c|[]], [x,y,z], [c|Zs]) :- concatenar([], [x,y,z], Zs). So when this call comes back, it results in concatenar([c|[]], [x,y,z], [c|[x,y,z]]) or concatenar([c], [x,y,z], [c,x,y,z]).
And how did we get to that call? It came from a call to concatenar([b|[c]], [x,y,z], [b|Zs]) :- concatenar([c], [x,y,z], Zs). So this one results in concatenar([b|[c]], [x,y,z], [b|[c,x,y,z]]) or concatenar([b,c], [x,y,z], [b,c,x,y,z]).
And this call came from concatenar([a|[b,c]], [x,y,z], [a|Zs]) :- concatenar([b,c], [x,y,z], Zs). which results in concatenar([a|[b,c]], [x,y,z], [a|[b,c,x,y,z]]) or concatenar([a,b,c], [x,y,z], [a,b,c,x,y,z]).
Tada! It's done.
Comment: Thank you so much!! you saved my life!!  so L is taking a letter since recursivity is running. is like a collecion or a lis L adding elements by steps of recursivity. L=[a], L[a,b], L[a,b,c], L[a,b,c,x,y,z]. I got it? thank you so much!! you made my day!
Comment: the last question. when you have concatenar([ ], [x,y,z], Zs') it match with concatenar([], Xs, Xs)? or how you get x,y,z to both sides?
Comment: I think that I got it. so the answer is [] unifies with [];  [x,y,z] unifies with Xs; Zs unifies with Xs; so Xs was unified before with [x,y,z] , Zs have now the same value. it is ok?
Comment: @LucianoFndz that is correct. When `concatenar([], [x,y,z], Zs)` unifies with `concatenar([], Xs, Xs)` you get `[] = []`, `[x,y,z] = Xs` and `Zs = Xs`. So `Zs = [x,y,z]`.
Comment: @LucianoFndz to answer your first question, the final list is filled in on the returns from the recursive calls. So you really get `L` of `[x,y,z]`, then `[c,x,y,z]`, then `[b,c,x,y,z]`, and finally `[a,b,c,x,y,z]`.
Comment: why in that way? because is using backtracking method so is adding back to front?
Comment: @LucianoFndz it's that way because if you follow the logic carefully as I described, it goes all the way down to the base case `concatenar([], [x,y,z], Zs)`, then the call to the base case has the next element, in this case, `c`. I can add more to my answer to explain...
Comment: @LucianoFndz now that I've gone through the whole process, you should try this at the Prolog prompt, but enter `trace.` first. Then enter `concatenar([a,b,c], [x,y,z], L).`  and press Space bar at each `?`.
Comment: thank you very much!!!!!! I understand now! is like a pyramid!!. first is taking a, then b then c, and then take the case base and take xyz and then is taking cxyz, then b,c,x,y,z and finally a,b,c,x,y,z


Let $\mathcal H$ be a Hilbert space. If $\mathcal H$ is not finite-dimensional, then $B := \{x \in \mathcal H : ||x|| \le 1\}$ is not compact.

Question: Let $\mathcal H$ be a Hilbert space. Consider $B := \{x \in \mathcal H : ||x|| \le 1\}$.
I've proven that $B$ is closed and bounded with respect to the metric $\rho(x,y) = || x -y ||$.
Now I want to show that if $\mathcal H$ is not finite-dimensional, then $B$ is not compact.
For this I've considered the ortonormal system $\{e_n : n \in \mathbb N\}$.
I must show that there exist a sequence $(x_n)$ in $B$ such that no subsequence $(x_{n_i})$ of $(x_n)$ is convergent in $B$ ? How can this be done ?
Finally, I've tried to find an example of a Hilbert space $\mathcal H$, where $B$ is not compact.
Comment: Compute the norm between two distinct members of your orthonormal set (or just the square of the norm).
Answer: If $e = \{e_n \colon n\in\mathbb{N}\}$ is an orthonormal system (hence $e\subset B$), then
$$\rho^2(e_m,e_n) = (e_m-e_n,e_m-e_n) = (e_m,e_m)-2(e_m,e_n)+(e_n,e_n) = 1-2\cdot 0 + 1=2$$
if $m, n$ are distinct natural numbers. Therefore, from $e$ it can't be selected convergent subsequance.
Moreover, from this, you can deduce that the unit sphere $S =\{x\in H \colon \|x\|=1 \}$ is also non-compact, since our system $e\subset S$.
Comment: How can I be sure $e \subset B$ ?
Comment: Orthonormal means $\|e_n\|=1$
Comment: Of course ... Should have thought of that. And I can use this system, because every Hilbert space has such a basis ?
Comment: Yeap! Every Hilbert spase has an orthonormal basis.
Comment: Can you help with finding a Hilbert space $\mathcal H$ where $B$ is not compact ?
Comment: Take any infinite dimensional space, for example $l^2(\mathbb{N})$ as in the other answer.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18957/discussion-between-mher-and-user111854).
Answer: The usual example is
$$\mathcal{H} = l^2 = \left\lbrace (a_n)_{n=1}^{\infty} \in \mathbb{R}^{\mathbb{N}} ~ | ~ \sum_{n=1}^{\infty} a_n^2 < \infty \right\rbrace$$
Taking the sequence $(e^{(n)})$, where $e^{(n)}_n = 1$ and $e^{(n)}_i = 0$ for all $i \neq n$, we obtain a sequence that has no convergent subsequence.
To see that this holds, note that
$$\rho(e^{(m)}, e^{(n)}) = 2 \cdot \delta_{m,n}.$$
Hence, any sequence that consisting of these vectors $e^{(n)}$ and converges has to become constant at some point.
Comment: I think you meant $l^2(\mathbb{N})$. $l^2(\mathbb{R})$ is a little more pathological and not needed here.
Comment: @Lolman That is true, thank you.
Comment: Why should $a_n$ be squared ?
Comment: @user111854 This is just an example of a Hilbert space.
Comment: Would the inner product be the normal dot-product ?
Comment: The inner product is $((a_n), (b_n))_{l^2} = \sum\limits_{n=1}^{\infty} a_n b_n$.
Comment: How can you say this converge ?
Comment: @user111854 If you mean the inner product: Using the [Cauchy-Schwarz-Inequality](http://en.wikipedia.org/wiki/Cauchy%E2%80%93Schwarz_inequality) one has $\left\lvert \sum_{n=1}^{\infty} a_nb_n \right\rvert \leq \left( \sum\limits_{n=1}^{\infty} a_n^2 \right)^{1/2} \left( \sum\limits_{n=1}^{\infty} b_n^2 \right)^{1/2}$. Both factors on the right side are finite by definition of $l^2$.


Prove that $a:\mathbb{Z}_+\to \mathbb{R}$, with $a_n = \frac{1}{n}$ is a Cauchy sequence.

Question: I am not allow to use the fact if a sequence is convergent then its Cauchy which is the only way I can solve this problem.
Comment: Use the definition of a cauchy sequence.
Comment: Do outline what you did or think.
Answer: Just use the definition of Cauchy sequence.
Let $\epsilon>0$ and show that there is $N\geq 1$ (which depends on $\epsilon$) such that for all $n,m\geq N$, $\left|\frac{1}{n}-\frac{1}{m}\right|<\epsilon$.
Hint. Note that $\left|\frac{1}{n}-\frac{1}{m}\right|\leq \frac{1}{\min(m,n)}$,


Salvar arquivo .doc no banco de dados com Django

Question: Estou desenvolvendo uma aplicação com Djando e Python.
Em models.py, para criar um objeto cliente com um nome, por exemplo, faço o seguinte:
class Cliente(models.Model):
    nome = models.CharField(max_length=255)

em forms.py faço o seguinte:
class ClienteForm(forms.ModelForm):
    class Meta:
        fields = ('nome',)
        widgets = {'nome': forms.TextInput(attrs={'class': 'form-control'}),}
        labels = {'nome': _('Nome'),}

mas como faço se esse campo ao invés de ser um campo de texto ser um arquivo .doc?
preciso anexar um documento word em cada cliente, algo como isso:
class Cliente(models.Model):
    nome = models.CharField(max_length=255)
    documento = models.DOCUMENTO.DOC

Answer: Django provê o tipo BinaryField para salvar binarios, voce pode definir da seguinte maneira:
doc_file = models.BinaryField(blank=True)

Mas atente bem para o que diz a documentação (Parte destacada nesse link)

Embora vc possa considerar armazenar arquivos em banco de dados, tenha em mente que esse design é ruim em 99% dos casos. Esse tipo de campo não é um substituto para o manuseio adequado de arquivos estáticos.


I need to find the spectrum of an operator.

Question: I need to prove that the spectrum of operator A in $L_{2}[0,1]$ is [-1;1] where $Ax(t) = \sin(\frac{1}{t})x(t)$ if $ t > 0$ and$ Ax(0) = 0$
Elementary - norm of $A$ is less or equal to $1$. Hence, all $\lambda$ from spectrum is such that $|\lambda| \leq$ 1.
$g(t)$ := $\sin(\frac{1}{t})$ if $t > 0$ and $0$ if $4t = 0$.
If there exists $y(t)$ such that $(A -\lambda I)x(t) = y(t)$ then if $y_{0} = 1$ almost everywhere then $x(t) = \frac{1}{g(t) - \lambda}$ $\notin L_{2}[0,1]$ if $\lambda \in [-1;1]$.
So, this means that $1 \notin$ Im(A-$\lambda I$) which means that Im(A - $\lambda I$) $\neq$ $L_{2}[0,1]$ and $\lambda$ is in spectrum.
But i can't seem to proof the fact that i used:
$x(t) = \frac{1}{g(t) - \lambda}$ $\notin L_{2}[0,1]$ if $\lambda \in [-1;1]$ And that's where i need help. Why is $x(t) = \frac{1}{g(t) - \lambda} \notin L_{2}[0,1]$ where $\lambda $ in $[-1;1]$
Answer: Hint: First make the substitution $u=\frac  1 t$ in $\int |x(t)|^{2}dt$. Write $\lambda$ as $\sin y$. Use the fact that $\sin u -\sin y=2\sin (\frac {u-y} 2) \cos (\frac {u+y} 2)$. In an interval around $y$  the function $\frac 1 {\sin (\frac {u-y} 2)}$ behaves like $\frac 2 {u-y}$ and the square of this is not integrable around $y$.
Comment: @vladimir soshnikov I had omitted an important step in my answer. I have edited the answer now.
Comment: seems like a legit solution. Thank you!


"The EM algorithm failed to converge in 25 iterations"

Question: When I Replace Missing Values - Expectation-Maximization in SPSS, I receive the following message: The EM algorithm failed to converge in 25 iterations.  Should the algorithm be able to converge?
Can anybody help me? :)
I have 20 variables and 299 cases (217 cases listwise).
Answer: For a start, increase the number of iterations (on the EM subdialog box).  Try, say, 100
Answer: I had a similar problem and it turned out to be that I included the Case IDs with the quantitative variables that I was testing.
The problem was fixed when I removed the Case IDs from the list that is being tested.
Good luck.


How to make UISheetPresentationController prefersGrabberVisible follow light/dark mode?

Question: In setting UISheetPresentationController's prefersGrabberVisible to true, our app successfully displays the grabber handle at the top of modal view controllers.
However, the grabber is always in the system light/dark mode, ignoring the overrideUserInterfaceStyle setting and ignoring the UITraitCollection override.
How do we make the grabber respect the specific view controller's light/dark UIUserInterfaceStyle instead of just adhering to device light/dark mode?
Answer: overrideUserInterfaceStyle for the grabber is overrided by its view that's why setting this property to a view controller (or superview) doesn't help.
Therefore, you can't control the color of the grabber.
However, if you really want to change it, you can try to change color of the grabber manually finding it in subviews each time traitCollectionDidChange(...) is called


How to filter views rows whose nid is less than nid provided by url?

Question: Drupal 7. In a node/edit form panel I have added a view that returns nodes.
I whish to filter thoses nodes and keep only the nodes whose nid is less than the nid of the node beeing edited.
the url of the node/edit form   is : /node/11541/edit?step=11538
the nid of the node being edited is : 11541
I wish the view to return only the nodes whose nid < 11541
I use Views PHP
Comment: this is for Drupal 7? Because I don't have test my code in Drupal 8
Answer: You can implement the hook_views_query_alter() to alter your query and change the = operator by the < operator.
function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if($view->name == 'YOUR_VIEW_NAME') {
    /* Using the following line dmp($query)
     * (you need the devel module to use dpm) you will be able to search
     * where is condition to alter, you will see that in the
     * $query->where[0]['conditions'][0]['field'] you will have:
     * node.nid = :node_nid
     * so your solution will be replace the
     * = operator by the < operator
     * at this moment you can't do this from the Views UI
     */
    dpm($query);

    $query->where[0]['conditions'][0]['field'] = str_replace('=', '<', $query->where[0]['conditions'][0]['field']);
  }
}

I test the code and in my environment it works as I want it to.
Here is my view for if you want test the code (in this case the view name is articulos):
$view = new view();
$view->name = 'articulos';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'articulos';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'articulos';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'articulos/%';
$translatables['articulos'] = array(
  t('Master'),
  t('articulos'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('All'),
  t('Page'),
);

Comment: @Pierre.Vriens merci, ;-)
Comment: Thanks Adrian. It works great for one view in ma page, but not for the second view (see my code in my edited question), can my function handle 2 views with same query variable ?
Comment: Bienvenue dans le monde +5K ... PS: "... and it works" sounds a bit strange/bizarre. I understand you use it as a kind of quality assurance label (which is fine), but maybe you should use a phrasing like "in my environment it works as I want it to" ...
Answer: You can use a contextual filter for your view:

If you are using a page display, you will be able to retrieve the nid from the URL.
If you are using a block display, you will need to do it a bit differently. See Contextual filter with a block view
Comment: Thanks for helping.

I use a page display and a contextual filter for another parameter :

[view:metier=page_1=1]

If I'd wish to filter on "nid=   "  I know that I could use a contextual filter,

but how to use a contextual filter in order to filter nid " is less than " ?
Comment: Sorry I read you to fast. you say for a page display I could retrieve nid from URL. But I don't see how to do it.


I've been trying to build a game in react native and I have to render some svga files. How can I use svga in react native?

Question: I have tried these npm packages "react-native-svga-player-ex","react-native-svga-player","react-native-svga" but these are outdated and not supported in react version upper than 14. Please suggest any better solution for using svga file in react native.
Answer: You can use a webview with package react-native-webview where the html is the contents of the svga. For example:
import animation from "./assets/animation.svga";

...

return (
   <Webview source={{ html: animation }} />
)

Don't forget to change the style of the webview to have backgroundColor: "transparent", so that it shows the background you have behind (if that is the behaviour you want).
You might need to add something like this in your plugins section of your babel.config.js:
[
    "babel-plugin-inline-import",
    {
        extensions: [".svg", ".svga"]
    }
],


Linux firewalld - I can hit port 4506, but my configuration shouldn't let me

Question: Not sure what I've got wrong here. I don't see port 4506 open in this configuration, but I'm able to telnet to it from a remote machine on the 156.9.122 subnet. What am I doing wrong?
# firewall-cmd --list-all-zones

firewall-cmd --list-all-zones
block
  target: %%REJECT%%
  icmp-block-inversion: no
  interfaces:
  sources:
  services:
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

dmz
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: ssh
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

drop
  target: DROP
  icmp-block-inversion: no
  interfaces:
  sources:
  services:
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

external
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: ssh
  ports:
  protocols:
  masquerade: yes
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

home
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: ssh mdns samba-client dhcpv6-client
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

internal
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: ssh mdns samba-client dhcpv6-client
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

public (active)
  target: default
  icmp-block-inversion: no
  interfaces:
  sources: 188.8.131.52/24
  services: http https ntp dhcpv6-client kerberos ldaps ssh dns ldap
  ports: 443/tcp 7902/tcp 8014/tcp 7903/tcp 8089/tcp 463/tcp 7899/tcp 7898/tcp 7900/tcp 52311/udp 80/tcp 7901/tcp 1584/tcp 1585/tcp 463/udp 22/tcp
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

trusted
  target: ACCEPT
  icmp-block-inversion: no
  interfaces:
  sources:
  services:
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

work
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: ssh dhcpv6-client
  ports:
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

# iptables -nvL

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
28874 7345K ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
  205 36869 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
  117 12145 INPUT_direct  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  117 12145 INPUT_ZONES_SOURCE  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  112 11773 INPUT_ZONES  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
   21  4809 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
    0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
    0     0 FORWARD_direct  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FORWARD_IN_ZONES_SOURCE  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FORWARD_IN_ZONES  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FORWARD_OUT_ZONES_SOURCE  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FORWARD_OUT_ZONES  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
    0     0 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT 29114 packets, 7722K bytes)
 pkts bytes target     prot opt in     out     source               destination
29114 7722K OUTPUT_direct  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FORWARD_IN_ZONES (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 FWDI_public  all  --  +      *       0.0.0.0/0            0.0.0.0/0           [goto]

Chain FORWARD_IN_ZONES_SOURCE (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 FWDI_public  all  --  *      *       220.127.116.11/24       0.0.0.0/0           [goto]

Chain FORWARD_OUT_ZONES (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 FWDO_public  all  --  *      +       0.0.0.0/0            0.0.0.0/0           [goto]

Chain FORWARD_OUT_ZONES_SOURCE (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 FWDO_public  all  --  *      *       0.0.0.0/0            18.104.22.168/24      [goto]

Chain FORWARD_direct (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain FWDI_public (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 FWDI_public_log  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FWDI_public_deny  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FWDI_public_allow  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FWDI_public_allow (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain FWDI_public_deny (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain FWDI_public_log (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain FWDO_public (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 FWDO_public_log  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FWDO_public_deny  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 FWDO_public_allow  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain FWDO_public_allow (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain FWDO_public_deny (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain FWDO_public_log (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT_ZONES (1 references)
 pkts bytes target     prot opt in     out     source               destination
  112 11773 IN_public  all  --  +      *       0.0.0.0/0            0.0.0.0/0           [goto]

Chain INPUT_ZONES_SOURCE (1 references)
 pkts bytes target     prot opt in     out     source               destination
    5   372 IN_public  all  --  *      *       22.214.171.124/24       0.0.0.0/0           [goto]

Chain INPUT_direct (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain IN_public (2 references)
 pkts bytes target     prot opt in     out     source               destination
  117 12145 IN_public_log  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  117 12145 IN_public_deny  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  117 12145 IN_public_allow  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    3   252 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0

Chain IN_public_allow (1 references)
 pkts bytes target     prot opt in     out     source               destination
   93  7084 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            limit: avg 25/min burst 100
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443 ctstate NEW
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            udp dpt:123 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:88 ctstate NEW
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            udp dpt:88 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:636 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:53 ctstate NEW
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            udp dpt:53 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:389 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:7902 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:8014 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:7903 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:8089 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:463 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:7899 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:7898 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:7900 ctstate NEW
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            udp dpt:52311 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:7901 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:1584 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:1585 ctstate NEW
    0     0 ACCEPT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            udp dpt:463 ctstate NEW
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:22 ctstate NEW

Chain IN_public_deny (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain IN_public_log (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT_direct (1 references)
 pkts bytes target     prot opt in     out     source               destination
Comment: Did someone manually alter the firewall? Check with `iptables -nvL`
Comment: I see nothing here that would allow incoming traffic to port 4506. Exactly how are you testing this?
Comment: @Michael Hampton - Added the output to my question, but I'm not sure what to look for. I did not install this OS, so it's possible it was changed manually.
Comment: A simple "telnet  4506" from a Windows machine
Comment: I've also done a tcpdump on the server to validate that I am in fact hitting that port on that server. I did see traffic over port 4506.
Answer: This seems to be the rule that allows such traffic:
Chain IN_public_allow (1 references)
 pkts bytes target     prot opt in     out     source               destination
   93  7084 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            limit: avg 25/min burst 100

Starting from the INPUT chain:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
28874 7345K ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
  205 36869 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
  117 12145 INPUT_direct  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  117 12145 INPUT_ZONES_SOURCE  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  112 11773 INPUT_ZONES  all  --  *      *       0.0.0.0/0            0.0.0.0/0

Note INPUT_ZONES_SOURCE and INPUT_ZONES_SOURCE. INPUT_direct is empty so nothing before denied/rejected anything.
Chain INPUT_ZONES_SOURCE (1 references)
 pkts bytes target     prot opt in     out     source               destination
    5   372 IN_public  all  --  *      *       184.108.40.206/24       0.0.0.0/0

Chain INPUT_ZONES (1 references)
 pkts bytes target     prot opt in     out     source               destination
  112 11773 IN_public  all  --  +      *       0.0.0.0/0            0.0.0.0/0           [goto]

Both chains call IN_public. In this case the source is in 156.9.1220/24 so INPUT_ZONES_SOURCE is used. Had it not INPUT_ZONES would have been called with identical results. Basically INPUT_ZONES_SOURCE is doing nothing in this config but the presence of a [goto] in one could make a difference if the rules change.
Chain IN_public (2 references)
 pkts bytes target     prot opt in     out     source               destination
  117 12145 IN_public_log  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  117 12145 IN_public_deny  all  --  *      *       0.0.0.0/0            0.0.0.0/0
  117 12145 IN_public_allow  all  --  *      *       0.0.0.0/0            0.0.0.0/0

IN_public_log and IN_public_deny are empty so they do nothing. Thus IN_public_allow is reached:
Chain IN_public_allow (1 references)
 pkts bytes target     prot opt in     out     source               destination
   93  7084 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            limit: avg 25/min burst 100

All IPs and all tcp ports are accepted with some rate limits. Due to INPUT_ZONES this is true for all sources, not just 18.104.22.168/24 so things seem worse than you may have thought.
Disclaimer: programmatically generated iptables rules make my eyes bleed so I could very well be wrong.
Comment: I don't know. I have never used firewalld.
Comment: That doesn't look like it came from firewalld at all. Perhaps someone manually inserted it?
Comment: Thanks for the info, so do you know what I would need to do to fix it? Could it be fixed via firewall-cmd? I'm no iptables expert and agree this is spaghetti that I guess is generated via firewalld.
Comment: OK well in that case I think I'll probably disable firewalld and see if I can fix it with straight iptables from scratch. Appreciate the assist.
Comment: @Michael - Possibly. This OS was not installed by me, and I kind of feel like my best path is to back everything out and start over. I'm comfortable with both firewalld and iptables, but I'm not an expert with either. So I'm gonna clear the iptables rules, and copy the firewalld zones from a "clean" OS and start fresh. I can handle it from there. Thanks Michael and Mark.
Comment: Turns out the rule was in /etc/firewalld/direct.xml, possibly as part of a STIG of the OS.
Answer: In my testing, this rule provided by Redhat was invalid. Since the rule does not seem to be in the STIG documentation any more, I'm just removing it.
[root@d1dd-trdev-rv01 ~]#  cat /etc/firewalld/direct.xml
<?xml version="1.0" encoding="utf-8"?>
<direct>
<rule priority="0" table="filter" ipv="ipv4" chain="IN_public_allow">-p tcp -m limit --limit 25/minute --limit-burst 100 -j INPUT_ZONES</rule>
</direct>

[root@d1dd-trdev-rv01 ~]# firewall-cmd --reload
Error: COMMAND_FAILED: Direct: '/usr/sbin/iptables-restore -w -n' failed: iptables-restore: line 3 failed

Note that the below DID NOT WORK. leaving for reference.
I got confirmation today from Redhat that the rule @Michael Hampton pointed out was in fact from the /etc/firewalld/direct.xml, and it was a bug in the STIG documentation. The docs said to use this (note the ACCEPT)
<?xml version="1.0" encoding="utf-8"?>
<direct>
 <rule priority="0" table="filter" ipv="ipv4" chain="IN_public_allow">-p tcp -m limit --limit 25/minute --limit-burst 100 -j ACCEPT</rule>
</direct>

When you should be using this (note the INPUT_ZONES)
<?xml version="1.0" encoding="utf-8"?>
<direct>
 <rule priority="0" table="filter" ipv="ipv4" chain="IN_public_allow">-p tcp -m limit --limit 25/minute --limit-burst 100 -j INPUT_ZONES</rule>
</direct>

Comment: Did they publish a KB entry about it? Or fix the docs?
Comment: The RH guy said he'd seen it before and was trying to get DISA to change the STIG. When I was searching for a solution I found reference to the draft RH7 STIG, and when I looked at the current one (v2), I did not find an entry for this at all. So maybe they removed it for the time being.


Are there textbooks that include the fact that an isomorphism depends on the choice of a universe?

Question: I cannot remember much, so I apologise for the vague question in advance. I previously have glanced at being written that an isomorphism depends on the choice of a universe and so the concept of an isomorphism is not perfect as it of "a same". I would like to learn more about this fact, are there any textbooks that give a detailed description? Thanks in advance.
Comment: Your question is extremely vague to the point of being unanswerable. We don't even know isomorphisms of what you are talking about. Put yourself in the shoes of someone reading what you wrote: do you really think they would be able to know what you mean?
Comment: In what sense are you using the word "universe"? A possible interpretation is a category, and of course the notion of whether a map is an isomorphism depends on which category you are in.
Comment: @JackozeeHakkiuz I construe the meaning of a universe as a model of ZFC. If the source I have glanced at, however, use this word at a different meaning, I'm sorry.
Comment: Unfortunately, I don't remember much, so I think too those who can answer this question are only some people already know this fact. I wish I could explain more detail...
Answer: Yes, Wilfrid Hodges comments on this in his Model Theory:

Compare the two relations $\simeq$ (isomorphism) and $\equiv$ (elementary equivalence) between structures. In one sense isomorphism is a more intrinsic property of structures, because it's defined directly in terms of structural properties, whereas $\equiv$ involves a language. But in another sense elementary equivalence is more intrinsic, because the existence of an isomorphism can depend on
some subtle questions about the surrounding universe of sets. (p. 94)

He gives an example of vector spaces, which may not be isomorphic in a given model, but may "become" isomorphic in a forcing extension that collapses their cardinals into the same one. He also uses this to motivate the introduction of the back-and-forth technique as a relation that is intrinsic (not dependent on the universe of sets) and language-independent.
Comment: @beginner_nt - No worries. it just so happens that this passage had stricken me when I first read it, so it was easy to recall it in the context of your question.
Comment: @beginner_nt: If you are on a university or other institutional network, then you should be able to access the Hodges book here: http://dx.doi.org/10.1017/CBO9780511551574  If you don't have an institutional affiliation, you may be able to find it through SciHub.
Comment: That's exactly what I wanted to know. I appriciate your kindness which let you answer this extremely vague question. I will search for Wilfrid Hodges' Model Theory.


ERRO #1111 - Invalid use of group function (SUM | COUNT)

Question: Esta query dá-me o total de presenças de dois grupos parlamentares (e.g: PS, PSD) entre duas datas:
SELECT DISTINCT a.partido,

(SELECT COUNT(presencas.assiduidade) FROM presencas, reunioes
 WHERE presencas.assiduidade = 'Presença (P)'
 AND presencas.id_deputado = a.id_deputado
 AND reunioes.data_reuniao BETWEEN '2015-10-23' AND '2017-08-30'
 AND presencas.id_reuniao = reunioes.id_reuniao) AS total_presencas

FROM deputados a WHERE a.partido IN ('PS','PSD');

No entanto, queria somar o total de presenças por grupo parlamentar (e.g: PS, PSD) entre datas, mas a seguinte query dá-me erro:
SELECT DISTINCT a.partido,

(SELECT SUM(COUNT(presencas.assiduidade)) FROM presencas, reunioes
 WHERE presencas.assiduidade = 'Presença (P)'
 AND presencas.id_deputado = a.id_deputado
 AND reunioes.data_reuniao BETWEEN '2015-10-23' AND '2017-08-30'
 AND presencas.id_reuniao = reunioes.id_reuniao) as total_presencas

FROM deputados a WHERE a.partido IN ('PS','PSD');

Penso que este erro deve-se ás duas funções juntas SUM | COUNT.

1111 - Invalid use of group function

Podem ajudar-me?
A minha intenção é fazer algo como:
Comment: Só faltou você colocar o `group by`.
Comment: Não seria fazer um Sum de `assiduidade` agrupado por `partido` e `assiduidade`?
Answer: As funções de agrupamento como COUNT, SUM, AVG... dentre tantas outras, devem ser utilizadas com agrupamento de dados utilizando-se da cláusula GROUP BY, e tu não estás utilizando para definir como será o agrupamento e a contagem dos valores.
No teu caso, precisas de algo como:
SELECT deputados.partido, SUM(presencas.assiduidade) AS presenca
FROM deputados
JOIN presencas ON (presencas.id_deputado = deputados.id_deputado )
JOIN reunioes ON (presencas.id_reuniao = reunioes.id_reuniao)
WHERE presencas.assiduidade = 'Presença (P)'
AND reunioes.data_reuniao BETWEEN '2015-10-23' AND '2017-08-30'
AND deputados.partido IN ('PS','PSD')
GROUP BY deputados.partido

PS: Ao efetuar junções, dê preferência à utilização explícita de JOINs, deixe a cláusula WHERE para a filtragem necessária dos dados.


ODE computational ending issue

Question: After turning $y'$ = $\frac{(4y-3x)}{(2x-y)}$ into a homogenous equation and applying partial fractions, I get (and I rechecked the calculation, I don't think there's an error) $\frac{1}{4} ln\vert v-1\vert - \frac{5}{4} ln \vert v+3\vert = ln\vert{x}\vert + C$ where $v$ = $\frac{y}{x}$ and $C$ is a constant of integration.
Question is: what do I do from here to finish solving the equation? The solution manual says I should be getting $\vert{y-x}\vert = C \vert{y+3x}\vert^{5}$. But I have no idea how it got that from what I have.
Answer: Starting from
$$
\frac{1}{4} \ln\vert v-1\vert - \frac{5}{4} \ln \vert v+3\vert = \ln\vert{x}\vert + C
$$
Using properties of logarithm:
$$
\ln\vert v-1
\vert^\frac{1}{4}-\ln\vert v+3\vert^\frac{5}{4}=\ln\vert x\vert+\ln(C)\to\\
\ln\left(\frac{\vert v-1\vert^\frac{1}{4}}{\vert v+3\vert^\frac{5}{4}}\right)=\ln(C\vert x\vert)\to\\
\frac{\vert v-1\vert^\frac{1}{4}}{\vert v+3\vert^\frac{5}{4}}=C\vert x\vert
$$
Substitute $v=\frac{y}{x}$
$$
\frac{\vert \frac{y}{x}-1\vert^\frac{1}{4}}{\vert \frac{y}{x}+3\vert^\frac{5}{4}}=C\vert x\vert\to\frac{\vert \frac{y}{x}-1\vert}{\vert \frac{y}{x}+3\vert^5}=C^4\vert x\vert^4 \to \vert x\vert\left\vert \frac{y}{x}-1\right\vert=\left\vert \frac{y}{x}+3\right\vert^5C^4\vert x\vert^5\to\\
\vert y-x\vert=C^*\vert y+3x\vert^5
$$

ODE computational ending issue


How to add environment variables to app.json file

Question: I have an app.json file in my Expo project. In this file I have two API keys (labeled API_KEY below) that I'd like to hide via environment variables.
How can I go about using environment variables instead of hard coding the API keys?
app.json
{
  "expo": {
    "name": "Closeout",
    "slug": "Closeout",
    "version": "1.0.0",
    "orientation": "portrait",
    "privacy": "hidden",
    "notification": {
      "icon": "./assets/images/notification-icon.png",
      "color": "#000000",
      "iosDisplayInForeground": true
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": ["**/*"],
    "ios": {
      "icon": "./assets/images/icon.png",
      "buildNumber": "2",
      "config": {
        "googleMapsApiKey": "API_KEY"
      }
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/images/icon.png",
        "backgroundColor": "#000"
      },
      "versionCode": 5,
      "useNextNotificationsApi": true,
      "config": {
        "googleMaps": {
          "apiKey": "API_KEY"
        }
      },
      "googleServicesFile": "./google-services.json"
    }
  }
}

Comment: here you'll find an explanaition on this topic: https://stackoverflow.com/questions/48168369/cant-override-appsettings-json-settings-with-environment-variables/67719140#67719140
Comment: Did you come up with a solution?
Answer: I'm guessing you may have figured out a solution or tried something else by now. However, here is a solution to this issue, I hope it helps anyone facing the same challenge. This is from a typescript environment I'm implementing.
Create an app.config.ts file that overrides the content of the app.json file
import { ExpoConfig, ConfigContext } from '@expo/config';
import * as dotenv from 'dotenv';

// initialize dotenv
dotenv.config();

export default ({ config }: ConfigContext): ExpoConfig => ({
  ...config,
  slug: 'my-app',
  name: 'My App',
  ios: {
    supportsTablet: true,
    bundleIdentifier: 'com.croon',
    config: {
      googleMapsApiKey: process.env.GOOGLE_CLOUD_API_KEY,
    },
  },
  android: {
    adaptiveIcon: {
      foregroundImage: './assets/adaptive-icon.png',
      backgroundColor: '#FFFFFF',
    },
    package: 'com.croon',
    config: {
      googleMaps: {
        apiKey: process.env.GOOGLE_CLOUD_API_KEY,
      },
    },
  },
});

Then you could leave the API entry blank on the app.json file.
{
  "expo": {
    "name": "Closeout",
    "slug": "Closeout",
    "version": "1.0.0",
    "orientation": "portrait",
    "privacy": "hidden",
    "notification": {
      "icon": "./assets/images/notification-icon.png",
      "color": "#000000",
      "iosDisplayInForeground": true
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": ["**/*"],
    "ios": {
      "icon": "./assets/images/icon.png",
      "buildNumber": "2",
      "config": {
        "googleMapsApiKey": ""
      }
    },
    "android": {
      "adaptiveIcon": {
        "foregroundImage": "./assets/images/icon.png",
        "backgroundColor": "#000"
      },
      "versionCode": 5,
      "useNextNotificationsApi": true,
      "config": {
        "googleMaps": {
          "apiKey": ""
        }
      },
      "googleServicesFile": "./google-services.json"
    }
  }
}

Remember to install the required dependencies
Cheers!


Reescrita de URL no HTACCESS ignorando arquivos e pastas existentes

Question: Quando vou passar um site no servidor eu coloco um arquivo .htaccess com esse código abaixo:
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Esse código faz com que ao digitar o site:

www.dominio.com.br

Entre direto no index.php da pasta public do Laravel.
Mas agora está acontecendo um problema. Tenho um painel que está em uma pasta painel, fora da pasta public do Laravel, que é independente do Laravel.
Mas quando digito:

www.dominio.com.br/painel

Não entra.
E mesmo eu colocando a pasta painel dentro da pasta public, também não entra. Por causa do .htaccess dentro da pasta public.
Como posso deixar essa URL independente ?
Answer: Isto ocorreu porque você não fez a verificação se a pasta existe e um outro detalhe ao invés disto:
RewriteRule ^painel - [L]

Prefira isto:
RewriteRule ^painel/ - [L]

Sem a barra o .htaccess vai aceitar endereços como localhost/painel2 e supondo que ele seja uma rota ele se tornará inacessivel.
Voltando ao problema, provavelmente você fez algo semelhante a isto no teu .htaccess: https://pt.stackoverflow.com/a/91799/3635
Primeira solução
Deve estar usando semelhante a isto:
/home
  |--- /user
         |--- /public_html
                |--- .htaccess (seu .htaccess)
                |--- /public
                        |--- index.php
                        |--- .htaccess
                |--- /app
                |--- /bootstrap
                |--- /config
                |--- /database
                |--- /painel (pasta do painel)

Se quer que a pasta painel aqui seja acessivel o public_html/.htaccess deve ficar assim:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ public/ [L]

Segunda solução
No entanto o melhor é tudo fique dentro de public mesmo, então a estrutura seria assim das pastas sendo esta (public_html é uma pasta comum em servidores, pode ter outro nome como www), veja que mudei o local da pasta painel para dentro de public:
/home
  |--- /user
         |--- /public_html
                |--- .htaccess (seu .htaccess)
                |--- /public
                        |--- /painel (pasta do painel)
                        |--- index.php
                        |--- .htaccess
                |--- /app
                |--- /bootstrap
                |--- /config
                |--- /database

Então neste caso o arquivo public_html/.htaccess deve conter:
RewriteEngine On

RewriteRule ^ public/ [L]

E o arquivo public_html/public/.htaccess deve conter:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Terceira solução
Mas devo dizer uma coisa, você pode até usar o .htaccess pra apontar tudo para public, no entanto o melhor caminho é definir o DocumentRoot como sendo o public do Laravel ou então soltar o conteudo de public em public_html e as pastas dos laravel irão ficar fora, algo como:
/home
   |--- /user
         |--- /app
         |--- /bootstrap
         |--- /config
         |--- /database
         |--- public_html (conteúdo de public deve ficar nesta pasta)
              |--- /painel (pasta do painel)
              |--- index.php
              |--- .htaccess

Answer: Mano, esse SO é top.
Acho que tem algum poder que fica pairando por aqui... tem perguntas que eu faço aqui e pouco tempo depois, questão de minutos soluciono meu problema.
Como vocês conseguem ?
Pra deixar a URL 'independente' digitei assim:
RewriteRule ^painel - [L]

Ficando assim:
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteRule ^painel - [L]
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>


Partition $\lambda/\mu$ notation?

Question: When talking about two partitions $\lambda$ and $\mu$, what does the operation $$\lambda/\mu$$ mean? When Macdonald introduces partitions in the first chapter of "Symmetric functions and Hall polynomials", he defines addition, subtraction and multiplication of partitions - but no division. Nevertheless, he uses notation $\lambda/\mu$ later in the book. Any hint?
EDIT:
user254665 seems to suggest that $\lambda/\mu$ is basically the intersection of the two partitions in all of their elements. I.e. this would imply the following example

But I don't quite understand what \ $\{\phi\}$ is supposed to mean.
Comment: I haven't seen this but I would make  a guess:For  partitions of a non-empty set: For $S\in \lambda$ let $S/\mu=\{S\cap T : T\in \mu \}\backslash \{\phi\},$ and let $\lambda/\mu=\cup_{S\in \lambda}S/\mu.$  If this is wrong then what he says about $\lambda/\mu$ will probably  not make sense. If this is right, then it will.
Comment: $\phi$ is the empty set.
Comment: The only meaning of partition of a set $S$  that I know of, is a family $ F$ of pairwise-disjoint subsets of $S$ satisfying $\cup F=S$.  Sometimes, when $S$ is not empty, it is convenient that the empty set is not a member of $F$, and some authors  may include this as a  requirement in the def'n. If $S=\{1,2,3,4,5\}$ and $\lambda =\{ \{1,2,3\},\{4,5\}\}$ and $\mu=\{\{1,3,4\},\{2,5\}$ then $\cup_{s\in \lambda}S/\mu=$ $\{ \{1,3\},\{2\},\{4\}, \{5\}\}.$ As I said, see if this makes sense in the context of what is done in the book.
Comment: @user254665 Thank you for the answer. I have edited the question above. Did I understand your idea correctly? What does $\phi$ mean?
Answer: The symbol $\lambda / \mu$ is the standard notation for a skew shape.
The shape of a partition can be thought of as a geometrical arrangement of boxes (I use o's here).  For example, $\lambda = (5,3,2,1)$ is
<code>o o o o o
o o o
o o
o
</code>
Now if $\lambda$ and $\mu$ are 2 partitions such that $\mu_i \le \lambda_i$ for all $i$, then $\lambda/\mu$ is a skew shape, obtained by removing the shape $\mu$ from the shape $\lambda$.  For example, if $\lambda$ is as above, and $\mu = (4,2,1)$, then $\lambda/\mu$ is the following, where the dots denote removed boxes that are not part of the shape.
<code>. . . . o
. . o
. o
o
</code>
Comment: Thank you for the link and explanation! It is a bit weird, since Macdonald calls this operation $\theta=\lambda-\mu$ and not $\lambda/\mu$ in the book. He still uses the $\lambda/\mu$ notation also. I guess it is an abbreviation for $\lambda-\mu$?

Partition $\lambda/\mu$ notation?


how to limit the ouput of get_all_images in amazon boto?

Question: I tried to load list of AWS images using Python boto library. My code looks like this:
con = boto.connect_ec2(user, pasw)
images_list = con.get_all_images()

How do I get only the first 10 results from the function get_all_images()?
I'm looking for something like con.get_all_images(maxresult=10).
Answer: As you can find out from the boto documentation you cannot directly limit the amount of images returned by that function. It's lacking the API support (see the link below), it's not exactly a boto's issue.
Filtering
You can pass a filters parameter though if you want to limit the results based on some specific attributes of those images.

filters (dict) – Optional filters that can be used to limit the results returned. Filters are provided in the form of a dictionary consisting of filter names as the key and filter values as the value. The set of allowable filter names/values is dependent on the request being performed. Check the EC2 API guide for details.

For example
c.get_all_images(filters={'architecture': 'x86_64'})

Supported attributes can be found in the AWS documentation.
Limiting
The function returns a list so if you really just need to limit the number of results, I'd do this:
images = con.get_all_images()[:10]

Caveats
Keep in mind that the API does not guarantee any specific order (at least it's not documented), so your first 10 images may differ in time.
If you have too many images, it might be also eating up memory, so I'd really suggest filtering it by some attributes if you can.
Answer: If you only want your images, you need to specify the owners parameter.
Also of note, the name accepts wildcards, if you want to filter based on the image names:
images = ec2Connection.get_all_images(owners = ['self'], filters = {'name':'*image*'})

Answer: My two cents to find images that have a specific string in the name tag , based on storm_m2138's answer:
amis = EC2conn.get_all_images(
    filters={
        "tag-key":"Name",
        "tag-value":"*some_string"
    }
)


TBS tiny but strong: how to recursively fill in data

Question: I use openTBS to parse an invoice template. The invoice address is supplied via a custom function. I would like to conditionally more information to the filled in data.
I was thinking of permitting the invoice address (the filled in data) to contain another TBS field, e.g. for a person to speak to, and have TBS re-parse the form. In other words, can I make TBS parse a template twice if the first run supplies a new TBS field?
Example:
[abk.invoiceaddress]
--- is replaced with -->
ACME inc.
[abk.person]
Somestreet 123
Somecity 54321

--- should be replaced with -->
ACME inc.
Mr. Knowitall
Somestreet 123
Somecity 54321

There seems to be no option for recursive replacement and calling MergeField() twice does not have the desired effect.
Answer: By default, TBS prevents from TBS fields injection when merging data.
Otherwise it could be a security issue.
By default, if the data is:

ACME inc. [abk.person] Somestreet 123 Somecity 54321

then it will be merged as:

ACME inc. &#91abk.person] Somestreet 123 Somecity 54321

The string &#91 is the unicode for [, so this is not visible for lot of templates.
But you can lift this protection using parameter protect=no
See https://www.tinybutstrong.com/manual.php#html_field_prm_protect
Comment: Thanks very much, Skrol. I tried this with ```[abk.invoiceaddress;protect=no]```. To be sure, I also set ```$TBS->setOption('protect', false);``` in my script. Still, I cannot get recursive merging to work. Drilling into the generated DOCX file I see the plain '[' character in document.xml. Can it have to do with openTBS or the fact that I use MergeField() with my own callback function?
Comment: you have to merge 'abk' ( MergeFields() or MergeBlock() ) twice, once for the fields in the template, once more for those appeared by the data


Ideal generated by $v\otimes v - \Phi(v)1$

Question: I'm trying to understand the proof of the existence of a Clifford algebra. Let $V$ be a vector space over $\mathbb{K}$, $\varphi: V\times V \to \mathbb{K}$ a bilinear form and $\Phi(v) = \varphi(v,v)$ its associated quadratic form. The prove existence of a Clifford algebra, one takes the quotient of the tensor algebra $T(V)$ with the ideal generated by elements of the form $v\otimes v - \Phi(v)1$, $v \in V$ and $1 \in \mathbb{K}$.
I don't have background in algebra, so I'd like to know what exactly is "the ideal generated by elements of the form $v \otimes v - \Phi(v)$". Also, is this the same as the ideal generated by $u\otimes v + v\otimes u - \varphi(u,v)1$ (which is also found in some references)?
Comment: Do you know what an ideal in a commutative ring is, or what the ideal in a commutative ring generated by $a$, $b$, and $c$ means?
Answer: In general, if $A$ is an algebra, and $S$ is a subset, then the ideal generated by $S$, is the smallest ideal $I_{S} \subseteq A$ that contains $S$.
In this specific case, the set $S$ is
\begin{equation*}
 S = \{ v \otimes v - \Phi(v)1 \in T(V) \mid v \in V \}.
\end{equation*}
One way to get your hands on $I_{S}$ in this case is to simply set
\begin{equation*}
 I_{S} = \{ a \in T(V) \mid \exists (b_{i},b_{i}' \in T(V), s_{i} \in S): a = \sum_{i} b_{i}s_{i}b_{i}' \}.
\end{equation*}
To answer your question about the relation to the other ideal, we'd have to consider
\begin{equation*}
 S' = \{ u \otimes v + v \otimes u - 2\varphi(u,v)1 \mid u,v, \in V \}
\end{equation*}
and show that $I_{S} = I_{S'}$.
(You definitely need the factor 2, just consider the case $v=u$.)
So, let $V$ and $\varphi$ be as you stated, and let's define $\mathrm{Cl}(V)$ to be algebra $T(V)/I_{S}$.
Now we'd like to prove that this satisfies the universal property.
To that end, let $A$ be an associative, unital algebra, and let $f: V \rightarrow A$ be an arbitrary map.
Then, the map $f: V \rightarrow A$ extends to an algebra homomorphism $F: T(V) \rightarrow A$.
Now, suppose that $f$ was in fact a Clifford map, i.e.,
\begin{equation*}
 f(v)^{2} = \Phi(v) 1_{A},
\end{equation*}
for all $v \in V$.
One can use this equation that the map $F: T(V) \rightarrow A$ vanishes on the ideal $I_{S}$, and thus descends to an algebra homomorphism $T(V)/I_{S} = \mathrm{Cl}(V) \rightarrow A$.
If you want to know more about Clifford algebras, I strongly recommend the first chapter of Lawson & Michelsohn's Spin Geometry.
Comment: Very nice answer! Right to the point! Thanks!
Comment: @IamWill I was a bit sloppy, the way I set it up you might end up with something that's not a subspace! You really have to take sums.
Answer: @Peter's answer is great for your specific case, but some insight on the more general algebraic construct you're dealing with should help, I think, because it helped me a lot back in the day.
I think the concept you are lacking is the idea of "an algebraic quotient by an equivalence class", and how this is linked to ideals of rings.
I'll take it that you're familiar with the very basics of set theory/abstract algebra/category theory: ie, that you at least know what an equivalence relation, a partial order, a binary operator, closure, associativity, identity, invertibility, commutativity, a monoid, a group, a ring, a field, a vector space, and a $\mathbb{K}$-algebra are. [If you're not acquainted with each of these concepts, I've written a concise introduction to this subject that might interest you, and that's freely available online; but such introductions abound on the web in any case.]
An ideal is a particular subset of a ring (or a $\mathbb{K}$-algebra, which is very similar to a ring). Ideals are special because they are subsets of a ring that are closed (stable) under both addition and multiplication. This gives them some important properties. Ideals of a ring $R$ are generally expressed as a set $eR = \{ e * r \; | \; r \in R \}$ (note that in non-commutative rings, you have to distinguish left-ideals from right-ideals). Thus, an ideal can generally be understood as "the set of multiples of $e$ in $R$". For example $4\mathbb{Z} = \{\dots, -8, -4, 0, 4, 8, \dots\}$, and $(x^2 + 1)\mathbb{R}[X]$ is the set of all polynomials which you can factor by $(x^2 + 1)$ (all polynomials that have $i$ and $-i$ amongst their list of roots).
One very important property of ideals is that they separate a ring into a "subspace" (the ideal itself; which is not exactly a ring, because it lacks the multiplicative identity in general) and a list of "affine subspaces" (the ideal plus some element of the ring) which are parallel to the "subspace".  For example,
$4\mathbb{Z} = \{\dots, -8, -4, 0, 4, 8, \dots\}$
$4\mathbb{Z} + 1 = \{\dots, -7, -3, 1, 5, 9, \dots\}$
$4\mathbb{Z} + 2 = \{\dots, -6, -2, 2, 6, 10, \dots\}$
$4\mathbb{Z} + 3 = \{\dots, -5, -1, 3, 7, 11, \dots\}$
$4\mathbb{Z} + 4 = 4\mathbb{Z}$
With this, we can define an equivalence relation over elements of the base ring (here $\mathbb{Z}$), based on any ideal: we consider any element to be equivalent if they are in the same affine space for that ideal. This is expressed algebraically as $e \sim f \Leftrightarrow e - f \in I$, where I is the ideal. The "algebraic quotient of a ring by an ideal" is then the homomorphism mapping an element of the input ring to its equivalence class. The output set, generally written $R/e$ or $R/eR$, has the same number of elements as there were "subspaces". $\mathbb{Z}/4\mathbb{Z}$ is obtained by mapping $\mathbb{Z}$ via the "modulo $4$" operator (the remainder of the Euclidean division by four); it is a space which functions like a clock with $4$ hours. $\mathbb{R}[X]/(x^2 + 1)$ is isomorphic to $\mathbb{C}$. The kernel of this homomorphism is ALWAYS the ideal itself.
Algebraic quotients come up all over mathematics; everywhere you see an equivalence relation. They're not limited to rings. Parallelism is an equivalence relation, and for example, taking the set of lines $\mathbb{R}^2$, and quotienting it by parallelism, you'll get a "looping half-circle" isomorphic to $S^1$. You can define the $u - v \in W$ equivalence relation for any subspace $W$ of any vector space $V$. Most spaces you'll see have their "most elegant construction" done through algebraic quotients. Generally, you use a free functor to "get an abstract block of marble" from some other structure (for example, the free functor from $Vect_\mathbb{K}$ to $Alg_\mathbb{K}$, which turns a vector space into its tensor algebra, which is the "least specific/most general way" of building an algebra from a vector space) and then you use algebraic quotients to "inject desired mathematical properties" into your quotient space (for example, the ideal generated by the elements of the form $a \otimes b + b \otimes a = 0$ injects anticommutavity into your tensor algebra over $V$; turning into the exterior algebra over $V$).
In the case of $\mathbb{R}[X]/(x^2 + 1)$, there's "only one element of the form $(x^2 + 1)$", the polynomial $I = x^2 + 1$; but this also means every polynomial which is a multiple of $I$ is part of the kernel; so in $\mathbb{R}[X]/(x^2 + 1)$, any $Q = (x^2 + 1)P = 0$. This makes the property $x^2 + 1 = 0$ be injected into $\mathbb{R}[X]$. Consequently, there exists at least one element $i$ such that $i^2 + 1 = 0$.
Now, in your case, you have an ideal generated by multiple elements, but the principle is the same. For every vector $v$ in $V$, you're going to inject the property that the "abstract, propertyless (safe for bilinearity)" multiplication of the tensor algebra must respect $v \otimes v = \Phi(v)$ (ie, the product of two vectors is a globally defined quadratic, euclidean (pseudo)norm). It is equivalent, @Peter shows, to defining the (pseudo)norm via the use of a (generalized) inner product (ie, $u \otimes v + v \otimes u = \phi(u,v)$).


difference-in-differences with fixed effects

Question: I have two questions related to having fixed effects in the DD model.
I have a treatment that occurs at different times (e.g., 2001, 2005, etc.).
I want to fit a DD model, so I standardize the treatment years to year "0" as the the treatment time. To control for treatment year heterogeneity, I included the true year fixed effects.
$y_{it} = \beta_0 + \beta_1 \text{Treat} + \beta_2 \text{After} + \beta_3 (\text{Treat $\cdot$ After}) + \eta (\text{Year Fixed Effects})+ \gamma C_{it} + \epsilon_{it}$
Question 1:
Is there anything wrong with this model?
Question 2:
Is there an issue with including time-constant fixed effects to this DD model? For example, what if I include i-level fixed effects ($\alpha_i$) and/or group indicators of i fixed effects (e.g. male/female or race)? I realize that DD cancels out time-constant i-lvl FE, but what if I include it here again?
Answer: The model is fine but instead of standardizing the treatment years there is an easier way to incorporate different treatment times in difference in differences (DiD) models which would be to regress,
$$y_{it} = \beta_0 + \beta_1  \text{treat}_i + \sum^T_{t=2} \beta_t \text{year}_t + \delta \text{policy}_{it} + \gamma C_{it} + \epsilon_{it}$$
where $\text{treat}$ is a dummy for being in the treatment group, $\text{policy}$ is a dummy for each individual that equals 1 if the individual is in the treatment group after the policy intervention/treatment, $C$ are individual characteristics and $\text{year}$ are a full set of year dummies. This is a different version of the DiD model that you stated above but it does not require standardization of treatment years as it allows for multiple treatment periods (for an explanation see page 8/9 in these slides).
With regards to the second question you can include time-invariant variables at the individual level. You cannot add them at the group level (treatment vs control) because these will be absorbed by the $\text{treat}$ dummy. You can still include individual control variables like gender but note that they do not play a mayor role in DiD analyses. Their only benefit is that they may reduce the residual variance and hence increase the power of your statistical tests (see slide 8 here).
Comment: You need panel data for difference in differences because you require a pre- and post-treatment period. The treatment effect is $\delta$, the implicit assumption is that the treatment effect is constant over time but this can be relaxed if needed.
Comment: @user001 you can interact your treatment variable with the time fixed effects (leaving out one interaction as the baseline). The time interactions for periods before the treatments happen should be insignificant (the treatment can't have an effect before it even happens, otherwise sth is wrong) and the post-treatment time indicator interactions will estimate the fade-out time of the treatment. Somewhere I have given a similar answer which shows the regression specification for this.
Comment: Andy, can you give some ideas on how to relax the implicit assumption that the effect is consistent over time?
Comment: why there is no interaction term between policy and after term?
Comment: does this apply to cross-sectional data set. And how do we determine the treatment effec from the model you stated.
Comment: Andy, I have a related question, what if I don't observe each individual in each time period. Let's say, I start with 10.000 individuals but number of individuals in the sample increases over time ?


Open Virtual Machine Genymotion Network error

Question: Error when open Virtual Device Nexus 7 android 5.0 API 21
Comment: http://stackoverflow.com/questions/18641423/not-able-to-start-genymotion-device
Comment: May be this can help. Start Virtual Box, there you will see devices (genymotion devices). Select the device you want and click start...Then a black screen (like cmd appears) .Then open genymotion and start the same device.
Comment: I can't start device in virtualbox i got 1 error "This kernel requires an X86CPU, but only detected an i686 CPU"
Answer:  If you have tried above solution and still in trouble then enable the Virtuaization in your BIOS. This error occurs if you have not Enabled virtualization in your BIOS.Please Check over it once :) :)
Comment: Yes Niroj thapa when I Enabled virtualization in my BIOS , I got one error
"This kernel requires an X86CPU, but only detected an i686 CPU".
Comment: Download the correct installtion file... you downloaded a 64 bit version but have a 32 bit system. My best guess is that you somehow configured the VM for 32 bit execution instead of 64.
Comment: Thank for your help


Out of memory error when trying to allocate memory mapped INDArray

Question: I'm trying to allocate a large memory-mapped 2d array that's larger than RAM and it keeps failing with an out of memory error.  I'm using java8, linux-amd64 and nd4j 1.0.0-beta4.  My understanding according to the docs (https://deeplearning4j.org/docs/latest/deeplearning4j-config-memory) is that I should be able to allocate an array that is much larger than RAM, as it will use a temporary file and then rely on the OS to page that in as required (e.g. using mmap)
Update  - I'm getting some intermittent successes after a reboot - I'm wondering if there's some base amount of RAM needed for housekeeping for the large array allocation routine?  Maybe the zeroing?  I'll report back...
I've tried some different policy options, made sure there's enough disk free where the temp file goes, and done a wee bit of debugging to see what's going on the bowels of the memory allocation code, but to no avail.  It always seem to fail complaining that there's not enough physical memory - which is sort of correct, there isn't enough RAM to do this, that's the point
long cols = 3000;
long rows = 1000000;

long expectedSize = 4 * cols * rows;
this.nd4jWorkspaceManager = Nd4j.getWorkspaceManager();
this.workspaceConfig  = WorkspaceConfiguration.builder()
    .initialSize(expectedSize)
    .policyLocation(LocationPolicy.MMAP)
    .policyAllocation(AllocationPolicy.OVERALLOCATE)
    .policySpill(SpillPolicy.EXTERNAL)
    .tempFilePath(System.getProperty("user.home") + "/.nd4jtmp")
    .build();

System.out.format("Attempting to create workspace of size %s%n", formatBytes(expectedSize));
this.memoryWorkspace = Nd4j.getWorkspaceManager().getAndActivateWorkspace(workspaceConfig, "M2");
System.out.println("... Done");

System.out.format("Attempting to create array of size %s%n", formatBytes(expectedSize));
INDArray matrix = Nd4j.create(DataType.FLOAT, rows, cols);
System.out.println("... Done");

System.out.format("Populating array with random numbers...%n");

for (int i = 0; i < rows; i++) {
  for (int j = 0; j < cols; j++) {
    matrix.put(i, j, (float) Math.random());
  }
}

System.out.println("... Done");

Here's the output to free,
$ free
              total        used        free      shared  buff/cache   available
Mem:        7852420     2950656      120860      311200     4780904     4067768
Swap:       7811068      190632     7620436

I run the main method and it fails to allocate the array with:
09:14:36,476 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
09:14:36,477 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
09:14:36,477 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/home/nickg/src/riskscape/riskscape/cli/bin/main/logback.xml]
09:14:36,478 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs multiple times on the classpath.
09:14:36,478 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [file:/home/nickg/src/riskscape/riskscape/test-shared/bin/main/logback.xml]
09:14:36,478 |-WARN in ch.qos.logback.classic.LoggerContext[default] - Resource [logback.xml] occurs at [file:/home/nickg/src/riskscape/riskscape/cli/bin/main/logback.xml]
09:14:36,786 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set
09:14:36,790 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
09:14:36,797 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDERR]
09:14:36,909 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting level of logger [nz.org.riskscape] to WARN
09:14:36,909 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDERR] to Logger[nz.org.riskscape]
09:14:36,909 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to ERROR
09:14:36,910 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDERR] to Logger[ROOT]
09:14:36,910 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
09:14:36,912 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@6950e31 - Registering current configuration as safe fallback point

Attempting to create workspace of size 11.18gb
... Done
Attempting to create array of size 11.18gb
Exception in thread "main" java.lang.OutOfMemoryError: Cannot allocate new LongPointer(8): totalBytes = 1, physicalBytes = 3779M
    at org.bytedeco.javacpp.LongPointer.<init>(LongPointer.java:76)
    at org.bytedeco.javacpp.LongPointer.<init>(LongPointer.java:41)
    at org.nd4j.linalg.api.buffer.BaseDataBuffer.<init>(BaseDataBuffer.java:407)
    at org.nd4j.linalg.api.buffer.LongBuffer.<init>(LongBuffer.java:81)
    at org.nd4j.linalg.api.buffer.factory.DefaultDataBufferFactory.createLong(DefaultDataBufferFactory.java:478)
    at org.nd4j.linalg.api.buffer.factory.DefaultDataBufferFactory.createLong(DefaultDataBufferFactory.java:473)
    at org.nd4j.linalg.factory.Nd4j.createBufferDetached(Nd4j.java:1449)
    at org.nd4j.linalg.api.shape.Shape.createShapeInformation(Shape.java:3241)
    at org.nd4j.linalg.api.ndarray.BaseShapeInfoProvider.createShapeInformation(BaseShapeInfoProvider.java:76)
    at org.nd4j.linalg.cpu.nativecpu.DirectShapeInfoProvider.createShapeInformation(DirectShapeInfoProvider.java:65)
    at org.nd4j.linalg.cpu.nativecpu.DirectShapeInfoProvider.createShapeInformation(DirectShapeInfoProvider.java:49)
    at org.nd4j.linalg.api.ndarray.BaseNDArray.<init>(BaseNDArray.java:232)
    at org.nd4j.linalg.api.ndarray.BaseNDArray.<init>(BaseNDArray.java:343)
    at org.nd4j.linalg.cpu.nativecpu.NDArray.<init>(NDArray.java:185)
    at org.nd4j.linalg.cpu.nativecpu.CpuNDArrayFactory.create(CpuNDArrayFactory.java:189)
    at org.nd4j.linalg.factory.Nd4j.create(Nd4j.java:4651)
    at org.nd4j.linalg.factory.Nd4j.create(Nd4j.java:4129)
    at NDArrayAllocationTest.run(NDArrayAllocationTest.java:40)
    at NDArrayAllocationTest.main(NDArrayAllocationTest.java:14)
Caused by: java.lang.OutOfMemoryError: Physical memory usage is too high: physicalBytes (3779M) > maxPhysicalBytes (3410M)
    at org.bytedeco.javacpp.Pointer.deallocator(Pointer.java:585)
    at org.bytedeco.javacpp.Pointer.init(Pointer.java:125)
    at org.bytedeco.javacpp.LongPointer.allocateArray(Native Method)
    at org.bytedeco.javacpp.LongPointer.<init>(LongPointer.java:68)
    ... 18 more

Comment: How much RAM and how much swap does the machine have?  What does the `free` command print out?  Temp space is not relevant here AFAIK.
Comment: I'm trying to go outside of RAM by using memory mapped files (https://deeplearning4j.org/docs/latest/deeplearning4j-config-memory), so my understanding is that disk space is relevant.  I'll edit the question to put those details in as well and clarify.
Answer: It looks like it was just a house-keeping thing.  I confirmed that the mmaped file was being used for my NDArray, the OOM was happening when allocating some buffer for the array's shape.  After setting org.bytedeco.javacpp.maxphysicalbytes to be big enough, the NDArray successfully builds.
I'm not really sure why this works and why it's necessary, but there we go.  The long buffer that it's failing to allocate is only about 8 longs in length...  - perhaps the mmap'd file is skewing the processes reported memory size?
If there's anyone who knows more about ND4J's memory management who can comment, please comment.


Having issues passing counts in my scheduler function

Question: I'm working with the schedule package built by Dan Bader and I'm not sure how to pass a counter into the package.
Here is the basic example of how this is used:
def job(message="stuff"):
    print("I'm working on:", str(message))

schedule.every(10).seconds.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

So this prints I'm working on: stuff every 10 seconds which is great but what its missing for my application is a counter. I'd like to count every time a job is run and pass that into my function but I haven't been able to figure that out.
This was my latest attempt:
def job(count = 0):
    print(count)

count = 0

schedule.every(10).seconds.do(job, count)

while True:
    schedule.run_pending()
    time.sleep(1)
    count += 1

I thought that having count as a parameter and looping it within the while loop would work but it did not.
At the end of the day, I need a platform that will allow me to constantly run a function at some interval and keep track of how many times the job has run.
Any help would be much appreciated
Answer: Well, not sure it's the more obvious way, but I would do something like
import schedule
import time

class Count(object):

    def __init__(self):
        self._count = 0

    def __str__(self):
        count = self._count
        self._count += 1
        return str(count)

def job(count):
    print(count)

count = Count()
schedule.every(1).seconds.do(job, count)

while True:
    schedule.run_pending()

Count's instance just increment itself when printed, so if you are sure to print it only in job you keep track of how many times it was ran.
The only real pro VS the dict solution is you don't have to compute anything in job - count handles itself alone.

 Edit
Since some SO folks seems to like my idea even if (and that's clearly true) it hide some functional aspects of the counter (nobody expect to handle an instance that increment an integer when printed) here is a little update that makes it less tricky, less confusing, in brief: better.
class CountLogger(object):

    def __init__(self):
        self._count = 0

    def log(self, message = ''):
        print('{}: {}'.format(self._count, message))
        self._count += 1

It does almost the exact same thing, but calling CounterLogger.log() to see an integer getting incremented is less puzzling.
Just replace print(count) by count.log().
Comment: I like the idea :) Though, in a larger project, I'd be careful with it, because it hides a significant portion of the functionality. Just one single string conversion to many, for whatever reason ... screws things up pretty badly.
Comment: This works for the most part but what if I needed to use that count in some calculation.
Comment: Well, you can with both solution I proposed: `count._count` gives you access to the integer value of the counter. So after the `while True` you can make compute
Comment: Its a string value that I can't seem to change. Sorry, I don't use classes that often so I may be missing something simple.
Comment: No, it's an integer, you can update it: `count = CountLogger(); count._count = 100; count.log()` will output `100:`.
Answer: You can use a mutable object like a dictionary to achieve what you want. (Your original count variable is an integer, which is NOT mutable in Python.) The following works:
import schedule
import time

store = {'count': 0}

def job(data):
    data['count'] += 1
    print(data['count'])

schedule.every(10).seconds.do(job, store)

while True:
    schedule.run_pending()
    time.sleep(1)


Setting up catching event in directive

Question: I have a directive for flashmessages
'use strict';

angular.module('diplomovaPraceFrontendApp')
.directive('flashMessages', () ->
    directive:
        restrict: 'E'
        replace: true
        template: '
' +
                    '
' +
                    '{{m.text}}' +
                    '
' +
                    '
'
        controller: ($scope, $rootScope) ->
            $rootScope.$on('flash:message', (_, messages, done) ->
                $scope.messages = messages
                done()
        )
)

and when I call in my controller $rootScope.$emit('flash:message', messages, someFunction); it isn't caught by $rootScope.$on() set up in directive, although if I put this in application.run() it works correctly.
Any ideas what I'm missing? Thanks for any advice
I have edited the question:
I do of course use an shared service, here's my code http://pastie.org/private/es25rvo0zvejuw9yx3acja (sorry, gist.github.com seems to be broken for me atm)
I was following this tutorial http://chiragchamoli.com/post/61277736964/building-a-flash-message-with-angular-js
Though it seems it doesn't call the directive at all, since replace is set to true and I still see <flash-messages> in code inspector.
Plunkr version: http://plnkr.co/edit/buRaguEyTMuhUM9Z4Jsw?p=preview
Answer: I already gave a fix in #angularjs earlier, but here it is for posterity:
http://plnkr.co/edit/Fb9FYSXgU0t93w7i2B8q?p=preview
The problem is that MainCtrl is instantiated before the directive, so the $scope event gets fired before the directive sets a listener on $scope, so the directive never gets the event listened to here.
Answer: The problem is that your non directive controller function is called before the directive controller. Thus, the message is being sent before the the directive has registered for alerts.
A simple solution to this would be, instead of using events, use a shared service. Services are singletons, so any state is shared between all usages of that service. Using a service only makes sense if your all of your flashMessage directives need a shared state. If this solution does not fit your needs, help me better understand your requirements.
Working plunker
Javascript:
var app = angular.module('plunker', [])

.controller('MainCtrl', function ($scope, alertsService) {
    alertsService.add({
        text: 'I am an alert',
        level: 'high'
    });
})

.service('alertsService', function () {
    this.alerts = [];
    this.add = function (message) {
        this.alerts.push(message);
    }.bind(this);
})

.directive('flashMessages', function (alertsService) {
    return {
        restrict: 'E',
        replace: true,
        template: '
' +
            '
' +
            '{{m.text}}' +
            '
' +
            '
',
        scope: true,
        link: function ($scope) {
            $scope.messages = alertsService.alerts;
        }
    };
});

HTML:

    <flash-messages></flash-messages>

Setting up catching event in directive


How to instal Aegir without root access

Question: The Aegir documentation states that root access is required for installation, but I have seen comments suggesting it is possible to instal without root.
If this is correct can anyone point me in the right direction?
Background:
I host a few non profit sites with an Aegir service provider who has provided great service. But the sites have grown and the cost has become a challenge for them. I don't have the skills for a self-managed server, so I am hoping to be able to find someone to instal on a fully managed server where someone else can maintain it and keep it secure etc.
Answer:
The Aegir documentation states that root access is required for
installation, but I have seen comments suggesting it is possible to
instal without root. If this is correct can anyone point me in the
right direction?

In addition to the installation and configuration of web and database servers, the standard installation of Aegir requires the creation of a user account and the deployment of one or more sudoers files.
While I'm sure there are creative ways to work around some of this, each step down that path gets you further and further from a standard setup. The more bespoke your deployment becomes the more time and effort will be required to ensure its security and reliability.
I highly recommend against pursing this path.

I host a few non profit sites with an Aegir service provider who has
provided great service. But the sites have grown and the cost has
become a challenge for them.

Have you offered to cover the costs for your current Aegir service provider to scale up their hardware, move your sites to a dedicated server, etc.? This is likely to be the most cost-effective approach, since they're presumably already tooled up for the deployment and management of Aegir servers.
Comment: Thanks for the guidance, especially about avoiding a non-standard setup.. I'm talking to a couple of service providers who may be able to help.

How to instal Aegir without root access


django sphinx search always get none from query

Question: i using this part of code to getting docs from sphinx but sphinx Query always return None. But if i execute code from command line i get correct result, what wrong?
def search_query(query, offset=0):
    mode = SPH_MATCH_EXTENDED
    host = 'localhost'
    port = 9312
    index = 'rss_item'
    filtercol = 'group_id'
    filtervals = []
    sortby = '-@weights'
    groupby = 'id'
    groupsort = '@group desc'
    limit = 30

    # do query
    cl = SphinxClient()
    cl.SetServer ( host, port )
    cl.SetWeights ( [100, 1] )
    cl.SetMatchMode ( mode )

    #cl.SetSortMode(SPH_SORT_TIME_SEGMENTS)
    if limit:
        cl.SetLimits ( offset, limit, max(limit,1000) )
    res = cl.Query ( query, index )

    docs =[]
    for item in res['matches']:
        docs.append(item['id'])

    return docs

# this is django view
def search(request):
    q = request.GET.get('q', '')
    offset = int(request.GET.get('older', 0))
    docs=search_query(q, offset)

    result = Item.objects.filter(id__in=docs).all()

    objects = dict([(obj.id, obj) for obj in result])
    sorted_objects = [objects[id] for id in docs]

    result = sorted_objects

    return render_to_response('rss/_items.html',
                              {'latest_items':result, 'offset':offset+30,'q':q},
                              context_instance=RequestContext(request))

Server : centos6, sphinx: 2.0.5, django: 1.4.2 , apache/wsgi
Answer: resolve issue, by turn Selinux OFF and restart server, i listen to apache process by this command:
ps auxw | grep httpd | awk '{print"-p " $2}' | xargs strace

and see permission denied for access apache to sphinx and memcache


Find the function given the equation $(g \circ f)(x) = x + 5$

Question: Let $g(x) = 4x + 1$.
Find $f(x)$, given that the equation $(g \circ f)(x) = x + 5$ is true for all values of $x$.
From my text, it looks like this would be expressed as $g[f(x)]$, but I don't see how you can determine the definition of $f(x)$. Do I need to assume a value of x and work backwards through the problem?
Answer: $(g\circ f)(x) = g(f(x))$.
So you know that $g(a) = 4a+1$, no matter what $a$ is. I particular, that means that
$$(g\circ f)(x) = g\bigl(f(x)\bigr) = 4(f(x)) + 1.$$
Now, you want $(g\circ f)(x) = x+5$, so that means that whatever $f(x)$ is, you want
$$4(f(x)) + 1 = x+ 5.$$
Can you figure out what $f(x)$ should be for this to be true?
Comment: @erimar77 Also, in general, there are other issues to consider other than $x$ being in the denominator. You should pay extra attention whenever $x$ is in the denominator, $x$ is in an odd radical, or $x$ is in a logarithm.
Comment: Yes, this simplifies to f(x) = (x+6) \ 4, which "is" true for all values of x because x is not in the denominator.
Comment: @erimar77 You mean $\frac{x+4}{4}$.
Answer: f(x)= (X+4)/4
This is how I got it:
4(f(x))+1=x+5
4(f(x))+1-1=x+5-1
4(f(x))=x+4
(4(f(x)))/4=(x+4)/4
(f(x))=(x+4)/4
So the x that would make the equation true is (x+4)/4


How to Interpret p-value from multi-curve Kaplan-Meier Graph

Question: I've generated a few KM graphs from TCGA data. I am unsure of what the p-value provided by the function and the graphed chart indicates. I just looked through the survival.pdf from cran but am still unsure.
I currently believe that the p-value indicates with a 0.95 confidence that there is statistically significant variance of survival probabilities over time between the curves.
Here is a representative graph:

I think the relevant code snippets are:
<code>survival_object <- Surv(time = cesc_survival_data$survival_time, event = cesc_survival_data$survival_status)
#Fit the survival data to a curve that is defined by the quartiles of zscore SLC2A2
quartiles_SLC2A2_expression_survival_curve <- survfit(survival_object ~ zscore_value_SLC2A2_quartile, data = cesc_survival_data)
#Generate a graph of survival object/expression quartile curve of zscore SLC2A2 median quartiles
ggsurvplot(quartiles_SLC2A2_expression_survival_curve, data = cesc_survival_data,
           #conf.int = TRUE,
           pval = TRUE,
           fun = "pct",
           risk.table = TRUE,
           size = 1,
           linetype = "strata",
           #palette = c("#E7B800", "#2E9FDF"),
           legend = "bottom",
           legend.title = "Expression Quartiles",
           legend.labs = c("Low Exp.", "Med. Low Exp.", "Med. High Exp.", "High Exp."),
           caption = "SLC2A2 Expression Quartile Survival Curve"
)

</code>
Do I have the correct interpretation of this p-value? Is there NEARLY a significant variance in the survival probabilities of these four groups? And if not, what is the p-value trying to tell me?
Comment: If your alpha level = 0.05, then your p gives you the probability for null hypothesis (the survival of the studied groups are equal). As your p = 0.052, you do not have sufficient evidence for alternative hypothesis. Also, there seems to be a risk for type II error - sample size may not be sufficient for detecting actual differences. This can be well seen if you add confidence intervals to this plot (they should be wide). Finally, CI-s would also allow to compare survival between different groups using eyeballing.
Comment: Thanks st4co4! Appreciated.
Answer: Kevin Bligh on Biostars posted this answer to my question, mirrored there.
The default p-value that is calculated is the log-rank p-value. It is testing the null hypothesis that each of your strata (survival groups) has the same survival probability.
I show this in a previous answer, here: A: survfit(Surv()) P-value interpretation for 3 survival curves?
https://www.biostars.org/p/401657/#401759
In my other answer, I also show how you can use the coxph() function to generate p-values for each pairwise stratum / curve.
Looking at your data, it p-value is not statistically significant and your data-points are sparse after ~75 days.


Xcode não encontra o botão

Question: Eu criei um botão na storyboard para fazer a ligação a uma viewController.
Ao clicar no botão ocorre o erro:

thread 1:signal SIGARBT

O que poderia estar ocasionando tal erro?
Já vi muitos tutoriais e nada.
Comment: Coloque na pergunta o código que você está utilizando para ficar mais fácil te ajudar.
Comment: Eu nao estou a usar código apenas liguei o botao á view controller....
Answer: Fabio, fiz um exemplo bem simples de captura de click em um botão:

Criei um projeto "Single View Application"
No arquivo ViewController.m, implementei o callback para o click

No storyboard, adicionei o botão e cliquei com o botão direito do mouse sobre ele. Depois liguei o evento "Touch up inside" em ViewController.
Answer: Esse erro ocorre quando o que esta no storyboard nao esta ligado corretamente a viewcontroller. Clique com o botao direito do mouse encima no botao e veja para onde ele esta apontando. Isso vai estar no Sent Events.
Voce pode excluir a ligacao e fazer outra ou ate ligar no codigo que ja esta  na viewcontroller
Espero ter ajudado

Xcode não encontra o botão