问:
How to change a text in JSON that has quotes in it?
The following code works on python without any issue. It opens the JSON file, and replace all bananas to apples:

```<code>import json

replacements = "banana" : "apple"

with open(mycodepath, 'r') as file:
    data = file.read()
for old, new in replacements.items():
    data = data.replace(old, new)
</code>```

However, I want to replace "ArmReoriented", "visible": true with "ArmReoriented", "visible": false,

I tried using triple quotes, but it does not work.

```<code>replacements = """ArmReoriented", "visible": true""" : """ArmReoriented", "visible": false,"""
</code>```

How I replace a text containing quotes on JSON using Python?

答:
Try switching to single quotes in your replacements dict:

```<code>replacements = {'"ArmReoriented", "visible": true': '"ArmReoriented", "visible": false,'}

data = 'asd asd asd "ArmReoriented", "visible": true asd asd'
for old, new in replacements.items():
    data = data.replace(old, new)
print(data)
</code>```

You also may escape double quotes both from key and from value in your replacement dict:

```<code>replacements = {"\"ArmReoriented\", \"visible\": true": "\"ArmReoriented\", \"visible\": false,"}
</code>```

Body:
The following code works on python without any issue. It opens the JSON file, and replace all bananas to apples:

import json

replacements = "banana" : "apple"

with open(mycodepath, 'r') as file:
    data = file.read()
for old, new in replacements.items():
    data = data.replace(old, new)

However, I want to replace "ArmReoriented", "visible": true with "ArmReoriented", "visible": false,

I tried using triple quotes, but it does not work.

replacements = """ArmReoriented", "visible": true""" : """ArmReoriented", "visible": false,"""

How I replace a text containing quotes on JSON using Python?

Body:
Try switching to single quotes in your replacements dict:

replacements = {'"ArmReoriented", "visible": true': '"ArmReoriented", "visible": false,'}

data = 'asd asd asd "ArmReoriented", "visible": true asd asd'
for old, new in replacements.items():
    data = data.replace(old, new)
print(data)

You also may escape double quotes both from key and from value in your replacement dict:

replacements = {"\"ArmReoriented\", \"visible\": true": "\"ArmReoriented\", \"visible\": false,"}


来源: stackexchange

问:
Reload Page on Focus
I have a Progressive Web App that I need to refresh every time the user opens it.

To achieve this I have tried:

```<code>1) First Option
window.onblur = function() {
    window.onfocus= function () {
        window.location = self.location;
    }
};

2) Second Option
var blurred = false;
window.onblur = function() {
    blurred = true;
};
window.onfocus = function() {
    blurred && (window.location = self.location);
};
</code>```

Credit of Option 1: https://stackoverflow.com/a/16406350/11843328

Credit of Option 2: https://stackoverflow.com/a/11313719/11843328

This work well but the problem is that sometimes whenever you click something, it reloads again. It basically reloads like 4 times in a row with some action. Other times it works as expected, just reloading once, but most of the times is like 4 or 5 times in a row.

I need it to reload just once when opened (on focus). Is there any alternatives I could try or any advice would be appreciated!

答:
Make sure you're using window focus event. As others have pointed out, there is no need to use the blur event, as focus will only fire if the window focus was blurred.

You can use the window.location.reload method to reload the window as well.

window.addEventListener("focus", e => window.location.reload());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Look for a flicker</p></code>```

ContentLicense: CC BY-SA 4.0

Title: Reload Page on Focus

Body:
I have a Progressive Web App that I need to refresh every time the user opens it.

To achieve this I have tried:

1) First Option
window.onblur = function() {
    window.onfocus= function () {
        window.location = self.location;
    }
};

2) Second Option
var blurred = false;
window.onblur = function() {
    blurred = true;
};
window.onfocus = function() {
    blurred && (window.location = self.location);
};

Credit of Option 1: https://stackoverflow.com/a/16406350/11843328

Credit of Option 2: https://stackoverflow.com/a/11313719/11843328

This work well but the problem is that sometimes whenever you click something, it reloads again. It basically reloads like 4 times in a row with some action. Other times it works as expected, just reloading once, but most of the times is like 4 or 5 times in a row.

I need it to reload just once when opened (on focus). Is there any alternatives I could try or any advice would be appreciated!

Body:
Make sure you're using window focus event. As others have pointed out, there is no need to use the blur event, as focus will only fire if the window focus was blurred.

You can use the window.location.reload method to reload the window as well.

window.addEventListener("focus", e => window.location.reload());

<p>Look for a flicker</p>


问:
Getting 401 Unauthorized on Cloud Run when using end-user authentication
Following the authentication guide for Cloud Run here, I wanted to make a service only accessible by authenticated users.

I created a base service, called helloworld (yes, no originality here), and applied the following policy:

gcloud run services add-iam-policy-binding helloworld \
    --member="allAuthenticatedUsers" \
    --role="roles/run.invoker"
```

<p>I then tried to invoke it using the <code>gcloud auth print-identity-token</code> ID Token like this:</p>

<pre class="lang-sh prettyprint-override"><code>curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://helloworld-*****.a.run.app
</code>```

All good, the service responds with bearer tokens coming from a @gmail.com account and a GSuite one using gcloud.

As a next step, I followed the end-user authentication guide here and:

created web application credentials in the same project as the Cloud Run service above

redeployed the service to absorb the new Client ID configuration

created a simple HTML page with that Client ID and Google Sign-In logic (like this one)

run a local webserver to serve that page and got a new ID Token

attempted to do the same curl with that very token

This time though, the response was a 401 with the following value in the WWW-Authenticate header:

```<code>Bearer error="invalid_token" error_description="The access token could not be verified"
</code>```

This is the response of the https://oauth2.googleapis.com/tokeninfo API:

```<code>{
  "iss": "accounts.google.com",
  "azp": "*****************.apps.googleusercontent.com",
  "aud": "*****************.apps.googleusercontent.com",
  "sub": "*******",
  "email": "theuser@gmail.com",
  "email_verified": "true",
  "at_hash": "********",
  "name": "********",
  "picture": "********",
  "given_name": "********",
  "family_name": "********",
  "locale": "en",
  "iat": "1581617530",
  "exp": "1581621130",
  "jti": "6a0dd7561c0d95f7c92fc29a885039fe3f23db16",
  "alg": "RS256",
  "kid": "d8efea1f66e87bb36c2ea09d837338bdd810353b",
  "typ": "JWT"
}
</code>```

and the azp and aud values are the same Client ID that is defined as a Web Application credential in the project.

I also tried to add the specific user to the service like this:

gcloud run services add-iam-policy-binding helloworld \
    --member="user:theuser@gmail.com" \
    --role="roles/run.invoker"
```

Still no luck... What am I doing wrong?

答: Thanks to wlhee's input about the issue, I redeployed the service and was able to successfully access it with a token generated using the Client ID from the same project.</p>

Body:
Following the authentication guide for Cloud Run here, I wanted to make a service only accessible by authenticated users.

I created a base service, called helloworld (yes, no originality here), and applied the following policy:

gcloud run services add-iam-policy-binding helloworld \
    --member="allAuthenticatedUsers" \
    --role="roles/run.invoker"

I then tried to invoke it using the gcloud auth print-identity-token ID Token like this:

curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" https://helloworld-*****.a.run.app

All good, the service responds with bearer tokens coming from a @gmail.com account and a GSuite one using gcloud.

As a next step, I followed the end-user authentication guide here and:

created web application credentials in the same project as the Cloud Run service above

redeployed the service to absorb the new Client ID configuration

created a simple HTML page with that Client ID and Google Sign-In logic (like this one)

run a local webserver to serve that page and got a new ID Token

attempted to do the same curl with that very token

This time though, the response was a 401 with the following value in the WWW-Authenticate header:

Bearer error="invalid_token" error_description="The access token could not be verified"

This is the response of the https://oauth2.googleapis.com/tokeninfo API:

{
  "iss": "accounts.google.com",
  "azp": "*****************.apps.googleusercontent.com",
  "aud": "*****************.apps.googleusercontent.com",
  "sub": "*******",
  "email": "theuser@gmail.com",
  "email_verified": "true",
  "at_hash": "********",
  "name": "********",
  "picture": "********",
  "given_name": "********",
  "family_name": "********",
  "locale": "en",
  "iat": "1581617530",
  "exp": "1581621130",
  "jti": "6a0dd7561c0d95f7c92fc29a885039fe3f23db16",
  "alg": "RS256",
  "kid": "d8efea1f66e87bb36c2ea09d837338bdd810353b",
  "typ": "JWT"
}

and the azp and aud values are the same Client ID that is defined as a Web Application credential in the project.

I also tried to add the specific user to the service like this:

gcloud run services add-iam-policy-binding helloworld \
    --member="user:theuser@gmail.com" \
    --role="roles/run.invoker"

Still no luck... What am I doing wrong?


问:
Why do I see jerky animation when using this UIView animation block?
I have a a tab bar that is made in the application delegate. By calling an action form a button click from one of the views loaded from the tab bar, I open the help screen but there is a jerking motion after loading.

forgive me for speaking informally..I have been picking my brain for the past few hours trying to figure this out..

```<code>-(void)flipToHelp {
 HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
 [self setHelpViewController:helpVariable];
 [UIView beginAnimations:@"flipview" context:nil];
 [UIView setAnimationDuration:0.5];
 [UIView setAnimationCurve:UIViewAnimationCurveLinear];
 [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
 forView:_window cache:YES];

[_window removeFromSuperview];
[helpVariable release];
self.window.rootViewController = self.HelpViewController;
[UIView commitAnimations];
}
</code>```

答:
```<code>-(void)flipToHelp {
  HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
  [self setHelpViewController:helpVariable];
  [helpVariable release];

  [UIView beginAnimations:@"flipview" context:nil];
  [UIView setAnimationDuration:0.5];
  [UIView setAnimationCurve:UIViewAnimationCurveLinear];
  [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                         forView:self.window
                           cache:YES];

  self.window.rootViewController = self.HelpViewController;
  [UIView commitAnimations];
}
</code>```

How about this code? Does it still have a jerky animation?

ContentLicense: CC BY-SA 3.0

Body:
I have a a tab bar that is made in the application delegate. By calling an action form a button click from one of the views loaded from the tab bar, I open the help screen but there is a jerking motion after loading.

forgive me for speaking informally..I have been picking my brain for the past few hours trying to figure this out..

-(void)flipToHelp {
 HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
 [self setHelpViewController:helpVariable];
 [UIView beginAnimations:@"flipview" context:nil];
 [UIView setAnimationDuration:0.5];
 [UIView setAnimationCurve:UIViewAnimationCurveLinear];
 [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
 forView:_window cache:YES];

[_window removeFromSuperview];
[helpVariable release];
self.window.rootViewController = self.HelpViewController;
[UIView commitAnimations];
}

Body:
-(void)flipToHelp {
  HelpViewController *helpVariable = [[HelpViewController alloc] initWithNibName:@"HelpView" bundle:nil];
  [self setHelpViewController:helpVariable];
  [helpVariable release];

  [UIView beginAnimations:@"flipview" context:nil];
  [UIView setAnimationDuration:0.5];
  [UIView setAnimationCurve:UIViewAnimationCurveLinear];
  [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft
                         forView:self.window
                           cache:YES];

  self.window.rootViewController = self.HelpViewController;
  [UIView commitAnimations];
}

How about this code? Does it still have a jerky animation?


答: You don't need the onblur event. Using just the onfocus event will do the work.</p>

Title: Reload Page on Focus


问:
Replacing certain values in Python List
I have created a list for displaying a black/white (binary) image with its pixel values. However for the calculations  I am running I can not work with 0s represented by the black pixels. I have been trying to convert the 0s to 1s with the following code but it  does not work despite producing no errors:

```<code>from PIL import Image

img = Image.open('C:/Users/binary.png', 'r')
WIDTH, HEIGHT = img.size

data = list(img.getdata())  # convert image data to a list of integers
data = [data[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

for (i, item) in enumerate(data):
    if item == 0:
        data[i] = 1

for row in data:
    print(' '.join('{:3}'.format(value) for value in row))

</code>```

It might be noteworthy that when I try "item = 255" I get the following error:
"TypeError: '<' not supported between instances of 'list' and 'int'"

However this error doesn't make sense to me as when I do type(data) I get list output

答:
data is a list of lists, you need nested loops.

```<code>for row in data:
    for i, value in enumerate(row):
        if value == 0:
            row[i] = 1
</code>```

Title: Replacing certain values in Python List

Body:
I have created a list for displaying a black/white (binary) image with its pixel values. However for the calculations  I am running I can not work with 0s represented by the black pixels. I have been trying to convert the 0s to 1s with the following code but it  does not work despite producing no errors:

from PIL import Image

img = Image.open('C:/Users/binary.png', 'r')
WIDTH, HEIGHT = img.size

data = list(img.getdata())  # convert image data to a list of integers
data = [data[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

for (i, item) in enumerate(data):
    if item == 0:
        data[i] = 1

for row in data:
    print(' '.join('{:3}'.format(value) for value in row))

It might be noteworthy that when I try "item = 255" I get the following error:
"TypeError: '<' not supported between instances of 'list' and 'int'"

However this error doesn't make sense to me as when I do type(data) I get list output

Body:
data is a list of lists, you need nested loops.

for row in data:
    for i, value in enumerate(row):
        if value == 0:
            row[i] = 1


问:
How to fix Laravel eager loading not working with custom foreign key
Listing and Sub_Category have a one to many relationship. Listing belongs to one sub_category and sub_category has many listings.

I have a column on my listings table 'sub_catgory_id' and I have also specified the foreign key in my relationship

```<code>Listing.php Model
public function sub_category()
{
    return $this->belongsTo('App\Sub_Category', 'sub_category_id', 'id');
}
</code>```

Trying to get all listings associated with a sub category

```<code>return $sub_category = \App\Sub_Category::with('listing')->get()
</code>```

I get this error => Column not found: 1054 Unknown column 'listings.sub__category_id' in 'where clause'.

I know eloquent is checking for sub__category_id (double underscore) but I am already far into this project and would like to leave it as sub_category_id (single underscore). Any ideas about how this can be achieved?

答:
For the custom foreign key column you have pass two additional arguments for the function hasMany('Model', 'fk', 'pk') with the foreign key column name and the reference key column name.

```<code>class Category extends Model
{
    protected $table = 'categories';
    public function contents(){
        return $this->hasMany('App\Content', 'sub_cat_id', 'id');
    }
}
class Content extends Model
{
    //
    protected $table = 'contents';
    public function category(){
        return $this->belongsTo('App\Category');
    }
}

 Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id');
            $table->integer('parent_id');
            $table->string('title');
            $table->timestamps();
        });

Schema::create('contents', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('app_id');
            $table->integer('cat_id');
            $table->bigInteger('sub_cat_id')->unsigned();
            $table->integer('content_type');
            $table->text('content');
            $table->text('title');
            $table->timestamps();
            $table->foreign('sub_cat_id')->references('id')->
            on('categories')->onDelete('cascade');

        });
</code>```

Body:
Listing and Sub_Category have a one to many relationship. Listing belongs to one sub_category and sub_category has many listings.

I have a column on my listings table 'sub_catgory_id' and I have also specified the foreign key in my relationship

Listing.php Model
public function sub_category()
{
    return $this->belongsTo('App\Sub_Category', 'sub_category_id', 'id');
}

Trying to get all listings associated with a sub category

return $sub_category = \App\Sub_Category::with('listing')->get()

I get this error => Column not found: 1054 Unknown column 'listings.sub__category_id' in 'where clause'.

I know eloquent is checking for sub__category_id (double underscore) but I am already far into this project and would like to leave it as sub_category_id (single underscore). Any ideas about how this can be achieved?

Body:
For the custom foreign key column you have pass two additional arguments for the function hasMany('Model', 'fk', 'pk') with the foreign key column name and the reference key column name.

class Category extends Model
{
    protected $table = 'categories';
    public function contents(){
        return $this->hasMany('App\Content', 'sub_cat_id', 'id');
    }
}
class Content extends Model
{
    //
    protected $table = 'contents';
    public function category(){
        return $this->belongsTo('App\Category');
    }
}

 Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id');
            $table->integer('parent_id');
            $table->string('title');
            $table->timestamps();
        });

Schema::create('contents', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('app_id');
            $table->integer('cat_id');
            $table->bigInteger('sub_cat_id')->unsigned();
            $table->integer('content_type');
            $table->text('content');
            $table->text('title');
            $table->timestamps();
            $table->foreign('sub_cat_id')->references('id')->
            on('categories')->onDelete('cascade');

        });


问:
Foreign key POST in Django
I have some problems with my app . I need to make task with relations to user.

Here is my code:

bug

```<code> ValueError at /
Cannot assign "(<SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x04C54E38>>,)": "Task.usertask" must be a "UserMembership" instance.
</code>```

models.py

```<code>class UserMembership(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True,blank=True)
    image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)

class Task(models.Model):
    title=models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.now,blank=True)
    is_published=models.BooleanField(default=True)
    usertask=models.ForeignKey(UserMembership, on_delete=models.PROTECT, null=True, blank=True)
</code>```

views.py

```<code>if request.method == 'POST':
    usertask = request.user,
    title = request.POST['title']
    task = Task(usertask=usertask,title=title)
    task.save()

task = Task.objects.order_by('-date').filter(is_published=True, usertask=request.user.id)

context={
    'task':task,
}
return render(request,'index.html',context)
</code>```

html form

```<code><form action="" method="POST">
{% csrf_token %}

    <input name="title" type="text" class="form-control" id="usr">

<button type="submit" class="btn btn-primary">add</button>
</code>```

答:
A few things:

1) in your views function you are doing this: usertask = request.user. Note that request.user will return a User object.

2) You then try to create a Task object by doing this task = Task(usertask=usertask,title=title) but here you have set usertask to a User object when you really need a UserMembership object

You can try rewriting your view function like so:

```<code>def MyViewFunction(request):

    # unpack request:
    user = request.user
    title = request.POST['title']

    # create new UserMembership object:
    user_membership = UserMembership.objects.create(user=user)
    user_membership.save()

    # create new Task object:
    task = Task.objects.create(usetask=user_membership, title=title)
    task.save()

    # continue code here...
</code>```

Title: Foreign key POST in Django

Body:
I have some problems with my app . I need to make task with relations to user.

Here is my code:

bug

 ValueError at /
Cannot assign "(<SimpleLazyObject: <function AuthenticationMiddleware.process_request.<locals>.<lambda> at 0x04C54E38>>,)": "Task.usertask" must be a "UserMembership" instance.

models.py

class UserMembership(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True,blank=True)
    image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)

class Task(models.Model):
    title=models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.now,blank=True)
    is_published=models.BooleanField(default=True)
    usertask=models.ForeignKey(UserMembership, on_delete=models.PROTECT, null=True, blank=True)

views.py

if request.method == 'POST':
    usertask = request.user,
    title = request.POST['title']
    task = Task(usertask=usertask,title=title)
    task.save()

task = Task.objects.order_by('-date').filter(is_published=True, usertask=request.user.id)

context={
    'task':task,
}
return render(request,'index.html',context)

html form

<form action="" method="POST">
{% csrf_token %}

    <input name="title" type="text" class="form-control" id="usr">

<button type="submit" class="btn btn-primary">add</button>

Body:
A few things:

1) in your views function you are doing this: usertask = request.user. Note that request.user will return a User object.

2) You then try to create a Task object by doing this task = Task(usertask=usertask,title=title) but here you have set usertask to a User object when you really need a UserMembership object

You can try rewriting your view function like so:

def MyViewFunction(request):

    # unpack request:
    user = request.user
    title = request.POST['title']

    # create new UserMembership object:
    user_membership = UserMembership.objects.create(user=user)
    user_membership.save()

    # create new Task object:
    task = Task.objects.create(usetask=user_membership, title=title)
    task.save()

    # continue code here...


问:
How do I get spacemacs web-mode autocomplete to relax a little?
I'm new to Spacemacs and Emacs. When I'm editing in web-mode, like an html document, I'm often triggering the autocomplete prompt when I haven't typed anything relevant yet. I don't have this problem in the html blocks, that I remember, but when in script (js) or css blocks it gets pretty cumbersome to have to swat away the menu constantly.

You can see from the above example that I'm editing css and after completing the property definition with a semicolon the autocompletion pops up meaning that hitting semicolon and enter to start the next line will instead add useless text to the line after the semicolon. how can I alter this behaviour?

You can see here again I have almost the same problem when editing inside the script tag. Opening a function definition with a curly brace and hitting enter to go to the next line instead inserts useless text after the brace.

The file I am editing is .svelte, but I've told emacs to use web-mode

My dotspacemacs/user-config has the following:

```<code>(add-hook 'text-mode-hook 'turn-on-visual-line-mode)
(add-to-list 'auto-mode-alist '("\\.svelte?\\'" . web-mode))
(setq web-mode-markup-indent-offset 2)
(setq web-mode-css-indent-offset 2)
(setq web-mode-code-indent-offset 2)

(setq configuration-layer--elpa-archives
      '(("melpa-cn" . "http://elpa.emacs-china.org/melpa/")
        ("org-cn"   . "http://elpa.emacs-china.org/org/")
        ("gnu-cn"   . "http://elpa.emacs-china.org/gnu/")))
</code>```

答: Not a spacemacs user myself, but it appears you have set company-minimum-prefix-length to 0, whereas you probably want it to be at least 2.  You could also consider increasing company-idle-delay which would cause candidates to be presented slower.

Body:
I'm new to Spacemacs and Emacs. When I'm editing in web-mode, like an html document, I'm often triggering the autocomplete prompt when I haven't typed anything relevant yet. I don't have this problem in the html blocks, that I remember, but when in script (js) or css blocks it gets pretty cumbersome to have to swat away the menu constantly.

You can see from the above example that I'm editing css and after completing the property definition with a semicolon the autocompletion pops up meaning that hitting semicolon and enter to start the next line will instead add useless text to the line after the semicolon. how can I alter this behaviour?

You can see here again I have almost the same problem when editing inside the script tag. Opening a function definition with a curly brace and hitting enter to go to the next line instead inserts useless text after the brace.

The file I am editing is .svelte, but I've told emacs to use web-mode

My dotspacemacs/user-config has the following:

(add-hook 'text-mode-hook 'turn-on-visual-line-mode)
(add-to-list 'auto-mode-alist '("\\.svelte?\\'" . web-mode))
(setq web-mode-markup-indent-offset 2)
(setq web-mode-css-indent-offset 2)
(setq web-mode-code-indent-offset 2)

(setq configuration-layer--elpa-archives
      '(("melpa-cn" . "http://elpa.emacs-china.org/melpa/")
        ("org-cn"   . "http://elpa.emacs-china.org/org/")
        ("gnu-cn"   . "http://elpa.emacs-china.org/gnu/")))


问:
Weird Debugging Behavior with Struct That Contains a UUID
Consider this struct:

```<code>struct test
{
    var id:UUID = UUID()
    var name:String = ""
}
</code>```

When executing the following line of code:

```<code>var myTest : test?
</code>```

The debugger correctly shows myTest = nil

Then I execute:

```<code>myTest = test()
</code>```

The debugger still shows MyTest = nil

If I remove the id variable from the struct, the debugger correctly shows a value for myTest.

It seems that whenever I have a UUID in the struct it does this.

Is this a bug in Xcode11, or am I missing something?

Here is a screenshot after declaring myTest showing it nil as expected:

Here is a screenshot after setting myTest to test(), and printing it. You can see that the print shows the initialized structure, but the debug window still shows myTest as nil:

答:
I am not sure why you think this is unexpected behaviour.
If you were to have a struct like so:

```<code>struct test {
    var name: String = ""
}
</code>```

By doing so

```<code>var myTest: test?

myTest = test()

print(myTest)
</code>```

result: Optional(__lldb_expr_7.test(name: ""))

Even if you were to add in a UUID like so :

```<code>struct test {
    var id: UUID = UUID(uuid: UUID_NULL)
    var name: String = ""
}
</code>```

and did the same thing

```<code>var myTest: test?
myTest = test()
print(myTest)
</code>```

Result: Optional(__lldb_expr_9.test(id: 00000000-0000-0000-0000-000000000000, name: ""))

You are still given the structure

if you had a struct like so

```<code>struct test {
    var id: UUID = UUID(uuid: UUID_NULL)
    var name: String = ""
    var lastName: String = ""
}
</code>```

and still did the same thing...

```<code>var myTest: test?

myTest = test()

print(myTest)
</code>```

result: Optional(__lldb_expr_11.test(id: 00000000-0000-0000-0000-000000000000, name: "", lastName: ""))

you are still given back results...

The results are all nill or empty strings as defined in the struct...

we can then append to the struct like so

```<code>var myTest: test?

myTest = test(id: some_UUID_Number_Here, name: "Jack", lastName: "Sparrow")

print(myTest as Any)
</code>```

result: Optional(__lldb_expr_3.test(id: BBDD802E-8976-4D93-A6E2-1D43442EA9CD, name: "Jack", lastName: "Sparrow"))

Hope this helps...

Body:
Consider this struct:

struct test
{
    var id:UUID = UUID()
    var name:String = ""
}

When executing the following line of code:

var myTest : test?

The debugger correctly shows myTest = nil

Then I execute:

myTest = test()

The debugger still shows MyTest = nil

If I remove the id variable from the struct, the debugger correctly shows a value for myTest.

It seems that whenever I have a UUID in the struct it does this.

Is this a bug in Xcode11, or am I missing something?

Here is a screenshot after declaring myTest showing it nil as expected:

Here is a screenshot after setting myTest to test(), and printing it. You can see that the print shows the initialized structure, but the debug window still shows myTest as nil:

Body:
I am not sure why you think this is unexpected behaviour.
If you were to have a struct like so:

struct test {
    var name: String = ""
}

By doing so

var myTest: test?

myTest = test()

print(myTest)

result: Optional(__lldb_expr_7.test(name: ""))

Even if you were to add in a UUID like so :

struct test {
    var id: UUID = UUID(uuid: UUID_NULL)
    var name: String = ""
}

and did the same thing

var myTest: test?
myTest = test()
print(myTest)

Result: Optional(__lldb_expr_9.test(id: 00000000-0000-0000-0000-000000000000, name: ""))

You are still given the structure

if you had a struct like so

struct test {
    var id: UUID = UUID(uuid: UUID_NULL)
    var name: String = ""
    var lastName: String = ""
}

and still did the same thing...

var myTest: test?

myTest = test()

print(myTest)

result: Optional(__lldb_expr_11.test(id: 00000000-0000-0000-0000-000000000000, name: "", lastName: ""))

you are still given back results...

The results are all nill or empty strings as defined in the struct...

we can then append to the struct like so

var myTest: test?

myTest = test(id: some_UUID_Number_Here, name: "Jack", lastName: "Sparrow")

print(myTest as Any)

result: Optional(__lldb_expr_3.test(id: BBDD802E-8976-4D93-A6E2-1D43442EA9CD, name: "Jack", lastName: "Sparrow"))

Hope this helps...


问:
High performance TCP server in C#
I am an experienced C# developer, but I have not developed a TCP server application so far. Now I have to develop a highly scalable and high performance server that can handle at least 5-10 thousand concurrent connections: getting -raw byte- data via GPRS from GPS devices.

A common communication process should look like this:

GPS device initiates a connection to my server

my server answers if I want to get data

device send GPS data

my server sends report to the device about getting it (sg like checksum)

getting new data from GPS, reportm and this happens again and again

later GPS DEVICE closes the connection

So, in my server I need

trace connected/active clients

to close any client from server side

catch the event, when a device closes the connection

get byte data

send data to clients

I started to read about this topic over the internet, but it seems to be a nightmare for me. There are a lot of ways, but I could not find out which is the best.

Async socket methods seems the best for me, but writing code in this async style is terrible and not easy to debug.

So my question is: which do you think the best way to implement a high performance TCP server in C#? Do you know any good open source component to do this? (I tried several ones, but I could not find a good one.)

答:
It must be async, there is no way around this. High performance and scalability don't mix with one-thread-per-socket. You can have a look at what StackExchange themselves are doing, see async Redis await BookSleeve which leverages the CTP features from the next C# release (so is on the edge and subject to changes, but it is cool). For even more bleeding edge the solutions evolves around leveraging SocketAsyncEventArgs Class which takes things one step further by eliminating the frequent allocations of async handlers associated with 'classic' C# async processing:

The SocketAsyncEventArgs class is part
  of a set of enhancements to the
  System.Net.Sockets.Socket class that
  provide an alternative asynchronous
  pattern that can be used by
  specialized high-performance socket
  applications. This class was
  specifically designed for network
  server applications that require high
  performance. An application can use
  the enhanced asynchronous pattern
  exclusively or only in targeted hot
  areas (for example, when receiving
  large amounts of data).

Long story short: learn async or die trying...

BTW, if you're asking why async, then read the three articles linked from this post: High Performance Windows programs. The ultimate answer is: the underlying OS design requires it.

Title: High performance TCP server in C#


问:
How to configure filebeat kubernetes deamon to index on namespace or pod name
I am currently attempting to get the logs from my kubernetes cluster to an external ElasticSearch/Kibana. So far I have used this daemon deployment to get filebeat running and piping to my external server, but I am unable to figure out how to set the index to something meaningfull. This documentation page tells me that I need to create am index key in the output.elasticsearch section, but I don't know what to put in the value.

My desired output format would be something along the lines of <cluster-name>-<namespace>-<pod name>

IE: devKube-frontend-publicAPI-123abc

答:
Precondition: You have enabled add_kubernetes_metadata: ~.

Then you can use that metadata in the index name like this:

```<code>output.elasticsearch:
  index: "%{[kubernetes.namespace]:filebeat}-%{[beat.version]}-%{+yyyy.MM.dd}"
</code>```

%{[kubernetes.namespace]:filebeat}: Use the Kubernetes namespace or if there is none fall back to filebeat.

Adding %{[beat.version]} is highly recommended for the scenario when you upgrade Filebeat and there is a breaking change in the mapping. This should be limited to major version changes (if at all), but is an issue you can easily avoid with this setting.

A time based index pattern like %{+yyyy.MM.dd} or even better would be an ILM policy to have evenly and properly sized shards.

PS: You have the Pod name and other details in fields from add_kubernetes_metadata: ~. I would be careful not to cut the indices into tiny pieces, since every shard has a certain amount of overhead. The default Filebeat ILM policy is 50GB per shard — if your shards are smaller than 10GB you will most likely run into issues at some point. Leave the indices a bit more coarse grained and just use a filter for a specific Pod instead.

Body:
Precondition: You have enabled add_kubernetes_metadata: ~.

Then you can use that metadata in the index name like this:

output.elasticsearch:
  index: "%{[kubernetes.namespace]:filebeat}-%{[beat.version]}-%{+yyyy.MM.dd}"

%{[kubernetes.namespace]:filebeat}: Use the Kubernetes namespace or if there is none fall back to filebeat.

Adding %{[beat.version]} is highly recommended for the scenario when you upgrade Filebeat and there is a breaking change in the mapping. This should be limited to major version changes (if at all), but is an issue you can easily avoid with this setting.

A time based index pattern like %{+yyyy.MM.dd} or even better would be an ILM policy to have evenly and properly sized shards.

PS: You have the Pod name and other details in fields from add_kubernetes_metadata: ~. I would be careful not to cut the indices into tiny pieces, since every shard has a certain amount of overhead. The default Filebeat ILM policy is 50GB per shard — if your shards are smaller than 10GB you will most likely run into issues at some point. Leave the indices a bit more coarse grained and just use a filter for a specific Pod instead.


问:
Authenticate javax.naming.NamingException: LDAP
I am trying authenticate with LDAP using SpringBoot, but I get error for NamingException, I am new with this, but I saw this post Authenticating using LDAP with spring LDAP API and without using spring security

Pom.xml

```<code><dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
 </dependency> -> 2.3.2
</code>```

Then, I created my config to access

```<code>@Configuration
public class LdapConfig {
    /** The ldap url. */
    @Value("${ldap.url}")
    private String ldapUrl;       //   ldap://MYCOMPANY.com:389

    /** The ldap access password. */
    @Value("${ldap.password}")
    private String ldapAccessPassword;  // Password to access LDAP

    /** The ldap U base user. */
    @Value("${ldap.base}")
    private String ldapUBaseUser;  //  OU=USERS,OU=ACCOUNTS,DC=rg,DC=MYCOMPANY,DC=com

    /**
     * Context source.
     *
     * @return the ldap context source
     */
    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldapUrl);
        contextSource.setPassword(ldapAccessPassword);
        contextSource.setBase(ldapUBaseUser);
        return contextSource;
    }

    /**
     * Ldap template.
     *
     * @return the ldap template
     */
    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}
</code>```

Ok, Here I have a big question... I create my connection with url (logic) with password(logic) ...... ¿¿ WHERE is my user ?? I put password but I never see in google put user, really ???

Finally my Impl:

```<code>@Autowired
private LdapTemplate ldapTemplate;

@Value("${ldap.base}")
private String base;    // WHY DO I REPEAT THIS VALUE ??? In my @configuration I especified the base

public boolean existUser(String usr, String pwd) {
try {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("mailNickname", usr));

    Boolean authenticate = ldapTemplate.authenticate(base, filter.encode(), pwd);
    boolean result = authenticate.booleanValue();
    if(!result) {
        LOGGER.info("The: " + usr + " , is failed.");
    }
    return result;
 } catch (Exception e) {
    LOGGER.error("Error existUser() --> " +e);
    e.printStackTrace();
    return false;
 }
}
</code>```

Finally I call my method existUser() with user and password the front-End, I need know if this user/password exists in LDAP, but I get this error:

```<code>12-02-2020 09:03:27.821 [http-nio-80-exec-5] ERROR e.c.service.impl.LoginServiceImp.existUser -Error existUser() --> org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: e                                                 rror code 1 - 000004DC: LdapErr: DSID-0C0907C2, comment: In order to perform this operation a s                                                 uccessful bind must be completed on the connection., data 0, v2580]; remaining name 'OU=USERS,O                                                 U=ACCOUNTS,DC=rg,DC=MYCOMPANY,DC=com'
org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - 000004DC:LdapErr: DSID-0C0907C2, comment: In order to perform this operation a successful bind must be                                                  completed on the connection., data 0, v2580]; remaining name 'OU=USERS,OU=ACCOUNTS,DC=rg,DC=rep                                                 sol,DC=com'
        at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:228)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:397)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
        at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1441)
        at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1426)
        at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1369)
        at es.MYPROJECT.service.impl.LoginServiceImp.existUser(LoginServiceImp.java:29)
        at es.MYPROJECT.controller.LoginController.login(LoginController.java:40)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43                                                 )
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHand                                                 lerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(Invoc                                                 ableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.                                                 invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.i                                                 nvokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.h                                                 andleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(Abstr                                                 actHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:                                                 967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:9                                                 01)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.jav                                                 a:970)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:317)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(Exceptio                                                 nTranslationFilter.java:114)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionMan                                                 agementFilter.java:137)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilt                                                 er(AnonymousAuthenticationFilter.java:111)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.                                                 doFilter(SecurityContextHolderAwareRequestFilter.java:170)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(Reque                                                 stCacheAwareFilter.java:63)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutF                                                 ilter.java:116)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWr                                                 iterFilter.java:64)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(S                                                 ecurityContextPersistenceFilter.java:105)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFil                                                 ter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.                                                 java:214)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177                                                 )
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilter                                                 Proxy.java:347)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.                                                 java:263)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextF                                                 ilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutForm                                                 ContentFilter.java:108)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMet                                                 hodFilter.java:81)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEnc                                                 odingFilter.java:197)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:50                                                 4)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:7                                                 90)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
Caused by: javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0907C2                                                 , comment: In order to perform this operation a successful bind must be completed on the connec                                                 tion., data 0, v2580]; remaining name 'OU=USERS,OU=ACCOUNTS,DC=rg,DC=MYCOMPANY,DC=com'
        at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3194)
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3100)
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2891)
        at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1846)
        at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1769)
        at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:392)
        at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContex                                                 t.java:358)
        at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:276)
        at org.springframework.ldap.core.LdapTemplate$3.executeSearch(LdapTemplate.java:303)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:363)
        ... 92 more
</code>```

Thanks.

答:
An authentication(bind) is required before performing the search operation. You need to add contextSource.setUserDn("userDn"); to the ldapcontextsource, or try:

/**
 * this method is used to verify and authenticate the user.
 *
 * @param login user's login
 * @param password user's password
 */
public void verifyCredentials(String login, String password)
{
    LdapQuery query = LdapQueryBuilder.query().where("cn").is(login);
    ldapTemplate.authenticate(query, password);
}
```

Body:
I am trying authenticate with LDAP using SpringBoot, but I get error for NamingException, I am new with this, but I saw this post Authenticating using LDAP with spring LDAP API and without using spring security

Pom.xml

<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
 </dependency> -> 2.3.2

Then, I created my config to access

@Configuration
public class LdapConfig {
    /** The ldap url. */
    @Value("${ldap.url}")
    private String ldapUrl;       //   ldap://MYCOMPANY.com:389

    /** The ldap access password. */
    @Value("${ldap.password}")
    private String ldapAccessPassword;  // Password to access LDAP

    /** The ldap U base user. */
    @Value("${ldap.base}")
    private String ldapUBaseUser;  //  OU=USERS,OU=ACCOUNTS,DC=rg,DC=MYCOMPANY,DC=com

    /**
     * Context source.
     *
     * @return the ldap context source
     */
    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldapUrl);
        contextSource.setPassword(ldapAccessPassword);
        contextSource.setBase(ldapUBaseUser);
        return contextSource;
    }

    /**
     * Ldap template.
     *
     * @return the ldap template
     */
    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}

Ok, Here I have a big question... I create my connection with url (logic) with password(logic) ...... ¿¿ WHERE is my user ?? I put password but I never see in google put user, really ???

Finally my Impl:

@Autowired
private LdapTemplate ldapTemplate;

@Value("${ldap.base}")
private String base;    // WHY DO I REPEAT THIS VALUE ??? In my @configuration I especified the base

public boolean existUser(String usr, String pwd) {
try {
    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("mailNickname", usr));

    Boolean authenticate = ldapTemplate.authenticate(base, filter.encode(), pwd);
    boolean result = authenticate.booleanValue();
    if(!result) {
        LOGGER.info("The: " + usr + " , is failed.");
    }
    return result;
 } catch (Exception e) {
    LOGGER.error("Error existUser() --> " +e);
    e.printStackTrace();
    return false;
 }
}

Finally I call my method existUser() with user and password the front-End, I need know if this user/password exists in LDAP, but I get this error:

12-02-2020 09:03:27.821 [http-nio-80-exec-5] ERROR e.c.service.impl.LoginServiceImp.existUser -Error existUser() --> org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: e                                                 rror code 1 - 000004DC: LdapErr: DSID-0C0907C2, comment: In order to perform this operation a s                                                 uccessful bind must be completed on the connection., data 0, v2580]; remaining name 'OU=USERS,O                                                 U=ACCOUNTS,DC=rg,DC=MYCOMPANY,DC=com'
org.springframework.ldap.UncategorizedLdapException: Uncategorized exception occured during LDAP processing; nested exception is javax.naming.NamingException: [LDAP: error code 1 - 000004DC:LdapErr: DSID-0C0907C2, comment: In order to perform this operation a successful bind must be                                                  completed on the connection., data 0, v2580]; remaining name 'OU=USERS,OU=ACCOUNTS,DC=rg,DC=rep                                                 sol,DC=com'
        at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:228)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:397)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:309)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:642)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:578)
        at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1441)
        at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1426)
        at org.springframework.ldap.core.LdapTemplate.authenticate(LdapTemplate.java:1369)
        at es.MYPROJECT.service.impl.LoginServiceImp.existUser(LoginServiceImp.java:29)
        at es.MYPROJECT.controller.LoginController.login(LoginController.java:40)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43                                                 )
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHand                                                 lerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(Invoc                                                 ableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.                                                 invokeAndHandle(ServletInvocableHandlerMethod.java:97)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.i                                                 nvokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.h                                                 andleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(Abstr                                                 actHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:                                                 967)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:9                                                 01)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.jav                                                 a:970)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:317)
        at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(Exceptio                                                 nTranslationFilter.java:114)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionMan                                                 agementFilter.java:137)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilt                                                 er(AnonymousAuthenticationFilter.java:111)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.                                                 doFilter(SecurityContextHolderAwareRequestFilter.java:170)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(Reque                                                 stCacheAwareFilter.java:63)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutF                                                 ilter.java:116)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:96)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWr                                                 iterFilter.java:64)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(S                                                 ecurityContextPersistenceFilter.java:105)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFil                                                 ter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(Filter                                                 ChainProxy.java:331)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.                                                 java:214)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177                                                 )
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilter                                                 Proxy.java:347)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.                                                 java:263)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextF                                                 ilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutForm                                                 ContentFilter.java:108)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMet                                                 hodFilter.java:81)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEnc                                                 odingFilter.java:197)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.ja                                                 va:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterCh                                                 ain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java                                                 :166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:50                                                 4)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:7                                                 90)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
Caused by: javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C0907C2                                                 , comment: In order to perform this operation a successful bind must be completed on the connec                                                 tion., data 0, v2580]; remaining name 'OU=USERS,OU=ACCOUNTS,DC=rg,DC=MYCOMPANY,DC=com'
        at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3194)
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:3100)
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2891)
        at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1846)
        at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1769)
        at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:392)
        at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContex                                                 t.java:358)
        at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:276)
        at org.springframework.ldap.core.LdapTemplate$3.executeSearch(LdapTemplate.java:303)
        at org.springframework.ldap.core.LdapTemplate.search(LdapTemplate.java:363)
        ... 92 more

Thanks.


问:
How to collapse columns and overwrite values into a single row
I'm trying to collapse rows into a single line  (Last Name, First Name, ID) and at the same time, overwrite False with True any time there is a column/row that has True.  True is a system-generated flag and asks us to look more deeply into that record.

```<code>df = pd.DataFrame({'ID':[1, 1,2, 3,3],'LastName':['Cardinal','Cardinal', 'BlueJay', 'Robin','Robin'], 'FirstName':['Red', 'Red','Bluey', 'Round','Round'], 'French':[True, False,False,False, True], 'Flying':[False,True, True, True, False]})
</code>```

I don't know where to start. In this case, we can't use a split-apply-combine type of thinking, since we're replacing by column and row, simultaneously.  Group-by,update, combine_first is out.  Also, there are more than 100 columns...

Desired output:
df2 = pd.DataFrame({'ID':[1, 2, 3],'LastName':['Cardinal', 'BlueJay', 'Robin'], 'FirstName':['Red','Bluey','Round'], 'French':[True, False, True], 'Flying':[True, True, True]})

Thanks!

答:
Try any:

```<code>df.groupby(['ID','LastName','FirstName'], as_index=False).any()
</code>```

Output:

```<code>   ID  LastName FirstName  French  Flying
0   1  Cardinal       Red    True    True
1   2   BlueJay     Bluey   False    True
2   3     Robin     Round    True    True
</code>```

Body:
I'm trying to collapse rows into a single line  (Last Name, First Name, ID) and at the same time, overwrite False with True any time there is a column/row that has True.  True is a system-generated flag and asks us to look more deeply into that record.

df = pd.DataFrame({'ID':[1, 1,2, 3,3],'LastName':['Cardinal','Cardinal', 'BlueJay', 'Robin','Robin'], 'FirstName':['Red', 'Red','Bluey', 'Round','Round'], 'French':[True, False,False,False, True], 'Flying':[False,True, True, True, False]})

I don't know where to start. In this case, we can't use a split-apply-combine type of thinking, since we're replacing by column and row, simultaneously.  Group-by,update, combine_first is out.  Also, there are more than 100 columns...

Desired output:
df2 = pd.DataFrame({'ID':[1, 2, 3],'LastName':['Cardinal', 'BlueJay', 'Robin'], 'FirstName':['Red','Bluey','Round'], 'French':[True, False, True], 'Flying':[True, True, True]})

Thanks!

Body:
Try any:

df.groupby(['ID','LastName','FirstName'], as_index=False).any()

Output:

   ID  LastName FirstName  French  Flying
0   1  Cardinal       Red    True    True
1   2   BlueJay     Bluey   False    True
2   3     Robin     Round    True    True


问:
How indent this Objective-C code?
I have a simple question. How I indent a very long line. Let's use the traditional 80 caracters.
This is a line in my code:

```<code>    NSString *count = [[NSString alloc] initWithString: [sTemp substringFromIndex:[sTemp rangeOfString:@"count="].location + [sTemp rangeOfString:@"count="].length]];
</code>```

One solution was

```<code>    NSString *count = [[NSString alloc]                                 //line 1
                            initWithString: [sTemp substringFromIndex:
                                [sTemp rangeOfString:@"count="].location +
                                [sTemp rangeOfString:@"count="].length]];
</code>```

This is not the best sample, but the idea is:

Ok, the first line is the assignment and alloc thing.

The line 2 indent with a fell more right space. But, if the name of variable or type is very big, I will have the situation above. What I do?

```<code>NSStringWithVeryBigType *bigNameVariable = [NSStringWithVeryBigType alloc]
                  initWithString: [sTemp substringFromIndex:
</code>```

IN second line I create a new NSString. I can be confuse if the line 3 and 4 (in a bad situation, not this) is the main function creation, or is this new one. Have a good rule about it? And if it have a big name too, what to do again...

In other words, in a big assignment line, what rule I have to fallow?

答:
Don't try to squeeze it all into one line. Whenever you have weird nested calls like this, make one or more intermediate variables for readability:</p>

```<code>NSRange rng = [sTemp rangeOfString:@"count="];
NSUInteger indexAfterCount = rng.location + rng.length;
NSString * countSubString = [sTemp substringFromIndex:indexAfterCount];

NSStringSubclassWithReallyLongName * countString;
countString = [[NSStringSubclassWithReallyLongName alloc] initWithString:countSubString];
</code>```

Title: How indent this Objective-C code?

Body:
I have a simple question. How I indent a very long line. Let's use the traditional 80 caracters.
This is a line in my code:

    NSString *count = [[NSString alloc] initWithString: [sTemp substringFromIndex:[sTemp rangeOfString:@"count="].location + [sTemp rangeOfString:@"count="].length]];

One solution was

    NSString *count = [[NSString alloc]                                 //line 1
                            initWithString: [sTemp substringFromIndex:
                                [sTemp rangeOfString:@"count="].location +
                                [sTemp rangeOfString:@"count="].length]];

This is not the best sample, but the idea is:

Ok, the first line is the assignment and alloc thing.

The line 2 indent with a fell more right space. But, if the name of variable or type is very big, I will have the situation above. What I do?

NSStringWithVeryBigType *bigNameVariable = [NSStringWithVeryBigType alloc]
                  initWithString: [sTemp substringFromIndex:

IN second line I create a new NSString. I can be confuse if the line 3 and 4 (in a bad situation, not this) is the main function creation, or is this new one. Have a good rule about it? And if it have a big name too, what to do again...

In other words, in a big assignment line, what rule I have to fallow?

Body:
Don't try to squeeze it all into one line. Whenever you have weird nested calls like this, make one or more intermediate variables for readability:

NSRange rng = [sTemp rangeOfString:@"count="];
NSUInteger indexAfterCount = rng.location + rng.length;
NSString * countSubString = [sTemp substringFromIndex:indexAfterCount];

NSStringSubclassWithReallyLongName * countString;
countString = [[NSStringSubclassWithReallyLongName alloc] initWithString:countSubString];


答:
As the error says your usertask field of your Task model refers to a UserMembership, not a User object.

You can use .get_or_create() [Django-doc] to retrieve, or create such object if it does not yet exists. For example:

```<code>def myview(request):
    if request.method == 'POST':
        <b>usertask, __</b> = UserMembership.objects.get_or_create(
            user=request.user
        )
        title = request.POST['title']
        task = Task.objects.create(usertask=usertask, title=title)
    task = Task.objects.order_by('-date').filter(
        is_published=True,
        <b>usertask__user=request.user</b>
    )
    context={
        'task':task,
    }
    return render(request,'index.html',context)</code>```

You should filter on the usertask__user=request.user, since again, a usertask will retrieve a UserMembership object, not a User object.

I strongly advice to work with forms [Django-doc] and not try to process the request.POST querydictionary yourself. It is for example possible that the POST request does not contain any value for title, which can raise errors. A form will handle that more elegantly.

Title: Foreign key POST in Django

Body:
As the error says your usertask field of your Task model refers to a UserMembership, not a User object.

You can use .get_or_create() [Django-doc] to retrieve, or create such object if it does not yet exists. For example:

def myview(request):
    if request.method == 'POST':
        usertask, __ = UserMembership.objects.get_or_create(
            user=request.user
        )
        title = request.POST['title']
        task = Task.objects.create(usertask=usertask, title=title)
    task = Task.objects.order_by('-date').filter(
        is_published=True,
        usertask__user=request.user
    )
    context={
        'task':task,
    }
    return render(request,'index.html',context)

You should filter on the usertask__user=request.user, since again, a usertask will retrieve a UserMembership object, not a User object.

I strongly advice to work with forms [Django-doc] and not try to process the request.POST querydictionary yourself. It is for example possible that the POST request does not contain any value for title, which can raise errors. A form will handle that more elegantly.


问:
Create multiple sequences with different lengths (length.out)
Let's say I have a vector,

```<code>n <- c(1:100)
</code>```

and I want to output multiple sequences for each value 'n' takes in the vector above.

I tried doing something like this:

```<code>x <- seq (0,5, length.out = n+1)
x <- x[-1]
</code>```

I get the error:

Warning Message:
In seq.default(0,5, length.out = n+1)
First element used of length.out argument

I then want to use 'x' for a calculating in:

```<code>fx <- dnorm(x, mean = 0 , sd = 4)
</code>```

Where fx[1] will output the first value of fx and so on up to fx[n]

Body:
Let's say I have a vector,

n <- c(1:100)

and I want to output multiple sequences for each value 'n' takes in the vector above.

I tried doing something like this:

x <- seq (0,5, length.out = n+1)
x <- x[-1]

I get the error:

Warning Message:
In seq.default(0,5, length.out = n+1)
First element used of length.out argument

I then want to use 'x' for a calculating in:

fx <- dnorm(x, mean = 0 , sd = 4)

Where fx[1] will output the first value of fx and so on up to fx[n]

Body:
Maybe the following base R code can help

g <- Vectorize(function(k) seq (0,5, length.out = k+1)[-1])
x <- g(n)
fx <- sapply(x, dnorm, mean = 0,sd = 4)

such that

> head(x)
[[1]]
[1] 5

[[2]]
[1] 2.5 5.0

[[3]]
[1] 1.666667 3.333333 5.000000

[[4]]
[1] 1.25 2.50 3.75 5.00

[[5]]
[1] 1 2 3 4 5

[[6]]
[1] 0.8333333 1.6666667 2.5000000 3.3333333 4.1666667 5.0000000

and

> head(fx)
[[1]]
[1] 0.04566227

[[2]]
[1] 0.08204024 0.04566227

[[3]]
[1] 0.09144309 0.07047797 0.04566227

[[4]]
[1] 0.09498265 0.08204024 0.06426848 0.04566227

[[5]]
[1] 0.09666703 0.08801633 0.07528436 0.06049268 0.04566227

[[6]]
[1] 0.09759449 0.09144309 0.08204024 0.07047797 0.05797360 0.04566227


问:
Failed to resolve: com.squareup.retrofit2:retrofit:2.3.0
I tried to include retrofit library in android studio 2.2.3. I added the following line in gradle

```<code>compile 'com.squareup.retrofit2:retrofit:2.3.0'
</code>```

But it is giving me the following error :

```<code>Failed to resolve: com.squareup.retrofit2:retrofit:2.3.0
</code>```

What is the solution?

答: Change your version to a newer version ```implementation 'com.squareup.retrofit2:retrofit:2.4.0'```</p>

Body:
I tried to include retrofit library in android studio 2.2.3. I added the following line in gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'

But it is giving me the following error :

Failed to resolve: com.squareup.retrofit2:retrofit:2.3.0

What is the solution?

Body:
Change your version to a newer version
implementation 'com.squareup.retrofit2:retrofit:2.4.0'


答:
Your task model's usertask field related with UserMembership model as ForeignKey.So you must give a UserMembership object for create Task object. You gave request.user as usertask but request.user is'nt a UserMembership object.You must find UserMembership object before. You can use following code:</p>

```<code>user_member_ship = UserMemberShip.objects.get(user=request.user)
Task.objects.create(title=title,usertask=user_member_ship)
</code>```

Title: Foreign key POST in Django

Body:
Your task model's usertask field related with UserMembership model as ForeignKey.So you must give a UserMembership object for create Task object. You gave request.user as usertask but request.user is'nt a UserMembership object.You must find UserMembership object before. You can use following code:

user_member_ship = UserMemberShip.objects.get(user=request.user)
Task.objects.create(title=title,usertask=user_member_ship)