问:
When is the best place to use Task.Result instead of awaiting Task
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

```<code>var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;
</code>```

Now becomes:

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;
</code>```

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

答:
Let's make sure to not bury the lede here:

So for example: [some correct code] becomes [some incorrect code]

NEVER NEVER NEVER DO THIS.

Your instinct that you can restructure your control flow to improve performance is excellent and correct. Using Result to do so is WRONG WRONG WRONG.

The correct way to rewrite your code is

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);
//Some work that doesn't rely on the user object
user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);
return user;
</code>```

Remember, await does not make a call asynchronous.  Await simply means "if the result of this task is not yet available, go do something else and come back here after it is available". The call is already asynchronous: it returns a task.

People seem to think that await has the semantics of a co-call; it does not. Rather, await is the extract operation on the task comonad; it is an operator on tasks, not call expressions. You normally see it on method calls simply because it is a common pattern to abstract away an async operation as a method.  The returned task is the thing that is awaited, not the call.

However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independent logic at the same time?

Why do you believe that using Result will allow you to perform other independent logic at the same time???  Result prevents you from doing exactly that.  Result is a synchronous wait. Your thread cannot be doing any other work while it is synchronously waiting for the task to complete. Use an asynchronous wait to improve efficiency.  Remember, await simply means "this workflow cannot progress further until this task is completed, so if it is not complete, find more work to do and come back later".  A too-early await can, as you note, make for an inefficient workflow because sometimes the workflow can progress even if the task is not complete.

By all means, move around where the awaits happen to improve efficiency of your workflow, but never never never change them into Result. You have some deep misunderstanding of how asynchronous workflows work if you believe that using Result will ever improve efficiency of parallelism in the workflow.  Examine your beliefs and see if you can figure out which one is giving you this incorrect intuition.

The reason why you must never use Result like this is not just because it is inefficient to synchronously wait when you have an asynchronous workflow underway.  It will eventually hang your process.  Consider the following workflow:

task1 represents a job that will be scheduled to execute on this thread in the future and produce a result.

asynchronous function Foo awaits task1.

task1 is not yet complete, so Foo returns, allowing this thread to run more work. Foo returns a task representing its workflow, and signs up completing that task as the completion of task1.

The thread is now free to do work in the future, including task1.

task1 completes, triggering the execution of the completion of the workflow of Foo, and eventually completing the task representing the workflow of Foo.

Now suppose Foo instead fetches Result of task1.  What happens?  Foo synchronously waits for task1 to complete, which is waiting for the current thread to become available, which never happens because we're in a synchronous wait.  Calling Result causes a thread to deadlock with itself if the task is somehow affinitized to the current thread. You can now make deadlocks involving no locks and only one thread!  Don't do this.

Body:
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;

Now becomes:

var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

Body:
Let's make sure to not bury the lede here:

So for example: [some correct code] becomes [some incorrect code]

NEVER NEVER NEVER DO THIS.

Your instinct that you can restructure your control flow to improve performance is excellent and correct. Using Result to do so is WRONG WRONG WRONG.

The correct way to rewrite your code is

var userTask = _userRepo.GetByUsername(User.Identity.Name);
//Some work that doesn't rely on the user object
user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);
return user;

Remember, await does not make a call asynchronous.  Await simply means "if the result of this task is not yet available, go do something else and come back here after it is available". The call is already asynchronous: it returns a task.

People seem to think that await has the semantics of a co-call; it does not. Rather, await is the extract operation on the task comonad; it is an operator on tasks, not call expressions. You normally see it on method calls simply because it is a common pattern to abstract away an async operation as a method.  The returned task is the thing that is awaited, not the call.

However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independent logic at the same time?

Why do you believe that using Result will allow you to perform other independent logic at the same time???  Result prevents you from doing exactly that.  Result is a synchronous wait. Your thread cannot be doing any other work while it is synchronously waiting for the task to complete. Use an asynchronous wait to improve efficiency.  Remember, await simply means "this workflow cannot progress further until this task is completed, so if it is not complete, find more work to do and come back later".  A too-early await can, as you note, make for an inefficient workflow because sometimes the workflow can progress even if the task is not complete.

By all means, move around where the awaits happen to improve efficiency of your workflow, but never never never change them into Result. You have some deep misunderstanding of how asynchronous workflows work if you believe that using Result will ever improve efficiency of parallelism in the workflow.  Examine your beliefs and see if you can figure out which one is giving you this incorrect intuition.

The reason why you must never use Result like this is not just because it is inefficient to synchronously wait when you have an asynchronous workflow underway.  It will eventually hang your process.  Consider the following workflow:

task1 represents a job that will be scheduled to execute on this thread in the future and produce a result.

asynchronous function Foo awaits task1.

task1 is not yet complete, so Foo returns, allowing this thread to run more work. Foo returns a task representing its workflow, and signs up completing that task as the completion of task1.

The thread is now free to do work in the future, including task1.

task1 completes, triggering the execution of the completion of the workflow of Foo, and eventually completing the task representing the workflow of Foo.

Now suppose Foo instead fetches Result of task1.  What happens?  Foo synchronously waits for task1 to complete, which is waiting for the current thread to become available, which never happens because we're in a synchronous wait.  Calling Result causes a thread to deadlock with itself if the task is somehow affinitized to the current thread. You can now make deadlocks involving no locks and only one thread!  Don't do this.


来源: stackexchange

问:
tensorflow missing dependency declaration for mpi_rendezvous_mgr
I am trying to compile tensorflow on SL7.3 with verbs and MPI support (no cuda).
I am getting stuck at following error on trying to build using bazel:

Command used for compilation :

```<code>bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package --verbose_failures
</code>```

Error seen:

```<code>ERROR: /root/tensorflow/tensorflow/contrib/mpi/BUILD:60:1: undeclared inclusion(s) in rule '//tensorflow/contrib/mpi:mpi_rendezvous_mgr':
this rule is missing dependency declarations for the following files included by 'tensorflow/contrib/mpi/mpi_rendezvous_mgr.cc':
  '/root/tensorflow/tensorflow/core/distributed_runtime/tensor_coding.h'.
Target //tensorflow/tools/pip_package:build_pip_package failed to build
</code>```

Can someone please help me with this ? I tried to look for a solution on stackoverflow (and other forums) but could not find much information.

Thanks

答:
You can try add a line into ..../tensorflow/tensorflow/contrib/mpi/BUILD file

```<code>...

cc_library(
    name = "mpi_rendezvous_mgr",
    srcs = ["mpi_rendezvous_mgr.cc"],
    hdrs = ["mpi_rendezvous_mgr.h"],
    deps = [
        ":mpi_msg_proto_cc",
        ":mpi_utils",
        "//tensorflow/core:core_cpu_internal",
        "//tensorflow/core:framework",
        "//tensorflow/core:gpu_runtime",
        "//tensorflow/core:lib",
        "//tensorflow/core:protos_cc",
        "//tensorflow/core:worker_proto_cc",
        "//tensorflow/core/distributed_runtime:base_rendezvous_mgr",
        "//tensorflow/core/distributed_runtime:session_mgr",
        "//tensorflow/core/distributed_runtime:worker_env",
        "//third_party/mpi",
        "//tensorflow/core/distributed_runtime:tensor_coding",   ## <<<<< add this line
    ],
)
</code>```

Hope it helps,

BR/thupalo

ContentLicense: CC BY-SA 4.0

Body:
I am trying to compile tensorflow on SL7.3 with verbs and MPI support (no cuda).
I am getting stuck at following error on trying to build using bazel:

Command used for compilation :

bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package --verbose_failures

Error seen:

ERROR: /root/tensorflow/tensorflow/contrib/mpi/BUILD:60:1: undeclared inclusion(s) in rule '//tensorflow/contrib/mpi:mpi_rendezvous_mgr':
this rule is missing dependency declarations for the following files included by 'tensorflow/contrib/mpi/mpi_rendezvous_mgr.cc':
  '/root/tensorflow/tensorflow/core/distributed_runtime/tensor_coding.h'.
Target //tensorflow/tools/pip_package:build_pip_package failed to build

Can someone please help me with this ? I tried to look for a solution on stackoverflow (and other forums) but could not find much information.

Thanks

Body:
You can try add a line into ..../tensorflow/tensorflow/contrib/mpi/BUILD file

...

cc_library(
    name = "mpi_rendezvous_mgr",
    srcs = ["mpi_rendezvous_mgr.cc"],
    hdrs = ["mpi_rendezvous_mgr.h"],
    deps = [
        ":mpi_msg_proto_cc",
        ":mpi_utils",
        "//tensorflow/core:core_cpu_internal",
        "//tensorflow/core:framework",
        "//tensorflow/core:gpu_runtime",
        "//tensorflow/core:lib",
        "//tensorflow/core:protos_cc",
        "//tensorflow/core:worker_proto_cc",
        "//tensorflow/core/distributed_runtime:base_rendezvous_mgr",
        "//tensorflow/core/distributed_runtime:session_mgr",
        "//tensorflow/core/distributed_runtime:worker_env",
        "//third_party/mpi",
        "//tensorflow/core/distributed_runtime:tensor_coding",   ## <<<<< add this line
    ],
)

Hope it helps,

BR/thupalo

ContentLicense: CC BY-SA 3.0


问:
Debugging keyboard events like 'Ctrl+Up Arrow'
I want to debug a part of a program that is intended to respond to keyboard input such as Ctrl+↑.

So, I put a breakpoint in the code in the area interest. However, once I press the Ctrl key the program jumps to that breakpoint. This happens before I have pressed an arrow key, so I'm finding this situation difficult to debug.

So, how can I debug a multi-key input event such as Ctrl+↑?

答: How about just putting the breakpoint inside the if clause? That way it only breaks if the condition is fulfilled.

ContentLicense: CC BY-SA 2.5


问:
Output PHP in a view?
I have an include that passes vars:

```<code>@include('site.my-view', ['text' => '<p>some text</p>'])
</code>```

But I wish to put some text and php in the text var, like so:

```<code>@include('site.my-view', ['text' => '<p>some text {{ $myVar }}</p>'])
</code>```

But this is rendered out as:

```<code>some text <?php echo $myVar ?>
</code>```

Inside my-view the text var is output like so:

```<code>{!! $text !!}
</code>```

How can I get it to actually echo? i've tried {{ }} with no luck.

答:
You can do it like this -</p>

```<code>@include('site.my-view', ['text' => '<p>some text '.$myVar.'</p>'])
</code>```

Title: Output PHP in a view?

Body:
I have an include that passes vars:

@include('site.my-view', ['text' => '
some text
'])

But I wish to put some text and php in the text var, like so:

@include('site.my-view', ['text' => '
some text {{ $myVar }}
'])

But this is rendered out as:

some text <?php echo $myVar ?>

Inside my-view the text var is output like so:

{!! $text !!}

How can I get it to actually echo? i've tried {{ }} with no luck.

Body:
You can do it like this -

@include('site.my-view', ['text' => '<p>some text '.$myVar.'</p>'])


问:
How can I set Anaconda3 python my default on windows
I have anaconda 3 with python 3 that works perfectly in anaconda prompt but I want to make anaconda python my default python. file names 'python.exe' is located at 'C:\ProgramData\Anaconda3\python.exe' but when I go to PATH Variables there's no file named python in Anaconda3 folder. Any suggestions on how to do it?</p>

答:
C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Scripts;C:\ProgramData\Anaconda3\Library\bin;

These three settings should be set automatically in the path folder by Anaconda? If not done automatically, put them at the very beginning of the list.


问:
UML use-cases and iterations
How can I represent in a UML use case's diagram the fact that an action is iterative? For example: actor Admin can add new categories and new subcategories. A subcategory can have other subcategories, so admin can add a new subcategory in a subcategory. Thanks.</p>

答: Usually a use-case diagram is accompanied by a document describing its basic and alternate flows. Iterative behavior may described in the those flows (steps).</p>

Title: UML use-cases and iterations


问:
Select data in single row for multi records of an ID from table
I have the following table in PostgreSQL database

I want a query that can produce following results.

Thank you

答:
Use conditional aggregate.

```<code>SELECT record_id,
       max(case when node = 'A' then state end) as A,
       max(case when node = 'B' then state end) as B,
       max(case when node = 'C' then state end) as C
FROM table1
group by record_id
order by record_id;
</code>```

OR

```<code>SELECT record_id,
       min(case when node = 'A' then state end) as A,
       min(case when node = 'B' then state end) as B,
       min(case when node = 'C' then state end) as C
FROM table1
group by record_id
order by record_id;
</code>```

Result:

```<code>record_id   a   b   c
----------------------
1000000     CC  CC  CC
1000001     CC  CC  CC
1000002     CC  CC  CC
</code>```

DEMO

Body:
Use conditional aggregate.

SELECT record_id,
       max(case when node = 'A' then state end) as A,
       max(case when node = 'B' then state end) as B,
       max(case when node = 'C' then state end) as C
FROM table1
group by record_id
order by record_id;

OR

SELECT record_id,
       min(case when node = 'A' then state end) as A,
       min(case when node = 'B' then state end) as B,
       min(case when node = 'C' then state end) as C
FROM table1
group by record_id
order by record_id;

Result:

record_id   a   b   c
----------------------
1000000     CC  CC  CC
1000001     CC  CC  CC
1000002     CC  CC  CC

DEMO


问:
PrimeNG autocomplete doesn't show suggestions
I'm using PrimeNg p-autocomplete in this way:

```<code><p-autoComplete id="area" [(ngModel)]="areaSearch" [ngModelOptions]="{standalone: true}" [suggestions]="results" (completeMethod)="retrieveArea($event)" field="name"></p-autoComplete>
</code>```

In component:

```<code>retrieveArea(event) {
    let searchString = event.query;
    this.results = [];
    searchString = searchString.toUpperCase();
    this.service.retrieveAreaCa(searchString).subscribe(response => {
        if (response.result) {
          this.results = response.data.list;
          //list = [{"name": "Paris", "code": "001"}, ...]
        },
        }
      });
  }
</code>```

It worked fine with PrimeNG version 4.0.1 but, after updating to 4.2.0, it doesn't show suggestions on typing. I think there aren't differences to do in code after updating but I can't understand why it doesn't work.
Any suggestions?

答:
This component is not stable yet.
There are some known issues about it.
I had the same and after update to PrimeNG 4.3.0 everything works fine.

See these 1 and 2 from PrimeNG's Github

Body:
I'm using PrimeNg p-autocomplete in this way:

In component:

retrieveArea(event) {
    let searchString = event.query;
    this.results = [];
    searchString = searchString.toUpperCase();
    this.service.retrieveAreaCa(searchString).subscribe(response => {
        if (response.result) {
          this.results = response.data.list;
          //list = [{"name": "Paris", "code": "001"}, ...]
        },
        }
      });
  }

It worked fine with PrimeNG version 4.0.1 but, after updating to 4.2.0, it doesn't show suggestions on typing. I think there aren't differences to do in code after updating but I can't understand why it doesn't work.
Any suggestions?


问:
Node.js unable to find a unique ID for a guest visiting my web/app
I want to get the user's IP or unique device ID so I can allow / disallow him to register based on history of tries he did.

Therefore: a guest visits my app.
This guest register.
I want to block him for register again at-least for two days.
But I do not how to do to this because he is guest.

OR, a guest ask for a SMS verification.
I want to allow him do that only 5 times a day.

I have searched tons of searches in Google on how to get a user's IP, but it did not work and I did not success finding his IP - seems too complicated or unreachable.

I have tried to use the UUID plugin by npm (GitHub repo) but this gave the same UUID for all visitors (probably it gave the UUID of the server or something).

I need an efficient way to do that.

Thanks.

答:
I am assuming that, you're using express framework.

Add the npm module express-session in your server.js file like,

```<code>const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
    secret : 'yourSecretPassPhrase',
    resave: true,
    saveUninitialized: true,
    cookie : {
      maxAge : 1000 * 60 * 60 * 24 * 2 //for two days(in millisec)
    }
  })
);
</code>```

Thereafter, a session object is inserted in every request!

```<code>app.get('/setUser', function(request, response){
        request.session.allowUser = true;      //creates user session
    })
);

app.get('/removeUser', function(request, response){
        del request.session.allowUser;      //deletes user session
    })
);

app.get('/checkUser', function(request, response){
        if(request.session.allowUser){
            //your code for existing or returning user
        }else{
            //your code for new user or session expired user
        }
    })
);
</code>```

express-session takes care of cookie management for you.

For more details check npm doc here https://www.npmjs.com/package/express-sessions.

You could get user's ip address from request object like

```<code>const clientIp = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
</code>```

But most probably client user will use dynamic ip. So, I would recommend you to use the express-session npm module, which tracks user using cookie rather than ip address

Body:
I am assuming that, you're using express framework.

Add the npm module express-session in your server.js file like,

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
    secret : 'yourSecretPassPhrase',
    resave: true,
    saveUninitialized: true,
    cookie : {
      maxAge : 1000 * 60 * 60 * 24 * 2 //for two days(in millisec)
    }
  })
);

Thereafter, a session object is inserted in every request!

app.get('/setUser', function(request, response){
        request.session.allowUser = true;      //creates user session
    })
);

app.get('/removeUser', function(request, response){
        del request.session.allowUser;      //deletes user session
    })
);

app.get('/checkUser', function(request, response){
        if(request.session.allowUser){
            //your code for existing or returning user
        }else{
            //your code for new user or session expired user
        }
    })
);

express-session takes care of cookie management for you.

For more details check npm doc here https://www.npmjs.com/package/express-sessions.

You could get user's ip address from request object like

const clientIp = request.headers['x-forwarded-for'] || request.connection.remoteAddress;

But most probably client user will use dynamic ip. So, I would recommend you to use the express-session npm module, which tracks user using cookie rather than ip address


问:
Inspect element - how to get parameters sent to a redirected page and simulate it with postman?
In this link there is a quiz when you click on Start Now:

https://www.clinique.com/diagnostics

After the quiz finished, it posts data to a link and immediately redirects to another page with quiz results.
How to find out what data have been posted to the page and is there a way to simulate the final results with the Postman?

答:
Looks like what you're looking for is the Postman Interceptor feature. It allows you to capture and inspect all the requests made from the browser/system you configure it to proxy to.

Then, once your request was captured, and after a bit of filtering (it'll capture every single request made to the server, not only the POST you're interested into) You will be able to replicate it with the Postman client like you'll do with a regular request. e.g. with the quiz you posted:

You'll find the data posted being sent as x-www-form-urlencoded (what a mess!) on a JSON key with the value:

```<code>{
"ProfileName":"04-NA-USA ELC Online 4.05.2017",
"QuizVersion":6,
"QuizAnswers":[
    {
        "attributeName":"welcome",
        "attributeRecapValuesLocalized":"mens_concerns",
        "recapColumn":1
    },
    {
        "attributeName":"mens_concerns",
        "attributeRecapValuesLocalized":"Eye Area",
        "recapColumn":0
    },
    {
        "attributeName":"mens_age",
        "attributeRecapValuesLocalized":"50 - 59",
        "recapColumn":1
    },
    {
        "attributeName":"mens_eye_area_where",
        "attributeRecapValuesLocalized":"Lines/Wrinkles",
        "recapColumn":0
    },
    {
        "attributeName":"mens_skintype",
        "attributeRecapValuesLocalized":"oily-shiny,tight-uncomfortable",
        "recapColumn":0
    },
    {
        "attributeName":"mens_sensitivity_frequency",
        "attributeRecapValuesLocalized":"Rarely",
        "recapColumn":1
    },
    {
        "attributeName":"mens_sensitivity_redness",
        "attributeRecapValuesLocalized":"No",
        "recapColumn":1
    },
    {
        "attributeName":"recap",
        "attributeRecapValuesLocalized":"",
        "recapColumn":1
    }
],
"SkinType":"2",
"SKUs":[
    {
        "Eye Area":[
            "7YXH-01",
            "7ELF-01",
            "6TCR-01"
        ]
    },
    {
        "Daily Care":[
            "ZE4L-01",
            "ZF7E-01",
            "65EM-01",
            "Z219-01",
            "Z5WW-01"
        ]
    }
],
"UPCs":[
    {
        "Eye Area":[
            "020714632670",
            "020714506827",
            "020714382742"
        ]
    },
    {
        "Daily Care":[
            "020714734510",
            "020714744762",
            "020714104726",
            "020714649562",
            "020714682255"
        ]
    }
],
"Concerns#1":"Eye Area",
"Concerns#2":"Daily Care",
"UsageOrderSKUs":[
    "ZE4L-01",
    "ZF7E-01",
    "65EM-01",
    "7YXH-01",
    "Z219-01",
    "Z5WW-01",
    "7ELF-01",
    "6TCR-01"
],
"UsageOrderUPCs":[
    "020714734510",
    "020714744762",
    "020714104726",
    "020714632670",
    "020714649562",
    "020714682255",
    "020714506827",
    "020714382742"
]
}
</code>```

Body:
Looks like what you're looking for is the Postman Interceptor feature. It allows you to capture and inspect all the requests made from the browser/system you configure it to proxy to.

Then, once your request was captured, and after a bit of filtering (it'll capture every single request made to the server, not only the POST you're interested into) You will be able to replicate it with the Postman client like you'll do with a regular request. e.g. with the quiz you posted:

You'll find the data posted being sent as x-www-form-urlencoded (what a mess!) on a JSON key with the value:

{
"ProfileName":"04-NA-USA ELC Online 4.05.2017",
"QuizVersion":6,
"QuizAnswers":[
    {
        "attributeName":"welcome",
        "attributeRecapValuesLocalized":"mens_concerns",
        "recapColumn":1
    },
    {
        "attributeName":"mens_concerns",
        "attributeRecapValuesLocalized":"Eye Area",
        "recapColumn":0
    },
    {
        "attributeName":"mens_age",
        "attributeRecapValuesLocalized":"50 - 59",
        "recapColumn":1
    },
    {
        "attributeName":"mens_eye_area_where",
        "attributeRecapValuesLocalized":"Lines/Wrinkles",
        "recapColumn":0
    },
    {
        "attributeName":"mens_skintype",
        "attributeRecapValuesLocalized":"oily-shiny,tight-uncomfortable",
        "recapColumn":0
    },
    {
        "attributeName":"mens_sensitivity_frequency",
        "attributeRecapValuesLocalized":"Rarely",
        "recapColumn":1
    },
    {
        "attributeName":"mens_sensitivity_redness",
        "attributeRecapValuesLocalized":"No",
        "recapColumn":1
    },
    {
        "attributeName":"recap",
        "attributeRecapValuesLocalized":"",
        "recapColumn":1
    }
],
"SkinType":"2",
"SKUs":[
    {
        "Eye Area":[
            "7YXH-01",
            "7ELF-01",
            "6TCR-01"
        ]
    },
    {
        "Daily Care":[
            "ZE4L-01",
            "ZF7E-01",
            "65EM-01",
            "Z219-01",
            "Z5WW-01"
        ]
    }
],
"UPCs":[
    {
        "Eye Area":[
            "020714632670",
            "020714506827",
            "020714382742"
        ]
    },
    {
        "Daily Care":[
            "020714734510",
            "020714744762",
            "020714104726",
            "020714649562",
            "020714682255"
        ]
    }
],
"Concerns#1":"Eye Area",
"Concerns#2":"Daily Care",
"UsageOrderSKUs":[
    "ZE4L-01",
    "ZF7E-01",
    "65EM-01",
    "7YXH-01",
    "Z219-01",
    "Z5WW-01",
    "7ELF-01",
    "6TCR-01"
],
"UsageOrderUPCs":[
    "020714734510",
    "020714744762",
    "020714104726",
    "020714632670",
    "020714649562",
    "020714682255",
    "020714506827",
    "020714382742"
]
}


问:
Scraping html tables into R data frames
I have a problem. I have to extract information from the website: https://www.transfermarkt.co.uk/premier-league/startseite/wettbewerb/GB1 with the name of the club, the address of their website (transfermarkt profile) and the name of the stadium from the team's profile. This is my first contact with the extraction of data from websites.  Any help appreciated. At first I wrote such code: </p>

```<code>library(rvest)
theurl <- "https://www.transfermarkt.co.uk/premier-league/startseite/wettbewerb/GB1"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)
</code>```

答:
As @Henry Navarro has pointed out, it is not clear which nodes, etc. you need exactly. Finding the right nodes is a time consuming task, so you need to specify which nodes you want. You can use Selectorgadget for this purpose.

In the following a quick example how you might generate the list of team websites that you will have to loop through with rvest to extract information. I think the main functionality you have been missing so far for this purpose is html_attr(), see, e.g., this answer. Of course, you will have to find the nodes on these sites to extract information on stadium, etc.

```<code>file %>%
html_nodes("table") %>%
{ .[4]} %>%
html_nodes("a") %>%
html_attr("href") %>%
{ .[grep("/startseite/verein",., fixed=T)]} %>%
unique() %>%
{ paste0("https://www.transfermarkt.co.uk", .) }

# [1] "https://www.transfermarkt.co.uk/fc-chelsea/startseite/verein/631/saison_id/2017"
# [2] "https://www.transfermarkt.co.uk/manchester-city/startseite/verein/281/saison_id/2017"
# [3] "https://www.transfermarkt.co.uk/manchester-united/startseite/verein/985/saison_id/2017"
# [4] "https://www.transfermarkt.co.uk/tottenham-hotspur/startseite/verein/148/saison_id/2017"
#...
</code>```

Title: Scraping html tables into R data frames

Body:
I have a problem. I have to extract information from the website: https://www.transfermarkt.co.uk/premier-league/startseite/wettbewerb/GB1 with the name of the club, the address of their website (transfermarkt profile) and the name of the stadium from the team's profile. This is my first contact with the extraction of data from websites.  Any help appreciated. At first I wrote such code:

library(rvest)
theurl <- "https://www.transfermarkt.co.uk/premier-league/startseite/wettbewerb/GB1"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)

Body:
As @Henry Navarro has pointed out, it is not clear which nodes, etc. you need exactly. Finding the right nodes is a time consuming task, so you need to specify which nodes you want. You can use Selectorgadget for this purpose.

In the following a quick example how you might generate the list of team websites that you will have to loop through with rvest to extract information. I think the main functionality you have been missing so far for this purpose is html_attr(), see, e.g., this answer. Of course, you will have to find the nodes on these sites to extract information on stadium, etc.

file %>%
html_nodes("table") %>%
{ .[4]} %>%
html_nodes("a") %>%
html_attr("href") %>%
{ .[grep("/startseite/verein",., fixed=T)]} %>%
unique() %>%
{ paste0("https://www.transfermarkt.co.uk", .) }

# [1] "https://www.transfermarkt.co.uk/fc-chelsea/startseite/verein/631/saison_id/2017"
# [2] "https://www.transfermarkt.co.uk/manchester-city/startseite/verein/281/saison_id/2017"
# [3] "https://www.transfermarkt.co.uk/manchester-united/startseite/verein/985/saison_id/2017"
# [4] "https://www.transfermarkt.co.uk/tottenham-hotspur/startseite/verein/148/saison_id/2017"
#...


问:
Communication between services in .NET
I'm facing an issue in a High Available Windows Services I developed with a master/slave setup.

Context:

The services itself synchronize data to two endpoints. One endpoint is synced to a local database, and one is an external. The database that is local is duplicated on both machines, so both master and slave need to sync this. The external endpoint only needs to be synced once.

The Master will by default sync to the external service, the slave will take over when the master is down. When the master goes back up and the slave is still synchronizing to the external, master will ask slave to finish a portion of the work, and then tell the master is done so he can continue the remaining work.

All this needs to happen asynchronously, I do not want the program to stop and wait for the other to respond (like the slave still handling the data).

I already implemented all the logic for this.

Setup:

Two Windows services running on two different machines.
Currently the communication is done over Named Pipes.

The problem:

Named pipes isn't reliable enough for the throughput that is being done. It also often crashes, and isn't made for reconnecting/closing and reopening a lot of times. I also face the problem that it just 'hangs' a lot when sending/receiving messages. Retrying sometimes works but I think I shouldn't be retrying. I need to have a reliable communication between the two instances.

Solutions:

I've been looking for an alternative to Named Pipes, but can't seem to find a solution of which I'm convinced that would work. Mostly because a lot of the technologies are for communication between a service and a client over http.

WCF over MSMQ is also not what I need, because I only want communication to happen when both are online. WCF in general is also more focused on one endpoint receiving data and sending a response. I need bidirectional communication, so both instances need to be able to receive and send messages at any time.

I think my best option is SignalR, but I'm also not convinced.

答:
Have you looked at MassTransit over RabbitMQ?

We have been using them together very successfully both for intra-service and client/service communication for a few years now.

Title: Communication between services in .NET


问:
How do you change the background color of the empty tab space in vim?
In vim, when you create a new tab, the tab bar appears at the top of the screen.  On the left are all your tabs, on the far right is an "X" for closing the tabs.  In between, there is "empty" space, that on my screen appears white.

I'll admit, I'm very picky about how my terminal looks, and this bright white bar at the top of the screen is distracting.  Is it possible to change this color to black, or maybe even gray?

答:
TLDR;

For a black tab bar (color 0)

```<code>:hi TabLineFill term=bold cterm=bold ctermbg=0
</code>```

Explanation

Use vim's highlight command to set the attributes you want on the TabLineFill group.

This command will show you a list of all the current groups and their highlight attributes.

```<code>:hi
</code>```

Find TabLineFill, and next to it you will see a preview of how your "tab line" will appear.  Also note the attributes on this line.

In order for the color you want to be displayed, the attribute representing your terminal needs to be set to "bold".  The two options are "term" and "cterm".  If your using vim in a color terminal, then cterm will apply, otherwise term will apply.  Set these attributes to bold like this:

```<code>:hi TabLineFill term=bold cterm=bold
</code>```

The attribute "ctermbg" may or may not appear on the TabLineFill line, but it is used to define the color of the terminal background.  See the list of cterm-color options by typing:

```<code>:help cterm-colors
</code>```

Choose a color (for unobtrusive, I recommend 0, which is Black), then set the ctermbg attribute to the code for that color:

```<code>:hi TabLineFill ctermbg=0
</code>```

This can all be combined into one single command:

```<code>:hi TabLineFill term=bold cterm=bold ctermbg=0
</code>```

Body:
TLDR;

For a black tab bar (color 0)

:hi TabLineFill term=bold cterm=bold ctermbg=0

Explanation

Use vim's highlight command to set the attributes you want on the TabLineFill group.

This command will show you a list of all the current groups and their highlight attributes.

:hi

Find TabLineFill, and next to it you will see a preview of how your "tab line" will appear.  Also note the attributes on this line.

In order for the color you want to be displayed, the attribute representing your terminal needs to be set to "bold".  The two options are "term" and "cterm".  If your using vim in a color terminal, then cterm will apply, otherwise term will apply.  Set these attributes to bold like this:

:hi TabLineFill term=bold cterm=bold

The attribute "ctermbg" may or may not appear on the TabLineFill line, but it is used to define the color of the terminal background.  See the list of cterm-color options by typing:

:help cterm-colors

Choose a color (for unobtrusive, I recommend 0, which is Black), then set the ctermbg attribute to the code for that color:

:hi TabLineFill ctermbg=0

This can all be combined into one single command:

:hi TabLineFill term=bold cterm=bold ctermbg=0


问:
Spring boot: should validation been tested when testing controller layer
I am working on the project where I want to have decent test-infrastructure.
I am using spring boot, which makes easier for testing separate layers of the project: for example

If I want to test controller layer I will mock (with mockito) service dependencies of the controller, and check whether right service method will be called on given http request, and expected http status will be returned. If I want to test service layer I will mock repository and business logic dependencies. And so on.

In my project, I am using spring validators to check whether request body is passed correctly (with the use of @InitBinder method I am adding my custom validators to the WebDataBinder, and with use of @Valid annotation, those validators are called on the parsed request body).

So my question is: is it good practice to mock validators and test only controller logic (validators will be tested in context of validator layer)?
I am just not sure which is the best practice, and is it normal to test validators along with controllers?

答:
Mocking is not always best option, when you are testing your controller logic, validation logic and especially business logic. I would not recommend to mock any of these.

You can use various framework to test:

Controller logic - RestAssured or MockMvc

Business logic - Plain JUnit tests under SpringBootTest and SpringRunner

Validation logic - Plain JUnit tests under SpringBootTest and
SpringRunner

For further reading:

RestAssured: http://rest-assured.io/

Spring validator test: Writing JUnit tests for Spring Validator implementation


问:
Scrapy get pre-redirect url
I've a crawler running without troubles but i need to get the start_url and not the redirected one.

The problem is i'm using rules to pass parameters to the URL ( like field-keywords=xxxxx ) and finally get the correct url.

The parse function starts getting the item attributes without any troubles but when i want the start URL ( the true one ) it stores the redirected one ...

I've tryed:

```<code>response.url
response.request.meta.get('redirect_urls')
</code>```

Both returns the final url ( the redirected one ) and not the start_url.

Some one know why, or has any clue ?

Thanks in advance.

答:
use a Spider Middleware to keep track of the start url from every response:

```<code>from scrapy import Request

class StartRequestsMiddleware(object):

    start_urls = {}

    def process_start_requests(self, start_requests, spider):
        for i, request in enumerate(start_requests):
            request.meta.update(start_url=request.url)
            yield request

    def process_spider_output(self, response, result, spider):
        for output in result:
            if isinstance(output, Request):
                output.meta.update(
                    start_url=response.meta['start_url'],
                )
            yield output
</code>```

keep track of the start_url every response comes from with:

```<code>response.meta['start_url']
</code>```

Title: Scrapy get pre-redirect url

Body:
I've a crawler running without troubles but i need to get the start_url and not the redirected one.

The problem is i'm using rules to pass parameters to the URL ( like field-keywords=xxxxx ) and finally get the correct url.

The parse function starts getting the item attributes without any troubles but when i want the start URL ( the true one ) it stores the redirected one ...

I've tryed:

response.url
response.request.meta.get('redirect_urls')

Both returns the final url ( the redirected one ) and not the start_url.

Some one know why, or has any clue ?

Thanks in advance.

Body:
use a Spider Middleware to keep track of the start url from every response:

from scrapy import Request

class StartRequestsMiddleware(object):

    start_urls = {}

    def process_start_requests(self, start_requests, spider):
        for i, request in enumerate(start_requests):
            request.meta.update(start_url=request.url)
            yield request

    def process_spider_output(self, response, result, spider):
        for output in result:
            if isinstance(output, Request):
                output.meta.update(
                    start_url=response.meta['start_url'],
                )
            yield output

keep track of the start_url every response comes from with:

response.meta['start_url']


问:
Delete from temporary tables takes 100% CPU for a long time
I have a pretty complex query where we make use of a temporary table (this is in Oracle running on AWS RDS service).

```<code>INSERT INTO TMPTABLE (inserts about 25.000 rows in no time)
SELECT FROM X JOIN TMPTABLE (joins with temp table also in no time)
DELETE FROM TMPTABLE (takes no time in a copy of the production database, up to 10 minutes in the production database)
</code>```

If I change the delete to a truncate it is as fast as in development.
So this change I will of course deploy. But I would like to understand why this occurs. AWS team has been quite helpful but they are a bit biased on AWS and like to tell me that my 3000 USD a month database server is not fast enough (I don't think so). I am not that fluent in Oracle administration but I have understood that if the redo logs are constantly filled, this can cause issues. I have increased the size quite substantially, but then again, this doesn't really add up.

答:
This is a fairly standard issue when deleting large amounts of data. The delete operation has to modify each and every row individually. Each row gets deleted, added to a transaction log, and is given an LSN.

truncate, on the other hand, skips all that and simply deallocates the data in the table.

You'll find this behavior is consistent across various RDMS solutions. Oracle, MSSQL, PostgreSQL, and MySQL will all have the same issue.

Body:
I have a pretty complex query where we make use of a temporary table (this is in Oracle running on AWS RDS service).

INSERT INTO TMPTABLE (inserts about 25.000 rows in no time)
SELECT FROM X JOIN TMPTABLE (joins with temp table also in no time)
DELETE FROM TMPTABLE (takes no time in a copy of the production database, up to 10 minutes in the production database)

If I change the delete to a truncate it is as fast as in development.
So this change I will of course deploy. But I would like to understand why this occurs. AWS team has been quite helpful but they are a bit biased on AWS and like to tell me that my 3000 USD a month database server is not fast enough (I don't think so). I am not that fluent in Oracle administration but I have understood that if the redo logs are constantly filled, this can cause issues. I have increased the size quite substantially, but then again, this doesn't really add up.


问:
What's the u prefix in a Python string?
Like in:

```<code>u'Hello'
</code>```

My guess is that it indicates "Unicode", is that correct?

If so, since when has it been available?

答:
I came here because I had funny-char-syndrome on my requests output. I thought response.text would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.

Turns out response.encoding was empty somehow and so response did not know how to properly decode the content and just treated it as ASCII (I guess).

My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8') to it. The result was schöne Umlaute.

The correctly decoded

für

vs. the improperly decoded

fĂźr

Title: What's the u prefix in a Python string?

Body:
Like in:

u'Hello'

My guess is that it indicates "Unicode", is that correct?

If so, since when has it been available?


问:
adding exception to a larger block of code
How would I go about adding this exception to a larger block of code? I already have the first part where "all courses with students enrolled where GRADE_LEVEL = PK through 12"

```<code>select [...], [...], [...],
case when [...]
into #table
from #other
where grade in ('PK', 'KG', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12')
and year = 2013
;
</code>```

but then I have to do this:

Select all courses with students enrolled where GRADE_LEVEL = PK through 12 with the following exception:
When SURVEY = 2 and DISTRICT_INST = 1 through 75, select all course enrollments – except if SCHOOL_INST = 7001, 7004, 7023, 7006; or DISTRICT = 71; or CHARTER_SCHL_STAT < > ‘Z’ and SCHL_FUNC_SETTING = ‘V’; or STUDENT_LOCATION = ‘T’, then only select courses where COURSE_GRADE = ‘IP’

```<code>   select count(*) from #students a
   where a.district_inst between 1 and 75
   and a.school_inst not in (7001, 7004, 7023, 7006)
   or a.district = 71
   or a.charter_schl_stat <> 'Z' and a.schl_func_setting = 'V'
   or a.student_location = 'T'
   and a.COURSE_GRADE_STAT = 'IP'

Is there a way to use except if?
</code>```

答:
EXCEPT is a keyword in SQL Server, but it doesn't work the way you would need it to, instead it's basically to compare two result sets, the opposite of INTERSECT.

For this you can get by with simple logic and brackets.

Your logic can be expressed like this:

Set 1 = all courses where the grade level is PK to 12 (as your original sample).

Set 2 = these are exceptions to the rule above, but I am assuming that these add to the results?  If not then the logic in my sample script will need changing.

Set 3 = these are exceptions to the exception, so items that would be allowed through the set 2 test, but then be excluded based on more complex logic.

Set 1 is simple, this is just anyone with the specified grade level.

Set 2 is also simple (if my understanding is correct), this is simply an exception to the constraint for set 1, based on the [survey] and [district_inst].  By bringing back all course enrolments we are basically saying that if any student passes the test for set 2 then SELECT all data for them.

Set 3 is an exception to set 2, where we bring back a constraint that the course grade must be "IP", but only for a subset of the data.

Putting this together, the logic is:

either the row falls under set 1, in which case we include it;

or it falls in set 2, but not set 3, in which case we include it;

or it falls in set 2, and also in set 3, but has a course grade of "IP" so is included.

All other data is excluded.

I put together this, it might be wrong, but I have no way to test (no data):

```<code>SELECT
    *
FROM
    #students s
WHERE
    --Grade level PK to 12
    s.grade_level IN ('PK', 'KG', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12')
    --Exception
    OR (
        s.survey = 2
        AND s.district_inst BETWEEN 1 AND 75
        AND (NOT (
            s.school_inst IN (7001, 7004, 7023, 7006)
            OR s.district = 71
            OR (s.charter_schl_stat != 'Z' AND s.schl_func_setting = 'V')
            OR (s.student_location = 'T'))
        OR s.course_grade = 'IP'));
</code>```

I imagine you will need to do some tweaking to this to get it to work exactly the way you want it.  Also, formatting SQL with multiple nested AND/ ORs with brackets becomes nasty quickly.

Body:
How would I go about adding this exception to a larger block of code? I already have the first part where "all courses with students enrolled where GRADE_LEVEL = PK through 12"

select [...], [...], [...],
case when [...]
into #table
from #other
where grade in ('PK', 'KG', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12')
and year = 2013
;

but then I have to do this:

Select all courses with students enrolled where GRADE_LEVEL = PK through 12 with the following exception:
When SURVEY = 2 and DISTRICT_INST = 1 through 75, select all course enrollments – except if SCHOOL_INST = 7001, 7004, 7023, 7006; or DISTRICT = 71; or CHARTER_SCHL_STAT < > ‘Z’ and SCHL_FUNC_SETTING = ‘V’; or STUDENT_LOCATION = ‘T’, then only select courses where COURSE_GRADE = ‘IP’

   select count(*) from #students a
   where a.district_inst between 1 and 75
   and a.school_inst not in (7001, 7004, 7023, 7006)
   or a.district = 71
   or a.charter_schl_stat <> 'Z' and a.schl_func_setting = 'V'
   or a.student_location = 'T'
   and a.COURSE_GRADE_STAT = 'IP'

Is there a way to use except if?

Body:
EXCEPT is a keyword in SQL Server, but it doesn't work the way you would need it to, instead it's basically to compare two result sets, the opposite of INTERSECT.

For this you can get by with simple logic and brackets.

Your logic can be expressed like this:

Set 1 = all courses where the grade level is PK to 12 (as your original sample).

Set 2 = these are exceptions to the rule above, but I am assuming that these add to the results?  If not then the logic in my sample script will need changing.

Set 3 = these are exceptions to the exception, so items that would be allowed through the set 2 test, but then be excluded based on more complex logic.

Set 1 is simple, this is just anyone with the specified grade level.

Set 2 is also simple (if my understanding is correct), this is simply an exception to the constraint for set 1, based on the [survey] and [district_inst].  By bringing back all course enrolments we are basically saying that if any student passes the test for set 2 then SELECT all data for them.

Set 3 is an exception to set 2, where we bring back a constraint that the course grade must be "IP", but only for a subset of the data.

Putting this together, the logic is:

either the row falls under set 1, in which case we include it;

or it falls in set 2, but not set 3, in which case we include it;

or it falls in set 2, and also in set 3, but has a course grade of "IP" so is included.

All other data is excluded.

I put together this, it might be wrong, but I have no way to test (no data):

SELECT
    *
FROM
    #students s
WHERE
    --Grade level PK to 12
    s.grade_level IN ('PK', 'KG', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12')
    --Exception
    OR (
        s.survey = 2
        AND s.district_inst BETWEEN 1 AND 75
        AND (NOT (
            s.school_inst IN (7001, 7004, 7023, 7006)
            OR s.district = 71
            OR (s.charter_schl_stat != 'Z' AND s.schl_func_setting = 'V')
            OR (s.student_location = 'T'))
        OR s.course_grade = 'IP'));

I imagine you will need to do some tweaking to this to get it to work exactly the way you want it.  Also, formatting SQL with multiple nested AND/ ORs with brackets becomes nasty quickly.


问:
GROUP BY with JOIN not giving correct result
How can I find the number of persons from each country

Person table

country_id, fName, lName

Countries table

country_id, country_name

I can find the number of persons from each country with their country IDs, using the below SQL statement

```<code>select
 p.country_id, COUNT(p.country_id) as [Count]
from
 persons p
GROUP BY
 p.country_id
</code>```

But what if I want to fetch country_name instead of country_id?
I tried this so far but it does not work as expected so I am missing something here.

```<code>select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    p.country_id
</code>```

SQL Server 2000

答: The SQL statement is correct. There was some data corruption in the database due to which the results were not returned correctly.</p>

Body:
How can I find the number of persons from each country

Person table

country_id, fName, lName

Countries table

country_id, country_name

I can find the number of persons from each country with their country IDs, using the below SQL statement

select
 p.country_id, COUNT(p.country_id) as [Count]
from
 persons p
GROUP BY
 p.country_id

But what if I want to fetch country_name instead of country_id?
I tried this so far but it does not work as expected so I am missing something here.

select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    p.country_id

SQL Server 2000


问:
How can I copy a string variable to another character by character without defining size of target variable?
I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

```<code>string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];
</code>```

But as the size of the string in C++ is calculated dynamically as

```<code>string k = "Hello";
string l = "Hello World";
string m = k;
m = l;
</code>```

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b.

```<code>string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];
</code>```

But in this case, my program is crashing and saying String subscript out of range.

Why not in this case the size of variable b is increasing?
What is the cause of the error and how can I achieve this without mentioning the size of any variable?

答:
You can simply use the += operator:

```<code>for (auto el : a){
    b += el;
}
</code>```

The std::string::operator+= has an overload that accepts character.

Body:
I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But as the size of the string in C++ is calculated dynamically as

string k = "Hello";
string l = "Hello World";
string m = k;
m = l;

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b.

string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But in this case, my program is crashing and saying String subscript out of range.

Why not in this case the size of variable b is increasing?
What is the cause of the error and how can I achieve this without mentioning the size of any variable?

Body:
You can simply use the += operator:

for (auto el : a){
    b += el;
}

The std::string::operator+= has an overload that accepts character.