问:
Spring WebClient multiple retryWhen to handle different errors
Could I be able to add multiple retryWhen to perform retries to handle different WebClient failure responses?

What I want to achieve:

I am using WebClient to make REST API Calls. There are few error scenarios, when happens I need to perform retry, but with different delays.

For eg,
 1. if 401 Unauthorize happens, I can retry immediately after refreshing the token.
 2. If 502/503 Server error happens, I need to delay the retries after 5 sec.
 3. if 429 Too Many Request happens, I need to delay the retry little longer, say 20sec after.

I would like to create Retry spec like below:

```<code>    protected static final Predicate<Throwable> is401 =
                (throwable) -> throwable instanceof WebClientResponseException.Unauthorized;

        protected static final Predicate<Throwable> is5xx =
                (throwable) -> throwable instanceof WebClientResponseException.ServiceUnavailable;

        protected static final Predicate<Throwable> is429 =
                (throwable) -> throwable instanceof WebClientResponseException.TooManyRequests;

        Retry retry401 = Retry.fixedDelay(5, Duration.ofSeconds(1))
                    .filter(is401)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());

        Retry retry5xx = Retry.fixedDelay(5, Duration.ofSeconds(10))
                    .filter(is5xx)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());

        Retry retry429 = Retry.fixedDelay(5, Duration.ofSeconds(20))
                    .filter(is429)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());

// trying to apply the to WebClient like below:
    WebClient.Builder()
        .get()
        .uri("endpointuri")
        .retrieve()
        .bodyToFlux(String.class)
        .retryWhen(retry401)
        .retryWhen(retry5xx)
        .retryWhen(retry429);
</code>```

Looks like `.retryWhen(retry429)' overwrites the other retries.

答:
Looks like `.retryWhen(retry429)' overwrites the other retries.

This is false. retryWhen is a composite operator that builds upon the existing publisher - you can chain it as many times as you like. The only time you need to worry about one retry "overriding" another is when your filter predicates overlap.

Even in this case, it looks like it's "first wins" (in the chain) not "last wins".

Your problems instead may be to do with this line:

```<code>protected static final Predicate<Throwable> is5xx =
            (throwable) -> throwable instanceof WebClientResponseException.ServiceUnavailable;
</code>```

From your naming and your description, it looks like you want this to catch any 5xx error - but it'll only catch 503 (which is specifically assigned to "service unavailable".)

If you're trying with something different, like a 502 or 500 error - then none of the predicates (and therefore retries) you've defined will match.

Instead, to check for any 5xx error, you likely want:

```<code>protected static final Predicate<Throwable> is5xx =
        (throwable) -> throwable instanceof WebClientResponseException && ((WebClientResponseException)throwable).getStatusCode().is5xxServerError();
</code>```

Body:
Could I be able to add multiple retryWhen to perform retries to handle different WebClient failure responses?

What I want to achieve:

I am using WebClient to make REST API Calls. There are few error scenarios, when happens I need to perform retry, but with different delays.

For eg,
 1. if 401 Unauthorize happens, I can retry immediately after refreshing the token.
 2. If 502/503 Server error happens, I need to delay the retries after 5 sec.
 3. if 429 Too Many Request happens, I need to delay the retry little longer, say 20sec after.

I would like to create Retry spec like below:

    protected static final Predicate<Throwable> is401 =
                (throwable) -> throwable instanceof WebClientResponseException.Unauthorized;

        protected static final Predicate<Throwable> is5xx =
                (throwable) -> throwable instanceof WebClientResponseException.ServiceUnavailable;

        protected static final Predicate<Throwable> is429 =
                (throwable) -> throwable instanceof WebClientResponseException.TooManyRequests;

        Retry retry401 = Retry.fixedDelay(5, Duration.ofSeconds(1))
                    .filter(is401)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());

        Retry retry5xx = Retry.fixedDelay(5, Duration.ofSeconds(10))
                    .filter(is5xx)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());

        Retry retry429 = Retry.fixedDelay(5, Duration.ofSeconds(20))
                    .filter(is429)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> retrySignal.failure());

// trying to apply the to WebClient like below:
    WebClient.Builder()
        .get()
        .uri("endpointuri")
        .retrieve()
        .bodyToFlux(String.class)
        .retryWhen(retry401)
        .retryWhen(retry5xx)
        .retryWhen(retry429);

Looks like `.retryWhen(retry429)' overwrites the other retries.

Body:
Looks like `.retryWhen(retry429)' overwrites the other retries.

This is false. retryWhen is a composite operator that builds upon the existing publisher - you can chain it as many times as you like. The only time you need to worry about one retry "overriding" another is when your filter predicates overlap.

Even in this case, it looks like it's "first wins" (in the chain) not "last wins".

Your problems instead may be to do with this line:

protected static final Predicate<Throwable> is5xx =
            (throwable) -> throwable instanceof WebClientResponseException.ServiceUnavailable;

From your naming and your description, it looks like you want this to catch any 5xx error - but it'll only catch 503 (which is specifically assigned to "service unavailable".)

If you're trying with something different, like a 502 or 500 error - then none of the predicates (and therefore retries) you've defined will match.

Instead, to check for any 5xx error, you likely want:

protected static final Predicate<Throwable> is5xx =
        (throwable) -> throwable instanceof WebClientResponseException && ((WebClientResponseException)throwable).getStatusCode().is5xxServerError();


来源: stackexchange

问:
responsivevoice - I have to read the text inside the html element to the sound robot
responsivevoice .org
I couldn't do the text voice over service as I wanted.
There is no detailed explanation on the website.

I don't want to use < textarea > The example I want to use. I don't want to choose a robot. It should only speak Turkish Male. How should I do this?

```<code><div id = "text-read"> one two tree four five </div>

<button onclick="responsiveVoice.speak('text-read');" type="button" value="Play">Play</button>
</code>```

I want it to read the contents with the button.
Thank you for your interest

resources:

https://responsivevoice.org/api

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-play-button

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-widget

答:
The first parameter of the speak function represents the text to be spoken, the second one defines the voice:

responsiveVoice.speak('bir, i̇ki, üç', 'Turkish Male');
```

<p>If you want to get the text that is inside some HTML element, you have to query it first, then get its text content and finally pass that to the function:</p>

<pre class="lang-js prettyprint-override"><code>var element = document.getElementById('text-read');
var text = element.innerText;
responsiveVoice.speak(text, 'Turkish Male');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
responsivevoice .org
I couldn't do the text voice over service as I wanted.
There is no detailed explanation on the website.

I don't want to use < textarea > The example I want to use. I don't want to choose a robot. It should only speak Turkish Male. How should I do this?

 one two tree four five

<button onclick="responsiveVoice.speak('text-read');" type="button" value="Play">Play</button>

I want it to read the contents with the button.
Thank you for your interest

resources:

https://responsivevoice.org/api

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-play-button

https://responsivevoice.org/text-to-speech-sdk/text-to-speech-widget

Body:
The first parameter of the speak function represents the text to be spoken, the second one defines the voice:

responsiveVoice.speak('bir, i̇ki, üç', 'Turkish Male');

If you want to get the text that is inside some HTML element, you have to query it first, then get its text content and finally pass that to the function:

var element = document.getElementById('text-read');
var text = element.innerText;
responsiveVoice.speak(text, 'Turkish Male');


问:
Trying to Use Gulp to Run Sass
I'm trying to set up Gulp to watch and compile my sass file in my Django project

I followed the app doc to install gulp. The sample task worked. Every answer I saw to run sass was different. This version runs but it doesn't handle a scss change:

```<code>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

sass.compiler = require('node-sass');

function defaultTask(cb) {
  gulp.watch('base/static/base/css/stylesheets/main.scss', sassCompile);
   cb();
 }
exports.default = defaultTask

function sassCompile(cb) {
  return gulp.src('base/static/base/css/stylesheets/main.scss')
    .pipe(sass()) // Converts Sass to CSS with gulp-sass
    .pipe(gulp.dest('base/static/base/css/main.css'));
  cb();
}
exports.sass = sassCompile;

// function watch() {
//   gulp.watch('base/static/base/css/stylesheets/main.scss', sassCompile);
// }
// exports.watch = watch; // don't forget to export your command!
</code>```

The output from running gulp is:

```<code>[22:17:09] Using gulpfile ~/htdocs/myproject/gulpfile.js
[22:17:09] Starting 'default'...
[22:17:09] Finished 'default' after 3.29 ms
</code>```

I have to ctrl-C to stop it.

gulp version 4.0.2 on MacOS.

This is how I manually run sass:

/usr/local/bin/sass base/static/base/css/stylesheets/main.scss: base/static/base/css/main.css

Fixed

Based on @Mark's comments this is the working version:

```<code>'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

sass.compiler = require('node-sass');

function defaultTask() {
  gulp.watch('base/static/base/css/stylesheets/**/*.scss', sassCompile);
 }
exports.default = defaultTask

function sassCompile() {
  return gulp.src('base/static/base/css/stylesheets/main.scss')
    .pipe(sass()) // Converts Sass to CSS with gulp-sass
    .pipe(gulp.dest('base/static/base/css'));
}
exports.sass = sassCompile;
</code>```

答:
You originally had no sass task defined, something like:

```<code>function sass2css() {
  return gulp.src('relative path (from the gulpfile.js file) to your main.scss')
    .pipe(sass())
    .pipe(gulp.dest('must be a directory name here'));
}
</code>```

is the general form.  In your edited question you added a sass task that used a filename (....main.css)  in the gulp.dest() call.  I pointed out that should be a directory name and that main.css is automatically created by gulp-sass so there is no need to name it yourself.  Otherwise, I tested your code and it was working.

You also had both a cb (callback function) and a return statement in your sassCompile task.  The cb() call would never be reached because of the return statement and the return statement is sufficient in this case to signal async completion to gulp so you could remove all references to cb in this task.

Title: Trying to Use Gulp to Run Sass

Body:
I'm trying to set up Gulp to watch and compile my sass file in my Django project

I followed the app doc to install gulp. The sample task worked. Every answer I saw to run sass was different. This version runs but it doesn't handle a scss change:

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

sass.compiler = require('node-sass');

function defaultTask(cb) {
  gulp.watch('base/static/base/css/stylesheets/main.scss', sassCompile);
   cb();
 }
exports.default = defaultTask

function sassCompile(cb) {
  return gulp.src('base/static/base/css/stylesheets/main.scss')
    .pipe(sass()) // Converts Sass to CSS with gulp-sass
    .pipe(gulp.dest('base/static/base/css/main.css'));
  cb();
}
exports.sass = sassCompile;

// function watch() {
//   gulp.watch('base/static/base/css/stylesheets/main.scss', sassCompile);
// }
// exports.watch = watch; // don't forget to export your command!

The output from running gulp is:

[22:17:09] Using gulpfile ~/htdocs/myproject/gulpfile.js
[22:17:09] Starting 'default'...
[22:17:09] Finished 'default' after 3.29 ms

I have to ctrl-C to stop it.

gulp version 4.0.2 on MacOS.

This is how I manually run sass:

/usr/local/bin/sass base/static/base/css/stylesheets/main.scss: base/static/base/css/main.css

Fixed

Based on @Mark's comments this is the working version:

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

sass.compiler = require('node-sass');

function defaultTask() {
  gulp.watch('base/static/base/css/stylesheets/**/*.scss', sassCompile);
 }
exports.default = defaultTask

function sassCompile() {
  return gulp.src('base/static/base/css/stylesheets/main.scss')
    .pipe(sass()) // Converts Sass to CSS with gulp-sass
    .pipe(gulp.dest('base/static/base/css'));
}
exports.sass = sassCompile;

Body:
You originally had no sass task defined, something like:

function sass2css() {
  return gulp.src('relative path (from the gulpfile.js file) to your main.scss')
    .pipe(sass())
    .pipe(gulp.dest('must be a directory name here'));
}

is the general form.  In your edited question you added a sass task that used a filename (....main.css)  in the gulp.dest() call.  I pointed out that should be a directory name and that main.css is automatically created by gulp-sass so there is no need to name it yourself.  Otherwise, I tested your code and it was working.

You also had both a cb (callback function) and a return statement in your sassCompile task.  The cb() call would never be reached because of the return statement and the return statement is sufficient in this case to signal async completion to gulp so you could remove all references to cb in this task.


问:
Make div height the max-height of container div
I have a container
 which has a max-height property. This
 contains another
, and I want the child
 to grow to the maximum height of its container.

```<code><div id='parent'>
  <div id='child'>
  </div>
</div>
</code>```

This is easy enough when the parent
 has a fixed height, but I cannot find a solution for making the child
 assume the max-height of the container. There is no padding or margin or anything to worry about - I simply need the child
 to assume the max-height of the parent.

How can I do this?

答:
That is super simple to fix, simply add a height to your parent div. </p>

```<code><div class="parent">
  <div class="child"></div>
</div>
</code>```

```<code>.parent{
  max-height:100px;
  width:500px;
  height:300px;
  background:coral;
}
.child{
  width:100%;
  height:100%;
  background:blue;
}
</code>```

Body:
I have a container
 which has a max-height property. This
 contains another
, and I want the child
 to grow to the maximum height of its container.

This is easy enough when the parent
 has a fixed height, but I cannot find a solution for making the child
 assume the max-height of the container. There is no padding or margin or anything to worry about - I simply need the child
 to assume the max-height of the parent.

How can I do this?

Body:
That is super simple to fix, simply add a height to your parent div.

<div class="parent">
  <div class="child"></div>
</div>

.parent{
  max-height:100px;
  width:500px;
  height:300px;
  background:coral;
}
.child{
  width:100%;
  height:100%;
  background:blue;
}


问:
Replacing symbol strange situation
```<code>foreach($ret as $object)
{
    $res = $object->...;
    $img_src = $res[0]->src;
    echo $img_src . '<br />';
    echo str_replace("&size=2", "", $img_src) . '<br /><br />';
}
</code>```

$img_src ~ 'http://site.com/img.jpg&size=2'

And I have to receive same link but without &size=2. Why doesn't work my last line in code. It shows the same url.

答:
Are you absolutely certain there are any goofy unprintable characters in your source string?  Try debugging with this:

```<code>printf("%s\n", join(':', str_split($img_src)));
</code>```

And make sure you really have &size=2 in your string.  If you see two consecutive colons, you've got something like a \0 or some other character mucking up the works in the middle of your string.

ContentLicense: CC BY-SA 3.0

Title: Replacing symbol strange situation

Body:
foreach($ret as $object)
{
    $res = $object->...;
    $img_src = $res[0]->src;
    echo $img_src . '
';
    echo str_replace("&size=2", "", $img_src) . '

';
}

$img_src ~ 'http://site.com/img.jpg&size=2'

And I have to receive same link but without &size=2. Why doesn't work my last line in code. It shows the same url.

Body:
Are you absolutely certain there are any goofy unprintable characters in your source string?  Try debugging with this:

printf("%s\n", join(':', str_split($img_src)));

And make sure you really have &size=2 in your string.  If you see two consecutive colons, you've got something like a \0 or some other character mucking up the works in the middle of your string.


问:
Search html table
I have a website that shows a table with data from a database, I'm trying to implement a search feature but can't get it to work.
The code for the search feature is mostly copied from a tutorial I watched, as I'm fairly new to coding. I have tried looking for spelling mistakes, missing brackets, etc, but couldn't get it to work.
So I'm hoping someone can tell me what I'm doing wrong :)

index.php:

```<code><!DOCTYPE html>

<html lang="en" dir="ltr">

  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <title>Ut</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">
     <!-- jQuery library -->
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
  </head>

  <body>
    <button class="back" onclick="window.location='../'">
      <img src="/src/icons/back.png">
    </button> <!-- Tilbake knapp -->

    <div class="container-fluid" id="utskjekkcontainer">
      <div class="row justify-content-center">
        <div class="col-mv-10 bg-light mt-5 rounded p-3">
          <h1 class="text-primary p-2">Utskjekk</h1>
          <hr>
          <div class="form-inline">
            <label for="search" class="font-weight-bold lead text-dark">Søk</label>
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
          </div>
          <hr>
          <?php
            include "../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM inventar");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>
          <table class="table table-hover table-light table-striped" id="table_data">
            <thead>
              <tr>
                <th>#</th>
                <th>Navn</th>
                <th>Antall</th>
                <th>Tilgjengelig</th>
                <th>Plassering</th>
                <th>Vekt (kg)</th>
                <th>Størrelse x y z (cm)</th>
                <th>Kommentar</th>
              </tr>
            </thead>
            <tbody>
              <?php while($row=$result->fetch_assoc()){ ?>
                <tr>
                  <td><?php echo $row["id"]; ?></td>
                  <td><?php echo $row["navn"]; ?></td>
                  <td><?php echo $row["antall"]; ?></td>
                  <td><?php echo $row["antall_tilgjengelig"]; ?></td>
                  <td><?php echo $row["plassering"]; ?></td>
                  <td><?php echo $row["vekt"]; ?></td>
                  <td><?php echo $row["størrelse"]; ?></td>
                  <td><?php echo $row["kommentar"]; ?></td>
                </tr>
              <?php } ?>
             </tbody>
           </table>
        </div>
      </div>
    </div>

    <script type="text/javascript">
      $(document).ready(function(){
        $('#search_text').keyup(function(){
          var search = $(this).val();
          $.ajax({
            url:'action.php',
            method:'post',
            data:{query:search},
            success:function(response){
              $('#table_data').html(response);
            }
          });
        });
      });
    </script>

  </body>

</html>
</code>```

action.php:

```<code>   <?php

    include "../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM inventar WHERE navn LIKE CONCAT('%','?','%') OR id LIKE CONCAT('%','?','%') OR plassering LIKE CONCAT('%','?','%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM inventar");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "<thead>
                        <tr>
                            <th>#</th>
                            <th>Navn</th>
                            <th>Antall</th>
                            <th>Tilgjengelig</th>
                            <th>Plassering</th>
                            <th>Vekt (kg)</th>
                            <th>Størrelse x y z (cm)</th>
                            <th>Kommentar</th>
                        </tr>
                    </thead>
                    <tbody>";

        while($row=$result->fetch_assoc()){
            $output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["navn"]."</td>
                    <td>".$row["antall"]."</td>
                    <td>".$row["antall_tilgjengelig"]."</td>
                    <td>".$row["plassering"]."</td>
                    <td>".$row["vekt"]."</td>
                    <td>".$row["størrelse"]."</td>
                    <td>".$row["kommentar"]."</td>
                </tr>";
        };
        $output .= "</tbody>";
        echo $output;
    } else {
        echo "<h3> Found no match!</h3>";
    };

?>
</code>```

答:
I had the same issue with a large table of data, i stumbled upon JQuery Datatables

it has a built in search function, allows sorting and other cool stuff :)

Title: Search html table

Body:
I have a website that shows a table with data from a database, I'm trying to implement a search feature but can't get it to work.
The code for the search feature is mostly copied from a tutorial I watched, as I'm fairly new to coding. I have tried looking for spelling mistakes, missing brackets, etc, but couldn't get it to work.
So I'm hoping someone can tell me what I'm doing wrong :)

index.php:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <title>Ut</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">

    <button class="back" onclick="window.location='../'">

    </button>

Utskjekk

            Søk
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">

          <?php
            include "../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM inventar");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>

                #
                Navn
                Antall
                Tilgjengelig
                Plassering
                Vekt (kg)
                Størrelse x y z (cm)
                Kommentar

              <?php while($row=$result->fetch_assoc()){ ?>

                  <?php echo $row["id"]; ?>
                  <?php echo $row["navn"]; ?>
                  <?php echo $row["antall"]; ?>
                  <?php echo $row["antall_tilgjengelig"]; ?>
                  <?php echo $row["plassering"]; ?>
                  <?php echo $row["vekt"]; ?>
                  <?php echo $row["størrelse"]; ?>
                  <?php echo $row["kommentar"]; ?>

              <?php } ?>

action.php:

   <?php

    include "../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM inventar WHERE navn LIKE CONCAT('%','?','%') OR id LIKE CONCAT('%','?','%') OR plassering LIKE CONCAT('%','?','%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM inventar");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "

                            #
                            Navn
                            Antall
                            Tilgjengelig
                            Plassering
                            Vekt (kg)
                            Størrelse x y z (cm)
                            Kommentar

";

        while($row=$result->fetch_assoc()){
            $output .= "

                    ".$row["id"]."
                    ".$row["navn"]."
                    ".$row["antall"]."
                    ".$row["antall_tilgjengelig"]."
                    ".$row["plassering"]."
                    ".$row["vekt"]."
                    ".$row["størrelse"]."
                    ".$row["kommentar"]."

";
        };
        $output .= "
";
        echo $output;
    } else {
        echo "
 Found no match!
";
    };

?>


问:
Selecting first child from all elements and nested elements
I need to only select the first and third/last elements.

It was working fine until I decided to make them links. In my actual source the divs are imgs

body {
  background-color: black;
  color: white;
}

.this:first-child {
  color: red;
}

.this:last-child {
  color: aqua;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

    <div class="this">
      FIRST
    </div>

    <div class="this">
      SECOND
    </div>

    <div class="this">
      THIRD
    </div>

</div></code>```

答:
Your .this elements are wrapped with another element (a), and they are the only children. This means that they are both first and last child, so the last rule takes over. Move the :first-child and :last-child pseudo-selectors to the a elements:

body {
  background-color: black;
  color: white;
}

a:first-child .this {
  color: red;
}

a:last-child .this {
  color: aqua;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

    <div class="this">
      FIRST
    </div>

    <div class="this">
      SECOND
    </div>

    <div class="this">
      THIRD
    </div>

</div></code>```

Body:
I need to only select the first and third/last elements.

It was working fine until I decided to make them links. In my actual source the divs are imgs

body {
  background-color: black;
  color: white;
}

.this:first-child {
  color: red;
}

.this:last-child {
  color: aqua;
}

      FIRST

      SECOND

      THIRD

Body:
Your .this elements are wrapped with another element (a), and they are the only children. This means that they are both first and last child, so the last rule takes over. Move the :first-child and :last-child pseudo-selectors to the a elements:

body {
  background-color: black;
  color: white;
}

a:first-child .this {
  color: red;
}

a:last-child .this {
  color: aqua;
}

<div class="main">
  <a href="">
    <div class="this">
      FIRST
    </div>
  </a>
  <a href="">
    <div class="this">
      SECOND
    </div>
  </a>
  <a href="">
    <div class="this">
      THIRD
    </div>
  </a>
</div>


问:
LINQ Query to join 2 different tables
I am currently working on library management project, which users update their reading status when they borrow a book. When I use linq to join tables, everything else except status is there.
Here are my models:
User model(TblUser):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}
```

<p>Book Model(TblBook):</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace LibMan.Models.DB
{
    public partial class TblBook
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string Translator { get; set; }
        public string Publisher { get; set; }
        public string Description { get; set; }
        public string Category { get; set; }
        public byte[] Cover { get; set; }
    }
}

</code>```

Book Status Model(TblBookStatus):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}

```

<p>And moving on to my code below, you can see I created DisplayBook with linq query join, but I can't display status in html side. It says it </p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LibMan.Models.DB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;

namespace LibMan.Pages
{
    public class LibraryModel : PageModel
    {
        private readonly LibMan.Models.DB.LibManContext _context;
        public string Message { get; set; }
        public LibraryModel(LibMan.Models.DB.LibManContext context)
        {
            _context = context;
            DisplayBook = new List<TblBook>();
;       }
        public IList<TblBookStatus> TblBookStatus { get; set; }
        public IList<TblBook> TblBook { get; set; }
        public IList<TblBook> DisplayBook { get; set; }
        public IList<TblUser> TblUser{ get; set; }
        [BindProperty]
        public async Task OnGetAsync()
        {
            TblBookStatus = await _context.TblBookStatus.ToListAsync();
            TblBook = await _context.TblBook.ToListAsync();
            TblUser = await _context.TblUser.ToListAsync();
            var UserEmail = HttpContext.Session.GetString("Email");

            if (TblBookStatus != null && TblBook != null)
            {
                DisplayBook = (from book in TblBook
                                join stat in TblBookStatus
                                on book.BookId equals stat.BookId
                                join usr in TblUser
                                on stat.UserEmail equals usr.Email
                                where (usr.Email == UserEmail)
                                select book).ToList();
            }
        }
    }
}
</code>```

How can I do this? Can I do this inside the statement that DisplayBook is assigned to the Linq query result? What is the best way to do this? Thanks!
Note: I can provide html code if needed.

答:
There are multiple options. You can correct your code changing type of DisplayBook to valuetuple (or create separate type for readability) :

```<code> public IList<(TblBook Book, TblBookStatus  Status)> DisplayBook { get; set; }
</code>```

Fetch books and statuses with users:

```<code>TblBookStatus = await _context.TblBookStatus.Include(s => s.User).ToListAsync();
TblBook = await _context.TblBook.ToListAsync();
</code>```

And lastly fill the DisplayBook:

```<code>DisplayBook = TblBook
    .Select(b => (b, TblBookStatus.FirstOrDefault(s => s.BookId == b.BookId)))
    .ToList()
</code>```

As far as I understand from your comments you have one-to-one relation between status and user, so this way you will have all books in your library fetched and all statuses(status for book can be null) with filled user relation.

P.S.

ToListAsync should not return null, so null checks are redundant there.

UPD

To fetch info only about one user and his books you can do it with single query:

```<code>var statusesWithUserAndBooks = await _context.TblBookStatus
    .Include(s => s.User)
    .Include(s => s.Book)
    .Where(s => s.User.Email == UserEmail)
    .ToListAsync();
</code>```

If you need a subset of data, then create DTO with necessary fields, like this:

```<code>public class DisplayBookDTO
{
    public string Status { get; set; }
    public string BookTitle { get; set; }
    public string BookAuthor { get; set; }
}

public IList<DisplayBookDTO> DisplayBook { get; set; }

DisplayBook = await _context.TblBookStatus
    .Where(s => s.User.Email == UserEmail
        && s.Book != null)
    .Select(s => new DisplayBookDTO
    {
        Status = s.Status,
        BookTitle = s.Book.Title,
        BookAuthor = s.Book.Author
    })
    .ToListAsync();
</code>```

Title: LINQ Query to join 2 different tables

Body:
I am currently working on library management project, which users update their reading status when they borrow a book. When I use linq to join tables, everything else except status is there.
Here are my models:
User model(TblUser):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}

Book Model(TblBook):

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace LibMan.Models.DB
{
    public partial class TblBook
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string Translator { get; set; }
        public string Publisher { get; set; }
        public string Description { get; set; }
        public string Category { get; set; }
        public byte[] Cover { get; set; }
    }
}

Book Status Model(TblBookStatus):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}

And moving on to my code below, you can see I created DisplayBook with linq query join, but I can't display status in html side. It says it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LibMan.Models.DB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;

namespace LibMan.Pages
{
    public class LibraryModel : PageModel
    {
        private readonly LibMan.Models.DB.LibManContext _context;
        public string Message { get; set; }
        public LibraryModel(LibMan.Models.DB.LibManContext context)
        {
            _context = context;
            DisplayBook = new List<TblBook>();
;       }
        public IList<TblBookStatus> TblBookStatus { get; set; }
        public IList<TblBook> TblBook { get; set; }
        public IList<TblBook> DisplayBook { get; set; }
        public IList<TblUser> TblUser{ get; set; }
        [BindProperty]
        public async Task OnGetAsync()
        {
            TblBookStatus = await _context.TblBookStatus.ToListAsync();
            TblBook = await _context.TblBook.ToListAsync();
            TblUser = await _context.TblUser.ToListAsync();
            var UserEmail = HttpContext.Session.GetString("Email");

            if (TblBookStatus != null && TblBook != null)
            {
                DisplayBook = (from book in TblBook
                                join stat in TblBookStatus
                                on book.BookId equals stat.BookId
                                join usr in TblUser
                                on stat.UserEmail equals usr.Email
                                where (usr.Email == UserEmail)
                                select book).ToList();
            }
        }
    }
}

How can I do this? Can I do this inside the statement that DisplayBook is assigned to the Linq query result? What is the best way to do this? Thanks!
Note: I can provide html code if needed.

Body:
There are multiple options. You can correct your code changing type of DisplayBook to valuetuple (or create separate type for readability) :

 public IList<(TblBook Book, TblBookStatus  Status)> DisplayBook { get; set; }

Fetch books and statuses with users:

TblBookStatus = await _context.TblBookStatus.Include(s => s.User).ToListAsync();
TblBook = await _context.TblBook.ToListAsync();

And lastly fill the DisplayBook:

DisplayBook = TblBook
    .Select(b => (b, TblBookStatus.FirstOrDefault(s => s.BookId == b.BookId)))
    .ToList()

As far as I understand from your comments you have one-to-one relation between status and user, so this way you will have all books in your library fetched and all statuses(status for book can be null) with filled user relation.

P.S.

ToListAsync should not return null, so null checks are redundant there.

UPD

To fetch info only about one user and his books you can do it with single query:

var statusesWithUserAndBooks = await _context.TblBookStatus
    .Include(s => s.User)
    .Include(s => s.Book)
    .Where(s => s.User.Email == UserEmail)
    .ToListAsync();

If you need a subset of data, then create DTO with necessary fields, like this:

public class DisplayBookDTO
{
    public string Status { get; set; }
    public string BookTitle { get; set; }
    public string BookAuthor { get; set; }
}

public IList<DisplayBookDTO> DisplayBook { get; set; }

DisplayBook = await _context.TblBookStatus
    .Where(s => s.User.Email == UserEmail
        && s.Book != null)
    .Select(s => new DisplayBookDTO
    {
        Status = s.Status,
        BookTitle = s.Book.Title,
        BookAuthor = s.Book.Author
    })
    .ToListAsync();


问:
Yield in for ... in
I came across some code like this:

```<code>def func(tree):
 nodes = tree
 for node in nodes:
  yield node
  nodes += [42]

gen = func([-42, 3, 1, 4, 159])

for i in range(10):
 print(next(gen))
</code>```

Does this code have undefined behaviour?

Specifically, does:

```<code>for node in nodes:
 yield node
 nodes += [42]
</code>```

show undefined behviour?

I know that:

```<code>for node in nodes:
 # yield node
 nodes += [42]
</code>```

may cause unexpected behaviour because the variable we are iterating through (nodes) is being updated in the for loop.

答:
No, why would the behavior be undefined?

The generator yields all original elements from the tree argument and then 42 to infinity.

```<code>>>> gen = func([1, 2, 3])
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
3
>>> next(gen)
42
>>> next(gen)
42
>>> next(gen)
42
</code>```

Extending nodes with [42] for each yield makes sure that the generator will never run out of numbers to yield.

The only problem is that if you call next enough times you will encounter a MemoryError because nodes grew too large.

Title: Yield in for ... in

Body:
I came across some code like this:

def func(tree):
 nodes = tree
 for node in nodes:
  yield node
  nodes += [42]

gen = func([-42, 3, 1, 4, 159])

for i in range(10):
 print(next(gen))

Does this code have undefined behaviour?

Specifically, does:

for node in nodes:
 yield node
 nodes += [42]

show undefined behviour?

I know that:

for node in nodes:
 # yield node
 nodes += [42]

may cause unexpected behaviour because the variable we are iterating through (nodes) is being updated in the for loop.

Body:
No, why would the behavior be undefined?

The generator yields all original elements from the tree argument and then 42 to infinity.

>>> gen = func([1, 2, 3])
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
3
>>> next(gen)
42
>>> next(gen)
42
>>> next(gen)
42

Extending nodes with [42] for each yield makes sure that the generator will never run out of numbers to yield.

The only problem is that if you call next enough times you will encounter a MemoryError because nodes grew too large.


问:
extract the last updated timestamp from outlook item
I am trying to find out the last recieved email in each outlook folder. for some reason, i can print it but cannot assign it to variable.

the set dat =obj.LastModificationTime is throwing exception. how can i fix it?

```<code>   Private Sub ProcessFolder(folder As MAPIFolder)

Dim folder2 As MAPIFolder
Dim obj As Object
Dim size As Double

Dim dat As Object
Set dat = Empty
If Not folder.Items Is Nothing Then
    For Each obj In folder.Items

        size = size + obj.size
        If TypeName(obj) = "MailItem" Then
       Debug.Print obj.LastModificationTime
      Set dat = obj.LastModificationTime
       End If

    Next
End If
 ' Create The Object
'Set FSO = CreateObject("Scripting.FileSystemObject")
' How To Write To A File

Debug.Print Now() & "," & folder.Name & "," & folder.Items.Count & "," & size & "," & folder.FolderPath & "," & dat
Set dat = Empty

'File.Write folder.Name & "," & folder.Items.Count & "," & size & "," & folder.FolderPath

For Each folder2 In folder.Folders
    ProcessFolder folder2
Next
'File.Close
End Sub

Sub FolderSize()

    'Needs reference to MS Outlook Object Library

   'Needs reference to MS Outlook Object Library

    Dim objOutlook As Outlook.Application
    Dim objNamespace As Outlook.NameSpace
    Dim objSourceFolder As Outlook.MAPIFolder
    Dim objDestFolder As Outlook.MAPIFolder
    Dim InboxMsg As Object
    Dim Inbox As Outlook.folder
    Dim SystemEmails As String

     Dim filter As String
       Dim olParentFolder As Outlook.MAPIFolder
    Dim olFolderA As Outlook.MAPIFolder
    Dim olFolderB As Outlook.MAPIFolder

    Set objOutlook = Application
    Set objNamespace = objOutlook.GetNamespace("MAPI") '

    Set olParentFolder = objNamespace.GetDefaultFolder(olFolderInbox)

    For Each olFolderA In olParentFolder.Folders
       ' Debug.Print olFolderA.FolderPath, olFolderA.Items.Count, olFolderA.Folders.Count

        ProcessFolder olFolderA

    Next

End Sub
</code>```

答:
First of all, there is no need to iterate over all items in the folder:

```<code>If Not folder.Items Is Nothing Then
    For Each obj In folder.Items
</code>```

Instead, you can use the Sort method of the Items class which sorts the collection of items by the specified property. The index for the collection is reset to 1 upon completion of this method.

```<code>Sub SortByDueDate()
 Dim myNameSpace As Outlook.NameSpace
 Dim myFolder As Outlook.Folder
 Dim myItem As Object
 Dim myItems As Outlook.Items

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
 Set myItems = myFolder.Items
 myItems.Sort "[LastModificationTime]", False

 For Each myItem In myItems
   Debug.Print myItem.Subject & "-- " & myItem.DueDate
 Next myItem

End Sub
</code>```

And you don't need to use the Set keyword to assign a date time structure. Set is used to assign a reference to an object.

```<code>dat = obj.LastModificationTime
</code>```

Body:
I am trying to find out the last recieved email in each outlook folder. for some reason, i can print it but cannot assign it to variable.

the set dat =obj.LastModificationTime is throwing exception. how can i fix it?

   Private Sub ProcessFolder(folder As MAPIFolder)

Dim folder2 As MAPIFolder
Dim obj As Object
Dim size As Double

Dim dat As Object
Set dat = Empty
If Not folder.Items Is Nothing Then
    For Each obj In folder.Items

        size = size + obj.size
        If TypeName(obj) = "MailItem" Then
       Debug.Print obj.LastModificationTime
      Set dat = obj.LastModificationTime
       End If

    Next
End If
 ' Create The Object
'Set FSO = CreateObject("Scripting.FileSystemObject")
' How To Write To A File

Debug.Print Now() & "," & folder.Name & "," & folder.Items.Count & "," & size & "," & folder.FolderPath & "," & dat
Set dat = Empty

'File.Write folder.Name & "," & folder.Items.Count & "," & size & "," & folder.FolderPath

For Each folder2 In folder.Folders
    ProcessFolder folder2
Next
'File.Close
End Sub

Sub FolderSize()

    'Needs reference to MS Outlook Object Library

   'Needs reference to MS Outlook Object Library

    Dim objOutlook As Outlook.Application
    Dim objNamespace As Outlook.NameSpace
    Dim objSourceFolder As Outlook.MAPIFolder
    Dim objDestFolder As Outlook.MAPIFolder
    Dim InboxMsg As Object
    Dim Inbox As Outlook.folder
    Dim SystemEmails As String

     Dim filter As String
       Dim olParentFolder As Outlook.MAPIFolder
    Dim olFolderA As Outlook.MAPIFolder
    Dim olFolderB As Outlook.MAPIFolder

    Set objOutlook = Application
    Set objNamespace = objOutlook.GetNamespace("MAPI") '

    Set olParentFolder = objNamespace.GetDefaultFolder(olFolderInbox)

    For Each olFolderA In olParentFolder.Folders
       ' Debug.Print olFolderA.FolderPath, olFolderA.Items.Count, olFolderA.Folders.Count

        ProcessFolder olFolderA

    Next

End Sub

Body:
First of all, there is no need to iterate over all items in the folder:

If Not folder.Items Is Nothing Then
    For Each obj In folder.Items

Instead, you can use the Sort method of the Items class which sorts the collection of items by the specified property. The index for the collection is reset to 1 upon completion of this method.

Sub SortByDueDate()
 Dim myNameSpace As Outlook.NameSpace
 Dim myFolder As Outlook.Folder
 Dim myItem As Object
 Dim myItems As Outlook.Items

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
 Set myItems = myFolder.Items
 myItems.Sort "[LastModificationTime]", False

 For Each myItem In myItems
   Debug.Print myItem.Subject & "-- " & myItem.DueDate
 Next myItem

End Sub

And you don't need to use the Set keyword to assign a date time structure. Set is used to assign a reference to an object.

dat = obj.LastModificationTime


问:
Python regex to find "document" word in a given string in forward direction and replace by empty string
If the word "document" can be produced by removing characters from a given string, the letters spelling "document" are to be removed from the string. If letters from the resulting string can be removed to leave the string "document", the letters spelling "document" in that string are removed. This continues until letters cannot be removed to leave "document", at which time the final string is to be returned.

For example, if the string were:

```<code>documdocumententer
     ^^^^^^^^
</code>```

"document" can be formed by removing "docum" from the beginning and "enter" at the "end", so "document" in the middle is removed, leaving

```<code>documenter
^^^^^^^^
</code>```

The process would then be repeated to leave

```<code>er
</code>```

As "er" does not contain "document", "er" would be returned.

Similarly, if the string were:

```<code>adbocucdmefgnhtj
 ^ ^^^  ^^  ^ ^
</code>```

the letters spelling "document" would be removed to leave:

```<code>abcdfghj
</code>```

This string would be returned because it does not contain "document".

Examples

doconeument is converted to one

documdocumentent is converted to an empty string

documentone is converted to one

pydocdbument is converted to pydb

documentdocument is converted to an empty string

How can I obtain the string of interest from a given string (for the specific word "document" only).

i tried this query by python for loop, but i didn't get idea how to do with only regex
my code is below

```<code>import re
def fun1(text):
    print('original string:', text)
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.sub(pattern, '', text)
    if len(result) == len(text):
        print('return original string because it does not contain "document" word forward direction:')
        return text

    # if word is containing "document" in forward direction

    temp = []   # for storing letter and its index

    # find each letter and index in "document" word
    search_str = 'document'
    for index in range(len(search_str)):
        # if it is a last letter in "document" that is t
        if index == len(search_str)-1:
            current_letter = search_str[index]
            pattern = r'.*n.*t'

        else:
            next_letter = search_str[index + 1]
            current_letter = search_str[index]
            pattern = rf".*{current_letter}.*{next_letter}"

        result = re.match(pattern, text)
        a, b = result.span()
        if temp:
            # value of last dict in temp list
            val = list(temp[-1].values())[0]
            current_letter = val + text[val:].index(current_letter)
        else:
            # first time when temp list is empty
            current_letter = text[a:b].rindex(current_letter)

        temp.append({search_str[index]: current_letter})

    # now using temp list we remove "document" word at specific index
    text = list(text)

    # create a list with index decending order to remove from text
    remove_index_list = [list(i.values())[0] for i in temp]
    remove_index_list.sort(reverse=True)

    for j in remove_index_list:
        text.pop(j)

    final_txt = ''.join(text)
    # to check if text containing or not one more "document" word
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.findall(pattern, final_txt)
    if result:
        print('The word again containing "document" in it')
        final_txt = fun1(final_txt)
    return final_txt
print('final_output:', fun1('doconeument'))
</code>```

答:
I have a solution with regular expressions and recursion:

```<code>from re import compile

candidates = ["doconeument", "documdocumentent",  "documentone",
              "pydocdbument", "documentdocument", "hansi"]
word = "document"

def strip_word(word, candidate):
    regex = compile("^(.*)" + "(.*)".join(word) + "(.*)$")
    match = regex.match(candidate)
    if not match:
        return candidate
    return strip_word(word, "".join(match.groups()))

for cand in candidates:
    print(f"'{cand}' -> '{strip_word(word, cand)}'")
</code>```

Edit: Did a correction on the code (two first lines of function were left outside).

Body:
If the word "document" can be produced by removing characters from a given string, the letters spelling "document" are to be removed from the string. If letters from the resulting string can be removed to leave the string "document", the letters spelling "document" in that string are removed. This continues until letters cannot be removed to leave "document", at which time the final string is to be returned.

For example, if the string were:

documdocumententer
     ^^^^^^^^

"document" can be formed by removing "docum" from the beginning and "enter" at the "end", so "document" in the middle is removed, leaving

documenter
^^^^^^^^

The process would then be repeated to leave

er

As "er" does not contain "document", "er" would be returned.

Similarly, if the string were:

adbocucdmefgnhtj
 ^ ^^^  ^^  ^ ^

the letters spelling "document" would be removed to leave:

abcdfghj

This string would be returned because it does not contain "document".

Examples

doconeument is converted to one

documdocumentent is converted to an empty string

documentone is converted to one

pydocdbument is converted to pydb

documentdocument is converted to an empty string

How can I obtain the string of interest from a given string (for the specific word "document" only).

i tried this query by python for loop, but i didn't get idea how to do with only regex
my code is below

import re
def fun1(text):
    print('original string:', text)
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.sub(pattern, '', text)
    if len(result) == len(text):
        print('return original string because it does not contain "document" word forward direction:')
        return text

    # if word is containing "document" in forward direction

    temp = []   # for storing letter and its index

    # find each letter and index in "document" word
    search_str = 'document'
    for index in range(len(search_str)):
        # if it is a last letter in "document" that is t
        if index == len(search_str)-1:
            current_letter = search_str[index]
            pattern = r'.*n.*t'

        else:
            next_letter = search_str[index + 1]
            current_letter = search_str[index]
            pattern = rf".*{current_letter}.*{next_letter}"

        result = re.match(pattern, text)
        a, b = result.span()
        if temp:
            # value of last dict in temp list
            val = list(temp[-1].values())[0]
            current_letter = val + text[val:].index(current_letter)
        else:
            # first time when temp list is empty
            current_letter = text[a:b].rindex(current_letter)

        temp.append({search_str[index]: current_letter})

    # now using temp list we remove "document" word at specific index
    text = list(text)

    # create a list with index decending order to remove from text
    remove_index_list = [list(i.values())[0] for i in temp]
    remove_index_list.sort(reverse=True)

    for j in remove_index_list:
        text.pop(j)

    final_txt = ''.join(text)
    # to check if text containing or not one more "document" word
    pattern = r"((d|D).*o.*c.*u.*m.*e.*n.*t){1,}"
    result = re.findall(pattern, final_txt)
    if result:
        print('The word again containing "document" in it')
        final_txt = fun1(final_txt)
    return final_txt
print('final_output:', fun1('doconeument'))

Body:
I have a solution with regular expressions and recursion:

from re import compile

candidates = ["doconeument", "documdocumentent",  "documentone",
              "pydocdbument", "documentdocument", "hansi"]
word = "document"

def strip_word(word, candidate):
    regex = compile("^(.*)" + "(.*)".join(word) + "(.*)$")
    match = regex.match(candidate)
    if not match:
        return candidate
    return strip_word(word, "".join(match.groups()))

for cand in candidates:
    print(f"'{cand}' -> '{strip_word(word, cand)}'")

Edit: Did a correction on the code (two first lines of function were left outside).


问:
SQL Server 2019 External Script Execution Authentication Error on JKS File
I'm attempting to put a POC together that leverages the SQL Server 2019 Extensibility Framework & External Languages feature. This enables execution of external languages in SQL Server Stored procedures. I've written a JAR file that encrypts and decrypts data being passed via a SQL Server stored procedure. I've confirmed that the each method is correct, and returns the correct values when not being sent as a stored procedure. However, when executing the stored procedure I receive an empty data set and see the following error in debug mode:

java.io.FileNotFoundException: <jks-file-location> (Access is denied)

The line of Java code throwing the error is below:

```<code>       Key _key = readKeyFromStore_cbs("<jks-file-location>, "<password>".toCharArray(), "entityEncryption", "<password>".toCharArray());
       _keySpec = new SecretKeySpec(_key.getEncoded(), _key.getAlgorithm());
</code>```

Again, the code is fine, I don't think there are issues there, and don't think posting the content of those methods is the issue (the SP itself runs fine with dummy data in the place of data being encrypted and decrypted, and the code with encryption and decryption runs as expected when run on its own).

Additional Info:

I'm running this on a local Windows 10 environment and have given "Everyone" full security permissions on the jks.

I've double checked the user running sql server and ensured that user has full permissions on the file as well. (This user also has admin privileges on SQL Server)

I've checked SQL Server sp_configure options as well.

Filestream is enabled and set to full control in sp_configure

I've even disabled clr strict security on sp_configure to see if that was the cause. I still receive the same error.

I've attempted tests with JKS in my User directory (with permissions on the directory and file for the SQL Server user), in the C drive, and in the child directory of the C drive (again, with permissions on the directory and file for the SQL Server user)

The stored procedure runs, but is returning an empty data set. When attempting run without encryption (using the key from the currently inaccessible keystore) and using dummy data, I receive the expected data set.

Anyone know what might be causing this error?

答:
UPDATE:
Moving the JAR and jks into SQL Server directories and starting the Launchpad service resolved the issue. Hope this helps someone avoid similar frustrations.</p>

Body:
I'm attempting to put a POC together that leverages the SQL Server 2019 Extensibility Framework & External Languages feature. This enables execution of external languages in SQL Server Stored procedures. I've written a JAR file that encrypts and decrypts data being passed via a SQL Server stored procedure. I've confirmed that the each method is correct, and returns the correct values when not being sent as a stored procedure. However, when executing the stored procedure I receive an empty data set and see the following error in debug mode:

java.io.FileNotFoundException: <jks-file-location> (Access is denied)

The line of Java code throwing the error is below:

       Key _key = readKeyFromStore_cbs("<jks-file-location>, "<password>".toCharArray(), "entityEncryption", "<password>".toCharArray());
       _keySpec = new SecretKeySpec(_key.getEncoded(), _key.getAlgorithm());

Again, the code is fine, I don't think there are issues there, and don't think posting the content of those methods is the issue (the SP itself runs fine with dummy data in the place of data being encrypted and decrypted, and the code with encryption and decryption runs as expected when run on its own).

Additional Info:

I'm running this on a local Windows 10 environment and have given "Everyone" full security permissions on the jks.

I've double checked the user running sql server and ensured that user has full permissions on the file as well. (This user also has admin privileges on SQL Server)

I've checked SQL Server sp_configure options as well.

Filestream is enabled and set to full control in sp_configure

I've even disabled clr strict security on sp_configure to see if that was the cause. I still receive the same error.

I've attempted tests with JKS in my User directory (with permissions on the directory and file for the SQL Server user), in the C drive, and in the child directory of the C drive (again, with permissions on the directory and file for the SQL Server user)

The stored procedure runs, but is returning an empty data set. When attempting run without encryption (using the key from the currently inaccessible keystore) and using dummy data, I receive the expected data set.

Anyone know what might be causing this error?


问:
What are the possible returns of a function in JavaScript?
I wonder what would be the possible returns of a given function in JavaScript.

Someone has a list of the possibilities?

I guess the possibilites are around the diferent types of a variable, that I know as this types:

undefined;

null;

boolean;

number;

string;

object.

答:
Return types in any programming language, including Javascript, can be determined by the list of types it support. You can of course combine a lot of these like:

An array of booleans

An object that has array value

An array of objects/array

You can see the list of datatypes in Javascript here. But pretty much you have six primitive types:

undefined

Boolean

Number

String

BigInt

Symbol

And:

null

and finally object. Arrays, Set, Date are all objects. What that means is that, for example, an array is just a special type of object with key/value pairs and you can access these properties by doing e.g. array.length.

Function is another type of special object.


问:
ASM 8086 division without div
I need to write in asm 8086 a program like b=a/6 but without the DIV instruction. I know how to do it with SAR but only 2,4,8,16...

```<code>mov ax,a
sar ax,1 ;//div a by 2
mov b,ax
</code>```

my question is how can I do it to div by 6?

答:
The approach given an another answer is simple brute force loop, and can take a while for large values of a. This is a version that uses larger chunks (working it like a long division problem) specifically coded to divide a signed number by 6:

```<code>; signed divide by 6
    mov ax,a
    mov cx,1000h  ; initial count of how many divisors into ax to check for
    mov bx,6000h  ; value of "divisor * cx"
    xor dx,dx     ; result
top:
    cmp ax,bx
    jl skip
    ; we can fit "cx" copies of the divisor into ax, so tally them
    add dx,cx
    sub ax,bx
    ; optionally can have a "jz done" here to break out of the loop
skip:
    shr bx,1
    shr cx,1
    jnz top

    ; copy result into ax
    mov ax,dx
</code>```

If you need to divide something other than 6, the initial cx and bx values need to be adjusted. cx is the power-of-two multiple of the divisor that leaves bit 14 set (since bit 15 is the sign bit; for an unsigned divide you'd want to have bit 15 set instead). bx is that power of 2. If there are limits on the initial value for a you can adjust the initial cx and bx values, but have to be careful because you'll get an incorrect answer if you make them too small.

Title: ASM 8086 division without div

Body:
I need to write in asm 8086 a program like b=a/6 but without the DIV instruction. I know how to do it with SAR but only 2,4,8,16...

mov ax,a
sar ax,1 ;//div a by 2
mov b,ax

my question is how can I do it to div by 6?

Body:
The approach given an another answer is simple brute force loop, and can take a while for large values of a. This is a version that uses larger chunks (working it like a long division problem) specifically coded to divide a signed number by 6:

; signed divide by 6
    mov ax,a
    mov cx,1000h  ; initial count of how many divisors into ax to check for
    mov bx,6000h  ; value of "divisor * cx"
    xor dx,dx     ; result
top:
    cmp ax,bx
    jl skip
    ; we can fit "cx" copies of the divisor into ax, so tally them
    add dx,cx
    sub ax,bx
    ; optionally can have a "jz done" here to break out of the loop
skip:
    shr bx,1
    shr cx,1
    jnz top

    ; copy result into ax
    mov ax,dx

If you need to divide something other than 6, the initial cx and bx values need to be adjusted. cx is the power-of-two multiple of the divisor that leaves bit 14 set (since bit 15 is the sign bit; for an unsigned divide you'd want to have bit 15 set instead). bx is that power of 2. If there are limits on the initial value for a you can adjust the initial cx and bx values, but have to be careful because you'll get an incorrect answer if you make them too small.


问:
python request.get always throws status code 200
python request.get always throws status code 200 . This is coming even after adding an user agent in the request.get( ) .
As status_code is always 200 , a file from that website is downloaded even if doesn't exists there .
How to get correct atatus_code ?</p>

答: 200 - "The HTTP 200 OK success status response code indicates that the request has succeeded."  This means it worked! Now, on to the next steps... :)


问:
how to use selectors in redux app with TypeScript?
I try to use selectors from reselect library in my Redux app.

my selectors file looks:

```<code>import { createSelector } from 'reselect'

const postsSelectors = state => state.global.posts.allPostse;

export const getPosts = createSelector(
  [ postsSelectors ],
  (posts) => posts
);
</code>```

and then I try to use in my component, like this:

```<code>const mapStateToProps = (state) => ({
  posts: getPosts(state),
});
</code>```

When I try to compile all of this, I got this error:

I'm guessing that with how I declare types for props, which currently looks like that:

```<code>interface Props{
 posts(state: any): any
 loadStories(): void;
};
</code>```

Help me please resolve this issue. Thanks in advance.

答:
An example with more types:

Describe types

type TPostData = {
  type: string;
};

type TPostsState = TPostData[];

type TState = {
  posts: TPostsState;
};
```

<ol start="2">
<li>Create selectors</li>
</ol>

<pre class="lang-js prettyprint-override"><code>// get all posts
export const selectPosts = (state: TState): TPostsState => state.posts;

// get new posts
export const selectNewPosts = createSelector<
  TState,
  TPostsState,
  TPostData[]>(
    selectPosts,
    (posts) => posts.filter(({ type }) => type === 'new'),
  );
</code>```

Result: You've got all posts with type parameter 'new'.

Body:
I try to use selectors from reselect library in my Redux app.

my selectors file looks:

import { createSelector } from 'reselect'

const postsSelectors = state => state.global.posts.allPostse;

export const getPosts = createSelector(
  [ postsSelectors ],
  (posts) => posts
);

and then I try to use in my component, like this:

const mapStateToProps = (state) => ({
  posts: getPosts(state),
});

When I try to compile all of this, I got this error:

I'm guessing that with how I declare types for props, which currently looks like that:

interface Props{
 posts(state: any): any
 loadStories(): void;
};

Help me please resolve this issue. Thanks in advance.

Body:
An example with more types:

Describe types

type TPostData = {
  type: string;
};

type TPostsState = TPostData[];

type TState = {
  posts: TPostsState;
};

Create selectors

// get all posts
export const selectPosts = (state: TState): TPostsState => state.posts;

// get new posts
export const selectNewPosts = createSelector<
  TState,
  TPostsState,
  TPostData[]>(
    selectPosts,
    (posts) => posts.filter(({ type }) => type === 'new'),
  );

Result: You've got all posts with type parameter 'new'.


问:
How to protect reactjs resources with spring boot based authentiation?
My current project state:

I am working on a Web Application with ReactJs (frontend) and spring boot (backend).

When I deploy this application, I package react code with my spring boot jar using gradle-node-plugin

Problem:

I understand that I should serve all the resources that require authentication from the server. - However, I'm having a hard time understanding if there is a way to put certain components/routes of my react project behind the authentication API.

An example is Google Docs, where Google does not let you create any new document (or even see the text canvas) without actually logging in.

Currently only the data I'm loading from the database is protected under spring security, but I have a design tool written in Javascript in my react project, that I'd like to protect as well.

Is this possible through spring security or should I just assume that everything under my react project can be accessed publicly?

In other words how do I protect the javascript based UI only page, where you are not making any backend calls to get authentication information.

Thank you!

答:
Call Authenticate API when the page loads to see if user's session is authenticated. I think spring security can do this. Based on the response, you can restrict the route.

```<code><Route
      {...rest}
      render={({ location }) =>
        authenticateApiResponse.authenticated ? (
          <Redirect
            to={{
              pathname: "/profile",
              state: { from: location }
            }}
          />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
</code>```

Now user can only go to profile screen if he's authenticated by backend API.

Body:
Call Authenticate API when the page loads to see if user's session is authenticated. I think spring security can do this. Based on the response, you can restrict the route.

<Route
      {...rest}
      render={({ location }) =>
        authenticateApiResponse.authenticated ? (
          <Redirect
            to={{
              pathname: "/profile",
              state: { from: location }
            }}
          />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />

Now user can only go to profile screen if he's authenticated by backend API.


问:
How to detect irregular placed bottles in the red circle while exclude those regular circle bottle by Matlab?
I only want to detect those irregular bottles, for example, in red circle:

However, I have tried several methods, but they find all edge bottle in the image, is there some way to dectect only slanting bottle or how I change my method?

```<code>f15 = imread('bottle_crate_15.png');
BW_15 = imbinarize(f15);

%Canny:
    BW_canny = edge(BW_15, 'Canny');
    imshow(BW_canny);

%bwboundaries
[B,L,N,A] = bwboundaries(BW_15, 'noholes');
imshow(label2rgb(L, @jet, [.5 .5 .5]))
hold on
for k = 1:length(B)
   boundary = B{k};
   plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)
end

%dilate:
im = mean(f15,4);
im = (im-min(im(:))) / (max(im(:))-min(im(:)));

bin = im2bw(im);
SE = strel('disk',1);
bin = ~imerode(~bin,SE);
bin = ~imerode(~bin,SE);

bin =~imdilate(~bin,SE);
bin =~imdilate(~bin,SE);
imshow(bin);
</code>```

ps: the origin image:

答:
If its already sufficient, one approach could be to classify if there is any bottle not correctly placed:

1.) detect the grid structure in the beverage crate (hough lines).
Then, you should be able to segment the image into the areas where the bottle should be placed.

2.) For each placement area you can classify if it contains a bottle, is empty, or looks different. There are several ways to approach this. In case you have acess to multiple images showing beverage crates, you can train a classifier (using SVM or CNN).
If you do not have enough training images,  you can still use low level image processing techniques to classify the areas (e.g. using circle detection to detect placement areas which contain bottles).

One approach to detect the wrongly placed bottle:

Apply an object detector (e.g. https://www.mathworks.com/help/deeplearning/ug/object-detection-using-yolo-v2.html?s_tid=blogs_rc_6) to localize all bottles. Ignore the detections which are correctly within the placement areas (e.g. using hough lines).
The remaining detections depict wrongly placed bottles.

Also, you could directly train an object detector to detect missplaced bottles by collecting and annotating corresponding images (https://de.mathworks.com/help/vision/ref/trainrcnnobjectdetector.html).

Body:
I only want to detect those irregular bottles, for example, in red circle:

However, I have tried several methods, but they find all edge bottle in the image, is there some way to dectect only slanting bottle or how I change my method?

f15 = imread('bottle_crate_15.png');
BW_15 = imbinarize(f15);

%Canny:
    BW_canny = edge(BW_15, 'Canny');
    imshow(BW_canny);

%bwboundaries
[B,L,N,A] = bwboundaries(BW_15, 'noholes');
imshow(label2rgb(L, @jet, [.5 .5 .5]))
hold on
for k = 1:length(B)
   boundary = B{k};
   plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)
end

%dilate:
im = mean(f15,4);
im = (im-min(im(:))) / (max(im(:))-min(im(:)));

bin = im2bw(im);
SE = strel('disk',1);
bin = ~imerode(~bin,SE);
bin = ~imerode(~bin,SE);

bin =~imdilate(~bin,SE);
bin =~imdilate(~bin,SE);
imshow(bin);

ps: the origin image:


问:
Iterate over two arrays simultaneously in List
How can I iterate two array in a list:

```<code>struct ContentView: View {
    let colors = ["red", "green", "blue"]
    let names = ["John", "Apple", "Seed"]

    var body: some View {
        VStack {
            List(colors, id: \.self) { color in
                Text(color)
            }
        }
    }
}
</code>```

For example I need to have:
Text("\(color) - \(animal)")

My code would be like this (I know it's wrong but that's the idea):

```<code>    List(colors, animals id: \.self) { color, animal in
        Text("\(color) - \(animal)")
    }
</code>```

答:
Or, if you want to get two nice columns that you can manipulate the way you want it:

```<code>import SwiftUI

struct ContentView: View {

    let colors = ["red", "blue", "black", "purple", "green"]
    let names = ["Paul", "Chris", "Rob", "Terry", "Andy"]

    var body: some View {

        HStack {

            List(names, id: \.self) { name in
                Text(name)
            }
            .frame(width: 130)

            List(colors, id: \.self) { color in
                Text(color)
            }
            .frame(width: 160)
        }
    }
}
</code>```

And then you get the result like this:

Body:
How can I iterate two array in a list:

struct ContentView: View {
    let colors = ["red", "green", "blue"]
    let names = ["John", "Apple", "Seed"]

    var body: some View {
        VStack {
            List(colors, id: \.self) { color in
                Text(color)
            }
        }
    }
}

For example I need to have:
Text("\(color) - \(animal)")

My code would be like this (I know it's wrong but that's the idea):

    List(colors, animals id: \.self) { color, animal in
        Text("\(color) - \(animal)")
    }

Body:
Or, if you want to get two nice columns that you can manipulate the way you want it:

import SwiftUI

struct ContentView: View {

    let colors = ["red", "blue", "black", "purple", "green"]
    let names = ["Paul", "Chris", "Rob", "Terry", "Andy"]

    var body: some View {

        HStack {

            List(names, id: \.self) { name in
                Text(name)
            }
            .frame(width: 130)

            List(colors, id: \.self) { color in
                Text(color)
            }
            .frame(width: 160)
        }
    }
}

And then you get the result like this:


问:
C++ help with error : cannot convert parameter 1 from 'float' to 'float [][2]
and I was doing a program, that isn't so important. Apparently, I cant send parameters to a float function.
the code look something like this

```<code>float myfunction(float array[1][2])
{
// ...
return 0;
}

int main()
{
float array[1][2];
int foo = 0;
// assigning values to the array

foo = myfunction(array[1][2]);
return 0;
}
</code>```

when I try to compile, I get the error "cannot convert parameter 1 from 'float' to 'float [][2]"
What is wrong? And how can I solve it?

答:
You've defined the variable: float array[1][2];
Then, you call the function in this way: foo = myfunction(array);
As a parameter, only you have to set the variable name. You shouldn't do this: foo = myfunction(array[1][2]);

When you make a function, do it in this way: type myfunction(float Array[][w]) , being type the type of function (void, float...) and "w" a constant integer.

ContentLicense: CC BY-SA 2.5

Body:
and I was doing a program, that isn't so important. Apparently, I cant send parameters to a float function.
the code look something like this

float myfunction(float array[1][2])
{
// ...
return 0;
}

int main()
{
float array[1][2];
int foo = 0;
// assigning values to the array

foo = myfunction(array[1][2]);
return 0;
}

when I try to compile, I get the error "cannot convert parameter 1 from 'float' to 'float [][2]"
What is wrong? And how can I solve it?


问:
Why does SASS darken/lighten seem to calculate the wrong grayscale?
This is a simple grayscale I made in Photoshop:

As you can see; the mid point (50%) between white and black is found to be #808080. This also correspond to what SASS would calculate given the following code:

```<code>$gray: darken(white, 50%); // #808080
</code>```

However, in Photoshop the 25% mark is found to be #CCCCCB, while this happens in SASS:

```<code>$light-gray: darken(white, 25%); // #BFBFBF
</code>```

The same difference also happens on 75%, which in Photoshop is found to be #333333, while in SASS becomes:

```<code>$dark-gray: darken(white, 75%); // #404040
</code>```

Why this discrepancy?

答:
I don't know the configuration you are using with Photoshop but the values returned by darken() are correct.

Below I made a gradient from white to black and it's not the same as the one you are showing and if you pick colors from it you will get the value returned by darken()

img {
  max-width:100%;
  margin-bottom:200px;
}

body {
  margin:0;
  background:linear-gradient(to right,white,black);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.stack.imgur.com/2gljG.png"></code>```

And if we make the calculation we can also find the same:

```<code>darken(white, 25%) == hsl(0,0%,(100% - 25%)) == hsl(0,0%,75%) == #bfbfbf
darken(white, 75%) == hsl(0,0%,(100% - 75%)) == hsl(0,0%,25%) == #404040
</code>```

Related: How to create color shades using CSS variables similar to darken() of SASS?

After few tests I found that your grayscale isn't linear but follow a non linear function that can explain the issue.

To illustrate this here is a basic animation of two elements not having the same ease function that animate from white to black. Notice how both will start at the same position, end at the same position and meet in the middle but will have different position on the road. So the 25% and the 75% of each animation won't be the same but the 50% will be.

img {
  max-width:100%;
  margin-bottom:200px;
}
body {
  margin:0;
}

body::before,
body::after{
  content:"";
  position:fixed;
  left:0;
  top:150px;
  width:10px;
  height:20px;
  border:2px solid green;
  background:#fff;
  animation:move 10s infinite alternate ease-in-out;
}
body::after {
  top:170px;
  animation:move 10s infinite alternate linear;
}
@keyframes move{
  from {
    left:0;
    background:#fff;
  }
  to {
    left:100%;
    background:#000;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.stack.imgur.com/2gljG.png"></code>```

I don't have access to photoshop but I am pretty sure this is the issue. If you check the configuration you will probably find how you can define the function and if you make it linear you will have the same result.

Body:
This is a simple grayscale I made in Photoshop:

As you can see; the mid point (50%) between white and black is found to be #808080. This also correspond to what SASS would calculate given the following code:

$gray: darken(white, 50%); // #808080

However, in Photoshop the 25% mark is found to be #CCCCCB, while this happens in SASS:

$light-gray: darken(white, 25%); // #BFBFBF

The same difference also happens on 75%, which in Photoshop is found to be #333333, while in SASS becomes:

$dark-gray: darken(white, 75%); // #404040

Why this discrepancy?

Body:
I don't know the configuration you are using with Photoshop but the values returned by darken() are correct.

Below I made a gradient from white to black and it's not the same as the one you are showing and if you pick colors from it you will get the value returned by darken()

img {
  max-width:100%;
  margin-bottom:200px;
}

body {
  margin:0;
  background:linear-gradient(to right,white,black);
}

<img src="https://i.stack.imgur.com/2gljG.png">

And if we make the calculation we can also find the same:

darken(white, 25%) == hsl(0,0%,(100% - 25%)) == hsl(0,0%,75%) == #bfbfbf
darken(white, 75%) == hsl(0,0%,(100% - 75%)) == hsl(0,0%,25%) == #404040

Related: How to create color shades using CSS variables similar to darken() of SASS?

After few tests I found that your grayscale isn't linear but follow a non linear function that can explain the issue.

To illustrate this here is a basic animation of two elements not having the same ease function that animate from white to black. Notice how both will start at the same position, end at the same position and meet in the middle but will have different position on the road. So the 25% and the 75% of each animation won't be the same but the 50% will be.

img {
  max-width:100%;
  margin-bottom:200px;
}
body {
  margin:0;
}

body::before,
body::after{
  content:"";
  position:fixed;
  left:0;
  top:150px;
  width:10px;
  height:20px;
  border:2px solid green;
  background:#fff;
  animation:move 10s infinite alternate ease-in-out;
}
body::after {
  top:170px;
  animation:move 10s infinite alternate linear;
}
@keyframes move{
  from {
    left:0;
    background:#fff;
  }
  to {
    left:100%;
    background:#000;
  }
}

<img src="https://i.stack.imgur.com/2gljG.png">

I don't have access to photoshop but I am pretty sure this is the issue. If you check the configuration you will probably find how you can define the function and if you make it linear you will have the same result.


问:
C++ does not use the desired constructor
So there seems to be some problem with the solution to Problem 9-2 in the book "Object-Oriented Programming in C++, 4th edition" by Robert Lafore. So the problem is that if I would like to create a Pstring object with a statement like Pstring = "This is a string", the Pstring constructor will only call the constructor with no arguments in the String class, instead of the second one with uses one char[] argument. Does anyone know what causes this kind of problem, and a fix to this? Thanks!

```<code>#include <iostream>
#include <cstring>
using namespace std;
////////////////////////////////////////////////////////////////
class String                      //base class
{
protected:                     //Note: can't be private
    enum {
        SZ = 80
    };           //size of all String objects
    char str[SZ];               //holds a C-string
public:
    String()                    //constructor 0, no args
    {
        str[0] = '\0';
    }
    String(char s[])          //constructor 1, one arg
            {
        strcpy(str, s);
    }      //  convert string to String
    void display() const        //display the String
    {
        cout << str;
    }
    operator char*()            //conversion function
    {
        return str;
    }          //convert String to C-string
};
////////////////////////////////////////////////////////////////
class Pstring: public String     //derived class
{
public:
    Pstring(char s[]);        //constructor
};
//--------------------------------------------------------------
Pstring::Pstring(char s[])      //constructor for Pstring
        {
    if (strlen(s) > SZ - 1)           //if too long,
            {
        for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
            str[j] = s[j];           //characters "by hand"
            str[j] = '\0';
        }           //add the null character
    } else
        //not too long,
        String(s);                  //so construct normally
}
////////////////////////////////////////////////////////////////
int main() {                                        //define String
    String s1 = "This is a string"; // This works great
    s1.display();
    Pstring s2 = "This is a string"; // *** Here, nothing will be assigned to s2****
    s2.display();                    // *** Nothing will be printed here***
    return 0;
}
</code>```

答:
In C++, constructors aren't allowed to be called like this:

```<code>else
    //not too long,
    String(s);
</code>```

C++ wants you to use its initialization list instead (see the link above for some examples).

If you have a portion of the construction in the parent class you would like to call from inside the child constructor, you can use a protected method instead:

```<code>class String                      //base class
{
protected:
    void commonTask(char s[]) {
        // do something...
    }
public:
    String(char s[])
    {
        commonTask(s);
    }
};

class Pstring: public String
{
public:
    Pstring(char s[]) {        //constructor
        if(someCondition) {
            commonTask(s);
        }
    }
};
</code>```

I'm using pseudo code here, but hopefully you get the idea.

Body:
So there seems to be some problem with the solution to Problem 9-2 in the book "Object-Oriented Programming in C++, 4th edition" by Robert Lafore. So the problem is that if I would like to create a Pstring object with a statement like Pstring = "This is a string", the Pstring constructor will only call the constructor with no arguments in the String class, instead of the second one with uses one char[] argument. Does anyone know what causes this kind of problem, and a fix to this? Thanks!

#include <iostream>
#include <cstring>
using namespace std;
////////////////////////////////////////////////////////////////
class String                      //base class
{
protected:                     //Note: can't be private
    enum {
        SZ = 80
    };           //size of all String objects
    char str[SZ];               //holds a C-string
public:
    String()                    //constructor 0, no args
    {
        str[0] = '\0';
    }
    String(char s[])          //constructor 1, one arg
            {
        strcpy(str, s);
    }      //  convert string to String
    void display() const        //display the String
    {
        cout << str;
    }
    operator char*()            //conversion function
    {
        return str;
    }          //convert String to C-string
};
////////////////////////////////////////////////////////////////
class Pstring: public String     //derived class
{
public:
    Pstring(char s[]);        //constructor
};
//--------------------------------------------------------------
Pstring::Pstring(char s[])      //constructor for Pstring
        {
    if (strlen(s) > SZ - 1)           //if too long,
            {
        for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
            str[j] = s[j];           //characters "by hand"
            str[j] = '\0';
        }           //add the null character
    } else
        //not too long,
        String(s);                  //so construct normally
}
////////////////////////////////////////////////////////////////
int main() {                                        //define String
    String s1 = "This is a string"; // This works great
    s1.display();
    Pstring s2 = "This is a string"; // *** Here, nothing will be assigned to s2****
    s2.display();                    // *** Nothing will be printed here***
    return 0;
}

Body:
In C++, constructors aren't allowed to be called like this:

else
    //not too long,
    String(s);

C++ wants you to use its initialization list instead (see the link above for some examples).

If you have a portion of the construction in the parent class you would like to call from inside the child constructor, you can use a protected method instead:

class String                      //base class
{
protected:
    void commonTask(char s[]) {
        // do something...
    }
public:
    String(char s[])
    {
        commonTask(s);
    }
};

class Pstring: public String
{
public:
    Pstring(char s[]) {        //constructor
        if(someCondition) {
            commonTask(s);
        }
    }
};

I'm using pseudo code here, but hopefully you get the idea.


问:
C++: Container of different types
I have some functions (simple for this example) with different paramaters:

```<code>int addNums(int a, int b) {
    return a + b;
}

int squareNum(int a) {
    return a * a;
}
</code>```

I have a template class action which has a function pointer which will eventually point to either of the above functions:

```<code>template<class T>
class action {
public:
    std::string descriptionOfAction;
    T functionPtr;
};
</code>```

I have a class user which should have some form of a container of actions:

```<code>class user {
public:
    std::string name;

    //container of actions
};
</code>```

In main, I defined and initialized two actions to correspond with the first two functions listed above:

```<code>action<int(*)(int, int)> addAction;
addAction.descriptionOfAction = "Add two numbers together";
addAction.functionPtr = addNums;

action<int(*)(int)> squareAction;
squareAction.descriptionOfAction = "Square a number";
squareAction.functionPtr = squareNum;
</code>```

Now I want to insert both of these actions into a users container of actions:

```<code>user aUser;
aUser.name = "User's Name";
//insert "addAction" and "squareAction" to user's container of actions
</code>```

Because of the templating, these actions are not the same types. Is there an existing type of container to hold these? If not, is there a way to do something similar without templates? Ideally, when a user "uses" one of the actions in their container, the action should be erased.

答:
The problem here is that functions have different arity (i.e., the number of arguments).

It's not much of a problem to put your functions into some container. You can always put your functions into an std::vector<void*> (the compiler does not care), but then... what? What's the plan?

You will also need to add function arity to the same container, so it transforms to std::vector<std::pair<void*, unsigned int>> (function pointer + arity). This automatically complicates your action adding, since you will obviously won't want to specify the arity by hand, and you will want to automate this in order to avoid any human error. This will involve templates. Moreover, you will need to manually inspect the arities and pass the appropriate number of parameters. This will be error prone, too.

The most simple approach would be to define some

```<code>struct my_function_interface {
    virtual int operator()(<all your parameters here>) = 0;
};
</code>```

And then define your actions in term of that interface. This is a classic OOP solution, which abstracts away all your problems. Moreover, it will most likely be more performant, since all your checks and special function invocations won't come for free. Here, you will have a single virtual function call.

Title: C++: Container of different types

Body:
I have some functions (simple for this example) with different paramaters:

int addNums(int a, int b) {
    return a + b;
}

int squareNum(int a) {
    return a * a;
}

I have a template class action which has a function pointer which will eventually point to either of the above functions:

template<class T>
class action {
public:
    std::string descriptionOfAction;
    T functionPtr;
};

I have a class user which should have some form of a container of actions:

class user {
public:
    std::string name;

    //container of actions
};

In main, I defined and initialized two actions to correspond with the first two functions listed above:

action<int(*)(int, int)> addAction;
addAction.descriptionOfAction = "Add two numbers together";
addAction.functionPtr = addNums;

action<int(*)(int)> squareAction;
squareAction.descriptionOfAction = "Square a number";
squareAction.functionPtr = squareNum;

Now I want to insert both of these actions into a users container of actions:

user aUser;
aUser.name = "User's Name";
//insert "addAction" and "squareAction" to user's container of actions

Because of the templating, these actions are not the same types. Is there an existing type of container to hold these? If not, is there a way to do something similar without templates? Ideally, when a user "uses" one of the actions in their container, the action should be erased.

Body:
The problem here is that functions have different arity (i.e., the number of arguments).

It's not much of a problem to put your functions into some container. You can always put your functions into an std::vector<void*> (the compiler does not care), but then... what? What's the plan?

You will also need to add function arity to the same container, so it transforms to std::vector<std::pair<void*, unsigned int>> (function pointer + arity). This automatically complicates your action adding, since you will obviously won't want to specify the arity by hand, and you will want to automate this in order to avoid any human error. This will involve templates. Moreover, you will need to manually inspect the arities and pass the appropriate number of parameters. This will be error prone, too.

The most simple approach would be to define some

struct my_function_interface {
    virtual int operator()(<all your parameters here>) = 0;
};

And then define your actions in term of that interface. This is a classic OOP solution, which abstracts away all your problems. Moreover, it will most likely be more performant, since all your checks and special function invocations won't come for free. Here, you will have a single virtual function call.


问:
Can I regenerate .designer.cs based on a manually edited .dbml?
I've made some modifications (renamings mostly) in a DBML file manually (using a text editor). Can I use VisualStudio to recreate the .designer.cs file based on new DBML?</p>

答: Right click on your dbml file and select "Run Custom Tool"</p>


问:
Converting .m3u playlists from Windows for Android media players using Notepad++
Winamp saves playlists that are saved in same folder as the music as relative paths for Windows, but copying and pasting into Android doesn't work unless I convert it to Linux relative paths. So

```<code>#EXTM3U
#EXTINF:262,Corona - Rhythm Of The Night
Unsorted\Corona - Rhythm Of The Night.mp3
#EXTINF:324,The B-52's - Love Shack
The B-52's - Love Shack.mp3
</code>```

needs conversion to

```<code>#EXTM3U
#EXTINF:262,Corona - Rhythm Of The Night
./Unsorted/Corona - Rhythm Of The Night.mp3
#EXTINF:324,The B-52's - Love Shack
./The B-52's - Love Shack.mp3
</code>```

for VLC Player on Android to read the playlist properly.

Well, figuring out how to convert \ to / on Notepad++ without regular expressions enabled was easy enough, but I'm too new at regex to get a grip on how to even read the table of contents on its guides even though all I want to do after that is to add ./ to the start of every odd line after the first line.

答:
You do not need to use regular expressions for this.
Just replace "/" with "\", it's that simple.

Then, you need to specify the correct path by removing the previous android path, which may be the internal memory or SD card to match your directory tree

In the example in the image above, the playlist must be in the same directory as the songs (the folder structure) on android to work, as the player will search for the songs in the current directory symbolized by ". \"
For the playlist to work anywhere it will be run inside windows, you need to replace it with the full path, as in the image below

Body:
Winamp saves playlists that are saved in same folder as the music as relative paths for Windows, but copying and pasting into Android doesn't work unless I convert it to Linux relative paths. So

#EXTM3U
#EXTINF:262,Corona - Rhythm Of The Night
Unsorted\Corona - Rhythm Of The Night.mp3
#EXTINF:324,The B-52's - Love Shack
The B-52's - Love Shack.mp3

needs conversion to

#EXTM3U
#EXTINF:262,Corona - Rhythm Of The Night
./Unsorted/Corona - Rhythm Of The Night.mp3
#EXTINF:324,The B-52's - Love Shack
./The B-52's - Love Shack.mp3

for VLC Player on Android to read the playlist properly.

Well, figuring out how to convert \ to / on Notepad++ without regular expressions enabled was easy enough, but I'm too new at regex to get a grip on how to even read the table of contents on its guides even though all I want to do after that is to add ./ to the start of every odd line after the first line.