text:
Q: Identifying the correlation between a slope and a level Throughout this post, I assume at least second moments exist. Consider a heterogeneous linear treatment effect model of the form:
$$Y_i = \alpha_i + \beta_i X_i$$
where $\alpha_i, \beta_i$ are potentially arbitrarily heterogenous (in other words, we make no restrictions on heterogeneity in the potential outcomes function, but we do restrict it to be linear). Suppose additionally, that $X_i$ is exogenous/comes from an experiment in the sense that
$$X_i \perp \alpha_i, \beta_i$$
Then standard arguments show that $\mathbb E[\alpha_i], \mathbb E[\beta_i]$ are identified by the (population) OLS with $Y_i$ as the outcome and $X_i$ as the covariate. Interestingly enough, we also have that $\mathbb C\mathrm{ov}(\alpha_i, \beta_i)$ is identified under the additional assumption that $X_i$ is symmetrically distributed around its mean. To see why, note that if we define $\tilde X_i = X_i - \mathbb E[X_i]$, we have
$$Y_i^2 \tilde X_i = \alpha_i^2 \tilde X_i + 2\alpha_i \beta_i \tilde X_i^2 + \beta_i^2 X_i^2 \tilde X_i$$
Noting that the first and third term vanish in expectation due to exogeneity and the symmetric distribution of $X_i$, only the third term is left. In particular, we can show that
$$\mathbb C\mathrm{ov}(\alpha_i, \beta_i) = \frac{\mathbb E\left[Y_i^2 \tilde X_i\right]}{2\mathbb E\left[\tilde X_i^2\right]} - \mathbb E[\alpha_i]\mathbb E[\beta_i]$$
where everything above is either directly observed or identified (in particular, the first term on the RHS is half the (population) OLS slope of the regression of $Y_i^2$ on $X_i$). Consider now, the case where I have two outcomes with their own linear-in-treatment potential outcomes:
$$Y_{i,1} = \alpha_{i,1} + \beta_{i,1} X_i$$
$$Y_{i,2} = \alpha_{i,2} + \beta_{i,2} X_i$$
Again, I am assuming that $X_i$ is exogenous in the sense that $X_i \perp \left\{\alpha_{i,j}, \beta_{i,j}\right\}_{j=1}^2$. My question is therefore the following. Can we identify $\mathbb C\mathrm{ov}\left(\alpha_{i,1}, \beta_{i,2}\right)$ in this model without making additional restrictions? The obvious generalization of the above argument does not seem to work here because
$$Y_{i,1} Y_{i,2} \tilde X_i = \alpha_{i,1}\alpha_{i,2} \tilde X_i + \alpha_{i,1}\beta_{i,2} \tilde X_i^2 + \alpha_{i,2}\beta_{i,1} \tilde X_i^2 + \beta_{i,1}\beta_{i,2} X_i^2 \tilde X_i$$
which does not allow us to separate out $\mathbb E\left[\alpha_{i,1}\beta_{i,2} \right]$ and $\mathbb E\left[\alpha_{i,2}\beta_{i,1} \right]$. It seems also that going to higher cross moments involving $Y_{i,1}, Y_{i,2}$ is unlikely to help either, as we end up introducing even more terms that cannot be separately identified. I am wondering if anybody has formally shown that what I am conjecturing here is true.
Edit: By the suggestion in the comments, here is some R code simulating the DGP I have in mind.
set.seed(12351)

# Set up standard normal variables
norm1 <- rnorm(100000)
norm2 <- rnorm(100000)

# Set up covariance matrix between alphas and betas
# Cov(alpha, beta) = 0.05, Var(alphas) = Var(betas) = 0.1
VCV <- matrix(c(0.1, 0.02, 0.02, 0.1), nrow = 2, ncol = 2)

# Draw individual alphas, betas from population where
# E[alphas] = 5, E[betas] = 3, and VCV(alpha, beta) = VCV as above
alphas <- 5 + sapply(1:100000, function(i) (chol(VCV) %*% c(norm1[i], norm2[i]))[1])
betas <- 3 + sapply(1:100000, function(i) (chol(VCV) %*% c(norm1[i], norm2[i]))[2])

# Independently sample Xs
Xs <- 2 * (rbinom(100000, 1, 0.5) - 0.5)

# Define Ys according to individual parameters (alpha, beta) and treatment (X):
Ys <- alphas + betas * Xs

# Run estimators corresponding to the moment equalities from the question
lmod <- lm(Ys ~ Xs)
lmod2 <- lm(Ys^2 ~ Xs)

# Moments for underlying parameters
mean(alphas)
# [1] 4.999713
mean(betas)
# [1] 3.000854
cov(alphas,betas)
# [1] 0.01947037

# As expected, intercept is approximately E[alpha], intercept is
# approximately E[beta], and half the OLS slope of
# Ys^2 ~ Xs minus slope times intercept from Ys ~ X is roughly
# Cov(alphas, betas)
summary(lmod)

# Call:
#   lm(formula = Ys ~ Xs)
#
# Residuals:
#   Min       1Q   Median       3Q      Max
# -2.19008 -0.29728  0.00006  0.29893  2.65507
#
# Coefficients:
#   Estimate Std. Error t value Pr(>|t|)
# (Intercept) 4.998635   0.001414    3536   <2e-16 ***
#   Xs          3.001279   0.001414    2123   <2e-16 ***
#   ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# Residual standard error: 0.447 on 99998 degrees of freedom
# Multiple R-squared:  0.9783,  Adjusted R-squared:  0.9783
# F-statistic: 4.507e+06 on 1 and 99998 DF,  p-value: < 2.2e-16

as.numeric(lmod2$coefficients[2] / 2 - lmod$coefficients[1] * lmod$coefficients[2])
# [1] 0.01906454

```

A: A slightly different characterisation of the problem
Instead of these separate variations/errors in $\alpha$ and $\beta$ you could describe the variance of $Y_i$ directly.
A common way (which you see a lot on this site) is to describe a linear function like $$y_i = a+bx_i + \epsilon \quad \text{where} \quad \epsilon \sim N(0,\sigma^2)$$ or
$$y_i|x_i \sim N(a+bx_i,\sigma^2)$$
The above is with normal distributed errors. But you can use other distributions too. In general you could describe the mean and variance for $Y_i$. Conditional on $X_i$ it is often like (the case for homogeneous errors, independent of $x_i$)
$$\begin{array}{rcl}
\text{E}[y_i|x_i] &=& \alpha + \beta x_i \\
\text{Var}[y_i|x_i] &=& \sigma^2
\end{array}$$
(In the case of general linear models a description where $\text{Var}[y_i|x_i]$ is a function of $\text{E}[y_i|x_i]$ is also useful)

Your case is very similar but now the variance of the error is not a constant $\sigma$ and it depends on $x_i$.
$$\begin{array}{rcl}
\text{E}[y_i|x_i] &=& \alpha + \beta x_i \\
\text{Var}[y_i|x_i] &=& \sigma_{\alpha\alpha} + 2 x_i \sigma_{\alpha\beta} + {x_i}^2 \sigma_{\beta\beta}
\end{array}$$
where we use $\sigma_{ij}$ to indicate the variance or covariance.
In the case $\alpha = 5, \beta = 3, \sigma_{\alpha\alpha} = \sigma_{\beta\beta} = 0.1, \sigma_{\alpha\beta} = 0.05$ and $X \sim Unif(-1,1)$ it will look like:

It is a linear relationship with heteroscedasticity.
We can estimate the variance and covariance of $\alpha$ and $\beta$ based on this heteroscedastic dependency of the variance of the error (which we might approximate with the residuals).

Method of moments
The method that you used is the method of moments. You expressed the expectation of $\tilde X_i Y_i^2$ for the population in terms of coefficients. Then you replace in the expressions the expectation for the population by the average for the sample to obtain estimates of the coefficients.
(In your particular execution there is a small mistake by assuming that the expectation of $X_i^2\tilde X_i$ is zero. This is only true when $X_i$ is distributed symmetrical around zero)
Least squares method
A simpler approach might be to model the expectation of the square of the errors as a linear function of terms of $X_i$ and estimate it with the least squares method applied to the residuals. (It is simpler because it is straightforward and it will help to generalize the problem)
The errors are distributed as:
$$E(\epsilon_i^2) = \text{Var}[y_i|x_i] = \sigma_{\alpha\alpha} + 2 x_i \sigma_{\alpha\beta} + {x_i}^2 \sigma_{\beta\beta}$$
library(MASS)

fit <- function(cMu, cSigma, n) {
  ### generate data
  coef <- mvrnorm(n,cMu,cSigma)
  X <- runif(n,-1,1)
  Y <- coef[,1]+coef[,2]*X

  ### model means
  mod <- lm(Y ~ X)
  res <- mod$residuals

  ### model covariance tabel
  modr <- lm(res^2 ~ 1 + I(2*X) + I(X^2))
      ### using glm as a slight improvement to lm
      ### as the variance is not homogeneous but scales with mu
      ### (note that res^2 follows a chi-square distribution
      ###  for which we have var = 2*mu)
  modr <- glm(res^2 ~ 1 + I(2*X) + I(X^2),
              family = quasi(link = "identity", variance = "mu"),
              start = coef(modr))
  ### fitcov
  fitcov <- mean(X*Y^2)/(2*mean(X^2)) - prod(coef(mod))

  ### return result
  ret <- c(coef(modr),fitcov)
  names(ret) <- c("alpha", "cov", "beta", "fitcov")
  return(ret)
}

### settings
set.seed(1)
n <- 10^4
cSigma <- matrix(c(0.1,0.05,
                   0.05,0.1), 2, byrow = 1)
cMu <- c(5,3)

### generate data and perform fitting
fit(cMu,cSigma, 10^5)

Maximum Likelihood
I guess that you might also maximize the likelihood function (or a quasi-likelihood function if you do not see a particular distribution and stick to a formulation with only known conditional mean and variance).
But I can not find a closed solution for this. It can be done computationally. I leave this as a separate problem as writing a function that solves it might make this answer too cluttered. In addition, I am not sure whether it will be much faster or more accurate than solving it with the method of moments or fitting the square of the residuals.
Generalising
Your problem with two equations can be solved in the same way. Now we have two sets of residuals $r_{1i}$ and $r_{2i}$ whose expectation of the products depend on the covariance of the $\alpha_1$, $\alpha_2$, $\beta_1$ and $\beta_2$.
$$\begin{array}{rcl}
\text{E}[r_{1i}r_{2i}|x_i] &=& \sigma_{\alpha_1\alpha_2} +  x_i (\sigma_{\alpha_1\beta_2} + \sigma_{\alpha_2\beta_1}) + {x_i}^2 \sigma_{\beta_1\beta_2}
\end{array}$$
You have indeed the term $(\sigma_{\alpha_1\beta_2} + \sigma_{\alpha_2\beta_1})$ whose terms can not be separated with this single equation. The dependency of $r_{1i}r_{2i}$ or $y_{1i}y_{2i}$ on $x_i$ is dependent on the sum but not the independent terms.
If you would measure the $y_{1i}$ and ${y_{2i}}$ based on the same correlated $\alpha_1$, $\alpha_2$, $\beta_1$ and $\beta_2$, but with different $x_i$ (say $x_{1i}$ and $x_{2i}$) then you could separate the variables
$$\begin{array}{rcl}
\text{E}[r_{1i}r_{2i}|x_i] &=& \sigma_{\alpha_1\alpha_2} +  x_{2i} \sigma_{\alpha_1\beta_2} + x_{1i} \sigma_{\alpha_2\beta_1} + x_{1i}x_{2i} \sigma_{\beta_1\beta_2}
\end{array}$$

For what it is worth, here's a code that would compute the covariances (based on the linear fit of the residual term):
fit2 <- function(cMu, cSigma, n) {
  ### generate data
  coef <- mvrnorm(n,cMu,cSigma)
  X <- runif(n,-1,1)
  Y1 <- coef[,1]+coef[,2]*X
  Y2 <- coef[,3]+coef[,4]*X

  ### model means
  mod1 <- lm(Y1 ~ X)
  res1 <- mod1$residuals
  mod2 <- lm(Y2 ~ X)
  res2 <- mod2$residuals

  ### model covariance tabel
  modr <- lm(I(res1*res2) ~ 1 + I(X) + I(X^2))

  ### return result
  ret <- c(coef(modr))
  names(ret) <- c("alpha-alpha", "alpha-beta", "beta-beta")
  return(ret)
}

### settings
set.seed(1)
n <- 10^4
                  # a1, b1 , a2,  b2
cSigma <- matrix(c(0.10,0.05,0.10,0.10,
                   0.05,0.10,0.10,0.10,
                   0.10,0.10,0.40,0.20,
                   0.10,0.10,0.20,0.40), 4, byrow = 1)
       # a1 , b1 , a2 , b2
cMu <- c( 5,   3,   5,   3)

### generate data and perform fitting
fit2(cMu,cSigma, n)

A: Let me not answer the question exactly as I posed it, but to answer a very related question (and in fact, the question I am interested in in the first place). Suppose we have potential outcomes $Y_1(X), Y_0(X)$, and suppose that for each individual has a default level of $X$, say $X_d$, in the absence of experimental intervention. Suppose that the experimenter can shock $X$ from its default level by some randomized quantity $\varepsilon$ so that locally, the experimenter can (at least in principle) use an experiment to measure any quantity taking the form
$$\frac{d g(Y_1(X_d + \varepsilon), Y_2(X_d + \varepsilon))}{d\varepsilon}\bigg |_{\varepsilon = 0}$$
for some pre-specified function $g(Y_1, Y_2)$. Translating my original question into this framework, the claim that $\mathbb E[\alpha_i\beta_i]$ (and hence $\mathbb C\mathrm{ov}(\alpha_i, \beta_i)$) is identified follows from the observation that taking $g(Y_1, Y_2) = \frac12 Y_1^2$ gives
$$\frac{d g(Y_1(X_d + \varepsilon), Y_2(X_d + \varepsilon))}{d\varepsilon}\bigg |_{\varepsilon = 0} = \underbrace{Y_1}_{"\alpha_i"}\cdot \underbrace{\frac{d Y_1}{d\varepsilon}\bigg|_{\varepsilon = 0}}_{"\beta_i"}$$
where I am being a bit loose with notation on the RHS above. Similarly, when we take $g(Y_1, Y_2) = Y_1 Y_2$, we have
$$\frac{d g(Y_1(X_d + \varepsilon), Y_2(X_d + \varepsilon))}{d\varepsilon}\bigg |_{\varepsilon = 0} = \underbrace{Y_1 \frac{d Y_2}{d X}}_{"\alpha_{i,1}\cdot \beta_{i,2}"} + \underbrace{Y_2 \frac{d Y_1}{d X}}_{"\alpha_{i,2}\cdot \beta_{i,1}"}$$
The question now, is whether the individual terms on the RHS above can be separately identified (instead of just identifying their sum) using some function $g$. Since we just showed that their sum can be identified, this is equivalent to asking if there exists some $g$ such that
$$\frac{d g(Y_1(X_d + \varepsilon), Y_2(X_d + \varepsilon))}{d\varepsilon}\bigg |_{\varepsilon = 0} = \frac{\partial g}{\partial Y_2}\frac{d Y_2}{dX} + \frac{\partial g}{\partial Y_1}\frac{d Y_1}{d X} = Y_1 \frac{d Y_2}{d X} - Y_2 \frac{d Y_1}{d X}$$
at all $Y_1, Y_2$. But this requires $g$ to satisfy the following system of PDE
$$\frac{\partial g}{\partial Y_1} = -Y_2,\quad \frac{\partial g}{\partial Y_2} = Y_1$$
Such a $g$ cannot exist on any neighborhood. To see why, fix some point $(a,b)$, and consider $g(a,b)$ compared to $g(a+\delta, b + \delta)$ for any $\delta > 0$. WLOG, we can normalize $g(a,b) = 0$. Using the PDE system above, we can try to evaluate $g(a+\delta,b+\delta)$ two different ways. First, we could first integrate along the first dimension and then integrate along the second dimension to get $g(a+\delta,b+\delta) = -\delta b + \delta (a + \delta)$. Second, we could first integrate along the second dimension and then integrate along the first to get $g(a+\delta,b+\delta) = - \delta(b + \delta) + \delta a$. Setting these two expresssings for $g(a+\delta,b+\delta)$ and simplifying, we arrive at the contradiction $\delta = - \delta$. I am not sure that this completely rules out any way of identifying the cross-equation correlations separately, but it certainly suggests that no treatment-effect based approach on its own will work.


text:
Q: calculate geometry properties using boundary coordinates Calculation of geometry properties of various shapes are useful specifically in engineering purposes. This is very easily formulated when the shapes of the geometry are rectangular, circle, etc. However, when the shape of becomes a combination of these and becomes more complicated, such calculations become too tough. In some engineering cases these shapes are simplified, in some scientific cases users take advantage of numerical packages coded in Python or similar scientific applications.
Are there any way to calculate geometry properties (like perimeter, area, first and second moment of inertia, etc) of sections with arbitrary shapes, using coordinates of some points on their boundaries?
My question focuses on two-dimensional shapes, however when shapes are in three-dimensional form, it may be interesting to know that how point coordinates on the boundary may be used to calculate properties like volume, center of gravity, surface area, etc.

A: Let $v : [n] \rightarrow \mathbb{R}^2$ be the consecutive vertices of your $n$-vertex simple polygon. The perimeter is simply the sum of the lengths of the edges between vertices:
\begin{align*}
P &= \sum_{i \in [n]} |v_i-v_{i+1}|
\end{align*}
where $v_{n+1} \stackrel{\text{def}}{=} v_1$. The signed area is given by the shoelace formula:
\begin{align*}
A &= \frac{1}{2} \sum_{i \in [d]} \star(v_i \wedge v_{i+1})
\end{align*}
where $\star$ is the Hodge dual and $\wedge$ is the wedge product:
\begin{align*}
\star (v_i \wedge v_{i+1})
&= \det \begin{bmatrix} x_i & x_{i+1} \\ y_i & y_{i+1} \end{bmatrix} \\
&= x_i y_{i+1} - x_{i+1} y_i
\end{align*}
The area is $|A|$. The centroid (center of mass) is
\begin{align*}
C &= \frac{1}{6 A} \sum_{i \in [d]} \star(v_i \wedge v_{i+1}) (v_i + v_{i+1})
\end{align*}
The moments of inertia are given here. In general, you can decompose an arbitrary polygon into a set of triangles and compute properties based on known formulas for those triangles.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I prevent an image's css-filter-drop-shadow from showing up when a div is on top of it? I am laying a rectangular div on top of a down-arrow image so that only a triangular piece peeks out (I did this by setting the rectangle's z-index to 100 and the arrow's z-index to -100). When I add a drop-shadow to the down-arrow image, I expect only the triangular piece's drop-shadow to appear, but the rest of the down-arrow's drop-shadow that should be hidden under the rectangular div also appears (see image below).
.
#arrowDown {
position: relative;
z-index: -100; /* z-index of rectangular div is 100 */
width: 88.5839416px;
height: 82px;
margin: -50px 100px;
bottom: 89.2px;

background: url('../img/arrowDown.png') no-repeat center center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

-webkit-filter: drop-shadow(0 0 5px #FFFFFF);
-moz-filter: drop-shadow(0 0 5px #FFFFFF);
-o-filter: drop-shadow(0 0 5px #FFFFFF);
filter: drop-shadow(0 0 5px #FFFFFF);
}


text:
Q: Does deployment slot URL change to defined custom URL after swap to prod? Hi I have a API deployed and is used in production, and I have been reading a bit about deployment slots. The thing is the API that is in Production has it own custom URL.
What I am wondering is that, if I deploy an updated version of the API, and swap it in Azure... would it still get the same URL as the old one?
That is will it also swap the URL, resulting in using it so that I don't have to change the URL in other connected systems?

A: It will not swap the custom domain names, meaning it stays in the Production slot.
The new version will be running under the custom domain name.
More info here on deployment slots: https://learn.microsoft.com/en-us/azure/app-service/web-sites-staged-publishing

Settings that are not swapped:

*

*Publishing endpoints

*Custom Domain Names

*SSL certificates and bindings

*Scale settings

*WebJobs schedulers


text:
Q: Generate multiple table (For viewing) I would like to ask on how to make my table to appear as following:

But I only manage to get my table to appear like this:

As you can see, the table is separated according to the different year or semester of when they stored their stuff. It is basically a history storage of that particular person. Unfortunately, I don't know how to make the generated table to attach together for the one with same year and semester instead of separating it. Even the numbering is affected. Below is the code that I have so far:
<?php
include("connect.php");
include("header.php");

if(isset($_GET['invstuview_bag'], $_GET['invstuview_name']))
{
    $get_id = $_GET['invstuview_bag'];
    $get_name = $_GET['invstuview_name'];

?>

View History

Baggage Detail History

Baggage Detail History For <?php echo $get_name; ?>(<?php echo $get_id; ?>)

    <?php
        $sql_join = "SELECT student.*,location.*, inventory.*, baggage.*
                FROM
                    student,location, inventory, baggage
                WHERE
                    student.student_id = inventory.invstu_id AND
                    baggage.baggage_id = inventory.invbag_id AND
                    location.location_id = inventory.invloc_id AND
                    invstu_id = '$get_id'
                ORDER BY inventory_id";

        $result_join= mysqli_query($connect,$sql_join);

        $prev_year = "";
        $prev_sem = 0;
        $get_year = "";
        $get_sem = 0;
        while($row_join=mysqli_fetch_assoc($result_join))
        {
            $counter = 1;
            $prev_year =  $row_join["invstu_year"];
            $prev_sem =  $row_join["invstu_sem"];

            //if the data is of same year and semester
            if(($prev_year!="") && ($prev_sem!=0) && ($prev_year == $get_year) && ($prev_sem == $get_sem))
            {
                $get_year = $row_join["invstu_year"];
                $get_sem = $row_join["invstu_sem"];
    ?>

                    No.
                    Baggage Types
                    Quantity
                    Location

                    <?php echo $counter; ?>
                    <?php echo $row_join["baggage_type"]; ?>
                    <?php echo $row_join["invbag_quantity"]; ?>
                    <?php echo $row_join["location_house"]; ?>

                <?php
                $counter++;
                echo'
';

            }
            //if data is not of same year or semester
            else
            {
                $get_year = $row_join["invstu_year"];
                $get_sem = $row_join["invstu_sem"];
            ?>

                Room: <?php echo $row_join["invstu_room"]; ?>

                Year: <?php echo $row_join["invstu_year"]; ?>

                Semester: <?php echo $row_join["invstu_sem"]; ?>

                    No.
                    Baggage Types
                    Quantity
                    Location

                    <?php echo $counter; ?>
                    <?php echo $row_join["baggage_type"]; ?>
                    <?php echo $row_join["invbag_quantity"]; ?>
                    <?php echo $row_join["location_house"]; ?>

                <?php
                    $counter++;
                    echo'
';
            }
        }
            ?>

            <button type="button" name="back" class="btn btn-success" id="back" style="width:200px; display:inline-block; margin-top:2%; margin-bottom:1%; background-color: #4CAF50" onclick="window.location.href='view.php'">Back</button>

<?php
}
?>

Any ideas is highly appreciated.

A: Move these out of the while loop:

                No.
                Baggage Types
                Quantity
                Location

           echo'
';


text:
Q: invalid operand to binary expression reading an array of struct I am trying to implement the fractional knapsack famous problem. I needed a struct to connect the values and the weights. Now I want to read the array of struct item, but it gives me this:

invalid expression error

#include <iostream>
#include <vector>
#include <string>

using std::vector;
using namespace std;

// Structure for an item which stores weight and corresponding
// value of Item
struct Item
{
    int value, weight;
    // Constructor
    Item(int value, int weight) : value(value), weight(weight) {}
};

int main()
{
    int n;
    int W;
    std::cin >> n >> W;

    vector<Item> arr(n);
    for (int i = 0; i < n; i++) {
        std::cin >> arr[i];
    }

    cout << "Maximum value we can obtain = " << fractionalKnapsack(W, arr, n);
    return 0;
}

A: arr is a vector of objects of type Item. To access Item fields, you have to do so using . or -> if you are using a pointer. Using cin >> arr[i] you are trying to input a char to an object of Item.
Try this: std::cin >> arr[i].value


text:
Q: How to count number of entries in a text file I have a text file:
10
List of ARFCNs = 987 988 989 991 992 993 995 999 1000 1004 1008 1009 1010 1011 1012 1018 1019 1020 1023
I want a code such that it returns the number of values in the list i.e. 19 in this case.
Furthermore, I need to use this number of entries such that if the answer is either 0 or more than 1, the output prints a textline. But if the numbe ris exactly 1, then another statement is printed.
I know its a very basic question but I cant find any specific solution.
I tried using len, but im not sure as to what should be the delimiter. Putting space as a delimiter gives a faulty answer. I want an exception to the code where entries after the = sign are counted and then processed in an if/else loop probably.

A: This will help you:
numbers = data.split("=")[1].split(" ")
for value in numbers:
    if value == "":
        numbers.remove(value)
count = len(numbers)

Here data the the whole string tha you are reading from text file.
This will return the number counts and you can use it further.

A: Here is the full code:
with open('problem.txt','r') as myfile:
    file_str = myfile.read()
my_list = [] ##initializing a list
for word in string.split('=')[1].split(' '): ##using split function to split, the list.this splits the value in index specified and return the value.
 ## storing the updated list
    my_list.append(word)
for var in my_list:
    if var == '':
        my_list.remove(var)
if len(my_list) == 0 :
    print(f'the number of entries are zero')
else:
    print(f'the number of entries are {len(my_list)}')


text:
Q: Keyboard starts skipping characters after wake from suspension/sleep, restart required. After my computer wakes from sleep the keyboard is starting to skip characters unless i type very very slow. The only solution i have found is to restart the computer.
Being linux i guess there most be a quicker way to fix this error, maybe by restarting the service that is handling the input or something similar that will save me time instead of doing a reboot.
Computer is an Dell Vostro v13 with ubuntu 12.10 if that helps.

A: Found a solution by running:

sudo modprobe -r psmouse
sudo modprobe psmouse

so i put it in a script and placed it in /etc/pm/sleep.d/ and named it 20_keyboardquickfix
#!/bin/sh
#put it in /etc/pm/sleep.d/ and name it 20_keyboardquickfix
#make sure it is runnable. by running "sudo chmod 755 20_keyboardquickfix"

#this scipts removes and then inserts the module psmouse, this is a #quick fix for keyboard working strangely after wakeup from sleep
#solution was found on askubuntu:
#http://askubuntu.com/questions/77143/keyboard-issues-after-resuming-from-sleep-on-a-dell-vostro-13?rq=1

modprobe -r psmouse
sleep 3
modprobe psmouse


text:
Q: Using helper function inside a Core Class in CodeIgniter There is a helper which I would like to use inside a core class, CI_Router (MY_Router, to be more accurate). In this custom router, I made some modifications to the original code, in order to be able to insert hyphens into my urls.
I have defined the helper on the autoload.php file, as usual, but it seems that I can´t invoque a helper function inside a class other than a view or controller.
Any ideas about how to handle this? My initial approach was to use a helper, so I can reuse it on any place I want.
TYVM.

A: Helpers are not instantiated until after the core, thus why it does not work.
You will either have to:

*

*Duplicate the function in your MY_Router class, or,

*Rethink why you might be using the same function in the Router that you use in a standard controller or view.

Option 1 is obviously easier, but might not be preferable depending on how bad your OCD is.

A: You could try getting the instance of the main CI object and setting it to a variable, then load the helper using that. Ex:
$ci =& get_instance();
$ci->load->helper('date');

I know that works in other areas, not 100% sure about any of the router classes.


text:
Q: Open a form from a report and vice versa So I have 2 projects, well a few more than that. But 1 project or multiple are forms and the other is a DevExpress XtraReport. I need to be able to open the report from the form and open the form from the report. Obviously there is a circular dependency, so any way around this? I am looking into using an Interface but am not knowledgeable enough to actually implement it.

A: How do you want to open a form from the Report? click on the some report element/control? or clicking on some ribbon button?


text:
Q: How to set certain elements as invalid in HTML? In my document I am printing all elements with the given classname like so: console.log(this.document.getElementsByClassName("curClass"));
but how do I set those return forms to invalid?
I would like to do something like:
this.document.getElementsByClassName("curClass").setAll('invalid');
or similarly to this post, using field.setCustomValidity('Invalid field.")
however, it seems that is not an existing functionality.
Thanks!


text:
Q: Site permissions do not work at all We have a strange issue here, looks like nobody, who is not a site collection administrator, can access anything under the collection (classic).
The rights are goot distributed, at least, when I click on "check permissions" I can see that user x has read access, that is coming from group visitors. Even giving full control has no effect. Tested with multiple users.
The standard approval process doesn't seem to be working. User goes to link, gets access denied screen, asks for access, I get the mail, click on approve, the user gets confirmation mail, clicks on the link in the mail, and again, get the same access denied screen.
The issue is with only this one site collection. Did anyone see an something like this?
Edit:
When I, as site collection administrator visit the /_layouts/15/settings.aspx page, I don't see the "site permissions" or any other access related options.
I can access the /_layouts/15/user.aspx page tough.
Edit2:
Looks like something is really messed up, we have a subsite that inherits permissions from the top site and our test user can access that one, but not the top site. That is, in theory, not possible. Now discussing with support.

A: Can you please try to add any one users through powershell, this kind of issue happening frequently in SharePoint Online but still not able to find the Root cause
Add-SPOUser -Site https://tenant.sharepoint.com/sites -LoginName userID -Group "Visitor Group"


text:
Q: How to change programmatically the text of a Word Bookmark I need to process a Word document and change (the text of) a bookmark.
I exported my Word document to flat xml format to help establish the structure of the document - here is a fragment
<w:bookmarkStart w:id="0" w:name="CustomerName"/>
<w:r w:rsidRPr="001E4487">
    <w:rPr>
        <w:rFonts w:ascii="MyTypeRegular"
              w:hAnsi="MyTypeRegular"
              w:cs="MyType V2 Regular"/>
        <w:szCs w:val="22"/>
    </w:rPr>
    <w:t>[CustomerName]</w:t>
</w:r>
<w:bookmarkEnd w:id="0"/>

The bit I need to change is <w:t>[CustomerName]</w:t> which should then become, for example <w:t>Some Punter</w:t>
so in my VBA i am hoping to be able to do something like this ...
  Dim bkm As Bookmark
  For Each bkm In ActiveDocument.Bookmarks
    bkm.Text = "Some Punter"
  Next bkm

only BookMark does not have a Text property
How do Access that little data item in the square Brackets?

A: A word bookmark doesn't have a text property, but its range property does.
Use bkm.Range.Text = "Some Punter"
Note that once you change the text, the bookmark will be removed from the Word Document.  In order to keep the bookmark you need to do:
    Dim bkm As Bookmark
    Dim bkmName As String
    Dim bkmRng As Range
    Dim NewText As String

    NewText = "Some Punter"

    For Each bkm In ActiveDocument.Bookmarks
        Set bkmRng = bkm.Range
        bkmName = bkm.Name
        bkm.Range.Text = NewText
        bkmRng.End = bkmRng.Start + Len(NewText)
        Bookmarks.Add(Name:=bkmName, Range:=bkmRng)
    Next bkm

Hope this helps.

A: I have a workaround for this that is not perfect but is less complicated:  In place of the bookmark, use ActiveX text box and in place of cross-reference use ActiveX label.  Then make change event (or LostFocus Event) for the text box:  LabelName.Caption = TextboxName.Text.  Formatting can be as desired.  Alignment of text outside controls may be needed using Font> Advanced > Position > Raised.  This may not be acceptable in all instances, but it often can be.  Requires no update of field.


text:
Q: MySQL - help with IF... ELSE usage within query I need to add an if/else stament inside a MySQL query but can't get it to work.
Below is an example with pseudo-code of what I want to accomplish.
SELECT *
FROM calendar
WHERE calendar.alert = 1

IF calendar.repeat = 0 THEN HAVING calendar.UTC_1 > UNIX_TIMESTAMP();

ELSE "get all records regardless of calendar.repeat value";

END IF;

Any suggestions to make this happen? I couldn't find the correct syntax for this MySQL IF ELSE.
Thanks for helping!

A: SELECT *
FROM calendar
WHERE calendar.alert = 1
AND CASE
WHEN `repeat` =0 THEN UTC_1 > UNIX_TIMESTAMP()
ELSE 1=1 END;

You can use IF-ELSE only inside the body of stored procedure/trigger. You can use IF(condition, value_if_condition_is_true, value_if_condition_is_false) in SELECT, but I prefer CASE(you can easily rewrite the query above to
 .... AND IF(`repeat` = 0, UTC_1>UNIX_TIMESTAMP(),1=1)

A: Not sure I got the syntax all right here, but I like the idea of somethign like this.  In my opinion it is much easier to look at in the future and see the two groups you're grabbing with the following example.  I'm not educated on efficiency of case vs union in MySQL but it seems to me like the case would be less efficient as well.  Maybe someone can answer that for sure?
SELECT *
FROM calendar
WHERE
    calendar.alert = 1
    AND calendar.repeat = 0
    AND calendar.UTC_1 > UNIX_TIMTESTAMP();
UNION
SELECT *
FROM calendar
WHERE
    calendar.alert = 1
    AND calendar.repeat != 0


text:
Q: Labelling the Target Variables I am trying to plot Heart Disease against Gender. Here I am trying to label 0 as absent and 1 as present in the fig. Is there is a way of doing it? I have tried the following code and plotted:
ax = sns.countplot(x='target', hue='sex', data=heartt)
plt.show()

A: I wouldn't relabel the axis ticks if I were you, unless you're very sure about how seaborn is going to handle the ordering for all your variables. Safer to do it in the data:
heartt['target_label'] = heartt['target'].map({0: 'absent', 1: 'present'})
ax = sns.countplot(x='target_label', hue='sex', data=heartt)
plt.show()


text:
Q: WiX: Update version number displayed in Add/Remove Programs I use WyUpdate to automatically deliver program updates so my customers are always running the latest version. However one problem with this approach is that the MSI installer (created with WiX 3.5) is not invoked during updates and thus the version numbers in Add/Remove Programs are not incremented.
My question is if there is some safe way to programmatically bump the displayed version ?(WyUpdate has the ability to execute custom code and change registry values during updates).

A: Technically, you can find a key in the system registry where the version is read from (typically, under SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall) and force your update software to modify this value each time with the correct version.
BUT I don't think it is a good idea. Modifying the registry keys you don't owe, and injecting your own logic into the Windows Installer might lead to unexpected consequences. I would personally never do this. Sooner or later, it will shoot...
BTW, if you don't rely on Windows Installer with updates, why it is that important to update the version in ARP? Have a well-known place in your application where users can look for the current version, for instance.

A: Simply change the "DisplayVersion" value to the latest version.
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\YourAppName

Also, to save time, in wyBuild you can use the %version% variable and every new version you create will use correct version (instead of having to type it each time you release a new version).
Regarding what Yan said...

BUT I don't think it is a good idea. Modifying the registry keys you don't owe, and injecting your own logic into the Windows Installer might lead to unexpected consequences. I would personally never do this. Sooner or later, it will shoot...

This is plain wrong. Editing a registry value isn't changing the installer logic. It isn't dangerous at all. The end-user can still repair the original installation (reverting the registry and all the files back to the original version) and they can run the uninstaller and it will remove the registry and files (despite them being changed).
If don't want the "msi repair" to revert to the original installation (rather than to the updated version of your app) then you'll want to deliver an *.msp or *.msi to your users and execute it as part of your update.
Short answer: editing registry is neither evil nor unsafe, as long as you understand what's what.


text:
Q: How to target react compunents from a map list using useRef I'm tring to make few buttons that corresponds to keyboard keys , But i'm fairly new to React and i don't know how to target those elements ,Each element have it's id and i can access the event key but after that i'm lost ,I alredy tried using refs but i didn't find an example that i can work with or understand how can i turn it to use inside my code.
This is the array of objects im using to genrate a list of compunents:

   const [bankOne,setBankOne] = React.useState([
    {
      keyCode: 81,
      keyTrigger: "Q",
      id: "Heater-1",
      url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
    },
    {
      keyCode: 87,
      keyTrigger: "W",
      id: "Heater-2",
      url: "https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3"
   }]);

this is the event handler:

  const handleKeyPress = React.useCallback((event) => {
    //console.log(event.key.toUpperCase());
    console.log(itemsRef.current)
   }, []);

  React.useEffect(() => {
    document.addEventListener('keypress', handleKeyPress);
    return () => {
      document.removeEventListener('keypress', handleKeyPress);
    };
  }, [handleKeyPress]);

this is the list im using to genrate React compunents:

  const bank1 = bankOne.map((item,i) => (
    <button
      ref={el => itemsRef.current[i] = item.keyTrigger}
      id={item.id}
      className="drum-pad"
      value={item.keyTrigger}
      onClick={handleClick}
      onKeyPress={handleKeyPress}
    >
      <audio  src={item.url} className="clip" id={item.keyTrigger}>
        <source src={item.url} type="audio/mp3" />
      </audio>
      {item.keyTrigger}
    </button>
  ));

i have no idea how to do this ,that's why i didn't post any of the ways i tried to solve the problem because i know they were all wrong one way or another .
i really appreciate any help ,and thank you all.

A: so i learned that i only needed a useRef array and then i targeted each button by it's index in that array,maybe not the best solution but at least it worked .

  const btnsRef = React.useRef([]);
    const handleKeyPress = React.useCallback((event) => {
   switch(event.key.toUpperCase()){
      case "Q":
        btnsRef.current[0].focus()
        btnsRef.current[0].firstChild.load()
        btnsRef.current[0].firstChild.play()
       setData(prev => ({...prev,currentNote: btnsRef.current[0].id}))
        break;
        case "W":
        btnsRef.current[1].focus()
        btnsRef.current[1].firstChild.load()
        btnsRef.current[1].firstChild.play()
       setData(prev => ({...prev,currentNote: btnsRef.current[1].id}))
        break;
}
   }, []);

  const component = obj.map((item,index) => (
    <button
      ref={(element) => btnsRef.current[index] = element}
      id={item.id}
      value={item.keyTrigger}
      onKeyPress={handleKeyPress}
    >
      <audio className="clip" id={item.keyTrigger}>
        <source src={item.url} type="audio/mp3" />
      </audio>
      {item.keyTrigger}
    </button>
  ));


text:
Q: full transition after updating query parameters in ember I have the following route that run a report for specific date range:
export default Ember.Route.extend({
  model: function(params){
    return this.store.query('report' {
      "report":"my_report",
      "from":params.startDate,
      "to":params.endDate
    });
  },

  setupController: function(controller, model) {
    this._super(controller, model);
    // change format model and save it in rows
    controller.set('model', rows);
  }
});

Now, my controller is as follow:
export default Ember.Controller.extend({
  queryParams:["startDate","endDate"],
  actions:{
    processReport:function(from,to){
      this.transitionToRoute('reports',{
        queryParams :{
          "startDate":from,
          "endDate":to,
          "refreshModel": true
        }
      });
    }
  },
  to:"",
  from:""
});

The template is as follow:
From {{bootstrap-datepicker value=to}}
To {{bootstrap-datepicker value=from}}
<button {{action  "processReport" from to}}>Process Report</button>

So, when I click the button the url changed and console show:
Attempting transition to reports   ember.debug.js:52602
Transitioned into 'reports'        ember.debug.js:27426

but the page remains same. How do I fully transition to the page?

A: You should add to your route the queryParams configuration to make a full transition
export default Ember.Route.extend({
  queryParams: {
    startDate: {
      refreshModel: true
    },
    endDate: {
      refreshModel: true
    }
  },
...

And on the controller you'll need to just update the values "startDate" and "endDate" in the custom action:
Export default Ember.Controller.extend({
  queryParams:["startDate","endDate"],
  actions:{
      processReport:function(){
        this.set('startDate', this.get('from'));
        this.set('endDate', this.get('to'));
      }

  },
  to:"",
  from:""
});

This has been explained on the guides:
https://guides.emberjs.com/v2.11.0/routing/query-params/#toc_opting-into-a-full-transition

A: I figured it out on my own by reading the updated API on query-params in the following link:
 https://guides.emberjs.com/v2.3.0/routing/query-params/


text:
Q: Reading a fasta file format into python dictionary I have a file with the following format:
>seq1
ATGGGTGTGTGTGTG
>seq2
ATGTGTTTGTGTGCTCCTCCTC
>seq3
AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA

I want to read this file as a dictionary in Python. I am aware of BIO-python functions but I want to learn scripting in python in addition to getting my job done. I have tried this code so far:
import sys
sequence = ' '
fasta = {}
with open(sys.argv[1]) as file_one:
    file_one_content = file_one.read()
    for line in file_one_content.split("\n"):
        if not line.strip():
            continue
        if line.startswith(">"):
            sequence_name = line.rstrip('\n').replace(">", "")
        else:
            sequence = line.rstrip('\n')
        if sequence_name not in fasta:
            fasta[sequence_name] = []
        fasta[sequence_name].append(sequence)
print fasta

I get the following output:
{'seq3': ['ATGTGTTTGTGTGCTCCTCCTC', 'AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2': ['ATGGGTGTGTGTGTG', 'ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': [' ', 'ATGGGTGTGTGTGTG']}

My expected output file is:
{'seq3': ['AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2': ['ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': [ 'ATGGGTGTGTGTGTG']}
I have been trying to understand why the dictionary is printed in a wrong way but I can't find the mistake. As I want to learn, it would be great if you could let me know how I could correct the mistake in my code. Thanks.

A: Using biopython SeqIO and a dict comprehension:
from Bio import SeqIO
seq_dict = {rec.id : rec.seq for rec in SeqIO.parse("myfile.fasta", "fasta")}

A: Fixed. There was a problem with your if/else logic.
import sys
fasta = {}
with open(sys.argv[1]) as file_one:
    for line in file_one:
        line = line.strip()
        if not line:
            continue
        if line.startswith(">"):
            active_sequence_name = line[1:]
            if active_sequence_name not in fasta:
                fasta[active_sequence_name] = []
            continue
        sequence = line
        fasta[active_sequence_name].append(sequence)

print fasta

    python fasta.py input.txt
    {'seq3': ['AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA'], 'seq2' ['ATGTGTTTGTGTGCTCCTCCTC'], 'seq1': ['ATGGGTGTGTGTGTG']}

A: Since your intention is to learn Python, I will dare to edit your code just a bit and explain it a little.
import sys
from itertools import imap

fasta = {}
with open(sys.argv[1]) as file_one:
    for line in imap(str.rstrip, file_one):
        if line.startswith(">"):
            sequence_name = line.lstrip(">")
        else:
            fasta.setdefault(sequence_name, []).append(line)

First of all, file objects are iterators, so you don't really need to read them in (via the file.read() method) if you only need to do it once. Secondly, you don't need to specify "\n" in the rstrip call. Moreover, instead of calling rstrip in several places, you can use imap (map in Python 3) to lazily strip all lines in one place. And you can just use the dict.setdefault() method in order to avoid manual key-check.

A: Use a defaultdictusing lines that start with > as the keys and call next on the file object to get the sequence:
from collections import defaultdict

fasta = defaultdict(list)
with open(sys.argv[1]) as file_one:
    for line in file_one:
        if line.startswith(">"):
            fasta[line.strip(">\n")].append(next(file_one).rstrip())
print fasta

defaultdict(<type 'list'>, {'seq1': ['ATGGGTGTGTGTGTG'], 'seq2': ['ATGTGTTTGTGTGCTCCTCCTC'], 'seq3': ['AACGTCGTGACGGGTGCGTGGTGTGTGTCCAA']})

Which can simply become a dict comprehension:
with open(sys.argv[1]) as file_one:
    fasta = {line.strip(">\n"):next(file_one).rstrip() for line in file_one}
    print(fasta)

Unless you have repeating keys or empty lines a lot of your code is redundant.


text:
Q: App crashes when trying to bind a list of strings to LongListMultiSelector I'm getting a weird error when I'm trying to bind a list of strings to the LongListMultiSelector. The values I want to assign are from the IsolatedStorage.GetFileNames("Path\\*");
XAML-Code:
The Template
               <DataTemplate x:Key="plItemTemplate">
            <Grid Margin="{StaticResource PhoneTouchTargetOverhang}">
                <toolkit:ContextMenuService.ContextMenu>
                    <toolkit:ContextMenu Name="conPlMgr" Opened="conPlMgr_Opened" Closed="conPlMgr_Closed">
                        <toolkit:MenuItem Name="mnuPlaylist" Header="{Binding LocalizedResources.AddToPlaylist, Source={StaticResource LocalizedStrings}}" Click="mnuPlaylist_Click"/>
                        <toolkit:MenuItem Name="mnuFav" Header="{Binding LocalizedResources.AddToFav, Source={StaticResource LocalizedStrings}}" Click="mnuFav_Click"/>
                    </toolkit:ContextMenu>
                </toolkit:ContextMenuService.ContextMenu>
                <TextBlock Name="cmdPlItem" Tap="cmdPlItem_Tap" FontFamily="Segoe UI Symbol" TextWrapping="Wrap" Margin="5,0,5,5" FontSize="24"/>
            </Grid>
        </DataTemplate>

The LongListMultiSelector
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Grid Style="{StaticResource LongListLastItemMargin}">
                <toolkit:LongListMultiSelector
                    Name="lstPlaylists"
                    Style="{StaticResource LongListMultiselectorProps}"
                    ItemTemplate="{StaticResource plItemTemplate}"
                    ItemsSource="{Binding Instance.GetPlaylists,Source={StaticResource PlaylistManager}}"
                    IsSelectionEnabledChanged="lstPlaylists_IsSelectionEnabledChanged"/>
            </Grid>
        </Grid>

The List:
public List<string> GetPlaylists
{
    get { return isoStore.GetFileNames("Playlists\\*").ToList(); }
}

And this is the error message I get:

Message: Error HRESULT E_FAIL has been returned from a call to a COM component. StackTrace:  Is handled?: False e.ToString()

System.Windows.ApplicationUnhandledExceptionEventArgs CompleteStuff:
  MS.Internal.WrappedException: Error HRESULT E_FAIL has been returned
  from a call to a COM component. ---> System.Exception: Error HRESULT
  E_FAIL has been returned from a call to a COM component.    at
  MS.Internal.XcpImports.CheckHResult(UInt32 hr)    at
  MS.Internal.XcpImports.FrameworkElement_MeasureOverride(FrameworkElement
  element, Size availableSize)    at
  System.Windows.FrameworkElement.MeasureOverride(Size availableSize)
  at System.Windows.FrameworkElement.MeasureOverride(IntPtr
  nativeTarget, Double inWidth, Double inHeight, Double& outWidth,
  Double& outHeight)    --- End of inner exception stack trace ---

I don't get what's the problem here, there should be no problem with the values, they're returned correctly. I've binged and googled so much but still weren't able to find a solution for this, it's so depressing since this is such a blocker for a new feature...
UPDATE
Well~ I don't know but it works now.
If I do this: <TextBlock Text={Binding} /> it works if I set the values in the constructor.

A: Try to make a list as the member of the class:
add member of the class:
private List <string> filesList = new List<string>();

...
change the function:
public void GetPlaylists
{
   filesList = isoStore.GetFileNames("Playlists\\*").ToList();
   LongListMultiSelectorName.itemsSource = filesList;
}

call GetPlaylists where you want.


text:
Q: How can I improve downloading speed with python urllib.request How can I improve downloading speed with urllib.request? I want to download image from web and It works well. But it takes too long downloading it. It took 42 seconds to excute donwload_album_art() func. What Can I do for that? Can I use mutiprocess or etc? h
import os
import shutil
import requests
from bs4 import BeautifulSoup
from urllib import request

URL = 'https://music.bugs.co.kr/chart/track/day/total'
PATH = os.getcwd() + '/static/images/'

# Scrapping html code
def get_html(target_url):
    _html = ""
    response = requests.get(target_url)
    if response.status_code == 200:
        _html = response.text
    return _html

# parse image url and save in list
def get_image_url():
    html = get_html(URL)
    soup = BeautifulSoup(html, 'html.parser')
    img_url = []

    for image in soup.select('a.thumbnail > img'):
        if image.has_attr('src'):
            img_url.append(image.get('src'))
        else:
            continue
    return img_url

# download album art in static/images directory
def download_album_arts():
    images = get_image_url()
    for i in range(0, 100):
        url = images[i]
        file_name = PATH + str(i + 1) + '.png'
        request.urlretrieve(url, file_name)

# delete all album art
def delete_album_art():
    path = os.getcwd() + '/static/images'
    if os.path.exists(path):
        shutil.rmtree(path)
        os.mkdir(path)
    else:
        os.mkdir(path)


text:
Q: Profiling C++ compilation times in Visual Studio I'm currently working on speeding-up the building process of a fairly large C++ codebase. While the process of improving compilation times of specific translation units is pretty well understood and documented I don't think there are any tools that would help me profile the building process to find candidates for optimisation - at least not for Visual Studio as I've read of some that would facilitate the process in GCC or Clang.
To better illustrate my problem, I'll give you a simple example:
Let's assume we have a large header file that includes multiple other headers. Including it in a .cpp file greatly degrades its compilation time. Let's say that it is included in many translation units and therefore optimising it will improve the overall building time by a lot.
Do you know of any tools that would help identify such heavy-hitters?
I've begun writing a Python script that parses Visual Studio build logs and creates a dependency graph and then analyses it, but I'd like to make sure that this work is indeed necessary.


text:
Q: Passing an error to a component I have an AddComment.vue component which has a form, on submit it hits a laravel api endpoint where validation happens. If validation fails I want to show the errors in AddComment.vue. How can return the error.response object to AddComment.vue? Currently, I can see 'fired' in the console when I want to be logging the error. Where am I going wrong any help would be greatly appreciated
AddComponent.vue
methods: {
    addComment() {
        this.$store.dispatch('addComment', {
            name: this.name,
            email: this.email,
            body: this.body
        })
        .then(response => {
            this.$router.push({ name: 'home' })
            console.log('fired')
        })
        .catch(error => {
            console.log(error)
        })
    },
}

store.js
actions: {
    addComment(context, comment) {
        new Promise((resolve, reject) => {
            axios.post('/comments', {
                name: comment.name,
                email: comment.email,
                body: comment.body,
                approved: false
            })
            .then(response => {
                context.commit('addComment', response.data)
                resolve(response)
            })
            .catch(error => {
                reject(error)
            })
        });
    },
}

A: The catch() block only gets called if the Laravel backend throws an error. So if you are returning a normal status code of 2xx then axios always calls the .then() part. In that case, you have to resolve the error message yourself.
Try something like this in your backend route (it will return an error):
return response()->toJson([
    'message' => 'error message',
], 500);

And see if this responds with an actual error in you vuejs application.


text:
Q: Not able to click on "Home" Button Python On Website when I login with Username: mercury and
PW: mercury and click on Submit button I go to Login Successfully page. Then I need to click on home button which is on the left side but i can't.
from telnetlib import EC
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome(executable_path="D:\ChromeDriverExtracted\chromedriver")
driver.get("http://demo.guru99.com/test/newtours/")
driver.maximize_window()

driver.find_element_by_name("userName").send_keys("mercury")
driver.find_element_by_name("password").send_keys("mercury")
driver.find_element_by_name("submit").click()
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/table/tbody/tr/td[1]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]/td[2]/font/a"))).click()

A: This is an absolute xpath
/html/body/div[2]/table/tbody/tr/td[1]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]/td[2]/font/a

please use one of the text-based locator from below:
//a[text()='Home']

or with LINK_TEXT like this :
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Home"))).click()

You can also use the below CSS selector:
a[href='index.php']

There are other ways as well to click,
Code trial 1:
time.sleep(5)
driver.find_element_by_xpath("//a[text()='Home']").click()

Code trial 2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Home']"))).click()

Code trial 3:
time.sleep(5)
button = driver.find_element_by_xpath("//a[text()='Home']")
driver.execute_script("arguments[0].click();", button)

Code trial 4:
time.sleep(5)
button = driver.find_element_by_xpath("//a[text()='Home']")
ActionChains(driver).move_to_element(button).click().perform()

Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

A: To click on the element with text as Home you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

*

*Using LINK_TEXT:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, "Home"))).click()

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.signin-btn.sbLoginBtn > span.btf-text"))).click()

*Using XPATH:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Home']"))).click()

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Why isn't there a space in the middle of my pyramid? So I am trying to solve https://cs50.harvard.edu/x/2021/psets/1/mario/more/ this problem set from cs50.
It's taken me way too long to get this far (5-6 hours WITH help from youtube).
#include <cs50.h>
#include <stdio.h>

int get_positive_int(void);
int main(void)
{
    int n = get_positive_int();
    // Run a below loop until i is greater than n
    for(int i = 0; i < n; i++)
    {
      // Run if statement on the same row until j is greater than n*2 + i+1
        for(int j=0; j < n*2 + i+1; j++)
        {
            // Create a blank space in exact center of the pyramid
            if(j + i - n == 0 || j + i - n == 1)
                printf(" ");
            //If the value of n-1 is less than the combined value of j and i, or
            //if the value of i and n minus j is less than or equal to zero print #
            else if ( j + i > n - 1 || i + n - j <= 0)
                printf("#");
            else
                //otherwise print " "
                printf(" ");
        }
        printf("\n");
    }
}

Why doesn't the below create a two " " in the center of my pyramid?
if(j + i - n == 0 || j + i - n == 1)
                printf(" ");

And why when I choose a value of 1 for n does the program not print anything?
What is this specific type of thinking/math called? I am having difficulty grasping it and I am not sure how to find information online because I don't know what it is called.
My output is below.
When N = 8
          #######
         #########
        ###########
       #############
      ###############
     #################
    ###################
   #####################

The output I want is.
When N = 8
       #  #
      ##  ##
     ###  ###
    ####  ####
   #####  #####
  ######  ######
 #######  #######
########  ########

When I input a value of 1 I get.

What I want when I input 1 is,
#  #

I'd like to know what specifically I did wrong in order to fix the issue myself, rather than the direct answer if possible.

A: First of all observe that your two for loops both start from 0. Thus at the beginning both i and j are equal to 0. Therefore, since n is a positive integer, both your if and else if clauses are evaluated as false and only the final else gets executed, which is printf(" ");
Now look at your pyramid. Your "pyramid" fills a space with n rows and 2*n + 2 columns. The first loop for (i = 0; i < n; i++) is for the rows, and it's correct, since there are n rows. Your second for loop, however, is faulty. It should be for (int j=0; j < n*2 + 2; j++).
Now when we look at the the i-th row we see that (remembering rows start from 0 because we started counting i from 0), you want to print n-1-i spaces, followed by i+1 # characters followed by 2 spaces, followed by i+1 # characters and finally followed by n-1-i spaces. So the "spaces" are when j < n-1-i (remember j also starts from 0), when j == n and j == n+1 and when j > n+2+i
This can be written as follows using if-else:
if ( j < (n-1-i) || j == n || j == n+1 || j > n+2+i) printf(" ");
else printf("#");

So the final code will look like:
#include <cs50.h>
#include <stdio.h>

int get_positive_int(void);

int main(void)
{
    int n = get_positive_int();

    for(int i = 0; i < n; i++)
    {
        for(int j=0; j < n*2 + 2; j++)
        {
            if ( j < (n-1-i) || j == n || j == n+1 || j > n+2+i) printf(" ");
            else printf("#");
        }
        printf("\n");
    }
}

A: Think about this mathematically. You have slope of -1, so we have j = -i + k. Our formula becomes k = i + j. If we have n = 5:
i j k
0 4 4
1 3 4
2 2 4
3 1 4
5 0 4

n = 6
i j k
0 5 5
1 4 5
2 3 5
3 2 5
4 1 5
5 0 5

so k = n - 1
That is first half, second is even easier, j = i + k, so k = j - i. It is positive slope moved by k. So for n=5
i j k
0 4 4
1 5 4
2 6 4
3 7 4
5 8 4

n = 6
i j k
0 5 5
1 6 5
2 7 5
3 8 5
4 9 5
5 10 5

look at that we have a match in both cases k = n - 1. So our formulas are
j = -i + n - 1 and j = i + n - 1.
Second in both cases we have maximum j at max(i) + k or in other words n - 1 + n - 1 so 2 * n - 2
so:

*

*We got your lines.

*Look closes and you will see how far your j has to go.

Here is the code:
// int get_positive_int(void);
int main(void)
{
    int n = 5; //get_positive_int();
    // Run a below loop until i is greater than n
    for(int i = 0; i < n; i++)
    {
        // Run if statement on the same row until j is greater than n*2 + i+1
        for(int j = 0; j < n * 2 - 1; j++)
        {
            // Create a blank space in exact center of the pyramid
            if (j == n - i - 1 || j == n + i - 1)
                printf("#");
            else
                //otherwise print " "
                printf(".");
        }
        printf("\n");
    }
}

Output:
....#....
...#.#...
..#...#..
.#.....#.
#.......#

Now you can optimize this to trim down number of inner loop execution by 25%, by looking at this. I do not need to go beyond the point where I print my second #, meaning beyond max(j) = j + 1 value of my second formula + 1 is because I still want to be able to go into loop, so we get maximum max(j) = (n + i - 1) + 1.
#include <stdio.h>

// int get_positive_int(void);
int main(void)
{
    int n = 5; //get_positive_int();
    // Run a below loop until i is greater than n
    for(int i = 0; i < n; i++)
    {
        // Run if statement on the same row until j is greater than n*2 + i+1
        for(int j = 0; j < n + i; j++)
        {
            // Create a blank space in exact center of the pyramid
            if (j == n - i - 1 || j == n + i - 1)
                printf("#");
            else
                //otherwise print " "
                printf(".");
        }
        printf("\n");
    }
}

output:
....#
...#.#
..#...#
.#.....#
#.......#

And if you notice, by thinking mathematically about this you save a lot of operations. For example in second for() loop, OP and other answer have more than 1 operations, where this has 1, in if/else both have more than 2 equality statements having, this one has 2.
NOTE: I used . instead of   for demonstration.


text:
Q: Problemas em carregar uma lista de Json no vue.js observe o código Javascript abaixo;
var app = new Vue({
    el:'#app',
    data:{
        bancodedados:[]

    },
    methods:{

    },
    created:function(){
        var self = this;
            self.$http.get('https://swapi.co/api/planets/1/?format=json').then(function(response){
            /*console.log(response); */
            self.bancodedados = response.data;
        });

    }

});

Essa é minha pagina;

                nome
                Title
                Nome

                {{ bancodedado.name }}
                {{ bancodedado.climate }}

O que está acontecendo é que ele está conseguindo carregar todas a lista porém não consigo visualizar como mostra abaixo;

Talves o problema esteja no código html, somente preciso saber como corrigir;
====================================================================
veja o que aparece no meu consoles;
deu esse resultado com esse comando;
console.log(response);

Isso quer dizer que ele consegue carregar os registro do Json!
mas se for com esse comando;
consoles.log(this.bancodedados);
é bem diferente;

A: Voce esta usando errado, voce esta recuperando a resposta assim ... response.data, quando na verdade é response.body
Basta alterar essa linha self.bancodedados = response.response.body;
JSBin

A: Esse url que tens só retorna um objeto. Usa outro que retorne uma array para poderes usar no bancodedados. Esse outro url tem uma array na propriedade results.
Exemplo:

new Vue({
  el: '#app',
  data: {
    bancodedados: []

  },
  methods: {

  },
  created: function() {
    var self = this;
    self.$http.get('https://swapi.co/api/planets/?format=json').then(function(response) {
      self.bancodedados = response.body.results;
    });

  }

});
table {
  width: 100%;
  display: table;
  table-layout: fixed;
}

table td,
table th {
  display: table-cell;
  text-transform: capitalize;
  text-align: center;
  padding: 2px;
}

        Nome
        Title
        Diametro

        {{ bancodedado.name }}
        {{ bancodedado.climate }}
        {{ bancodedado.diameter }} Km


text:
Q: Minimize a non-linear function with two variables Let $g,h \in \mathbb{R}^d$ and $A \in \mathbb{R}^{d \times d}$ symmetric. I am having the following two variable function
$$f(x,y) = \frac{1}{2} g^T\left(A + \frac{xy}{2}I\right)^{-1}g+\frac{x}{6}y^3 \tag{1}$$ with $x\geq 0$, $ y>0$, $g = -\left(A + \frac{xy}{2}I\right)h $ and $h \neq 0$. Let also
$$h(x,y) = - \left(A + \frac{xy}{2}I\right)^{-1} g,\tag{2}$$ where $g$ the actual constant vector.
To minimize $(1)$, I took the first derivative w.r.t. $x$ and $y$, and set them equal to zero, i.e.,
$$\begin{aligned}\partial_x f(x,y)= -\frac{y}{4} g^T\left(A + \frac{xy}{2}I\right)^{-2}g+\frac{y^3}{6} = -\frac{y}{4} ||h(x,y)||^2 + \frac{y^3}{6} = & 0 \Leftrightarrow \\ -\frac{y}{2}\left( \frac{||h(x,y)||^2}{2} - \frac{y^2}{3}\right) = &0\end{aligned}\tag{3}$$
and
$$\begin{aligned} \partial_y f(x,y)= -\frac{x}{4} g^T\left(A + \frac{xy}{2}I\right)^{-2}g+\frac{x}{2}y^2 = -\frac{x}{4} ||h(x,y)||^2 + \frac{xy^2}{2} = 0 & \Leftrightarrow \\  -\frac{x}{2}\left(\frac{||h(x,y)||^2 }{2} - y^2\right) = &0,\end{aligned}\tag{4}$$
where $$g^T\left(A + \frac{xy}{2}I\right)^{-2} g = \left[g^T\left(A + \frac{xy}{2}I\right)^{-1}\right] \left[\left(A + \frac{xy}{2}I\right)^{-1} g\right] = {||h(x,y)||^2} \tag{5}$$ is used.
What bothers me is the optimization procedure. Suppose, for a fixed $x$ we have solved the non-linear equation $||h(x,y)|| = \sqrt{2}/\sqrt{3}y$ to get $y$. Then, given $y$, from $(3)$, $x$ can be either zero or can be computed by solving $||h(x,y)|| = \sqrt{2} y$.
Even taking the derivatives and setting them to zero is an intuitive approach I found the optimization procedure strange enough. Could you please someone give some suggestions on a more appropriate way to solve (1)?
PS: In this case is it more preferable to use an black box root finder?
EDIT1: After @Joe comment I have tried to write the above equations using $u=-\frac{xy}{2}$ and $v=y$. Using this we have
$$f(u,v) = \frac{1}{2} g^T\left(A - u\:I\right)^{-1}g-\frac{uv^2 }{3}, \quad v \neq 0, \quad u \geq 0 \tag{6}$$
$$h(u,v) = - \left(A - u\:I\right)^{-1} g, \quad g \neq 0 \tag{7}$$
$$\partial_u f(u,v) = \frac{1}{2} ||h(u,v)||^2 - \frac{v^2}{3}, \quad h(u,v) \neq 0 \tag{8}$$
$$\partial_v f(u,v) = -\frac{2}{3}uv \tag{9}$$
EDIT2: Using the diagonalization @Joe suggested, i.e.,$A = O\Lambda O^T$ where $\Lambda$ a diagonal and $O$ orthogonal, we can write
$$f(u, v) = \frac{1}{2} ||O(\Lambda -u \:I)^{-1/2}O^Tg||^2 - \frac{1}{3}uv^2 \tag{10} $$.

A: Change variables to $u = -xy/2, v = y$. This co-ordinate transformation is invertible, so it's fine to minimise in $u,v$ and transform back to $x,y$ after. Then you see that $$f(u,v) = g^T(A-uI)^{-1}g/2 - u v^2/3.$$ Note that $\det(A-uI)=0$ whenever $u$ is an eigenvalue of $A$, and hence non invertible for some set of discrete values of $u$.
This means that for general $A$ you should not expect to be able to minimise $f$. For example, let $d=1$. Then $$f(u,v) =\frac{1}{2} \frac{g^2}{A-u} - u v^2/3,$$ which has a simple pole when $u=A$. So this function is unbounded from below and has no minimum.
For $d>1$, it will depend on the geometric multiplicities of your eigenvalues. If your matrix has all eigenvalues of even multiplicity then I believe you will get poles of the form $1/(\lambda-u)^{2n}$, in which case a minimum may exist. If you have any eigenvalues with odd multiplicities then your $f$ would be unbounded from below. So you need to look at the spectrum of eigenvalues of your $A$; most matrices $A$ would produce an $f$ with no minimum.
Edit;
I notice that you have now got $x\ge 0$ and $y>0$, and $A$ symmetric. Symmetric $A$ is diagonalisable, and hence has no second order poles in the expansion of $(A-uI)^{-1}$. However the restrictions on $x$ and $y$ may mean that the poles all fall outside of this region, which would be necessary for a minimum of your function to exist. To make further progress with this problem, it would be necessary to have further information about the spectrum of eigenvalues of $A$. Maybe it would be sufficient to know that they were all positive or negative, although I'd need to think about this.
Diagonalize $A$ with an orthogonal matrix $O$ such that $A=ODO^T$, where $D$ has the eigenvalues $\lambda_i$ of $A$ along its diagonal. Define $w=O^T g$. Then your $f$ can be written as $$f(u,v) = w^T(D-uI)^{-1}w/2 - u v^2/3.$$ Now we can expand the sum because $D$ is diagonal to arrive at $$f(u,v) = \frac{1}{2}\sum_{i=1}^d \frac{w_i^2}{\lambda_i -u} - u v^2/3.$$ It is necessary to know that all of the poles in this expression lie outside of the region which you want to minimise in for a minimum to exist.
Edit2:
Suppose that $A$ has all positive eigenvalues. Now look for points where the gradient of $f$ is 0;
$$\partial_u f =\frac{1}{2}\sum_{i=1}^d \frac{w_i^2}{(\lambda_i -u)^2} - v^2/3$$ and $$ \partial_v f = -2u v/3=0.$$
This is equivalent to a set of simultaneous polynomial equations. The second equation is solved either by $u=0$ or $v=0$. So firstly we see that there are two solutions of the form $$u=0, v =\pm\sqrt{\frac{3}{2}\sum_{i=1}^d \frac{w_i^2}{(\lambda_i)^2}}.$$Based on the fact that you want $y=v>0$, you can throw away the negative square root here.
It is also possible to solve this equation by setting $v=0$, which is different from the 1d case I described in the comments. In that case you would have a polynomial equation to solve, after multiplying through by all of the denominators in the following equation $$\sum_{i=1}^d \frac{w_i^2}{(\lambda_i -u)^2}=0.$$ if you are having trouble understanding this, try setting $d=2$ and then $d=3$, and look at the equation in both cases. Given that you asked for $v>0$ in your question, you may not be interested in this, however this could mean that the minimum of the function lies along $v=0$ and hence no minium exists for $v>0$.
In all cases, solving for $\partial_u f = \partial_v f = 0$ is not a necessary or sufficient condition for $f$ to be minimised at these points; you will need to look at these points and check if they are minima, maxima or saddle points, and also look along the boundaries $u=0$ and $v=0$ in case the function is minimised here.


text:
Q: How to add subView to ViewGroup using RelativeLayout.LayoutParams I wrote a class that extends ViewGroup and override the method as follow:
 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    for(int index = 0; index < getChildCount(); index++){
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            View child = getChildAt(index);
            child.measure(View.MeasureSpec.makeMeasureSpec(width,
                    View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                    .makeMeasureSpec(height, View.MeasureSpec.UNSPECIFIED));
    }
}

When I add subView to this viewGroup as follow:
String word = words[random.nextInt(words.length)];
            RelativeLayout layout = new RelativeLayout(DraggableGridViewSampleActivity.this);
            TextView text = new TextView(DraggableGridViewSampleActivity.this);
            text.setText(word);
            ImageView view = new ImageView(DraggableGridViewSampleActivity.this);
            view.setImageBitmap(getThumb(word));
            layout.addView(view);

            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            layout.addView(text, params);
            dgv.addView(layout);

The effect is like: The textView can't be displayed completely. It seems that the parent view doesn't provide enough space for the textview to display.
How to have the textView displayed completely?

A:
The textView can't be displayed completely. It seems that the parent
  view doesn't provide enough space for the textview to display.

What exactly are you trying to do with the onMeasure method? Right now you're letting the super class handle an initial measure of the children(super.onMeasure) and then you remeasure the children again, this time giving them a MeasureSpec.UNSPECIFIED, basically telling the children they could be as big as they want.
You should always respect the MeasureSpec when you're measuring the children(or the parent should allow scrolling). If the parent says that the children should be AT_MOST 500 px then don't potentially step over this value when measuring the children by giving them a MeasureSpec of UNSPECIFIED.


text:
Q: Facebook Marketing API: create Adcreative with Instagram Video I want to create an ad based on an existing Instagram-Video post. Therefore I already uploaded the video to the /advideos endpoint.
However, now I'm stuck with creating the adcreative. The documentation doesn't give information on how to add the ID of the uploaded video as a parameter to the /adcreative call.
Any suggestions?
This is what my code looks like:

FB.api(
  '/act_2757146414569266/adcreatives',
  'POST',
  {"object_id":"<PAGE_ID>","instagram_user_id":"<IG USER ID>","source_instagram_media_id":"<SRC_MEDIA_ID>","video_data":"{"video_id": "<UPLOADED VIDEO ID>"}"},

  function(response) {
      ...
  }
);

This is what I get back:

{
  "error": {
    "message": "Invalid parameter",
    "type": "OAuthException",
    "code": 100,
    "error_subcode": 1815279,
    "is_transient": false,
    "error_user_title": "Instagram video must be uploaded to Facebook",
    "error_user_msg": "If you want to promote an existing Instagram video, you need to upload it to Facebook first before creating the ad.",
    "fbtrace_id": "AfjvS_BshLJ8P3KlAB2EvJg1"
  }
}


text:
Q: Paragraph returns not being acknowledged in Wordpress Advanced Custom Fields I have a WYSIWYG field setup via the Advanced Custom Fields plugin.
The field itself is displaying on the frontend, but paragraph returns are not being acknowledged.
For example if I write 4 sentences with a return key pressed between each one, the resulting frontend view is just one long line of text.
If I view the backend editor in "Visual" tab I can see the paragraph returns, but if I change tab to "Text" there is no HTML "p" tags in place.
Can anyone suggest a solution?


text:
Q: Primary key column(s) (id) are not columns in this table () I am following the: http://framework.zend.com/manual/en/learning.quickstart.create-model.html.
Keep hitting wall after wall of issues. My current one is the following error:
    An error occurred

Application error

Exception information:

Message: Primary key column(s) (id) are not columns in this table ()

Stack trace:

#0 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Abstract.php(982): Zend_Db_Table_Abstract->_setupPrimaryKey()
#1 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Select.php(100): Zend_Db_Table_Abstract->info()
#2 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Select.php(78): Zend_Db_Table_Select->setTable(Object(Application_Model_DbTable_Guestbook))
#3 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Abstract.php(1018): Zend_Db_Table_Select->__construct(Object(Application_Model_DbTable_Guestbook))
#4 C:\wamp\www\zendtest\quickstart\library\Zend\Db\Table\Abstract.php(1326): Zend_Db_Table_Abstract->select()
#5 C:\wamp\www\zendtest\quickstart\application\models\GuestbookMapper.php(58): Zend_Db_Table_Abstract->fetchAll()
#6 C:\wamp\www\zendtest\quickstart\application\controllers\GuestbookController.php(14): Application_Model_GuestbookMapper->fetchAll()
#7 C:\wamp\www\zendtest\quickstart\library\Zend\Controller\Action.php(516): GuestbookController->indexAction()
#8 C:\wamp\www\zendtest\quickstart\library\Zend\Controller\Dispatcher\Standard.php(295): Zend_Controller_Action->dispatch('indexAction')
#9 C:\wamp\www\zendtest\quickstart\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#10 C:\wamp\www\zendtest\quickstart\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#11 C:\wamp\www\zendtest\quickstart\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#12 C:\wamp\www\zendtest\quickstart\public\index.php(26): Zend_Application->run()
#13 {main}
Request Parameters:

array (
  'controller' => 'guestbook',
  'action' => 'index',
  'module' => 'default',
)

But I am sure my table has a primary key id for table:
CREATE TABLE guestbook (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    email VARCHAR(32) NOT NULL DEFAULT 'noemail@test.com',
    comment TEXT NULL,
    created DATETIME NOT NULL
);

CREATE INDEX "id" ON "guestbook" ("id");

Don't understand why getting error.
How can I see if it is even picking up the right database

A: Zend_Db_Table_Abstract contains a protected property called _primary which defaults to id.
It assumes that id is the table's primary key and is a sequence (auto increment).
Since your table definition says that id is a primary key, you should get rid of the second SQL command that adds an index on the id column.  Since its already a primary key, it is an index.
Delete the table and re-create it using the create table statement you have in your question, just don't do the CREATE INDEX part.  After that you should be able to continue.

A: I think that your SQL schema is incorrect. Try to create table with primary kyy like this:
CREATE TABLE guestbook (
    id INTEGER NOT NULL AUTO_INCREMENT,
    email VARCHAR(32) NOT NULL DEFAULT 'noemail@test.com',
    comment TEXT NULL,
    created DATETIME NOT NULL,
    PRIMARY KEY (id)
);

A: This error might be induced by (accidentally) using md5(null) as the cache ID. Or any other customary values, for that matter, e.g. 1, 0, true, false. However, null is very likely to be the culprit in this context, as it could be produced by an undefined variable.
A fix could be as simple as:
    $cache = Zend_Registry::get('cache');
    $cache->remove(md5(null));

A: I had the same issue. The problem was that database was created in guestbook-dev.db instead of guestbook.db. You can check it by looking into this files. The solution was to change scripts/load.sqlite.php from
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (null === $env) ? 'development' : $env);
to:
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (null === $env) ? 'production' : $env);
and, of course, running the script once again.


text:
Q: how to study for 70-511 TS: Windows Applications Development with Microsoft .NET Framework 4 I'm trying to get certified for 70-511, but I'm low on resources, since there is no offical Microsoft press materials released, and there is a huge leap between the .NET 4 and the .NET 3.5 version of the exam. The .Net 4.0 version heavily discusses WPF technology.
Any ideas?

A: MCTS 70-511 is a combination of both WPF and WinForms. There existed two different tests for .NET Framework 3.5. There exists books  for both (MCTS-70-505 MCTS-70-502) in Microsoft Press. There are also some free questions at www.testmaster.ch, the questions are in German: http://www.testmaster.ch/MCTS-70-511.test
Hope this helps
Some few question available in English too:
http://www.testmaster.ch/MCTS-70-511-EN.test

A: Microsoft is planning to release updated materials for this exam, so if you wait for awhile they will be available.
That said, you can get a pretty good idea of what's on the exam by examining which certifications can be upgraded to it, as well as the detailed test description.
I've personally found experience to be the best preparation for MS cert exams, so I recommend building a few WPF applications if you haven't already done so. Consider OSS or assisting a local non-profit: you help the community and gain skills that help you.

A: MCTS Self-Paced Training Kit (Exam 70-511): Windows Application Development with Microsoft .NET Framework 4

A: i think the better point of start is review of preparation materials what you can view page of microsoft:
http://www.microsoft.com/learning/en/us/exam.aspx?ID=70-511#tab3
In this moment can download one test pdf with questions and correct answers, not are real questions for Microsoft certification but is good point of start.
http://www.64bitprogramlar.com/microsoft-70-511-test-training-premium-14979.html
hope you find it useful!
jmdeveloper


text:
Q: Including dict as value in MongoDB mapReduce emit For a map function, I have the following code that works:
self.url_with_sessions_mapper = Code("""
    function(){
        emit(this.page, {'session':this.session, 'time':this.time});
    }
    """)

But for some reason, this doesn't:
self.url_with_sessions_mapper = Code("""
    function(){
        emit(this.page, {this.session:this.time});
    }
    """)

I get this error message
on namespace test_database.$cmd failed: exception: SyntaxError: Unexpected token.

Why wouldn't the latter syntax work?

A: Turns out the keys in a dictionary ('associative array') are always being interpreted as strings, never as variable names.
To achieve what I was aiming for, the syntax is:
    self.url_with_sessions_mapper = Code("""
        function(){
            var dd = {};
            dd[this.session] = this.time;
            emit(this.page, dd);
        }
        """)


text:
Q: How to create Spinner Action Item in Action Bar Anyone know how to create the submenu with radio buttons like in the screenshot?

A: If you want a submenu with checkable radio buttons you should use something like that:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item android:id="@+id/red"
              android:title="@string/red" />
        <item android:id="@+id/blue"
              android:title="@string/blue" />
    </group>
</menu>

And then in the code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.red:
            return true;
        case R.id.blue:
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}


text:
Q: How do I use a github based laravel project? New to laravel, and web development in general, so pardon if this sounds like a stupid question.
I'm trying to setup a basic laravel framework that has authentication. I came across this: https://github.com/rydurham/Sentinel which on the face of it, it seems to be the right sort of thing that I'm looking for.
There's a few things that I don't understand.

*

*Sentinel: Sentry Implementation for Laravel 4   -   This package is based on my L4withSentry demo repo.

*Laravel 4 with Sentry 2 - Version 2.0 - This is a demo of Sentry    2 integrated with Laravel 4 and Bootstrap 3.0. This repo  is intended    to be for reference only - if you want to use this
code in your own    app I suggest using Sentinel - a Laravel package
based on this repo.

I'm expecting that I should be able to clone the project (item 1 above), and then make a few configuration adjustments and have the basic example up and running.
The part that confuses me is that they seem to be two very different sets of files. For example - the L4withSentry example has a "home.blade.php" in a recognisable Laravel style layout. The "laravel with sentry" (item 2 above) doesn't even have an app directory.
Am I supposed to clone and merge both of them?
I'd be grateful for a few pointers, thanks.

A: If you are starting in Laravel, don't try to make things too easy for you just yet. The best you can do, at least in the very beginning, is to install a Laravel and start doing things your way. You can then install Sentry and do your authentication with it, using your own line of development.
About those two packages: both are packages which use "cartalyst/sentry" to provide authentication via routes, controllers, views and models. Basically you can install it in any Laravel app and have those things done for you. To use them you need first to create a Laravel app and then install one of those packages, here's an example on installing them using Composer:
composer require "rydurham/sentinel":"1.*"    (this is an example for one of them)

Then you have to configure the package, as the readme, to make it work for you.
Those are not applications you can install and work with. There are some other Laravel application bootstrapppers around, but I would not use them, because, as I said, if you are starting, you better understand the concepts of Laravel, or you will end up being lost in something you don't know if it's Laravel or not.


text:
Q: How to consume from a different Kafka topic in each batch of a Spark Streaming job? I am pretty sure that there is no simple way of doing this, but here is my use case:
I have a Spark Streaming job (version 2.1.0) with a 5 second duration for each micro batch.
My goal, is to consume data from 1 different topic at every microbatch interval, of a total 250 Kafka topics. You can take the code bellow as a simple example:
 val groupId:String = "first_group"
 val kafka_servers:String =  "datanode1:9092,datanode2:9092,datanode3:9092"

 val ss:SparkSession = SparkSession.builder().config("spark.streaming.unpersist","true").appName("ConsumerStream_test").getOrCreate()
 val ssc:StreamingContext= new StreamingContext(ss.sparkContext,Duration(5000))

val kafka_parameters:Map[String,Object]=Map(
"bootstrap.servers"       -> kafka_servers,
"key.deserializer"        -> classOf[StringDeserializer],
"value.deserializer"      -> classOf[ByteArrayDeserializer],
"heartbeat.interval.ms"   -> (1000:Integer),
"max.poll.interval.ms"    -> (100:Integer),
"enable.auto.commit"      -> (false: java.lang.Boolean),
"autoOffsetReset"         -> OffsetResetStrategy.EARLIEST,
//"connections.max.idle.ms" -> (5000:Integer),
"group.id"                -> groupId
)

val r = scala.util.Random
val kafka_list_one_topic=List("topic_"+ r.nextInt(250))

val consumer:DStream[ConsumerRecord[String,Array[Byte]]] = KafkaUtils.createDirectStream(ssc, LocationStrategies.PreferBrokers, ConsumerStrategies.
Subscribe[String, Array[Byte]](kafka_list_one_topic , kafka_parameters))

consumer.foreachRDD( eachRDD => {
     // DOING SOMETHING WITH THE DATA...
  })
ssc.start()
ssc.awaitTermination()

But the issue with this approach, is that Spark will only run the initial code (everything before the foreachRDD command) once, in order to create the Kafka consumer DStream, but in the following micro batch, it only runs the "foreachRDD" statement.
As an example, let's say that r.nextInt(250) returned 40. The Spark Streaming job will connect to topic_40 and process its data. But in the next micro batches, it will still connect to topic_40, and ignore all the commands before the foreachRDD statement.
I guess this is expected, since the code before the foreachRDD statement runs only on the Spark driver.
My question is, is there a way that I can do this without having to relaunch a Spark application every 5 seconds?
Thank you.

A: My approach would be really simple, if you want it to be really random and don't care about any other consequences, make the kafka_list_one_topic as a mutable variable and change it in the streaming code.
val r = scala.util.Random
var kafka_list_one_topic=List("topic_"+ r.nextInt(250))

val consumer:DStream[ConsumerRecord[String,Array[Byte]]] =
KafkaUtils.createDirectStream(ssc, LocationStrategies.PreferBrokers,
ConsumerStrategies.
Subscribe[String, Array[Byte]](kafka_list_one_topic , kafka_parameters))

consumer.foreachRDD( eachRDD => {
 // DOING SOMETHING WITH THE DATA...
 kafka_list_one_topic=List("topic_"+ r.nextInt(250))
 })
ssc.start()
ssc.awaitTermination()


text:
Q: Dell Poweredge 2850 with (2) attached Powervault 220s will not boot I have a Dell Poweredge 2850, which has an additional PERC3 PCI RAID controller.  The controller has two Powervault 220s's connected to it, each with 14 143GB drives. (Also has the built in PERC4 controller with the built in drives attached that will function as the boot drive as a RAID 5).
I can see all of the drives in the RAID configuration utility, and I setup 28 logical drives (each with 1 physical disk) so that the OS will see each drive individually.  Going to setup a ZFS pool in Ubuntu.
When the Powervaults are attached via SCSI cable to the server, it will not boot ubuntu or load the installer.  Initially I was trying to install it, and after choosing install from the boot menu I would get a black screen that never changes. If I unplug the SCSI cables to the Powervaults, it boots to the installer just fine with no special boot options.  It even sees all of the logical drives (all 29 of them) when choosing a drive to install to.
I was able to successfully install Ubuntu server 12.04 with the Powervault SCSI cables unplugged. However, when I plug them back in, I get the same black screen issue after GRUB.
Any idea why it isn't booting with the SCSI devices connected? Thanks!


text:
Q: System freezes during boot after failed upgrade I was running an upgrade from Ubuntu 15.04 to 15.10. About 80% of the way through KDE crashed and the system became unresponsive. I restart and now the system hangs during boot and I am unable to drop into the terminal by pressing alt-F4.
If I run recovery mode in order to repair broken packages I get an error: 'Error getting authority: Error initializing authority: Could not connect: No such file of directory (g-io-error-quark, 1). Searching around for this error seems to indicate that I have an invalid mount point defined in /ect/fstab.
If i try to repair the broken packages manually I find that the network is down, so I try to bring the network back up with:
sudo ifup eth0
I get an ip address from the router but then again i get the error:
Error getting authority: Error initializing authority: Could not connect: No such file or directory (g-io-error-quark, 1)
followed by
resolvconf: Error: /run/resolvconf/interface either does not exist or is not a directory
bound to 192.168.1.15 -- renewal in 253997 seconds.
resolvconf: Error: /run/resolvconf/interface either does not exist or is not a directory
grep: /etc/resolv.conf: No such file or directory
However when I run
ls -l /etc/resolv.conf
I can see that the file is present and that I have full read write permissions. Can anyone shed any light onto what has gone wrong?
Thanks.


text:
Q: How do I make an overlay be "erased" with text It's kind of hard to explain, but I want to make a website with a picture as the background, and over the picture a grey overlay. I then want to have some text above the overlay, and where the text is, the grey overlay is removed, so the text is written in the absence of the grey overlay.
I made an example a year ago, with images, but I want to make it in CSS, if it's possible.
Here's the example (sorry for the mess, didn't really know what I was doing back then)
Example Page
Specifically, the text furthest down (most visible) on the page.
I really hope something like this is possible without using images as the text.
Thanks in advance!

A: This is not possible with CSS.  You can do it with SVG though:
Text with image background in svg or css


text:
Q: How can I convert an unstructured string to a dataframe? I have a long string text that I would like to convert to a dataframe to analyze. Please see below for a sample of the data below. I would like the columns to be "Facility", "Street", "City", "Phone", and "Store Hours".
string = AlaskaUSCG Base Ketchikan 1300 Stedman Street  Ketchikan, AK  (907) 228-0250 Mon-Fri 7:30am-5pm | Sat 10am-4pm | Closed Sunday USCG Base Kodiak Albatros Avenue, Building 26 (2nd Floor)  Kodiak, AK  (907) 487-5773 USCG Base Kodiak Albatros Avenue, Building 26 (1st Floor)  Kodiak, AK  (907) 487-5773 Mon-Fri: 7am-9pm | Sat: 9am-9pm |

I have used StringIO to convert it to a dataframe but it converts it into a dataframe with 0 rows and 1000 columns. Instead I would like the columns I mentioned above and rows for each store.
I expect it to look like this with the data populated as rows:
Facility                    Street               City           Phone
Alaska USCG Base Ketchikan  1300 Stedman Street  Ketchikan, AK  (907) 228 0250

A: You may use simple web-scraping techniques, such as bs4 and requests.
import bs4

r = requests.get(URL)
b = bs4.BeautifulSoup(r.text)

addresses = []

for val in b.find_all(name='p'):
  s = list(val.stripped_strings)
  if s and not s[0].startswith('HOURS'): addresses.append(' '.join(s[:-1]))


text:
Q: Cartan decomposition of SO(2n) I am trying to understand the Cartan decomposition theory, on the following example : $G=SO(2n)$, and $K=U(n)$, and I'm interested in the manifold $G/K$ (an hermitian symmetric space).
1) How do we see $U(n)$ as a subgroup of $SO(2n)$ ?
2) Do we have a Cartan decomposition to $G$ ? More precisely do we have for the Lie algebra of $G$ that
$\mathfrak{g} = \mathfrak{k} + \mathfrak{p}$, where $\mathfrak{k}$ is the Lie algebra of $K$, and also the +1 eigenspace of an involution $\theta$ on $\mathfrak{g}$, and $\mathfrak{p}$ is the -1 eigenspace of $\theta$ ?
3) If so, what is $\theta$ is that case? And what is $\mathfrak{p}$ explicitly ?

A: Let $h$ be an hermitian structure on $V=\bf C^n$.  The real part $q$ of $h$ is an euclidian structure on $\bf R^{2n}$$ =V_{\bf R}$, the real vector space underlying $V$. In coordinate, $q((z_1,...z_n)=h(z_1,...z_n)=z_1\bar z_1+...z_n\bar z_n$.
If a $\bf C$-linear map preserve $h$ it is $\bf R$linear and preserves $q$. This proves that $U(n)\subset O(2n)$.
Note that an element of $O(2n)$ is in $U(n)$ iff it is linear as a complex map, in other word  commutes with the complex multiplication $I$ (viewed as a $\bf R$-linear map).
Acting on $M(2n, R)$ the conjugation by $I$, denoted
$i$ and defined by $i(X)= IXI^{-1}$ is linear,  is an involution ($I^2=-Id$ commute with everything), and a group automorphism.
Therefore, the pair $(O(2n), U(n)) $ is a  symmetric pair as $U(n)\subset O(2n)$ is the fixed group of the involution $i$.
To compute the Cartan decomposition, it is enough to compute the set of fixed point of $i$ acting on the Lie algebra $o(2n)$ of antysmmetric $2n$ matrices, or to compute the tangent space of the symmetric space at the point $I$.
One finds that this is the set of antisymmetric $(2n,2n)$ matrice s.t. $ MI+IM=0$, or in block $\left( \begin{array}{cc} A & B \\
B & -A \end{array} \right)$, with $A$ antisymmetric, $B$ symmetric. Here we identiofy $\bf R^{2n}$ and $\bf C^{n}$ via the map $(x_1,...,x_n, y_1,...y_n)\to (x_1+iy_1,...,x_n+iy_n)$, and the matrix of $I$ is $\left( \begin{array}{cc} 0 & -Id \\
Id & 0 \end{array} \right)$.


text:
Q: Is there a way to use .htaccess in php cli? I have setup a folder as a temporary development server thru
$ php -S localhost:8080

Everything is working fine, that is, except the .htaccess settings. I saw from here that .htaccess is used only by apache. Is there a way for php cli to use it ?


text:
Q: Malware code inside pub/index.php I have found a few lines of code inside my pub/index.php file
I am sure that my website is not hacked and this code is added by 1 of the developers. There are a
few developers working on the website. So I am not sure this is added by whom.
But I am trying to understand what this code does and I am not able to understand that completely.
I also tried to check if the functions created here are called in other files using grep but did not find it. Could anyone help me in understanding what actually this code is doing.
This is the code inside pub/index.php
function filterObjectsInDump($data, $simple=false)
{
    $result = '';
    if (is_array($data) || $data instanceof \Magento\Framework\Data\Collection || $data instanceof \ArrayAccess) {
        $result = array();
        foreach ($data as $k=>$v) {
            if ($v instanceof \Magento\Framework\DataObject) {
                $_v = filterObjectsInDump($v->getData());
                array_unshift($_v, spl_object_hash($v));
                array_unshift($_v, get_class($v));
            } elseif ($v instanceof \Magento\Framework\Data\Collection) {
                $_v = filterObjectsInDump($v);
            } elseif (is_array($v)) {
                $_v = filterObjectsInDump($v);
            } elseif (is_object($v)) {
                if (method_exists($v, '__toString') || $v instanceof \Zend_Db_Select) {
                    $_v = get_class($v)." - ".spl_object_hash($v);
                    if (!$simple) $_v .= "\n\n".$v;
                } else {
                    $_v = get_class($v)." - ".spl_object_hash($v);
                    //if (!$simple) $_v .= var_export($v,1);
                }
            } else {
                $_v = $v;
            }
            $result[$k] = $_v;
        }
        if ($data instanceof \Magento\Framework\Data\Collection\AbstractDb) {
            array_unshift($result, $data->getSelect().'');
        }
        if ($data instanceof \Magento\Framework\Data\Collection) {
            array_unshift($result, spl_object_hash($data));
            array_unshift($result, get_class($data));
        }
    } elseif ($data instanceof \Magento\Framework\DataObject) {
        $result = filterObjectsInDump($data->getData());
        array_unshift($result, spl_object_hash($data));
        array_unshift($result, get_class($data));
    } elseif (is_object($data)) {
        if (method_exists($data, '__toString') || $data instanceof \Zend_Db_Select) {
            $result = get_class($data)." - ".spl_object_hash($data);
            if (!$simple) $result .= "\n\n".$data;
        } else {
            $result = get_class($data)." - ".spl_object_hash($data);
            if (!$simple) $result .= var_export($data,1);
        }
    } else {
        $result = $data;
    }
    return $result;
}

function udLog($data, $file)
{
    return _udDump($data, $file, true);
}
function udDump($data, $file)
{
    return _udDump($data, $file, false);
    return _udDumpDumper($data, $file, false);
}
function _udDumpDumper($data, $file)
{
    $cloner = new \Symfony\Component\VarDumper\Cloner\VarCloner();
    $dumper = new \Symfony\Component\VarDumper\Dumper\CliDumper();
    $output = fopen('php://memory', 'r+b');
    if ($data instanceof \Zend_Db_Select) {
        $data = "$data";
    }
    $dumper->dump($cloner->cloneVar($data), $output);
    $output = stream_get_contents($output, -1, 0);
    file_put_contents(BP.'/var/log/'.$file, $output, FILE_APPEND);
}

function _udDump($data, $file, $simple=false)
{
    $_dtlIps = array('127.0.0.1','81.162.236.168','10.0.2.2');
    $xff = array_map('trim', explode(',', @$_SERVER['HTTP_X_FORWARDED_FOR']));
    ob_start();
    $filtered = filterObjectsInDump($data, $simple);
    is_array($filtered) ? print_r($filtered) : var_dump($filtered);
    //Mage::log(ob_get_clean(), null, $file);
    file_put_contents(BP.'/var/log/'.$file, ob_get_clean(), FILE_APPEND);
}