问:
CSS Grid min-content not working properly on Chrome
I am creating a simple two columns layout with grid. One contains image and the second one only few paragraphs. I want to set images height same as second div with text. My template-rows property is set to min-content which works perfect on Firefox but on Chrome my image is expanding to all its height.

Display this example in two different browsers to see the difference.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: min-content;
  width: 1000px;
  margin: 0 auto;
}

img {
  width: 100%;
  max-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <img src="https://m.media-amazon.com/images/M/MV5BNjgwNjkwOWYtYmM3My00NzI1LTk5OGItYWY0OTMyZTY4OTg2XkEyXkFqcGdeQXVyODk4OTc3MTY@._V1_.jpg" alt="">
  <div>
    <p>The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.</p>
                   <p>The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.</p>
  </div>
</div></code>```

答:
Instead of min-content, wrap the img inside a div and consider the trick height: 0;min-height:100%;

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  margin: 0 auto;
}

img {
  width: 100%;
  height: 0;
  min-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>
    <img src="https://m.media-amazon.com/images/M/MV5BNjgwNjkwOWYtYmM3My00NzI1LTk5OGItYWY0OTMyZTY4OTg2XkEyXkFqcGdeQXVyODk4OTc3MTY@._V1_.jpg" alt=""></div>
  <div>
    <p>The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy
      veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.</p>
    <p>The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy
      veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.</p>
  </div>
</div></code>```

Related: How can you set the height of an outer div to always be equal to a particular inner div?

Body:
I am creating a simple two columns layout with grid. One contains image and the second one only few paragraphs. I want to set images height same as second div with text. My template-rows property is set to min-content which works perfect on Firefox but on Chrome my image is expanding to all its height.

Display this example in two different browsers to see the difference.

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: min-content;
  width: 1000px;
  margin: 0 auto;
}

img {
  width: 100%;
  max-height: 100%;
}

The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.

The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.

Body:
Instead of min-content, wrap the img inside a div and consider the trick height: 0;min-height:100%;

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  margin: 0 auto;
}

img {
  width: 100%;
  height: 0;
  min-height: 100%;
}

<div class="grid">
  <div>
    <img src="https://m.media-amazon.com/images/M/MV5BNjgwNjkwOWYtYmM3My00NzI1LTk5OGItYWY0OTMyZTY4OTg2XkEyXkFqcGdeQXVyODk4OTc3MTY@._V1_.jpg" alt=""></div>
  <div>
    <p>The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy
      veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.</p>
    <p>The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy
      veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.</p>
  </div>
</div>

Related: How can you set the height of an outer div to always be equal to a particular inner div?


来源: stackexchange

问:
MacOS Catalina Adobe Premiere Operation Not Permitted
I have a problem with my Adobe Premiere CC 2019 with MacOS Catalina.

the screenshot is below :
enter image description here

I have give Full Disk Access for Terminal & Finder, but yet still occured the same problem!
Is there anyone can help me with this problem?
I've beeen stuck here for 5 hours without any solution :(

答:
Have you attempted to install with sudo permissions yet?

If you haven't or aren't familiar with it, then here's a guide on how to set that up.

ContentLicense: CC BY-SA 4.0


问:
PHP: cut out ALL sequences within a string until dot
I have a string in PHP 5.6 that contains sequence(s) I need to extract into a new string. But we struggle with the code as I am new to php.

Example: ($searchstring)
"We got an example here which covers it to 99% all and this sentence is already part of it. Because this is the first Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. This proper Markerword: contains more of it multiple times and in caotic characters. If the Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword. And if there are other sentences or even just words inbetween or at the end or before we ignore them all."

The seqeunce is somewhere inbetween and there could be only 1 time such a sequence or multiple times like 2 times or 3 times or 5 times...

The sequence itself comes always with a variable length and with diffrent words/numbers. But it begins and ends with the same pattern which is:
Start: "Markerword:"
End: "." (first dot after "Markerword:")
Inbetween the sequences we need to extract there are no full stops.

I got a code but it only extracts one sequence (the last one) from the string. But if there are more they are skipped/not taken.

Code I have which does not work properly 100%:

```<code>    $resultstring = false;
if (strpos($searchstring, "Markerword:") !== false){
        preg_match('/(Markerword:([^.]+))/', $searchstring, $matches);
            $resultstring= $matches[0];
            $stopPos = strpos($resultstring, "  ");
            if ($stopPos !== false) {
            $resultstring= substr($resultstring,0,$stopPos + 1);
                }
            }
</code>```

How can I take out all of them that they are like this?

Desired outcome from the example above:
Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. Markerword: contains more of it multiple times and in caotic characters. Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword."

答:
```<code>$searchstring = "We got an example here which covers it to 99% all and this sentence is already part of it. Because this is the first Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. This proper Markerword: contains more of it multiple times and in caotic characters. If the Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword. And if there are other sentences or even just words inbetween or at the end or before we ignore them all.";

preg_match_all('/\bMarkerword:[^.]+\./', $searchstring, $m);
$result = implode(' ', $m[0]);
echo $result;
</code>```

Output:

```<code>Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. Markerword: contains more of it multiple times and in caotic characters. Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword.
</code>```

Regex explanation

Body:
I have a string in PHP 5.6 that contains sequence(s) I need to extract into a new string. But we struggle with the code as I am new to php.

Example: ($searchstring)
"We got an example here which covers it to 99% all and this sentence is already part of it. Because this is the first Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. This proper Markerword: contains more of it multiple times and in caotic characters. If the Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword. And if there are other sentences or even just words inbetween or at the end or before we ignore them all."

The seqeunce is somewhere inbetween and there could be only 1 time such a sequence or multiple times like 2 times or 3 times or 5 times...

The sequence itself comes always with a variable length and with diffrent words/numbers. But it begins and ends with the same pattern which is:
Start: "Markerword:"
End: "." (first dot after "Markerword:")
Inbetween the sequences we need to extract there are no full stops.

I got a code but it only extracts one sequence (the last one) from the string. But if there are more they are skipped/not taken.

Code I have which does not work properly 100%:

    $resultstring = false;
if (strpos($searchstring, "Markerword:") !== false){
        preg_match('/(Markerword:([^.]+))/', $searchstring, $matches);
            $resultstring= $matches[0];
            $stopPos = strpos($resultstring, "  ");
            if ($stopPos !== false) {
            $resultstring= substr($resultstring,0,$stopPos + 1);
                }
            }

How can I take out all of them that they are like this?

Desired outcome from the example above:
Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. Markerword: contains more of it multiple times and in caotic characters. Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword."

Body:
$searchstring = "We got an example here which covers it to 99% all and this sentence is already part of it. Because this is the first Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. This proper Markerword: contains more of it multiple times and in caotic characters. If the Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword. And if there are other sentences or even just words inbetween or at the end or before we ignore them all.";

preg_match_all('/\bMarkerword:[^.]+\./', $searchstring, $m);
$result = implode(' ', $m[0]);
echo $result;

Output:

Markerword: with a lot of other things like commata, special characters ä, ü, ß or % and more in it. Markerword: contains more of it multiple times and in caotic characters. Markerword: contains this, then cut the whole sequence out - until the first dot after that markerword.

Regex explanation


问:
How to solve linear programming model in R
I need to solve the following microeconomic problem:

I have six assets I can produce (asset 1 - 6) across five years (2011 - 2015).

Each asset can only be produced during one year.

Each asset must be produced in my five year period.

Production is not mutually exclusive; I can produce more than one good in a year without affecting the production of either.

Each asset has a fixed cost of production equal to 30.

I must have non-negative profit in each year; revenues must be at least 30.

Below is a matrix representing my potential revenue for producing each asset (i) in a given year (j).

```<code>          2011 2012 2013 2014 2015
  Asset1    35* 37  39  42  45
  Asset2    16  17  18  19  20*
  Asset3    125 130 136*139 144
  Asset4    15  27  29  30* 33
  Asset5    14  43* 46  50  52
  Asset6    5   7   8   10  11*
</code>```

The asterisks (*) represent what should be the optimal solution set.

How can I use R to solve for the production plan that maximizes my revenue (and therefore profit) subject to the constraints outlined.  My output should be a similar 6x5 matrix of 0's and 1's, where 1's represent choosing to produce a good in a given year.

答:
This is a classic problem, and one that needs to be reformulated.

Start by reformulating your problem

```<code>Max( sum_[i,t] (pi_[i,t] - C_[i,t]) * x_[i,t])
Sd.
sum_t x_[i,t] = 1 [ for all i ]
sum_i x_[i,t] >= 30 [ for all t ]
x_[i,t] >= 0 [for all i, t]
</code>```

In the lpSolve package the maximization problem is given in a linear representation, eg. in non-matrix format. Lets start by making a vector representing our x_[i,t]. For ease let's name it (although this is not used), just so we can keep track.

```<code>n <- 6
t <- 5
#x ordered by column.
x <- c(35, 16, 125, 15, 14, 5, 37, 17, 130, 27, 43, 7, 39, 18, 136, 29, 46, 8, 42, 19, 139, 30, 50, 10, 45, 20, 144, 33, 52, 11)
# if x is matrix use:
# x <- as.vector(x)
names(x) <- paste0('x_[', seq(n), ',', rep(seq(t), each = n), ']')
head(x, n * 2)
x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2] x_[2,2] x_[3,2] x_[4,2] x_[5,2] x_[6,2]
     35      16     125      15      14       5      37      17     130      27      43       7
length(x)
[1] 30
</code>```

Now now we need to create our conditions. Starting with the first condition

```<code>sum_t x_[i,t] = 1 [ for all i ]
</code>```

we can create this rather simply. The thing to watch out for here, is that the dimension has to be right. We have a vector of length 30, so we'll need our conditions matrix to have 30 columns. In addition we have 6 assets, so we'll need 6 rows for this condition. Again lets name the rows and columns to keep track ourself.

```<code>cond1 <- matrix(0, ncol = t * n,
                nrow = n,
                dimnames = list(paste0('x_[', seq(n), ',t]'),
                                names(x)))
cond1[, seq(n + 1)]
        x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2]
x_[1,t]       0       0       0       0       0       0       0
x_[2,t]       0       0       0       0       0       0       0
x_[3,t]       0       0       0       0       0       0       0
x_[4,t]       0       0       0       0       0       0       0
x_[5,t]       0       0       0       0       0       0       0
x_[6,t]       0       0       0       0       0       0       0
</code>```

Next we fill our the correct fields. x_[1,1] + x[1, 2] + ... = 1 and x_[2,1] + x_[2,2] + ... = 1 and so forth. Using a for loop is the simplest for this problem

```<code>for(i in seq(n)){
  cond1[i, seq(i, 30, n)] <- 1
}
cond1[, seq(n + 1)]
        x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2]
x_[1,t]       1       0       0       0       0       0       1
x_[2,t]       0       1       0       0       0       0       0
x_[3,t]       0       0       1       0       0       0       0
x_[4,t]       0       0       0       1       0       0       0
x_[5,t]       0       0       0       0       1       0       0
x_[6,t]       0       0       0       0       0       1       0
</code>```

We still have to create the RHS and specify direction but I'll wait with this for now.

So next lets create our matrix for the second condition

```<code>sum_i x_[i,t] >= 30 [ for all t ]
</code>```

The process for this one is very similar, but now we need a row for each period, so the dimension of the matrix is 5x30. The main difference here, is we need to insert the values of x_[i, t]

```<code>cond2 <- matrix(0, ncol = t * n,
                nrow = t,
                dimnames = list(paste0('t=', seq(t)),
                                names(x)))
for(i in seq(t)){
   cond2[i, seq(n) + n * (i - 1)] <- x[seq(n) + n * (i - 1)]
}
cond2[, seq(1, n * t, n)]
    x_[1,1] x_[1,2] x_[1,3] x_[1,4] x_[1,5]
t=1      35       0       0       0       0
t=2       0      37       0       0       0
t=3       0       0      39       0       0
t=4       0       0       0      42       0
t=5       0       0       0       0      45
</code>```

Note that I'm printing the result for x_[1, t] to illustrate we've got it right.

Last we have the final condition. For this we note the ?lpSolve::lp has an argument all.bin, and reading this, it states

Logical: should all variables be binary? Default: FALSE.

So since all variables are either 1 or 0, we simply set this value to TRUE. Before continuing lets combine our conditions into one matrix

```<code>cond <- rbind(cond1, cond2)
</code>```

Now both the RHS and the direction are simply taken from the 2 conditions. From the documentation on the const.dir argument

Vector of character strings giving the direction of the constraint: each value should be one of "<," "<=," "=," "==," ">," or ">=". (In each pair the two values are identical.)

In our conditions we have 6 rows representing the first condition, and rows represeting condition 2. Thus we need n (6) times == and t (5) times >=.

```<code>cond_dir <- c(rep('==', n), rep('>=', t))
</code>```

The RHS is created in a similar fashion

```<code>RHS <- c(rep(1, n), rep(30, t))
</code>```

And that's it! Now we're ready to solve our problem using the lpSolve::lp function.

```<code>sol = lpSolve::lp(direction = 'max',
                  objective.in = x,
                  const.mat = cond,
                  const.dir = cond_dir,
                  const.rhs = RHS,
                  all.bin = TRUE)
sol$objval
[1] 275
</code>```

The weights for the solution are stored in sol$solution

```<code>names(sol$solution) <- names(x)
sol$solution
x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2] x_[2,2] x_[3,2] x_[4,2] x_[5,2] x_[6,2] x_[1,3] x_[2,3] x_[3,3]
      1       0       0       0       0       0       0       0       0       0       1       0       0       0       1
x_[4,3] x_[5,3] x_[6,3] x_[1,4] x_[2,4] x_[3,4] x_[4,4] x_[5,4] x_[6,4] x_[1,5] x_[2,5] x_[3,5] x_[4,5] x_[5,5] x_[6,5]
      0       0       0       0       0       0       1       0       0       0       1       0       0       0       1
matrix(sol$solution,
       ncol = t,
       dimnames = list(rownames(cond1),
                       rownames(cond2)))
        t=1 t=2 t=3 t=4 t=5
x_[1,t]   1   0   0   0   0
x_[2,t]   0   0   0   0   1
x_[3,t]   0   0   1   0   0
x_[4,t]   0   0   0   1   0
x_[5,t]   0   1   0   0   0
x_[6,t]   0   0   0   0   1
</code>```

Which we quickly see is the correct solution. :-)

Side note on costs

One may have noticed "Where the hell did the costs go?". In this specific case, costs are fixed and not very interesting. This means we can ignore these during the calculations because we know the total cost is going to be 30 * 6 = 180 (which has to be substracted from the objective value). However it is not uncommon that costs depend on various factors, and might affect the optimal solution. For illustration, I'll include how we could incorporate costs in this example here.

First we'll have to extend our objective vector to incorporate the costs for each product at each period

```<code>Fixed_C <- -30
x <- c(x, rep(Fixed_C, n * t))
</code>```

Next we'll add a pseudo-constraint

```<code>x_[i,t] - C_[i,t] = 0 [for all i, t]
</code>```

This constraint ensures that if x_[i,t] = 1 then the relevant cost is added to the problem. There's 2 ways to create this constraint. The first is to have a matrix with n * t rows, one for each cost and period. Alternatively we can use our first constraint and actually live with only a single constrant

```<code>sum_[i,t] x_[i,t] - C_[i,t] = 0
</code>```

because our first constraint makes sure x[1, 1] != x[1, 2]. So our third constraint becomes

```<code>cond3 <- c(rep(1, n * t), rep(-1, n * t))
</code>```

Lastly we have to extend our RHS and condition 1 and 2 matrices. Simply add 0's to the condition matrices to make the dimensions fit.

```<code>cond1 <- cbind(cond1, matrix(0, nrow = n, ncol = n * t))
cond2 <- cbind(cond2, matrix(0, nrow = n, ncol = n * t))
cond <- rbind(cond1, cond2, cond3)
cond_dir <- c(cond_dir, '==')
RHS <- c(RHS, 0)
</code>```

And now we can once again find the optimal solution using lpSolve::lp

```<code>solC = lpSolve::lp(direction = 'max',
                  objective.in = x,
                  const.mat = cond,
                  const.dir = cond_dir,
                  const.rhs = RHS,
                  all.bin = TRUE)
solC$objval
[1] 95
</code>```

which is equal to our previous value 275 minus our fixed costs Fixed_C * n = 180.

Body:
I need to solve the following microeconomic problem:

I have six assets I can produce (asset 1 - 6) across five years (2011 - 2015).

Each asset can only be produced during one year.

Each asset must be produced in my five year period.

Production is not mutually exclusive; I can produce more than one good in a year without affecting the production of either.

Each asset has a fixed cost of production equal to 30.

I must have non-negative profit in each year; revenues must be at least 30.

Below is a matrix representing my potential revenue for producing each asset (i) in a given year (j).

          2011 2012 2013 2014 2015
  Asset1    35* 37  39  42  45
  Asset2    16  17  18  19  20*
  Asset3    125 130 136*139 144
  Asset4    15  27  29  30* 33
  Asset5    14  43* 46  50  52
  Asset6    5   7   8   10  11*

The asterisks (*) represent what should be the optimal solution set.

How can I use R to solve for the production plan that maximizes my revenue (and therefore profit) subject to the constraints outlined.  My output should be a similar 6x5 matrix of 0's and 1's, where 1's represent choosing to produce a good in a given year.

Body:
This is a classic problem, and one that needs to be reformulated.

Start by reformulating your problem

Max( sum_[i,t] (pi_[i,t] - C_[i,t]) * x_[i,t])
Sd.
sum_t x_[i,t] = 1 [ for all i ]
sum_i x_[i,t] >= 30 [ for all t ]
x_[i,t] >= 0 [for all i, t]

In the lpSolve package the maximization problem is given in a linear representation, eg. in non-matrix format. Lets start by making a vector representing our x_[i,t]. For ease let's name it (although this is not used), just so we can keep track.

n <- 6
t <- 5
#x ordered by column.
x <- c(35, 16, 125, 15, 14, 5, 37, 17, 130, 27, 43, 7, 39, 18, 136, 29, 46, 8, 42, 19, 139, 30, 50, 10, 45, 20, 144, 33, 52, 11)
# if x is matrix use:
# x <- as.vector(x)
names(x) <- paste0('x_[', seq(n), ',', rep(seq(t), each = n), ']')
head(x, n * 2)
x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2] x_[2,2] x_[3,2] x_[4,2] x_[5,2] x_[6,2]
     35      16     125      15      14       5      37      17     130      27      43       7
length(x)
[1] 30

Now now we need to create our conditions. Starting with the first condition

sum_t x_[i,t] = 1 [ for all i ]

we can create this rather simply. The thing to watch out for here, is that the dimension has to be right. We have a vector of length 30, so we'll need our conditions matrix to have 30 columns. In addition we have 6 assets, so we'll need 6 rows for this condition. Again lets name the rows and columns to keep track ourself.

cond1 <- matrix(0, ncol = t * n,
                nrow = n,
                dimnames = list(paste0('x_[', seq(n), ',t]'),
                                names(x)))
cond1[, seq(n + 1)]
        x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2]
x_[1,t]       0       0       0       0       0       0       0
x_[2,t]       0       0       0       0       0       0       0
x_[3,t]       0       0       0       0       0       0       0
x_[4,t]       0       0       0       0       0       0       0
x_[5,t]       0       0       0       0       0       0       0
x_[6,t]       0       0       0       0       0       0       0

Next we fill our the correct fields. x_[1,1] + x[1, 2] + ... = 1 and x_[2,1] + x_[2,2] + ... = 1 and so forth. Using a for loop is the simplest for this problem

for(i in seq(n)){
  cond1[i, seq(i, 30, n)] <- 1
}
cond1[, seq(n + 1)]
        x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2]
x_[1,t]       1       0       0       0       0       0       1
x_[2,t]       0       1       0       0       0       0       0
x_[3,t]       0       0       1       0       0       0       0
x_[4,t]       0       0       0       1       0       0       0
x_[5,t]       0       0       0       0       1       0       0
x_[6,t]       0       0       0       0       0       1       0

We still have to create the RHS and specify direction but I'll wait with this for now.

So next lets create our matrix for the second condition

sum_i x_[i,t] >= 30 [ for all t ]

The process for this one is very similar, but now we need a row for each period, so the dimension of the matrix is 5x30. The main difference here, is we need to insert the values of x_[i, t]

cond2 <- matrix(0, ncol = t * n,
                nrow = t,
                dimnames = list(paste0('t=', seq(t)),
                                names(x)))
for(i in seq(t)){
   cond2[i, seq(n) + n * (i - 1)] <- x[seq(n) + n * (i - 1)]
}
cond2[, seq(1, n * t, n)]
    x_[1,1] x_[1,2] x_[1,3] x_[1,4] x_[1,5]
t=1      35       0       0       0       0
t=2       0      37       0       0       0
t=3       0       0      39       0       0
t=4       0       0       0      42       0
t=5       0       0       0       0      45

Note that I'm printing the result for x_[1, t] to illustrate we've got it right.

Last we have the final condition. For this we note the ?lpSolve::lp has an argument all.bin, and reading this, it states

Logical: should all variables be binary? Default: FALSE.

So since all variables are either 1 or 0, we simply set this value to TRUE. Before continuing lets combine our conditions into one matrix

cond <- rbind(cond1, cond2)

Now both the RHS and the direction are simply taken from the 2 conditions. From the documentation on the const.dir argument

Vector of character strings giving the direction of the constraint: each value should be one of "<," "<=," "=," "==," ">," or ">=". (In each pair the two values are identical.)

In our conditions we have 6 rows representing the first condition, and rows represeting condition 2. Thus we need n (6) times == and t (5) times >=.

cond_dir <- c(rep('==', n), rep('>=', t))

The RHS is created in a similar fashion

RHS <- c(rep(1, n), rep(30, t))

And that's it! Now we're ready to solve our problem using the lpSolve::lp function.

sol = lpSolve::lp(direction = 'max',
                  objective.in = x,
                  const.mat = cond,
                  const.dir = cond_dir,
                  const.rhs = RHS,
                  all.bin = TRUE)
sol$objval
[1] 275

The weights for the solution are stored in sol$solution

names(sol$solution) <- names(x)
sol$solution
x_[1,1] x_[2,1] x_[3,1] x_[4,1] x_[5,1] x_[6,1] x_[1,2] x_[2,2] x_[3,2] x_[4,2] x_[5,2] x_[6,2] x_[1,3] x_[2,3] x_[3,3]
      1       0       0       0       0       0       0       0       0       0       1       0       0       0       1
x_[4,3] x_[5,3] x_[6,3] x_[1,4] x_[2,4] x_[3,4] x_[4,4] x_[5,4] x_[6,4] x_[1,5] x_[2,5] x_[3,5] x_[4,5] x_[5,5] x_[6,5]
      0       0       0       0       0       0       1       0       0       0       1       0       0       0       1
matrix(sol$solution,
       ncol = t,
       dimnames = list(rownames(cond1),
                       rownames(cond2)))
        t=1 t=2 t=3 t=4 t=5
x_[1,t]   1   0   0   0   0
x_[2,t]   0   0   0   0   1
x_[3,t]   0   0   1   0   0
x_[4,t]   0   0   0   1   0
x_[5,t]   0   1   0   0   0
x_[6,t]   0   0   0   0   1

Which we quickly see is the correct solution. :-)

Side note on costs

One may have noticed "Where the hell did the costs go?". In this specific case, costs are fixed and not very interesting. This means we can ignore these during the calculations because we know the total cost is going to be 30 * 6 = 180 (which has to be substracted from the objective value). However it is not uncommon that costs depend on various factors, and might affect the optimal solution. For illustration, I'll include how we could incorporate costs in this example here.

First we'll have to extend our objective vector to incorporate the costs for each product at each period

Fixed_C <- -30
x <- c(x, rep(Fixed_C, n * t))

Next we'll add a pseudo-constraint

x_[i,t] - C_[i,t] = 0 [for all i, t]

This constraint ensures that if x_[i,t] = 1 then the relevant cost is added to the problem. There's 2 ways to create this constraint. The first is to have a matrix with n * t rows, one for each cost and period. Alternatively we can use our first constraint and actually live with only a single constrant

sum_[i,t] x_[i,t] - C_[i,t] = 0

because our first constraint makes sure x[1, 1] != x[1, 2]. So our third constraint becomes

cond3 <- c(rep(1, n * t), rep(-1, n * t))

Lastly we have to extend our RHS and condition 1 and 2 matrices. Simply add 0's to the condition matrices to make the dimensions fit.

cond1 <- cbind(cond1, matrix(0, nrow = n, ncol = n * t))
cond2 <- cbind(cond2, matrix(0, nrow = n, ncol = n * t))
cond <- rbind(cond1, cond2, cond3)
cond_dir <- c(cond_dir, '==')
RHS <- c(RHS, 0)

And now we can once again find the optimal solution using lpSolve::lp

solC = lpSolve::lp(direction = 'max',
                  objective.in = x,
                  const.mat = cond,
                  const.dir = cond_dir,
                  const.rhs = RHS,
                  all.bin = TRUE)
solC$objval
[1] 95

which is equal to our previous value 275 minus our fixed costs Fixed_C * n = 180.


问:
How to get all ids to pouchdb's documents using node.js
i wanted to know how to get all the ids of a certain database from pouchdb using node.js
this is my try at it but as you can guess it hasn't been working, specifically i need to get all the ids into an array of numbers, only the ids nothing else. Im kind of a beginner to javascript and databases</p>

```<code>var PouchDB = require('PouchDB');
var db = new PouchDB('mes_iab_db');

db.allDocs({
   include_docs: true,
   attachments: true
 }).then(function (result) {
   console.log(result)
   var new1 = JSON.stringify(result.rows);
   console.log(new1);
   new1.filter(id=>{id=_id;})
 }).catch(function (err) {
   console.log(err);
 });
</code>```

答:
Try something like this</p>

```<code>db.allDocs({
  include_docs: true,
  attachments: true,
})
  .then(function (result) {
    if (result.rows && result.rows.length) {
      return result.rows.map(({ doc }) => doc._id);
    }
    return [];
  })
  .then(console.log)
  .catch(function (err) {
    console.log(err);
  });
</code>```

Body:
i wanted to know how to get all the ids of a certain database from pouchdb using node.js
this is my try at it but as you can guess it hasn't been working, specifically i need to get all the ids into an array of numbers, only the ids nothing else. Im kind of a beginner to javascript and databases

var PouchDB = require('PouchDB');
var db = new PouchDB('mes_iab_db');

db.allDocs({
   include_docs: true,
   attachments: true
 }).then(function (result) {
   console.log(result)
   var new1 = JSON.stringify(result.rows);
   console.log(new1);
   new1.filter(id=>{id=_id;})
 }).catch(function (err) {
   console.log(err);
 });

Body:
Try something like this

db.allDocs({
  include_docs: true,
  attachments: true,
})
  .then(function (result) {
    if (result.rows && result.rows.length) {
      return result.rows.map(({ doc }) => doc._id);
    }
    return [];
  })
  .then(console.log)
  .catch(function (err) {
    console.log(err);
  });


问:
How can I connect my ionic app to two different API URLS in the same page? how to pass the id from the first url's data to the second url?
I'm building an ionic recipe app, the home page is calling a list of recipes names, ids and images using an API url which is www.forexample/recipeslist.com.
The thing that I want is, I need to write smth which works as the following:
When I press on any recipe name from that same page, I want it to direct the user to a page that contains that recipes details such as the ingredients, methods, etc ..
These details will be called from a url named www.forexample.com/recipedetails/{id}
So i want it to take the clicked recipe's ID and add it to that url.
How can I do it? How can I pass the ID from the first url's data to the second URL? Please help:(

Here's my .service file:

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

const apiUrl = "https://forexample.com/recipeslist";
@Injectable({
  providedIn: 'root'
})
export class ApiLandingRecipesService {

  constructor(private http: HttpClient) { }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError('Something bad happened; please try again later.');
  }

  private extractData(res: Response) {
    let body = res;
    return body || [] ; }

  getDataUser(): Observable<any> {
    return this.http.get(apiUrl, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }

}
</code>```

Here's my homepage.ts file:

```<code>import { ApiLandingRecipesService} from '../api-landing-recipes.service'

@Component({
  selector: 'app-landing-page',
  templateUrl: './landing-page.page.html',
  styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
  datauser: any[];
  constructor( public api: ApiLandingRecipesService) { }

  ngOnInit() {
    this.getDataUser();
  }
  async getDataUser() {
    await this.api.getDataUser()
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }
</code>```

Here's my homepage.html file:

```<code><ion-card-header *ngFor="let data of datauser">
<p> {{data.recipename}} </p>
</ion-card-header>
</code>```

答:
First change your api url to :

```<code>const apiUrl = "https://forexample.com/";
</code>```

Second change this:

```<code>getDataUser(uri): Observable<any> {
    return this.http.get(apiUrl + uri, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }
</code>```

Third change this in the main recipies page:

```<code>ngOnInit() {
    this.getDataUser();
  }

async getDataUser() {
    await this.api.getDataUser('recipeslist')
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }
</code>```

Now in html of recepies change to:

```<code><ion-card-header *ngFor="let data of datauser" routerLink="/detailspage/{{data.recipeid}}">
<p> {{data.recipename}} </p>
</ion-card-header>
</code>```

Now in app-routing.module.ts add this:

```<code>{ path: 'details/:id', loadChildren: ...' }
</code>```

Now in details page :

```<code>import { ActivatedRoute } from '@angular/router';
recordId = null;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
    this.recordId = this.activatedRoute.snapshot.paramMap.get('id');
    this.getDataUser(this.recordId);
  }

async getDataUser(recordId) {
    await this.api.getDataUser('recipeslist/' + recordId)
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }
</code>```

I put different names of pages since i didn't understand your class naming for which is main page (home or receipies or landing) but the way i wrote coupd be clearer for you.

Body:
I'm building an ionic recipe app, the home page is calling a list of recipes names, ids and images using an API url which is www.forexample/recipeslist.com.
The thing that I want is, I need to write smth which works as the following:
When I press on any recipe name from that same page, I want it to direct the user to a page that contains that recipes details such as the ingredients, methods, etc ..
These details will be called from a url named www.forexample.com/recipedetails/{id}
So i want it to take the clicked recipe's ID and add it to that url.
How can I do it? How can I pass the ID from the first url's data to the second URL? Please help:(

Here's my .service file:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

const apiUrl = "https://forexample.com/recipeslist";
@Injectable({
  providedIn: 'root'
})
export class ApiLandingRecipesService {

  constructor(private http: HttpClient) { }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError('Something bad happened; please try again later.');
  }

  private extractData(res: Response) {
    let body = res;
    return body || [] ; }

  getDataUser(): Observable<any> {
    return this.http.get(apiUrl, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }

}

Here's my homepage.ts file:

import { ApiLandingRecipesService} from '../api-landing-recipes.service'

@Component({
  selector: 'app-landing-page',
  templateUrl: './landing-page.page.html',
  styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
  datauser: any[];
  constructor( public api: ApiLandingRecipesService) { }

  ngOnInit() {
    this.getDataUser();
  }
  async getDataUser() {
    await this.api.getDataUser()
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

Here's my homepage.html file:

<ion-card-header *ngFor="let data of datauser">

 {{data.recipename}}

</ion-card-header>

Body:
First change your api url to :

const apiUrl = "https://forexample.com/";

Second change this:

getDataUser(uri): Observable<any> {
    return this.http.get(apiUrl + uri, httpOptions).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }

Third change this in the main recipies page:

ngOnInit() {
    this.getDataUser();
  }

async getDataUser() {
    await this.api.getDataUser('recipeslist')
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

Now in html of recepies change to:

<ion-card-header *ngFor="let data of datauser" routerLink="/detailspage/{{data.recipeid}}">
<p> {{data.recipename}} </p>
</ion-card-header>

Now in app-routing.module.ts add this:

{ path: 'details/:id', loadChildren: ...' }

Now in details page :

import { ActivatedRoute } from '@angular/router';
recordId = null;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
    this.recordId = this.activatedRoute.snapshot.paramMap.get('id');
    this.getDataUser(this.recordId);
  }

async getDataUser(recordId) {
    await this.api.getDataUser('recipeslist/' + recordId)
      .subscribe(res => {
        console.log(res);
        this.datauser =res;
        console.log(this.datauser);
      }, err => {
        console.log(err);
      });
  }

I put different names of pages since i didn't understand your class naming for which is main page (home or receipies or landing) but the way i wrote coupd be clearer for you.


问:
QTabWidget insert a QSplitter can't switch when the splitter disabled
I insert a QFrame and QTabWidget in the QSplitter. And I wanna forbidden to adjust the size of elements in QSplitter. So I call method of 'setDisabled' in QSplitter. It's useful for disabling resizing the elements. But I also can't switch tab of QTabWidget. Who can give me some suggestions? Thanks very much......

```<code>import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSplitter, QHBoxLayout, QFrame, QTabWidget
from PyQt5.QtCore import Qt
class Example1(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(0, 0, 600, 600)
        self.setWindowTitle("Demo")
        self.layout = QHBoxLayout()

        top_frame = QFrame()
        top_frame.setFrameShape(QFrame.StyledPanel)

        bottom_frame = QTabWidget(self)
        tab1 = QWidget()
        tab2 = QWidget()
        bottom_frame.setTabText(0, "Generic")
        bottom_frame.setTabText(1, "Other")
        bottom_frame.addTab(tab1, "Tab 1")
        bottom_frame.addTab(tab2, "Tab 2")

        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)
        splitter.addWidget(top_frame)
        splitter.addWidget(bottom_frame)
        splitter.setSizes([300, 300])
        **splitter.setDisabled(True)**

        self.layout.addWidget(splitter)
        self.setLayout(self.layout)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example1()
    sys.exit(app.exec_())

</code>```

the running result of the program

答: I haven't used a QSplitter before but are the .setFixedHeight(300) .setFixedWidth(300), or .setFixedSize(300, 300) methods not applicable here?

Body:
I insert a QFrame and QTabWidget in the QSplitter. And I wanna forbidden to adjust the size of elements in QSplitter. So I call method of 'setDisabled' in QSplitter. It's useful for disabling resizing the elements. But I also can't switch tab of QTabWidget. Who can give me some suggestions? Thanks very much......

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSplitter, QHBoxLayout, QFrame, QTabWidget
from PyQt5.QtCore import Qt
class Example1(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(0, 0, 600, 600)
        self.setWindowTitle("Demo")
        self.layout = QHBoxLayout()

        top_frame = QFrame()
        top_frame.setFrameShape(QFrame.StyledPanel)

        bottom_frame = QTabWidget(self)
        tab1 = QWidget()
        tab2 = QWidget()
        bottom_frame.setTabText(0, "Generic")
        bottom_frame.setTabText(1, "Other")
        bottom_frame.addTab(tab1, "Tab 1")
        bottom_frame.addTab(tab2, "Tab 2")

        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)
        splitter.addWidget(top_frame)
        splitter.addWidget(bottom_frame)
        splitter.setSizes([300, 300])
        **splitter.setDisabled(True)**

        self.layout.addWidget(splitter)
        self.setLayout(self.layout)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example1()
    sys.exit(app.exec_())

the running result of the program


问:
Rotate a Swing JLabel
I am currently trying to implement a Swing component, inheriting from JLabel which should simply represent a label that can be oriented vertically.

Beginning with this:

```<code>public class RotatedLabel extends JLabel {

    public enum Direction {
        HORIZONTAL,
        VERTICAL_UP,
        VERTICAL_DOWN
    }

private Direction direction;
</code>```

I thought it's be a nice idea to just alter the results from getPreferredSize():

```<code>@Override
public Dimension getPreferredSize() {
    // swap size for vertical alignments
    switch (getDirection()) {
        case VERTICAL_UP:
        case VERTICAL_DOWN:
            return new Dimension(super.getPreferredSize().height, super
                .getPreferredSize().width);
        default:
            return super.getPreferredSize();
    }
}
</code>```

and then simply transform the Graphics object before I offload painting to the original JLabel:

```<code>@Override
protected void paintComponent(Graphics g) {
    Graphics2D gr = (Graphics2D) g.create();

    switch (getDirection()) {
        case VERTICAL_UP:
            gr.translate(0, getPreferredSize().getHeight());
            gr.transform(AffineTransform.getQuadrantRotateInstance(-1));
            break;
        case VERTICAL_DOWN:
            // TODO
            break;
        default:
    }

    super.paintComponent(gr);
}
</code>```

It seems to work—somehow—in that the text is now displayed vertically. However, placement and size are off.

Actually, the width of the background (orange in this case) is identical with the height of the surrounding JFrame which is ... not quite what I had in mind.

Any ideas how to solve that in a proper way? Is delegating rendering to superclasses even encouraged?

答:
I think it is off because you are translating about the wrong point.

the size of the object depends on what container you have this in, so while your preferred size might be what you want, your actual size isn't?

if you have this label in the CENTER of a BorderLayout, the size is always the full size of the container (minus north+south height, minus east+west width)

so don't you have to translate about the actual size, not preferred size?

OwnerDisplayName: Johannes Rössel

Title: Rotate a Swing JLabel

Body:
I am currently trying to implement a Swing component, inheriting from JLabel which should simply represent a label that can be oriented vertically.

Beginning with this:

public class RotatedLabel extends JLabel {

    public enum Direction {
        HORIZONTAL,
        VERTICAL_UP,
        VERTICAL_DOWN
    }

private Direction direction;

I thought it's be a nice idea to just alter the results from getPreferredSize():

@Override
public Dimension getPreferredSize() {
    // swap size for vertical alignments
    switch (getDirection()) {
        case VERTICAL_UP:
        case VERTICAL_DOWN:
            return new Dimension(super.getPreferredSize().height, super
                .getPreferredSize().width);
        default:
            return super.getPreferredSize();
    }
}

and then simply transform the Graphics object before I offload painting to the original JLabel:

@Override
protected void paintComponent(Graphics g) {
    Graphics2D gr = (Graphics2D) g.create();

    switch (getDirection()) {
        case VERTICAL_UP:
            gr.translate(0, getPreferredSize().getHeight());
            gr.transform(AffineTransform.getQuadrantRotateInstance(-1));
            break;
        case VERTICAL_DOWN:
            // TODO
            break;
        default:
    }

    super.paintComponent(gr);
}

It seems to work—somehow—in that the text is now displayed vertically. However, placement and size are off.

Actually, the width of the background (orange in this case) is identical with the height of the surrounding JFrame which is ... not quite what I had in mind.

Any ideas how to solve that in a proper way? Is delegating rendering to superclasses even encouraged?

OwnerDisplayName: John Gardner

ContentLicense: CC BY-SA 2.5


问:
What does &H57 represent and how can I translate it for C#?
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

```<code>Const REQUEST_EFI As Byte = &H57
</code>```

What would this be in c#?  I tried:

```<code>const byte request_efi = &H57;
</code>```

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

答: It's the letter W for crying out loud</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

Const REQUEST_EFI As Byte = &H57

What would this be in c#?  I tried:

const byte request_efi = &H57;

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

Body: It's the letter W for crying out loud


问:
NotFound() doesn't seem to work as expected
I'm new to ASP.NET core, so I hope you bear with me on this one. This is similar to this unanswered question.

When I'm testing a brand new C# MVC project, and I enter a wrong URL, there's no info. Just a blank page.

To solve this, I have adapted startup.cs adding a UseStatusCodePagesWithReExecute() to return a static 404.html page. This works.

So far, so good.

Now, I am coding a basic login logic. For testing purposes, I'm calling return NotFound(); when the post parameters are missing. This doesn't return anything. I'm aware that 404 is not the correct response, but I have seen NotFound(); in the generated code and I think that's what's returning blank pages, so I want to solve that before moving on.

The app.UseDeveloperException(); doesn't seem to be called for this. I'm not sure how to test that.

Is there a way to override the NotFound(); behavior to get a 404.html somehow?

This is the Tutorial I have used to set up my project.

Edit:
Based on the comments of Alexander Powolozki, I have replaced NotFound(); with Redirect("~/404.html");. This works.

```<code>// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");

public class HomeController : Controller
{
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
        // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
        if (code.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = code.Value;
        }

        //return a static file.
        try
        {
            return File("~/" + code + ".html", "text/html");
        }
        catch (FileNotFoundException)
        {
            return Redirect("Home/StatusCode?code=404");
        }
    }
}
</code>```

答:
After working a little more on the question, I have found a way to do it without using Redirect as suggested by Alexander Powolozki.

I have created a Utilities class to return the 404 code and 404.html.

In the HomeController, I have the StatusCode IActionResult.

```<code>// This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
public IActionResult StatusCode(int? code)
{
    // Call the static method
    return Utilities.StatusCode(code: code.Value, this.HttpContext);
}
</code>```

In Models, I've added a Utilities.cs.

```<code>using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;

namespace MediaMgt.Models
{
    public static class Utilities
    {
        public static IActionResult StatusCode(int code, HttpContext httpContext)
        {
            // here is the trick
            httpContext.Response.StatusCode = code;

            //return a static file.
            try
            {
                return new VirtualFileResult("~/" + code + ".html", "text/html");
            }
            catch (FileNotFoundException)
            {
                httpContext.Response.StatusCode = 404;
                return new VirtualFileResult("~/404.html", "text/html");
            }
        }
    }
}
</code>```

The reason to do it like this instead of using the Redirect method is to avoid a round-trip to the client with a 302. This method returns both the 404 error code and a standard 404.html.

You can easily add more functionality from here on.

Body:
I'm new to ASP.NET core, so I hope you bear with me on this one. This is similar to this unanswered question.

When I'm testing a brand new C# MVC project, and I enter a wrong URL, there's no info. Just a blank page.

To solve this, I have adapted startup.cs adding a UseStatusCodePagesWithReExecute() to return a static 404.html page. This works.

So far, so good.

Now, I am coding a basic login logic. For testing purposes, I'm calling return NotFound(); when the post parameters are missing. This doesn't return anything. I'm aware that 404 is not the correct response, but I have seen NotFound(); in the generated code and I think that's what's returning blank pages, so I want to solve that before moving on.

The app.UseDeveloperException(); doesn't seem to be called for this. I'm not sure how to test that.

Is there a way to override the NotFound(); behavior to get a 404.html somehow?

This is the Tutorial I have used to set up my project.

Edit:
Based on the comments of Alexander Powolozki, I have replaced NotFound(); with Redirect("~/404.html");. This works.

// Wherever you want to return your standard 404 page
return Redirect("Home/StatusCode?code=404");

public class HomeController : Controller
{
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
        // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
        if (code.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = code.Value;
        }

        //return a static file.
        try
        {
            return File("~/" + code + ".html", "text/html");
        }
        catch (FileNotFoundException)
        {
            return Redirect("Home/StatusCode?code=404");
        }
    }
}

Body:
After working a little more on the question, I have found a way to do it without using Redirect as suggested by Alexander Powolozki.

I have created a Utilities class to return the 404 code and 404.html.

In the HomeController, I have the StatusCode IActionResult.

// This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
public IActionResult StatusCode(int? code)
{
    // Call the static method
    return Utilities.StatusCode(code: code.Value, this.HttpContext);
}

In Models, I've added a Utilities.cs.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;

namespace MediaMgt.Models
{
    public static class Utilities
    {
        public static IActionResult StatusCode(int code, HttpContext httpContext)
        {
            // here is the trick
            httpContext.Response.StatusCode = code;

            //return a static file.
            try
            {
                return new VirtualFileResult("~/" + code + ".html", "text/html");
            }
            catch (FileNotFoundException)
            {
                httpContext.Response.StatusCode = 404;
                return new VirtualFileResult("~/404.html", "text/html");
            }
        }
    }
}

The reason to do it like this instead of using the Redirect method is to avoid a round-trip to the client with a 302. This method returns both the 404 error code and a standard 404.html.

You can easily add more functionality from here on.


问:
About " echo Test > Test.txt"
I wanna create a txt file only using a batch file that has multiple lines in it
For example :

In the txt file it will have:

I like to program

But I also like my name

But I cannot do that with :

```<code>echo I Like to program, But I also like my name > Test.txt
</code>```

Any help with this?

答:
Approach 1: FINDSTR

;@echo off
;findstr /V /R "^;" "%~f0" >text.txt
;exit /b
I like to program
But I also like my name
```
<h1>Approach 2: Multiline strings</h1>
<p>Unix (LF) endings:</p>
<pre class="lang-dos prettyprint-override"><code>@echo off
====SETLOCAL DisableDelayedExpansion EnableExtensions

set ^"LF=^
%====DO NOT REMOVE ME====%
"
set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"

<nul >text.txt set/p^"=SO%NL%
MANY%NL%
LINES^!"
</code>```

If you want Windows (CRLF) endings:

FOR /F "skip=3" %%C in (
'%__APPDIR__%wbem\wmic.exe os get Name'
) do set ^"NL=%%C^^^%LF%%LF%^%LF%%LF%^^"
```

Title: About " echo Test > Test.txt"

Body:
I wanna create a txt file only using a batch file that has multiple lines in it
For example :

In the txt file it will have:

I like to program

But I also like my name

But I cannot do that with :

echo I Like to program, But I also like my name > Test.txt

Any help with this?

Body:
Approach 1: FINDSTR

;@echo off
;findstr /V /R "^;" "%~f0" >text.txt
;exit /b
I like to program
But I also like my name

Approach 2: Multiline strings

Unix (LF) endings:

@echo off
====SETLOCAL DisableDelayedExpansion EnableExtensions

set ^"LF=^
%====DO NOT REMOVE ME====%
"
set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"

<nul >text.txt set/p^"=SO%NL%
MANY%NL%
LINES^!"

If you want Windows (CRLF) endings:

FOR /F "skip=3" %%C in (
'%__APPDIR__%wbem\wmic.exe os get Name'
) do set ^"NL=%%C^^^%LF%%LF%^%LF%%LF%^^"


问:
predict() missing 1 required positional argument: 'X' in sklearn LinearRegression
I am trying to predict the salary using simple linear regression. Where X is year of experience and y is salary.

This is my code

```<code>
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Fitting Simple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression
regressor(X_train, y_train)

# Predicting the Test set results
Y_pred = regressor.predict(X_test)

</code>```

This is my error

```<code>Y_pred = regressor.predict(X_test)
Traceback (most recent call last):

  File "<ipython-input-28-e33267d5ef4e>", line 1, in <module>
    Y_pred = regressor.predict(X_test)

TypeError: predict() missing 1 required positional argument: 'X'
</code>```

What am I doing wrong? How can I resolve this issue /error ?

答:
It should be as follows:</p>

```<code>from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor = regressor.fit(X_train, y_train)

# Predicting the Test set results
Y_pred = regressor.predict(X_test)
</code>```

Body:
I am trying to predict the salary using simple linear regression. Where X is year of experience and y is salary.

This is my code

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 1].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

# Fitting Simple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression
regressor(X_train, y_train)

# Predicting the Test set results
Y_pred = regressor.predict(X_test)

This is my error

Y_pred = regressor.predict(X_test)
Traceback (most recent call last):

  File "<ipython-input-28-e33267d5ef4e>", line 1, in <module>
    Y_pred = regressor.predict(X_test)

TypeError: predict() missing 1 required positional argument: 'X'

What am I doing wrong? How can I resolve this issue /error ?

Body:
It should be as follows:

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor = regressor.fit(X_train, y_train)

# Predicting the Test set results
Y_pred = regressor.predict(X_test)


问:
Error occured while import tensorflow in jupyter-notebook
I have installed tensorflow version 2.2.0 in my windows.But it shows the following error while i want to import it.How can i solve the problem?

```<code>    ---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     57
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59

G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in <module>
     27             return _mod
---> 28     _pywrap_tensorflow_internal = swig_import_helper()
     29     del swig_import_helper

G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in swig_import_helper()
     23             try:
---> 24                 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
     25             finally:

G:\anaconda\lib\imp.py in load_module(name, file, filename, details)
    241         else:
--> 242             return load_dynamic(name, filename, file)
    243     elif type_ == PKG_DIRECTORY:

G:\anaconda\lib\imp.py in load_dynamic(name, path, file)
    341             name=name, loader=loader, origin=path)
--> 342         return _load(spec)
    343

ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-15-5e7c1303e954> in <module>
----> 1 import tensorflow
      2
      3 train_examples = tf.keras.utils.normalize(new_train, axis=1)
      4
      5 test_examples = tf.keras.utils.normalize(new_test, axis=1)

G:\anaconda\lib\site-packages\tensorflow\__init__.py in <module>
     39 import sys as _sys
     40
---> 41 from tensorflow.python.tools import module_util as _module_util
     42 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader
     43

G:\anaconda\lib\site-packages\tensorflow\python\__init__.py in <module>
     48 import numpy as np
     49
---> 50 from tensorflow.python import pywrap_tensorflow
     51
     52 # Protocol buffers

G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     67 for some common reasons and solutions.  Include the entire stack trace
     68 above this error message when asking for help.""" % traceback.format_exc()
---> 69   raise ImportError(msg)
     70
     71 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "G:\anaconda\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "G:\anaconda\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.
</code>```

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

答:
Try this

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

download x64: vc_redist.x64.exe

install it.

Source: https://github.com/tensorflow/tensorflow/issues/35749#issuecomment-588425399

=====

Another possible solution is downgrading to tensorflow 2.0

```<code>pip install tensorflow==2.0
</code>```

Source: https://github.com/tensorflow/tensorflow/issues/35749#issuecomment-573313402

Body:
I have installed tensorflow version 2.2.0 in my windows.But it shows the following error while i want to import it.How can i solve the problem?

    ---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     57
---> 58   from tensorflow.python.pywrap_tensorflow_internal import *
     59

G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in <module>
     27             return _mod
---> 28     _pywrap_tensorflow_internal = swig_import_helper()
     29     del swig_import_helper

G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py in swig_import_helper()
     23             try:
---> 24                 _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
     25             finally:

G:\anaconda\lib\imp.py in load_module(name, file, filename, details)
    241         else:
--> 242             return load_dynamic(name, filename, file)
    243     elif type_ == PKG_DIRECTORY:

G:\anaconda\lib\imp.py in load_dynamic(name, path, file)
    341             name=name, loader=loader, origin=path)
--> 342         return _load(spec)
    343

ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
<ipython-input-15-5e7c1303e954> in <module>
----> 1 import tensorflow
      2
      3 train_examples = tf.keras.utils.normalize(new_train, axis=1)
      4
      5 test_examples = tf.keras.utils.normalize(new_test, axis=1)

G:\anaconda\lib\site-packages\tensorflow\__init__.py in <module>
     39 import sys as _sys
     40
---> 41 from tensorflow.python.tools import module_util as _module_util
     42 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader
     43

G:\anaconda\lib\site-packages\tensorflow\python\__init__.py in <module>
     48 import numpy as np
     49
---> 50 from tensorflow.python import pywrap_tensorflow
     51
     52 # Protocol buffers

G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow.py in <module>
     67 for some common reasons and solutions.  Include the entire stack trace
     68 above this error message when asking for help.""" % traceback.format_exc()
---> 69   raise ImportError(msg)
     70
     71 # pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long

ImportError: Traceback (most recent call last):
  File "G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "G:\anaconda\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "G:\anaconda\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "G:\anaconda\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Body:
Try this

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

download x64: vc_redist.x64.exe

install it.

Source: https://github.com/tensorflow/tensorflow/issues/35749#issuecomment-588425399

=====

Another possible solution is downgrading to tensorflow 2.0

pip install tensorflow==2.0

Source: https://github.com/tensorflow/tensorflow/issues/35749#issuecomment-573313402


问:
Access data from my table of sqlserver in asp.net
i am designing a project in .net 4.0 using mvc3. my table name "logindata" is stored in sql server 2008. i want to access rows of that table in my project model class. So please suggest me what connction string i should use and where i should specify table name to access data from that table.?</p>

答:
I highly suggest reading the LINQ to SQL tutorial by Scott Guthrie

LINQ to SQL is a very efficient and simple method for retrieving database data and placing it into easily-accessible pre-configured, adjustable business objects.

I think you will find it a good first step.

Part 1: Introduction to LINQ to SQL

Part 2: Defining our Data Model Classes

Part 3: Querying our Database

Part 4: Updating our Database

Part 5: Binding UI using the <asp:LinqDataSource> Control

Part 6: Retrieving Data Using Stored Procedures

Part 7: Updating our Database using Stored Procedures

Part 8: Executing Custom SQL Expressions

Part 9: Using a Custom LINQ Expression with the <asp:LinqDataSource> Control


问:
html file display at bottom position
I have added on my HTML page the content of a log file so when the log file has many lines, there is a scrollbar on my webpage.

I am trying to display my webpage with a scrollbar on the bottom position with this code but nothing is happening:

```<code><html>
  <header>
    <meta charset="utf-8">
    <title>Plannificateur</title>
    <style>
    p1  {
      font-size: 130%;
    }
    p2  {
      font-size: 80%;
    }
    </style>
  </header>
  <body>
    <form action="" method="POST">
    <h1>Liste</h1>
      <!-- DERNIER_UTILISATEUR -->
    </form>
    <br><br><br><br>
    <hr>
    <h3>Journal des évènements</h3>
    <script language="javascript" type="text/javascript">
        document.getElementById('log').scrollIntoView();
    </script>
    <div id='log'>
        <object data="log.txt" style="width:100%;"></object>
    </div>
  </body>
</html>
</code>```

Do you have any idea why it is not working?

答:
The Horizontal scrollbar and Vertical scroll bar can be added easily by a combination of these 3 CSS attributes:

overflow / overflow-x / overflow-y   (Show scrollbar when content overflows defined margins)

max-width  (define maximum width)

max-height (maximum height)

Here is an example for showing both horizontal and vertical scrollbars:

```<code><html>
  <head>
    <meta charset="utf-8">
    <title>Plannificateur</title>
    <style>
    .log-file-viewer {
        max-width: 110px;
        height: 110px;
        overflow: scroll;     --> shows scrollbar

             --- Other options for specifying scroll ---

        overflow-x: scroll;
        overflow-y: scroll;
    }
    </style>
  </head>
  <body>
    <div id="log" class="log-file-viewer">
        Log file contents here .....
        <br>
        Line 1: Hello! How are you doing? Hello! How are you doing?Hello!How are you doing?Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?
        <br>
        Line 2: Hello! How are you doing? Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?
    </div>
  </body>
</html>
</code>```

Output:

More information:

https://www.w3schools.com/cssref/pr_pos_overflow.asp

Title: html file display at bottom position

Body:
I have added on my HTML page the content of a log file so when the log file has many lines, there is a scrollbar on my webpage.

I am trying to display my webpage with a scrollbar on the bottom position with this code but nothing is happening:

    <meta charset="utf-8">
    <title>Plannificateur</title>

    <form action="" method="POST">

Liste

    </form>

Journal des évènements

        <object data="log.txt" style="width:100%;"></object>

Do you have any idea why it is not working?

Body:
The Horizontal scrollbar and Vertical scroll bar can be added easily by a combination of these 3 CSS attributes:

overflow / overflow-x / overflow-y   (Show scrollbar when content overflows defined margins)

max-width  (define maximum width)

max-height (maximum height)

Here is an example for showing both horizontal and vertical scrollbars:

<html>
  <head>
    <meta charset="utf-8">
    <title>Plannificateur</title>
    <style>
    .log-file-viewer {
        max-width: 110px;
        height: 110px;
        overflow: scroll;     --> shows scrollbar

             --- Other options for specifying scroll ---

        overflow-x: scroll;
        overflow-y: scroll;
    }
    </style>
  </head>
  <body>
    <div id="log" class="log-file-viewer">
        Log file contents here .....
        <br>
        Line 1: Hello! How are you doing? Hello! How are you doing?Hello!How are you doing?Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?
        <br>
        Line 2: Hello! How are you doing? Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?Hello! How are you doing?
    </div>
  </body>
</html>

Output:

More information:

https://www.w3schools.com/cssref/pr_pos_overflow.asp


问:
Throwing own exceptions
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }
```

<p>Now I also have this exception that I wrote </p>

<pre class="lang-java prettyprint-override"><code>    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }
</code>```

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

```<code>class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}
</code>```

答:
Extract the common place for acquiring the account</p>

```<code>private Acount getAccount(accountNo) {
  if (accountNo >= accounts.length || accounts[accountNo] == null) {
   throw new NoSuchAccountException();
  }
  return account;
}

  boolean deposit(int accountNo, double amount) {
    Account account = getAccount(accountNo);
    return account.deposit(amount);
  }

</code>```

Title: Throwing own exceptions

Body:
I have this class Account

    import java.io.IllegalArgumentException;

    class Account {
        final int accountNo;
        final Customer owner;
        final double overdraft;

        double balance = 0;

        private Account(int accountNo, Customer owner, double overdraft) {
            this.accountNo = accountNo;
            this.owner = owner;
            this.overdraft = overdraft;
        }

        void print() {
            Out.println("Kontonummer: " + accountNo);
            owner.print();
            Out.format("Kontostand: %.2f%nÜberziehungsrahmen: %.2f%n", balance, overdraft);
        }

        public boolean deposit(double amount) throws IllegalArgumentException {
            if (amount <= 0) {
                throws new IllegalArgumentException("Cannot deposit negative amounts!");
                break;
            } else {
                balance += amount;
                return true;
            }

            public boolean withdraw(double amount) throws OverdraftLimitReachedException {
                if (amount <= 0 || !isCovered(amount)) {
                    throw new OverdraftLimitReachedException("Overdraft limit has been reached", accountNo);
                    break;
                } else {
                    balance -= amount;
                    return true;
                }

                boolean isCovered(double amount) {
                    return amount - overdraft <= balance;
                }

                boolean transfer(Account target, double amount) {
                    boolean success = withdraw(amount);
                    if (!success) return false;

                    target.deposit(amount);
                    return true;
                }
            }
        }
    }

Now I also have this exception that I wrote

    public class NoSuchAccountException extends AccountException {

        public NoSuchAccountException(int accountNo) {
            super(message, accountNo);
        }
    }

Now I need to throw this exception in the class account,when the searched account number does not exist.Now my question is in which method(or function I think that is the same,please correct me if I'm wrong) do I throw this exception.And after what check.How would I check if the account number exist,and if it doesnt I'll throw this exception. Thank you!

EDIT: The class banking, to complete the program

class Banking {
  static final int CAPACITY = 100;

  final Account[] accounts = new Account[CAPACITY];
  int nOfAccounts = 0;

  int createAccount(String firstName, String lastName, String phone, double overdraft) {
    if (nOfAccounts == CAPACITY) return -1;

    // use nOfAccounts as accountNo and index to array
    Customer owner = new Customer(firstName, lastName, phone);
    Account account = new Account(nOfAccounts, owner, overdraft);
    accounts[nOfAccounts] = account;
    nOfAccounts++;

    return account.accountNo;
  }

  boolean deposit(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.deposit(amount);
  }

  boolean withdraw(int accountNo, double amount) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return false;

    Account account = accounts[accountNo];
    return account.withdraw(amount);
  }

  boolean transfer(int fromNo, int toNo, double amount) {
    if (fromNo < 0 || toNo < 0 ||
        fromNo >= nOfAccounts || toNo >= nOfAccounts) return false;

    Account from = accounts[fromNo];
    Account to = accounts[toNo];
    return from.transfer(to, amount);
  }

  double getBalance(int accountNo) {
    if (accountNo < 0 || accountNo >= nOfAccounts) return 0;

    Account account = accounts[accountNo];
    return account.balance;
  }

  double getBalance() {
    double sum = 0;

    for (int i = 0; i < nOfAccounts; i++) {
      sum += accounts[i].balance;
    }
    return sum;
  }

  void print() {
    Out.println("---------- Bankauszug ----------");

    for (int i = 0; i < nOfAccounts; i++) {
      accounts[i].print();
      Out.println("--------------------------------");
    }
    Out.format("Bilanzsumme: %.2f%n", getBalance());
    Out.println("--------------------------------");
  }

  // --------------------- Optionaler Teil ---------------------

  public static void main(String[] args) {
    Banking banking = new Banking();
    char op;

    do {
      printMenu();
      op = readOperation();

      switch (op) {
        case 'a': {
          printTitle("Konto anlegen");
          String firstName = getString("Vorname");
          String lastName = getString("Nachname");
          String phone = getString("Telefonnummer");
          double overdraft = getDouble("Überziehungsrahmen");

          int accountNo = banking.createAccount(
            firstName, lastName, phone, overdraft);
          printMessage("Anlegen von Konto " + accountNo, accountNo != -1);
          break;
        }
        case 'e': {
          printTitle("Einzahlen");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Einzahlungsbetrag");

          boolean success = banking.deposit(accountNo, amount);
          printMessage("Einzahlen", success);
          break;
        }
        case 'b': {
          printTitle("Abheben");
          int accountNo = getInt("Kontonummer");
          double amount = getDouble("Abhebungsbetrag");

          boolean success = banking.withdraw(accountNo, amount);
          printMessage("Abheben", success);
          break;
        }
        case 't': {
          printTitle("Überweisen");
          int fromNo = getInt("Von Kontonummer");
          int toNo = getInt("Auf Kontonummer");
          double amount = getDouble("Betrag");

          boolean success = banking.transfer(fromNo, toNo, amount);
          printMessage("Überweisen", success);
          break;
        }
        case 'd':
          banking.print();
          break;
        case 'q':
          Out.println("Beenden");
          break;
        default:
          Out.println("Ungültige Operation");
          break;
      }
    } while(op != 'q');
  }

  static void printMenu() {
    Out.println();
    Out.println("*********** Bankverwaltung ********");
    Out.println("Konto anlegen ................... a");
    Out.println("Einzahlen ....................... e");
    Out.println("Beheben ......................... b");
    Out.println("Überweisen ...................... t");
    Out.println("Übersicht drucken ............... d");
    Out.println("Beenden ......................... q");
    Out.print("Welche Menuoption? [a|e|b|t|d|q]: ");
  }

  static char readOperation() {
    char ch = Character.toLowerCase(In.readChar());
    In.readLine();
    return ch;
  }

  static void printTitle(String text) {
    Out.println("*** " + text + " ***");
  }

  static String getString(String text) {
    Out.print(text + ": ");
    return In.readLine();
  }

  static double getDouble(String text) {
    Out.print(text + ": ");
    return In.readDouble();
  }

  static int getInt(String text) {
    Out.print(text + ": ");
    return In.readInt();
  }

  static void printMessage(String operation, boolean success) {
    String message = success ?
      operation + " erfolgreich durchgeführt" :
      "Ungültige Operation";
    Out.println(message);
  }
}

Body:
Extract the common place for acquiring the account

private Acount getAccount(accountNo) {
  if (accountNo >= accounts.length || accounts[accountNo] == null) {
   throw new NoSuchAccountException();
  }
  return account;
}

  boolean deposit(int accountNo, double amount) {
    Account account = getAccount(accountNo);
    return account.deposit(amount);
  }


答:
```<code># Fitting Simple Linear Regression to the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()  # <-- you need to instantiate the regressor like so
regressor.fit(X_train, y_train) # <-- you need to call the fit method of the regressor

# Predicting the Test set results
Y_pred = regressor.predict(X_test)
</code>```

Title: predict() missing 1 required positional argument: 'X' in sklearn LinearRegression


问:
Can I write a program in binary directly ? How can I get the computer to execute it?
I know that may seem weird and looking for troubles but I think experiencing what the ancient programmers experienced before is something interesting. So how can I execute a program written only in binary? (Suppose that I know what I am doing and not using assembly of course.)

I just want to write a series of bits like 111010111010101010101 and execute that. So how can I do that?

答:
most assemblers (MMIX assembler for instance see www.mmix.cs.hm.edu) dont care if
you write instructions or data.

So instead of wirting

```
Main ADD $0,$0,3
     SUB $1,$0,4
     ...
```

you can write

```
Main TETRA #21000003
     TETRA #25010004
     ...
```

So this way you can assemble your program by hand and then have the assembler transform it in a form the loader needs. Then you execute it. Normaly you use hex notatition not binary because keeping track of so many digits is difficult. You can also use decimal, but the charts that tell you which instructions have which codes are typically in hex notation.

Good luck! I had to do things like this when I started programming computers. Everybody was glad to have an assembler or even a compiler then.
Martin

Body:
most assemblers (MMIX assembler for instance see www.mmix.cs.hm.edu) dont care if
you write instructions or data.

So instead of wirting

Main ADD $0,$0,3
     SUB $1,$0,4
     ...

you can write

Main TETRA #21000003
     TETRA #25010004
     ...

So this way you can assemble your program by hand and then have the assembler transform it in a form the loader needs. Then you execute it. Normaly you use hex notatition not binary because keeping track of so many digits is difficult. You can also use decimal, but the charts that tell you which instructions have which codes are typically in hex notation.

Good luck! I had to do things like this when I started programming computers. Everybody was glad to have an assembler or even a compiler then.
Martin


问:
How to add if else statement in python along with function defination
Sorry to bother i m new to coding just learning python. i just created some code by myself in python  no error shows. but why if else statement not executing. can someone help.

code:

```<code>def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

person = name("Aditya", 17)
print(person)
</code>```

答:
On your line 2, you have used "return". It means below codes won't be executed. You should move the code line 2 to the end of function like

def name(f_name, age):
    # this code has removed
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

    return f"Hi, {f_name} {age}"
```

Body:
Sorry to bother i m new to coding just learning python. i just created some code by myself in python  no error shows. but why if else statement not executing. can someone help.

code:

def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

person = name("Aditya", 17)
print(person)


问:
version 1.7 of the jvm is not suitable for this product. version 1.8 greater is required for eclipse nano in window
I am trying to launch Eclipse Nano in Windows 7, but getting the error:

```<code>Version 1.7 of the JVM is not suitable for this product. version 1.8 greater is required for Eclipse Nano in Windows
</code>```

I already have Java 8 installed on the system

答:
Eclipse will consider the version that is mentioned in eclipse.ini file, this error
means that your installed java version (in environment variable) and the mentioned java
version in eclipse.ini file is not matching.

You may just change the java version there (it will be in eclipse-installation-dir).

Change the property as below:-
-Dosgi.requiredJavaVersion=

Body:
I am trying to launch Eclipse Nano in Windows 7, but getting the error:

Version 1.7 of the JVM is not suitable for this product. version 1.8 greater is required for Eclipse Nano in Windows

I already have Java 8 installed on the system


问:
Java 8 Pattern Matching?
Will Java 8 support pattern matching like Scala and other functional programs do? I'm putting a presentation together of Java 8's Lambda features. I can't find anything on this particular Functional-programming concept.

I remember what got me interested in functional programming was the quicksort implementation, especially compared to imperative programming's implementation.

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.</p>

```<code>   matches(data).as(
      new Person("man"),    () ->  System.out.println("man");
      new Person("woman"),  () ->  System.out.println("woman");
      new Person("child"),  () ->  System.out.println("child");
      Null.class,           () ->  System.out.println("Null value "),
      Else.class,           () ->  System.out.println("Default value: " + data)
   );

   matches(data).as(
      Integer.class, i  -> { System.out.println(i * i); },
      Byte.class,    b  -> { System.out.println(b * b); },
      Long.class,    l  -> { System.out.println(l * l); },
      String.class,  s  -> { System.out.println(s * s); },
      Null.class,    () -> { System.out.println("Null value "); },
      Else.class,    () -> { System.out.println("Default value: " + data); }
   );

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );
</code>```

Title: Java 8 Pattern Matching?

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.

   matches(data).as(
      new Person("man"),    () ->  System.out.println("man");
      new Person("woman"),  () ->  System.out.println("woman");
      new Person("child"),  () ->  System.out.println("child");
      Null.class,           () ->  System.out.println("Null value "),
      Else.class,           () ->  System.out.println("Default value: " + data)
   );

   matches(data).as(
      Integer.class, i  -> { System.out.println(i * i); },
      Byte.class,    b  -> { System.out.println(b * b); },
      Long.class,    l  -> { System.out.println(l * l); },
      String.class,  s  -> { System.out.println(s * s); },
      Null.class,    () -> { System.out.println("Null value "); },
      Else.class,    () -> { System.out.println("Default value: " + data); }
   );

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );


问:
How to include dynamic constraints in Linear Optimization with PuLP in python?
I have been working on a linear optimization problem using the PuLP library. How can I include this dynamic constraint in my code?

snapshot of excel example with terms

I need to minimize VaR 1D of the portfolio (-19391.8) formed by the weighted sum of A and B - Objective function

At the same time, VaR10D of of portfolio should be reduced by the target given (-39100 to -29100).
ow, the catch as you can see is that Var10d and Var1d of the portfolio are the second smallest value in the column of 'Total'. Now, I need to a constraint to add in code that the Var10d should be reduced by 10000 (i.e. to -29100), but at the same time, it should also be the second smallest value in the total column calculated by the weighted sum of 'A' and 'B' on every day.

Thus, I need optimal weights that can 1. minimize Var1d (while it is the second smallest in 'Total' column of Var10d), 2. reduce Var10d by 10000 (i.e. to -29100)(while it is the second smallest in 'Total' column of Var1d).

答:
Min -8000 * x1 - 15000 * x2 + target

I don't get your constraints, because the numbers just seem to be other values for the coefficients in the objective-function.

So I can't see a reason why your "program" not just set x1, x2 = 0, there is nothing to calculate, because there are no constraints..

If you want your objective-value in a specific range you could add:
coeff * x1 + coeff * x2 <= (>=) value
And then if you want to change the right side value, you could run the program again after the first cycle and so on..