问:
Would like to make my progressbar as smooth as possible
Can anyone help me make this progessbar smoother?

This is my javascript code for the progressbar. I hope you can do something with it and help me with it.
I would like to improve the smoothness because it is very stuttering at a higher runtime.

```<code>        window.addEventListener('message', (event) => {
            var item = event.data;

            if (item !== undefined && item.type === "ui") {
                if (item.display === true) {
                    $(".container").fadeIn(700);

                    var start = new Date();

                    var title = item.title;
                    var maxTime = item.time;
                    var text = item.text;
                    var timeoutVal = Math.floor(maxTime/100);
                    animateUpdate();
                    $('#notifyMsg').text(text);
                    $('#notifyHead').text(title);

                    function updateProgress(percentage) {
                        $('#progb').css("width", percentage + "%");
                    }

                    function animateUpdate() {
                        var now = new Date();
                        var timeDiff = now.getTime() - start.getTime();
                        var perc = Math.round((timeDiff/maxTime)*100);
                        if (perc <= 100) {
                            updateProgress(perc);
                            setTimeout(animateUpdate, timeoutVal);
                        } else {
                            $(".container").fadeOut(700);
                        }
                    }

                } else {
                    $("#container").hide();
                }
            }
        });
</code>```

答:
You should use window.requestAnimationFrame instead of setTimeout. This function runs on every animation cycle.

And adjust your animateUpdate function.

function animateUpdate() {
    var now = new Date();
    var timeDiff = now.getTime() - start.getTime();
    var perc = Math.round((timeDiff/maxTime)*100);
    if (perc <= 100) {
        updateProgress(perc);
        // Changed this line
        window.requestAnimationFrame(animateUpdate)
    } else {
        $(".container").fadeOut(700);
    }
}
```

Here are the docs of window.requestAnimationFrame.

Body:
Can anyone help me make this progessbar smoother?

This is my javascript code for the progressbar. I hope you can do something with it and help me with it.
I would like to improve the smoothness because it is very stuttering at a higher runtime.

        window.addEventListener('message', (event) => {
            var item = event.data;

            if (item !== undefined && item.type === "ui") {
                if (item.display === true) {
                    $(".container").fadeIn(700);

                    var start = new Date();

                    var title = item.title;
                    var maxTime = item.time;
                    var text = item.text;
                    var timeoutVal = Math.floor(maxTime/100);
                    animateUpdate();
                    $('#notifyMsg').text(text);
                    $('#notifyHead').text(title);

                    function updateProgress(percentage) {
                        $('#progb').css("width", percentage + "%");
                    }

                    function animateUpdate() {
                        var now = new Date();
                        var timeDiff = now.getTime() - start.getTime();
                        var perc = Math.round((timeDiff/maxTime)*100);
                        if (perc <= 100) {
                            updateProgress(perc);
                            setTimeout(animateUpdate, timeoutVal);
                        } else {
                            $(".container").fadeOut(700);
                        }
                    }

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

Body:
You should use window.requestAnimationFrame instead of setTimeout. This function runs on every animation cycle.

And adjust your animateUpdate function.

function animateUpdate() {
    var now = new Date();
    var timeDiff = now.getTime() - start.getTime();
    var perc = Math.round((timeDiff/maxTime)*100);
    if (perc <= 100) {
        updateProgress(perc);
        // Changed this line
        window.requestAnimationFrame(animateUpdate)
    } else {
        $(".container").fadeOut(700);
    }
}

Here are the docs of window.requestAnimationFrame.


来源: stackexchange

问:
Declaring variable without var sign in beginning?
I have seen class that states var _hello_kitty = array(); why they dont use $? i tried to make it public and static and it does not work without adding $i.e. public static $_hello_kitty = array();

now when i do add $ other functions who reference it by _hello_kitty stop working.

EDIT: OOOPS was my bad i somehow removed $ from there, i looped up original file and its there. but its still referencing like $this->_tpl_vars[$tpl_var] = &$value without $ and i cannot use self::_tpl_vars[$tpl_var];

now i did use self::$_tpl_vars[$tpl_var]; but now error comes up array_merge() [function.array-merge]: Argument #1 is not an array i

答:
You're using smarty and it looks like you're using the PHP 4 notation of class variables:

```<code>var
</code>```

The PHP 5 representation of it is:

```<code>public
</code>```

But you don't need to change the code because PHP is backwards compatible. Just leave it as is as a reminder that things change and for your own code you won't make use of var.

In case you will actually need to change the code because it breaks (and not you break the code because you want to change it), you will notice early enough.

ContentLicense: CC BY-SA 3.0

Body:
You're using smarty and it looks like you're using the PHP 4 notation of class variables:

var

The PHP 5 representation of it is:

public

But you don't need to change the code because PHP is backwards compatible. Just leave it as is as a reminder that things change and for your own code you won't make use of var.

In case you will actually need to change the code because it breaks (and not you break the code because you want to change it), you will notice early enough.


问:
Does git-checkout keep 'half-done' worktree changes on fatal error?
```<code> jordan zu$  git status
On branch origin/features
Your branch is up to date with 'remotes/origin/features'.
nothing to commit, working tree clean

 jordan zu$  git checkout master
error: unable to unlink old 'api_rest/vendor/....php': Permission denied
fatal: cannot create directory at 'api_rest/vendor/...php': Permission denied

 jordan zu$  git status
On branch origin/features
Your branch is up to date with 'remotes/origin/features'.

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
   ---- 100's of deleted/modified files ---

 jordan zu$  git branch
  master
* origin/features
  ^^^ still on origin/features; but index is now changed!
</code>```

So, I was on a 'features' branch, did a 'git checkout master', but it failed. After it failed, I ran 'git status', and now my index is full of changes and untracked files. So, this is what I think happened: git checkout got as far as it could with modifying the worktree, but once it hit an error, it quit, and didn't update HEAD. Instead of reverting the worktree to before it was ran, it just quits.

Am I right on my thinking? Is that what is happening?

Sub-question; part of the problem is that when I start my docker services, they modify some of the worktree and leave directories and files that are owned by 'root', and this is where git checkout runs into problems. Is there a standard way to handle a situation like that? Can I map the docker user to the owner of the worktree somehow?

Thank you for your help.

答:
git checkout got as far as it could with modifying the worktree, but once it hit an error, it quit, and didn't update HEAD. Instead of reverting the worktree to before it was ran, it just quits.

I think it is indeed what happened.

A git status dispays:

paths that have differences between the index file and the current HEAD commit,

paths that have differences between the working tree and the index file,

and paths in the working tree that are not tracked by Git

If HEAD is still as feature, while the index et working tree start to reflect master, you would see all those differences.

By the way, using git switch master would be the modern equivalent of git checkout (when switching branch, hence the switch command

part of the problem is that when I start my docker services, they modify some of the worktree and leave directories and files that are owned by 'root', and this is where git checkout runs into problems.

Can I map the docker user to the owner of the worktree somehow?

Yes, you could Isolate containers with a user namespace

The best way to prevent privilege-escalation attacks from within a container is to configure your container’s applications to run as unprivileged users.

For containers whose processes must run as the root user within the container, you can re-map this user to a less-privileged user on the Docker host.

The mapped user is assigned a range of UIDs which function within the namespace as normal UIDs from 0 to 65536, but have no privileges on the host machine itself.

The general principle:

About remapping and subordinate user and group IDs

The remapping itself is handled by two files: /etc/subuid and /etc/subgid.

Each file works the same, but one is concerned with the user ID range, and the other with the group ID range.

Consider the following entry in /etc/subuid:

```<code>testuser:231072:65536
</code>```

This means that testuser is assigned a subordinate user ID range of 231072 and the next 65536 integers in sequence.

UID 231072 is mapped within the namespace (within the container, in this case) as UID 0 (root).

UID 231073 is mapped as UID 1, and so forth.

If a process attempts to escalate privilege outside of the namespace, the process is running as an unprivileged high-number UID on the host, which does not even map to a real user.

This means the process has no privileges on the host system at all.

In your case, that would mean the user root inside your container could write files outside the container as your current user account uid/gid.

What I usually ask is:

```<code>cat  /etc/docker/daemon.json
{
  "data-root": "/project/docker-root",
  "storage-driver": "overlay2",
  "userns-remap": "myUserApp1:myGroup"  =====
}

sysctl -w user.max_user_namespaces=15000
systemctl restart docker
systemctl status docker
cat /proc/sys/user/max_user_namespaces
</code>```

(On user.max_user_namespaces, see "Docker error process_linux.go:319: getting the final child's pid from pipe caused "EOF": unknown", and moby/moby issue 40835)

With:

```<code>cat /etc/subuid
myUserApp1:44581:65536
cat /etc/subgid
myGroup:14220:65536
</code>```

(Assuming the current user account myUserApp1:MyGroup is has the uuid/guid 44581:14220)

Sometimes (for a Docker JBoss/wildfly image for instance, which runs as 1000:1000 by default), I have to ask for /etc/subuid with 43581 (instead of 44581), because that way, the user 1000 inside the container is mapped to 44581 outside (43581+1000).

Big drawback: That means you can only map one internal container user to one external host user.

If you have another container which runs with 1000:1000, it would be mapped to the same myUserApp1, even though you might have another service account myUserApp2 for this second container persistent data.

ContentLicense: CC BY-SA 4.0

Body:
 jordan zu$  git status
On branch origin/features
Your branch is up to date with 'remotes/origin/features'.
nothing to commit, working tree clean

 jordan zu$  git checkout master
error: unable to unlink old 'api_rest/vendor/....php': Permission denied
fatal: cannot create directory at 'api_rest/vendor/...php': Permission denied

 jordan zu$  git status
On branch origin/features
Your branch is up to date with 'remotes/origin/features'.

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
   ---- 100's of deleted/modified files ---

 jordan zu$  git branch
  master
* origin/features
  ^^^ still on origin/features; but index is now changed!

So, I was on a 'features' branch, did a 'git checkout master', but it failed. After it failed, I ran 'git status', and now my index is full of changes and untracked files. So, this is what I think happened: git checkout got as far as it could with modifying the worktree, but once it hit an error, it quit, and didn't update HEAD. Instead of reverting the worktree to before it was ran, it just quits.

Am I right on my thinking? Is that what is happening?

Sub-question; part of the problem is that when I start my docker services, they modify some of the worktree and leave directories and files that are owned by 'root', and this is where git checkout runs into problems. Is there a standard way to handle a situation like that? Can I map the docker user to the owner of the worktree somehow?

Thank you for your help.

Body:
git checkout got as far as it could with modifying the worktree, but once it hit an error, it quit, and didn't update HEAD. Instead of reverting the worktree to before it was ran, it just quits.

I think it is indeed what happened.

A git status dispays:

paths that have differences between the index file and the current HEAD commit,

paths that have differences between the working tree and the index file,

and paths in the working tree that are not tracked by Git

If HEAD is still as feature, while the index et working tree start to reflect master, you would see all those differences.

By the way, using git switch master would be the modern equivalent of git checkout (when switching branch, hence the switch command

part of the problem is that when I start my docker services, they modify some of the worktree and leave directories and files that are owned by 'root', and this is where git checkout runs into problems.

Can I map the docker user to the owner of the worktree somehow?

Yes, you could Isolate containers with a user namespace

The best way to prevent privilege-escalation attacks from within a container is to configure your container’s applications to run as unprivileged users.

For containers whose processes must run as the root user within the container, you can re-map this user to a less-privileged user on the Docker host.

The mapped user is assigned a range of UIDs which function within the namespace as normal UIDs from 0 to 65536, but have no privileges on the host machine itself.

The general principle:

About remapping and subordinate user and group IDs

The remapping itself is handled by two files: /etc/subuid and /etc/subgid.

Each file works the same, but one is concerned with the user ID range, and the other with the group ID range.

Consider the following entry in /etc/subuid:

testuser:231072:65536

This means that testuser is assigned a subordinate user ID range of 231072 and the next 65536 integers in sequence.

UID 231072 is mapped within the namespace (within the container, in this case) as UID 0 (root).

UID 231073 is mapped as UID 1, and so forth.

If a process attempts to escalate privilege outside of the namespace, the process is running as an unprivileged high-number UID on the host, which does not even map to a real user.

This means the process has no privileges on the host system at all.

In your case, that would mean the user root inside your container could write files outside the container as your current user account uid/gid.

What I usually ask is:

cat  /etc/docker/daemon.json
{
  "data-root": "/project/docker-root",
  "storage-driver": "overlay2",
  "userns-remap": "myUserApp1:myGroup"  =====
}

sysctl -w user.max_user_namespaces=15000
systemctl restart docker
systemctl status docker
cat /proc/sys/user/max_user_namespaces

(On user.max_user_namespaces, see "Docker error process_linux.go:319: getting the final child's pid from pipe caused "EOF": unknown", and moby/moby issue 40835)

With:

cat /etc/subuid
myUserApp1:44581:65536
cat /etc/subgid
myGroup:14220:65536

(Assuming the current user account myUserApp1:MyGroup is has the uuid/guid 44581:14220)

Sometimes (for a Docker JBoss/wildfly image for instance, which runs as 1000:1000 by default), I have to ask for /etc/subuid with 43581 (instead of 44581), because that way, the user 1000 inside the container is mapped to 44581 outside (43581+1000).

Big drawback: That means you can only map one internal container user to one external host user.

If you have another container which runs with 1000:1000, it would be mapped to the same myUserApp1, even though you might have another service account myUserApp2 for this second container persistent data.


问:
Angular 8: assets not loading
I'm trying to use (image) assets in a brand new angular (8.0.3) project.
I've looked into the asset configuration from the docs. Judging by the information there it should work out of the box?

So I created an image folder and put a random .jpg image in there.

```<code>ls src/assets/images
paladin.jpg
</code>```
```<code>ls src
app  assets  environments  favicon.ico  index.html  main.ts  polyfills.ts  styles.css  test.ts
</code>```

angular.json (this is all default)

```<code>  "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
</code>```

In index.html we have (also default)

```<code><link rel="icon" type="image/x-icon" href="favicon.ico">
</code>```

app.component.html (I changed the base64 logo with the assets image)

```<code><img width="300" alt="Angular Logo" src="assets/images/paladin.jpg">
</code>```

But nothing is loading or copies to the 'dist' directory.

The closest I've come to an answer are old threads:

Angular 5 images not loading from assets directory

Assets folder issue

```<code>ng serve
ng build
</code>```

Same result...even favicon.ico isn't loading...

I've tried:

```<code><img width="300" alt="Angular Logo" src="./assets/images/paladin.jpg">
<img width="300" alt="Angular Logo" src="assets/images/paladin.jpg">
<img width="300" alt="Angular Logo" src="../assets/images/paladin.jpg">
<img width="300" alt="Angular Logo" [src]="assets/images/paladin.jpg">
<img width="300" alt="Angular Logo" [src]="'assets/images/paladin.jpg'">
</code>```

How to reproduce

```<code>ng new myTestApp
# => routing y/N doesn't matter
# => css option
ng serve --open
</code>```

=> favicon gives 404

Am I missing something obvious here? :)

More info that might help:

```<code>$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 8.0.3
Node: 10.16.0
OS: win32 x64
Angular: 8.0.2
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.800.3
@angular-devkit/build-angular     0.800.3
@angular-devkit/build-optimizer   0.800.3
@angular-devkit/build-webpack     0.800.3
@angular-devkit/core              8.0.3
@angular-devkit/schematics        8.0.3
@angular/cli                      8.0.3
@ngtools/webpack                  8.0.3
@schematics/angular               8.0.3
@schematics/update                0.800.3
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.30.0

$ npm list -g --depth=0
C:\Users\jonghena\AppData\Roaming\npm
`-- @angular/cli@8.0.3

$ npm list --depth=0
my-test-app@0.0.0 D:\Gitprojects (GitHub)\angular-test\myTestApp
+-- @angular-devkit/build-angular@0.800.3
+-- @angular/animations@8.0.2
+-- @angular/cli@8.0.3
+-- @angular/common@8.0.2
+-- @angular/compiler@8.0.2
+-- @angular/compiler-cli@8.0.2
+-- @angular/core@8.0.2
+-- @angular/forms@8.0.2
+-- @angular/language-service@8.0.2
+-- @angular/platform-browser@8.0.2
+-- @angular/platform-browser-dynamic@8.0.2
+-- @angular/router@8.0.2
+-- @types/jasmine@3.3.13
+-- @types/jasminewd2@2.0.6
+-- @types/node@8.9.5
+-- codelyzer@5.1.0
+-- jasmine-core@3.4.0
+-- jasmine-spec-reporter@4.2.1
+-- karma@4.1.0
+-- karma-chrome-launcher@2.2.0
+-- karma-coverage-istanbul-reporter@2.0.5
+-- karma-jasmine@2.0.1
+-- karma-jasmine-html-reporter@1.4.2
+-- protractor@5.4.2
+-- rxjs@6.4.0
+-- ts-node@7.0.1
+-- tslib@1.10.0
+-- tslint@5.15.0
+-- typescript@3.4.5
`-- zone.js@0.9.1
</code>```

Full angular.json: https://pastebin.com/HaeKmQZ0

答:
I also had exactly the same problem on Angular 8, with loading local images,
with the html, img, src tags. In my case the project's path was absolutely fine: /home/1/app-spa

I had the "src/assets" in angular.json file, and put an image 1.png directly into the assets folder (with no subfolder there).

And surprisingly after running ng-serve, I could not see the image when trying to access it on Firefox Browser with url or img tag:

```<code>http://localhost:4200/assets/1.png
</code>```

Getting 404 not found

However, exactly the same URL opened correctly on Chrome.

I found out that in my firefox browser I had disabled option to display local images, in the Page Info Settings (Ctrl + I) to access, as on the attached image. After changing this Firefox setting the image started to display properly, same as on Chrome. I took me half a day to figure this out.

[Firefox Page Info Settings][1]

[1]: https://i.stack.imgur.com/Pv4Du.jpg

Title: Angular 8: assets not loading

Body:
I'm trying to use (image) assets in a brand new angular (8.0.3) project.
I've looked into the asset configuration from the docs. Judging by the information there it should work out of the box?

So I created an image folder and put a random .jpg image in there.

ls src/assets/images
paladin.jpg

ls src
app  assets  environments  favicon.ico  index.html  main.ts  polyfills.ts  styles.css  test.ts

angular.json (this is all default)

  "assets": [
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []

In index.html we have (also default)

<link rel="icon" type="image/x-icon" href="favicon.ico">

app.component.html (I changed the base64 logo with the assets image)

But nothing is loading or copies to the 'dist' directory.

The closest I've come to an answer are old threads:

Angular 5 images not loading from assets directory

Assets folder issue

ng serve
ng build

Same result...even favicon.ico isn't loading...

I've tried:

How to reproduce

ng new myTestApp
# => routing y/N doesn't matter
# => css option
ng serve --open

=> favicon gives 404

Am I missing something obvious here? :)

More info that might help:

$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 8.0.3
Node: 10.16.0
OS: win32 x64
Angular: 8.0.2
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.800.3
@angular-devkit/build-angular     0.800.3
@angular-devkit/build-optimizer   0.800.3
@angular-devkit/build-webpack     0.800.3
@angular-devkit/core              8.0.3
@angular-devkit/schematics        8.0.3
@angular/cli                      8.0.3
@ngtools/webpack                  8.0.3
@schematics/angular               8.0.3
@schematics/update                0.800.3
rxjs                              6.4.0
typescript                        3.4.5
webpack                           4.30.0

$ npm list -g --depth=0
C:\Users\jonghena\AppData\Roaming\npm
`-- @angular/cli@8.0.3

$ npm list --depth=0
my-test-app@0.0.0 D:\Gitprojects (GitHub)\angular-test\myTestApp
+-- @angular-devkit/build-angular@0.800.3
+-- @angular/animations@8.0.2
+-- @angular/cli@8.0.3
+-- @angular/common@8.0.2
+-- @angular/compiler@8.0.2
+-- @angular/compiler-cli@8.0.2
+-- @angular/core@8.0.2
+-- @angular/forms@8.0.2
+-- @angular/language-service@8.0.2
+-- @angular/platform-browser@8.0.2
+-- @angular/platform-browser-dynamic@8.0.2
+-- @angular/router@8.0.2
+-- @types/jasmine@3.3.13
+-- @types/jasminewd2@2.0.6
+-- @types/node@8.9.5
+-- codelyzer@5.1.0
+-- jasmine-core@3.4.0
+-- jasmine-spec-reporter@4.2.1
+-- karma@4.1.0
+-- karma-chrome-launcher@2.2.0
+-- karma-coverage-istanbul-reporter@2.0.5
+-- karma-jasmine@2.0.1
+-- karma-jasmine-html-reporter@1.4.2
+-- protractor@5.4.2
+-- rxjs@6.4.0
+-- ts-node@7.0.1
+-- tslib@1.10.0
+-- tslint@5.15.0
+-- typescript@3.4.5
`-- zone.js@0.9.1

Full angular.json: https://pastebin.com/HaeKmQZ0

Body:
I also had exactly the same problem on Angular 8, with loading local images,
with the html, img, src tags. In my case the project's path was absolutely fine: /home/1/app-spa

I had the "src/assets" in angular.json file, and put an image 1.png directly into the assets folder (with no subfolder there).

And surprisingly after running ng-serve, I could not see the image when trying to access it on Firefox Browser with url or img tag:

http://localhost:4200/assets/1.png

Getting 404 not found

However, exactly the same URL opened correctly on Chrome.

I found out that in my firefox browser I had disabled option to display local images, in the Page Info Settings (Ctrl + I) to access, as on the attached image. After changing this Firefox setting the image started to display properly, same as on Chrome. I took me half a day to figure this out.

[Firefox Page Info Settings][1]

[1]: https://i.stack.imgur.com/Pv4Du.jpg


问:
why are the email templates still made with tables? Can't we use div and flexbox(as it is widely supported presently)?
They say the table is a standard for making email templates and also they are using elements that are not supported in html5 eg., . I haven't made any layout with tables and I am comfortable with using flexbox. Can I use flexbox?</p>

答: The limitation is mostly because some versions of Outlook are way behind typical web browsers when it comes to handling CSS and for sure, Flexbox. So if you want your email template to be compatible with the majority of email apps, tables are the way to go because they are the lowest common denominator and you can get consistent results.</p>


问:
ASP.NET MVC - Approach for global error handling?
I was wondering what the best implementation for a global error (doesn't have to be errors, can also  be success messages) handler would be? Let me break it down for you with an example:

User tries to delete a record

Deletion fails and an error is logged

User redirects to another page

Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page

```<code>public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete)
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}
</code>```

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

```<code><%= Html.RenderAllMessages %>
</code>```

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.

答:
I'm confused by these steps:

Deletion fails and an error is logged

User redirects to another page

Why would you redirect the User when an error occurs? That doesnt make any sense, unless im misunderstanding something.

Generally, i follow these guidelines:

Error with form submission (e.g HTTP POST): check ModelState.IsValid and return the same View and render the error out with @Html.ValidationSummary()

Error with AJAX call: return JsonResult (like @Tomas says), and use basic client-side scripting to inspect the JSON and show the result

Error with domain/business: throw custom exceptions and let the controller catch them and add to ModelState as above

Body:
I was wondering what the best implementation for a global error (doesn't have to be errors, can also  be success messages) handler would be? Let me break it down for you with an example:

User tries to delete a record

Deletion fails and an error is logged

User redirects to another page

Display error message for user (using a HtmlHelper or something, don't want it to be a specific error page)

I'm just curious what you guys think. I've been considering TempData, ViewData and Session but they all have their pros and cons.

TIA!

UPDATE:

I'll show an example what I exactly mean, maybe I wasn't clear enough.
This is an example of a method that adds a message when user deletes a record.
If user succeeds, user redirects to another page

public ActionResult DeleteRecord(Record recordToDelete)
{
    // If user succeeds deleting the record
    if (_service.DeleteRecord(recordToDelete)
    {
        // Add success message
        MessageHandler.AddMessage(Status.SUCCESS, "A message to user");

        // And redirect to list view
        return RedirectToAction("RecordsList");
    }
    else
    {
        // Else return records details view
        return View("RecordDetails", recordToDelete);
    }
}

And in the view "RecordsList", it would be kinda cool to show all messages (both error and success messages) in a HtmlHelper or something.

<%= Html.RenderAllMessages %>

This can be achieved in many ways, I'm just curious what you guys would do.

UPDATE 2:

I have created a custom error (message) handler. You can see the code if you scroll down.


问:
Django rest framework Detail not found while deleting
i have a a problem deleting an object via API. So i have 2 models, Answer and Vote vote is connected to Answer via foreignKey like this

```<code>class Vote(models.Model):
    class AnswerScore(models.IntegerChoices):
        add = 1
        subtract = -1

    score = models.IntegerField(choices=AnswerScore.choices)
    answer = models.ForeignKey('Answer', on_delete=models.PROTECT)
    user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT)

    class Meta:
        unique_together = ('answer', 'user',)

class Answer(models.Model):
    answer = models.TextField()
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT)
    question = models.ForeignKey('Question', on_delete=models.PROTECT)
    number_of_points = models.IntegerField(default=0)
    moderate_status = models.BooleanField(default=False)
</code>```

Now i have an API endpoint for creating a Vote for user on a particular answer

```<code>    path('answers/<int:pk>/vote', VoteCreate.as_view()),
</code>```

Looks like this:

```<code>class VoteSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    answer = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Vote
        fields = '__all__'

class VoteCreate(ParentKeyAPIView, generics.CreateAPIView):
    model = Vote
    parent_model_field = 'answer_id'
    serializer_class = VoteSerializer

    def perform_create_kwargs(self, **kwargs):
        answer_id = self.kwargs['pk']
        answer = Answer.objects.get(id=int(answer_id))

        if Vote.objects.filter(user=self.request.user, answer=answer).exists():
            old_vote = Vote.objects.get(user=self.request.user, answer=answer)
            answer -= old_vote.score
            answer.save()
            old_vote.delete()

        return super().perform_create_kwargs(user=self.request.user, answer_id=answer_id, **kwargs)

</code>```

Im using the same serializer just like above*

I get an error:
Not Found: /api/v1/answers/55/voteDelete
There is no any traceback, i have checked in fact that in database the Vote with answer_id 55 exists and i can delete them via django-admin but cant via API.
Do you have any idea why?

答:
First thing - let's change get_queryset to get_object, because you want single object. Then instead of answer_id=self.kwargs['pk'] simplify it to answer=self.kwargs['pk'].

Another thing - I think it's might be better to delete old vote while creating new one. You don't need serializer or special view for that. Just add to function creating new Vote object in your view:

```<code>class VoteCreate(...):
    ...
    def perform_create_kwargs(self, **kwargs):
        answer_id = self.kwargs['pk']
        answer = Answer.object.get(id=int(answer_id))

        if Vote.objects.filter(user=self.request.user, answer=answer).exists():
            old_vote = Vote.objects.get(user=self.request.user, answer=answer)
            answer.number_of_points -= old_vote.score
            answer.save()
            old_vote.delete()

        return super().perform_create_kwargs(user=self.request.user, answer_id=answer_id, **kwargs)
</code>```

Body:
i have a a problem deleting an object via API. So i have 2 models, Answer and Vote vote is connected to Answer via foreignKey like this

class Vote(models.Model):
    class AnswerScore(models.IntegerChoices):
        add = 1
        subtract = -1

    score = models.IntegerField(choices=AnswerScore.choices)
    answer = models.ForeignKey('Answer', on_delete=models.PROTECT)
    user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT)

    class Meta:
        unique_together = ('answer', 'user',)

class Answer(models.Model):
    answer = models.TextField()
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
    user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT)
    question = models.ForeignKey('Question', on_delete=models.PROTECT)
    number_of_points = models.IntegerField(default=0)
    moderate_status = models.BooleanField(default=False)

Now i have an API endpoint for creating a Vote for user on a particular answer

    path('answers/<int:pk>/vote', VoteCreate.as_view()),

Looks like this:

class VoteSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    answer = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Vote
        fields = '__all__'

class VoteCreate(ParentKeyAPIView, generics.CreateAPIView):
    model = Vote
    parent_model_field = 'answer_id'
    serializer_class = VoteSerializer

    def perform_create_kwargs(self, **kwargs):
        answer_id = self.kwargs['pk']
        answer = Answer.objects.get(id=int(answer_id))

        if Vote.objects.filter(user=self.request.user, answer=answer).exists():
            old_vote = Vote.objects.get(user=self.request.user, answer=answer)
            answer -= old_vote.score
            answer.save()
            old_vote.delete()

        return super().perform_create_kwargs(user=self.request.user, answer_id=answer_id, **kwargs)

Im using the same serializer just like above*

I get an error:
Not Found: /api/v1/answers/55/voteDelete
There is no any traceback, i have checked in fact that in database the Vote with answer_id 55 exists and i can delete them via django-admin but cant via API.
Do you have any idea why?

Body:
First thing - let's change get_queryset to get_object, because you want single object. Then instead of answer_id=self.kwargs['pk'] simplify it to answer=self.kwargs['pk'].

Another thing - I think it's might be better to delete old vote while creating new one. You don't need serializer or special view for that. Just add to function creating new Vote object in your view:

class VoteCreate(...):
    ...
    def perform_create_kwargs(self, **kwargs):
        answer_id = self.kwargs['pk']
        answer = Answer.object.get(id=int(answer_id))

        if Vote.objects.filter(user=self.request.user, answer=answer).exists():
            old_vote = Vote.objects.get(user=self.request.user, answer=answer)
            answer.number_of_points -= old_vote.score
            answer.save()
            old_vote.delete()

        return super().perform_create_kwargs(user=self.request.user, answer_id=answer_id, **kwargs)


问:
How to build a route inside a polygon OpenLayer
I use OpeenStreetMap and the OpenLayers library, I need to build a route inside the polygon as in the mission planner program, here https://www.youtube.com/watch?v=MhHomssqD7k&ab_channel=AeroHawk at 2 minutes you can see how inside the polygon marked with red segments , the program automatically builds a route. How can I replicate this? What is this algorithm?

mission planer

答:
I see you're talking about generating a drone flight path within a polygon, calculating the positions of way points.

Quite a fun challenge! I'll write out in words how the algorithm would work, but doing this in javascript would also be fun!

It should be possible to do this for a given (adjustable) angle of orientation, but I suggest you could simplify things initially by assuming the drone is to fly in passes orientated exactly East <-> West.

That also means the start way point is simply the northernmost corner of the polygon i.e. the vertex with the greatest latitude (Given a polygon with a northern edge like the one pictured, it doesn't matter which of the two top corners is the start point). Likewise the final way point is straightforward. The southernmost corner of the polygon.

We need to caculate all the waypoints in between. A series of locations on the left and right to create this laddered effect. Perhaps you'll want to start by building two lines (or ordered arrays of corner points) representing the left and right sides. The algrithm needs to "walk" down these sides, so maintain a lastLeft and lastRight point which are both intialised to the start of their lines. For both lines this is the start point at the top.

Each "walk step" down a line is going involve some calculation (sub-function!). They'll be a configured "gap" between the drone passes. This delta-latitude will be used at this point. For each walk step we're starting from the last point (lastLeft or lastRight) and so we've got a target latitude. targetLat = lastLeft.lat - gap.  In a loop we can walk to the next point of the line (corner of the original polygon) if that lies within the gap, i.e. the latitude of that point is > targetLat. Another edge case is if the next point is actually the end point (break! we're done!). But otherwise we've got an edge that crosses the targetLat. We do the geometric calculation to find the point along the edge where it crosses the targetLat*. That point is our next way point!

*Geometric calculation to find the point along a line which has the targetLat? Possibly this part is do-able with something like TurfJS, although I couldn't tell you exactly which library call. But having worked out the rest of the algorithm, personally I'd probably just the code linear maths directly. You have known start and end to the line, therefore a known gradient. Take that and apply it to the known delta-lat to find the delta-lon.

We need to follow that algorithm for a "walk step", walking down the left line and then down the right line, and then down the right line and then down the left line, generating the ladder shaped series of way points all the way down to the end!


问:
Relative Interface (TYPESCRIPT)
How can I make the state in ISetOpen with relative type of modal in ISetOpen?

Example:

if ISetOpen.modal === 'payModal': ISetOpen.state = IPayModal

if ISetOpen.modal === 'deleteModal': ISetOpen.state = IDeleteModal

```<code>import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IPayModal {
  amount: number
  isOpen: boolean
}

interface IDeleteModal {
  id: number
  isOpen: boolean
}

export interface ModalsState {
  payModal: IPayModal
  deleteModal: IDeleteModal
}

const initialState: ModalsState = {
  payModal: {
    amount: 0,
    isOpen: false
  },
  deleteModal: {
    id: 0,
    isOpen: false
  }
}

interface ISetOpen {
  modal: keyof typeof initialState
  state: IPayModal | IDeleteModal
}

export const modalsSlice = createSlice({
  name: 'modals',
  initialState,
  reducers: {
    setOpen: (state, action: PayloadAction<ISetOpen>) => {
      state[action.payload.modal] = action.payload.state
    }
  }
})

export const { setOpen } = modalsSlice.actions

export default modalsSlice.reducer
</code>```

答:
The two properties in your current ISetOpen interface are both unions, but there is no relationship between the modal and the state.

What you want is a union of valid pairings of modal and state.  We can do this with mapped types.  For each key ("payModal" | "deleteModal") we create an object with the specific modal and state for each type.

```<code>type ISetOpen = {
  [K in keyof ModalsState]: {
    modal: K;
    state: ModalsState[K]
  }
}[keyof ModalsState]
</code>```

This resolves to

```<code>type ISetOpen = {
    modal: "payModal";
    state: IPayModal;
} | {
    modal: "deleteModal";
    state: IDeleteModal;
}
</code>```

This will ensure that all of your actions are dispatched with the correct values.

Unfortunately it does not resolve the issues in the reducer, as state[action.payload.modal] is still evaluated as a union state.payModal | state.deleteModal.  You may need to use a type assertion here.  For example, action.payload.state as IPayModal & IDeleteModal;

Title: Relative Interface (TYPESCRIPT)

Body:
How can I make the state in ISetOpen with relative type of modal in ISetOpen?

Example:

if ISetOpen.modal === 'payModal': ISetOpen.state = IPayModal

if ISetOpen.modal === 'deleteModal': ISetOpen.state = IDeleteModal

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IPayModal {
  amount: number
  isOpen: boolean
}

interface IDeleteModal {
  id: number
  isOpen: boolean
}

export interface ModalsState {
  payModal: IPayModal
  deleteModal: IDeleteModal
}

const initialState: ModalsState = {
  payModal: {
    amount: 0,
    isOpen: false
  },
  deleteModal: {
    id: 0,
    isOpen: false
  }
}

interface ISetOpen {
  modal: keyof typeof initialState
  state: IPayModal | IDeleteModal
}

export const modalsSlice = createSlice({
  name: 'modals',
  initialState,
  reducers: {
    setOpen: (state, action: PayloadAction<ISetOpen>) => {
      state[action.payload.modal] = action.payload.state
    }
  }
})

export const { setOpen } = modalsSlice.actions

export default modalsSlice.reducer

Body:
The two properties in your current ISetOpen interface are both unions, but there is no relationship between the modal and the state.

What you want is a union of valid pairings of modal and state.  We can do this with mapped types.  For each key ("payModal" | "deleteModal") we create an object with the specific modal and state for each type.

type ISetOpen = {
  [K in keyof ModalsState]: {
    modal: K;
    state: ModalsState[K]
  }
}[keyof ModalsState]

This resolves to

type ISetOpen = {
    modal: "payModal";
    state: IPayModal;
} | {
    modal: "deleteModal";
    state: IDeleteModal;
}

This will ensure that all of your actions are dispatched with the correct values.

Unfortunately it does not resolve the issues in the reducer, as state[action.payload.modal] is still evaluated as a union state.payModal | state.deleteModal.  You may need to use a type assertion here.  For example, action.payload.state as IPayModal & IDeleteModal;


问:
Docker - output data to a file - Python
I am starting out with docker and trying to run a python code that generates a csv file as output.

```<code>import pandas as pd

# string values in the list
lst = ['Java', 'Python', 'C', 'C++',
         'JavaScript', 'Swift', 'Go']

# Calling DataFrame constructor on list
dframe = pd.DataFrame(lst)
dframe.to_csv('test.csv')
</code>```

This is my docker configuration:

```<code>FROM python:3.8

ADD main.py .
VOLUME /out
RUN pip install pandas

CMD ["python", "./main.py"]
</code>```

This is how I call docker.

```<code>docker run  --volume=/Users/myuser/Documents/DashyDash/Docker/out:/out python-test
</code>```

However I am unable to find the output file.
Can someone tell me what I am doing wrong and help me fix it.

Thank you!

答:
The location of the main.py writes the csv in the current directory which has no mapping to know which directory to the host. Therefore, you will have to change that so that the same is reflected in the host machine. I assume my work directory within the Dockerfile is /app and I also create a new directory output which is then mapped as a bind mount volume while running the container. I will detail that next.

Dockerfile: Same things with few improvements

```<code>FROM python:3.8
WORKDIR /app # This makes sure that a particular work dir is set
COPY main.py ./ # Copying all required files, could also be directories
RUN mkdir -p /app/output # Creating a new directory called output
RUN pip install pandas
CMD ["python3", "main.py"] # Just small improvement
</code>```

Now, I map the same output to the main.py: dframe.to_csv('/app/output/test.csv')

After this, I build the image:

```<code>docker build -t python-test .
</code>```

Run the image:

```<code>docker run -v $HOME/test/output:/app/output python-test
</code>```

Note: The entire files are on $HOME/test. Also, main.py can map the output directory automatically as well using python's os package.

Then, the output in the output directory is:

```<code>,0
0,Java
1,Python
2,C
3,C++
4,JavaScript
5,Swift
6,Go
</code>```

Title: Docker - output data to a file - Python

Body:
I am starting out with docker and trying to run a python code that generates a csv file as output.

import pandas as pd

# string values in the list
lst = ['Java', 'Python', 'C', 'C++',
         'JavaScript', 'Swift', 'Go']

# Calling DataFrame constructor on list
dframe = pd.DataFrame(lst)
dframe.to_csv('test.csv')

This is my docker configuration:

FROM python:3.8

ADD main.py .
VOLUME /out
RUN pip install pandas

CMD ["python", "./main.py"]

This is how I call docker.

docker run  --volume=/Users/myuser/Documents/DashyDash/Docker/out:/out python-test

However I am unable to find the output file.
Can someone tell me what I am doing wrong and help me fix it.

Thank you!

Body:
The location of the main.py writes the csv in the current directory which has no mapping to know which directory to the host. Therefore, you will have to change that so that the same is reflected in the host machine. I assume my work directory within the Dockerfile is /app and I also create a new directory output which is then mapped as a bind mount volume while running the container. I will detail that next.

Dockerfile: Same things with few improvements

FROM python:3.8
WORKDIR /app # This makes sure that a particular work dir is set
COPY main.py ./ # Copying all required files, could also be directories
RUN mkdir -p /app/output # Creating a new directory called output
RUN pip install pandas
CMD ["python3", "main.py"] # Just small improvement

Now, I map the same output to the main.py: dframe.to_csv('/app/output/test.csv')

After this, I build the image:

docker build -t python-test .

Run the image:

docker run -v $HOME/test/output:/app/output python-test

Note: The entire files are on $HOME/test. Also, main.py can map the output directory automatically as well using python's os package.

Then, the output in the output directory is:

,0
0,Java
1,Python
2,C
3,C++
4,JavaScript
5,Swift
6,Go


问:
How to solve error Arithmetic overflow error converting expression to data type int?
When running the following query(I created the query using python):

```<code>SELECT x, y, z, sum(r) AS R
FROM data_table
WHERE [start_time] >= convert(datetime, '2022-02-03')
  AND [end_time] <= CONVERT(datetime, '2022-02-07')
GROUP BY x, y, z
</code>```

I got the error:

Arithmetic overflow error converting expression to data type int.

If I change the date to '2022-02-04' it is working fine.
Can someone help me fix my query that it will work in all dates?

答:
seems like the result of sum() overflows, how about cast the r to bigint
before sum the result up :

```<code>SELECT x, y, z, sum(cast(r as bigint)) AS R
FROM data_table
WHERE [start_time] >= convert(datetime, '2022-02-03')
  AND [end_time] <= CONVERT(datetime, '2022-02-07')
GROUP BY x, y, z
</code>```

db<>fiddle here

Body:
When running the following query(I created the query using python):

SELECT x, y, z, sum(r) AS R
FROM data_table
WHERE [start_time] >= convert(datetime, '2022-02-03')
  AND [end_time] <= CONVERT(datetime, '2022-02-07')
GROUP BY x, y, z

I got the error:

Arithmetic overflow error converting expression to data type int.

If I change the date to '2022-02-04' it is working fine.
Can someone help me fix my query that it will work in all dates?

Body:
seems like the result of sum() overflows, how about cast the r to bigint
before sum the result up :

SELECT x, y, z, sum(cast(r as bigint)) AS R
FROM data_table
WHERE [start_time] >= convert(datetime, '2022-02-03')
  AND [end_time] <= CONVERT(datetime, '2022-02-07')
GROUP BY x, y, z

db<>fiddle here


问:
How to get my current user_id ..?
I want to get user information using coinbase api. For that one I have found the coinbase curl usl which will provide me the user information.

Curl Url :

```<code>https://api.coinbase.com/v2/users/:user_id
</code>```

I have already registered my account in coinbase website, also check in all option provided in website but no where I found my user_id.

Problem is How do I get my user_id of my coinbase account..?

答:
You can get in, in Python using de CoinBase API for Python, for instance:</p>
```<code>#LIBRERIAS:
from coinbase.wallet.client import Client

# conexion a CoinBase
client = Client('xxxxxxxxxx', 'xxxxxxxxxxxxxx')

user = client.get_current_user()

print("user items: "+str(user)+'\n')
</code>```

Title: How to get my current user_id ..?

Body:
I want to get user information using coinbase api. For that one I have found the coinbase curl usl which will provide me the user information.

Curl Url :

https://api.coinbase.com/v2/users/:user_id

I have already registered my account in coinbase website, also check in all option provided in website but no where I found my user_id.

Problem is How do I get my user_id of my coinbase account..?

Body:
You can get in, in Python using de CoinBase API for Python, for instance:

#LIBRERIAS:
from coinbase.wallet.client import Client

# conexion a CoinBase
client = Client('xxxxxxxxxx', 'xxxxxxxxxxxxxx')

user = client.get_current_user()

print("user items: "+str(user)+'\n')


问:
Java: can't close Client connection without closing Server
I made a previous post a bit back working on getting a two-way server/client socket connection working. I've largely succeeded yet, but I still have one more step as a barrier. I'd like to make it so the client disconnects after they perform an operation, but the server remains up and can take in another client operation until the client makes a specific response. I'm attempting to do this through while loops in both the client and server. This is my server class:

```<code>import java.net.*;
import java.io.*;
public class ServerDemo {
    private Socket mySocket = null;
    private ServerSocket server = null;
    private static ObjectInputStream in=null;
    private static ObjectOutputStream out=null;
    private static Payload myPayload=new Payload();

    public ServerDemo(int port) throws ClassNotFoundException
    {
        double time=0;
        int bytes=0;
        try
        {
               server = new ServerSocket(port);
               System.out.println("Server started");
               System.out.println("Waiting for a client ...");
        }
        catch(IOException i)
        {
            System.out.println(i);
            myPayload.setRepeat(false);
        }
        try {
               while(myPayload.getRepeat()==true) {
               mySocket = server.accept();
               System.out.println("Client accepted");
               in = new ObjectInputStream(
                       new BufferedInputStream(mySocket.getInputStream()));
               out = new ObjectOutputStream(mySocket.getOutputStream());
               myPayload.setDataPasses(10);
               while (myPayload.getCurr()<myPayload.getDataPasses())
               {
                    try
                    {
                         myPayload= (Payload) in.readObject();
                         myPayload.raisePasses();
                         out.writeObject(myPayload);

                    }
                    catch(IOException i)
                    {
                        System.out.println(i);
                        myPayload.setRepeat(false);
                    }
               }
               System.out.println("Closing connection");
               mySocket.close();
               in.close();
               System.out.println("Operation Complete");
               System.out.println("Client Address: "+myPayload.getClient());
               System.out.println("Server Address: "+myPayload.getServer());
               time=System.nanoTime()-(myPayload.getTime());
               time=time/1000000000;
               System.out.println("Total Time (in seconds): "+time);
               bytes=(int) ( ((myPayload.getPacket().length)*myPayload.getDataPasses())/time);
               System.out.println("Bytes per Second: "+bytes);
         }
        }
        catch(IOException i)
        {
            System.out.println(i);
            myPayload.setRepeat(false);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // TODO Auto-generated method stub
        ServerDemo server=new ServerDemo(5000);
    }

}
</code>```

This is my client class:

```<code>import java.net.*;
import java.util.Scanner;
import java.io.*;
public class ClientDemo {
    private Socket mySocket = null;
    private ObjectInputStream in= null;
    private ObjectOutputStream out = null;
    private static long roundTrips=1;
    private static Payload myPayload=new Payload();

    public ClientDemo(String address, int port) throws ClassNotFoundException
    {
        int packageSize=1;
        double time=0;
        int bytes=0;
 try
        {
            mySocket = new Socket(address, port);
            System.out.println("Connected");
            out = new ObjectOutputStream(mySocket.getOutputStream());
            in = new ObjectInputStream(new BufferedInputStream(mySocket.getInputStream()));

        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
            while (myPayload.getCurr()<myPayload.getDataPasses())
            {

                try
                {
                        if(myPayload.getCurr()==0) {
                        myPayload.setTime(System.nanoTime());
                    }
                    out.writeObject(myPayload);
                    myPayload= (Payload) in.readObject();
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
        try
        {
            in.close();
            out.close();
            mySocket.close();
            System.out.println("Operation Complete");
            System.out.println("Client Address: "+myPayload.getClient());
            System.out.println("Server Address: "+myPayload.getServer());
            time=System.nanoTime()-(myPayload.getTime());
            time=time/1000000000;
            System.out.println("Total Time (in seconds): "+time);
            bytes=(int) ( ((myPayload.getPacket().length)*myPayload.getDataPasses())/time);
            System.out.println("Bytes per Second: "+bytes);
            System.out.println("");
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // TODO Auto-generated method stub
        boolean isValid=false;
        String response="";
        int size=16384;
        Scanner myScanner = new Scanner(System.in);
        ClientDemo client=null;
        String server="";
        while (size>-1) {
            System.out.println("Please enter a max data packet size. Enter -1 to end the program");
            while(isValid==false) {
                response=myScanner.next();
                if(Long.parseLong(response)>=-1 && Long.parseLong(response)<=16384) {
                    isValid=true;
                    size=Integer.parseInt(response);
                    if(size>-1) {
                        myPayload.setPacket(fillPacket(size));
                    }
                }
                else {
                    System.out.println("Invalid Response. Please enter a value between 1 and 16384.");
                }
            }
        if(size==-1) {
            System.out.println("Closing server...");
            myPayload.setRepeat(false);
            client= new ClientDemo(server, 5000);

        }
        else {
            isValid=false;
            System.out.println("Please enter an amount of data passes.");
            while(isValid==false) {
                response=myScanner.next();
                if(Long.parseLong(response)>=1) {
                    isValid=true;
                    roundTrips=Long.parseLong(response);
                    myPayload.setDataPasses(roundTrips);
                }
                else {
                    System.out.println("Invalid Response. Please enter a value of 1 or greater.");
                }
            }
            isValid=false;
            System.out.println("Please enter your client address.");
            response=myScanner.next();
            myPayload.setClient(response);
            System.out.println("Please enter a server to connect to.");
            response=myScanner.next();
            server=response;
            myPayload.setServer(server);
            myPayload.reset();
            client= new ClientDemo(server, 5000);
            }
        }
    }

    public static int[] fillPacket(int size) {
        int[] thePacket= new int[size];
        int current=0;
        while(current<size) {
            for(int counter=0;counter<100;counter++) {
                if(current<size) {
                    thePacket[current]=counter;
                    current++;
                }
            }
        }
        return thePacket;
    }
}
</code>```

When I attempt to run both, the operation I have set up works completely fine, and entering -1 to close the program works but I run into errors when performing operations beyond that. Attempting to set size to -1 to end the program at this point causes an endless loop of

```<code>java.io.EOFException
</code>```

inside ServerDemo, while entering what should be a valid packet size between 0 and 16384 instead produces an endless stream of

```<code>java.net.SocketException: Broken pipe (Write failed)
</code>```

inside ClientDemo. Perhaps most strangely, the latter error only SOMETIMES occurs, not always. If anyone has any pointers on how to get this correctly working and remedying these errors, I would greatly appreciate it!

答:
I would rather change approach. The usual one when doing this kind of stuff is create a thread to listen on your port, then, when a client connects, immediately dispatch the new task to a thread pool and continue listening.

This way not only your server will continue listening after the client disconnects, but also will be able to serve multiple clients in parallel (up to the thread pool size).

Also please use try-with-resources whenever possible to easily avoid resource leaking.

So your code could be changed to something like this:

Server class

```<code>import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerDemo {
    private int port;
    private Thread listenThread;
    private ExecutorService serverPool;

    public ServerDemo(int port) {
        this.port = port;
    }

    public synchronized void startServer() {
        serverPool = Executors.newFixedThreadPool(4);

        listenThread = new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                System.out.println(String.format("Listening on port %d", port));
                System.out.println("1");
                while (!Thread.interrupted()) {
                    System.out.println("2");
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("3");
                    if(!Thread.currentThread().isInterrupted())
                        serverPool.submit(new ClientTask(clientSocket));
                    System.out.println("4");
                }
            } catch (IOException e) {
                System.err.println("Error processing client connection");
                e.printStackTrace();
            }

            System.out.println("ListenThread stopped");
        }, "ListenThread");

        listenThread.start();
    }

    public synchronized void stopServer() {
        System.out.println("Stopping server...");
        if (serverPool != null) {
            serverPool.shutdown();
            serverPool = null;
        }

        if(listenThread != null) {
            listenThread.interrupt();

            try (Socket voidSocket = new Socket("localhost", port)) {
                // Void socket to unlock the accept() call
            } catch (IOException e) {
            }

            listenThread = null;
        }
    }

    private class ClientTask implements Runnable {
        private final Socket clientSocket;

        private ClientTask(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            System.out.println("Client accepted");
            Payload myPayload = new Payload();
            try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream())) {

                myPayload.setDataPasses(10);
                while (myPayload.getCurr() < myPayload.getDataPasses()) {
                    try {
                        myPayload = (Payload) in.readObject();
                        myPayload.raisePasses();
                        out.writeObject(myPayload);

                    } catch (IOException i) {
                        System.out.println(i);
                        break;
                    } catch (ClassNotFoundException e) {
                        System.err.println("Error finding class to deserialize");
                        e.printStackTrace();
                    }
                }
                System.out.println("Operation Complete");
                System.out.println("Client Address: " + myPayload.getClient());
                System.out.println("Server Address: " + myPayload.getServer());
                double time = System.nanoTime() - (myPayload.getTime());
                time = time / 1000000000;
                System.out.println("Total Time (in seconds): " + time);
                int bytes = (int) (((myPayload.getPacket().length) * myPayload.getDataPasses()) / time);
                System.out.println("Bytes per Second: " + bytes);
            } catch (IOException e1) {
                System.err.println("Error opening client I/O streams");
                e1.printStackTrace();
            }

            try {
                System.out.println("Closing connection");
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("Error closing client connection");
                e.printStackTrace();
            }

            if(!myPayload.getRepeat())
                stopServer();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        ServerDemo server = new ServerDemo(5000);
        server.startServer();

        // do other stuff including trapping for sigterm, then call server.stopServer() if needed
    }

}
</code>```

Client class

```<code>import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientDemo {

    private static void executeClientJob(Payload myPayload, int port) {
        double time = 0;
        int bytes = 0;
        try (Socket mySocket = new Socket(myPayload.getServer(), port);
                ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(mySocket.getInputStream()))) {

            System.out.println("Connected");
            while (myPayload.getCurr() < myPayload.getDataPasses()) {

                if (myPayload.getCurr() == 0)
                    myPayload.setTime(System.nanoTime());

                out.writeObject(myPayload);
                myPayload = (Payload) in.readObject();
            }

            System.out.println("Operation Complete");
            System.out.println("Client Address: " + myPayload.getClient());
            System.out.println("Server Address: " + myPayload.getServer());
            time = System.nanoTime() - (myPayload.getTime());
            time = time / 1000000000;
            System.out.println("Total Time (in seconds): " + time);
            bytes = (int) (((myPayload.getPacket().length) * myPayload.getDataPasses()) / time);
            System.out.println("Bytes per Second: " + bytes);
            System.out.println("");
        } catch (UnknownHostException u) {
            u.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            c.printStackTrace();
        }
    }

    private static void testAutomatic() {
        for (int i = 0; i < 1; i++) {
            Payload myPayload = new Payload();
            myPayload.setPacket(fillPacket(40));
            executeClientJob(myPayload, 5000);
        }
        Payload stopPayload = new Payload();
        stopPayload.setRepeat(false);
        executeClientJob(stopPayload, 5000);
    }

    private static void testInteractive() {
        Payload myPayload;
        boolean repeat;
        do {
            myPayload = readPayloadSettings();
            repeat = myPayload.getRepeat();
            executeClientJob(myPayload, 5000);
        } while (repeat);
    }

    private static Payload readPayloadSettings() {
        Payload ret = new Payload();
        int size = 60;

        @SuppressWarnings("resource")
        Scanner myScanner = new Scanner(System.in);
        System.out.println("Please enter a max data packet size. Enter -1 to end the program");
        while (true) {
            String response = myScanner.next();
            if (Long.parseLong(response) >= -1 && Long.parseLong(response) <= 16384) {
                size = Integer.parseInt(response);
                break;
            } else {
                System.out.println("Invalid Response. Please enter a value between 1 and 16384.");
            }
        }
        if (size == -1) {
            System.out.println("Closing server...");
            ret.setRepeat(false);
        } else {
            ret.setPacket(fillPacket(size));
            System.out.println("Please enter an amount of data passes.");
            while (true) {
                String response = myScanner.next();
                if (Long.parseLong(response) >= 1) {
                    ret.setDataPasses(Long.parseLong(response));
                    break;
                } else {
                    System.out.println("Invalid Response. Please enter a value of 1 or greater.");
                }
            }
            System.out.println("Please enter your client address.");
            ret.setClient(myScanner.next());
            System.out.println("Please enter a server to connect to.");
            ret.setServer(myScanner.next());
        }
        return ret;
    }

    public static int[] fillPacket(int size) {
        int[] thePacket = new int[size];
        int current = 0;
        while (current < size) {
            for (int counter = 0; counter < 100; counter++) {
                if (current < size) {
                    thePacket[current] = counter;
                    current++;
                }
            }
        }
        return thePacket;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        testInteractive();
        //testAutomatic();
    }
}
</code>```

Payload class (with defaults to quick create an automatic test)

```<code>import java.io.Serializable;

public class Payload implements Serializable {

    private int curr=0;
    private long dataPasses=5;
    private long time;
    private String client="localhost";
    private String server="localhost";
    private int[] packet=new int[0];
    private boolean repeat=true;

    public Payload() {
    }

    public int getCurr() {
        return curr;
    }

    public void setCurr(int curr) {
        this.curr = curr;
    }

    public long getDataPasses() {
        return dataPasses;
    }
    public void setDataPasses(long roundTrips) {
        this.dataPasses = roundTrips;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long nanoTime) {
        time = nanoTime;

    }

    public String getClient() {
        return client;
    }

    public void setClient(String client) {
        this.client = client;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public int[] getPacket() {
        return packet;
    }

    public void setPacket(int[] packet) {
        this.packet = packet;
    }

    public boolean getRepeat() {
        return repeat;
    }

    public void setRepeat(boolean r) {
        this.repeat = r;
    }

    public void reset() {
        curr=0;
        dataPasses=0;
    }

    public void raisePasses() {
        curr++;
    }
}
</code>```

Body:
I made a previous post a bit back working on getting a two-way server/client socket connection working. I've largely succeeded yet, but I still have one more step as a barrier. I'd like to make it so the client disconnects after they perform an operation, but the server remains up and can take in another client operation until the client makes a specific response. I'm attempting to do this through while loops in both the client and server. This is my server class:

import java.net.*;
import java.io.*;
public class ServerDemo {
    private Socket mySocket = null;
    private ServerSocket server = null;
    private static ObjectInputStream in=null;
    private static ObjectOutputStream out=null;
    private static Payload myPayload=new Payload();

    public ServerDemo(int port) throws ClassNotFoundException
    {
        double time=0;
        int bytes=0;
        try
        {
               server = new ServerSocket(port);
               System.out.println("Server started");
               System.out.println("Waiting for a client ...");
        }
        catch(IOException i)
        {
            System.out.println(i);
            myPayload.setRepeat(false);
        }
        try {
               while(myPayload.getRepeat()==true) {
               mySocket = server.accept();
               System.out.println("Client accepted");
               in = new ObjectInputStream(
                       new BufferedInputStream(mySocket.getInputStream()));
               out = new ObjectOutputStream(mySocket.getOutputStream());
               myPayload.setDataPasses(10);
               while (myPayload.getCurr()<myPayload.getDataPasses())
               {
                    try
                    {
                         myPayload= (Payload) in.readObject();
                         myPayload.raisePasses();
                         out.writeObject(myPayload);

                    }
                    catch(IOException i)
                    {
                        System.out.println(i);
                        myPayload.setRepeat(false);
                    }
               }
               System.out.println("Closing connection");
               mySocket.close();
               in.close();
               System.out.println("Operation Complete");
               System.out.println("Client Address: "+myPayload.getClient());
               System.out.println("Server Address: "+myPayload.getServer());
               time=System.nanoTime()-(myPayload.getTime());
               time=time/1000000000;
               System.out.println("Total Time (in seconds): "+time);
               bytes=(int) ( ((myPayload.getPacket().length)*myPayload.getDataPasses())/time);
               System.out.println("Bytes per Second: "+bytes);
         }
        }
        catch(IOException i)
        {
            System.out.println(i);
            myPayload.setRepeat(false);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // TODO Auto-generated method stub
        ServerDemo server=new ServerDemo(5000);
    }

}

This is my client class:

import java.net.*;
import java.util.Scanner;
import java.io.*;
public class ClientDemo {
    private Socket mySocket = null;
    private ObjectInputStream in= null;
    private ObjectOutputStream out = null;
    private static long roundTrips=1;
    private static Payload myPayload=new Payload();

    public ClientDemo(String address, int port) throws ClassNotFoundException
    {
        int packageSize=1;
        double time=0;
        int bytes=0;
 try
        {
            mySocket = new Socket(address, port);
            System.out.println("Connected");
            out = new ObjectOutputStream(mySocket.getOutputStream());
            in = new ObjectInputStream(new BufferedInputStream(mySocket.getInputStream()));

        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
            while (myPayload.getCurr()<myPayload.getDataPasses())
            {

                try
                {
                        if(myPayload.getCurr()==0) {
                        myPayload.setTime(System.nanoTime());
                    }
                    out.writeObject(myPayload);
                    myPayload= (Payload) in.readObject();
                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
        try
        {
            in.close();
            out.close();
            mySocket.close();
            System.out.println("Operation Complete");
            System.out.println("Client Address: "+myPayload.getClient());
            System.out.println("Server Address: "+myPayload.getServer());
            time=System.nanoTime()-(myPayload.getTime());
            time=time/1000000000;
            System.out.println("Total Time (in seconds): "+time);
            bytes=(int) ( ((myPayload.getPacket().length)*myPayload.getDataPasses())/time);
            System.out.println("Bytes per Second: "+bytes);
            System.out.println("");
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // TODO Auto-generated method stub
        boolean isValid=false;
        String response="";
        int size=16384;
        Scanner myScanner = new Scanner(System.in);
        ClientDemo client=null;
        String server="";
        while (size>-1) {
            System.out.println("Please enter a max data packet size. Enter -1 to end the program");
            while(isValid==false) {
                response=myScanner.next();
                if(Long.parseLong(response)>=-1 && Long.parseLong(response)<=16384) {
                    isValid=true;
                    size=Integer.parseInt(response);
                    if(size>-1) {
                        myPayload.setPacket(fillPacket(size));
                    }
                }
                else {
                    System.out.println("Invalid Response. Please enter a value between 1 and 16384.");
                }
            }
        if(size==-1) {
            System.out.println("Closing server...");
            myPayload.setRepeat(false);
            client= new ClientDemo(server, 5000);

        }
        else {
            isValid=false;
            System.out.println("Please enter an amount of data passes.");
            while(isValid==false) {
                response=myScanner.next();
                if(Long.parseLong(response)>=1) {
                    isValid=true;
                    roundTrips=Long.parseLong(response);
                    myPayload.setDataPasses(roundTrips);
                }
                else {
                    System.out.println("Invalid Response. Please enter a value of 1 or greater.");
                }
            }
            isValid=false;
            System.out.println("Please enter your client address.");
            response=myScanner.next();
            myPayload.setClient(response);
            System.out.println("Please enter a server to connect to.");
            response=myScanner.next();
            server=response;
            myPayload.setServer(server);
            myPayload.reset();
            client= new ClientDemo(server, 5000);
            }
        }
    }

    public static int[] fillPacket(int size) {
        int[] thePacket= new int[size];
        int current=0;
        while(current<size) {
            for(int counter=0;counter<100;counter++) {
                if(current<size) {
                    thePacket[current]=counter;
                    current++;
                }
            }
        }
        return thePacket;
    }
}

When I attempt to run both, the operation I have set up works completely fine, and entering -1 to close the program works but I run into errors when performing operations beyond that. Attempting to set size to -1 to end the program at this point causes an endless loop of

java.io.EOFException

inside ServerDemo, while entering what should be a valid packet size between 0 and 16384 instead produces an endless stream of

java.net.SocketException: Broken pipe (Write failed)

inside ClientDemo. Perhaps most strangely, the latter error only SOMETIMES occurs, not always. If anyone has any pointers on how to get this correctly working and remedying these errors, I would greatly appreciate it!

Body:
I would rather change approach. The usual one when doing this kind of stuff is create a thread to listen on your port, then, when a client connects, immediately dispatch the new task to a thread pool and continue listening.

This way not only your server will continue listening after the client disconnects, but also will be able to serve multiple clients in parallel (up to the thread pool size).

Also please use try-with-resources whenever possible to easily avoid resource leaking.

So your code could be changed to something like this:

Server class

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerDemo {
    private int port;
    private Thread listenThread;
    private ExecutorService serverPool;

    public ServerDemo(int port) {
        this.port = port;
    }

    public synchronized void startServer() {
        serverPool = Executors.newFixedThreadPool(4);

        listenThread = new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                System.out.println(String.format("Listening on port %d", port));
                System.out.println("1");
                while (!Thread.interrupted()) {
                    System.out.println("2");
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("3");
                    if(!Thread.currentThread().isInterrupted())
                        serverPool.submit(new ClientTask(clientSocket));
                    System.out.println("4");
                }
            } catch (IOException e) {
                System.err.println("Error processing client connection");
                e.printStackTrace();
            }

            System.out.println("ListenThread stopped");
        }, "ListenThread");

        listenThread.start();
    }

    public synchronized void stopServer() {
        System.out.println("Stopping server...");
        if (serverPool != null) {
            serverPool.shutdown();
            serverPool = null;
        }

        if(listenThread != null) {
            listenThread.interrupt();

            try (Socket voidSocket = new Socket("localhost", port)) {
                // Void socket to unlock the accept() call
            } catch (IOException e) {
            }

            listenThread = null;
        }
    }

    private class ClientTask implements Runnable {
        private final Socket clientSocket;

        private ClientTask(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        @Override
        public void run() {
            System.out.println("Client accepted");
            Payload myPayload = new Payload();
            try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream())) {

                myPayload.setDataPasses(10);
                while (myPayload.getCurr() < myPayload.getDataPasses()) {
                    try {
                        myPayload = (Payload) in.readObject();
                        myPayload.raisePasses();
                        out.writeObject(myPayload);

                    } catch (IOException i) {
                        System.out.println(i);
                        break;
                    } catch (ClassNotFoundException e) {
                        System.err.println("Error finding class to deserialize");
                        e.printStackTrace();
                    }
                }
                System.out.println("Operation Complete");
                System.out.println("Client Address: " + myPayload.getClient());
                System.out.println("Server Address: " + myPayload.getServer());
                double time = System.nanoTime() - (myPayload.getTime());
                time = time / 1000000000;
                System.out.println("Total Time (in seconds): " + time);
                int bytes = (int) (((myPayload.getPacket().length) * myPayload.getDataPasses()) / time);
                System.out.println("Bytes per Second: " + bytes);
            } catch (IOException e1) {
                System.err.println("Error opening client I/O streams");
                e1.printStackTrace();
            }

            try {
                System.out.println("Closing connection");
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("Error closing client connection");
                e.printStackTrace();
            }

            if(!myPayload.getRepeat())
                stopServer();
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        ServerDemo server = new ServerDemo(5000);
        server.startServer();

        // do other stuff including trapping for sigterm, then call server.stopServer() if needed
    }

}

Client class

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class ClientDemo {

    private static void executeClientJob(Payload myPayload, int port) {
        double time = 0;
        int bytes = 0;
        try (Socket mySocket = new Socket(myPayload.getServer(), port);
                ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(mySocket.getInputStream()))) {

            System.out.println("Connected");
            while (myPayload.getCurr() < myPayload.getDataPasses()) {

                if (myPayload.getCurr() == 0)
                    myPayload.setTime(System.nanoTime());

                out.writeObject(myPayload);
                myPayload = (Payload) in.readObject();
            }

            System.out.println("Operation Complete");
            System.out.println("Client Address: " + myPayload.getClient());
            System.out.println("Server Address: " + myPayload.getServer());
            time = System.nanoTime() - (myPayload.getTime());
            time = time / 1000000000;
            System.out.println("Total Time (in seconds): " + time);
            bytes = (int) (((myPayload.getPacket().length) * myPayload.getDataPasses()) / time);
            System.out.println("Bytes per Second: " + bytes);
            System.out.println("");
        } catch (UnknownHostException u) {
            u.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            c.printStackTrace();
        }
    }

    private static void testAutomatic() {
        for (int i = 0; i < 1; i++) {
            Payload myPayload = new Payload();
            myPayload.setPacket(fillPacket(40));
            executeClientJob(myPayload, 5000);
        }
        Payload stopPayload = new Payload();
        stopPayload.setRepeat(false);
        executeClientJob(stopPayload, 5000);
    }

    private static void testInteractive() {
        Payload myPayload;
        boolean repeat;
        do {
            myPayload = readPayloadSettings();
            repeat = myPayload.getRepeat();
            executeClientJob(myPayload, 5000);
        } while (repeat);
    }

    private static Payload readPayloadSettings() {
        Payload ret = new Payload();
        int size = 60;

        @SuppressWarnings("resource")
        Scanner myScanner = new Scanner(System.in);
        System.out.println("Please enter a max data packet size. Enter -1 to end the program");
        while (true) {
            String response = myScanner.next();
            if (Long.parseLong(response) >= -1 && Long.parseLong(response) <= 16384) {
                size = Integer.parseInt(response);
                break;
            } else {
                System.out.println("Invalid Response. Please enter a value between 1 and 16384.");
            }
        }
        if (size == -1) {
            System.out.println("Closing server...");
            ret.setRepeat(false);
        } else {
            ret.setPacket(fillPacket(size));
            System.out.println("Please enter an amount of data passes.");
            while (true) {
                String response = myScanner.next();
                if (Long.parseLong(response) >= 1) {
                    ret.setDataPasses(Long.parseLong(response));
                    break;
                } else {
                    System.out.println("Invalid Response. Please enter a value of 1 or greater.");
                }
            }
            System.out.println("Please enter your client address.");
            ret.setClient(myScanner.next());
            System.out.println("Please enter a server to connect to.");
            ret.setServer(myScanner.next());
        }
        return ret;
    }

    public static int[] fillPacket(int size) {
        int[] thePacket = new int[size];
        int current = 0;
        while (current < size) {
            for (int counter = 0; counter < 100; counter++) {
                if (current < size) {
                    thePacket[current] = counter;
                    current++;
                }
            }
        }
        return thePacket;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        testInteractive();
        //testAutomatic();
    }
}

Payload class (with defaults to quick create an automatic test)

import java.io.Serializable;

public class Payload implements Serializable {

    private int curr=0;
    private long dataPasses=5;
    private long time;
    private String client="localhost";
    private String server="localhost";
    private int[] packet=new int[0];
    private boolean repeat=true;

    public Payload() {
    }

    public int getCurr() {
        return curr;
    }

    public void setCurr(int curr) {
        this.curr = curr;
    }

    public long getDataPasses() {
        return dataPasses;
    }
    public void setDataPasses(long roundTrips) {
        this.dataPasses = roundTrips;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long nanoTime) {
        time = nanoTime;

    }

    public String getClient() {
        return client;
    }

    public void setClient(String client) {
        this.client = client;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public int[] getPacket() {
        return packet;
    }

    public void setPacket(int[] packet) {
        this.packet = packet;
    }

    public boolean getRepeat() {
        return repeat;
    }

    public void setRepeat(boolean r) {
        this.repeat = r;
    }

    public void reset() {
        curr=0;
        dataPasses=0;
    }

    public void raisePasses() {
        curr++;
    }
}


问:
Here Maps API - group.getBoundingBox is not a function
Trying to group map Markers then focus and zoom on the group.

I have followed the Docs: Zooming to a Set of Markers

script

    public viewGroupMarkers() {
        // CREATE MARKERS
        const toronto = new H.map.Marker({lat:43.7,  lng:-79.4});
        const boston = new H.map.Marker({lat:42.35805, lng:-71.0636});
        const washington = new H.map.Marker({lat:38.8951, lng:-77.0366});
        // CREATE GROUP
        const group = new H.map.Group();
        group.addObjects([toronto, boston, washington]);
        // ADD GROUP TO MAP
        this.map.addObject(group);
        // GET VIEW BOUND GROUP
        this.map.getViewModel().setLookAtData({
          bounds: group.getBoundingBox()
        });
      }
```
<p>...but when trying to <code>group.getBoundingBox</code> I get an error:</p>
```core.js:6479 ERROR TypeError: group.getBoundingBox is not a function
    at HereMapsComponent.viewGroupMarkers (here-maps.component.ts:286:21)
    at TripMapComponent.setGroupViewBounds (trip-map.component.ts:91:28)
    at CardMapTripComponent.setMarkers (card-map-trip.component.ts:30:18)
    at CardMapTripComponent_Template_app_trip_map_isReady_15_listener (template.html:28:11)
    at executeListenerWithErrorHandling (core.js:15307:1)
    at Object.wrapListenerIn_markDirtyAndPreventDefault [as next] (core.js:15345:1)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:1)
    at SafeSubscriber.next (Subscriber.js:122:1)
    at Subscriber._next (Subscriber.js:72:1)
    at Subscriber.next (Subscriber.js:49:1)
```

答:
getBoundingBox method was introduced in Group object in the latest (3.1) version of API.

I think you still load legacy 3.0 API.

You have two options:

Migrate to version 3.1 (recommended). This migration guide should help you to switch to version 3.1.

change method to getBounds()

Body:
Trying to group map Markers then focus and zoom on the group.

I have followed the Docs: Zooming to a Set of Markers

script

    public viewGroupMarkers() {
        // CREATE MARKERS
        const toronto = new H.map.Marker({lat:43.7,  lng:-79.4});
        const boston = new H.map.Marker({lat:42.35805, lng:-71.0636});
        const washington = new H.map.Marker({lat:38.8951, lng:-77.0366});
        // CREATE GROUP
        const group = new H.map.Group();
        group.addObjects([toronto, boston, washington]);
        // ADD GROUP TO MAP
        this.map.addObject(group);
        // GET VIEW BOUND GROUP
        this.map.getViewModel().setLookAtData({
          bounds: group.getBoundingBox()
        });
      }

...but when trying to group.getBoundingBox I get an error:

core.js:6479 ERROR TypeError: group.getBoundingBox is not a function
    at HereMapsComponent.viewGroupMarkers (here-maps.component.ts:286:21)
    at TripMapComponent.setGroupViewBounds (trip-map.component.ts:91:28)
    at CardMapTripComponent.setMarkers (card-map-trip.component.ts:30:18)
    at CardMapTripComponent_Template_app_trip_map_isReady_15_listener (template.html:28:11)
    at executeListenerWithErrorHandling (core.js:15307:1)
    at Object.wrapListenerIn_markDirtyAndPreventDefault [as next] (core.js:15345:1)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:1)
    at SafeSubscriber.next (Subscriber.js:122:1)
    at Subscriber._next (Subscriber.js:72:1)
    at Subscriber.next (Subscriber.js:49:1)


问:
Adding SSL to domain hosted on route 53 AWS
I have added an IP to route 53 to make it a domain name and its working fine. But I dont know how could I add an ssl to that domain. Can anyone please refer me something how to do it?</p>

答:
Post is a bit old but I recently was looking for the same and I wanted to share how i solved it in hopes it's useful to others. It's easier than you think in AWS.

You need an SSL cert, either get it from other cert authorities and import it into AWS Certificate Manager (ACM) or get a public one from ACM and validate it against your domain by adding a hosted zone line, either manually or if you use Route 53 you just need to follow the ACM cert creation process and it will add it for you.

You need an AWS Application Load Balancer (ALB) to handle the https request handshakes for you to avoid doing it in every single web server node. In your ALB create 2 listeners, one on port 80 that will be redirecting all http requests to https, and the 2nd listener on port 443 where you associate the ACM certificate, define the default security policy and the forwarding to your Target Group (where you register the target instances/nodes of your servers)

In the security group of your ALB you enable inbound traffic in both ports 80 and 443

Lastly in your node web server you just need to make sure it accepts traffic in port 443 which for instance in a default Apache installation it does.

With this configuration, the ALB will handle the cert handshake validation with the client's browser and you don't need to bother configuring the ssl certificate in each of your web servers.
By the way AWS ALB doesn't allow traffic redirection from HTTPS to HTTP, so if you see here, we are doing the opposite, redirecting from HTTP to HTTPS.