Erro conversão de Char para String

Question: Tenho o seguinte código:
procedure TDM_Maquinas.IBQCons_MaquinasCOD_LINHAGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
  Text := Sender.AsString;
  if Text <> '' then
  begin
    case Text[1] of
    '1'   : Text := 'Linha 1';
    '2'   : Text := 'Linha 2';
    '3'   : Text := 'Linha 3';
    '4'   : Text := 'Linha 4';
    '101' : Text := 'Recebimento 1'; //aqui da erro
    '102' : Text := 'Recebimento 2'; //aqui da erro
    '201' : Text := 'Expedição 1';   //aqui da erro
    '202' : Text := 'Expedição 2';   //aqui da erro
    '203' : Text := 'Expedição 3';   //aqui da erro
   end;
 end;
end;

error:
E2010 Incompatible types: 'Char' and 'string'

Como faço para resolver?
Comment: Como poderia Text[1] ser igual a 101,102.....?
Comment: @ReginaldoRigo, por que não poderia ser ?
Answer: Ao analisar o padrão, temos que os cases são sempre números, então, poderíamos converter o valor do Text para integer, e assim solucionar seu problema:
procedure TDM_Maquinas.IBQCons_MaquinasCOD_LINHAGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
  Text := Sender.AsString;
  if Text <>'' then
  begin
    case StrToInt(Text) of
    1   : Text := 'Linha 1';
    2   : Text := 'Linha 2';
    3   : Text := 'Linha 3';
    4   : Text := 'Linha 4';
    101 : Text := 'Recebimento 1';
    102 : Text := 'Recebimento 2';
    201 : Text := 'Expedição 1';
    202 : Text := 'Expedição 2';
    203 : Text := 'Expedição 3';
   end;
 end;
end;

Edit: Assim como o @Reginaldo comentou, ao utilizar o Text[1], terá somente o primeiro caractere da sua string, então também alterei Text[1] por Text
Comment: Se Text[1] tem apenas um caracter. Como pode StrToInt(Text[1]) ser igual a 101,102..?
Comment: Viajei aqui, pensei que o `text` era um vetor, e ele tava pegando a primeira posição para usar no case. Então trocando o `Text[1]` por `Text`, resolve o problema. Obrigado @ReginaldoRigo

Erro conversão de Char para String


Accessing dictionaries in Django templates

Question: views.py:
return render(request,'images.html',temp)

Temp:
{'cluster1': ['temp/vinoth/cluster1/demo-pic94.jpg', 'temp/vinoth/cluster1/id1.jpg'], 'cluster2': ['temp/vinoth/cluster2/demo-pic94.jpg', 'temp/vinoth/cluster2/demo-pic99.jpg', 'temp/vinoth/cluster2/id2.jpg', ['temp/vinoth/cluster2/demo-pic94.jpg', 'temp/vinoth/cluster2/demo-pic99.jpg', 'temp/vinoth/cluster2/id2.jpg']], 'cluster3': ['temp/vinoth/cluster3/demo-pic96.jpg', 'temp/vinoth/cluster3/id3.jpg'], 'cluster4': ['temp/vinoth/cluster4/demo-pic99.jpg', 'temp/vinoth/cluster4/id4.jpg'], 'cluster5': ['temp/vinoth/cluster5/demo-pic99.jpg', 'temp/vinoth/cluster5/id5.jpg'], 'cluster6': ['temp/vinoth/cluster6/id6.jpg', 'temp/vinoth/cluster6/triplet loss.jpg'], 'cluster7': ['temp/vinoth/cluster7/id7.jpg', 'temp/vinoth/cluster7/triplet loss.jpg'], 'cluster8': ['temp/vinoth/cluster8/id8.jpg', 'temp/vinoth/cluster8/triplet loss.jpg'], 'cluster9': ['temp/vinoth/cluster9/id9.jpg', 'temp/vinoth/cluster9/triplet loss.jpg']}
System check identified no issues (0 silenced).

The Values are array of images
image.html:

                {% for key,value in temp.items %}

{{ key }}

                {% endfor %}

But nothing gets printed What am i doing wrong here?
Comment: You're passing {'cluster1': ..., 'cluster2': ...} as context to your template, so there's no such variable as `temp` defined. The context variables in your template are `cluster1`, `cluster2`, ...
Comment: You probably want `render(request, 'images.html', {'temp': temp})`.
Comment: I want as key and below key all the images listed :ex cluster1 as heading below it all the images inside cluster1
Answer: Your temp variable you are "sending" to template is called context and you will be able to access to its items by its key values:

            {% for value in cluster1 %}

{{ value }}

            {% endfor %}

In other words, each value of your temp variable will be accesible in the template directly with its key name. So, you will have in your template a cluster1, cluster2, ... cluster9 vars in your template.
If you want to wrap all your vars in only one, you need to modify your context (temp) as follow:

temp = {
   'data': {
      'cluster1': ...,
      ....
   }
}

In the template:

{% for cluster in data %}
  {% for img in cluster %}
    ...
  {% endfor %}
{% endfor %}


Explicit bijection between the set of binary sequences and $\mathbb{R}$?

Question: I know there is a standard proof (Cantor's diagonalization argument) to show that the set of infinite binary sequences, call it $\Omega := \{0,1\}^\mathbb{N}$, is uncountable.
However, I would like to describe an explicit bijection between $\mathbb{R}$ and $\Omega$ to show that they are equipotent. Is there a direct way to do this? Or is my best bet to find a bijection between $\Omega$ and $(0,1)$ (or something) and compose it with a bijection from $(0,1)$ to $\mathbb{R}$?
On that note, is there a "standard" bijection between $\Omega$ and $(0,1)$?
Many thanks.
Comment: I would say that the composition idea is probably your best bet.
Comment: Do you consider a bijection obtained via Cantor-Bernstein to be "an explicit bijection"?
Comment: @ArturoMagidin I would be interested in seeing that construction, yes
Comment: I describe an approach as part of [this answer](https://math.stackexchange.com/questions/4004540/an-example-of-one-to-one-function-to-two-variables/4004583#4004583) going through $(0,1)$
Answer: There's not really a 'standard' one but here's a simple construction (from $\Omega$ to $(0,1)$; bijecting $(0,1)$ and $\mathbb{R}$ is easy as you can just take something continuous like $f(x) = \frac{2x-1}{x(1-x)}$):
Let $A$ be the set of dyadic rational numbers in $(0,1)$, and let $B$ be the set of binary sequences that have only finitely many $0$'s or have only finitely many $1$'s. The binary expansion gives a bijection from $\Omega\setminus B$ to $(0,1)\setminus A$. Both $A$ and $B$ are countable so it should be straightforward to define a bijection between them, for example, we can enumerate them in parallel like so
\begin{eqnarray}
n &\hspace{25pt} A \hspace{25pt}& B\\
1 & \frac12& 1\color{gray}{00000...}\\
2 & \frac14& 0\color{gray}{11111...}\\
3 & \frac34& 01\color{gray}{0000...}\\
4 & \frac18& 10\color{gray}{1111...}\\
5 & \frac38& 11\color{gray}{0000...}\\
6 & \frac58& 00\color{gray}{1111...}\\
7 & \frac78& 001\color{gray}{000...}\\
8 & \frac1{16}& 110\color{gray}{111...}\\
9 & \frac3{16}& 011\color{gray}{000...}\\
10& \frac5{16}& 100\color{gray}{111...}\\
11&\frac{7}{16}& 101\color{gray}{000...}\\
12&\frac{9}{16}& 010\color{gray}{111...}\\
13&\frac{11}{16}& 111\color{gray}{000...}\\
14&\frac{13}{16}& 000\color{gray}{111...}\\
\vdots&\vdots&\vdots
\end{eqnarray}
Hopefully the pattern is clear at this point.
Comment: When you say $B$ is the set of of binary sequences that does not have infinitely many 0's or infinitely many 1's, you mean that it has either a finite number of 1's or a finite number of 0's, right? Just trying to make sense of what you wrote.
Comment: Yea that's a better way of putting it. Or the sequence has a tail of all $1$'s or all $0$'s.
Answer: The Cantor-Bernstein Theorem (aka Cantor-Schröder-Bernstein Theorem and Schröder-Bernstein Theorem) provides a "sort of" constructive proof that given injections $f\colon A\to B$ and $g\colon B\to A$, there exists a bijection $h\colon A\to B$. It's "sort of" constructive because it requires you to know whether a given element can be traced back "infinitely", and that may not be immediately apparent.
So my answer would involve several steps.
First, there is a standard bijection from $(0,1)$ to $\mathbb{R}$; there are several ways of doing so: one is given by Dark Malthorp. I usually like to take the bijection between $(-\frac{\pi}{2},\frac{\pi}{2})$ and $\mathbb{R}$ given by $\arctan(x)$, and of course the interval $(0,1)$ can be bijection with $(-\frac{\pi}{2},\frac{\pi}{2})$ given by $f(t) = -\frac{\pi}{2}+t\pi$.
Now, we can embedd $(0,1)$ into the set of binary sequences using the base-2 expansion, with the convention that for numbers with two expansions, we always pick the one with a tail of $1$s (you can pick whichever you want). So $\frac{1}{2}$ is $0.011111\ldots$, rather than $0.1$. Then $g\colon (0,1)\to 2^{\omega}$ is given by letting $g(t)(n)$ be the $n$th digit in the expansion.
And we can embedd $f\colon 2^{\omega}\to (0,1)$ as follows: given a sequence $(a_n)$ of $0$s and $1$s, we let $f((a_n))$ be
$$\frac{1}{10} + \sum_{n=0}^{\infty}\frac{5+a_n}{10^{n+2}}.$$
That is: the decimal expansion of the number $f((a_n))$ has a $5$ in position $n+1$ after the decimal digit if $a_n$ is $0$, and has $6$ in that position if $a_n=1$. And it has a $1$ in the first position after the decimal point. The latter is to ensure we are in $(0,1)$ even if we take the sequence of zeros. And I use $5$ and $6$ to avoid the problem of multiple expansions for the same number.
Then we use Cantor-Bernstein to construct a bijection $h\colon 2^{\omega}\to(0,1)$ using $f$ and $g$. The construction runs as follows:
We say an element $(a_n)$ of $2^{\omega}$ has a "parent" if there exists $x\in(0,1)$ such that $g(x)=(a_n)$. Similarly, an element $t\in (0,1)$ has a "parent" if there exists $(b_n)\in 2^{\omega}$ such that $f((b_n))=t$.
Given an element $(a_n)\in 2^{\omega}$, we have two possibilities: either we can use the "parent" relation to bounce back and forth between $(0,1)$ and $2^{\omega}$ infinitely many times, or else there comes a point where the process stops (by reaching either a $t\in (0,1)$ that is not in the image of $f$, or a $(b_n)$ in $2^{\omega}$ that is not in the image of $g$).
We can partition $2^{\omega}$ into three sets: $A_1$, the elements where the process stops in an element of $2^{\omega}$; $A_2$, the elements where the process stops in an element of $(0,1)$; and $A_{\infty}$, the elements where the process continues indefinitely without stopping.
Similarly, we can partition $(0,1)$ into three sets: $B_1$, the elements where the process stops in an element of $2^{\omega}$; $B_2$, the elements where the process stops in an element of $(0,1)$; and $B_{\infty}$, the elements where the process continues indefinitely without stopping.
Now, if $(a_n)\in A_1$, then $f((a_n))\in B_1$; if $(a_n)\in A_2$, then there exists a unique $t\in B_2$ such that $g(t)=(a_n)$; if $(a_n)\in A_{\infty}$, then $f((a_n))\in B_{\infty}$. Moreover, every element in $B_1$ is the image of someone in $A_1$; every element in $B_{\infty}$ is the image of someone in $A_{\infty}$. Thus, we define $h\colon 2^{\omega}\to(0,1)$ by
$$h((a_n)) = \left\{\begin{array}{lll}
f(a_n)&\quad&\text{if }(a_n)\in A_1;\\
g^{-1}(a_n)&&\text{if }(a_n)\in A_2;\\
f(a_n)&&\text{if }(a_n)\in A_{\infty}.
\end{array}\right.$$
So, composing $h$ with the bijection of $(0,1)$ to $(-\frac{\pi}{2},\frac{\pi}{2})$, and then using $\arctan(x)$ to biject with $\mathbb{R}$ would give you an "explicit} bijection between $2^{\omega}$ and $\mathbb{R}$.
To be honest, one almost never actually does this. Instead, we rely on knowing that such bijections exist. So I would usually explicitly use $\arctan(x)$ to see $\mathbb{R}$ and $(-\frac{\pi}{2},\frac{\pi}{2})$ can be bijected. Then have a general result about how any two finite open intervals can be bijected (to biject $(a,b)$ and $(c,d)$, use $g(t) = c + \left(\frac{t-a}{b-a}\right)(d-c)$). Then define the two injections above, and invoke Cantor-Schröder-Bernstein.


Comparing Coefficients of Two Time Series Models

Question: I am estimating a time series model. For simplicity, let it be:
$y_t=\beta_0+\beta_1y_{t-1}+\epsilon_t$.
I estimate this model for a whole panel of $n$ sections, i.e. I end up with a tuple of coefficients $\beta_{1,1},...,\beta_{1,n}$.
I also have a slightly adjusted version of the same panel. The adjustment is not of statistical nature. I am dealing with accouning data and the adjusted version is simply some accounting adjustment that is being introduced. More specifically, the adjustments occur at specific points in time, i.e. not every quantity of a time series is adjusted. I again estimate a time series model:
$p_t=\gamma_0+\gamma_1p_{t-1}+\omega_t$,
where $p$ denotes the adjusted $y$ and $k$ denotes the adjusted $x$. I thus get a tuple of coefficients $\gamma_{1,1},...,\gamma_{1,n}$.
I now want to test wether the independent variable has a significantly larger effect on the dependent variable in the adjusted panel than in the unadjusted panel, i.e. I want to compare the persistence (coefficient of an AR1 model) of the two panels. How do I do this? That is, how do I determine which coefficient of the two models applied to different sets of data is of significantly higher value.
Specifically, two issues have to be considered:
(1) I dont have two values which I want to compare. I have two tuples of values.  I was thinking about a decision threshhold. For example, if more than half of the $\beta_{1,1},...,\beta_{1,n}$ are higher than their adjusted counterpart $\gamma_{1,1},...,\gamma_{1,n}$, the effect of the independent variable on the dependent variable seems to be higher in the unadjusted dataset. Is this reasonable?
(2) I need to test wether the the proposed difference between the coefficients is significant. How do I test wether the regression coefficients from two models applied to different data are significantly different? Is the Chow-Test appropriate here?
How do I tackle these issues at once?
Comment: I am looking at accounting information. The original versions are originally reported accounting information. The adjusted versions are retrospectively readjusted reported accounting information.
Comment: How are you "adjusting" the $y$s and $x$s?  If you have a vector of values, you'll have to compare them element by element.  In general, the approach to deriving statistical tests is to write down the distributions of the independent and dependent variables, manipulate them through your adjustment process, and see the resulting distributions at the comparison stage.  Start with strong distributional assumptions -- normality, independence, etc., wherever applicable -- that's OK -- and then try to see what you can relax.
Comment: What formula are you using to adjust your $y$?  For instance, are you mean-centering them?  This matters because if you are mean-centering them using means computed from the data, then it will affect the distribution of the adjusted $y$.
Comment: Its just an accounting "thing". Accounting numbers might get restated for several reasons. Its not a statistical "thing".
Answer: I fully concur with the last paragraph of @AlexC-L's answer which is in essence a paired comparisons method. I have a feeling, though, that you do not want to look at the raw differences $\delta_i = \beta_i - \gamma_i$. The $\beta_i$ and $\gamma_i$ are presumably estimated by regression and are affected by uncertainty: does $\hat\beta_i=0.8$ with standard deviation of 0.6 imply higher persistence that $\hat\gamma_i=0.5$ with standard deviation 0.1? I would think the second more indicative of persistence than the first, which is not even significantly different from zero.
The choice  depends on your problem, but I think you might at least consider to take not the raw estimated coefficients, but rather the coefficients measured in standard deviations when you compute the differences.
Comment: I am aware of that. I would need to estimate a model of the form:
$\left(\array{y_t \\ p_t}\right) = \left(\array{y_{t-1} \ \ 0 \\ 0 \ \ p_{t-1}}\right)\left(\array{\beta_1 \\ \gamma_1 }\right) + \left(\array{\epsilon \\ \omega }\right) $ for each $i$ to derive the covariance matrix for each $i$, right? This would allow me to test for significance while not having to impose the restrictive limitation you were mentioning. Yet, even if I am able to do that, I do not know how to integrate those results into the analysis suggested by @AlexC.-L.
Comment: Once you are satisfied with the standardization, I guess all that is left is to test mean zero of a set of observations with a predefined alternative.
Comment: I am sorry, but I dont understand your last comment @F. Tusell. Could you maybe explain it to me?
Comment: Well, if you obtain $\hat\beta_i-\hat\gamma_i$ that you are satisfied have variance 1, testing that the mean is zero versus the alternative that it is positive seems quite doable. It seems that a simple t-test would do (it is remarkably robust against non-normality). Or may be I am missing something.
Comment: In fact, I am interested in the raw difference. However, you are touching an issue I am currently also thinking about. What if the differences are insignificant? This would deem any subsequent analysis, such as a KS test, irrelevant. https://stats.stackexchange.com/questions/93540/testing-equality-of-coefficients-from-two-different-regressions describes an approach of how the significance could be tested. However, I am unsure of how to integrate results of such an analysis into the method suggested by @AlexC-L.
Comment: The problem with @rusellpierce proposal as applied to your problem is that $\hat\beta_i$, $\hat\gamma_i$ seem likely correlated --for $p_t$ and $y_t$ as I understand refer to the same firms and can be expected to be correlated. So dividing the differences by $sd( \hat\beta_i) + sd(\hat\gamma_i)$ neglects the term in covariance among them.
Answer: I assume when saying "test wether the independent variable has a significantly larger effect on the dependent variable in the adjusted panel than in the unadjusted panel", you are actually trying to find out which model can better describe the uncertainties and relations among the observations.
So instead of comparing the difference of the coefficients, a better approach is to perform model selection on your models. Since model selection has to be done on the same set of samples, you need to some how tweak your models to make them applying to the same sample set:
Model 1:
$$
\begin{align}y & = \beta_0 + \beta_1x_1 + ... + \beta_n x_n + \epsilon \\\Rightarrow y &\sim F(y|x_{1:n},\theta_1) \\\end{align}
$$
Where $\theta_1 = \{\beta_{0:n} \text{ and all the other parameters}\}$, you can understand $F(y|x_{1:n},\theta_1)$ as a distribution of $y$ conditioned on $(x_{1:n},\theta_1)$. For example when the model is a simple linear regression $y = \beta_0 + \beta_1x_1 + ... + \beta_n x_n + \epsilon,\epsilon \sim N(0,\sigma^2)$, then $F(y|x_{1:n},\theta_1)$ will be a normal distribution with mean $\beta_0+\beta_1x_1+...+\beta_nx_n$ and variance $\sigma^2$, i.e.  $F(y|x_{1:n},\theta_1) = N(y|\beta_0+\beta_1x_1+...+\beta_nx_n, \sigma^2)$
Model 2:
No matter how you "adjust" your samples, there must be a way to represent the adjustment with a function, say $p = h(y)$, $k=g(x)$. For example if the adjustment is discounting future payment $y$ into current value $p$, then the function $h(y)$ will be something like $h(y) = \frac{y}{(1+r)^m}$. With this idea in mind, your second model $p = \gamma_0 + \gamma_1k_1+,...,+\gamma_nk_n+\epsilon_2$ can be rewritten as:
$$
\begin{align}y & = h^{-1}(\gamma_0 + \gamma_1g(x_1)+,...,+\gamma_ng(x_n)+\epsilon_2) \\\Rightarrow y &\sim G(y|x_{1:n},\theta_2) \\\end{align}
$$
Where $\theta_2 = \{\gamma_{0:n} \text{ and all the other parameters involved in h() and g()}\}$.
Now that both the models are put to the same set of samples, you can start comparing them. There are two common ways to perform the comparison:

method1: If $F()$ and $G()$ are Bayesian models, you can compare their marginal likelihood (the higher the better) or BIC (the lower the better).
method2: Use cross validation and compare their cross validated expected-prediction-error.
Comment: Thats a clever method. However, the question I am trying to answer can be more precisely defined as follows: Is the persistence of some metric (e.g. cash flow), i.e. the coefficient in an AR1 model, higher in the adjusted dataset or the unadjusted dataset. The way you rephrased it does not take into account the actual value of the coefficient that I am interested in, but rather the goodness of fit. Is this correct? Because then, it would not provide an answer to the question of which coefficient is significantly higher.
Comment: Moreover, the adjustment is not of the nature you were suggesting. I am talking about accounting adjustments such as a firm might readjust its previous financial statements to ensure comparability across periods, e.g. in the case of M&A activity. So the readjustments occur at specific points in time and the time series is not readjusted as a whole. Thus, it is *practically* not possible (at least in my opinion) to formulate the readjustment process as a single function. I edited the question so it is more clear.
Comment: Am I correct? Or am I wrong with what I was saying in regards to your approach against the background of what I am interested in?
Answer: Note: This answer does not take into consideration that $\beta_i$ and $\gamma_i$ are themselves estimated (thank @Turell for pointing that out). I make another try in another answer.

You have n $\beta_i$ and n $\gamma_i$ that you want to compare. If n is large enough, you might turn this problem into the comparison between two distributions.
You may use the Kolmogorov–Smirnov test to determine if those two distributions are significantly different from each other. If this is the case, graphical inspection may then be used to determine if beta are generally higher than the gamma.
To go beyond this simple graphical inspection, you may look at the differences between the quantiles of two distributions following Doksum, and Wilcox.
One issue I notice yet: above, this would not compare $\beta_{i0}$ and  $\gamma_{i0}$ one to one. This can be fixed by defining: $\delta = \beta - \gamma$, and by comparing $\delta$ with a distribution of zeros.
Comment: Indeed. I make another try in another answer.
Comment: NB: a quick suggestion from a non-expert
Comment: Good idea! I was thinking about that too. It would actually solve both issues, since I could thereby compare two vectors of values (by looking at their distribution) while doing testing for significant differences. However, is there a statistical method directly determining wether one distribution is "shifted" relative to the other, i.e. skipping the KS Test + graphical inspection and doing both in one step?
Comment: If there is a significant difference between the two distributions, you may then look at the quantiles. Are those of one distribution always lower than for the other distribution ? I would imagine this would fit your purpose.
Comment: I otherweise added a blog reference that illustrates the last sentence of my answer: https://garstats.wordpress.com/2016/07/12/shift-function/
Comment: Thanks, I will reward the bounty to your answer throughout the next days, if no other answers are being posted.
Comment: Thank you, but please wait indeed - see the issue that I just noticed and added.
Comment: One sidenote, what if the differences are non-significant? Please see the post of @F. Tusell.
Answer: Let us define $\delta_i = \beta_{1,i} - \gamma_{1,i}$, with i indexing the samples.
You would ideally regress $\delta_i$ over 1: $\delta_i = b.1 +\eta_i $.
If I make no mistake, your question can indeed be rephrased:: What is the value of $b$? Is $b$ significantly different from 0?
However, as noticed by @F.Tusel, there is some uncertainty regarding $\delta_i$; this will bias upwards the variance associated with $b$, and this could cause your result to be (wrongly) non-significant.
If your result is significantly different from zero, stop here as what is below would only increase significance.
If not: Having uncertainty on the value of the dependent variable is however a classical problem.  A clear explanation on how to deal with it in classical cases can be found in [1].
Is it simple in your case? It probably depends. Are your samples i.i.d. ?

If yes: the variance-covariance matrix of $\delta_i$ is simply the diagonal matrix with $\sigma_{\delta_i}$ on the diagonal. And $\sigma_{\delta_i}$ can itself be infered from the matrixes of variance-covariance of $\left(\array{\beta_{1,i} \\ \gamma_{1,i} }\right)$. The latter can be estimated if you jointly estimate: $$ \left(\array{y_{t,i} \\ p_{t,i}}\right) = \left(\array{\beta_{0,i} \\ \gamma_{0,i} }\right)  + \left(\array{y_{t-1,i} \ \ 0 \\ 0 \ \ p_{t-1,i}}\right)\left(\array{\beta_{1,i} \\ \gamma_{1,i} }\right) + \left(\array{\epsilon_{t,i} \\ \omega_{t,i} }\right) $$.
If not, more thinking is required. Please add more information in the Question regarding your samples.

Reference:
[1] Lewis, Jeffrey B., and Drew A. Linzer. "Estimating regression models in which the dependent variable is based on estimates." Political analysis 13.4 (2005): 345-364. http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.318.7018&rep=rep1&type=pdf
Comment: I make a second try! (again, this comes without guarantee)


conf.lua not being read (Lua/LOVE 0.8.0)

Question: I need a higher resolution for my program to run. For some reason I cannot discern alone, LOVE is not applying (or finding?) conf.lua.
My folder architecture is as follows:

basefolder/
basefolder/main.lua
basefolder/conf.lua
basefolder/Resources/

My conf.lua file reads:
function love.conf(t)
    t.window.width = 1280
    t.window.height = 720
end

Is it something with my code, or with how my directory is set up?
Answer: Try with:
function love.conf(t)
    t.screen.width = 1280
    t.screen.height = 720
end

There is no t.window field in version 0.8.0, t.screen was renamed to t.window in version 0.9.0.
See the Love2D documentation on configuration files.


How do I make a carousel with an highlighted node and thumbnails to the left and right?

Question: I'd like to make a carousel exactly like the picture below: six thumbnail nodes on the left, one highlighted node in the middle and six thumbnail nodes on the right; when users click on the controls, the next set of nodes shows up.

I guess it would be possible to achieve this with a view and using a module like the OwlCarousel module. So far I couldn't make it work.
How can I use a view and the OwlCarousel module to make a carousel?
Answer: You could do this with the jCarousel module:

Build your view to show the required nodes in the order you wish them to show.
Enable jCarousel view format
Create a style output template using a file name from OTHER -> Theme: Information -> Style output
Copy the code from the style template offered by the jCarousel module
Change the template code to output 7 rows at a time with the necessary wrappers and classes to make it look like your design
Make sure the .jcarousel and .jcarousel-clip divs are outside each group of 7 rows. [edit: it appears this happens outside of the template file, so not usually something you'll need to worry about]

Here's something to get you started with the style template file:
<?php

/**
 * @file jcarousel-view.tpl.php
 * View template to display a list as a carousel.
 */
$count = 0;
$rowcount = count($rows);
?>
<ul class="<?php print $jcarousel_classes; ?>">
  <?php while ($count < $rowcount): ?>
    <li class="<?php print $row_classes[$id]; ?>" style="display: none;">
      <?php // Print your seven rows here ?>

      ...

    <?php // Advance the counter ?>
    <?php $count += 7; ?>
    <?php // Depending on how you print your rows you may wish to slice 7 items off the $rows array ?>
    <?php $rows = arracy_slice($rows, 7); ?>
  <?php endwhile; ?>

Note that if you're referencing each row like $row[id] you may need to do a check before printing each one unless you're certain there will be a multiple of 7 rows in your view.
Comment: Okay can I still use OwlCarousel? also I know this is how I should do it, I wonder how can I make the highlighted node image style bigger
Comment: I don't know owl carousel but I imagine the principles are the same. Give the third item in the group a different class, wrap the others in dive as pairs.
Comment: can you please help me with the output and elaborate more? also if I use a different class how can I use a different Image style, not just different width and height with CSS?
Comment: Sorry, that kind of question (about CSS) belongs on Stack OverFlow.  As for the output, I'll come back later, I'm at work at the moment.
Comment: yep thx for the reply, I'm not asking about CSS though!
Comment: Oh right... well just set a different image style when you print the third image using [image_style_url()](https://api.drupal.org/api/drupal/modules!image!image.module/function/image_style_url/7)
Answer: If you are looking for an easy to implement approach try this:

Make a Content-type called: "Slideshow"

Make three different Entity Reference field referencing your desired nodes (your another content-type that you want to show)
call your entity reference fields like: "Right", "Middle" & "Left".

Create a node of content-type "Slideshow"
Using display suite module and view format of Rendered Entity define your image sizes and extra fields you want for your "Middle" node.
Create a views of Slideshow nodes using OwlCarousel or any other carousel module you want.
Do a little bit of CSS magic and you must be good to go!
Answer: Simply You could build the view to get content needed then from

OTHER -> Theme: Information -> Style

make the tpl file with the name suggested
In that file you could take the source of the markup that you need to build in the image you provided and start make the content be dynamic using that piece of
foreach ($view->style_plugin->rendered_fields as $delta => $item):
 //Do stuff here, you could control items display and order to meet your case and add the html
endforeach

After building the same html markup needed for that layout, Start add your js and css files needed by that plugin
by that way you could have full control over the items being rendered and markup out of views display settings and without needing extra modules


When while saving nodes do I have old and new vid available at once?

Question: I'ld like to programmatically trigger some very basic email notification when a new revision of a node is being created. I want to send a link to the compare page /node/$nid/revisions/view/$old_vid/$new_vid.
But I wonder on which hook when saving a node do I have the old and the new vid available at once? hook_node_presave() looks like a dead end to me.

This question is not specifically about D7. Though it's D7 I'm using right now, I'ld prefer to find a solution for both D7 and D8.
Answer: You simply can add a custom submit callback to the node form.
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  $node_forms = [
    'article_node_form',
  ];

  if (in_array($form_id, $node_forms)) {

    // Add a custom submit callback.
    $form['actions']['submit']['#submit'][] = '_MYMODULE_postsave';
  }
}

There you can access the original vid from the $form_state array. And when you load the freshly saved node you'll have the new vid available.
/**
 * Custom submit callback.
 */
function _MYMODULE_postsave($form, &$form_state) {

  $old_vid = $form_state['values']['vid'];
  $nid = $form_state['values']['nid'];
  $node = node_load($nid);
  $new_vid = $node->vid;

  // Voilà!
  dpm($old_vid, 'OLD_VID');
  dpm($new_vid, 'NEW_VID');

  // Do your stuff here
}

For reference: https://drupal.stackexchange.com/a/221041/15055


DKIM do I need to allow port 8891 on my firewall?

Question: I'm trying to set up dkim on my server so my emails are less likely to end up in my customers' spam.
Quick question: does port 8891 need to be opened? I'm using ufw.
Many thanks in advance,
Comment: You accepted the wrong answer.
Answer: No you don't need the port 8891 to be opened to the outside connection, that is only for Postfix SOCKET.
The what DKIM keys works are like this: You create a public key and a private key. The public key is published on your DNS records as a TXT record, on the other side your emails are signed with your private key, when you send an email the recipient server check your DNS record for the public key for example "default._domainkey" and it verifies the DKIM. There is nothing related with connecting directly to the server.
Hope this helps.
Comment: Thank you so much. I can confirm that I have 8891 denied in my firewall config and the dkim works (I tried it out using http://www.brandonchecketts.com/emailtest.php)
Answer: Probably not.
My guess is that you have a dedicated daemon for dkim signing (such as opendkim) listening on that port, and that your mail server is using that port to communicate with it? Assuming that your mail server and your dkim server runs on the same machine they ought to be communicating over localhost, which I hope your local firewall rules leave alone.
Assuming all above is true there is also the possibility of having your mail server and your dkim server communicating over a socket instead. It has the potential to make things a bit more complicated but also has the potential to increase security, by enforcing filesystem rules, restricting what local users/daemons can do dkim signing. Assuming you have a dedicated machine for handing mail the additional security of using sockets are probably negligible compared to communicating over localhost network.


Qual é a diferença entre Strategy Pattern e Specification Pattern

Question: Estou implementando um app CLI em C# de jogo da velha e queria saber qual é a melhor pattern para utilizar para fazer a "AI" que seria o player vs computer no caso.
Andei olhando algumas patterns para fazer isso e me surgiu a dúvida de qual utilizar.
Minha dúvida pela implementação da Strategy e da Specification é que as duas são para validar algum tipo de entrada e retornar o resultado provável para aquele valor de entrada. Qual seria a diferença de implementação entre as duas e qual é a sua usabilidade, quando devo utilizar a Strategy e quando devo optar pela Specification?
Answer: Ah, um jogo da velha precisa de um desses padrões? Então tá.
A principal diferença é que o padrão da estratégia é isolado, indica uma regra a ser aplicada de acordo com uma implementação externa em algum ponto específico, e pode parametrizar qualquer comportamento desejado no objeto. E o padrão da especificação é algo mais complexo e estabelece um conjunto de regras, geralmente encadeadas, que serão aplicadas em alguma parte, sendo que cada regra individual pode ser trocada, adicionada ou removida, além de mudar a ordem, e estas regras devem ser principalmente validações (em um sentido amplo, e não só a validação tradicional, pode ser uma seleção por exemplo), portanto bem mais limitada. Portando nem deveria haver confusão, eles servem a propósitos bem diferentes. Geralmente a dúvida sobre o uso do Strategy é se não seria melhor o Bridge, Adapter, State, Template Method, Decorator, e por vezes Visitor ou Facade.
Já tenho minhas dúvidas se deveria usar um deles, mas o Specification parece menos interessante aí, ainda que eu possa estar errado por não conhecer os detalhes. Quanto mais vai aplicando essas coisas tende a adotar o antipattern chamado Second System. Por outro lado se quiser insistir nele, talvez queira usar como mecanismo de "AI", e pode fazer sentido já que quer complicar a solução, usar este padrão para encadear as decisões. Lembre que ele é só um if bem mais complicado, é OOP sendo usada onde o simples imperativo resolvia o problema. E se varia o que fazer em certas sequências então o Strategy pode ser útil, mas acho que nem é o caso, pense até em outros que eu citei acima. Eu não posso pensar por não ter detalhes.
Note que C# tem mecanismos que muitas vezes faz com que um certo padrão não seja necessário. Por isso sempre digo: as pessoas querem usar design patterns sem nem mesmo saber o que isto significa, é só porque está na moda.

Design patterns are bug reports against your programming language
-- Peter Norvig

Detalhamento.
Paul Graham também fala algo sobre isto.
Discussão.

Coloquei no GitHub para referência futura.
Comment: Muito obrigado pela ajuda!!


What does this notation mean for calculating prime?

Question: I'm not very proficient with math, but Ive managed to make my way to problem 7 of Project Euler using python. I have to now find the 10,001st prime number. I'm reading about Eucilid's theorem. But I'm afraid I do not understand enough about mathematical notation to understand the theorem.
What do the numbers in the p=p1,p2,p3 expression on this page (http://en.wikipedia.org/wiki/Euclid%27s_theorem#Euclid.27s_proof) mean? Is p the prime number? and the 1,2,3,4 are just counting the position?
Thanks in advance for your help.
Comment: Are you referring to the equation $P = p_1 p_2 \dotsm p_n$ in the first section?
Answer: To turn this into the language of a programmer, $p$ is essentially an array of prime numbers. So $p_1$ is the first element of the array, $p_2$ is the second, and so on.
Comment: @ReneSchipperus Generally speaking, you are correct, there is no formula for the $n$-th prime (if you were to figure one out then you'd win every prize in mathematics).
Comment: I am not sure what OP is talking about but its not possible to find 10001 st prime without computers right ?
Comment: @ReneSchipperus OF course this is possible without computer. I'm pretty sure some the "old ones" listed all primes up to several millions. After all they also computed $30§ decimals of $\pi$ by hand or manually divised a method to construct the regular $257$-gon with straightedge and compasses.
Comment: https://projecteuler.net/problem=7 I'm trying to use a computer :-)
Comment: @HagenvonEitzen I don't think he was specifically interested in the 10001st prime, he meant for an arbitrary number.
Comment: @Kelbizzle if you want a hint then look up the Sieve of Eratosthenes.
Comment: @user2584283 Thank you, I've head of that. I will check that out now. Thanks again everyone for your help.
Comment: What I meant was that I alone sitting at by desk, maybe with a pocket calculator, would not be able to calculate the 10001 prime without prohibitively difficult work. I mean there is no clever way using prime number theorem or something else.
Answer: Yes indeed, that's the prime number position. Euler's proof of the infinitude of primes is a proof by contradiction, which assumes that the primes can be ordered into a finite set. Then, Euclid builds a number, which is the finite product of all primes. Then he adds 1 to that number, and he discovers that he has just built another prime.


E_DEPRECATED and E_NOTICE errors showing in dblog / syslog despite disabling in php.ini

Question: I'm still getting a lot of PHP Deprecation and Notice messages in my logs despite having these values turned off in php.ini. According to admin/config/development/logging I should only be displaying errors and warning if that is relevant. Is there some other way that Drupal might override my php.ini settings?
Comment: Have you restarted your server?
Comment: For the record, the real solution is _not_ to disable error logging, but to fix file bugs/fix the errors. Errors _should_ be logged. (But not displayed in a production environment)
Comment: I agree, but on production the mass of notices and deprecation errors really gets in the way of trying to find legitimate issues.
Answer: In drupal_environment_initialize(), Drupal changes the report level with the following code.
// Enforce E_ALL, but allow users to set levels not part of E_ALL.
error_reporting(E_ALL | error_reporting());

The value of E_ALL changes basing on the PHP version, and it is:

--------------------------------------------------------------------------------
PHP   | Value expressed using the other constants                              |
-------------------------------------------------------------------------------|
Before| E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
5.2.x | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE                                                          |
-------------------------------------------------------------------------------|
5.2.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_RECOVERABLE_ERROR                                    |
-------------------------------------------------------------------------------|
5.3.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_RECOVERABLE_ERROR | E_DEPRECATED | E_USER_DEPRECATED |
-------------------------------------------------------------------------------|
5.4.x | E_WARNING | E_PARSE | E_NOTICE | E_CORE_ERROR | E_CORE_WARNING         |
      | E_COMPILE_ERROR | E_COMPILE_WARNING | E_USER_ERROR | E_USER_WARNING    |
      | E_USER_NOTICE | E_STRICT | E_RECOVERABLE_ERROR | E_DEPRECATED          |
      | E_USER_DEPRECATED                                                      |
--------------------------------------------------------------------------------

With all the PHP versions, error_reporting(E_ALL | error_reporting()) causes any warning to be raised; since PHP 5.3, it causes any deprecation message to be raised too.
drupal_environment_initialize() is the only place where Drupal sets the error level. A custom settings.php file could change it with ini_set('error_reporting'). Since settings.php is included after drupal_environment_initialize() is executed, that file could restrict the error level, or expand it; this means that with PHP 5.3, settings.php could cause E_STRICT errors to be raised too.
function _drupal_bootstrap_configuration() {
  // Set the Drupal custom error handler.
  set_error_handler('_drupal_error_handler');
  set_exception_handler('_drupal_exception_handler');

  drupal_environment_initialize();
  // Start a page timer:
  timer_start('page');
  // Initialize the configuration, including variables from settings.php.
  drupal_settings_initialize();
}

About the error levels, the PHP documentation has the following notes:

In PHP 5 a new error level E_STRICT is available. Prior to PHP 5.4.0 E_STRICT was not included within E_ALL, so you would have to explicitly enable this kind of error level in PHP < 5.4.0. Enabling E_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue E_STRICT errors such as assigning objects by reference upon instantiation.

If you are using PHP 5.4, that would explain why Drupal is recording E_STRICT errors, since Drupal adds E_ALL to the error level.
Comment: Added `ini_set('error_reporting', E_ALL & ~E_DEPRECATED & ~E_NOTICE);` to settings.php, problem solved, thanks! I assumed this probably would be the solution, however you explained the reasons why quite expertly :D
Comment: I am sorry my previous answer was not so explicit; I realized that after I took a nap. I think my answer is much better now. `:)`


How to add a list of stock and node reference to create the perfect stock of beers?

Question: I'm creating a Drupal site that is able to follow the stock of your beers.
For beers, I have a Beer Content type wth all info on the beer, it's OK.
Now, for each user, I want to give the possibility to create a list of beer and the number of beer user has in fridge. How can I do that?
I was thinking of making these Content Types:

InStock (fields : int + node reference to beer).
MyBeers (fields : node reference to InStock).

But with that, user has to create one InStock for each beer and then after that create one MyBeers and reference to all it's beers, so it isn't the good approach.
I don't want to make custom module if it's possible.
Ideally in fact, in my perfect works, I can add directly a List of (node reference to beer + int items in stock) into the InStock but I don't know how to do so.
Answer: Only use the Flag module, so that your users can just "flag" the nodes related to your Beer Content type. With such approach, there is no need for the extra content types InStock and MyBeers that you are considering (a commonly known best practise in Drupal is to try to keep the number of content types to a minimum).
Some details about the Flag module (from its project page):

Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

Create a flag that can be used by each user individually (not a "global" flag), so that each user can flag the Beer Content types, and which would be the equivalent of your "MyBeers" type you had in mind. And by using the technique of Attaching fields to flags, you could create a field corresponding to that "int" field of your "InStock" content type you had in mind.
Super easy and straight forward. And by using the Flag module, as a bonus you get all those amazing features about integrations with other modules such as Rules, Views, Views Bulk Operations (VBO), etc. Some samples:

Build a view to see what is in "your" fridge, and or apply mass updates using the VBO module.
Use the Rules module to send eMail reminders when your stock "is running low".

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about this module. Especially the Video about Creating non-global flags: between about 6:00 and 8:30 it explains how to add a Flag-related relationship in your view, so that you can then also use flag related data in your view (for fields, etc). The same video (near the end) also shows how to combine this with VBO.
Some more suggestions related to some additional (non-global) flags I recommend you to create, which would probably enhance the beer-experience of your users even further:

My favourites: a flag to indicate the favourite beer(s) of a user (... like "Leffe Blond" ...)
Looking for it: a flag to indicate the beer(s) a user is looking/searching for, like where to buy such beer (like "Celis White" ...).
Tasted it: a flag to indicate the beer(s) a user ever tasted, e.g. to create a contest about nr of different beers somebody every tried (like "400" ...), or an inventory of beers that are still on your whish list to ever try (like "empty" ...).


Converting a general tensor element into an elementary tensor

Question: So here is a sort of vague question. Suppose $\sum_{i=1}^kx_i\otimes y_i\in X\otimes Y$ be a general element in the tensor product of finite dimensional vector spaces $X$ and $Y$. Does there exist finite dimensional vector spaces $\tilde{X}$ and $\tilde{Y}$ such that $X\otimes Y$ sits inside $\tilde{X}\otimes \tilde{Y}$ and that $\sum_{i=1}^kx_i\otimes y_i$ is $\tilde{x}\otimes \tilde{y}$ for some $\tilde{x}\in \tilde{X}$ and for some $\tilde{y}\in\tilde{Y}$.
I would like some hints rather than a complete answer.
Answer: Well, you could always take $\tilde{X}=X\otimes Y$...
Comment: Oh! Yes. That should help.


O loop de escolha precisa encerrar ou continuar em um menu

Question: Disponho de dois objetos que recebem parâmetros pela entrada padrão do sistema, porem na hora do usuário escolher em continuar ou sair, o loop não obedece a saída e quando obedece a saída não obedece o continuar, vou deixar a parte do código, fora das classes pois não é relevante para o problema:
#include "setter,getter.h"

using namespace std;

int main(void)
{

  char str;
  int ob1;
  int ob2;
  cout << "selecione a opcao do objeto 1:";
  cin >> ob1;
  cout << "selecione a opcao do objeto 2:";
  cin >> ob2;

  apc *obj1 = new apc(ob1);
  apc *obj2 = new apc(ob2);

  cout << obj1->getPublicInt() << "\n";
  cout << obj1->getPublicStrings() << "\n";

  cout << obj2->getPublicInt() << "\n";
  cout << obj2->getPublicStrings() << "\n";

  while (1)
  {
    cout << "continuar ? s ou n"
         << "\n";
    cin >> str;

    if (str = 's' or 'S')
    {
      main();
    }
    if (str = 'n' or 'N')
    {
      system("pause");
      return 0;
    }
    else
    {
      cout << "opcao invalida!";
    }
  }
}

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Acho que quer isto:
int main() {
    while (1) {
        char str;
        cout << "selecione a opcao do objeto 1:";
        cin >> ob1;
        cout << "selecione a opcao do objeto 2:";
        cin >> ob2;
        int apc *obj1 = new apc(ob1);
        int apc *obj2 = new apc(ob2);
        cout << obj1->getPublicInt() << "\n";
        cout << obj1->getPublicStrings() << "\n";
        cout << obj2->getPublicInt() << "\n";
        cout << obj2->getPublicStrings() << "\n";
        while (1) {
            cout << "continuar ? s ou n" << "\n";
            cin >> str;
            if (str == 's' || str == 'S') break;
            if (str == 'n' || str == 'N') {
                system("pause");
                return 0;
            } else cout << "opcao invalida!";
        }
    }
}

Coloquei no GitHub para referência futura.
Não chame a função de novo, isso cria recursividade e pode em casos mais extremos quebrar a aplicação, mesmo que funcione em exercício, aprenderá errado, faço um laço que repita a operação, como já sabe fazer.
O laço que ficará mais interno é só para garantir que a pessoa digitou algo válido, então se ele digitou inválido continua no loop interno, caso contrário sai. Se for para continuar digitando, só sai de laço e fica dentro do outro mantendo a repetição do laço mais externo, e isso se faz com um break. Se é pra sair de vez o return funciona bem porque ele sairá dos dois laços.
Havia erro na comparação do texto, o operador correto é o de igualdade == e não o de atribuição =. E ainda tem que fazer a comparação por completo, quando monta uma expressão só com 'S' ela é sempre verdadeira, apenas a expressão str == 'S' pode dar verdadeira ou falso de acordo com o valor da variável, o compilador não adivinha o que você quer fazer ali, você é responsável por escrever o código certo. E não use or, use ||.
Em exercício não dá problema mas está errado alocar memória e não desalocar como fez, precisa de um delete. Veja Qual a finalidade da função free()?.
Ningu´-em liga pra isso mas eu vou falar assim mesmo: antes de fazer algum código um pouco mais elaborado, aprenda a sintaxe básica, como a linguagem é, os conceitos de programação, se treinar o erro, é isso que sempre fará. A maioria das pessoas hoje em dia fazem isso e erram muito.
E
Comment: kkkkkkkk, ajudou bastante, eu sabia que  era possível de ser feito esse laço assim, mas n passou por minha cabeça, a questão do operar o if com atribuição, foi nas minhas falhas tentativas de identificar o erro, mas depois que eu vi que não era, voltei para a comparação, ainda nao consegui compreender porque de duas comparações terem que ser feitas, acabei esquecendo desses conceitos, e o or, sabia que não podia ser usado, mas o porque não deve ser usado ?
Comment: È considerado obsoleto.


Situação curiosa ao inserir grid-area com JavaScript

Question: Estou inserindo algumas estilizações em um projetinho que estou fazendo, e estou com um forEach rodando no DOM pra percorrer uma lista, acontece que se eu adiciono um grid-area e coloco o indice como valor do grid area, ele replica o valor 4 vezes. Talvez por texto não seja muito compreensível, vou demonstrar no código:

document.querySelectorAll('ul li').forEach((element, indice) => {
  element.style.cssText = `grid-area: item${indice}`
})
ul {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  width; 100%;
  justify-content: center;
  align-items: center;
  text-align: center;
  grid-gap: 15px;
  grid-template-areas: "item0 item2 item3" "item4 item5 item6"
}

li {
  list-style: none;
  border: 1px dashed;
}

Teste 1

Teste 2

Teste 3

Teste 4

Teste 5

Teste 6

O que ele me retorna é isso:

Teste 1

Teste 2

Teste 3

Teste 4

Teste 5

Teste 6

Por que ele faz isso item0 / item0 / item0 / item0, se o forEach retorna o indice no parâmetro 2?
Comment: Segundo a MDN: [*The grid-area CSS property is a shorthand property for grid-row-start, grid-column-start, grid-row-end and grid-column-end*](https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area).
Answer: O Grid funciona como um plano cartesiano, onde cada célula tem um X/Y inicial e um X/Y final. Por isso ele repete 4x, na verdade ele está colocando o valor para x inicial / y inicial / x final / y final.
Se vc quer contornar isso vc pode colocar o style usando o setAttribut e colocando o index como valor do grid-area conforme abaixo

document.querySelectorAll('ul li').forEach((element, i) => {
    element.setAttribute("style", "grid-area: item"+[i])
})
ul {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  width; 100%;
  justify-content: center;
  align-items: center;
  text-align: center;
  grid-gap: 15px;
  grid-template-areas: "item0 item2 item3" "item4 item5 item6"
}

li {
  list-style: none;
  border: 1px dashed;
}

Teste 1

Teste 2

Teste 3

Teste 4

Teste 5

Teste 6

O resultado no DOM ficaria assim:

Teste 1

Teste 2

Teste 3

Teste 4

Teste 5

Teste 6

Apenas para fins didáticos
Esse gid área seria grid-area: 1 / 1 / 2 / 2;
Comment: ::Gif do Leo Stronda:: O maluco é Brabo. Valeu de novo hugão!
Comment: @LucasdeCarvalho esse é o bonda da maromba! Birllll


continuous and strictly increasing implies differentiable

Question: I am not sure if this is true, but intuitively it seems that if a function is strictly increasing and it is also continuous...it is differentiable.
It may be because there are no bumps like in the absolute value.
Answer: Not necessarily. Counterexample:
$$
f(x)=\begin{cases}
x & \text{if }x<0,\\
2x & \text{if }x\ge 0.\end{cases}
$$
Is continuous, strictly increasing but not differentiable at $x=0$.
Comment: ^ or its density may not be its derivative
Comment: Or you use a different notion of derivative than that in intro calculus.   One way to avoid this (for simple functions as in the example above) is to say the probability for region is defined as the integral of the density function (not the density function is the derivative), then a finite number of discontinuities would not be a problem for the Riemann inertial (perhaps use the Lebesgue integral for a countable number).
Comment: @ChrisK.Caldwell An interesting fact about Riemann integrals is that they can also handle countably many discontinuities.  In fact, a necessary and sufficient condition for being Riemann integrable is that the set of discontinuities of the function has Lebesgue measure zero.
Comment: @AsafKaragila A monotone function is differentiable almost everywhere.
Comment: So if a a probability distribution has this property, it may not have a density?
Comment: Is it possible to construct an example which is not-differentiable [almost] everywhere?
Answer: No, as Julián Aguirre's answer shows. However, what is true is:

Lebesgue's Theorem: Every monotone function $f$ (increasing or decreasing) defined on an
open interval $(a,b)$ is differentiable almost everywhere on $(a,b).$
Answer: Take a look at Billingsley' Probability and Measure, example 31.1
Comment: Answers should be somewhat self-contained. References and links are fine, but descriptions and explanations in the answer help in case references are not available or links go stale.


Example of equicontinuous sequence of functions which is not convergent

Question: I need to prove there exits an equicontinuous sequence which is not pointwise convergent.
I have been working on it but unfortunately , I am not even near to find such sequence of functions.
Does someone have any idea about it?
Thanks
Comment: Hint: $f_n(x) = n$.
Comment: Yes, this is nice , I did not even realize this works. Thanks anyway.
Answer: For a bounded example, try $f_n(x) = (-1)^n$.


yum remove doesn't remove things completely?

Question: I am trying to remove apache completely from my server,which is a ec2 instance, running Amazonian linux v2.6xx.
Lets assume I have a file in /etc/httpd/conf/xyz.txt
I am using the following code :
yum remove httpd

when I try to cd /etc/httpd I get "there is no such directory" error.
Next, if I install httpd again, using this : yum install httpd, and then if I look in /etc/httpd/conf/ I still have that file as it is.. untouched..
How is this possible ?
How do I "Clean" this ?
Answer: yum/rpm will not remove things it did not put into place (unless someone does it in the scripts, but only ISVs with a few screws loose do that). I highly suspect that you typoed your cd command, and that the directory did actually exist.
Comment: I "CD"ed into proper directory, I repeated it many times (install/remove) and confirmed that it was happening..
So no chance of typos.. And I confirm that the directory wasn't there.. (I tried winscp to browse through to it..)


Generating a pivot table from a sql query

Question: I have a project that consist of a function that generate a table based on some filter. Then, I found a problem that when some combination of some filter are return nothing so, when it rendered in browser as a table is less than number of combination.
To achieve it, I want to give "-" mark to the loss record that not saved in the table.
My first approach is check one-by-one the array with the filter and if the condition is match to 'loss rows', it will push array untill all missing record in result is filled with '-'. But, it'll dealing with time because, the last must be sorted again and then to be constructed into the wanted table.
Sample schema of main table "A":
 amount_of_product, id_product, id_people, id_place.

The primary key columns are:
 id_product, id_people, id_place.

The content of the main table is:
23456, book-a, 1, aa
5678, book-b, 1, cc
2587, book-b, 1, aa

The source query will be something like:
select * from A
where
    id_product in ('book-a', 'book-b')
    and id_people in ('1') and id_place in ('aa', 'bb', 'cc')
order by id_product, id_place

Then, we want to show in a table view (html) all combinations of all selected filters. 6 rows should be rendered, with empty cells shown as "-".
Sample result table:

Can I do it efficiently or are there any solution to this?
Thanks in advance.
Comment: show some scnreehots, jsfiddle, code,..
Comment: In Oracle, you would use `pivot` : `select * from A pivot(sum(amount_of_product) for id_place in ('aa','bb','cc'))`. The postgresql [`crosstab`](http://www.postgresonline.com/journal/index.php?/archives/14-CrossTab-Queries-in-PostgreSQL-using-tablefunc-contrib.html) function should provide similar functionality.
Answer: Thanks for some advice above.
I've try to use crosstab function in postgresql to produce the pivot table but I can't produce for more complex table.
So, I use another approach to retrieve all datas based on combination row-coloumn gradually (example query from id_place 'aa', id_people '1', id-product 'aa' etc) and contruct each table head row and coloumn then contruct the data.
Regard


couldn't find the difference between two date in another textbox in javascript

Question: my date format is dd/mm/yyyy and calculate this format
here a script

Comment: your description of the problem is not clear enough, I wonder if you describe it more.
Comment: calculate no of days between two dates
Comment: but date format is dd/mm/yyyy
Comment: Regarding date operations, I find very convenient to use [moment.js](https://momentjs.com/) if you don't mind using an external library. Making your own operations on dates seems easy at first, but can be quite tedious...
Answer: you need to get time from date and then do the calculation
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");

// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();

// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

//To display the final no. of days (result)
console.log("Total number of days between dates
"
               + date1 + "
 and
"
               + date2 + " is:
 "
               + Difference_In_Days);

Comment: but i can display value in textbox
Comment: document.getElementById("numdays2").value = Difference_In_Days;
Answer: at the first place identifiers are wrong
at the second place use getTime function to get milliseconds
at the third place add brackets to evaluation expression to get difference in days
var difference = dropdt.getTime() - pickdt.getTime();
return Math.round(difference / (1000 * 3600 * 24));

Comment: and add brackets difference / (1000 * 3600 * 24)
Comment: @HitendraPatil please check this https://codepen.io/dimoff66/pen/GRgKdXW?editors=0001
Comment: my date format is dd/mm/yyyy and you are using yyyy/mm/dd
Comment: @HitendraPatil, it has nothing to do with my code, new Date doesnt accept your format, i changed my example, now it works correctly with your format https://codepen.io/dimoff66/pen/GRgKdXW?editors=0002


Using Autocomplete populate more than one field

Question: I am trying to implement auto complete via jquery auto complete plugin.
I have used the script from here jQuery UI autocomplete.
I currently have a field called 'Search Infections' where I am storing the 'Description'.

Search Infection

<input id="tags" type="text"  size="80" />

this works fine for autocomplete.
I also have a field called 'Short code' in which I want to store the Code.

Short Code

<input id="" type="text"  size="15" />

Is there a way I could store the code in the 'short code' field when a user search the Description in the infection field?
Please, please help.
  CODE and DESCRIPTION list.

  ---------------------------------------------------------
  Code  Description
  ---------------------------------------------------------
  ID01  Actinomycosis
  ID02  Aspergillosis
  ID03  Bacteraemia / blood stream infection/ Septicaemia
  ID04  Bacterial meningitis
  ID05  Bronchiectasis
  ID06  Candidiasis
  ID07  Carotid patch infection
  ID08  Cellulitis
  ID09  Cerebral abscess
  ID10  Cholangitis
  ---------------------------------------------------------------------
  =====================================================================

Comment: This is not clear for me, you are trying to get the Id of the infection in the 'short code' td when doing an autocomplete (but in behind)?
Comment: I haven't tested, but I think you should be able to bind an onchange to the completion field to accomplish what you want.  $('#tags').bind('change', function(e) { //do your thing });
Comment: One more question, are you using PHP for this?
Comment: i am using csp (cache server page). i basically want to link the code with the description whilst doing the autocomplete. (yes the code populates in the behind)
Answer: Try to this link.
That's sample code is :
var availableTags = [
    {key:"ID01",value:"Actinomycosis"},
    {key:"ID02",value:"Aspergillosis"},
    {key:"ID03",value:"Bacteraemia / blood stream infection/ Septicaemia"}
];

http://jsfiddle.net/5EsAb/3/
Answer: I made this for you:
I also used a plugin for text events:
http://www.zurb.com/playground/javascripts/plugins/jquery.textchange.min.js
(to clean the short code when infection doesn't match with less code)
Live Demo: http://jsfiddle.net/oscarj24/SUckd/1/
Comment: this is exactally what i wanted. thanks. when i load it on my page it doesent seem to work i am using
Comment: Oscar many thanks ... works great. everyones help much appreciated.
Comment: @jk1844 No problem, I am here to help. Don't forget to check this answer as the correct one :-)
Comment: one last question, actually i have about more than 100 infections. is it possible to have a scroll bar if more that 10 results?
Comment: this jquery autocomplete plugin will match things for not losing it's design, for example if I write 'C' will filter everything with 'C' and design will look good, so no problem for the scroll bar :-) One question, are you getting the infections from a database?
Comment: i do have a table in the database with all the infections. is there a way to look up(or search) the data from the table, rather than list them in jquery script? thanks
Comment: Are you using PHP? yes, there is a way to get the elements from db using jquery, its easy but I need to know the language
Comment: i use intersystems Cache, csp (cache server page). [link](http://www.intersystems.com/cache/index.html) similar to SQL
Comment: Uhm, thats new for me, but what programming language are you using for your system?
Comment: The language itself is called 'cache' we create forms on the csp pages (works like html page or like ASP). we query the database using cachesql similar to sql.
Comment: Oh, I am sorry thats new for me, I heard about it but never use it, I know how to get data from db using PHP and jQuery, not CSP :-)
Comment: probably you could give me the idea of how to introgate data from db using jquery and/or PHP. iwill see if i could adopt it in Cache. many thanks.


Como escolher o maior valor de um array?

Question: Estou tentando utilizar a função max, mas não consigo acertar.
// variáveis da diferença salarial
$saldev[0] = $_POST ["Tdate5"];
$saldev[1] = $_POST ["Tdate9"];
$saldev[2] = $_POST ["Tdate13"];
$saldev[3] = $_POST ["Tdate17"];
$saldev[4] = $_POST ["Tdate21"];

$saldev2 = max($saldev);

(Nota: O código acima funciona da forma como está. Devido a um erro inexplicável recebi algumas saídas erradas e criei a pergunta, e à partir de algumas dicas descobri que estava funcionando (ok, é confuso, mas o que importa é que está funcionando). A hipótese com ksorttambém funciona para o mesmo efeito, então escolhi ela como resolvido)
Mas a saída do var_dump de $saldev após o envio do formulário com os campos preenchidos, é:

array(5) { [0]=> string(0) "" 1=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" [4]=> string(0) "" }

E o de $saldev2 é:

string(0) ""

O HTML do form está dentro de uma grande tabela, vou incluir um dos campos input (todos são assim):

<input type="text" id="Cvpos5" name="Tdate5" size="10" class="preco">

Answer: Existe uma função para ordenar um array pelas chaves em ordem decrescente - krsort
Use krsort para ordenar o array de forma decrescente e basta usar current para recuperar o primeiro elemento, pois krsort mantém a correlação entre entre as chaves e os valores.
$saldev[] = 'Tdate5';
$saldev[] = 'Tdate9';
$saldev[] = 'Tdate13';
$saldev[] = 'Tdate17';
$saldev[] = 'Tdate21';

krsort($saldev);
echo current( $saldev );

Output:
Tdate21

Answer: A função max espera receber um array de números, então faça assim:
$saldev[0] = (double) $_POST ["Tdate5"];
$saldev[1] = (double) $_POST ["Tdate9"];
$saldev[2] = (double) $_POST ["Tdate13"];
$saldev[3] = (double) $_POST ["Tdate17"];
$saldev[4] = (double) $_POST ["Tdate21"];

$saldev2 = max($saldev);

Answer: Tem um espaço na sua linha, o colchete deveria "encostar" na variável:
$saldev[0] = $_POST["Tdate5"];

Além disso, certifique-se que o form contem method="post" ou ele enviará os dados por GET. Quando enviados por GET os valores ficam acessíveis via algo como $_GET["Tdate5"], que além de ser menos recomendado na maioria dos casos não funcionaria nunca utilizando $_POST.
Exemplo:
<form method="post">

Se mesmo assim não funcionar, poste o form e as URLs utilizadas, mas pela minha experiência isso deve resolver..


Birth time of files are missing if file is created in a logical volume with size less than 512 MB

Question: I have a volume group in my system, created with single physical volume.
I'm creating two logical volumes - one with size 100M and one with size 512M.
Any file created on LV with 100M size does not display birth-time attribute.
LV with size 512M does not have this issue.
Any clue on why is this so?
Physical volume and volume group:
# pvdisplay
  --- Physical volume ---
  PV Name               /dev/sda4
  VG Name               VG_System
  PV Size               400.00 GiB / not usable 4.00 MiB
  Allocatable           yes
  PE Size               4.00 MiB
  Total PE              102399
  Free PE               38099
  Allocated PE          64300
  PV UUID               Awnq0n-24v1-Z53P-MC09-3Fvv-dc0r-6QvAyX

# vgdisplay VG_System
  --- Volume group ---
  VG Name               VG_System
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  25
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                24
  Open LV               22
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               <400.00 GiB
  PE Size               4.00 MiB
  Total PE              102399
  Alloc PE / Size       64300 / 251.17 GiB
  Free  PE / Size       38099 / 148.82 GiB
  VG UUID               Zg53rH-kuCI-dWKa-Uo3H-Mr2i-G2As-Wflm0d

First LV:
# lvcreate --stripes 1 -n testing -L 100M VG_System
  Logical volume "testing" created.

# mkfs.ext4 /dev/VG_System/testing
mke2fs 1.45.6 (20-Mar-2020)
Discarding device blocks: done
Creating filesystem with 102400 1k blocks and 25688 inodes
Filesystem UUID: ac9c1782-7770-4031-bad8-9b76f7577467
Superblock backups stored on blocks:
        8193, 24577, 40961, 57345, 73729

Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done

# blkid /dev/VG_System/testing
/dev/VG_System/testing: UUID="ac9c1782-7770-4031-bad8-9b76f7577467" BLOCK_SIZE="1024" TYPE="ext4"

# mount /dev/VG_System/testing /mnt/test
# mount | grep test
/dev/mapper/VG_System-testing on /mnt/test type ext4 (rw,relatime,stripe=4)

# touch /mnt/test/a
# stat /mnt/test/a
  File: /mnt/test/a
  Size: 0               Blocks: 0          IO Block: 1024   regular empty file
Device: 252,23  Inode: 12          Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-04-13 22:13:43.000000000 +0530
Modify: 2023-04-13 22:13:43.000000000 +0530
Change: 2023-04-13 22:13:43.000000000 +0530
 Birth: -

Here the Birth field is empty.
Second LV:
# lvcreate  -n testing2 -L 512M VG_System
  Logical volume "testing2" created.

# mkfs.ext4 /dev/VG_System/testing2
mke2fs 1.45.6 (20-Mar-2020)
Discarding device blocks: done
Creating filesystem with 131072 4k blocks and 32768 inodes
Filesystem UUID: 0b5e24a9-cdf1-4749-9089-bf0cf1495185
Superblock backups stored on blocks:
        32768, 98304

Allocating group tables: done
Writing inode tables: done
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done

# blkid /dev/VG_System/testing2
/dev/VG_System/testing2: UUID="0b5e24a9-cdf1-4749-9089-bf0cf1495185" BLOCK_SIZE="4096" TYPE="ext4"

# mount /dev/VG_System/testing2 /mnt/test2
# mount | grep test
/dev/mapper/VG_System-testing2 on /mnt/test2 type ext4 (rw,relatime)

# touch /mnt/test2/a
# stat /mnt/test2/a
  File: /mnt/test2/a
  Size: 0               Blocks: 0          IO Block: 4096   regular empty file
Device: 252,24  Inode: 12          Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-04-13 22:19:01.873047858 +0530
Modify: 2023-04-13 22:19:01.873047858 +0530
Change: 2023-04-13 22:19:01.873047858 +0530
 Birth: 2023-04-13 22:19:01.873047858 +0530

Note sure if it is relevant, but the mount options of first LV has stripe=4, where as second one does not have this.
Other than this, both LVs are similar.
# lvdisplay VG_System/testing
  --- Logical volume ---
  LV Path                /dev/VG_System/testing
  LV Name                testing
  VG Name                VG_System
  LV UUID                n19sRr-SqHW-znjI-0fEW-MkQX-JRUn-MTmZHF
  LV Write Access        read/write
  LV Creation host, time controller, 2023-04-13 22:12:45 +0530
  LV Status              available
  # open                 0
  LV Size                100.00 MiB
  Current LE             25
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:23

# lvdisplay VG_System/testing2
  --- Logical volume ---
  LV Path                /dev/VG_System/testing2
  LV Name                testing2
  VG Name                VG_System
  LV UUID                94oJKP-r2Ob-ReHr-sDSO-t3HY-isJB-ZtEPsq
  LV Write Access        read/write
  LV Creation host, time controller, 2023-04-13 22:18:01 +0530
  LV Status              available
  # open                 1
  LV Size                512.00 MiB
  Current LE             128
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:24

Answer: It is not Issue with LVM. It is Issue with Ext4.
When the filesystem size is less than 512 MB , Ext4 uses Default Inode Size = 128 Bytes , which is not enough to store the "extended metadata".
When the filesystem size is more than 512 MB , Ext4 uses Default Inode Size = 256 Bytes , which is enough to store the "extended metadata" including "Birth time" @ offset 0x90 & offset 0x94.
More Details :
https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout#Inode_Table
You can try this :
mkfs.ext4 -I 256 /dev/VG_System/testing

This will force Inode Size = 256 on the Smaller filesystem.
More Details :
https://manpages.debian.org/bullseye/e2fsprogs/mke2fs.8.en.html
Comment: @m.divya.mohan of course now there are 1/2 as many inodes on the 100MB volume.  That could become a problem.


Problemas ao enviar notificação

Question: Estou usando o seguinte código para enviar notificação a partir do android e não do console
public static void pushFCMNotification(String userDeviceIdKey) throws Exception
{

        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization","key=AIzaSyCEwVIxZv_..._hHEmAO0");
        conn.setRequestProperty("Content-Type","application/json");

        JSONObject json = new JSONObject();
        json.put("to",userDeviceIdKey.trim());
        JSONObject info = new JSONObject();
        info.put("title", "Enviando msg");   // Notification title
        info.put("body", "cadastrou"); // Notification body
        json.put("notification", info);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(json.toString());
        wr.flush();
        conn.getInputStream();

    }

Não aparece nenhum erro na aplicação, simplesmente o código é executado e não funciona.

W/EGL_emulation: eglSurfaceAttrib not implemented W/EGL_emulation:
  eglSurfaceAttrib not implemented W/System.err:
  android.os.NetworkOnMainThreadException W/System.err:     at
  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
  W/System.err:     at
  java.net.InetAddress.lookupHostByName(InetAddress.java:385)
  W/System.err:     at
  java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
  W/System.err:     at
  java.net.InetAddress.getAllByName(InetAddress.java:214) W/System.err:
  at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
  W/System.err:     at
  com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
  W/System.err:     at
  com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
  W/System.err:     at
  com.android.okhttp.internal.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:254)
  W/System.err:     at
  com.alpha.tec.agendaonline.Evento.EventosCad.pushFCMNotification(EventosCad.java:188)
  W/System.err:     at
  com.alpha.tec.agendaonline.Evento.EventosCad$1.onClick(EventosCad.java:84)
  W/System.err:     at android.view.View.performClick(View.java:4438)
  W/System.err:     at
  android.view.View$PerformClick.run(View.java:18422) W/System.err:
  at android.os.Handler.handleCallback(Handler.java:733) W/System.err:
  at android.os.Handler.dispatchMessage(Handler.java:95) W/System.err:
  at android.os.Looper.loop(Looper.java:136) W/System.err:     at
  android.app.ActivityThread.main(ActivityThread.java:5045)
  W/System.err:     at java.lang.reflect.Method.invokeNative(Native
  Method) W/System.err:     at
  java.lang.reflect.Method.invoke(Method.java:515) W/System.err:     at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
  W/System.err:     at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
  W/System.err:     at dalvik.system.NativeStart.main(Native Method)
Answer: O erro ocorre pois você está tentando abrir uma conexão na Thread principal  da aplicação ( NetworkOnMainThreadException ).
Neste caso é necessário executar esta operação em uma AsyncTask
Segue um exemplo:
  public class AsyncConnection extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... strings) {

        final String userDeviceIdKey = strings[0];
        URL url = null;
        try {
            url = new URL("https://fcm.googleapis.com/fcm/send");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization","key=AIzaSyCEwVIxZv_..._hHEmAO0");
            conn.setRequestProperty("Content-Type","application/json");

            JSONObject json = new JSONObject();
            json.put("to",userDeviceIdKey.trim());
            JSONObject info = new JSONObject();
            info.put("title", "Enviando msg");   // Notification title
            info.put("body", "cadastrou"); // Notification body
            json.put("notification", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();
            conn.getInputStream();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
     }
   }

Para executar a operação chame da seguinte forma:
new AsyncConnection().execute(userDeviceIdKey);

Problemas ao enviar notificação


Image resize handler visible outside of tinymce editor area if image is bigger than editor in IE

Question: I'm using tinymce 3.5.8 version. In IE8 when i am adding the big images the resize handler comes out of the editor.please help me.
Answer: Had the same problem. The solution is to set the unselectable attribute to images.
I do this on image insertion and editor init:
$(ed.getBody()).find('img').attr('unselectable', 'on');

Before saving my content to db i remove the attribute.
Comment: @Thariama, I seen that you have answered many tinymce question on stckoverflow, so I wan to ask one thing I am having a problem with re-size handlers, they does not appear where images are. same thing happen with table re-size. please give me a solution
Comment: @Thariama please check my question here : http://stackoverflow.com/questions/17779780/tinymce-resize-scale-handelers-are-not-in-the-same-place-as-resize-object
Comment: @HowToPlease: i will have a look later


remove last pipe-delimited value from dataframe column in pyspark

Question: I am using spark 2.1 and have a dataframe column contain value like AB|12|XY|4.
I want to create a new column by removing the last element, so it should show like AB|12|XY.
I tried to split, rsplit did not work, so need some suggestion to get the desired output.
Answer: Use the Spark SQL split function as follows:
>>> from pyspark.sql.functions import split
>>> json_data = ['{"c1":"AB|12|XY|4"}','{"c1":"11|22|33|44|remove"}']
>>> df        = spark.read.json(sc.parallelize(json_data))
>>> df.show()
+------------------+
|                c1|
+------------------+
|        AB|12|XY|4|
|11|22|33|44|remove|
+------------------+

>>> df2 = df.withColumn("c2", split(df.c1, '\|\w+$')[0])  # split takes a regex pattern
>>> df2.show()
+------------------+-----------+
|                c1|         c2|
+------------------+-----------+
|        AB|12|XY|4|   AB|12|XY|
|11|22|33|44|remove|11|22|33|44|
+------------------+-----------+

If you need to do something more complicated that can't be implemented using the built-in functions, you can define your own user-defined function (UDF):
>>> from pyspark.sql.functions import udf
>>> from pyspark.sql.types import *
>>> def my_func(str):
...   return str.rsplit('|',1)[0]
...
>>> my_udf    = udf(my_func, StringType())
>>> json_data = ['{"c1":"AB|12|XY|4"}','{"c1":"11|22|33|44|remove"}']
>>> df        = spark.read.json(sc.parallelize(json_data))

>>> df2 = df.withColumn("c2", my_udf(df.c1))
>>> df2.show()
+------------------+-----------+
|                c1|         c2|
+------------------+-----------+
|        AB|12|XY|4|   AB|12|XY|
|11|22|33|44|remove|11|22|33|44|
+------------------+-----------+

Built-in SQL functions are preferred (also here) because your data does not get passed back and forth between the JVM process and the Python process, which is what happens when you use a UDF.


Why is the tangent bundle defined using a disjoint union?

Question: In textbooks about differential geometry, one finds often the disjoint union in the definition of the tangent bundle (e.g. in "Lee: Introduction to smooth manifolds", or "Amann, Escher: Analysis III"):
$$T\mathcal{M}:=\coprod_{p\in\mathcal{M}}T_{p}\mathcal{M}:=\bigcup_{p\in\mathcal{M}}\{p\}\times T_{p}\mathcal{M}$$
I have the following questions:
(1) Why is this necessary? Is it necessary for the definition of the smooth structure on $T\mathcal{M}$?
(2) When we define the tangent space as the set of all derivations (like in Lee's book), aren't $T_{p}\mathcal{M}$ and $T_{q}\mathcal{M}$ for $p\neq q$ allready disjoint? Why is it then necessary to use the disjoint union? Is it just a notation in this cases? How about other definitions of tangent spaces, like the geometric defined tangent space, via equivalence classes of curves?
(3) How about other bundles? Also in the definition of tensor fields and differential forms, these authors often use the disjoint union...
Thank you all!
Answer: You are right, the "usual" constructions of $T_p M$ as a set of derivations or a set of equivalence classes of curves produces disjoint tangent spaces at distinct points. Thus you could define $T'M = \bigcup_{p \in M} T_pM$ which is the union of pairwise disjoint vector spaces. I used $T'M$ to distinguish it from $TM = \bigcup_{p \in M} \{p\} \times T_pM$.
Has $T'M$ any benefit in comparison to $TM$? There exists a canonical bijection between both sets, and if we introduce the usual smooth structure on $TM$ and (mutatis mutandis) on $T'M$, then this bijection turns out to be a diffeomorphism.
You might argue that the bundle projection $\pi' : T'M \to M$ has the property that the fiber over $p$ is the "true" tangent space $T_pM$, whereas $\pi : TM \to M$  has the fiber $\{p\} \times T_pM$ which is only a copy of $T_pM$. But as you know, there are various constructions for $T_pM$ which yield formally different vector spaces. Hence it is a rather philosophical question what the true variant should be, and $\{p\} \times T_pM$ has the same right as $T_pM$.
In my opinion it is just a matter of taste if you want to work with $TM$ or $T'M$. The same applies of course to other bundles like tensor bundles, cotangent bundles, etc.
Here is an example where the additional $\{p\}$ is useful. For smooth submanifolds $M \subset \mathbb R^N$ there is a nice geometric construction of the tangent space at $p$: Take all smooth curves $c$ in $\mathbb R^N$ whose image is contained in $M$ and which go through $p$ at some $t_0$. Then the set of all derivatives $c'(t_0)$ forms an $\dim M$-dimensional linear subspace $\tilde T_pM$ of $\mathbb R^N$. These $\tilde T_pM$ are not pairwise disjoint. We need the point $p$ to make them disjoint and then define
$$\tilde T M =  \bigcup_{p \in M} \{p\} \times \tilde T_pM \subset \mathbb R^{2N}.$$
It turns out that this a smooth submanifold of $\mathbb R^{2N}$ which is diffeomorphic to the abstract $TM$.
Answer: In my book Introduction to Smooth Manifolds, I define $T_pM$ as the set of all linear maps $v\colon C^\infty(M)\to\mathbb R$ that satisfy
$$
v(fg) = f(p)vg + g(p)vf
$$
for all $f,g\in C^\infty(M)$. Note that the zero map is an element of all these spaces, so $T_pM$ and $T_qM$ are not disjoint for $p\ne q$.
For other definitions of tangent vectors, disjointness might follow automatically. Using the disjoint union in the definition of the bundle is just a handy way to ensure that the vector spaces associated with different points are disjoint regardless of the definition being used.


target specific HTML element from an object that is mapped

Question: So I have replicated my issue on a smaller level so its easier to work with. The goal is to have an onclick function that shows the content inside the column which is hidden as default, this will ideally be handled through setting display: none and changing to display: flex. I have to use an object hence lodash. I cant use document.getElement because all mapped components share a common classname. The data comes from a database so the amount of columns is unknown and always changing per user requirements.
I guess im looking for a method to target to the classname of the div/tag of the iteration of the map where the onclick for that container is. Any help is appreciated!
import _ from "lodash"
import React from 'react'

const dummyData = {
    columnOne: "item one",
    columnTwo: "item two",
    columnThree: "item three"
}

function TestPage() {
    return (
        _.map(dummyData, (data, key) => {
            return (
                <>

{key}

V
 //button to toggle content visibility

{data}
 //content to be hidden/shown
                </>
            )
        }

        )
    )
}

export default TestPage

Answer: You can use useState to store classnames and then toggle them with onClick function by changing state with setState.
See this answer. I think it contains what you want.
Comment: Right, and im assuming 'this' allows me to target to div the onclick is attached to
Comment: @coldharbour Yes, but since you're using a functional component, you don't need the 'this.state'. It will work like stateVar.active, assuming you created the state variables like "const [stateVar, setStateVar] = useState({active: false})"
Answer: One way of doing this is by making a separate component for HTML which return from map function and handle state in it.  Like:
import _ from "lodash";
import React from "react";

const dummyData = {
  columnOne: "item one",
  columnTwo: "item two",
  columnThree: "item three"
};

function Data({ id, data }) {
  const [show, setShow] = React.useState(false);
  return (
    <>

{id}

          <button onClick={() => setShow(!show)}>V</button>

      {show &&
{data}
}
    </>
  );
}
function TestPage() {
  return _.map(dummyData, (data, key) => {
    return <Data key={key} id={key} data={data} />;
  });
}

export default TestPage;

Comment: The actual project im working on is significantly larger than the demo i provided and im trying to minimise code at this point haha but ill keep it in mind if i cant figure anything else out, thank you!!


Unused or variables only used for control flow in onnx model

Question: I have an onnx model, which has some (ideally) boolean inputs, that are only used for control flow within the model.
Some minimal code for what I try to do:
import onnx
import onnxruntime
import torch.onnx

class SumModule(torch.nn.Module):
  def forward(self, x1, x2):
    if x2 is not None:
      x1 *= 1
    return torch.sum(x1)

torch_model = SumModule()
torch_model.eval()
model_inputs = {'x1': torch.tensor([1, 2]), 'x2': torch.tensor([1, 2])}

torch_out = torch_model(**model_inputs)
torch.onnx.export(torch_model,
                  tuple(model_inputs.values()),
                  'model.onnx',
                  export_params=True,
                  opset_version=16,
                  do_constant_folding=True,
                  input_names=list(model_inputs.keys()),
                  output_names=['output'],
                  dynamic_axes={'x1': {0: 'batch_size'}, })

onnx_model = onnx.load('model.onnx')
onnx.checker.check_model(onnx_model)

ort_session = onnxruntime.InferenceSession('model.onnx')

def to_numpy(tensor):
  if isinstance(tensor, torch.Tensor):
    return tensor.detach().cpu().numpy()
  return tensor

model_inputs_np = {k: to_numpy(v) for k, v in model_inputs.items()}
ort_outs = ort_session.run(None, input_feed=model_inputs_np)

While the onnx export goes through, I cannot run the inference model without the error
onnxruntime.capi.onnxruntime_pybind11_state.InvalidArgument: [ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Invalid Feed Input Name:x2

I think I misunderstand something fundamental with onnx here. The argument x2 obviously exists, why does onnx discard it somehow? The same happens if I don't use the argument x2 at all (but have it as an input argument), which I also find weird.
In my actual code, the control flow I want to do is the following:
I have 3 inputs that are optional, so ideally it would be Optional[torch.Tensor]. However, onnx seems to be unable to deal with None. So instead I wanted to have the 3 inputs + 3 boolean flags (torch.tensor(True) or if need be torch.tensor([True]) or replace Truewith1or1.0` --> Same issue with all of those).
Then within the code I do different things based on those flags.
Why does onnx not allow this? I found out that having those variables if fine if I somehow include them in some computations sometimes, but I can't figure out the rule behind all of this.
Answer: Your problem is related to how torch.onnx.export works.
When generating the ONNX model, torch executes (traces) the module once with given inputs while keeping track of all performed computations, then maps them to the corresponding ONNX Operators, and finally simplifies the graph. In your case, the noteworthy detail is that all control flows are evaluated once and Python built-in types are evaluated as constants. So the code
if x2 is not None:
    x1 *= 1
return torch.sum(x1)

is saved as
if True:
    x1 *= 1
return torch.sum(x1)

and when torch.onnx.export simplifies the graph, it removes all unused variables including x2, hence your error.
If you want to preserve control flow in your exported model, you need torch to evaluate your model with torch.jit.script instead of torch.jit.trace. As you've already pointed out, ONNX expects a fixed amount of tensors as inputs, and does not accept "optional" arguments. Exporting the model with Scripting is done like this
scripted_model = torch.jit.script(torch_model)
torch.onnx.export(scripted model, ...)

However, with this your model will still not work. We notice that the if statement in your forward pass is a Pythonic comparison, and doesn't operate on the tensor itself. So x2 will still be discarded during simplification. Changing SumModel to
class SumModule(torch.nn.Module):
  def forward(self, x1, x2):
    if torch.any(x2):
      x1 *= 1
    return torch.sum(x1)

will yield the correct graph, since now x2 is actually operated on. With this, you could use x2 as a boolean flag for control flow.
Highly recommend looking into the torch documentation, as it explains a lot of common mistakes in regard to exporting.
EDIT
For completeness, I should add that the aforementioned approach should generally be avoided. Much of the hardware acceleration is not designed for conditionals, and trying to run ONNX models containing a lot of control flow with, for example CUDA, often leads to large parts of the graph falling back to CPU. When presented with a situation described in this question, I would recommend to consider

If you can input the "optional" tensors as zeros without affecting the result
If it makes sense to split the model into different several models altogether, and running each one for the corresponding input

Rather than using the solution presented above


Why use two stage least squares for the instrumental variable estimator?

Question: Following the rationale from Econometric Methods with Applications in Business and Economics by Heij et al., the instrumental variables estimator $b_{IV}$ for the linear regression model
$y = X\beta + \varepsilon$
with instrumental variables $Z$ (with more variables than $\#\beta$) is given by
$b_{IV} = (X'Z(Z'Z)^{-1}Z'X)^{-1}X'Z(Z'Z)^{-1}Z'y$.
The book proposes calculating this $b_{IV}$ using two stage least squares:

Regress each column of $X$ on $Z$, resulting in $\hat{X} = Z(Z'Z)^{-1}Z'X$
Regress $y$ on $\hat{X}$, with parameter estimates $b_{IV} = (\hat{X}'\hat{X})^{-1}\hat{X}'y$

Am I wrong by thinking that calculating $b_{IV} = (X'Z(Z'Z)^{-1}Z'X)^{-1}X'Z(Z'Z)^{-1}Z'y$ directly wil yield the same results as two stage least squares, since
$b_{IV} = (X'Z(Z'Z)^{-1}Z'X)^{-1}X'Z(Z'Z)^{-1}Z'y = (\hat{X}'\hat{X})^{-1}\hat{X}'y$?
And if it will yield the same results, why does the book give any attention to two stage least squares, and doesn't just leave it at something like
"you can calculate the instrumental variables estimator using the equation $b_{IV} = (X'Z(Z'Z)^{-1}Z'X)^{-1}X'Z(Z'Z)^{-1}Z'y$."
?
Comment: I think you're correct, but the main reason for doing two stages (as I understand it) is that you may want to treat *some* of your $x$ variables as endogenous, and some as exogenous. Your method (I think) treats all of them as endogenous.
Answer: I haven't gone through your math against a good text, and my 2SLS theory is a little stale.
But I think you are right.  Obviously, 2SLS involves doing a stage one with the instrumental variables to develop a new (transformed) set of variables in the form of $\hat{X}$ from the instruments.  And step two is simply OLS, as I recall, with that.
Provided the construction of the $\hat{X}$ matrix can be done as simply algebraic manipulations, then it is just plugging this into the second stage formula.
If that is correct - and I don't see why not - the explanation may be to help remind the motivation of doing 2SLS.  The goal of that first stage is to get you a set of independent variables that have the right qualities - e.g., uncorrelated with the error term or filling in for a missing effect.
Comment: Thank you for your answer! I think you are right. The lecture slides that accompany this book simply compare the $b_{IV}$ above (which is derived from the GMM framework) with the 2SLS estimator, and show that they are equal. I think the book also tries to make this point, but does not conclude the argumentation.
Answer: Also, you want the instrumental variable to have some correlation with the "tainted" variable that was in the original regression. You will be able to see that correlation when you run the 1st stage of 2SLS.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).