How can I use perfmon/logman to set up logging on a master (Windows) VM, writing to another machine on the network?

Question: I know how to set up logging to write to a remote location in the general case - just specify the output filename using the full UNC path (e.g. \\HOST-PC\directory\logoutput.etl) when creating the log job. However, a problem arises when new Virtual Machines are created from a master VM where logging has been enabled: each VM will be writing logs to the exact same file on the network. I need to find a way that each new VM will automatically write to a remote file unique to it.
I've tried using the %ComputerName% environment variable in the UNC path when setting up the log using logman.exe (e.g. \host\directory\%ComputerName%\log.etl) hoping that each VM would automatically expand this to include its unique name, but this doesn't work - you just get a folder named "%ComputerName%", without the variable being expanded. This is despite the fact that if you use e.g. %SystemRoot%, this does get expanded correctly (though of course this would create an invalid path in this instance). I'm not sure what causes some variables to be expanded and not others.
Any better ideas?
Comment: Let me know if any of that needs clarification!
Comment: [Use logman update to change output directory and logman start after updating](https://i.stack.imgur.com/M5ICW.png)
Answer: I don't see how it can be done natively with logman, but through both the UI and the COM interface, you can set the Subdirectory Format to include the computer name as a prefix.

See MSDN for documentation on how to set the option programmatically.
Edit: The checkbox in question appears on both the data set collector and the performance counter itself.  The performance counter seems to have the option greyed out.  Be sure to right click the item under "Data Collector Sets > User Defined" in the MMC tree to adjust the appropriate option.
Also, Powershell:
$taskName = "daily_perf_log"
$qualifiedName = "Service\{0}" -f $taskName

# retrieve the collection set
$dcss = new-object -com Pla.DataCollectorSetCollection
$dcss.GetDataCollectorSets($null, $qualifiedName)
$dcs = $dcss.Item(0)

# update
# 3 to enable, 1 to disable (http://msdn.microsoft.com/en-us/library/windows/desktop/aa371811(v=vs.85).aspx)
$dcs.SubdirectoryFormat = 3 <# Prepend computer name #>

# save
# 1 create new / 2 update / other options (http://msdn.microsoft.com/en-us/library/windows/desktop/aa371873(v=vs.85).aspx)
$dcs.Commit($qualifiedName, $null, 2 <# update only #>)

Comment: Thanks for adding that PowerShell code. However, trying it, it seems to perform a one-off rename of the directory, rather than what I would expect that tick-box to do. So if I rename the machine, the path of the log file keeps the previous name rather than automatically changing. I'll add that I'm using "Autosession\..." rather than "Service\..." as I found the latter returned 0 results. Perhaps we're thinking of different things? I don't see anything listed in the "Data Collector Sets > User Defined" pane in perfmon.exe.
Comment: That does seem to be the case.  If you are trying to capture all logs, perhaps have a sysprep action which sets the unique name.  E.g.: log to `C:\drop\logs` on the base image, a sysprep action runs the script above to set to the computer name, and copies `C:\drop\logs` to the central server.
Comment: That would work perfectly - not sure how I didn't see that before! One more problem though, that tick-box is greyed out for me, any idea why?


Estimating Poisson process intensity using GLM

Question: Suppose I want to build an explanatory model for events generated by an inhomogeneous Poisson process with unknown intensity $\lambda$. Each entry in my dataset represents the registration of an event: time $t_i$, location $(x_i,y_i)$ and some explanatory variables $z_{i1},...,z_{ip}, i=1,...,n$. The entries are in chronological order. I want to estimate the effect of the explanantory variables on the intensity of the Poisson process using GLM.
The entries cannot be grouped, because this inevitably leads to loss of explanatory information. Hence a count model with poisson regression does not work in this case.
However, if we assume that the sojourn times $s_i$ (which we can compute in this dataset) are exponentially i.i.d., we can apply Gamma regression. Please ignore for the moment that we lose one observation due to differencing. Using a log link this becomes
$E[s_i|\textbf{z}_i] = exp(\beta_0 + \beta_1 z_{i1} + ... + \beta_p z_{ip}) = \lambda(z_{i1},...,z_{ip})$
(Edit) Since the explanatory data analysis reveals that the process is inhomogeneous both in time and two-dimensional space, I also include the location coordinates in the linear component:
$E[s_i|\textbf{z}_i,x_i,y_i] = exp(\beta_0 + \beta_1 z_{i1} + ... + \beta_p z_{ip} + \gamma_1 x_{i} + \gamma_2 y_{i}) = \lambda(z_{i1},...,z_{ip},x_i,y_i)$
Questions:

Is this approach valid?
Can I assume the sojourn times to be exponentially i.i.d. given that the Poisson process is inhomogeneous?
Does $E[s_i|\textbf{z}_i,x_i,y_i]$ indeed model the intensity of the process?
Am I modeling a one-dimensional (time), three-dimensional (time and location) or a $p+2$ dimensional Poisson process?
Comment: I don't think it's technically valid, but it (i.e. assuming piecewise-constant intensity between events) seems to be a reasonable approximation for a slowly varying process ...
Comment: Thank you for your suggestion. It makes sense to see it as an approximation, rather than a model for the true sojourn time distribution. I was under the impression that inhomogeneous processes could be modeled as if they were homogeneous - at least in the 1D case every inhomogeneous process can be transformed into an homogeneous one. It is not entirely clear to me how this affects the sojourn time distribution though
Answer:
Can I assume the sojourn times to be exponentially i.i.d. given that the Poisson process is inhomogeneous?

In general the inter-event intervals will not be exponentially distributed. This paper by Yakovlev et al. (2008) derives an expression for the inter-event distribution for one-dimensional non-homogeneous Poisson distributions (Equation 6) and gives counterexamples (e.g., Equation 8).

Am I modeling a one-dimensional (time), three-dimensional (time and location) or a $p + 2$ dimensional Poisson process?

I'm guessing you want to model a three-dimensional process. It's not one-dimensional, because you will have different rates $\lambda(t, x, y)$ for different positions $(x, y)$. On the other hand, it's not $(p + 2)$-dimensional, since you probably observe only one $\mathbf{z}$ for every time and position, so that knowing $(t, x, y)$ implies knowing the value of $\mathbf{z}$. Of course you might then assume something like $\lambda(t, x, y) = \lambda(\mathbf{z}_{txy})$ or $\lambda(t, x, y) = \lambda(\mathbf{z}_{txy}, x, y)$, but I would still call that a three-dimensional process.


How do I force Breadcrumb to use a menu other than Main Menu?

Question: I am trying to force breadcrumb to follow the structure of a menu other than Main Menu.
I have configured the content type to use the new menu to add links, which are displayed correctly in the sidebar menu. However breadcrumb just displays Home > (current_page).
Where is this configured? Is it hard coded?
Any advice appreciated.
Cheers
Paul
Answer: Menu Breadcrumb
By default, Drupal will use the Navigation menu for the breadcrumb. This module allows you to use the menu the current page belongs to for the breadcrumb.
As an added bonus, it also allows you to Append the page title to the breadcrumb (either as a clickable url or not) and hide the breadcrumb if it only contains the link to the front page.
Comment: This is of course the correct answer. Saved me a lot of time!
Comment: Then you should mark it as correct. :)
Comment: I thought I had... obviously not. Now marked as correct. Thanks again.


prove $ H(x)\geq \ln(x)(\ln (1 - x))$ for $ 0\lt x\lt 1$

Question: The equation below is true i have proved it using values between 0 and 1 but how can I prove it mathematically? I have already reduced it to its simplest form (according to me) and I am kind of stuck at this point:
$$ H(x)\geq \ln(x)(\ln (1 - x)) \qquad\text{for}\qquad 0\lt x\lt 1$$
where $$ H(x) = -x \ln(x) - (1-x)\ln(1-x)$$
Any help will be quite useful to me. Thanks.
Answer: We have to show that
$$
f(x) = x \ln(x) + (1-x) \ln(1-x) + \ln(x) \ln(1-x) \\
= \bigl( \ln(x) + 1 - x \bigr) \bigl( \ln(1-x) + x \bigr) - x(1-x)
$$
is $\le 0$ for $0 < x < 1$. Using the "well-known" estimates
$$
 \frac{x-1}{x} \le \ln(x) \le x-1 \quad (\text{for } x > 0)
$$
(see for example How can I prove that $ \frac {x-1}{x}\leq \log x\leq x-1$), the first factor can be estimated as
$$
 0 \ge \ln(x) + 1 - x \ge \frac{x-1}{x} + 1-x = -\frac{(1-x)^2}{x}
$$
and the second factor as
$$
 0 \ge \ln(1-x) + x \ge \frac{-x}{1-x} + x = -\frac{x^2}{1-x} \, .
$$
It follows that
$$
 f(x) \le \frac{(1-x)^2}{x} \cdot \frac{x^2}{1-x} - x(1-x) = 0 \, .
$$
Answer: Note that for $0\lt x\lt1$,
$$
x=\int_0^x1\,\mathrm{d}t\le\overbrace{\int_0^x\frac1{1-t}\,\mathrm{d}t}^{-\log(1-x)}\le\int_0^x\frac1{1-x}\,\mathrm{d}t=\frac{x}{1-x}\tag1
$$
Negating gives,
$$
-\frac{x}{1-x}\le\log(1-x)\le-x\tag2
$$
Therefore,
$$
-\frac{x^2}{1-x}\le x+\log(1-x)\le0\tag3
$$
and substituting $x\mapsto1-x$,
$$
-\frac{(1-x)^2}{x}\le(1-x)+\log(x)\le0\tag4
$$
Multiplying inequalities $(3)$ and $(4)$ gives
$$
[x+\log(1-x)][(1-x)+\log(x)]\le x(1-x)\tag5
$$
which upon rearrangement yields
$$
\log(1-x)\log(x)\le-x\log(x)-(1-x)\log(x)\tag6
$$
which is the inequality sought.
Answer: One approach is to show that the function $$G(x) = \ln(x) \ln(1-x) - H(x)$$ is convex, i.e. $G''(x) \geq 0$ for $0 < x < 1$. Since $G$ is continuous on $[0,1]$ and $G(0) = G(1) = 0$, it follows that $G(x) \leq 0$ on $[0,1]$ yielding the desired inequality.
A direct calculation gives
$$
G''(x) = \frac{-\ln(x)}{(1-x)^2} + \frac{-\ln(1-x)}{x^2} - \frac{1}{x(1-x)}.
$$
The first two terms have a "good" sign, but the third term has a "bad" sign for $0 < x < 1$. Using the elementary inequalities $-\ln(1-x) \geq x, -\ln(x) \geq 1-x$ for $0 \leq x \leq 1$, we get
$
G''(x) \geq 0.
$


How many permutations are the on $\mathbb{Z}_5$ such that the orbits of 2 have 3 elements

Question: How many permutations are the on $\mathbb{Z}_5$ such that the orbits of $2$ have $3$ elements.
It looks like there are $24$. There are $12$ such permutations where the elements outside the orbit of $2$ are fixed and a another $12$ where they permute to each other.
This one wasn't bad to make an exhaustive list but that could quickly become tiresome. How to I figure that out without making an exhaustive list? I tried looking at my book but couldn't figure it out!
Answer: Using the cycle representation, we know that such a permutation $\sigma$ contains a 3-cycle of the form $(2 \; a \; b)$ where $a \neq b$ are elements of $\mathbb{Z}_5 \setminus \{2\}$.
There are thus $4 \cdot 3$ such 3-cycles, and for each such cycle we could either swap the remaining two elements of $\mathbb{Z}_5$ or fix them. This gives a total of $2 \cdot (4 \cdot 3)=24$ permutations.


Creating default object from empty value

Question: I am having issues with a template - in the template.php there is code causing a warning:
Warning: Creating default object from empty value in theme545_preprocess_html() (line 31 of /home/noramtow/public_html/sites/all/themes/theme545/template.php).
The line in questions is this:
$vars['rdf']->version = 'version="HTML+RDFa 1.1"';

The whole section of code looks like this:
function theme545_preprocess_html(&$vars) {
if (module_exists('rdf')) {
$vars['doctype'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML+RDFa 1.1//EN">' . "\n";
$vars['rdf']->version = 'version="HTML+RDFa 1.1"';
$vars['rdf']->namespaces = $vars['rdf_namespaces'];
$vars['rdf']->profile = ' profile="' . $vars['grddl_profile'] . '"';
} else {
$vars['doctype'] = '<!DOCTYPE html>' . "\n";
$vars['rdf']->version = '';
$vars['rdf']->namespaces = '';
$vars['rdf']->profile = '';
}
$vars['classes_array'][] = 'body';

I'm not great with PHP - anyone have any idea how to fix this or what's causing it??
Thanks for any help you can give!!
Candace
Answer: It sounds like your system wants to make sure $vars['rdf'] is a valid object before assigning properties to it.
Try adding:
if (empty($variables['rdf']) || !is_object($variables['rdf'])) {
  $vars['rdf'] = new stdClass();
}

Just above your line 31.
For safety's sake, add it above
if (module_exists('rdf')) {

That way the object will get initialized regardless of whether the RDF module is enabled or not.
Comment: I added it an uploaded, but it's still showing the same warning.  :-(
Comment: Rats. Do you know what version of PHP you have?
Comment: No, but they're a really good hosting company, and they're usually really updated.
Comment: Keeping PHP at the latest version would be risky for a host - they might break Drupal and Wordpress. So you are on Drupal 7 you are using PHP 5.2 or 5.3 - I was able to replicate this error on 5.3 but not 5.2.

I updated my code with the solution that works for me.
Comment: Has anyone told you that you are BRILLIANT??!!  THANK YOU!!!!
Comment: You are nice. I would feel more brilliant if I got it right on the first try.


How to compute the gradient for a separable nonlinear least-squares problem?

Question: Consider the case of non-linear least squares regression with one dependent variable $y_i$ and two independent variables $x_{i1}$ and $x_{i2}$ where the non-linear function is a linear function of two non-linear functions $f_1$ and $f_2$ (for simplicity I reduce this to two functions and functions with only one parameter/coefficient but it can be more general)
$$y_i  =  \sum_{j=1,2} \alpha_j f_j(x_{ij},\beta_j) + \epsilon_i$$
Say we wish to use fit this function to some data with least squares regression, then we could find the solution with a step-wise algorithm that alternates between fitting the $\alpha_j$ and $\beta_j$. This can be a useful approach because the solution for the $\alpha_j$ when the $\beta_j$ are fixed is easily found by ordinary least squares regression.
To perform the optimization step for the $\beta_j$ we need to know the gradient of the loss function. There are solvers that can estimate the derivatives computationally, but the algorithms will be faster and more accurate when we can provide the derivatives ourselves.
How do we describe the derivative $\frac{\partial L}{\partial \beta_j}$ of the sum of squared residuals loss function $$L = \Vert y - \hat{y}\Vert ^2$$
when
$$\hat y = F (F^T F)^{-1} F^T y$$
where the $F$ is the matrix of the regressors $f(x_{ij}, \beta_{j})$
$$F = \begin{bmatrix} f(x_{{11}}, \beta_1) & f(x_{12}, \beta_2) \\
f(x_{{21}}, \beta_1) & f(x_{22}, \beta_2) \\
f(x_{{31}}, \beta_1) & f(x_{32}, \beta_2) \\
\vdots & \vdots \\
f(x_{{n1}}, \beta_1) & f(x_{n2}, \beta_2) \\  \end{bmatrix}$$
There should be some simple way to express
$$\frac{\partial L}{\partial \beta_j}$$
in terms of $\frac{\partial f(x_{ij})}{\partial \beta_j}$
Comment: See also the Gauss-Newton algorithm.
Comment: @JohnMadden yes this could be applied to a Gauss-Newton algorithm (if we also compute second derivatives, but maybe the expressions become too complex) . Although in the code I used a line search gradient-descent method with a very small maximum step size; that gives a prettier image (follows more smoothly the gradient) that's works better for introducing the principle of gradient descent...
Comment: ...A difference/detail in this question is that the parameters $\alpha_j$ are optimised seperately by using the method for solving a linear least squares problem. The question is about how to eliminate these $\alpha_j$ such that we end up with a function of only $\beta_j$ and the derivatives of that function, and such that we can apply the Gauss-Newton algorithm by using a function of only the parameters $\beta_j$ instead of a function of parameters $\beta_j$ and $\alpha_j$.
Comment: Gauss Newton does not require Hessian terms, it approximates them (somewhat a la BFGS) :). Thanks for clarifying your intentions. Just out of curiosity, have you tried just straight up jointly optimizing everything (e.g. not profiling $\alpha$ out)? I'm currently deciding between similar approaches on a different problem.
Answer:
A related question exist on math.stackexchange.com Derivative of projection with respect to a parameter: $D_{a}: X(a)[ X(a)^TX(a) ]^{-1}X(a)^Ty$
The answer suggests using the product rule which leads to:
$$\begin{align}\hat{y}^\prime =(X(X^TX)^{-1}X^Ty)^\prime&=X^\prime(X^TX)^{-1}X^Ty\\&-X(X^TX)^{-1}(X^{\prime T}X+X^TX^\prime)(X^TX)^{-1}X^Ty\\&+X(X^TX)^{-1}X^{\prime T}y\prime.\end{align}$$
Then we compute the derivative of the loss function as
$$L^\prime = \left( \sum (y-\hat{y})^2 \right)^\prime = \sum -2(y-\hat{y})\hat{y}^\prime$$
Where $^\prime$ denotes the derivative to any of the $\beta_j$
Example:
In the example below, we fit the function
$$y_i  = \alpha_{1} e^{\beta_1 x_{1,i}} + \alpha_2 e^{\beta_2 x_{2,i}}$$
In this case $X^\prime = \frac{\partial}{\beta_j} X$ will be the same as $X$ but with the $i$-th column multiplied with $x_i$ and the others zero.
Below is some R-code that illustrates the computation. It is a gradient descent method that uses the function fr to compute the cost function and the function gr to compute the gradient. In this function gr we have computed the derivatives as above. The value of the cost function as a function of $\beta_1$ and $\beta_2$ is shown in the figure below. The thick black line shows the path that is followed by the gradient descent method.

set.seed(1)

# model some independent data t1 and t2
x1 <- runif(10,0,1)
x2 <- runif(10,0,0.1)+x1*0.9
t1 <- log(x1)
t2 <- log(x2)
# compute the dependent variable y according to the formula and some added noise
y <- round(1*exp(0.4*t1) - 0.5*exp(0.6*t2) + rnorm(10, 0 ,0.01),3)

###############################

# loss function
fr <- function(p) {
  a <- p[1]
  b <- p[2]
  u1 <- exp(a*t1)
  u2 <- exp(b*t2)
  mod <- lm(y ~ 0 + u1 + u2)
  ypred <- predict(mod)
  sum((y-ypred)^2)
}

# gradient of loss function
gr <- function(p) {
  a <- p[1]
  b <- p[2]
  u1 <- exp(a*t1)     ### function f1
  u2 <- exp(b*t2)     ### function f2
  X <-  cbind(u1,u2)       # matrix X
  Xa <- cbind(t1*u1,0*u2)     # derivative  dX/da
  Xb <- cbind(0*u1,t2*u2)     # derivative  dX/db

  ### predicted y
  mod <- lm(y ~ 0 + u1 + u2)
  ypred <- predict(mod)

  ### computation of the derivatives of the projection
  dPa <- Xa %*% solve(t(X) %*% X) %*% t(X) %*% y -
         X %*% solve(t(X) %*% X) %*% (t(Xa) %*% X + t(X) %*% Xa) %*% solve(t(X) %*% X) %*% t(X) %*% y +
         X %*% solve(t(X) %*% X) %*% t(Xa) %*% y
  dPb <- Xb %*% solve(t(X) %*% X) %*% t(X) %*% y -
         X %*% solve(t(X) %*% X) %*% (t(Xb) %*% X + t(X) %*% Xb) %*% solve(t(X) %*% X) %*% t(X) %*% y +
         X %*% solve(t(X) %*% X) %*% t(Xb) %*% y

  ### computation of the derivatives of the squared loss
  dLa <- sum(-2*(y-ypred)*dPa)
  dLb <- sum(-2*(y-ypred)*dPb)

  ### result
  return(c(dLa,dLb))
}

# compute loss function on a grid
n=201
xc <- 0.9*seq(0,1.5,length.out=n)
yc <- 0.9*seq(0,1.5,length.out=n)
z <- matrix(rep(0,n^2),n)
for (i in 1:n) {
  for(j in 1:n) {
    z[i,j] <- fr(c(xc[i],yc[j]))
  }
}

# levels for plotting
levels <- 10^seq(-4,1,0.5)
key <- seq(-4,1,0.5)

# colours for plotting
colours <- function(n) {hsv(c(seq(0.15,0.7,length.out=n),0),
                            c(seq(0.2,0.4,length.out=n),0),
                            c(seq(1,1,length.out=n),0.9))}
# empty plot
plot(-1000,-1000,
     xlab=expression(n[1]),ylab = expression(n[2]),
     xlim=range(xc),
     ylim=range(yc)
)

# add contours
.filled.contour(xc,yc,z,
                col=colours(length(levels)),
                levels=levels)

contour(xc,yc,z,add=1, levels=levels, labels = key)

# compute path
# start value
new=c(0.9,1.1)
maxstep <- 0.001
# make lots of small steps
for (i in 1:5000) {
  ### safe old value
  old <- new
  ### compute step direction by using gradient
  grr <- -gr(new)
  lg <- sqrt(grr[1]^2+grr[2]^2)
  step <- grr/lg
  ### find best step size (yes this is a bit simplistic and computation intensive)
  min <- fr(old)
  stepsizes <- maxstep*10^seq(-2,0.001,length.out1=100)
  for (j in stepsizes) {
    if (fr(old+step*j)<min) {
      new <- old+step*j
      min <- fr(new)
    }
  }
  ### plot path
  lines(c(old[1],new[1]),c(old[2],new[2]),lw=2)
}

# finish plot with title and annotation
title(expression(paste("Solving \n", sum((alpha[1]*e^{beta[1]*x[i,1]}+alpha[2]*e^{beta[2]*x[i,2]}-y[i])^2,i==1,n))))
points(0.9,1.1)
text(0.9,1.1,"start",pos=2,cex=1)
points(new[1],new[2])
text(new[1],new[2],"end",pos=4,cex=1)

See for a historic showcase of this method:
"The Differentiation of Pseudo-Inverses and Nonlinear Least Squares Problems Whose Variables Separate" by G. H. Golub and V. Pereyra in SIAM Journal on Numerical Analysis Vol. 10, No. 2 (1973), pp. 413-432


Can I declare an autofilter as object?

Question: Hellow, is it possible to use?
dim x as Range
set x = Workbooks("main.xlsm").Worksheets("filter").Range("A1:Y100").AutoFilter field:=1, Criterial:="<>0"

I get an error saying that it expects end of instruccion and highlights field
Comment: Change `Criterial:="<>0"` to `Criteria1:="<>0"`  (replace the `l` for a `1`)      (I also added a picture with the English text "Compile error: Expected: end of statement")
Comment: Because you must use parentheses when you are storing a function's result into a variable? (Which is a general VBA rule, irrespective to whether the `AutoFilter` method specifically returns anything useful.)
Comment: `AutoFilter` doesn't return a Range object - seems like it only returns True/False.  What are you trying to do there?
Comment: You need to add parentheses around the arguments
Comment: @TimWilliams ir helps me to filter all cells with zeros and leave me only the rows with relevant data, sin all the other rows have zeros from a reference it's very useful
Comment: Thanks @Luuk I will try it, always confuse me the >l with the >1
Answer: Maybe something like this:
Dim x as Range

With Workbooks("main.xlsm").Worksheets("filter").Range("A1:Y100")
    .AutoFilter field:=1, Criteria1:="<>0"
    Set x = .SpecialCells(xlCellTypeVisible)
End With

Just guessing what you want with x though.

Can I declare an autofilter as object?


HTTPS redirects in nginx

Question: I'm trying to redirect all HTTP traffic to HTTPS. The web server I'm using is nginx. This is the server block I'm using to do the redirect.
server {
    listen      80;
    rewrite ^ https://$server_name$request_uri? permanent;
}

This successfully redirects URLs like http://localhost to https://localhost. However, for URLs like http://localhost/table/ I get redirected to https://table which is incorrect. I would like it to re-direct to https://localhost/table/
Any help would be much appreciated.
Update:
It seems that the rewrite scheme has a problem with trailing slashes. For example, http://localhost/table gets correctly redirected but http://localhost/table/ does not.
Comment: can you try to hardcode the server name like https:// localhost$request_uri? permanent; and check if it works
Comment: Hard coding the server name to localhost fixes it. However, other machines cannot access it as they get redirected to localhost, instead  of the server name.
Comment: Ok, so nginx is not getting $server_name. Set the servername $server_name domain.com
Comment: I don't think that's the problem. To test it out, I've set server_name  and I still get the same behaviour. It looks like the rewrite rule is getting confused and is treating /table/ as the server name.
Comment: Are you sure that your problem isn't in your https server configuration?
Answer: server {
    listen 80;
    rewrite 301 https://$host$request_uri;
}

http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

HTTPS redirects in nginx


Adicionar Conta em Array e Exibir as informações em uma Table

Question: Podem me ajudar com um código?
Preciso que insira informações em dois Array diferentes através de duas mensagens prompt sempre que o botão "Adicionar Conta" seja acionado e, assim que o botão "Mostrar contas" for acionado, mostrar todas as contas em uma tabela com o número da conta (nCad), o nome e o valor na conta. Meu código não funciona da forma que eu gostaria.

var nomeA = new array[''];
var account = new array[''];
var nCad = new array[''];
var cadastro = 0;

function addAccount(){
  cadastro++;
  nomeA.push = prompt("Nome: ");
  account.push = prompt("Conta: ");
  nCad.push = cadastro;
}

function showAccounts(){
info.innerHTML("
");

for(x=0; x=cadastro; x++){
  info.innerHTML("
");
  info.innerHTML("" + nCad[x] + "	");
  info.innerHTML("" + nomeA[x] + "	");
  info.innerHTML("" + account[x] + "	");
  info.innerHTML("
");
info.innerHTML("
");
}
td{
  border: 1px solid grey;
}
<button onclick="addAccount()">Adicionar Conta</button>
<button onclick="showAccounts()">Mostrar Contas</button>

Comment: Oi Gabriel, falta um `}` na função `showAccounts`. Sabes isso ou é esse o teu problema?
Answer: Tens alguns erros no teu código:

falta um } na função showAccounts
para inserir HTML deves usar .innerHTML = 'string', e não .innerHTML('string'), isso seria mais parecido com jQuery
para inserir elementos numa array deves usar .push(elemento), e não .push = elemento

Refiz o teu código, removi o nCad e cadastro pois tendo uma array sabes sempre o seu .length ou seja o numero de elementos. No caso do meu exemplo através do indice iterado pelo reduce.

const info = document.getElementById('info');

const clients = [];
const account = [];

function addAccount() {
  clients.push({
    name: prompt("Nome: "),
    account: prompt("Conta: ")
  });
}

function showAccounts() {
  const rows = clients.reduce((html, client, i) => {
    return `

        ${i+1}
        ${client.name}
        ${client.account}

    `;
  }, '');
  info.innerHTML = `<table>${rows}</table>`;
}
td {
  border: 1px solid grey;
}
<button onclick="addAccount()">Adicionar Conta</button>
<button onclick="showAccounts()">Mostrar Contas</button>

Comment: Sim, @Sergio, dessa forma ele funciona bem em quesito geral, porém na tabela aparecem apenas com o a última conta inserida, estou tentando usar o loop do for conforme o 'Lenght' do tamanho do Array de Clientes para criar a tabela com todos os dados.
Comment: @GabrielVeiga já tens uma array com clientes? podes colocar aqui ou na pergunta? e queres ainda ter o `prompt` ou isso foi só para a pergunta?
Answer: const clients = [];
const account = [];

function addAccount(){
   clients.push({
   name: prompt("Nome: "),
   account: prompt("Conta: ")
 });
}

function showAccounts(){
   info.innerHTML = '
';

   for(x=0; x=clients.length; x++){
      info.innerHTML = '' + clientes.lenght +'';
      info.innerHTML = '' + name[x] + '	';
      info.innerHTML = '' + account[x] + '	';
      info.innerHTML = '
';
   }
   info.innerHTML = '
';
}


Necessity of Hausdorff-ness in "continuous function determined by its values on a dense subset"

Question: It's well-known that if a continuous function taking values in a Hausdorff space is uniquely determined by its specification on a dense subset of the domain. Now, I contemplate on the necessity of Hausdorff-ness in this result:
It's clear that the result no longer holds if the codomain is just $T_0$, as is demonstrated by the function $\mathbb R$ to the Sierpiński space $\{0, 1\}$ (with $1$ being the Sierpiński point) given by $x\mapsto 0$ if $x\ne 0$ and $x\mapsto 1$ if $x = 0$. (Thus this and the constant $0$ function are both continuous despite agreeing on the dense $\mathbb R\setminus \{0\}$.)
Now, I am trying to come up with an similar example where the codomain is $T_1$ (and not Hausdorff ofc), but haven't been able to conjure anything up yet. You know anything? The only examples of $T_1$ spaces fmailiar to me are the co-finite/-countable spaces.
Comment: Hello. Are you aware that $X$ being Hausdorff is *equivalent* to $\{y \in Y: f(y) = g(y)\}$ being closed for all topological spaces $Y$ and functions $f, g: Y \to X$? This is usually proved via the also equivalent condition "the diagonal $\{(x, x) : x \in X\}$ is closed in $X^2$". I'm struggling a bit to find a good link to a proof of that at the moment, but it answers your question very strongly - if $X$ is not Hausdorff, you can find $f$ and $g$ which agree on a non-closed set. In particular, that set is dense in its closure but $f$ and $g$ do not agree on the closure!
Comment: I've found some links now. You can piece it together from [here](https://math.stackexchange.com/q/136922/473276) and [here](https://math.stackexchange.com/q/2080863/473276). It's also mentioned [here](https://math.stackexchange.com/q/3436772/473276). When you piece it together, what you end up with is "if $X$ is not Hausdorff, then the two projection maps $\pi_1, \pi_2 : X \times X \to X$ agree on the diagonal $\Delta \subseteq X \times X$, but not on its closure". I'm not sure if this is close enough to count as a duplicate or not.
Comment: @IzaakvanDongen Thanks tons for your responses! But I think I have found a simple example: Any bijection on $\mathbb R$ is continuous with the codomain being taken under cofinite topology. Now, just consider the identity function with two points swapped. What do you think?
Comment: @Atom Looks good to me, with the dense subset taken to be $\Bbb R\setminus\{a,b\}$ where $a,b$ are the swapped points
Comment: @FShrike Great, I will post as an answer then
Comment: List of T1 not T2 spaces: https://topology.pi-base.org/spaces/?q=%24T_1%24%2B%7E%24T_2%24
Answer: Any bijection on $\mathbb R$ is continuous with the codomain taken under cofinite topology. Now, just consider the identity function with two distinct points, $a$ and $b$, swapped. Then this and the identity function are continuous functions agreeing on the dense subset $\mathbb R\setminus\{a, b\}$ and yet distinct.


Comparação com ifs sempre entrando no primeiro

Question: Estou tentando fazer comparação usando if, mas sempre vai no primeiro if:
 if((vetor[0] << vetor[1]) && (vetor [0] << vetor [2]) && (vetor [0] << vetor [3])){
    cout << "\n" << vetor [0] << "\n eh o menor \n"; }

    else if((vetor [1] << vetor [2]) && (vetor [1] << vetor [3])){
    cout << "\n" << vetor [1] << "\n eh o menor \n"; }

    else if ((vetor[2] << vetor[1]) && (vetor [2] << vetor [3])){
    cout << "\n" << vetor [2] << "\n eh o menor \n"; }

    else if ((vetor[3] << vetor[1]) && (vetor [3] << vetor [2])){
    cout << "\n" << vetor [3] << "\n eh o menor \n"; }

Answer: << e >> não são comparadores
Troque << por <, e >> por >.


SQL issue aggregating values based on time

Question: I need a running total of value 1 and value 2.
I have a table that looks like this:
Time | Plus Value | Minus Value 2 |
0         30           10
10        20           15
15        10           20
...

I would like to be able to get the following table
Time | Plus Value | Minus Value 2 | Total
0         30           10             20
10        20           15             25
15        10           20             15
...

I would like to be able to select something like this
select time, plus_value, minus_value(sum(plus_value) - sum(minus_value)) as total
from table
where time <= time

How can I do this? I am forced to group by time which then does not give me the desired result.
Comment: It depends on what RDBMS you are using. MySQL? SQL Server? Pick your variety and then search Stack Overflow for `running-total`
Answer: select time,
       plus_value,
       minus_value,
       sum(plus_value - minus_value) over(order by time rows unbounded preceding) as total
from table

Comment: That the OP's RDBMS can do this is a significant assumption. At least mention where and when this will or won't work?
Comment: Thanks to [SQL Fiddle](http://sqlfiddle.com/) this is tested on SQL Server 2012, Oracle 11g R2 and PostgreSQL 9.1.3. It might work on other DBMS as well.
Comment: Thanks for the solution. I actually came up with another one on my own however I am unable to post for another 6 hours. I'm sure most will have lost interested by then. Cheers
Answer: I don't understand your where clause: where time <= time?
Anyways, I believe that your query could be implemented like:
select time, plus_value, minus_value, (plus_value - minus_value) as total
from table;

Comment: No, check your calculation against the example data.  The OP wants a running total...
Comment: Ahhh..my mistake.  Maybe you can make use of SQL variables: DECLARE @total; SET @total = 0; SELECT time, plus_value, minus_value, (@total + plus_value - minus_value) AS total FROM table; @ total = total;


evaluation of integral using residue theorem

Question: I do not fully understand how to use the residue theorem for evaluating integrals. Can someone evaluate the following integral using the residue theorem explaining step by step?
$$\int_\gamma \frac{e^{z\pi}}{z^2(z^2+2z+2)} \,dz$$
where $\gamma$ is circle of centre $0$ and radius $3$
Comment: I have recently given in (http://math.stackexchange.com/q/2186117) a way to apply residue calculus on an example.
Answer:
Find the zero of $z^2(z^2+2z+2)$.
Find the residue at the zeroes of ${e^{z\pi}\over{z^2+2z+2}}$ multiply them by $2i\pi$  and add the result.
Comment: Yes but I think that it must be said... to somebody who is a newcomer in this technique.
Comment: ... only for the poles which are inside the contour...
Comment: ..but all the poles are inside the contour
Answer: Let $f(z)={e^{\pi z}}/({z^4+2z^3+2z^2})$. The poles of the function are at $z=0,-1\pm i$ and all three poles lie in the contour $\gamma:|z|=3$. To evaluate the integral we can use residue theorem.
$$\int_\gamma f(z)\ dz = 2\pi i \sum\left[\text{residues of}\ f\ \text{inside}\ \gamma\right]$$
So we need to find the residues at all the poles.
$$\int_\gamma \frac{e^{\pi z}}{z^4+2z^3+2z^2}\ dz = 2\pi i\left(\mathrm{Res}(f,0)+\mathrm{Res}(f,-1+i)+\mathrm{Res}(f,-1-i)\right)$$
At $z=0$ the pole is of order $2$ so we can evaluate the residue using the formula for higher-order poles: If $z_0$ is a pole of order $n$, the residue of $f$ at $z_0$ is given by the following.
$$\mathrm{Res}(f,z_0)=\frac{1}{(n-1)!}\lim_{z\to z_0}\frac{d^{n-1}}{dz^{n-1}}\left((z-z_0)^nf(z)\right)$$
In our case,
$$\mathrm{Res}(f,0)=\lim_{z\to 0}\frac{d}{dz}\left(\frac{ze^{\pi z}}{z^2+2z+2}\right)=\frac{\pi-1}{2}$$
At $z=-1+i=\sqrt2 e^{3\pi i/4}$ the pole is simple and the residue for a simple pole is given by the following.
$$\mathrm{Res}(f,z_0)=\lim_{z\to z_0}(z-z_0)f(z)$$
In our case, we can use L'Hôpital's rule to find,
$$\mathrm{Res}(f,\sqrt2 e^{3\pi i/4})=\lim_{z\to \sqrt2 e^{3\pi i/4}}\left[\frac{e^{\pi z}(z-\sqrt2 e^{3\pi i/4})}{z^4+2z^3+2z^2}\right]=-\frac{1}{4e^{\pi}}$$
At $z=-1-i=\sqrt2 e^{5\pi i/4}$ the pole is simple as well.
$$\mathrm{Res}(f,\sqrt2 e^{5\pi i/4})=\lim_{z\to \sqrt2 e^{5\pi i/4}}\left[\frac{e^{\pi z}(z-\sqrt2 e^{5\pi i/4})}{z^4+2z^3+2z^2}\right]=-\frac{1}{4e^{\pi}}$$
Thus we have,
$$\begin{align*}
\int_\gamma \frac{e^{\pi z}}{z^4+2z^3+2z^2}\ dz &= 2\pi i \left(\mathrm{Res}(f,0)+\mathrm{Res}(f,-1+i)+\mathrm{Res}(f,-1-i)\right)\\
&=2\pi i \left(\frac{\pi - 1}{2}-\frac{1}{4e^{\pi}}-\frac{1}{4e^\pi}\right) \\
&=\pi i \left(\pi - e^{-\pi} - 1 \right).
\end{align*}$$


Android daily notifications not working properly

Question: I wanted to make daily automatically notification on saved by my time.
I've got in main activity onCreate:
Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 35);
    calendar.set(Calendar.SECOND, 0);
    Intent intent1 = new Intent(ActivitySplashScreen.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(ActivitySplashScreen.this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) ActivitySplashScreen.this.getSystemService(ActivitySplashScreen.this.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

And my AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Intent notificationIntent = new Intent(context, ActivitySplashScreen.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.ic_invite_friends)
                .setContentTitle("Yeah!")
                .setContentText("Do not forget to earn zeni!")
                .setSound(alarmSound)
                .setAutoCancel(true).setWhen(when)
                .setContentIntent(pendingIntent)
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
        notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), mNotifyBuilder.build());

    }

}

The problem is, that this is showing everytime on app is creating and only in that day when the user open it. When the user not open app in next day it's not showing.
Comment: The code looks fine. I tried it with a shorter span (5 minute gap between 2 alarm instances) and it seems to work even when the App is not running and the device is in sleep mode.  This is from Android doc - _Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact._    In short it's totally upto OS to decide.
Comment: One another thing with longer duration is that you have to consider the possibility that the user might have restarted the phone in that interval. Not all alarms survive device restarts (please read upon the Android behaviour on this).  See this Q&A on stack - [link](http://stackoverflow.com/questions/12034357/does-alarm-manager-persist-even-after-reboot)  . In such case as soon as user launches your app after a reboot,  the alarm is scheduled and if it is already past the time of the day (as mentioned in your alarm creation) , the alarm would trigger immediately
Answer:   Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 1);
            cal.set(Calendar.MINUTE, 00);

            Calendar cur_cal = new GregorianCalendar();
            cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

            Calendar cal = new GregorianCalendar();
            cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
            cal.set(Calendar.HOUR_OF_DAY, 00);
            cal.set(Calendar.MINUTE, 02);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE) + 1);
            cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));

            //Create a new PendingIntent and add it to the AlarmManager
            Intent intent = new Intent(getContext(), YourCustomBroadcast.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(),
                    12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            AlarmManager am =
                    (AlarmManager) getContext().getSystemService(Activity.ALARM_SERVICE);
            am.cancel(pendingIntent);
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

try using this code, provide your exact time of daily notification in Calendar instance
create your own custom Broadcast class, like this
public class YourCustomBroadcast extends BroadcastReceiver {
private final String SOMEACTION = "packagename.ACTION";
public static int notId = 1;

@Override
public void onReceive(Context context, Intent intent) {

    Log.d("inside broadcast", "onReceive: ");

    //Toast.makeText(context, "call again", Toast.LENGTH_SHORT).show();

    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(System.currentTimeMillis());

    NotificationCompat.Builder mBuilder =
            (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                    .setSmallIcon(android.R.drawable.sym_def_app_icon)
                    .setContentTitle("Day changed")
                    .setContentText("" + c.getTime().toString());

    NotificationManager mNotificationManager =

            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(++notId, mBuilder.build());

}

}


SwiftUI sheet closure capture list syntax

Question: How would I add capture list to a SwiftUI .sheet(content: ) closure?
I have a sheet in SwiftUI and in the content: closure I check the value of an optional to determine which view to show. The first time it is run the value is alway nil even if I've set it beforehand. I submitted a bug report and Apple says if I reference the variable in the closure's capture list then it will work as expected. I'm new to SwiftUI and haven't been able to figure out the proper syntax for doing so. What is the syntax?
struct ContentView: View {

   @State var presentButtonTwoDetail: Bool = false

   @State var seletedIndex: Int? = nil

   var body: some View {
            Text("Hello")
            .sheet(isPresented: $presentButtonTwoDetail) {
                selectedIndex = nil
            } content: {
                {
                    [selectedIndex] // This syntax won't compile
                    () -> View in
                    if let theIndex = selectedIndex {
                        DetailView(selectedIndex: theIndex)
                    } else {
                        // This gets called on the first run only even when the `selectedIndex` is not nil.
                        DetailView(selectedIndex: 0)
                    }
                }
            }
    }
}

Answer: This compiles.
struct ContentView: View {

    @State var presentButtonTwoDetail: Bool = false

    @State var selectedIndex: Int? = nil

    var body: some View {
        Text("Hello")
            .sheet(isPresented: $presentButtonTwoDetail) {
                selectedIndex = nil
            } content: { [selectedIndex] in
                if let theIndex = selectedIndex {
                    DetailView(selectedIndex: theIndex)
                } else {
                    DetailView(selectedIndex: 0)
                }
            }
    }
}

Comment: Thanks! I was pretty sure I'd tried that variation in the 10 options I'd tried, but sure enough it worked!


AttributeError: 'NoneType' object has no attribute 'format' with Python Format funtion

Question: I am trying to use the Python format function with the following but I keep on getting the error:
AttributeError: 'NoneType' object has no attribute 'format'

df_data.to_csv(r"/dbfs/mnt/pdf-recognized/FinalInvestmentReport/{}.txt", index=False).format("test")

Any thoughts on why I'm getting the error?
Answer: Try this.
df_data.to_csv(r"/dbfs/mnt/pdf-recognized/FinalInvestmentReport/{}.txt".format("test"), index=False)

Error
df_data.to_csv(...) # Returns None And You try to implement format on this like

df_data.to_csv(...).format('test')

Comment: this worked, thank you Sharim ```df_data.to_csv(r"/dbfs/mnt/pdf-recognized/FinalInvestmentReport/{}.txt".format("test"), index=False)```
Answer: Let's take a look at your code together and you will be able to spot the problem easily.
df_data.to_csv(r"/dbfs/mnt/pdf-recognized/FinalInvestmentReport/{}.txt", index=False).format("test")

The above code means that your code is trying to transform df_data - a dataframe to CSV, while the to_csv takes two arguments.
The first argument is the path, you are trying to format the path dynamically, but the format() method should directly follow the string that you try to format, otherwise you are telling the .format method to operate on the return value of to_csv(), which is None, now we can see the problem.
You could refer to the documentation of to_csv here,
Then, the correct way of formatting should be
"/dbfs/mnt/pdf-recognized/FinalInvestmentReport/{}.txt".format("test")

or even simpler using Python 3.6+ f-string syntax
f"/dbfs/mnt/pdf-recognized/FinalInvestmentReport/{your_variable}.txt"

Comment: my suggestion is, you should copy-paste the doc text rather than take a screenshot. and it's better to include a link to the doc you are quoting from. fyi i'm not the one who downvoted.


How to scale a 2D vector and keep direction

Question: I want to take any vector in R2 and scale its length to 1 while keeping the original direction (ratio of x component to y). As an example of my goal, let's say I have the vector (1,1), it would become $(\frac{\sqrt{2}}{2}, \frac{\sqrt{2}}{2})$ . The vector (0,5) would become (0,1). You can see how the answer is not so apparent if the original vector is something like (0.98, 2.6). I hope for a function that can solve this for me but the best I've been able to do is convert the vector into an angle and then calculate dimensions using trig and the unit circle. How would you go about this?
Bonus - find a function that can scale a vector to any inputted size while keeping the direction.
As a final note, I do not have access to R, Matlab, etc.
Comment: See [unit vector](https://en.wikipedia.org/wiki/Unit_vector)
Answer: To normalize any vector you simply need to divide each component by its magnitude. In your first example, you changed from $(1,1)$ to $(\frac{\sqrt2}2,\frac{\sqrt2}2)$, or in your second example, from $(0,5)$ to $(0,1)$ but how did you get there? You may not have realized it but essentially you just divided each component by the magnitude.
Given a vector $(a,b)$, the magnitude is:
$$
\sqrt{a^{2} + b^{2}}
$$
Simply divide each component of your vector by this magnitude and your vector will be of length one, a unit vector.
Answer: Thank you K. Rmth. That's what I needed. If anyone else wonders, you simply divide each component of the vector by the length of the vector.
Comment: @JohnMa The third sentence is an answer, no?
Comment: You may always comment on your own questions, regardless of reputation.


Add nested json object item to another json item

Question: I want to add two nested objects in JSON in typescript.
In JSON given below I want to add second JSON's activityLogs item in first JSON's activityLogs.
JSON1:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
    [{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:38:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]

JSON2:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
    [{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
    {"gpsdate":"01/03/2019","gpstime":"13:43:18"}]
}]

Result:
[{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
    [{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
    {"gpsdate":"01/03/2019","gpstime":"13:43:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:40:18"},
    {"gpsdate":"01/03/2019","gpstime":"13:38:18"},
    {"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]

How I can do this?
Comment: Possible duplicate of [Native way to merge objects in Javascript](https://stackoverflow.com/questions/4740806/native-way-to-merge-objects-in-javascript)
Comment: try to use `concat` with specific condition ,if not you can use lodash use merge.a[0].activityLogs = a[0].activityLogs.concat(b[0].activityLogs)
Answer: You can use push() with the spread operator or concat and reassign:

var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]
var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]

JSON1[0].activityLogs.push(...JSON2[0].activityLogs)

console.log(JSON1)

This assumes that your json arrays contain just the one top-level object. If that's not the case you need to add more details about how the two arrays are synchronized (for example will vehicleno be the same in both?).
As an example, if the vehicleno is a unique identifier in both arrays you could create a lookup of the JSON1 values and the use that to push into the appropriate arrays. This will update JSON1 in place even if it contains multiple vehicles:

var JSON1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}]
var JSON2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]

let lookup = JSON1.reduce((lookup, obj) => {
  lookup[obj.vehicleno] = obj
  return lookup
}, {})

JSON2.forEach(obj => lookup[obj.vehicleno].activityLogs.push(...obj.activityLogs))
console.log(JSON1)
Comment: Hi @Mark, I used unshift instead of push and it is adding on first index. It solve my problem
Comment: Thanks @Mark, this is working for me. But it is pushing data in bottom but I want this in top.
Answer: You can use concatination array method.
let json1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:40:18"},{"gpsdate":"01/03/2019","gpstime":"13:38:18"},{"gpsdate":"01/03/2019","gpstime":"13:37:18"}]}];

let json2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":[{"gpsdate":"01/03/2019","gpstime":"13:46:18"},{"gpsdate":"01/03/2019","gpstime":"13:43:18"}]}]

let result = json1[0].activityLogs.concat(json2[0].activityLogs);

console.log(result);

Comment: @bear-nithi Its concat but removed the vehicleno and device_code.
Answer: The simplest way is to concat the activityLogs:

var arr1 = [{
  "vehicleno": "SV028",
  "devicE_CODE": "8505",
  "activityLogs": [{
      "gpsdate": "01/03/2019",
      "gpstime": "13:40:18"
    },
    {
      "gpsdate": "01/03/2019",
      "gpstime": "13:38:18"
    },
    {
      "gpsdate": "01/03/2019",
      "gpstime": "13:37:18"
    }
  ]
}];
var arr2 = [{
  "vehicleno": "SV028",
  "devicE_CODE": "8505",
  "activityLogs": [{
      "gpsdate": "01/03/2019",
      "gpstime": "13:46:18"
    },
    {
      "gpsdate": "01/03/2019",
      "gpstime": "13:43:18"
    }
  ]
}];
var arr3 = arr1[0].activityLogs.concat(arr2[0].activityLogs);
console.log(arr3);
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}

Note this will only work if you only have one object in the top-level array.
Comment: Its concat but removed the vehicleno and device_code
Answer: result = json1;
/// result = Object.assign({}, json1); if you don't want to mutate the original json1
result.forEach(elem1 => elem1.activityLogs
    .concat(json2.find(elem2 => elem2.vehicleno === elem1.vehicleno).activityLogs));

Concat the activityLogs of the second array item to the first array item by finding the matching element by vehicleno..
Answer: var json1 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
    [{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:38:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
},{"vehicleno":"SV02","devicE_CODE":"8505","activityLogs":
    [{"gpsdate":"01/03/2019","gpstime":"13:40:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:38:18"},
     {"gpsdate":"01/03/2019","gpstime":"13:37:18"}]
}]

var json2 = [{"vehicleno":"SV028","devicE_CODE":"8505","activityLogs":
    [{"gpsdate":"01/03/2019","gpstime":"13:46:18"},
    {"gpsdate":"01/03/2019","gpstime":"13:43:18"}]
}];

var jsonCont = json1.concat(json2);

var result = Object.values(jsonCont.reduce((acc, o)=>{
    if(!acc.hasOwnProperty(o['vehicleno'])) {
        acc[o['vehicleno']] = Object.assign({}, o);
    } else {
        acc[o['vehicleno']]['activityLogs'] = acc[o['vehicleno']]['activityLogs'].concat(o['activityLogs']);
    }
    return acc;
}, {}));

console.log(result);


Como substituir o valor de uma propriedade em um objeto utilizando spread?

Question: Eu estou com uma dúvida em um exercício desde ontem e não consigo achar nada na net. O problema é o seguinte: eu preciso alterar o valor da propriedade CIDADE e colocar outro nome nela, porém quando eu tento alterar, ele reescreve o campo de endereço deixando apenas o valor que tentei alterar.
Código abaixo para contextualizar:
const usuario = { nome: "Rafael", idade: 17,
   endereco: { cidade: "Guatapará", uf: "SP", pais: "Brasil" }
};

const usuario2 = { ...usuario, endereco: { cidade: "Ribeirão Preto" } };

O que eu espero obter é o seguinte:
{ nome: 'Rafael', idade: 19, endereco: { cidade: "Ribeirão Preto", uf: "SP", pais: "Brasil" }}

Mas o que recebo é:
{ nome: 'Rafael', idade: 19, endereco: { cidade: 'Ribeirão' }}

Como podem ver, dentro da propriedade de endereço só ficou a cidade. Como posso corrigir isso?
Answer: O que está acontecendo:
Quando você utiliza o spread no objeto, você recebe um novo objeto com as mesmas propriedades e valores, {...usuario} retornaria o mesmo valor.
Ao usar o uma segunda propriedade, você está adicionando ou substituindo. endereco: { cidade: "Ribeirão Preto" } substitui a propriedade endereco com o objeto { cidade: "Ribeirão Preto" }, e é isso que você recebe.
Alternativa:
Se o seu exercício exige que você resolva através de spread, uma solução é fazer com que o endereço também seja uma "cópia" do endereço original:
const usuario2 = { ...usuario, endereco: { ...usuario.endereco, cidade: "Ribeirão Preto" } }


How to get an object out of list of objects based on specific value? C#

Question: How can I get the object from a list of objects based on price? In the below example, I have a list of pharmacy where I am trying to compare price among pharmacies and pick one with the best price.
i.e. for "NyQuil", CVS is giving me lower price, so I want to pick that. How can I do that?
I am okay with LINQ or for..loop
CODE
    public InventoryItem(string drug, decimal cost) {
      this.Drug = drug;
      this.Cost = cost;
    }

    public class Pharmacy {
        public string Name {get; set; }
        public List<InventoryItem> Inventory {get; set; }
        public decimal? EstimatedOrderItemCost { get; set; }

        public Pharmacy(string name, List<InventoryItem> inventories, decimal? estimatedOrderItemCost = null) {
            this.Name = name;
            this.Inventory = inventories;
            this.EstimatedOrderItemCost = estimatedOrderItemCost;
        }
    }

var pharmacyList = new List<Pharmacy> {
            cvsPharmacy, walgreensPharmacy
        };

// Option-1;:
// This gives me cost and drug name only, index[2] results from screen shot
 var test = pharmacyList.Select(x => x.Inventory.Where(y => y.Drug.ToLower() == item.Drug.ToLower()));

// Option-2:
// This gives me ""At least one object must implement IComparable." message but no error.
var test = pharmacyList.Select(x => x.Inventory.Min()).Where(y => y.Drug.ToLower() == item.Drug.ToLower());

INPUT
Comment: `x.Inventory.Min()` This is a problem. Linq has no way to understand how to interate "Give me the minimum inventory" because the "minimum of a set of inventories" is not a well defined concept. How is one inventory less then or greater then another? If the answer is Cost, then you need to tell it that either with one of the overloads to `.Min` that accepts a function to select the bit you want to use for the comparison, or for the type to implement `IComparable` so that it can use that as the basis for the comparisons.
Answer:
How can I get the object from a list of objects based on price?

With LINQ we can use the .Where() method to construct an IEnumerable object that is filled by iterating every element of a collection and running some provided function on each element, if the function returns true then the element is added to the result, if it's false it's ignored.
With that we can 'search', if you will, a list.
Let's find all the pharmacies that contain the drug we're looking for
// define an easier to read function that will tell is if an inventory has a drug
bool ContainsDrug(string DrugName, IEnumerable<InventoryItem> Inventory)
{
    foreach(var item in Inventory)
    {
        if(item.ToUpper().Equals(DrugName))
        {
             return true;
        }
    }
    return false;
}

// get a enumerable that tells us which pharmacies have the drug
var pharmaciesContainingNyQuil = pharmacyList.Where(pharmacy => ContainsDrug("NyQuil", pharmacy.Inventory));

Now that we have all the pharmacies that contain the  drug we should sort them by the price of that drug.
For that we will need to use 2 different LINQ commands.
The .Select() command iterates over the enumerable and creates a NEW enumerable with a NEW type based on whatever you return from the function you give the method.
For example to convert a int[] to a string[] we can use the select command.
It will iterate through the int[] and run the function string UnamedLamda(int num) return num.ToString(); on each element and build 'a new enumerable' that only contains strings.
var strings = new int[]{1,2,3,4}.Select( num => num.ToString());

// outputs
strings = {"1","2","3","4"}

We can use that to convert all the pharmacies into an enumerable object that are a bit easier to sort.
To sort we can use the .Sort() System.Collections.Generic command. It's actually fairly simple. We provide .Sort() with a lambda expression just like .Where() and .Select() but this time we give it two parameters left and right(they don't have to be named that way). System.Collections.Generic then iterates through the enumerable and compares each left with each right and sorts them that way.
For example, if we wanted to sort a list of strings by the length of the strings we could use:
List<string> strs = {"1","two", "three", "four"};

// sort the list
strs.Sort((left,right) => left.Length.CompareTo(right.Length));

// this returns
{"1","two","four", "three"}

If we use these two commands we can make a new enumerable that is super easy to sort
decimal FindPrice(string Drug, IEnumerable<InventoryItem> Inventory)
{
    foreach(var item in Inventory)
    {
         if(item.ToUpper().Equals(Drug))
         {
             return item.Cost;
         }
    }
}

var pharmaciesInEasyToSortTuples = pharmaciesContainingNyQuil.Select(pharmacy => (pharmacy, FindPrice("NyQuil",pharmacy.Inventory)));

// sort the pharmacies

var sortedPharmacies = pharmaciesInEasyToSortTuples.ToArray().Sort((left,right)=>left.item2.CompareTo(right.item2));

// return the lowest price
return sortedPharmacies?.FirstOrDefault().pharmacy ?? default;

Now if we put it all together we can get a final method that does what you want it to do, it could look something like this:
Pharmacy FindDrugAtPharmacyWithLowestPrice(string Drug, IEnumerable<Pharmacy> Pharmacies)
{
    // we should check every pharmacy
    // we should check if the pharmacy has the drug
    // after we have all the pharmacies that contain the drug, sort them by price and grab the lowest one,

    // get the pharmacies that have the drug
    string name = Drug.ToUpper();

    // Pharmacies.Where -> looks through the pharmacies
    // pharmacy => pharmacy.Inventory.Select(x => x.Drug.ToUpper()) -> creates a List<string>(not really) that we can check to see if it contains the drug
    var pharmaciesContainingTheDrug =
        // search the pharmacies
        Pharmacies.Where(
            pharmacy =>
                // convert the inventory to a list of strings
                pharmacy.Inventory.Select(x => x.Drug.ToUpper())
                    // check the inventory for the drug
                    .Contains(name));

    if (pharmaciesContainingTheDrug?.Count() is null or 0)
    {
        // no pharmacies containing drug
        return default;
    }

    // now we have a enumerable that has all the pharmacies that contain the drug
    // sort by the lowest price
    // first convert to a more usable format so we can sort

    decimal GetPriceInList(string Drug, IEnumerable<InventoryItem> Inventory)
    {
        return Inventory.Where(x => x.Drug.ToUpper() == Drug)?.FirstOrDefault()?.Cost ?? default;
    }

    var sortedPharmacies = pharmaciesContainingTheDrug.Select(pharmacy => (pharmacy, GetPriceInList(name, pharmacy.Inventory)));

    // don't bother continuing if for some reason we couldn't construct the enumerable tuples
    if (sortedPharmacies?.Count() is null or 0)
    {
        return default;
    }

    // actually sort the pharmacies
    sortedPharmacies.ToList().Sort((left, right) => left.Item2.CompareTo(right.Item2));

    return sortedPharmacies?.FirstOrDefault().pharmacy ?? default;
}


Improve the time series model in python

Question: I have the below data. This is data from 2019, where missing dates are '0'
DATE,value
01/04/2019,2
31/05/2019,1
04/07/2019,2
18/05/2020,1
05/06/2020,1
17/09/2020,1
06/10/2020,3
21/10/2020,42
26/10/2020,1
30/11/2020,1
02/12/2020,2
03/12/2020,1
12/12/2020,3
14/12/2020,1
15/12/2020,2
17/12/2020,1
24/12/2020,1
05/01/2021,1
13/01/2021,1
04/02/2021,2
18/02/2021,1
10/03/2021,1
01/04/2021,1
09/04/2021,1
25/04/2021,1
18/05/2021,1
19/05/2021,1
07/06/2021,1
30/06/2021,1
09/07/2021,1
15/07/2021,1
26/07/2021,1
27/07/2021,1
29/07/2021,2
06/08/2021,1
16/08/2021,1
17/08/2021,2
23/08/2021,1
24/08/2021,1
25/08/2021,1
28/09/2021,2
21/10/2021,1
15/02/2022,1
24/02/2022,2
18/03/2022,1
31/05/2022,1

I am trying to do forecasting for next two years. i tried ARIMA,AUTO ARIMA, holtsmethod and holts winter to do the forecast and non of them give satisfactory result.
I tried cumulating the value and then do the forecast, then the models will give a trend but without any patterns. How can I do forecast on such data?
Any suggestions are welcome
Answer: First, your data seems to be count data, so rather than auto arima, you should use e.g. tscount. Second, you have huge gaps of missing data, which makes it unlikely that any time series model will succeed in obtaining some pattern. Third, if you nevertheless want to try it, you should not impute the missing data with 0 but rather with a count near the average.
It would of course be helpful to get more information about your data, but without that, I would first try proper imputation, aggregate the imputed data monthly, and then apply a time series model to this monthly time series, probably with seasonality.
Comment: what are your thoughts on of cumulating the data and then use forecast.. example: if original values are 1,0,0,1,1,1 .. after cumulating: 1,1,1,2,3,4 etc and then do forecasting?
Comment: That is what I meant by "aggregate and then apply a time series model". But you should impute before the aggregation.

Improve the time series model in python


How to create predictive model using Naive Bayes in Python?

Question: It's my first time using python and I have created a basic csv file. I want to know how would you create a predictive model using Naive Bayes to classify if the words are informative or uninformative ?
Answer: Python has a very extensive machine learning library scikit-learn.
As you are new to AI with python, you should consider learning from the basics. If you have already, DataCamp's Naive Bayes guide would be a good resource you can follow to achieve the classification model you want.


Group a StaticText with a TextCtrl in wxPython

Question: I want to build a UI for editing ID3v2 tags of mp3 files. I need a list of StaticText - TextCtrl for editing different tags. Instead of creating StaticText and TextCtrl separately I would like to write a widget that combines them both.
I want it to look sth like this:

My first idea was to extend a BoxSizer and prepopulate it with a StaticText and a TextCtrl
import wx

class LabelTextSizer(wx.BoxSizer):
    def __init__(self, label):
        super().__init__(wx.HORIZONTAL)

        self.label = wx.StaticText(self, label=label)
        self.text = wx.TextCtrl(self)

        self.Add(self.label)
        self.Add(self.text)

but it does not seam to work like i expect it to:
Traceback (most recent call last):
  File "D:\Tron\repo\rex-song-tagger\main.py", line 58, in <module>
    frm = HelloFrame(None, title='Hello World 2')
  File "D:\Tron\repo\rex-song-tagger\main.py", line 25, in __init__
    sizer = LabelTextSizer('Title')
  File "D:\Tron\repo\rex-song-tagger\LabelTextSizer.py", line 25, in __init__
    self.label = wx.StaticText(self, label=label)
TypeError: StaticText(): arguments did not match any overloaded call:
  overload 1: too many arguments
  overload 2: argument 1 has unexpected type 'LabelTextSizer'

Process finished with exit code 1

How would you do it the wx-way?
Comment: You want a widget not a sizer. `wx.ListBox` could be a contender.
Answer: You have used the LabelTextSizer (a sizer) as the parent of the StaticText and TextCtrl widgets, but this must be a wx.window (e.g your frame or panel), see wxPython docs
This works:
import wx

class MainFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(None, *args, **kwargs)

        self.panel = MainPanel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.panel)
        self.SetSizer(sizer)
        self.Show()

class MainPanel(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        labeltext_1 = LabelTextSizer(self, 'Title', size=(300, -1), style=wx.TE_PROCESS_TAB)
        labeltext_2 = LabelTextSizer(self, 'Artist', size=(300, -1), style=wx.TE_PROCESS_TAB)
        labeltext_3 = LabelTextSizer(self, 'Track', size=(300, -1), style=wx.TE_PROCESS_TAB)
        labeltext_1.text.SetHint("TIT2 ...")
        labeltext_2.text.SetHint("TPE2 ...")
        labeltext_3.text.SetHint("TRCK ...")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(labeltext_1, 0, wx.ALL, 10)
        sizer.Add(labeltext_2, 0, wx.ALL, 10)
        sizer.Add(labeltext_3, 0, wx.ALL, 10)
        self.SetSizer(sizer)

class LabelTextSizer(wx.BoxSizer):
    def __init__(self, parent, label, size=wx.DefaultSize, style=0):
        super().__init__(wx.VERTICAL)

        self.label = wx.StaticText(parent, label=label)
        self.text = wx.TextCtrl(parent, size=size)

        self.Add(self.label)
        self.Add(self.text)

if __name__ == '__main__':
        wx_app = wx.App()
        MainFrame()
        wx_app.MainLoop()

Comment: I hope you don't mind, I adjusted the code a bit. Let me know if it's a problem and I'll revert the code back to your original.


Unable to print directly from Server 2008 R2

Question: I have searched to see if this has been asked before but it doesn't look as though it has.
I have been asked to take a look at a server printing issue which to be honest is a little beyond me at the moment.
The printer is a HP M177fw, it is attached to a Netgear Prosafe 1gb switch and everyone on the network can print except for the server which is Server 2008 R2.
The printer is installed and detected. I can ping the printer IP address, I can view the web interface and print a test page from there, however when I print from any other means I can see the item appear in the queue and disappear almost instantly with no print to be seen.
The user account (administrator) trying to print has full access to the server, the printer driver has 'everyone' set to allow access to everything just to rule out permissions.
I am now beginning to wonder if some other security settings have been put in place to stop printing but i'm afraid I don't know where to begin.
I have applied a Microsoft Fixit designed to fix issues with the spooler service, the spooler service has been stopped and restarted, I have even created another user account to see if there was an issue with the user account itself.
Any and all help would be greatfully received.
Kindest regards
tmd
Added note: drivers have been updated but I am unable to update firmware with an error stating the printer is not attached even though I can ping and view the web interface. This printer has also been replaced by my colleague with no difference.
The printer has been installed using the GUI, and also after removing the printer for a reinstall by IP and searching for the driver only package.
Added note: The printer drivers have been uninstalled via the Control Panel and I have also deleted all ghosted entries as per instructions below. The printer has been installed via the GUI with basic drivers only and the software package does detect and install the printer, however printing still fails.
SFC /SCANNOW has been run 100% all ok with no violations or errors.
Following instructions below I was able to find that there were errors with permissions over the 'printers' folder where 'Local Host' wasn't allowed to do anything.
Thank you all for the assist!
Comment: `I can view the console and print a test page directly from the console` - What do you mean by that? What console are you referring to? Do you mean the web interface of the printer?
Comment: you're quite correct, it is the web interface for the printer. Thank you.
Answer: You may need to reinstall the print drivers. You can download and install them from here:
http://support.hp.com/us-en/product/HP-Color-LaserJet-Pro-M170-Multifunction-Printer-series/5303438/model/5303443/drivers.
Completely uninstall the drivers and delete the disconnected device by using the devmgr_show_nonpresent_devices 1 environmental variable. Then reinstall the print drivers.
Another possibility is that the OS is corrupted. run SFC /scannow at the command line to check for system issues.
I would also recommend updating the Firmware also as this reduces installation issues.
Make sure that you get the basic drivers as the full driver comes with tons of bloat and other junk.
Don't forget to select your OS as Server 2008 R2 so that you get compatible drivers...
Hopefully this helps!
Comment: @CraigSunderland That sounds right, What is located in that section?
Comment: Bah, no notification that I had a response. apologies Elliot. In my previous reply I wrote exactly what was there. Unfortunately there is nothing else other than that?!
Comment: The latest drivers have been downloaded and installed however I am unable to run the firmware update. Each attempt there informs me that the printer is not attached even though it is.

I've never used the devmgr_show_nonpresent_devices environment variable, would you be kind enough to explain how this is used in this scenario?
Comment: Did you remove the drivers as I instructed?
Comment: Also, is there a GUI installed or is this a core installation?
Comment: This printer has been added to the server by both full GUI install and by adding the printer by IP and searching for the driver from a driver only package.
Comment: ok, uninstall the drivers using the above method.
Comment: I do not know how to use the environment variable mentioned, can you explain?
Comment: Yah, Go into `system properties` and go to the `advanced` tab. Once there click on `environmental variables` and create a new system variable. Copy the `devmgr` part to the top and the `1` on the bottom. Next push ok . After you have done that open the device manager and click on the `view menu`. Push `show hidden devices` and delete all of the devices that look like "ghosts" (faded). Reboot the server and install the BASIC drivers.

I would not recommend deleting any faded devices in the system devices section.
Comment: Thank you, I have deleted all ghosts from the device management page that where ghosted except for those that were in system devices. For your information, there was only one in the UMBus area.

The server is rebooting now having already unstalled the device via the control panel.
Comment: K, thx for the info! Crud, I forgot to mention to uninstall the HP driver from the programs and features before you did that. After uninstalling the device from the programs and feature control panel check back to see if any new devices are "ghosted". If not then install the **BASIC** device drivers from HP using the GUI version and not the `inf` version. (the `inf` version are used for direct command line additions. Lets stick to the GUI.)
Comment: Make sure to add the device as a network printer if prompted by the installer. If it does not prompt then go to the control panel and add a printer via the `devices and printers` applet by pushing the `add printer` button and selecting the printer from the network scan. After it has added the device print a test page (type test in the document and press print) from `notepad` or some other text editor, to see if it is configured properly.
Comment: Oh, on the plus side the server will now operate faster, as it is now no longer loading drivers for non present devices.
Comment: OK, I have downloaded basic drivers only and installed via the GUI. I have opted for network mode as I had done with the full package, specified the IP address, seen that the software has detected the printer and completed installation. I am asked by the GUI if I would like to set the printer as default which I have done and sent a test print to the printer using the GUI.

I can confirm that I can still print a test page via the web interface but cannot print from any other software.

I can also confirm that running the firmware update fails
Comment: Awesome! Did it print? I would have thought that it would have scanned for the printer (which is better than entering the IP as it tracks it instead of having a static IP) but you have a different printer than I do so the setup process may be slightly different than mine...
Comment: To update the firmware you might have to be connected via USB.
Comment: I've been retesting the print and can confirm that the print has a status of 'spooling' before dissappearing.
Comment: crud, did you run the sfc command to see if there are errors with the system?
Comment: Yes, 100% with no violations or such.
Comment: Can you tell me what features are enabled in the features section under `Print and Document Services`?
Comment: Unfortunately on servers my knowledge is limited. Where would I find this information?

I have seen this the right hand pane when highlighting that section.

The document Untitled - Notepad, owned by administrator, failed to print on printer HP Color LaserJet Pro MFP M177 PCLmS. Try to print the document again, or restart the print spooler.
Data type: RAW. Size of the spool file in bytes: 19301. Number of bytes printed: 0. Total number of pages in the document: 1. Number of pages printed: 0. Client computer: \\USER_1. Win32 error code returned by the print processor: 5. Access is denied.
Comment: in the server manager under add roles and features go to the features part of it.
Comment: What solved the issue? (for my future reference, Some of my clients have had issues like this in the past where I had to reload the OS)
Comment: I have updated the post and have asked my colleague to let me know if the print actually came out of the printer (i'm doing this remotely)
Comment: Thanks for the update. Did you ever get the installed Windows features list? That would be helpful as there might be a feature that is needed that is disabled...
Comment: There isnt a features list in the print roles section :/
Comment: There is a box underneath Print Services which has 4 entries. 2 of those are installed being Print Server and LDP Service
Comment: @CraigSunderland The section I am talking about is not going to be in roles. It will be in features which is located in the add roles and features wizard. Can you tell me what features are installed for `print and document services`?
Comment: I have found a section in Server Manager underneath Roles aptly named 'Features'. In this section there is a 'feature' named 'Print and Services Tools'. This is all that is named under this header. Is this the correct one?
Answer: After changing the permissions to allow 'Local Host' full access, instead of seeing documents with a status of 'spooling' and dissappearing from the print queue, there are '*.tmp' files now appearing in the 'printers' folder.
My colleague has now confirmed that since altering the permissions of the 'printers' folder, prints have been flying out.
Comment: Great to hear! What do you mean `folder prints`?
Comment: Edited my comment to make more sense.


Writing characteristic chord progressions in inversion, & doubling notes other than the root

Question: There are characteristic chord progressions taught in music theory, for example, the cadential 6-4, which is Ic - V - I. Then there's Ib - ii7b - V - I, & so on. I want to know if these cadences have to be written as is, or they can be modified by writing one or more chords in them in an inversion?
Also, from a previous question asked by me (double the third or the fifth of a chord), I learnt that notes other than the root are also doubled. I want to know if this is ok to do in the cadences I mentioned above (& other examples of such characteristic cadences). For example, is it ok to double the third instead of the root in chord Ib of the Ib - ii7b - V - I progression?
Comment: Are you using "a, b, c" to denote inversions? Because the "b" is easily confused with "♭"...
Comment: Without any context, it's ok to do anything you want to do. Are you trying to ask what is or was a popular practice for some particular style of composition? If so, what style?
Comment: I don't know how this good question went unnoticed for so long, but I'm glad it popped up to the home page today!
Comment: @user45266 Yes, the "b, c..." was to denote inversions.
Comment: @ToddWilcox Yes I would like to know it especially for harmonising a chorale in the style of Bach, & harmonising hymns. Also, would the practice change depending on the style of music you want to write for?
Answer:
...or they can be modified by writing one or more chords in them in an inversion?

In a nutshell, no.
You can't arbitrarily change a progression to any inversion.
In the case of a cadential 6/4 chord the whole point is the dominant in the bass. Inverting those chords changes the bass and the whole harmonic identity of the progression.
Similarly you couldn't take any progression and then arbitrarily invert it such that lots of second inversion chords are formed. Second inversion gets special handling that wouldn't be a concern with other inversions.
On a certain level you can say some progressions are roughly the same regardless of inversion. You could say generically I IV is the same as I6 IV. Certainly the root movements are the same. But I think you shouldn't indiscriminately treat them as the same. With I IV both chords in root position treats them as sort of equal in terms of stability. It has an evenness. But the inversion in I6 IV sets up a more dynamic progression. With the bass half step motion of MI to FA - analogous to a leading tone to tonic motion - makes IV more of a goal. The two chords are uneven in this sense. Various inversion are not total equal, not the same harmonically.
Regarding doubling of tones in inverted chords I like Walter Piston's rule of thumb: double the tonal degrees for inverted chords. The tonal degrees are ^1 the tonic, ^4 the subdominant, and ^5 the dominant.
Can you deviate from the various norms and rules? Yes. It's art. There is always artistic license. But it depend how closely you want to hew to a particular style. In common practice style harmony is pretty circumscribed so don't deviate too much if you want to get that period sound.
In regard to cadences it's best to stick to their formulas. That's part of the point. The clear formulas signal ending types. When a V I6 cadence is called imperfect and described as an incomplete closing, it's the inversion that makes it incomplete. This makes a good phrase ending to push into a new phrase. Changing the inversion type would then miss the whole point of how phrases are structured by cadence qualities.
Comment: My mom gave me some advice (similar to Piston's) that seems to work well. Avoid doubling the third of major chords; favor doubling the third of minor chords. I later noticed that doubling the third of major chords often gives the impression of a Neapolitan Sixth (in CPP style).
Comment: @ttw, some food for thought: are the minor chords in a major or minor key? Notice that in major the minor chords `ii iii vi` have their thirds on scale degrees `^4 ^5 ^1` respectively. I wonder if the case is two differently worded rules that have the same result.
Comment: Minor chords in minor too. Doubling the third in a minor key is acoustically (not necessarily musically) doubling the roots of the relative major.
Answer: In Western classical music theory classes, progression writing is typically focused on the voice-leading principles of Tonality, in the context of four-part vocal writing. So cadences, for example, are voiced to preserve the smooth movement of each voice (pitch) to the next. (Jazz and Pop music are looser in this regard, but tend to follow the same principles.)
You can change the voicing/inversion of any chord, but the subsequent chords would also change to preserve the voice leading. Taking your Ib - ii7b - V - I in the key of C Major, a standard arrangement would be:

But let's say you prefer ii7 to ii7b. If you change only that one voicing, you get this:

To get a "correct" solution, you would have to change, at least, the V chord. For example, Ib - ii7b - Vc - I:

It's okay to double any pitch(es) in the chord, but -- again for "correct" voice-leading -- it's best not to double pitches that have strong movement toward another particular pitch in the next chord. For this reason, you should near always avoid doubling a leading tone (e.g., the third of a dominant chord).
For a (vastly) more detailed description, see Steven G Laitz. 2008. The Complete Musician. Oxford University Press.

For anyone unfamiliar with the notation used in the three examples above, it is equivalent to:

I[6] - ii[6-5] - V - I,
I[6] - ii[7] - V - I, and
I[6] - ii[7] - V[6-4] - I.
Answer: The 'Cadential 6/4' just about has to BE a 6/4 :-)  You could divert its resolution to VI or bVI to form an Interrupted cadence rather than a Perfect one.
Your other example, Ib - ii7b - V - I,  is characterised by the bass line walking up to the dominant. It would have much the same feel if IV was substituted for ii7b.  Or, obviously, if V7 substituted for plain V.   And again, it could go interrupted instead of Perfect.
You've quoted a couple of useful musical clichés.  Yes, other things are also good.  But be cautious. Clichés are clichés because they are tried and true, because they WORK.  A Cat may sit on the Mat, so may a Rat. Or a Bat.  But most people go for the cat!
(Nice to see the clear, compact Ic, iib etc. notation for inversions.  Why write 'ii[6-5]' when 'ii7b' does the same job?  We should use it more.)


Formulário ModelForm dinâmico - Django

Question: Olá! Estou utilizando ModelForm do django 2.2, e preciso deixar o formulário dinâmico. O campo "Quantidade de parcelas" só deve aparecer quando o Método de pagamento for crédito.

A princípio tentei fazer com JS:
function exibir_ocultar(){
var valor = $("#id_metodo_de_pagamento").val();

if(valor == 'credito'){
     $("#id_quantidade_de_parcelas").show();

 } else {
     $("#id_quantidade_de_parcelas").hide();
 } };

Me deparei com o problema de não conseguir editar o select para chamar a função JS, já que o próprio Django gera o formulário. Segue o código utilizado para gerar o formulário:
           {% bootstrap_messages %}
            <form action="{% url 'cadastro' %}" method="POST" class="form" autocomplete="off" >
                {% csrf_token %}
                {% bootstrap_form form %}
                {% buttons %}
                    <button type="submit" href="{% url 'index' %}" class= "btn btn-success">Salvar </button>
                    <button type="submit" href="{% url 'index' %}" name="exit" value="True" class= "btn btn-dark">Salvar e fechar </button>
               {% endbuttons %}
            </form>

Qual a melhor forma de realizar essa ação?
Answer: Então rapaziada, pra quem está com a mesma dúvida e não quer depender desses fracassados em sua vida fora de fórumzinho que marcam a pergunta como "nenhum esforço", segue o que utilizei para aplicar essa ideia em meu projeto de estudo (ESTUDO, logo significa que não tenho muita noção de como ou o quê pesquisar e explicar minhas dúvidas, rsrs)
No django existem os widgets, o que torna possível inserir elementos de entrada HTML. Fui até o arquivo "forms.py" do projeto, e dentro da classe Meta, onde é especificado os fields do formulário, conseguimos definir os elementos HTML a partir de um dicionário em python.
from django import forms
from .models import Compra

class CompraModelForm(forms.ModelForm):
class Meta:
    model = Compra
    fields = ['nome_da_compra', 'preco', 'data_da_compra', 'local_da_compra', 'metodo_de_pagamento', 'quantidade_de_parcelas']
    widgets  =  { 'metodo_de_pagamento': forms.Select(attrs = {'onchange' : "exibir_ocultar();"}) }

Após isso, a ideia de exibir e ocultar os campos funciona perfeitamente. Utilizei o script JS dentro da pasta static e importei ele pro meu HTML através da tag script. Abraço!

Formulário ModelForm dinâmico - Django


two-sample Kolmogorov-Smirnov test suggest that sample with the same data generating process from different populations

Question: I have two different samples I need to test if they are drawn from the same population distribution. The two samples are of the volatility of an asset that I simulated. Since the data is simulated I know that both samples have the same data generating process. The only difference between the two samples are the days that I am using from the simulation.
A summary of the two samples is given below. It is also important to note that since this is simulated data the sample size is quite large. I have 249,281 observations in sample 1 and 254,453 in sample 2.
<code>> summary(Sample1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 0.0128  0.0894  0.1194  0.1367  0.1627  0.9925
> summary(Sample2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 0.0141  0.0950  0.1263  0.1467  0.1724  1.1435
</code>
When I apply the Kolmogorov-Smirnov test the results reject the null hypothesis that the two samples are drawn from the same population.
<code>ks.test(Sample1,Sample2)

    Two-sample Kolmogorov-Smirnov test

data:  Sample1 and Sample2
D = 0.053089, p-value < 2.2e-16
alternative hypothesis: two-sided
</code>
However if I plot the kernel approximation of the two different density functions and the CDF both of the samples appear to be from the same distribution. A copy of the plots is given below.

How is it possible that the two samples come from different distributions if they have the same data generating process? Am I missing interpreting the results from the KS test? Is there another test that I should be apply?
Comment: Try the simulation 1000 times. If you set $\alpha=0.05$, you should reject about $5\%$ of the time. If you're much different from that, then perhaps your simulation isn't as correct as you think.
Answer: The KS test is based on the CDF, so it's telling you that the small vertical differences between the two CDFs are much larger than you'd expect in 250,000 independent observations from the same distribution.  The expected differences would be on the order of 0.001, and yours  are more like 0.01.
It sounds  as though your data generating process generates data with slightly different distributions on different days. Or the observations are not independent and the effective sample size is about 1% of the actual sample  size.
Comment: Yes, it is necessary that the observation in each sample are independent of each other.
Comment: Thomas, thank you for your comment. The observations with in each sample are not independent from one another. On any given day the asset price was used to calculate the implied volatility over a one day period, then a two day period, all the way up to a 75 day period. Therefore, all observation on the same day will be correlated with each other. However, since different days where used in each sample I believe the two samples should be independent of one another.  Does this violate the assumptions of the KS test? Is there another test that I should use?


Return value from Word VBA to calling Excel VBA

Question: From within MS Excel I have VBA code which runs VBA code within MS Word.  Everything works fine.  I need to return a string value from Word, back into an Excel variable.  Is this possible?
Some irrelevant background... I'm building a list of pdf files within Excel and need to extract values out of each of those pdf files.  Word natively reads pdf, that's why I'm using it.  I have a perfectly working python script that does it but no-one else in the organisation knows python and my manager isn't comfortable having code that only I understand.  Which is fair enough!
Any hint would be appreciated!
Comment: Please [edit] your question with your code.
Comment: You can use clipboard. Copy in Word macro and then paste in Excel from clipboard
Comment: Clipboard!  Of course!  Doh!  Thanks a million!
Answer: Excel:
Sub RunWord()

    Dim appWd As Object, res

    Set appWd = GetObject(, "Word.Application")

    res = appWd.Run("Tester")

    Debug.Print res

End Sub

Word:
Public Function Tester()
    Tester = "hi!"
End Function


Categorization of continuous predictor in logistic regression

Question: I have one continuous variable GENETIC SCORE and one binary variable HEALTH (case vs control i.e. 0/1). I want to fit a log regression model to this data to get the odds ratio for different percentile categories of GENETIC SCORE variable. One way to do this is to simply use a continuous variable. However I want to get the result in the form of
Percentile (%) -  OR
<1        -      0.30
1-5        -     0.40
5-10        -   0.49
10-20        -   0.59
20-40         -  0.77
40-60         -  1.00
60-80         -  1.29
80-90         -  1.65
90-95         -  2.03
95-99         -  2.52
.>99          -  3.60
Notice the baseline category 40-60 with OR = 1. So, my first guess (after a long research) is that GENETIC SCORE is categorized in 11 percentile groups. I am aware of all disadvantages of binning. But still, I want to get the results in this form.
My main question here is: how do I setup the model with the desired baseline group? In other words; how do I setup the model in the way that OR is 1 for the middle percentile group (either with continuous or with categorized variable).
Comment: This is my goto reference for all this kind of stuff: https://www.springer.com/gp/book/9781441929181 Prof Harrell has a webpage here: https://www.fharrell.com/
Answer: To present the results in that form you do not need to represent the data in that form! Just use the data as is, numerically, and then you can represent the results in that form, as a table.
Comment: Yes, I agree. But still - I am asking how to make a transformation from the log regression output (with cont. variable) to this kind of table?


Create different URL alias based on CCK field

Question: So I have a typical blog entry content type and I've added a CCK checkbox for some extra functionality. I'm using the pathauto module to automatically set the URL alias for the blog entry content type.
What I would like to do is alter the URL alias created depending on the value of the CCK checkbox. If the box is checked, I'd like to change the URL alias. If not, let pathauto do it.
Possible? Can this be done in the template.php file of my theme?
Answer: I'm assuming you're well-versed in the settings that Pathauto gives you (like it's own "automated alias" checkbox, and the settings that change what happens when a node is updated).  I'm assuming those settings don't meet your needs.
This should be possible, but not in the theme layer.  You'll need to write a module, probably a relatively small one.  You'll need to implement hook_nodeapi in D6 or one of the hook_node* family in D7, and maybe hook_pathauto, to make sure the right thing happens.
Drupal 6

hook_pathauto()
hook_nodeapi()

Drupal 7

hook_pathauto()
hook_node_presave()


Android custom file extension intent not working with standard file browser

Question: My app specifies as being able to open my own file extension in the manifest file like this:
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="file"/>
<data android:host="*"/>
<data android:mimeType="*/*"/>
<data android:pathPattern=".*\\.ext" />
<data android:pathPattern=".*\\..*\\.ext" />
<data android:pathPattern=".*\\..*\\..*\\.ext" />
<data android:pathPattern=".*\\..*\\..*\\..*\\.ext" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.ext" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\.ext" />
<data android:pathPattern=".*\\..*\\..*\\..*\\..*\\..*\\..*\\.ext" />

This used to work fine with the standard Android file browser ("My Files") and still works on an older test device running Android 4.3 but doesn't work on my other devices running Android 6 and 8. It also works on the new devices with other file browsers (though not all).
I also tried png and pdf with the corresponding mime types but it won't show my app in the list of apps able to open those files.
What does the standard Android file browser need in order to recognize my app to be able to open files with my extension?
EDIT: I also tried
<data android:scheme="content"/>

Comment: some device will use content mime type instead of file. To fix issue, you have to detect witch intent is launched for resolution. From Android file browser, choose option open with, you will get the log for intent... as this one for pdf file...
2018-11-02 00:46:51.515 1714-8164/system_process I/ActivityManager: START u0 {act=android.intent.action.CHOOSER flg=0x3 cmp=android/com.android.internal.app.ChooserActivity clip={application/pdf U:content://com.android.providers.downloads.documents/document/55} (has extras)} from uid 10012
Comment: Thanks for that but unfortunately, myfiles doesn't give me any log like that. No indication that it tried to call an intent. The only logs that I can see from myfiles are about drawing the activity. I have also tried setting the scheme as content, same result.
Comment: Opening a jpg from My Files gives me this line: W/ResolverActivity: mLaunchedFromPackage = com.sec.android.app.myfiles and I/ActivityManager: START u0 {act=android.intent.action.VIEW typ=image/jpeg flg=0x1 cmp=ComponentInfo{android/com.android.internal.app.ResolverActivity}} from uid  and shows a chooser for two apps capable of opening jpg files. Neither of these logs happen for files with my own extension.
Comment: when you want to open your file, witch application can handle it?
Comment: My own application can handle the files. I want my own application, where the above intent-filter is specified, to open when the file is clicked in "myfiles".
Answer: Try this (change "custom" with the extension you want to use) :
   <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="file"/>
            <data android:mimeType="*/*"/>
            <data android:pathPattern=".*\\.custom"/>

            <data android:pathPattern=".*\\..*\\.custom"/>
            <data android:pathPattern=".*\\..*\\..*\\.custom"/>
            <data android:pathPattern=".*\\..*\\..*\\..*\\.custom"/>
            <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.custom"/>
            <data android:host="*"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="file"/>
            <data android:pathPattern=".*\\.custom"/>
            <data android:pathPattern=".*\\..*\\.custom"/>
            <data android:pathPattern=".*\\..*\\..*\\.custom"/>
            <data android:pathPattern=".*\\..*\\..*\\..*\\.custom"/>
            <data android:pathPattern=".*\\..*\\..*\\..*\\..*\\.custom"/>
            <data android:host="*"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:mimeType="application/vnd.ni.custom" android:scheme="file"/>
        </intent-filter>
    </activity>