Probability of independent events within a specified window

Question: So I have an event that can occur on a daily basis with probabilty 1%. There is no dependence between days. Now I can calculate the probabality of the event occuring X times in Y days:
  COMBIN(Y,X) * (0.01 ^ X) * [0.99 ^ (Y - X)]

where COMBIN() is the number of combinations for X in Y. Now what I'd like to calculate is the probablity of X events in any Y window for the last Z days, e.g what is the probability of 5 events occuring in at least one 30 day window during the last 10 years. Any assistance much appreciated.
Thanks
Note: Original question edited to add "at least" qualifier per MansT suggestion below.
Comment: Analytical answers are preferable, but given its not homework, I am curious why you don't use brute force Monte Carlo simulation.
Comment: If this is homework, it should have the homework tag.
Comment: Not homework, real world problem cast in generalised terms... my stats is a bit rusty
Comment: Do you mean "the probability of 5 events in at least one 30 day window for the last 10 years"?
Comment: @MånsT - yes exactly
Comment: @phaneron: yes I may well do this; but analytical proof is preferable.
Answer: If the days are truly independent as you say then let us denote an event A as X events in any Y day period and denote P(A), the probability of X events in Y days:
P(A) = COMBIN(Y,X) * (0.01 ^ X) * [0.99 ^ (Y - X)]
This is true for any Y day window provided the probability of an event occurring is not time dependent.
Then you can apply the Binomial probability again to the event A.  We have to be careful because now the event A is not independent for overlapping windows, i.e. for a window of length 10, the probability of event A on days 1-10 is not independent of days 2-11.  Thus the following is assuming non-overlapping windows to ensure independence.  Now,  because you want the probability of at least one non-overlapping window having an event, it is easier to do:
1 - P(no overlapping windows satisfying event A).
Let n be the number of non-overlapping windows of size Y in time period Z.  Then the probability of X events in a non-overlapping window of size Y over a time period Z is:

1 - COMBIN(n,0) * P(A)^0 * [1-P(A)]^(Y-0)
= 1 - n * [1-P(A)]^Y
Comment: This would answer the question if it were about months and not windows. I believe that a window is defined as 30 consecutive days (correct me if I'm wrong, @Richard). January 1-30 is a window, but so is January 2-31. The windows are not independent in that case. Indeed, window $i+1$ can only have $X$ events if window $i$ has at least $X-1$ events.
Comment: MansT is correct, there is an implied assumption that the windows are independent.  I've edited my response to make it clear that the solution is for *non-overlapping* windows.
Comment: @aduniac - yes I am looking for a solution for over-lapping windows, not adjacent non-overlapping windows.
Comment: @MansT - your understanding of the problem is correct: probability of X number of events in _any_ 30 day window in the last 10 years.
Answer: Here is some code, a brute-force approach, to get a ballpark for the probability.
In this I assume that the particular 30 day window does not matter. If there were 3 at the end of one month and 2 at the beginning of the next, I still count it as 5 in a row.
set.seed(1)

#number of runs
N <- 5e5

#max number of events per month (simulation tops out around 4)
n_max <- 10

#other parameters
n_years <- 10
days_per_year <- 365.24

#would be number of rows if year change was reset
n <- floor(n_years*days_per_year)

#sample is wrapped in this to handle workspace and memory
#find run lengths
my_rle <- rle(rbinom(n = n*N,prob = 0.01,size = 1))

#find run-lengths that refer to "TRUE" values sequences
idx <- which(my_rle$values ==1)

#subset out non-zero runs
cus_y <- my_rle$lengths[idx]

#pre-declare for loop
store<- numeric(length = n_max)

#put zeros into a single bin
store[1] <- sum(my_rle$lengths[-idx])/n/N

#find bin frequenceis
for (j in 1:(n_max-1)){
  store[j+1] <- length(which(cus_y==j,arr.ind=T))/n/N
}

#stage for plot and model
x    <- 0:(n_max-1)
y <- log10(store)

#subset to non-nan values
y1 <- y[1:5]
x1 <- seq(from=0,to=4,by=1)

#fit model
est <- lm(y1~x1)
summary( est)

#extrapolate
x2 <- 5
y2 <- est$coefficients[1]+est$coefficients[2]*x2
y2

#main plot
plot(x,y,ylab="Log10 frequency", xlab="run length",ylim = c(-10,0))
grid()
abline(est)

points(x2,y2,pch=19,col="Red",cex=1.2)

Here is the plot that I get

The fit gave me this summary:
> summary( est)

Call:
lm(formula = y1 ~ x1)

Residuals:
         1          2          3          4          5
 0.0072500  0.0007404 -0.0025619 -0.0260976  0.0206690

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.01161    0.01528   -0.76    0.503
x1          -1.99795    0.00624 -320.21 6.72e-08 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.01973 on 3 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 1.025e+05 on 1 and 3 DF,  p-value: 6.717e-08

Using the coefficients gives -10.00137 as the expected log10 of frequency for runs of 5 in a row.  This is ~1e-10.  The estimated probability for a 5-element sequence at any time is 1e-10, or (0.01^5).


Perl Dereferencing Syntax

Question: What is the syntax to dereference a reference in Perl?

Answer: Whenever you can use the name of a variable, you can use a block that evaluates to a reference instead. For example, the following are valid syntax for specifying an array:
@NAME    # If you have the name      e.g. @array
@BLOCK   # If you have a reference   e.g. @{ $ref }

This is the "circumfix syntax" illustrated in the table below.
An alternative syntax colloquially known as the "arrow notation" is easier to read, but requires Perl 5.20+ in some cases. This is the "postfix syntax" illustrated in the table below.

                              Direct           Using References     Using References
                                               Circumfix Syntax[1]   Postfix Syntax

scalar  itself                $s               ${$sr}               $sr->$* [3]

array   itself                @a               @{$ar}               $ar->@* [3]
array   element               $a[0]            ${$ar}[0]            $ar->[0]
array   slice                 @a[0,1,2]        @{$ar}[0,1,2]        $ar->@[0,1,2] [3]
array   index/value slice[2]   %a[0,1,2]        %{$ar}[0,1,2]        $ar->%[0,1,2] [3]
array   last index            $#a              $#{$ar}              $ar->$#* [3]

hash    itself                %h               %{$hr}               $hr->%* [3]
hash    element               $h{'a'}          ${$hr}{'a'}          $hr->{'a'}
hash    slice                 @h{'a','b','c'}  @{$hr}{'a','b','c'}  $hr->@{'a','b','c'} [3]
hash    key/value slice[2]     %h{'a','b','c'}  %{$hr}{'a','b','c'}  $hr->%{'a','b','c'} [3]

code    call                  func(@args)
code    w/ prototype ignored  &func(@args)     &{$cr}(@args)        $cr->(@args)
code    w/ inherited @_       &func            &{$cr}               $cr->&* [3]

glob    itself                *glob            *{$gr}               $gr->** [3]
glob    slot                  *glob{ARRAY}     *{$gr}{ARRAY}        $gr->*{ARRAY} [3]

Notes:

The curly brackets around $sr, $ar, $hr, $cr and $gr are optional when the contents of the curlies is simply a scalar variable.
If they are used, those curlies form blocks, so they can actually contain multiple statements.

Requires Perl 5.20+.

Requires Perl 5.24+. Available in Perl 5.20+ by adding both use feature qw( postderef ); and no warnings qw( experimental::postderef );, or by adding use experimental qw( postderef );. This is safe because the then-experimental feature was accepted into Perl without change.

See also:

References Quick Reference
perlref
perlreftut
perldsc
perllol

Perl Dereferencing Syntax


Showing an affine set is a subset of another affine set

Question: I have a question regarding affine set.
Say given a vector space $V$,and two subspace say $U_1,U_2$ of $V$, and also given $x_1,x_2 \in V$. Also let $L_1$ = $x_1 +U_1$ and $L_2$ = $x_2 +U_2$
How do we show : $L_1 \subseteq L_2$ iff these two conditions $U_1 \subseteq U_2$ and $x_1 - x_2 =0$ are true.
Also I am little bit confused about what the $x_1,x_2$ could be, could they be vector like $x_1= [4,3,7,1]$, or $x_1,x_2$ has to be some constant number ?
I am new to affine space , so I am very confused.
Thank you
Comment: There is no such thing as a "constant number" in a vector space. Elements of a vector space are called vectors, so yes, $x_1$ and $x_2$ are vectors. After the choice of a basis (and assuming the space is finite dimensional), they may be written as a column with some coefficients inside it.
Comment: but could you also comment on how to solve the problem? thank you
Answer: Your statement is wrong. If $U_1=U_2,x_2=0$ and $x_1 \in U_2\setminus \{0\}$ then $L_1 \subset L_2$ but $x_1 \neq x_2$. The correct statement is $L_1 \subset L_2$ iff $U_1 \subset U_2$ and $x_1-x_2 \in U_2$.
Answer: As Kavi Rama Murthy stated it, the correct statement is $L_1 \subset L_2$ if and only if $U_1 \subset U_2$ and $x_1-x_2 \in U_2$.
For the direct implication, assume that $L_1 \subset L_2$. Then $x_1\in L_2=x_2+U_2$, which exactly means that $x_1-x_2 \in U_2$. Then, let us consider an element $z\in U_1$. We know by definition that $x_1+z$ belongs to $L_1\subset L_2=x_2+U_2$. It follows that $z\in (x_2-x_1)+U_2=U_2$ because we already know that $x_1-x_2 \in U_2$.
For the converse, assume that $U_1 \subset U_2$ and $x_1-x_2 \in U_2$. Let us consider any element of $L_1$. It can be written (uniquely) as $x_1+z$ for some $z\in U_1$. Then, $z\in U_2$ and our element $x_1+z$ may be written as $x_2 + (x_1-x_2+z)$. Because $x_1-x_2 \in U_2$, we know that this is an element of $x_2+U_2=L_2$, which is exactly what we wanted.
Comment: hi Suzet, sorry I am just wondering could you explain your first paragraph where you said $x_1 \in L_2 ...$, how does $L_1 \subset L_2$ implies $x_1 \in L_2 $?
Comment: This is because $x_1=x_1+0 \in L_1$. Remember that $0$ is an element that lies in every vector spaces, so in particular in $U_1$.


incoming SMTP not getting to my Azure VM Windows server 2012 C:\inetpub\mailroot\Drop

Question: This worked until November 2016.
Then, I shutdown the VM to save money because I didn't need it for awhile.
This year 2017 I restarted VM ok, but now SMTP is received, according to Wireshark and the SMTP log below, but incoming doesn't go to C:\inetpub\mailroot\Drop\ folder.
C:\Windows\System32\LogFiles\SMTPSVC1\ ...
<code>#Software: Microsoft Internet Information Services 8.5
#Version: 1.0
#Date: 2017-05-05 15:30:19
#Fields: time c-ip cs-method cs-uri-stem sc-status
15:30:19 18.104.22.168 EHLO - 250
15:30:19 220.127.116.11 MAIL - 250
15:30:19 188.8.131.52 RCPT - 550
15:30:24 188.8.131.52 QUIT - 240
15:36:56 188.8.131.52 EHLO - 250
15:36:56 18.104.22.168 MAIL - 250
15:36:56 22.214.171.124 RCPT - 550
15:37:02 220.127.116.11 QUIT - 240
#Software: Microsoft Internet Information Services 8.5
#Version: 1.0
#Date: 2017-05-05 16:09:34
#Fields: time c-ip cs-method cs-uri-stem sc-status
16:09:34 184.108.40.206 EHLO - 250
16:09:34 220.127.116.11 MAIL - 250
16:09:34 126.96.36.199 RCPT - 550
16:09:39 18.104.22.168 QUIT - 240
16:21:11 184.108.40.206 EHLO - 250
16:21:11 188.8.131.52 MAIL - 250
16:21:11 184.108.40.206 RCPT - 550
16:21:16 188.8.131.52 QUIT - 240
</code>
Comment: `16:21:11 126.96.36.199 RCPT - 550` - SMTP code 550 usually signifies an invalid recipient.
Answer: Problem was that my DNS provider changed my email domain name.
I fixed it:
IIS6 > SMTP Virtual ..  >  Domains  >  Domain Name:  add missing email domain name


Product Bundles & referenced products in Drupal Commerce

Question: What is the preferred way of retrieving referenced products when using hook_commerce_checkout_complete on a line item that is of type Product Bundle.
As an example, the customer has added Product ID 5 (which is a bundle consisting of Products 3 & 4).
How can find it's referenced products at the point of checkout completion?
Answer: In case anyone stumbles across this, you can use the following function:
<code>function commerce_product_bundle_get_sub_line_items(&$parent_line_item, $reset = FALSE){
    //...
}
</code>


How to visualize two bar charts with very different scales without looking redundant

Question: More an aesthetics question to do with presentation of statistical data, say you have 2 sets of data,

     speed     weight
a      2.2      500
b      4.7      222
c      7.3      999
d      3.1     1000

So if you plot the speeds and weights on the same bar chart, you will get squishy tiny bars for all the speed values (making them unreadable).  The data should be viewed together though, because there is some relationship between speed and weight that you're trying to show.
What I came up with was adjacent bar charts:

But it kind of looks redundant, with the repeated axes there.
Answer: It's OK to have two graphs share an axis.

But it's best to avoid one graph with two scales in the same dimension. There is too much potential for misreading (mainly assuming the alignment carries some significance). See the Stephen Few article Dual-Scaled Axes in Graphs: Are They Ever the Best Solution?.
Comment: +1 In my opinion, this is the most elegant approach if OP simply intends to efficiently show the weight and speed. If OP actually intends to visualize a dependency between weight and speed, a scatterplot would be preferred, as @gung describes. I also agree with xan that including two axes on a single plot often confuses interpretation and should usually be avoided.
Comment: There are good points here, but I don't necessarily agree. I think the best approach is going to depend on various factors. Few's article is interesting (thanks for the link, btw) but it's worth noting his point is people might be confused. Moreover, his advice is for the presentation of business data to people from a wide variety of backgrounds. Yes, it is crucially important that graphs quickly & clearly communicate the important information & not mislead. But, which strategy does this can depend on the audience.
Comment: In econ eg, time-series plots with 2 dif axes are commonly used, and people don't make the erroneous assumptions Few warns against, so they don't need to be "suppressed". OTOH, bar charts are commonly used to display group-level statistics, eg means, rather than simple magnitudes like here. Thus, *bars* could be misleading in some situations. Furthermore, Cleveland has shown that horizontal distances are more accurately read than vertical & dotplots more than bar charts. Thus, this might be a better strategy, but it might not.
Answer: You could also transform absolute scales into relative by using z-transformation (or any other that you think is more suitable).
speed  = c(2.2, 4.7, 7.3, 3.1)
weight = c(500, 222, 999, 1000)
speed=scale(speed)
weight=scale(weight)
rng=extendrange(range(c(speed,weight)))

plot(speed, type="b", col="red", ylim=rng,ylab="z-values",xlab="",xaxt="n",bty="n")
points(weight, type="b",col="blue")
legend("topleft",legend=c("speed","weight"),col=c("red","blue"),lty=1, bty="n",pch=1)
axis(1, at=lbls, labels=lbls)

The nice feature of this approach is that it can be used on more than two scales. And although it is not as informative on the values of individual points, it makes scales more comparable.
Comment: Oops, I overlooked z-transformation in gung's comment. Shame on me.
Comment: No problem, it's always nice to have another way to do it, even if it's just a different version of the same. +1
Answer: In general, if you have two different measurements on each of a set of observations, and you think there may be a relationship between them, I think it's best to visualize them with a scatterplot.  I don't know if you use R, but here is some simple code and a sample plot:
speed  = c(2.2, 4.7, 7.3, 3.1)
weight = c(500, 222, 999, 1000)

windows()
  plot(speed, weight)

This plot doesn't look very exciting, mainly because you only have 4 data points.
Another way to visualize data is to use a dotplot.  This is an especially good way to look at data that represent simple magnitudes, which is what would you have, if you were looking at only one of your variables.  Note that this is the same thing a bar chart provides, it's just that dotplots have been shown to be easier for people to extract the information.  The question is, can you look at two variables at the same time in such a way that you could perhaps see relationships, but without redundancy?
One way to deal with this general problem is to plot two variables on the same plot (in this case, the same dotplot).  This sort of thing is very commonly done with time series data in economics (here's one I found through Googling).  The trick is to find a way to get two different scales on the same plot.  This can be done by rescaling one of the variables in terms of the other; in addition, you must rescale the axis values of the other variable into the terms of the first.  These 'rescalings' must be linear transformations so as not to change the data in a meaningful way.  The following is some R code that does this in a way which is incredibly kluge-y, but that I hope will be easy to follow:
sM  = mean(speed);     wM  = mean(weight)
sSD = sd(speed);       wSD = sd(weight)

weightZ     = (weight-wM)   / wSD
convertedW  = (weightZ*sSD) + sM

sTicks      = c(0:8)
sTicksZ     = (sTicks-sM)    / sSD
convertedST = (sTicksZ*wSD)  + wM
convertedST = round(convertedST)

sY = seq(from=1.1, to=4.1, by=1)
wY = seq(from=0.9, to=3.9, by=1)

windows()
  plot(speed, sY, pch=1, col="red", axes=F, xlab="", ylab="", ylim=c(0.5, 4.5), xlim=c(0,8))
  points(convertedW, wY, pch=2, col="blue")
  abline(h=c(1:4), lty="dashed", col="lightgray")

  box()
  axis(side=2, at=c(1:4), labels=c("a","b","c","d"))
  axis(side=3, at=sTicks,                          col="red")
  axis(side=1, at=sTicks, labels=convertedST,      col="blue")

  mtext("Speed",  side=3, line=2.5, cex=1.5, col="red")
  mtext("Weight", side=1, line=2.5, cex=1.5, col="blue")

  legend("bottomright", legend=c("Speed", "Weight"), pch=c(1,2), col=c("red","blue"))

With smaller amounts of data, as you have here, this may be more informative.
Comment: Actually the two different horizontal axes on the same graph looks very good.  It seems I could turn these into bars (and not scatter plot) and have a similar result.
Comment: @bobobobo, there's really little difference between a dotplot & a bar chart where the bars run horizontally. Often, bars are used to plot things like group means, instead of raw values (as here), so it could throw someone off. In addition, Cleveland has shown that dotplots are read a little more accurately. But for the most part, there shouldn't be much difference. The key to this is rescaling your data so that they can be plotted together. The transformations I used were via z-scores, which equates their centers & how far they spread out.
Answer: Given that your data sets are different by orders of magnitude you might want to use logarithmic scale for your x-axis (or take the log of all samples before plotting.) That way the you can still see the variation within the same order of magnitude relatively clearly while the empty space between the sets is condensed.
Example in R:
speed  = c(2.2, 4.7, 7.3, 3.1)
weight = c(500, 222, 999, 1000)

barplot(rbind(speed, weight), log='x', beside=T, horiz=T,
        legend.text=T, args.legend=list(x='right'))


What is the distribution of $Y = e^X$ when $X$ is normal?

Question: What is the distribution of $Y = e^X$ when $X$ is normally distributed?
Am I supposed to use characteristics function of normal random variable ?
Comment: You might find some information here: http://en.wikipedia.org/wiki/Log-normal_distribution
Comment: There are several different methods. What is stopping you here?
Comment: This is the easiest approach for your case: http://en.wikipedia.org/wiki/Random_variable#Functions_of_random_variables
Comment: Have you not covered how to determine the density of a function of a continuous random variable?
Comment: I don't know how to start! If it is using characteristic function its better, but I think the easiest one is using CDF of $X$ ?
Answer: In case you still haven't sorted it out: apply the formula in the Wiki link I gave you to get for $X \sim N(0,1)$
$$
X'_{y}=\frac{1}{y}\\
f_{X}(\varphi^{-1}(y))=\frac{1}{\sqrt{2 \pi}}e^{-\frac{\log^2 y}{2}}
$$
Hence the distribution of $Y$ is
$$
f_Y(y)=\frac{1}{\sqrt{2 \pi}y}e^{-\frac{\log^2 y}{2}}
$$
for $y>0$. Here I don't use the absolute value for $y$ because the pdf is defined for strictly positive values since $\log y$ doesn't exist for $y \leq 0$.


Can`t set up $watch of attribute

Question: I was creating simple example of angular animation based on element,class and attribute directive.
http://plnkr.co/edit/Tw2dAGQJqoUy2sOOdoJr?p=preview
I`ve set up a variable and animate it change

In case of attribute, i tried to watch not for the variable, but for the attribute
In html:

In script.js:
scope.$watch(attr.myDir3, function(newVal) {...}

But it doesn`t works(except page openning).
Can you give me explanation, why? Or maybe some links for explaining the question?
Answer: You can do it, but you should use $observe instead like :
attr.$observe('myDir3', function(val) {
    //change
});

Here is your updated Plunkr
Comment: Thanks a lot! I thought, i tried it, but it doesnt helped those time))

Can`t set up $watch of attribute


objective c, NSMutableArray: indexOfObject

Question: int k = 0;
k = [myArray  indexOfObject:_endNode];

I only have a few objects added to the array and _endNode isn't one of them.
I expect my k value to be -1. But, my k on the second line gives me a value of 21787887.
Answer: It's actually NSNotFound, which is defined as NSIntegerMax.
This, by the way, is quite explicit in the documentation.
Comment: Actually, how would I access constants from the auto complete box.      Like I can see methods from NSMutableArray, by doing [NSMutableArray ...], but the constants don't show up.
Answer: This information may help you,
I think there is no DATA in you _endNode so its returning the junk value for the "k"

Please check the values of _endNode.....
Answer: It's actually NSNotFound ans defined as NSIntegerMax

NSArray *array = [[NSArray arrayWithObject:_endNode] arrayByAddingObjectsFromArray:Myarray];
int k;
k=[array indexOfObject:_endNode];


iptables DROP all access except my dynamic IP, is it possible and how/workaround?

Question: If not possible, is there any workaround without affecting CPU performance?

iptables -A INPUT -p tcp --dport 80 -j DROP
Answer: If you don't use static ip but DHCP, you can filter on mac address in iptables.
Something like :
<code>iptables -A INPUT -p tcp --destination-port 80 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT
</code>
With your workstation mac address.
Have a look here : http://www.cyberciti.biz/tips/iptables-mac-address-filtering.html
Hope this help !
Comment: This will only work if both machines are in the same subnet.
Comment: @mulaz: wow bad...i didn't know that :( I use this in my job but you are right, hosts are in same subnet...
Comment: I did not test, but I believe it works. Perhaps any iptables workaround when not shared the same network?


Flutter : ListView Builder - Texto

Question: Boa tarde, galera!
Poderiam me auxiliar em uma dúvida?
O que estou fazendo:

Eu criei uma ListView.builder dentro do meu body. Como podem observar eu estou passando um itemCount: dados.length, porque eu criei uma Lista Dados que ajunta todas as outras Listas
o retorno do meu dados[index] está:
  [Infracao{id: 20, conteudo: DIRIGIR veículo SEM possuir CNH}]
  [Anexo{id: 40, nome: GESTOS DE AGENTES, conteudo: movimentos convencionais de braço, adotados exclusivamente pelos agentes de autoridades de trânsito nas vias, para orientar, indicar o direi

  [Fiscalizacao{id: 40, nome: VIADUTO,}]

E como estou fazendo e minha Dúvida
Como podem observar preciso comparar if (dados[index] is Infracao) return ListaInfracao(dados[index] as Infracao); e assim para os outros ou seja ele me retorna a LISTA
Porem alem da lista eu gostaria que ele  trouxesse um Pedding chamando um Text("Infrações") em baixo retorna a lista e assim para os demais.
Poque da forma que está ele só ta dando um return na lista e antes de dar o return na lista eu gostaria de retornar tmb um  TEXTO, abaixo está imagem de como está atualmente como gostaria que ficasse.
    body: Column(
      children: <Widget>[
        Expanded(
          child: ListView.builder(
            padding: EdgeInsets.all(10.0),
            itemCount: dados.length,
            itemBuilder: (BuildContext context, int index) {
              if (dados[index] is Infracao)
                //AQUI RETORNARIA UM PEDDING TEXT();
                //DEPOIS A LISTA
                return ListaInfracao(dados[index] as Infracao);
              if (dados[index] is Anexo)
                return ListaAnexos(dados[index] as Anexo);
              else
                return ListaFiscalizacao(dados[index] as Fiscalizacao);
            },
          ),
        ),
      ],
    ));

COMO ESTÁ ATUALMENTE TRAZENDO A LISTA DE INFRAÇÕES E ANEXOS NO PRINT

COMO EU GOSTARIA QUE RETORNASSE
Comment: Hey Victor beleza? Que tal utilizar apenas uma conta para fazer as perguntas? E tente finalizar uma pergunta antes de começar a fazer outras! É sempre bom dar um feedback para quem está tentando lhe ajudar.
Comment: vou fechar a outra é que vcs comentou de abrir outra pergunta para minha dúvida porem na minha outra conta o limite bloqueou e eu preciso tirar essa ´duvida
Answer: é importante você saber formular a sua pergunta, para que seja fácil entender qual a sua necessidade, de qualquer maneira vejamos se isso pode te ajudar:
if (dados[index] is Infracao)
   //AQUI RETORNARIA UM PEDDING TEXT();
   //DEPOIS A LISTA
   return ListaInfracao(dados[index] as Infracao);

Se eu bem entendi a sua pergunta, caso o Widget seja Infracao você precisa retornar um Widget ListaInfracao com um padding certo? Se este o caso você pode realizar isso em vários modos:
O modo mais simples seria ultilizando um Padding:
Então o seu return seria:
return Padding(
   padding: const EdgeInsets.only(top: ALTURA_DESEJADA),
   child: ListaInfracao(dados[index] as Infracao);
);

Ou você criar a sua lista dentro a um Container:
return Container(
   padding: const EdgeInsets.only(top: ALTURA_DESEJADA),
   child: ListaInfracao(dados[index] as Infracao);
);

Organize melhor o seu código, você está criando 3 listas diferentes entre elas, dentro a uma Lista, então praticamente você pode ter 3 ListViews dentro a 1 ListView, por que não criar diretamente as ListViews que você precisa? Se todas as ListViews são parecidas (ao menos pela imagem parece que sim), por que não criar um único widget, que recebe a sua lista generica e cria a view?
Comment: Na real ele quer fazer um lista agrupada, mas pelo visto não quer ir atrás das coisas mais básicas da linguagem... Assim como você, eu já dei um caminho a ele em uma outra pergunta dele mesmo ([Essa aqui](https://pt.stackoverflow.com/questions/458710/d%c3%bavida-flutter-listview)) e também já indiquei um package próprio para o que ele deseja... Falta é empenho da parte dele buscar entender antes de aplicar.

Flutter : ListView Builder - Texto


How do you configure it so a published article promoted to another page instead of "front page"?

Question: I have a main menu with:
"Home" -basic page
 "Contact us" -the default drupal contact form
 "news" - which I want all the news articles to dynamically publish to the top so that when people click on news they see the latest article.
I thought that making a menu item in the form of an "article page" might do it but that only seemed to be comfortable with a single article. I made it into a book and it has allowed me to create a page but the formatting has gone dead weird so I would like to be able to create my articles and click an option which allows me to promote my articles to the news page. Is this possible?
Thanks
Answer: With Views, you can use "promoted to front page" as a filter value, so that things with that box checked can also be "promoted" to any page view that takes that as a filter.
If you don't want to us the native "promoted to front page" checkbox, but would rather have a separate checkbox just for that page, you can add a custom field to your content type(s) and use that as a filter value instead.
Comment: Thanks that helps. Would you be able to elaborate a bit on the filters and how they work?
Comment: @Magpie This is a very broad question, and as Serpiente pointed out, there is a lot of available documentation. You could start with [the Views online help page on filters](http://views-help.doc.logrus.com/help/views/filter).
Comment: There's also [this question about a Views tutorial](http://drupal.stackexchange.com/questions/673/where-is-a-detailed-tutorial-on-views)
Answer: Views

You need Views if

You like the default front page view, but you find you want to sort    it differently.
You like the default taxonomy/term view, but you find you want to    sort it differently; for example, alphabetically.
You use /tracker, but you want to restrict it to posts of a certain    type.
You like the idea of the 'article' module, but it doesn't display    articles the way you like.
You want a way to display a block with the 5 most recent posts of    some particular type.
You want to provide 'unread forum posts'.
You want a monthly archive similar to the typical Movable    Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts
  for that month.

Views can do a lot more than that, but those are some of the obvious
  uses of Views.

Views Tutorials
Comment: I have views. How do I configure it to solve my problem though?
Comment: there are tons of howto's out there..


On a conjectured relationship between the least prime factor and the Euler prime of an odd perfect number

Question: (Note: This question has been cross-posted to MO.)
Let $\sigma$ be the classical sum-of-divisors function.  For example,
$$\sigma(6)=1+2+3+6=12={2}\cdot{6}.$$
If $\sigma(N)=2N$ and $N$ is odd, then $N$ is called an odd perfect number.  Currently, the problem of the existence of odd perfect numbers is still open.
Euler proved that an odd perfect number $N$ must have the form
$$N=q^k n^2,$$
where $q$ is prime with $q \equiv k \equiv 1 \pmod 4$ and $\gcd(q,n)=1$.
Dris [2008] showed that the inequality
$$\sigma(q^k) \leq \dfrac{2n^2}{3}$$
holds, and subsequent improvements were given by other authors (Dris, Luca (2016), Chen, Chen (2012), Broughan, Delbourgo, Zhou (2013), and Chen, Chen (2014)).
Let $p_1$ be the least prime factor of the odd perfect number $N$ with Euler prime $q$.  It is relatively easy to show that $p_1 \neq q$. Suppose to the contrary that the Euler prime $q$ is also the least prime factor of the odd perfect number $N$.  Since $\sigma(q) \mid \sigma(q^k) \mid \sigma(N) = 2N$, we get that
$$\dfrac{q+1}{2} = \dfrac{\sigma(q)}{2} \mid N,$$
so that $(q+1)/2$ divides $N$.  If $(q+1)/2$ is prime, then this will contradict the assumption that $q$ is the least prime factor of $N$ (as $(q+1)/2 < q$).  If $(q+1)/2$ is composite, then $(q+1)/2$ will have a prime factor (necessarily smaller) that likewise divides $N$. Again, this is a contradiction.  QED
Therefore, $p_1 < q$.
Here is my question:

Will it be possible to either prove or rule out the following equality, using the current state of knowledge that we have on odd perfect numbers?
  $$\dfrac{q+1}{2} = {p_1}$$
Comment: The calculation that I can get, **but doesn't solve nothing about your question** is: expand using Newton's Binomial theorem to get from $(q+1)^k= 2^kp_1^k$ then $$q^k+\sum_{j=0}^{k-1}\binom{k}{j}q^j=2^kp_1^k,$$ and from this (since one wants to use the inequality $\sigma(q^k)\leq \frac{2n^2}{3}$) then multiply by $q$, substract $1$ and dividing by $q-1$ one gets $$\sigma(q^k)+\frac{q}{q-1}\sum_{j=0}^{k-1}\binom{k}{j}q^j=\frac{q(2^kp_1^k)-1}{q-1},$$ and now one can use the inequality $\sigma(q^k)\leq \frac{2n^2}{3}$, and try deduce something  (!).
Comment: I understand that is only a contribution as a comment, is not an answer. I was writting those simple calculations because perhaps you can deduce something useful about the size or from the first of those identities something when you divide, or combining with different factors. Very thanks much.
Comment: @user243301, that is a good start.  I invite you to write that out as an actual answer.
Answer: This is a partial answer, and takes off from the hint in user243301's comment here.

Let $N = q^k n^2$ be an odd perfect number with special prime $q$ satisfying $q \equiv k \equiv 1 \pmod 4$ and $\gcd(q,n)=1$.
Let
$$n = \prod_{i=1}^{\omega(n)}{{p_i}^{\alpha_i}}$$
be the canonical prime factorization of $n$.  (That is, all of the $\alpha_i$'s are positive, and $p_1 < p_2 < \ldots < p_{\omega(n)}$ are prime numbers.)
Suppose to the contrary that
$$\frac{q+1}{2}=p_1.$$
user243301 obtained the following equation:
$$\sigma(q^k) + \frac{q}{q-1}\sum_{j=0}^{k-1}\binom{k}{j}q^j = \frac{q(2^k {p_1}^k) - 1}{q - 1},$$
where $\sigma(x)=\sigma_1(x)$ is the classical sum of divisors of the positive integer $x$.
However, we know that we have the upper bound
$$\frac{\sigma(q^k)}{q^k} < \frac{q}{q-1}$$
since $q$ is prime.  This means that
$$\frac{q(2^k {p_1}^k) - 1}{q - 1} = \sigma(q^k) + \frac{q}{q-1}\sum_{j=0}^{k-1}\binom{k}{j}q^j > \sigma(q^k)\left(1 + \sum_{j=0}^{k-1}\binom{k}{j}q^{j-k}\right)$$
$$> \sigma(q^k)\cdot\left(\sum_{j=0}^{k}q^{j-k}\right) = \sigma(q^k)\cdot{\frac{\sigma(q^k)}{q^k}}.$$
This implies that
$$\frac{q(2^k {p_1}^k) - 1}{q^k (q - 1)} > \left(\frac{\sigma(q^k)}{q^k}\right)^2 \geq \left(\frac{q+1}{q}\right)^2.$$
But the fraction $q/(q - 1)$ is bounded from above by
$$\frac{q}{q - 1} \leq \frac{5}{4}$$.
Hence, it follows that
$$\left(\frac{q+1}{q}\right)^2 < \frac{q(2^k {p_1}^k) - 1}{q^k (q - 1)} < \frac{q(2^k {p_1}^k)}{q^k (q - 1)} \leq \frac{5}{4}\cdot\frac{2^k {p_1}^k}{q^k} = \frac{5}{4}\cdot\left(\frac{2p_1}{q}\right)^k = \frac{5}{4}\cdot\left(\frac{q+1}{q}\right)^k,$$
whence the inequality
$$\left(\frac{q+1}{q}\right)^{2-k} < \frac{5}{4},$$
or equivalently the inequality
$$\left(\frac{q}{q+1}\right)^{k-2} < \frac{5}{4}, \tag{1}$$
holds.
WolframAlpha then gives the following inequality plot:

and the following real solutions (???) to Inequality $(1)$:
$$k > 2, q = 0$$
$$k = n_1 + 2, -1 < q < -\frac{\sqrt[n_1]{5}}{2^{2/{n_1}} + \sqrt[n_1]{5}}, n_1 \in \mathbb{Z}, n_1 \leq -1$$
$$k = n_1 + 2, -\frac{\sqrt[n_1]{5}}{2^{2/{n_1}} + \sqrt[n_1]{5}} < q < 0, n_1 \in \mathbb{Z}, n_1 \geq 1$$
$$k = n_2 + 2, -1 < q < 0, n_2 \in \mathbb{Z}$$
$$k < 2, q < -1.$$
(Note that these real solutions violate $q \geq 5$.)
But the minimum value for $q/(q+1)$ occurs at $5/6$ (for $q=5$), hence
$$\left(\frac{5}{6}\right)^{k-2} \leq \left(\frac{q}{q+1}\right)^{k-2} < \frac{5}{4}. \tag{2}$$
Solving Inequality $(2)$ for $k$ yields
$$k > \dfrac{\log\left(\dfrac{144}{125}\right)}{\log\left(\dfrac{6}{5}\right)} \approx 0.776099,$$
which does not rule out $k=1$.

(This answer is currently under construction.)


Formatting datetime

Question: i am trying to format a datetime which comes fromt he database in the format of
2012-06-11 21:39:54

However i want it to display in the format of June 11
How can  do this?
Thanks
Comment: Tried [this](http://php.net/manual/en/function.sscanf.php) in combination with [this](http://php.net/manual/en/function.date.php)?
Comment: What have you tried (post the code) and what was the error/problem with that approach?
Comment: Answers using the DateTime class get my vote :)
Comment: possible duplicate of **Related Section**
Answer: echo date('M d', strtotime('2012-06-11 21:39:54'));

Output
Comment: For June, not Jun: use `F` instead of `M`
Answer: You can also use DateTime object.
$date = new DateTime($yourString);
$date->format($yourFOrmat);

I think that it would be the best way because DateTime is really more powerful than timestamp and date/strtotime functions.
From the code I gave above you can add functionalities like modifying dates, iterate over the time, compare 2 dates without functions like str_to_time...
$date->modify('+1 day');//the day after for example
foreach(new DatePeriod($date,new DateInterval('PT1M'),10){
    $date->format($yourFormat);//iterate each minute
}

and so on
Comment: Why are you iterating over the minutes? The OP Just asked for the format conversion. The extra code may be confusing. Also your DateInterval specification is wrong, it should me 'PT1M'.
Comment: Er, yep. It was just because I wanted to show what was the interest of dateTime over the mess with timestamp and date/strtotime functions. If it is too confusing I will erase this part.
Comment: Best just to answer the question that is asked really. If you want yo leave in the extra code, you need to explain clearly what it is doing and why. Unfortunately, as it stands, I can't given you the up vote I want to give for using DateTime.
Answer: PHP manual gives an excellent documentation about using Date/Time functions. Basically you will need a  combination of two functions: strtotime() and date().
strtotime() will convert your date into Unix timestamp which can be supplied to date() as second argument.
The format of date you will need is: M d.
Alternative: In addition you could also try the MYSQL counterpart which won't require conversion to UNIX timestamp. It is documented here. Assuming you are using date as your Datetime field, you will need something like this,
SELECT id,..,DATE_FORMAT(`date`, '%M %d') as f_date FROM table

Answer: For formatting date using php, you need to pass timestamp of date
and format specifiers as arguments into date function .
Eg echo date('M d',strtotime('2012-06-11 21:39:54'));
Comment: you don't need that and so far I am concerned I dislike this methodology. There is a more consistant, powerful and readable API with DateTime object.

Formatting datetime


Can you save state in the $form_state variable that remains when the form is rebuilt?

Question: I have a form with a nested subform that has an ajax submit button in it. The subform is built inside a form_alter and attached to the form. The submit buttons #name is made unique by using a UUID generator.
When I press the ajax submit button, Drupal steps through its form builder steps rebuilding the form. Because of this, the same code in the form_alter is called rebuilding the same subform. The problem is that when it is rebuilt, the submit button gets a brand new #name via the UUID generator. As such, Drupal cannot match the _triggering_element to a #name, and the ajax fails.
One solution I thought to try was to attach the #name to $form_state storage when the form is first built hoping that it would be available when the form is rebuilt. For e.g. in the same form_alter I execute:
      $input = $form_state->getUserInput();
      if($input){
        //This only runs when the form is being rebuilt
      }

And I may be able to grab the correct #name out of $form_state storage and set it so Drupal can correctly match and find the right ajax callbacks.
Is something like this possible? Is there a better way to handle this?
Comment: What I can tell you is that in nearly 15 years of using Drupal, I have only ever found setting `#name` to cause issues. Better to leave that one alone. Not sure what you're trying to do though, so can't really help with a solution.
Answer: You only need #name if the form array keys don't provide a unique path for form_state. I agree with @Jaypan, I too found setting #name never really necessary, it seems to be more reliable to define a unique key to the lowest level of the form element if you have issues with Ajax not finding the form element. In either case, #name or form key, it has to be predictable, derived from data which doesn't change between form builds, for example a field delta.
The form object and $form_state are not cached when a form is rendered, only after submitting the first Ajax request. So it doesn't help to store data in $form_state you want to use to rebuild $form.
Comment: The form that gets built within the node edit form exists in a certain Paragraph type. So if more than one of these paragraphs is added to the page, I'm not quite sure how I'd get away with not using a UUID generator to either create unique keys or a unique #name. Is your intuition that it would work better if the generate was acting on the keys instead of the #name?
Comment: It needs to be unique only within the form, so it should work if you add the field delta of the paragraph reference field to #name or form array key.
Comment: Ah that makes sense, use the ordering on the fields to make the names or keys unique. Now in my case, each relevant field on the Node is a Paragraph which references a Paragraph. The $form array I get is like `['field_name']['widget'][0]` where the [0] array does have a '#delta' value, but in my case its always 0 because there aren't other items in ['widget'] (and there will only ever be 1). I noticed at the $form['field_name'] level there is a 'weight' key with a changing value. Could that potentially be used in the same way?
Comment: To any who find this question: 4k4 led me down the right path. I was building the form in a hook_field_widget_WIDGET_TYPE_form_alter so there was not a unique delta available, but in the 3rd argument (context) the machine name of the parent field is provided in a few places. This machine name has to be unique within the Node, so I used it to assign the `#name` value instead of a UUID and ajax started working.


Try/catch em JS

Question: Possuo um array chamado agenciasUri, o qual formato os dados antes de inserir nele. Após isso, monto o JSON jsonObjpara enviar uma requisição. O que achei estranho é que está funcionando corretamente.
Por que eu consigo acessar agenciasUri? Como funciona a visibilidade de uma variável dentro de um laço em JavaScript (ciclo de vida)?
$scope.salvar = function () {
        var agenciasSeparadas = $scope.opcoes + '';
        agenciasSeparadas = agenciasSeparadas.split(',');
        try {
            var agenciasUri = [];
            for (var i = 0; i < $scope.listaAgencias.length; i++) {
                var json = $scope.listaAgencias[i];
                for (var k = 0; k < agenciasSeparadas.length; k++) {
                    if (json.nome == agenciasSeparadas[k]) {
                        agenciasUri.push(json._links.self.href);
                    }
                }
            }
        } catch (err) {
            alert(err);
        }

        var jsonObj = {
            nome: $scope.nome,
            tipo: $scope.tipo,
            agencias: agenciasUri
        };

        alert(JSON.stringify(jsonObj));
        veiculosAPI.postVeiculo(jsonObj)
            .success(function (data, status, headers, config) {
                $scope.nome = null;
                $scope.tipo = null;
            }).error(function (data, status, headers) {
                alert("Erro ao salvar dados do veiculo!");
                alert(data + "\t" + JSON.stringify(data));
            });

    };

Answer: A questão é que o JavaScript tem o escopo de variáveis declarada com var local à função e não ao bloco de execução, como ocorre em outras linguagens. Este fenômeno é conhecido por hoisting.
Então não importa onde você declare a variável, ela existirá em toda a função. Mas não fora dela.
Somente variáveis declaradas fora da função é que possuem escopo global ou pelo menos regional. Por regional entenda que uma variável pode ser acessível dentro da função onde ela foi declarada e dentro de funções contidas nesta função.
Com o EcmaScript 6 é possível usar o let que permite o uso de escopo de bloco, como o encontrado em outras linguagens. Mais detalhes sobre a diferença entre eles podem ser encontrados nessa pergunta.
A ideia do escopo do var não é ruim, o problema é que ela foi mal implementada. Se você declarar duas vezes a mesma variável dentro de uma função, em blocos diferentes, é aceito sem erros. Isto não deveria acontecer. Mas pela filosofia da linguagem a segunda declaração funciona normalmente como se fosse uma atribuição. Isto é confuso. Outro problema é que a variável existe mesmo que ela tenha sido declarada depois do seu uso.
Desta forma, o estilo "moderno" de programar é usar sempre que possível, e sempre é em navegadores modernos, o let. É uma pena que ainda não há suporte garantido em navegadores que estão em pleno uso (isso mudou desde essa resposta, quase não tem mais esse problema).
Ou seja, isto não é algo específico do try-catch, é válido para qualquer bloco.
Mais informações nessa pergunta no SO.

Try/catch em JS


Easy Question about P-names

Question: Notation(from Kunnen): $M$ is countable transitive model of $ZFC$, $P$ is a partial order that belongs to $M$, $G$ is a $P$-generic filter over $M$, $\hat{b}$ will be a $P$-name for $b\in M$, and $M[G]$ is the smallest model of $ZFC$ containing $G$ and $M$.
The exercise i'm trying to do is the following: If $f$ is a function with range contained in $M$ and $f$ belongs to $M[G]$ then there is a set $B$ that belongs to $M$ containing the range of $f$. The hint given is to consider
$B=\left \{ b:\exists p  \in P(p\Vdash \hat{b} \in \operatorname{Rng}(\tau ) ) \right \} $ where $\operatorname{val} (\tau,G) = f$
I understand that this describes the desired $B$ as a class in $M$ but i can't find a way to show that this is actually a set in $M$.
Thanks for the help and sorry for the trivial question.
Answer: Here is a quick proof, which doesn't use the hint.
If $f$ is a function in $M[G]$ with $\text{ran}(f)\subset M$, then since $\text{ran}(f)$ is a set in $M[G]$, it has some von Neumann rank $\alpha$ there. Thus, every element of $\text{ran}(f)$ has rank less than $\alpha$. Since rank is absolute and $\alpha$ is an ordinal in $M$, it follows that $\text{ran}(f)\subset (V_\alpha)^M$, and this is a set in $M$.
(This proof requires you already to know that $M$ and $M[G]$ have the same ordinals and that $M[G]$ satisfies ZFC.)
Comment: How elegant! :-)
Answer: The class $B$ is the class of all elements that some condition forces them into $\rm{Rng}(f)$.
The question is, indeed, why is this a set in $M$.
Note that: $B_p = \{b\colon p\Vdash \hat b\in\operatorname{Rng}(\tau)\}$ is a definable class in $M$, since $p$ cannot force a proper class of elements into the range of $f$ we have that this is a set in $M$.
Suppose some $p$ would force $B_p$ to be a proper class of elements, then any generic filter concentrating on $p$ would force $f$ to be a proper class. Take $G$ to be a generic filter concentrating on $p$ and derive contradiction.
Now $\displaystyle B=\bigcup_{p\in P}B_p$ is also a set in $M$ by axioms of replacement and union.
Let's look at a concrete example. Consider a Cohen forcing that introduces one new real number, that is a new function $f\colon\omega\to 2$, or a new $A\subseteq\omega$.
Of course, for different $P$-generic filters, the resulting set is going to be different (that is, one filter might force $f(0)=1$ and another the opposite). However for every $p\in P$ we can define the set $B_p = \{n\colon p\Vdash n\in A\}$.
Note if we consider $P$ to be partial functions from some $n$ into $2$ (ordered by extension) then $B_p$ is exactly $\{n\colon n\in\operatorname{Dom}(p)\land p(n)=1\}$, i.e. all the numbers on which $p$ decides that are in the set.
Of course that in this rather trivial example $B = \omega$, and the $B_p$ was extremely simple to define, but I hope the idea got through.
Comment: If the forcing notion is a set, then the size of antichains in it will have some bounded size. Thus, there will be some bound on the size of the range of $f$. And there will be only an antichain of possible values for the $\alpha$-th element, for any fixed $\alpha$. So the class of possible elements in the range will be a set.
Comment: I'm sorry but I still don't get why $p$ cannot force a proper class of elements into the range of $f$. What's the problem with this being true?
Comment: Thanks to both of you for the help, I got it.

Easy Question about P-names


Diferença entre biblioteca e helper

Question: O que diferencia o helper de uma biblioteca? Por exemplo: vamos dizer que eu tenha uma classe para manipulação de URL. Eu a chamo e ela completa a URL com o caminho do site. Isso seria um helper?
Comment: *Helper* é um padrão de design. *Biblioteca* é um conjunto de estruturas e funcionalidades comuns a um conjunto de aplicações. Não sei se vale muito a pena comparar coisas tão diferentes.
Comment: Depende do que você está chamando de *helper*. Se for um *helper method*, não sei se tem uma relação direta entre os termos a não ser que uma biblioteca pode ser uma coleção de métodos auxiliares, entre outras coisas.
Comment: Não posso falar no contexto do CodeIgniter, se é sobre ele que você deseja, coloque a *tag* identificando isto. Se é em um contexto geral, é o que já comentamos.
Comment: Esse artigo é bacana: http://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix
Answer: Eu nunca vi o termo biblioteca (ou library) ser aplicado no contexto específico do MVC, mesmo uma tecnologia específica usando MVC. Já vi o termo ser usando em contextos genéricos, o que obviamente inclui o MVC. Uma biblioteca é uma solução de estruturas e algoritmos, um conjunto de features relacionadas. Sem dúvida ela pode conter helpers. Eventualmente uma biblioteca pode ser composta só de helpers.
No contexto do MVC o helper é algo que deve ser usado para organizar a aplicação. É uma forma de criar uma versão canônica do que precisa ser usado. É muito comum fazer um helper quando ele será usado diversas vezes na aplicação. Mas eventualmente pode ser usado unicamente e ele é criado para simplificar o seu uso abstraindo o conteúdo. Isto é importante quando vai criar views, que devem possuir bem pouca lógica, então você "esconde" esta lógica nestes helpers. O mesmo pode ser dito para controllers.
Pelo menos no contexto do MVC esses helpers, grosso modo, costumam funcionar como snippets para usar dentro de views e como serviços no controller.
O helper tem uma função mais bem definida, apesar dele ser usado essencialmente para organização. A biblioteca é um conceito e técnica de organização e esta é sua função principal: organizar. Muda pouco na aplicação se você não organizar bibliotecas. Mas muda bem mais se não usar helpers. Sem helpers você pode ter redundância, inconsistência, ilegibilidade, só para citar alguns problemas, além dos problemas específicos por falta de organização.
Pode ser que alguma tecnologia específica de MVC tenha um uso e uma definição mais especializada. Por exemplo:
No comentário do Daniel Omine tem um artigo mostrando a diferença entre um helper clássico usado exclusivamente em view do ASP.NET MVC (Razor) e uma função que até pode ser usada como se fosse um helper. Além de existir um motivo semântico para escolher cada um existe uma diferença no tipo de dado que cada um retorna. Certamente o helper tem um padrão mais estrito porque o framework sabe fazer alguma coisa específica com aquilo.
Não respondi exatamente sobre a diferença porque, até onde eu sei, estes conceitos não são comparáveis diretamente. No máximo um pode fazer parte do outro.
Acho que seu exemplo é um helper mas precisa ver como ele foi escrito, usado e em que tecnologia é usado. Embora ache improvável, pode ser que esta classe não tenha uma função auxiliadora no sentido que costumamos entender.
Coloquei no GitHub para referência futura.
Comment: Para entender mais especificamente o que disse - https://ellislab.com/codeigniter/user-guide/helpers/url_helper.html. Perceba que através do **helper** URL eu posso obter a base url do meu site, a url atual, além de outras funções como a do redirect.
Comment: Foi o que eu imaginei, então é isto mesmo. Mas note que não é o conteúdo que vai definir se é *helper* ou não, é porque ele existe e como ele é usado.

Diferença entre biblioteca e helper


How do we play a wiggling line with multiple notes on the piano?

Question: I saw a wiggling line with three notes for a song for piano, and played it and recorded it on GarageBand and edited it on the picture on the right:

I waited about a quarter of a beat to play the second note and another quarter beat to play the third note. And let them all play to the end of that single beat. Alternatively, they can be played so that they all have the same duration (so the lines on GarageBand should all have the same length).  How should it be played?
Answer: It's an arpeggio.  You "roll" the notes like you did.  Usually you start with the bottom note and work your way up.  The exact timing is not precisely indicated, so it's not as specific as you suggested.  The notes get released all together, so technically only the first note played will gets its full value.
In terms of rhythm, the first note gets played exactly on the indicated beat.
Also, although it's most obvious to play the bottom note first, there are arpeggios played from the top down.   They are less common.
Think of it as the pianos way of copying how a guitar player might slowly strum a chord.
Comment: yes, later on I saw some arpeggio played with one hand, and the last note has to be played with the pinky and with the thumb leaving the keyboard... so I guess in that case, the first note cannot be played for the full duration
Answer: Yes, it's an arpeggio, normally played with the notes staggered from lowest to highest, unless the wiggly line has an arrowhead at the bottom, when it's top to bottom.
Depending on the style, it can be played as you did, starting on the beat with the first note, and making it all last till the end of that note, or, it could be played so the last note gets played as the beat starts. Sometimes it's marked, sometimes it's down to the player's discretion. Even the speed of execution is open to interpretation. Nuggethead's scenario of a guitarist strumming slowly is a good one.


can not read property of undefined url

Question: i want do something like this
in my blog app user can not post without uploading image untill handle the request  . post need 1 image to be published
i want do something that user can post without uploading image i mean image image not necessary
i do like this
           const { url?...url, public_id: publicId } = await uploadToCloudinary(file,
          'Posts');

but it gieves error that url is is not defined
here is my post controller
const Post = require('../model/Post');
const User = require('../model/User');
const Tag = require('../model/Tag');
const Comment = require('../model/Comment');
const cloudinary = require('../config/cloudinary');
const { uploadToCloudinary } = require('../utils/cloudinary');
const { getPostParams, unCapitalizeFirstLetter } = require('../helpers/string');
const { createTags, updateTags, deleteTags } = require('./tagsController');
const {
    likeNotification,
    removeLikeNotification,
    postNotification,
    removePostNotification,
} = require('./notificationsController');

const createPost = async (req, res) => {
    const { title,file, tags,body, authorUsername } = req.body;

    const { url, public_id: publicId } = await uploadToCloudinary(file, 'Posts');
    const author = await User.findOne({ username: authorUsername }).exec();

    const formattedTags = tags
        .trim()
        .split(',')
        .map(w => w.trim().replace(/ /g, '-'));

    const createdPost = await Post.create({
        title,
        image:{ url, publicId },
        body,
        author: author._id,
    });

    author.followers.map(followerId => {
        (async () => {
            await postNotification(author._id, createdPost._id, followerId);
        })();
    });

    await createTags(formattedTags, createdPost);

    author.posts.push(createdPost._id);

    await author.save();

    res.status(200).json(createdPost.toObject({ getters: true }));
};

const getPost = async (req, res) => {
    const author = await User.findOne({ username: req.params.username }).exec();
    const authorId = await author?.toObject({ getters: true }).id;
    const { postTitle, postId } = getPostParams(req.params.postUrl);

    const foundPost = await Post.findOne({
        author: authorId,
        title: postTitle,
        _id: postId,
    })
        .populate('author')
        .populate('comments')
        .populate('tags')
        .exec();

    res.status(200).json(foundPost.toObject({ getters: true }));
};

const getPosts = async (req, res) => {
    const { userId } = req.params;

    const posts = await Post.find(userId ? { bookmarks: userId } : {})
        .sort({ createdAt: -1 })
        .populate('author')
        .populate('tags');
    if (!posts) res.status(204).json('No posts found');

    res.status(200).json(posts.map(post => post.toObject({ getters: true })));
};

const updatePost = async (req, res) => {
    const authorId = await User.findOne({ username: req.params.username }).exec();
    const { postTitle, postId } = getPostParams(req.params.postUrl);

    const { url, public_id: publicId } = await uploadToCloudinary(req.body.image.url, 'Posts');

    await cloudinary.uploader.destroy(req.body.image.publicId);

    req.body.image = { url, publicId };
    const formattedTags = req.body.tags
        .trim()
        .split(',')
        .map(w => w.trim().replace(/ /g, '-'));

    const post = await Post.findOne({
        author: authorId,
        title: postTitle,
        _id: postId,
    })
        .populate('author')
        .populate('tags');

    Object.keys(req.body).map(key => {
        if (key !== 'tags') post[key] = req.body[key];
    });

    await updateTags(formattedTags, post);

    await post.save();

    res.status(200).json(post.toObject({ getters: true }));
};

const deletePostsByUserId = async user => {
    const { _id: userId } = user;

    user.comments.forEach(commentId => {
        (async () => {
            await Post.updateMany({ comments: commentId }, { $pull: { comments: commentId } });
        })();
    });

    const posts = await Post.find({ author: userId }).populate('tags');

    ['likes', 'unicorns', 'bookmarks'].forEach(k => {
        (async () => {
            await Post.updateMany({ [k]: userId }, { $pull: { [k]: userId } });
        })();
    });

    posts.forEach(post => {
        (async () => {
            await deleteTags(
                post.tags.map(({ name }) => name),
                post,
                true
            );
            await cloudinary.uploader.destroy(post.image.publicId);
            await Post.deleteOne({ _id: post._id });
        })();
    });

    await Comment.deleteMany({ author: userId });
};

const deletePost = async (req, res) => {
    const author = await User.findOne({ username: req.params.username }).exec();
    const { postTitle, postId } = getPostParams(req.params.postUrl);

    await cloudinary.uploader.destroy(req.body.publicId);

    const foundPost = await Post.findOne({
        author: author._id,
        title: postTitle,
        _id: postId,
    })
        .populate('tags')
        .exec();

    if (!foundPost) return res.sendStatus(204);

    const comments = await Comment.find({ parentPost: postId }).populate({
        path: 'author',
        populate: 'followers',
    });

    comments.forEach(({ author }) =>
        (async () => {
            author.comments.forEach(comment => author.comments.pull(comment));
        })()
    );
    author.posts.pull(postId);
    await author.save();

    await Comment.deleteMany({ parentPost: postId });

    await deleteTags(
        foundPost.tags.map(({ name }) => name),
        foundPost,
        true
    );

    removePostNotification(author._id, foundPost._id, author.followers);

    await Post.deleteOne({ _id: foundPost._id });

    res.status(200).json(foundPost.toObject({ getters: true }));
};

const postReaction = async (req, res) => {
    const { userId } = req.body;
    const { action, postUrl } = req.params;
    const { postTitle, postId } = getPostParams(postUrl);
    const isUndoing = action.includes('remove');
    const actionKey = isUndoing
        ? unCapitalizeFirstLetter(action.replace('remove', '')) + 's'
        : action + 's';

    const author = await User.findOne({ username: req.params.username }).exec();
    const authorId = await author.toObject({ getters: true }).id;

    const updatedPost = await Post.findOneAndUpdate(
        { author: authorId, title: postTitle, _id: postId },
        isUndoing ? { $pull: { [actionKey]: userId } } : { $addToSet: { [actionKey]: userId } },
        { new: true, timestamps: false }
    );

    if (isUndoing) await removeLikeNotification(userId, updatedPost._id, authorId);
    else await likeNotification(userId, updatedPost._id, authorId);

    res.status(200).json(updatedPost.toObject({ getters: true }));
};

module.exports = {
    createPost,
    getPosts,
    getPost,
    updatePost,
    deletePost,
    deletePostsByUserId,
    postReaction,
};

and here is my post Model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PostSchema = new Schema(
  {
    title: { type: String, required: true },
    image: { url: { type: String }, publicId: { type: String } },
    body: { type: String, required: true },
    likes: [{ type: mongoose.Types.ObjectId, ref: 'User' }],
    unicorns: [{ type: mongoose.Types.ObjectId, ref: 'User' }],
    bookmarks: [{ type: mongoose.Types.ObjectId, ref: 'User' }],
    tags: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Tag' }],
    comments: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Comment' }],
    author: { type: mongoose.Types.ObjectId, required: true, ref: 'User' },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model('Post', PostSchema);

I change

    const { url, public_id: publicId } = await uploadToCloudinary(req.body.image.url, 'Posts');

to
const { url?...url, public_id: publicId } = await uploadToCloudinary(req.body.image.url, 'Posts');

this is utils/cloudinary.js
const cloudinary = require('../config/cloudinary');

const uploadToCloudinary = async (file, folder) => {
  try {
    const uploadedResponse = await cloudinary.uploader.upload(file, {
      folder: `evToClone/${folder}`,
    });
    return uploadedResponse;
  } catch (err) {
    console.log(err);
  }
};

module.exports = { uploadToCloudinary };

but it gives errors url is not defined
sorry for bad english
what can i do to make this possible ?
user can post without uploading to cloudinary
Comment: url?...url is not right syntax. What are you trying to do?
Comment: @Ralle  the user after sign up wants create post in my blog . but uploading image is required . i want make it not require. i did change the post model to not require and in front end not require . but here in post controller.js the app wants upload image to cloudinary . but i do not want . i want say if url exist then u upload . this url i think it means the file or the input image . i mean if they pick image in input image and then they submit form . if they did not picked any image to upload . u not upload . sorry for bad english
Comment: Can you post also ../utils/cloudinary.
Comment: @Ralle i am really happy u answering me . thank you brother . i did add cloudinary to my question thanks
Answer: You can do like so:
Looking to your code, the image is in the body, so i guess you are sending that base64 encoded. (Cant be sure as i dont see that part of your code).
If in your frontend you decide to not send an image, just send, file: null.
Then in the backend you will have it also null.
    const { title,file, tags,body, authorUsername } = req.body;

So now wrap the part of image upload.
  let urlData = {}
  if(file) {
  urlData= await uploadToCloudinary(file, 'Posts');
  }
  const { url, public_id: publicId } = urlData || {url:null,public_id: null} // asigns default

In this way if a file is there it will be send. Then or the data are assigned by desstructuring to url and publicId or it will take the null values. (|| {url:null,public_id: null}).
Do the same for the update part.
Hint. When this work you can play arround and implement a better errorhandling.
What if the user sends an image but for some reason the upload fails?
Comment: this soloution u gave me it workded for add post  .   why this solution not work when user try to edit post . i mean for editing post user have to add image again . if u see my post controller file . u can finde this line this is for updating post but not same as add post                     const updatePost = async (req, res) => {
    const authorId = await User.findOne({ username: req.params.username }).exec();
    const { postTitle, postId } = getPostParams(req.params.postUrl);

    const { url, public_id: publicId } = await uploadToCloudinary(req.body.image.url, 'Posts');
Comment: I mean the answer u gave me it worked . and user thanks to you . now can add post without adding image .  but in my postcontroller.js file . there is a code for updating post .  I add the code u gave me for updating post . but not work like adding post . i mean why this solution work for adding post . and not working for updating post . what can i do sir .
Comment: for updating post . i get errors like this           UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason
Comment: wrap all in a try catch and analyse the error. You have several code snpilets without any errorhandling. If you are using axios somewhere, think axios returns error in the response, without throwing an error itselfs. In that case you need to analyse the response.
Comment: i did this process again with more attention . it gives this error        if(file) {
[0]             ^
[0]
[0] ReferenceError: file is not defined              why is file defined for add post ? their both in postcontroller.js    what do you think ? i do something wrong ?
Comment: Do you have a demosite or github repo. So i can check it?
Comment: yes i did this before .    but for post controller . i did not add my newpostcontroller file .   https://github.com/am0029/latest-dev-to-clone
Comment: the post controller file the only change is for postcontroller u should add your answer to it  . i did it in local host and it worked for adding post but for updating post i have problems
Comment: u can see in my github . if u want the new postcontroller file, i edit in my question

can not read property of undefined url


How do I redirect a Read More link to another URL in Showcase Image?

Question: When creating a showcase image for my homepage, I would like to redirect the Read More link to another page in the site, instead of the default link back to the image.  Is it possible?
Or do I just have to remove the Read More link and insert a URL link inside the slide text?
Answer: You can use the path-redirect module to forward the URL in the "read-more" link to any other internal or external URL.  If you forward internally, you need to use the "node/123" system URL and delete the alias for the node you are forwarding from, before you setup the redirect.
If you point at the read more link you'll see its node or alias in the lower left hand corner of your browser.


virtualenvwrapper -> updating python binary

Question: I'm using virutalenvwrapper and created a virtualenv for my django application. I was running python 2.6.1. At the time i set this up
Unfortunately python 2.6.1 has a bug with respect to passing unicode strings in kwargs. As a result I'm looking to update the python binary used by my vritualenv.
Python 2.7.2 is all installed. I just need to understand what is the best way to "migrate" my current virtualenv to use the new python binary.
As i understand it, virtualenv and virtualenvwrapper are sensitive to the python used during install. Do i then,
1) uninstall and reinstall virtualenv, virutalenvwrapper while making sure i'm using python 2.7? If i do this, will the old virtualenv just work, or do i need to recreate it?
or
2) can i just somehow update the binary used in my virtualenv ?

update:
I just ended up creating a new env from scratch.
I did not uninstall and reinstall virutalenv or virtualenvwrapper. still don't know if that will bite me later on down the line but so far seems ok.
Would still like to know definitively if changing python versions on virtualenv wrapper and virtualenv is ok.
Answer: virtualenvwrapper has a cpvirtualenv command. Have you tried executing that from the new Python?
If that doesn't work, you could just destroy the old virtualenv and create a new one for your project. It should be easy if you have been diligent about keeping track of your dependencies (either in setup.py or requirements.txt). If you haven't been diligent, you can use pip freeze to capture the libs that are currently installed.
Comment: So it sounds like virtualenvwrapper and virtualenv are insensitive to the python version used at install? I can recreate the whole thing but one of the requirements is Pillow and i need to do a manual pip --no-install on it and modify config files and blah blah so just lazy to do that again.
Comment: virtualenv is sensitive the last time I tested it, but I thought cpvirtualenv might be able to fix the brokenness as part of its tweak age of the new virtualenv. Just a guess.
Answer: So for the benefit of others who may be reading this.
Ran into an issue all of a sudden today. Upon logging in via ssh i was presented with
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named virtualenvwrapper.hook_loader
virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenv has been installed for VIRTUALENVWRAPPER_PYTHON=/home/*******/opt/bin/python and that PATH is set properly.

WTF. it was working fine for like... i guess a month now. Turns out maybe i never closed my ssh session (i.e. virtualenvwrapper never had to restart).
Google wasn't much help. As it turns out, the problem was exactly what the error message said. Virtualenv was not installed for the python specified. (2.7)
It was installed for the version i was using previously (2.6)
D'oh.
Since i wasn't really using 2.6 anymore, i simply renamed the directory containing my local  site packages from
~/.local/lib/python2.6/site-packages

to
~/.local/lib/python2.7/site-packages

(site-packages is appended to the path just to make clear what and why i renamed)
Similarly, I could have just as easily run easy_install or pip to install virtualenvwrapper to a new local directory using the python2.7 binary. (which theoretically should have created the appropriate site-packages folder)


Add leading zeros in alphanumeric string

Question: I have a character vector with strings with a similar format (letters, underscore, digits):
v <- c("AB_124", "BAE_1", "LOED_1234", "H_01")

I want to add leading zeroes to have a length of 4 for the numerical part:
c("AB_0124", "BAE_0001", "LOED_1234", "H_0001")

What are ways to do it?
Answer: Using regex:
sprintf("%s_%04d", substr(v, 1, regexpr("_", v) - 1),
        as.numeric(substring(v, regexpr("_", v) + 1)))
# [1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"

Or stringr:
library(stringr)

str_replace(v, "(\\d+)$", ~sprintf("%04d", as.numeric(.x)))
# [1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"

A bit simpler version of your sapply solution:
sapply(strsplit(v, "_"), \(x){ sprintf("%s_%04d", x[1], as.numeric(x[2])) })
# [1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"

Comment: we can also use `str_extract` with sprintf as `sprintf('%s%04d',str_extract(v,'^\\w+\\_'),as.numeric(str_extract(v,'\\d+')))`
Answer: A stringr solution that supplies a function (e.g. str_pad) into str_replace() to replace the match.
library(stringr)

str_replace(v, "(\\d+)$", ~ str_pad(.x, 4, pad = 0))

# [1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"

Answer: One way to go about it (but that I find a bit cumbersome), is to split and reunite:
sapply(strsplit(v, "_"), \(x) {x[2] <- sprintf("%04d", as.numeric(x[2])); paste(x, collapse = "_")})
#[1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"

Answer: Small variation, using data.table's tstrsplit function
s <- data.table::tstrsplit(v, "_", type.convert = TRUE)
sprintf("%s_%04d", s[[1]], s[[2]])

# [1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"


I need to find in which subject the student has scored the highest marks in matillion

Question: I need to find in  which subject the student has scored the most marks(only the subject name is enough) using matillion
My data looks like this
studentid   maths   science art computer sports
1             55     68      59   75     62
2             75     68      79   56     89
3             89     85      74   32     56
4             89     92      86   75     12
5             99     100     45  68      45

And I want my result to look like this
studentid     highestmark
1              computer
2              sports
3              maths
4              science
5              science

Answer: In Snowflake, or most SQL dialects, you can use greatest():
select t.*,
       (case greatest(maths, science, art, computer, sports)
           when maths then 'maths'
           when science then 'science'
           when art then 'art'
           when computer then 'computer'
           when sports then 'sports'
        end) as highestmark
from t;

Comment: sorry @gordonlinoff i also need to display the mark in that subject                                                         it should look like                                  1  maths 99
Comment: @Gowtham_7 . . . That is not the question you asked here, but you can just use the `greatest()` function.
Answer: I have added to Gordon's answer to get highest mark too.
select t.*,
(case greatest(maths, science, art, computer, sports)
when maths then 'maths'
when science then 'science'
when art then 'art'
when computer then 'computer'
when sports then 'sports'
end) as highestmark,
greatest(maths, science, art, computer, sports) highest_mark
from t;
Comment: can u please help me with another question too i've attached the link https://stackoverflow.com/questions/65291812/how-to-add-a-constant-value-1-in-an-empty-column-in-snowflake-matillion


Mod_proxy Chunk minimum file size

Question: I am using Apache HTTPD 2.2.17  + Mod_proxy + SSL on Ubuntu as a gateway. Everything works fine but when I send a request with Transfer Encoding: Chunked, it converts(de-chunk) back if the file size  is too small.
I tested with a 43k works fine. Tested with 16K and 5.5K it's getting converted as a request with 'content-length'.
My conf file:
<IfModule mod_ssl.c>
NameVirtualHost *:443
<VirtualHost *:443>
  ServerAdmin *
  ServerName  *

  DocumentRoot "/var/www"
  ErrorLog /var/log/apache2/error.log
  LogLevel warn
  TransferLog /var/log/apache2/access.log

  SSLEngine on
  SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
  SSLCertificateFile /etc/ssl/certs/*.pem
  SSLCertificateKeyFile /etc/ssl/certs/*.pem
  SSLCertificateChainFile /etc/ssl/certs/symantec_intermediate_ca_bundle.pem

  CustomLog /var/log/apache2/access.log combined

  ProxyPreserveHost On
  ProxyRequests Off
  #ProxyIOBufferSize 1024
  #SetEnv proxy-sendchunked 1
  #ProxyPass / http://localhost:9443/ flushpackets=on proxy-sendchunked=on
  #ProxyIOBufferSize 1024
  SetEnv proxy-sendchunked 1
  ProxyPass / http://localhost:9443/ iobuffersize=1024
  #ProxyPassReverse / http://localhost:9443/
  #ProxyPass / http://localhost:9443/ flushpackets=on
  ProxyPassReverse / http://localhost:9443/

</VirtualHost>
</IfModule>

httpd 2.4.1 too got the same issue.
Any help would be appreciated
Comment: What version of Apache is this config being used on - 2.2 or 2.4?  (looks like it won't load in 2.2)  The data at issue is in the request, not the response, correct?  Any why's it a problem to send it un-chunked?
Comment: This is from 2.4 version. Apche is used as a gateway which terminates https requests and passes to HAProxy as http. The problem is in requests not repines. This is a special requirement we need it chunked. Question is how to set Minimum chunked size in Apache or Mod_proxy
Answer: This seems to be this bug:
https://issues.apache.org/bugzilla/show_bug.cgi?id=50402
complied with patch and added :
SetEnv proxy-sendchunked
Now it's working fine :)

Mod_proxy Chunk minimum file size


React + Webpack don't resolve file loaders

Question: I was trying to migrate a typical HTML site to a "light" React app. Therefore, I have installed React without create-react-app.
I configured Webpack and then file-loader to use fonts in the CSS files. But I am still getting errors when compiling because it does not recognize the file loaders (I also tried ttf-loader and url-loader).
I have been reading similar questions but neither of their solutions works on this case.
The project's directory structure looks like this:

webpack.config.js
src

index.js
css

style.css

fonts

pgroofrunners.ttf

This is my current Webpack configuration (webpack.config.js):
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: path.resolve(__dirname, 'src/index'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
        {
            test: /\.js$/,
            include: path.resolve(__dirname, 'src'),
            use: ['babel-loader']
        },
        {
            test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[ext]',
                  outputPath: 'fonts/'
                }
              }
            ]
          }
    ]
  },
  devServer: {
    contentBase:  path.resolve(__dirname, 'dist'),
    port: 9000
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/index.html"
    })
  ]
};

So, when I run webpack-dev-server --mode development it compiles but then crashes with the following errors:

C:\Web\pwa-static2>yarn serve
yarn run v1.17.3
$ webpack-dev-server --mode development
i 「wds」: Project is running at http://localhost:9000/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from C:\Web\app1\dist
× 「wdm」: Hash: 77bf7ce09014ddcd0764
Version: webpack 4.41.5
Time: 3901ms
Built at: 2020-01-27 13:35:42
     Asset      Size  Chunks             Chunk Names
 bundle.js  1.43 MiB    main  [emitted]  main
index.html  2.75 KiB          [emitted]
Entrypoint main = bundle.js
[0] multi (webpack)-dev-server/client?http://localhost:9000 ./src/index 40 bytes {main} [built]
[./node_modules/ansi-html/index.js] 4.16 KiB {main} [built]
[./node_modules/react-dom/index.js] 1.33 KiB {main} [built]
[./node_modules/react/index.js] 190 bytes {main} [built]
[./node_modules/strip-ansi/index.js] 161 bytes {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:9000] (webpack)-dev-server/client?http://localhost:9000 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.91 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./src/css/style.css] 335 bytes {main} [built] [failed] [1 error]
[./src/index.js] 207 bytes {main} [built]
    + 30 hidden modules

ERROR in ./src/css/style.css 1:0
Module parse failed: Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> @font-face {
|     font-family: pgRoofRunners;
|     src: url("../fonts/pgroofrunners.ttf");
 @ ./src/index.js 3:0-25
Child html-webpack-plugin for "index.html":
     1 asset
    Entrypoint undefined = index.html
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 2.99 KiB {0} [built]
    [./node_modules/lodash/lodash.js] 528 KiB {0} [built]
    [./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
    [./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
i 「wdm」: Failed to compile.

I guess this is what is crashing the app in **src/css/style.css*:
@font-face {
    font-family: pgRoofRunners;
    src: url("../fonts/pgroofrunners.ttf");
}

How can I solve this?
Comment: You need a [style loader](https://github.com/webpack-contrib/style-loader)
Answer: Instead of file-loader, I used url-loader (need to be installed).
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }

Answer: It looks like you are importing the CSS somewhere with webpack. In order to understand CSS, webpack needs a loader for that as well. Usually you have something like this in your module.rules:
{
  test: /\.css$/,
  use: [MiniCssExtractPlugin.loader, 'css-loader']
}

or, if you don't use MiniCssExtractorPlugin:
{
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
}


Assembly: How to print offset values

Question: I am trying to print out the offset values.
(Is the term "print" correct? Is there another term for it?
Is the code correct? I am rather confused with documentation for assembly.
print_offsets:  mov  SI,0
                mov  CX,30
                mov  AH,2
                int  21h
                jmp  offsloop

offsloop:       cmp  0,Array[SI]
                ja   print_offset ;if the array element is nonzero
                inc  SI
                dec  CX
                jnz  offsloop

print_offset:   mov DL,SI
                mov  AH,2
                int  21h

Answer: If you're trying to print numbers, your code is incorrect.
INT 21h, AH=2 outputs an ASCII character. What your code is doing is putting the offset value into DL. DOS will treat that offset value as an ASCII character and output that instead.
For example, suppose the first non-zero element is at an offset of 7. Your code will call INT 21h, AH=2 with DL=07. DOS will output the ASCII character 07h which is BEL (basically a system beep). Instead, you would probably want DL=37h in order to output the ASCII character 37h which represents the number 7 digit.
There are a couple of ways of solving this.
The first way is easy - if your Array never has more than 10 elements, you can simply add 30h to the offset to convert the offset value to the correct ASCII character value:
print_offsets:  mov  SI,0          ; SI=offset
                mov  CX,10         ; CX = count (must be <= 10!!!!)

offsloop:       cmp  0,Array[SI]
                ja   print_offset ;if the array element is nonzero
next_element:   inc  SI
                dec  CX
                jnz  offsloop
                jmp finished

print_offset:   mov DL,SI
                add DL, 30h      ; convert offset to ASCII digit 0..9
                mov  AH,2
                ; save the registers in case INT 21h modifies them!
                push cx          ; save current count
                push si          ; save current offset
                int  21h
                pop si           ; restore current offset
                pop cx           ; restore current count
                jmp next_element
finished:
                ; do something else!

The second way is more complex because you need to implement a full integer-to-ascii conversion routine. But there are plenty of code samples out there that can do that.
Comment: Why do you need to save the current count?
Comment: Execution will continue to the next array element after a print_offset. If INT 21 modifies the cx register, the count value (which you're still using) will be wrong.
Comment: I see. So where does cx and si get pushed into? Their own cx[] and si[] array?
Comment: No. PUSH and POP are general purpose x86 instructions for placing data onto (and taking data off) the stack. The stack is an area of memory pointed to by the SP register. You probably need to read more about the basic x86 architecture to really understand what's going on here.

Assembly: How to print offset values


Customizing a drupal webform for Drupal 6

Question: I am working on a system that would require users to register online by filling out a membership application form. There used to be a PDF form that used to be filled out and sent for processing. The client wants the online form to be as close in appearance to this PDF form. Is it possible to customize a form created using webforms such that it can have some of these elements such as logos, images, etc.?
Answer: You can customize form's HTML markup using Drupal's form alter hooks:

hook_form_alter or hook_form_FORM_ID_alter
Form API Reference

after changing form's markup you should only styling form using CSS.


Create a new order

Question: I am working with Drupal commerce and I want to create a new order with the Rules module, when the Completing checkout process event is fired.
The second order should have all the same commerce line items the first order has.
Could anyone help me?
Answer: Perhaps you can do the following (not entirely sure though)
Create a rule that triggers on Checkout completion and execute custom php code.
How it works:
On the event Completing the checkout process the order that is involved in this checkout process is available through the variable $commerce_order. Then we assign this order to a new variable and use it in the code provided by the function referenced below. We save the uid and profile_id from the order we want to clone so we can set the user and the billing information on the clone.
Import code of rule
<code>{ "rules_clone_order" : {
    "LABEL" : "Clone order",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "custom" ],
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "php_eval" : { "code" : "$previous_order = $commerce_order;\r\n$uid = $previous_order-\u003Euid;\r\n$profile_id = $previous_order-\u003Ecommerce_customer_billing[LANGUAGE_NONE][0][\u0027profile_id\u0027];\r\n\r\nforeach (commerce_order_load_multiple(array(), array(\u0027status\u0027 =\u003E \u0027pending\u0027), TRUE) as $previous_order) {\r\n  $product_ids = array();\r\n  foreach (entity_metadata_wrapper(\u0027commerce_order\u0027, $previous_order)-\u003Ecommerce_line_items as $delta =\u003E $line_item_wrapper) {\r\n    if (in_array($line_item_wrapper-\u003Etype-\u003Evalue(), commerce_product_line_item_types())) {\r\n      $product_ids[] = $line_item_wrapper-\u003Ecommerce_product-\u003Eraw();\r\n    }\r\n  }\r\n}\r\n\r\n    $order = commerce_order_new ( $uid , \u0027pending\u0027 );\r\n    \/\/ Save the order so its ID is assigned.\r\n    commerce_order_save ( $order );\r\n\r\n    $order_wrapper = entity_metadata_wrapper ( \u0027commerce_order\u0027 , $order );\r\n\r\n    \/\/add products to order by ids array\r\n    foreach ( $product_ids as $product_id ) {\r\n        $product = commerce_product_load ( $product_id );\r\n\r\n        \/\/ Create a line item with quantity 1 and this product.\r\n        $line_item = commerce_product_line_item_new ( $product , 1 , $order-\u003Eorder_id );\r\n\r\n        \/\/ Save the line item to get its ID.\r\n        commerce_line_item_save ( $line_item );\r\n\r\n        \/\/ Add the line item to the order using the wrapper.\r\n        $order_wrapper-\u003Ecommerce_line_items[ ] = $line_item;\r\n    }\r\n\r\n\r\n    $profile_object = array ( \r\n        \u0027und\u0027 =\u003E array ( array ( \u0027profile_id\u0027 =\u003E $profile_id , ) , ) , ); \r\n    \r\n    \r\n    $order-\u003Ecommerce_customer_billing = $profile_object;\r\n\r\n    \/\/ Save the order.\r\n    commerce_order_save ( $order );" } }
    ]
  }
}
</code>
Credits:
The code to save an order comes from this post:   https://drupalcommerce.org/comment/3491#comment-3491
Comment: I still have an issue if you could help me again !
Comment: Great, good to hear :)
Comment: I just have another question , shall I tell you that here , or post another question ?
Comment: Better to post another question I guess :)
Comment: Already done , I will be very very pleased if you could help me in this issue , you will save my life if you do : Link : http://drupal.stackexchange.com/questions/229093/create-many-order-using-drupal-rules . Thank you

Create a new order


Holt-Winters exponential smoothing formula

Question: I am trying to implement Holt-Winters exponential smoothing in Java program (I understand that R and Python have implementations of these algorithms, but I can't use those due to other reasons, so they are ruled out).
I have been going through Rob J. Hyndman's book and formula. I am trying to execute the following formula on my sample data manually, but I'm having a hard time understanding some of the notations. If I can run it manually, I can start implementing in code:
Let us say we have 12 data points (Monthly data for a year): 8,9,10,7,9,10,9,8,9,8
The last 8 in this data represents current month data, and I want to forecast the next 3 months' values (which will be something like 9,9,8, I assume). How can I use the formula listed in the above link to get these values is the part with which I am struggling.
Specially I am not clear with two things:

What does $\hat{y}_{t+h|t}$ represent? Is it next month's value (or) next value from the starting point?
How can I calculate the $s_{t-m+h_m^+}$ value?

Any pointers to get started on manual calculation would be appreciated. Thanks for your time and help.
Comment: $\hat{y}_{t+h|t}$ means "the forecast at time $t+h$, given data up to time $t$".

So no, it's not the next-period forecast (unless $h=1$), it's the forecast for $h$ periods ahead from time $t$, using information available at time $t$.
Comment: @Glen_b: Thank you! I will work on this tomorrow. Hopefully I can finish this time.
Comment: I'd use the error-correction formula, and the starting values from table 7.9. The $s$ term is easier to understand if you follow through the example.
Comment: @Glen_b: I think I am getting clarity on what is going on here, but stuck at point on how s(t) is 10.3 for first row in this case? Based on formula, I think L(t-1), b(t-1) and s(t-m) are zero for this row right? Which should bring s(t) to ZERO. Any input here?
Answer: I made code for python that can be found here if you want to check it out. It is fairly easy to understand.
y(t+h) is the last point of data you have with the addition of h steps ahead. For example if you forecast 3 months ahead it would be at point t +3
What I used to make my code was the NIST site.
For your second question I think you are calculating the seasonal data. I am not sure what you mean by s((t-m)+hm+).
If you do not want to implement it yourself here is a java implementation I found
Comment: `s((t-m)+hm+)` referred to $s_{t-m+h_m^+}$ in $\hat{y}_{t+h|t} = \ell_{t} + hb_{t} + s_{t-m+h_m^+}$.
Comment: @Nambari You will want to have a way to deal with remainders in step 2 and 3 for seasonal data or else you will only be able to predict X steps at a time, where X is the length of your period. I fixed this at line 180 of my code. That is the only different thing
Comment: @ccsv: Thanks for the java implementation link, I found few other implementations too. To be frank I want to do it manually on paper before to understand the algorithm before picking on any implementation, that gives me flexibility to modify code as required. Thanks for your links though. If any other links which explains algorithm step by step, that would be really helpful.
Comment: @Nambari Then basically follow the NIST site Here: http://www.itl.nist.gov/div898/handbook/pmc/section4/pmc435.htm
Comment: @ccsv: Thanks for those valuable pointers. I will work on these tomorrow.
Comment: @ccsv:@Glen_b: I think I am getting clarity on what is going on here, but stuck at point on how s(t) is 10.3 for first row in this case? Based on formula, I think L(t-1), b(t-1) and s(t-m) are zero for this row right? Which should bring s(t) to ZERO. Any input here?
Comment: @Nambari s(t) is a cyclical component of the season that was extracted out. He is doing by quarters. Notice it goes from 1,10.3,-9.9,-2.4 So it is a continuous pattern that was extracted, which repeats.


Sum and subtraction of euler form numbers

Question: I was unable to find it in nowhere.
How to do sum and subtraction of complex numbers in euler form?
I will give an problem as example:
z1 = 2·exp( -j15° ) and z2 = 13·exp( j45° )
What is z1 + z2 in euler form?
and what is z1 - z2 in euler form?
How i find the results of problems like this, that is, how i do sum and subtraction of complex numbers in Euler Form?
Comment: It's usually easier to add complex numbers in the form $x+yi$ with real $x$ and $y$
Comment: @J.W.Tanner So worth I transform it to the form x + yi to make the sum and subtraction? But not for multiplication and quotient?
Comment: Yes; see [this question](https://math.stackexchange.com/questions/4203175/when-is-writing-complex-number-in-polar-form-better-then-rectangular-form)
Comment: Thank you :D ...
Answer: To add or subtract complex numbers in Euler form,
it's usually easiest to convert them to the form $x+yi$ with real $x$ and $y$
and then add or subtract them.


Backing up a single database with mariabackup?

Question: I've been working on redoing our database backup routines, and have looked into mariabackup as mysqldump doesn't cut it anymore given the size of our schemas. We have multiple schemas that need to be backed up - they all vary in size, and they also vary in backup frequency (some need to be backed up on a six hour period, others can go a day in between backups). On top of that, our database consists of two database servers, running in a master-slave configuration.
To start, I ran this command against one of our schemas:
<code>mariabackup --backup --user root --password <pass> --databases db1
</code>
That generated a copy of the 'db1' schema's data files, along with some files used by MariaDB itself (aria_log, ib_buffer_pool, ib_logfile, ibdata, so on). This works perfectly - we can create separate backups of each of our schemas.
Restoring seems to be another story however. After '--prepare'ing the backup and issuing the mariabackup --copy-back command, it complains that the data directory must be empty. If I have separated backups, would it be possible for me to restore those schemas under one database (or rather, one MariaDB instance)? To be even clearer, if I've made backups of schemas 'db1', 'db2', and 'db3', I don't seem to be able to restore them all under the same database instance - is there something I'm not understanding?
Answer: Partial backup, like yours, can only be restored with --prepare --export. that generates some .cfg files alone the .ibd files.  The "restore" ,is meant to be "ALTER TABLE .. DISCARD TABLESPACE", "ALTER TABLE IMPORT TABLESPACE" for every table on the target system. Unfortunately, it is not 100% automated, because to discard a tablespace on a target system, you first need to create a tablespace on the target system, with the same "CREATE TABLE"


When exactly is ng-checked called

Question: While using AngularMaterial, I have ng-checked like this:
<md-list>
    <md-list-item ng-repeat="option in options">

 {{ option }}

       <md-checkbox class="md-secondary" aria-label="{{$index}}" ng-checked="exists($index)" ng-click="toggle($index)"></md-checkbox>
    </md-list-item>
</md-list>

And my exists function:
$scope.exists = function (optionNum) {
    console.log('Inside $scope.exists. option: '+optionNum);
};

My timer:
function updateTimer() {
    var onTimeout = function(){
      mytimeout = $timeout(onTimeout,1000);
    }
    var mytimeout = $timeout(onTimeout,1000);
}

With this, the $scope.exists function is getting called every second. Can someone please explain how ng-checked and $timeout related ? and how to avoid this ?
Answer: Reason in one word is: digest cycle. Since your function is bound to the view, every time digest cycle happens those expressions gets evaluated as a part of dirty check to make sure if respective DOM needs to be updated or not. This is nothing to do with angular material alone, it is the core angular implementation. Now in your case you are calling $timeout infinitely which means after each timeout execution digest cycle happens to perform dirty check.
Now what you have is fine, but whenever you bind a function to DOM (as a part of view binding, interpolation or property state attributes or even DOM filters - of course events are fine) you should be aware of the fact that you do not perform extensive operation in that function accidentally or intentionally as the app grows, it will slow down the entire app, and will be hard to refactor and diagnose when the app grows larger and problems starts happening. As much as possible bind to a property instead of a function. Note that even if you bind a property still angular $parse creates a getter on it and adds it to the $$watchers queue to be dirty checked every digest cycle, but difference is that it is a simple getter function.
So basically for instance in your case you could bind ng-checked to property
..ng-checked="doesExist"

and set the property doesExist whenever it needs to be updated. So with this instead of checking for the existence every time, you explicitly set the respective property when a respective event happens. That makes the logic explicit as well.
Answer: ng-checked, like many of angular's directives are based on watches. Anytime a digest cycle is called, it evaluates all of the watchers (which the function you are using is one of). So every time $timeout evaluates it is starting a new $digest cycle and evaluating all of the watchers. This is part of the "magic" that keeps the view updated with all of the data in your controllers and directives.
Watchers can become a performance issue if you make your functions complex, or make TONS of watchers. It is generally best to have simple logic that returns true or false very quickly and to avoid setting watches on everything.
Comment: I was just wondering that myself, they didn't even have time to read it!
Comment: Updated, from everything I've read watchers are fine as long as you keep them quick and in a reasonable quantity

When exactly is ng-checked called