问:
Value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'UserAdmin', or an attribute on 'authentication.User'
I am trying to add following code to admin.py to make sure that user's password created from django admin will be hashed.

```<code>from django.contrib import admin
from .models import *

from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin

class UserAdmin(DjangoUserAdmin):
    pass

# Register your models here.
admin.site.register(User, UserAdmin)
</code>```

But when i try i got following:

<class 'authentication.admin.UserAdmin'>: (admin.E108) The value of
'list_display[2]' refers to 'first_name', which is not a callable, an
attribute of 'UserAdmin', or an attribute or method on
'authentication.User'.

The User model looks like this

```<code>class User(AbstractBaseUser, PermissionsMixin):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
username = models.CharField(max_length=255, unique=True, db_index=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)

is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

balance = models.FloatField(default=0.0)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

objects = UserManager()

def __str__(self):
    return self.email

def tokens(self):
    """" Метод получения токена """
    refresh = RefreshToken.for_user(self)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token)
    }

def has_delete_permission(self, *args, **kwargs):

    return True if self.is_staff is True else False
</code>```

答:
Though the question is old, I am answering the question so that it will help others. In the user model that extends the AbstractBaseUser, a method should be added with the name of the field to display in the class that extends admin.ModelAdminadmin as:

```<code>@admin.display(ordering='user__first_name')
    def first_name(self):
    return self.user.first_name
</code>```

Body:
I am trying to add following code to admin.py to make sure that user's password created from django admin will be hashed.

from django.contrib import admin
from .models import *

from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin

class UserAdmin(DjangoUserAdmin):
    pass

# Register your models here.
admin.site.register(User, UserAdmin)

But when i try i got following:

<class 'authentication.admin.UserAdmin'>: (admin.E108) The value of
'list_display[2]' refers to 'first_name', which is not a callable, an
attribute of 'UserAdmin', or an attribute or method on
'authentication.User'.

The User model looks like this

class User(AbstractBaseUser, PermissionsMixin):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
username = models.CharField(max_length=255, unique=True, db_index=True)
email = models.EmailField(max_length=255, unique=True, db_index=True)

is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

balance = models.FloatField(default=0.0)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

objects = UserManager()

def __str__(self):
    return self.email

def tokens(self):
    """" Метод получения токена """
    refresh = RefreshToken.for_user(self)
    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token)
    }

def has_delete_permission(self, *args, **kwargs):

    return True if self.is_staff is True else False

Body:
Though the question is old, I am answering the question so that it will help others. In the user model that extends the AbstractBaseUser, a method should be added with the name of the field to display in the class that extends admin.ModelAdminadmin as:

@admin.display(ordering='user__first_name')
    def first_name(self):
    return self.user.first_name


来源: stackexchange

问:
i use this code to edit and delete in django python but this message shows DoesNotExist at /Edit/1 or DoesNotExist at /Delete/1
i use this code to edit and delete in django python
but this message shows DoesNotExist at /Edit/1 or DoesNotExist at /Delete/1
the primary key is different to the studnumber

```<code>       def stedit(request, id):
        getsudentdetails= acc.objects.get(studnumber=id)
        return render(request, 'edit.html',{"acc":getsudentdetails})

       def stupdate(request,id):
        if request.method=='POST':
            stupdate= acc.objects.get(studnumber=id)
            form=stform(request.POST,instance=stupdate)
            if form.is_valid():
                form.save()
                messages.success(request, "The Student Record Is Updated Successfully..!")
            return render(request, "edit.html",{"acc":stupdate})

      def stdel(request,  id):
        delstudent= acc.objects.get(studnumber=id)
        delstudent.delete()
        results=acc.objects.all()
        return render (request, "Login.html",{"acc":results})
</code>```

Models.py

from django import forms
from django.db import models

```<code>class acc(models.Model):
        studnumber=models.IntegerField(unique=True)
        firstname=models.CharField(max_length=150)
        middlename=models.CharField(max_length=150)
        lastname=models.CharField(max_length=150)
        age=models.IntegerField()
        gender=models.CharField(max_length=1)
        uname=models.CharField(max_length=150,unique=True)
        email=models.CharField(max_length=150,unique=True)
        pwd=models.CharField(max_length=150)
        contact=models.CharField(max_length =11)

class Meta:
    unique_together = ('studnumber','email','uname')

class NewACCForm(forms.ModelForm):
    class Meta:
        model = acc
        fields = "__all__"
</code>```

答:
You can use ObjectDoesNotExist[Django-doc] as documented

The base class for Model.DoesNotExist exceptions. A try/except for ObjectDoesNotExist will catch DoesNotExist exceptions for all models.

```<code>from django.core.exceptions import ObjectDoesNotExist

def stedit(request, id):
    try:
        getsudentdetails= acc.objects.get(studnumber=id)
        return render(request, 'edit.html',{"acc":getsudentdetails})
    except ObjectDoesNotExist:
            #... do something if data not exists with provided studnumber value

def stupdate(request, id):
    if request.method=='POST':
        try:
            stupdate= acc.objects.get(studnumber=id)
            form=stform(request.POST,instance=stupdate)
            if form.is_valid():
                form.save()
                messages.success(request, "The Student Record Is Updated Successfully..!")
            return render(request, "edit.html",{"acc":stupdate})
        except ObjectDoesNotExist:
            #... do something if data not exists with provided studnumber value

def stdel(request, id):
    try:
        delstudent= acc.objects.get(studnumber=id)
        delstudent.delete()
        results=acc.objects.all()
        return render (request, "Login.html",{"acc":results})
    except ObjectDoesNotExist:
            #... do something if data not exists with provided studnumber value
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i use this code to edit and delete in django python
but this message shows DoesNotExist at /Edit/1 or DoesNotExist at /Delete/1
the primary key is different to the studnumber

       def stedit(request, id):
        getsudentdetails= acc.objects.get(studnumber=id)
        return render(request, 'edit.html',{"acc":getsudentdetails})

       def stupdate(request,id):
        if request.method=='POST':
            stupdate= acc.objects.get(studnumber=id)
            form=stform(request.POST,instance=stupdate)
            if form.is_valid():
                form.save()
                messages.success(request, "The Student Record Is Updated Successfully..!")
            return render(request, "edit.html",{"acc":stupdate})

      def stdel(request,  id):
        delstudent= acc.objects.get(studnumber=id)
        delstudent.delete()
        results=acc.objects.all()
        return render (request, "Login.html",{"acc":results})

Models.py

from django import forms
from django.db import models

class acc(models.Model):
        studnumber=models.IntegerField(unique=True)
        firstname=models.CharField(max_length=150)
        middlename=models.CharField(max_length=150)
        lastname=models.CharField(max_length=150)
        age=models.IntegerField()
        gender=models.CharField(max_length=1)
        uname=models.CharField(max_length=150,unique=True)
        email=models.CharField(max_length=150,unique=True)
        pwd=models.CharField(max_length=150)
        contact=models.CharField(max_length =11)

class Meta:
    unique_together = ('studnumber','email','uname')

class NewACCForm(forms.ModelForm):
    class Meta:
        model = acc
        fields = "__all__"

Body:
You can use ObjectDoesNotExist[Django-doc] as documented

The base class for Model.DoesNotExist exceptions. A try/except for ObjectDoesNotExist will catch DoesNotExist exceptions for all models.

from django.core.exceptions import ObjectDoesNotExist

def stedit(request, id):
    try:
        getsudentdetails= acc.objects.get(studnumber=id)
        return render(request, 'edit.html',{"acc":getsudentdetails})
    except ObjectDoesNotExist:
            #... do something if data not exists with provided studnumber value

def stupdate(request, id):
    if request.method=='POST':
        try:
            stupdate= acc.objects.get(studnumber=id)
            form=stform(request.POST,instance=stupdate)
            if form.is_valid():
                form.save()
                messages.success(request, "The Student Record Is Updated Successfully..!")
            return render(request, "edit.html",{"acc":stupdate})
        except ObjectDoesNotExist:
            #... do something if data not exists with provided studnumber value

def stdel(request, id):
    try:
        delstudent= acc.objects.get(studnumber=id)
        delstudent.delete()
        results=acc.objects.all()
        return render (request, "Login.html",{"acc":results})
    except ObjectDoesNotExist:
            #... do something if data not exists with provided studnumber value


问:
Pandas explode list of dictionaries into rows
Have this:

```<code>                                  items, name
0   { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this }
1   { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that }
</code>```

But would like to have the list of dictionary objects exploded into (flattened?) into actual rows like this:

```<code>    a, b, name
0   { 2, 1, this}
1   { 4, 3, this}
0   { 2, 1, that}
1   { 4, 3, that}
</code>```

Having been trying to use melt but with no luck, any ideas? suggestions?

Data to produce DataFrame:

```<code>data = {'items': [[{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}]], 'name': ['this', 'that']}
</code>```

答:
Another solution is to set_index with "name" and explode "items". Then cast the resulting Series to a DataFrame.

```<code>s = df.set_index('name')['items'].explode()
out = pd.DataFrame(s.tolist(), index=s.index).reset_index()
</code>```

Output:

```<code>   name  a  b
0  this  2  1
1  this  4  3
2  that  2  1
3  that  4  3
</code>```

It appears, set_index + explode + DataFrame is faster (at least for OP's data) than all the other options given in the other answers.

```<code>%timeit -n 1000 out = pd.concat(df['items'].apply(pd.DataFrame).tolist(), keys=df["name"]).reset_index()
%timeit -n 1000 ab = pd.DataFrame.from_dict(np.concatenate(df['items']).tolist()); lens = df['items'].str.len(); rest = df.drop('items', axis=1).iloc[df.index.repeat(lens)].reset_index(drop=True); out = ab.join(rest)
%timeit -n 1000 out = pd.concat([pd.DataFrame(df1.iloc[0]) for x,df1 in df.groupby('name')['items']],keys=df.name).reset_index().drop('level_1',axis=1)
%timeit -n 1000 s = df.set_index('name')['items'].explode(); out = pd.DataFrame(s.tolist(), index=s.index).reset_index()
</code>```
```<code>2.5 ms ± 29.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.75 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
3.82 ms ± 433 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.46 ms ± 68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Body:
Have this:

                                  items, name
0   { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], this }
1   { [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], that }

But would like to have the list of dictionary objects exploded into (flattened?) into actual rows like this:

    a, b, name
0   { 2, 1, this}
1   { 4, 3, this}
0   { 2, 1, that}
1   { 4, 3, that}

Having been trying to use melt but with no luck, any ideas? suggestions?

Data to produce DataFrame:

data = {'items': [[{'a': 2, 'b': 1}, {'a': 4, 'b': 3}], [{'a': 2, 'b': 1}, {'a': 4, 'b': 3}]], 'name': ['this', 'that']}

Body:
Another solution is to set_index with "name" and explode "items". Then cast the resulting Series to a DataFrame.

s = df.set_index('name')['items'].explode()
out = pd.DataFrame(s.tolist(), index=s.index).reset_index()

Output:

   name  a  b
0  this  2  1
1  this  4  3
2  that  2  1
3  that  4  3

It appears, set_index + explode + DataFrame is faster (at least for OP's data) than all the other options given in the other answers.

%timeit -n 1000 out = pd.concat(df['items'].apply(pd.DataFrame).tolist(), keys=df["name"]).reset_index()
%timeit -n 1000 ab = pd.DataFrame.from_dict(np.concatenate(df['items']).tolist()); lens = df['items'].str.len(); rest = df.drop('items', axis=1).iloc[df.index.repeat(lens)].reset_index(drop=True); out = ab.join(rest)
%timeit -n 1000 out = pd.concat([pd.DataFrame(df1.iloc[0]) for x,df1 in df.groupby('name')['items']],keys=df.name).reset_index().drop('level_1',axis=1)
%timeit -n 1000 s = df.set_index('name')['items'].explode(); out = pd.DataFrame(s.tolist(), index=s.index).reset_index()

2.5 ms ± 29.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.75 ms ± 12.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
3.82 ms ± 433 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.46 ms ± 68 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
How to fix position image on another image
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkoutWrapper">
  <img src="https://via.placeholder.com/300" class="coverIMGLast" />
  <img src="https://via.placeholder.com/300/ff0000" class="phone" />

  <div class="CheckoutProcess">
    <Content />
  </div>
</div></code>```

答:
You can make the first image as background image, then specify the background-size whichever size you want. Then add the second image inside the
 element.

#bg-img{
  background-image:url('https://images.pexels.com/photos/36029/aroni-arsa-children-little.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500');
  position: absolute;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 50% 100%;
  background-color: #999;
}
#img-inside{
  position:absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width:15%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg-img">
  <img id="img-inside" src="https://images.pexels.com/photos/36029/aroni-arsa-children-little.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="second-img" />
</div></code>```

I just made the left div in the snippet

Body:
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/

    <Content />

Body:
You can make the first image as background image, then specify the background-size whichever size you want. Then add the second image inside the <div> element.

#bg-img{
  background-image:url('https://images.pexels.com/photos/36029/aroni-arsa-children-little.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500');
  position: absolute;
  width: 100%;
  height: 100%;
  background-repeat: no-repeat;
  background-size: 50% 100%;
  background-color: #999;
}
#img-inside{
  position:absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width:15%;
}

<div id="bg-img">
  <img id="img-inside" src="https://images.pexels.com/photos/36029/aroni-arsa-children-little.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="second-img" />
</div>

I just made the left div in the snippet


问:
Memory allocation in c problem
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

```<code>#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}
</code>```

Warning message:

```<code>|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|
</code>```

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

答:
Look up how realloc works - you have to pass it the original pointer:

```<code>int * tmp = realloc(arr, 8 * sizeof(int));
if (tmp)
{
  arr = tmp;
}
else // Error!
</code>```

ContentLicense: CC BY-SA 3.0

Title: Memory allocation in c problem

Body:
I'm nearing the end of an introductory book on c programming called "C programming in easy steps" by Mike McGrath. I think I'll have a lot more to learn after this book by the looks of things though. Anyways, I'm working with memory allocation and I wrote this demo program, but it errors closed when I try to run it:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, *arr;

    arr = calloc(5, sizeof(int));
    if(arr!=NULL)
    {
        printf("Enter 5 integers, seperated by a space:");
        for(i=0; i<5; i++) scanf("%d", &arr[i]);
        printf("Adding more space...\n");
        arr = realloc(8, sizeof(int));
        printf("Enter 3 more integers seperated by a space:");
        for(i=5; i<8; i++) scanf("%d", &arr[i]);
        printf("Thanks.\nYour 8 entries were: ");
        for(i=0; i<8; i++) printf("%d, ", arr[i]);
        printf("\n");
        free(arr);
        return 0;
        }
    else {printf("!!! INSUFFICIENT MEMORY !!!\n"); return 1; }
}

Warning message:

|13|warning: passing argument 1 of 'realloc' makes pointer from integer without a cast|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\..\..\..\..\include\stdlib.h|365|note: expected 'void *' but argument is of type 'int'|
||=== Build finished: 0 errors, 1 warnings ===|

The resulting compilation asks for 5 integers and prints "Adding more space..." at which point the program terminates, instead of asking for the additional three integers and printing the input.

Any help would be nice. :) Thanks!

Body:
Look up how realloc works - you have to pass it the original pointer:

int * tmp = realloc(arr, 8 * sizeof(int));
if (tmp)
{
  arr = tmp;
}
else // Error!


问:
Flurl \ RestSharp: `\r\n` is added to each parameter of the Multipart request
I'm trying to write a call to the Freshdesk API using either Flurl or RestSharp library.

The API call I'm trying to write is Creating a Ticket: https://developers.freshdesk.com/api/#create_ticket

An example of cURL:

curl -v -u yourapikey:X -F "attachments[]=@/path/to/attachment1.ext" -F "attachments[]=@/path/to/attachment2.ext" -F "email=example@example.com" -F "subject=Ticket Title" -F "description=this is a sample ticket" -X POST 'https://domain.freshdesk.com/api/v2/tickets'

Note params are passed by -F (i.e. --form) flag.

With the following code calling Flurl:

var rs = await url.WithBasicAuth(_configuration.ApiKey, _configuration.Password)
                  .PostMultipartAsync(mp =>
                  {
                      mp.AddString("email", ticket.Email);
                      mp.AddString("subject", ticket.Subject);
                      mp.AddString("status", ticket.Status.ToString());
                      mp.AddString("priority", ticket.Priority.ToString());
                      mp.AddString("description", ticket.Description);
                  });
```
<p>...Or the following code calling RestSharp:</p>
<pre class="lang-cs prettyprint-override"><code>var request = new RestRequest("tickets", Method.Post);
request.AlwaysMultipartFormData = true;
request.AddParameter("email", ticket.Email);
request.AddParameter("description", ticket.Description);
request.AddParameter("subject", ticket.Subject);
request.AddParameter("status", ticket.Status);
request.AddParameter("priority", ticket.Priority);

var rs = await client.ExecuteAsync(request);
</code>```

...I'm receiving 400 BadRequest with the following information (in both cases):

{
    "description": "Validation failed",
    "errors": [
        {
            "code": "invalid_field",
            "field": "email\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "subject\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "status\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "priority\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "description\r\n",
            "message": "Unexpected/invalid field in request"
        }
    ]
}
```
<p>Note that:</p>
<ul>
<li>Freshdesk API uses <code>-F</code> / <code>--form</code> as a way to pass parameters.</li>
<li>I want to use Multipart for handling attachments later on.</li>
<li>All data has proper values. If it wouldn't have a proper value, a validation error would come as a response.</li>
<li>When sending the same values in Postman (via form-data), I'm receiving 201 Created.</li>
</ul>
<h1>Update 1</h1>
<p>Postman screenshot (working example):</p>
<p><img src="https://i.stack.imgur.com/2mOl4.png" alt="enter image description here" /></p>
<h1>Update 2</h1>
<p>I tried to use Tiny.RestClient which has cURL listener and it came with the following cURL generated:</p>
```curl -X POST [...] -d "--1c3acb07-77bd-494d-bc56-21290dcd5088
Content-Type: text/plain
Content-Disposition: form-data; name=email

a@a.com
[...]
```

Perhaps, Flurl and RestSharp uses the same way to proceed with parameters and thus, the \r\n in fields.

答:
It's the FreshDesk API issue. They want, for some reason, for multipart form-data parameter names to be enclosed in quotation marks. It's not a requirement per HTTP standards. RestSharp and Flurl use MultipartFormDataContent, and it  adds uses parameter names as provided.

Following up on your issue, I added this property to RestRequest:

```<code>/// <summary>
/// When set to true, parameters in a multipart form data requests will be enclosed in
/// quotation marks. Default is false. Enable it if the remote endpoint requires parameters
/// to be in quotes (for example, FreshDesk API).
/// </summary>
public bool MultipartFormQuoteParameters { get; set; }
</code>```

It is available in RS 107.3.0.

You can also make it work by adding parameters like this:

```<code>request.AddParameter("\"status\"", ticket.Status);
</code>```

Body:
I'm trying to write a call to the Freshdesk API using either Flurl or RestSharp library.

The API call I'm trying to write is Creating a Ticket: https://developers.freshdesk.com/api/#create_ticket

An example of cURL:

curl -v -u yourapikey:X -F "attachments[]=@/path/to/attachment1.ext" -F "attachments[]=@/path/to/attachment2.ext" -F "email=example@example.com" -F "subject=Ticket Title" -F "description=this is a sample ticket" -X POST 'https://domain.freshdesk.com/api/v2/tickets'

Note params are passed by -F (i.e. --form) flag.

With the following code calling Flurl:

var rs = await url.WithBasicAuth(_configuration.ApiKey, _configuration.Password)
                  .PostMultipartAsync(mp =>
                  {
                      mp.AddString("email", ticket.Email);
                      mp.AddString("subject", ticket.Subject);
                      mp.AddString("status", ticket.Status.ToString());
                      mp.AddString("priority", ticket.Priority.ToString());
                      mp.AddString("description", ticket.Description);
                  });

...Or the following code calling RestSharp:

var request = new RestRequest("tickets", Method.Post);
request.AlwaysMultipartFormData = true;
request.AddParameter("email", ticket.Email);
request.AddParameter("description", ticket.Description);
request.AddParameter("subject", ticket.Subject);
request.AddParameter("status", ticket.Status);
request.AddParameter("priority", ticket.Priority);

var rs = await client.ExecuteAsync(request);

...I'm receiving 400 BadRequest with the following information (in both cases):

{
    "description": "Validation failed",
    "errors": [
        {
            "code": "invalid_field",
            "field": "email\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "subject\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "status\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "priority\r\n",
            "message": "Unexpected/invalid field in request"
        },
        {
            "code": "invalid_field",
            "field": "description\r\n",
            "message": "Unexpected/invalid field in request"
        }
    ]
}

Note that:

Freshdesk API uses -F / --form as a way to pass parameters.

I want to use Multipart for handling attachments later on.

All data has proper values. If it wouldn't have a proper value, a validation error would come as a response.

When sending the same values in Postman (via form-data), I'm receiving 201 Created.

Update 1

Postman screenshot (working example):

Update 2

I tried to use Tiny.RestClient which has cURL listener and it came with the following cURL generated:

curl -X POST [...] -d "--1c3acb07-77bd-494d-bc56-21290dcd5088
Content-Type: text/plain
Content-Disposition: form-data; name=email

a@a.com
[...]

Perhaps, Flurl and RestSharp uses the same way to proceed with parameters and thus, the \r\n in fields.

Body:
It's the FreshDesk API issue. They want, for some reason, for multipart form-data parameter names to be enclosed in quotation marks. It's not a requirement per HTTP standards. RestSharp and Flurl use MultipartFormDataContent, and it  adds uses parameter names as provided.

Following up on your issue, I added this property to RestRequest:

/// <summary>
/// When set to true, parameters in a multipart form data requests will be enclosed in
/// quotation marks. Default is false. Enable it if the remote endpoint requires parameters
/// to be in quotes (for example, FreshDesk API).
/// </summary>
public bool MultipartFormQuoteParameters { get; set; }

It is available in RS 107.3.0.

You can also make it work by adding parameters like this:

request.AddParameter("\"status\"", ticket.Status);


问:
TypeError: sequelize.define is not a function
I'm building a project that uses SQL for the database, node,express and sequelize for the backend.

I'm trying to use sequelize for my project and am running into an "TypeError: sequelize.define is not a function".

I'm not exactly sure what the problem is, I've looked at other posts and made various changes with no luck.

The first error starts at the define.

Error:

```<code>userModel.js:4
  const User = sequelize.define('user', {
</code>```

My dbConfig.js file

```<code>module.exports = {
  HOST: 'localhost',
  USER: 'placeholder',
  PASSWORD: 'placeholder',
  DB: 'placeholder',
  dialect: 'mysql',

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
}
</code>```

My index.js inside my models folder

```<code>const dbConfig = require('../config/dbConfig.js')

const { Sequelize, DataTypes } = require('sequelize')

const sequelize = new Sequelize(
  dbConfig.DB,
  dbConfig.USER,
  dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    pool: {
      max: dbConfig.pool.max,
      min: dbConfig.pool.min,
      acquire: dbConfig.pool.acquire,
      idle: dbConfig.pool.idle
    }
  }
)

sequelize.authenticate()
  .then(() => {
    console.log('Connected...')
  })
  .catch(err => {
    console.log(`Error ${err}`)
  })

const db = {}

db.Sequelize = Sequelize
db.sequelize = sequelize

// ----- Put tables models here -----
// This maps the tables to object
db.users = require('./userModel.js')(Sequelize, DataTypes)

// ----- IMPORTANT -----
// If force = true, everytime the server runs we will lose the data for the table
// force = true recreates a table
db.sequelize.sync({ force: false })
  .then(() => {
    console.log('Re-sync done')
  })

module.exports = db
</code>```

My userModel.js file

```<code>// DataTypes Documentation - https://sequelize.org/master/variable/index.html#static-variable-DataTypes

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('user', {
    userID: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    userName: {
      type: DataTypes.STRING
    },
    password: {
      type: DataTypes.STRING
    },
    firstName: {
      type: DataTypes.STRING
    },
    lastName: {
      type: DataTypes.STRING
    },
    phoneNumber: {
      type: DataTypes.STRING
    },
    emergencyContact: {
      type: DataTypes.STRING
    },
    verified: {
      type: DataTypes.BOOLEAN
    }
  })

  return User
}
</code>```

My app.js file where the server starts

```<code>const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan') // shows which device or browser access
const PORT = process.env.PORT || 8081

const app = express() // builds express server for API.

// Middle Ware
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan('combined'))
app.use(bodyParser.json()) // allows app to easily parse JSON request.
app.use(cors()) // to allow any host or client to access the server.

// ----- Routers -----
const router = require('../routes/userRouter.js')
app.use('/api/users', router)

app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`)
})
</code>```

答:
You should call define on Sequelize instance and not on Sequelize itself:

db.users = require('./userModel.js')(sequelize, DataTypes)
```

Also please look at another my answer to better understand how to register models and their associations

Body:
I'm building a project that uses SQL for the database, node,express and sequelize for the backend.

I'm trying to use sequelize for my project and am running into an "TypeError: sequelize.define is not a function".

I'm not exactly sure what the problem is, I've looked at other posts and made various changes with no luck.

The first error starts at the define.

Error:

userModel.js:4
  const User = sequelize.define('user', {

My dbConfig.js file

module.exports = {
  HOST: 'localhost',
  USER: 'placeholder',
  PASSWORD: 'placeholder',
  DB: 'placeholder',
  dialect: 'mysql',

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
}

My index.js inside my models folder

const dbConfig = require('../config/dbConfig.js')

const { Sequelize, DataTypes } = require('sequelize')

const sequelize = new Sequelize(
  dbConfig.DB,
  dbConfig.USER,
  dbConfig.PASSWORD, {
    host: dbConfig.HOST,
    dialect: dbConfig.dialect,
    operatorsAliases: false,

    pool: {
      max: dbConfig.pool.max,
      min: dbConfig.pool.min,
      acquire: dbConfig.pool.acquire,
      idle: dbConfig.pool.idle
    }
  }
)

sequelize.authenticate()
  .then(() => {
    console.log('Connected...')
  })
  .catch(err => {
    console.log(`Error ${err}`)
  })

const db = {}

db.Sequelize = Sequelize
db.sequelize = sequelize

// ----- Put tables models here -----
// This maps the tables to object
db.users = require('./userModel.js')(Sequelize, DataTypes)

// ----- IMPORTANT -----
// If force = true, everytime the server runs we will lose the data for the table
// force = true recreates a table
db.sequelize.sync({ force: false })
  .then(() => {
    console.log('Re-sync done')
  })

module.exports = db

My userModel.js file

// DataTypes Documentation - https://sequelize.org/master/variable/index.html#static-variable-DataTypes

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('user', {
    userID: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    userName: {
      type: DataTypes.STRING
    },
    password: {
      type: DataTypes.STRING
    },
    firstName: {
      type: DataTypes.STRING
    },
    lastName: {
      type: DataTypes.STRING
    },
    phoneNumber: {
      type: DataTypes.STRING
    },
    emergencyContact: {
      type: DataTypes.STRING
    },
    verified: {
      type: DataTypes.BOOLEAN
    }
  })

  return User
}

My app.js file where the server starts

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan') // shows which device or browser access
const PORT = process.env.PORT || 8081

const app = express() // builds express server for API.

// Middle Ware
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(morgan('combined'))
app.use(bodyParser.json()) // allows app to easily parse JSON request.
app.use(cors()) // to allow any host or client to access the server.

// ----- Routers -----
const router = require('../routes/userRouter.js')
app.use('/api/users', router)

app.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`)
})

Body:
You should call define on Sequelize instance and not on Sequelize itself:

db.users = require('./userModel.js')(sequelize, DataTypes)

Also please look at another my answer to better understand how to register models and their associations


问:
c# how to use xml.SelectSingleNode method
I'm using c# .NET 4.8 and I'm trying to extract a value from an XML document. Here is a sample of the document I'm using:

```<code><SOME_GROUP SomeValue="2">
    <SOME_PLACEHOLDER SOMEDateTime="2022-02-10T14:50:48-08">
        <SOME_DATA>
            <MAIN_SOME SomeValue="2" MAINSOMEID="MAINSOME1">
                <TARGET_FIELD MAINFIELDID="MAIN111" SomeID="somedata" _Value="someValue">
                    <_SUB_FIELD _Code="038" _Text="some other data"></_SUB_FIELD>
                </TARGET_FIELD>
            </MAIN_SOME>
        </SOME_DATA>
    </SOME_PLACEHOLDER>
</SOME_GROUP>
</code>```

I want to get the _Value from TARGET_FIELD and store it in a variable. Right now I can do this using the method SelectNodes() like this:

```<code>using System.Xml;

XmlDocument someXmlDocument = new XmlDocument();
someXmlDocument.LoadXml(someXmlFile);

var myValue = someXmlDocument.SelectNodes("/SOME_GROUP/SOME_PLACEHOLDER/SOME_DATA/MAIN_SOME/TARGET_FIELD")
    .Cast<XmlNode>()
    .Select(x => x.Attributes["_Value"].Value).ToList();
</code>```

and I get my value someValue in the first element of the list myValue. It seems like because there is only one node I'm getting this value from I should use the SelectSingleNode() method instead.

If I try this:

```<code>var myValue = someXmlDocument.SelectSingleNode("/SOME_GROUP/SOME_PLACEHOLDER/SOME_DATA/MAIN_SOME/TARGET_FIELD")
    .Cast<XmlNode>()
    .Select(x => x.Attributes["_Value"].Value);
</code>```

the code runs but I don't get anything stored in myValue as I expect.

If I leave off the ToList() in an attempt to store the value in myValue as just a string like this:

```<code>var myValue = someXmlDocument.SelectNodes("/SOME_GROUP/SOME_PLACEHOLDER/SOME_DATA/MAIN_SOME/TARGET_FIELD")
    .Cast<XmlNode>()
    .Select(x => x.Attributes["_Value"].Value);
</code>```

then I get a null reference exception like this:

System.NullReferenceException: 'Object reference not set to an
instance of an object.'

Sorry if this is a stupid question, I'm just getting back into c# development. Can anyone tell me what I'm doing wrong when trying to use SelectSingleNode() or if that is even something I should be trying to use in this case?

As always, a correct, clearly explained answer will be marked as accepted and upvoted.

Thanks.

答:
Try this ...

```<code>public static void DoSelectSingleNode()
{
    var xml = "<SOME_GROUP SomeValue=\"2\"><SOME_PLACEHOLDER SOMEDateTime=\"2022-02-10T14:50:48-08\"><SOME_DATA><MAIN_SOME SomeValue=\"2\" MAINSOMEID=\"MAINSOME1\"><TARGET_FIELD MAINFIELDID=\"MAIN111\" SomeID=\"somedata\" _Value=\"someValue\"><_SUB_FIELD _Code=\"038\" _Text=\"some other data\"></_SUB_FIELD></TARGET_FIELD></MAIN_SOME></SOME_DATA></SOME_PLACEHOLDER></SOME_GROUP>";

    var xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(xml);

    var value = xmlDocument.DocumentElement.SelectSingleNode("//TARGET_FIELD").Attributes["_Value"].InnerText;

    Console.WriteLine(value);
}
</code>```

... naturally, if there are more than one TARGET_FIELD then you'll only pull back one.

I find this to be a good resource when it comes to using XPath for node selections ... https://devhints.io/xpath

Body:
I'm using c# .NET 4.8 and I'm trying to extract a value from an XML document. Here is a sample of the document I'm using:

<SOME_GROUP SomeValue="2">
    <SOME_PLACEHOLDER SOMEDateTime="2022-02-10T14:50:48-08">
        <SOME_DATA>
            <MAIN_SOME SomeValue="2" MAINSOMEID="MAINSOME1">
                <TARGET_FIELD MAINFIELDID="MAIN111" SomeID="somedata" _Value="someValue">
                    <_SUB_FIELD _Code="038" _Text="some other data"></_SUB_FIELD>
                </TARGET_FIELD>
            </MAIN_SOME>
        </SOME_DATA>
    </SOME_PLACEHOLDER>
</SOME_GROUP>

I want to get the _Value from TARGET_FIELD and store it in a variable. Right now I can do this using the method SelectNodes() like this:

using System.Xml;

XmlDocument someXmlDocument = new XmlDocument();
someXmlDocument.LoadXml(someXmlFile);

var myValue = someXmlDocument.SelectNodes("/SOME_GROUP/SOME_PLACEHOLDER/SOME_DATA/MAIN_SOME/TARGET_FIELD")
    .Cast<XmlNode>()
    .Select(x => x.Attributes["_Value"].Value).ToList();

and I get my value someValue in the first element of the list myValue. It seems like because there is only one node I'm getting this value from I should use the SelectSingleNode() method instead.

If I try this:

var myValue = someXmlDocument.SelectSingleNode("/SOME_GROUP/SOME_PLACEHOLDER/SOME_DATA/MAIN_SOME/TARGET_FIELD")
    .Cast<XmlNode>()
    .Select(x => x.Attributes["_Value"].Value);

the code runs but I don't get anything stored in myValue as I expect.

If I leave off the ToList() in an attempt to store the value in myValue as just a string like this:

var myValue = someXmlDocument.SelectNodes("/SOME_GROUP/SOME_PLACEHOLDER/SOME_DATA/MAIN_SOME/TARGET_FIELD")
    .Cast<XmlNode>()
    .Select(x => x.Attributes["_Value"].Value);

then I get a null reference exception like this:

System.NullReferenceException: 'Object reference not set to an
instance of an object.'

Sorry if this is a stupid question, I'm just getting back into c# development. Can anyone tell me what I'm doing wrong when trying to use SelectSingleNode() or if that is even something I should be trying to use in this case?

As always, a correct, clearly explained answer will be marked as accepted and upvoted.

Thanks.

Body:
Try this ...

public static void DoSelectSingleNode()
{
    var xml = "<SOME_GROUP SomeValue=\"2\"><SOME_PLACEHOLDER SOMEDateTime=\"2022-02-10T14:50:48-08\"><SOME_DATA><MAIN_SOME SomeValue=\"2\" MAINSOMEID=\"MAINSOME1\"><TARGET_FIELD MAINFIELDID=\"MAIN111\" SomeID=\"somedata\" _Value=\"someValue\"><_SUB_FIELD _Code=\"038\" _Text=\"some other data\"></_SUB_FIELD></TARGET_FIELD></MAIN_SOME></SOME_DATA></SOME_PLACEHOLDER></SOME_GROUP>";

    var xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(xml);

    var value = xmlDocument.DocumentElement.SelectSingleNode("//TARGET_FIELD").Attributes["_Value"].InnerText;

    Console.WriteLine(value);
}

... naturally, if there are more than one TARGET_FIELD then you'll only pull back one.

I find this to be a good resource when it comes to using XPath for node selections ... https://devhints.io/xpath


问:
Button hover does not work after I change button color using JS
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}</code>```

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>```

After I click the button event occurs and the color changes to dark blue and the hover do not work.

答:
button click adds inline styles which have higher priority due to that hover property changes are ignored. You can add !important to get rid of the issue

```<code>.button1:hover {
     background-color: red !important;
     color: black !important;
     border: 2px solid #4caf50;
}
</code>```

Hoverable Buttons

    <button
      id="buttonGreen"
      class="button button1"
      onclick="setColor('buttonGreen', '#122256')"
      ;
    >
      Green
    </button>

```

Body:
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}

.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>

After I click the button event occurs and the color changes to dark blue and the hover do not work.

Body:
button click adds inline styles which have higher priority due to that hover property changes are ignored. You can add !important to get rid of the issue

.button1:hover {
     background-color: red !important;
     color: black !important;
     border: 2px solid #4caf50;
}

<html>
  <head>
    <style>
      .button {
        background-color: #4caf50; /* Green */
        border: none;
        color: white;
        padding: 16px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        transition-duration: 0.4s;
        cursor: pointer;
      }

      .button1 {
        background-color: white;
        color: black;
        border: 2px solid #4caf50;
      }

      .button1:hover {
        background-color: red !important;
        color: black !important;
        border: 2px solid #4caf50;
      }
    </style>

    <script>
      var count = 1;
      function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
          property.style.backgroundColor = "white";
          count = 1;
        } else {
          property.style.backgroundColor = color;
          count = 0;
        }
      }
    </script>
  </head>

  <body>
    <h2>Hoverable Buttons</h2>
    <button
      id="buttonGreen"
      class="button button1"
      onclick="setColor('buttonGreen', '#122256')"
      ;
    >
      Green
    </button>
  </body>
</html>


问:
Image file input with Formtastic and ActiveAdmin
I started using formstatic but I need to make a file field with an image preview. I mean, when I edit an object, I want to see the image already linked.

How can I do that?

答:
The answer is to use the hint attribute :

```<code>ActiveAdmin.register Event do
  form :html => { :enctype => "multipart/form-data" } do |f|
    f.input :map, :as => :file, :hint => f.template.image_tag(f.object.map.url(:thumb))
  end
end
</code>```

Bye

Body:
The answer is to use the hint attribute :

ActiveAdmin.register Event do
  form :html => { :enctype => "multipart/form-data" } do |f|
    f.input :map, :as => :file, :hint => f.template.image_tag(f.object.map.url(:thumb))
  end
end

Bye


问:
How to stop form submission?
I'm new to JavaScript. I need to prevent the form from submitting if any of the validation conditions returned false.

ex:-

```<code>if((document.getElementById("name").value)==""){
    alert("'Name' field can not be empty");
    return false;
}
</code>```

I tried <form onsubmit="return validate();"> and <form onsubmit="event.preventDefault(); validate();">. None of those helped. First one prompt the same alert message twice. Second one continuously prompt all alert messages. What I want is,

If there is one false condition, I need the browser to stop the form from submitting and prompt the relevant alert message.

If there are more than one false conditions, I need the browser to stop the form from submitting and only prompt one alert message.

Is there any way to accomplish this by using JavaScript (No JavaScript libraries)?

Sorry if there are any grammar mistakes, English is not my first language :(

答:
You need to call preventDefault of the event object that comes as a parameter you get from the callback function of the EventListener. Like that:

```<code>...
<head>
<script>
window.addEventListener("load",init);
function init()
  {document.getElementById("form").addEventListener("submit",function(e)
     {e.preventDefault();});}
</script>
</head>
<body>
<form id="form">
  <input type="submit">
</form>
</body>
...
</code>```

You can call that parameter anything, and you can also define that function somewhere else.

```<code>...
<script>
window.addEventListener("load",init);
function init()
  {document.getElementById("form").addEventListener("submit",handleSubmit);}
function handleSubmit(event)
  {event.preventDefault();}
</script>
...
</code>```

Title: How to stop form submission?

Body:
I'm new to JavaScript. I need to prevent the form from submitting if any of the validation conditions returned false.

ex:-

if((document.getElementById("name").value)==""){
    alert("'Name' field can not be empty");
    return false;
}

I tried <form onsubmit="return validate();"> and <form onsubmit="event.preventDefault(); validate();">. None of those helped. First one prompt the same alert message twice. Second one continuously prompt all alert messages. What I want is,

If there is one false condition, I need the browser to stop the form from submitting and prompt the relevant alert message.

If there are more than one false conditions, I need the browser to stop the form from submitting and only prompt one alert message.

Is there any way to accomplish this by using JavaScript (No JavaScript libraries)?

Sorry if there are any grammar mistakes, English is not my first language :(

Body:
You need to call preventDefault of the event object that comes as a parameter you get from the callback function of the EventListener. Like that:

...
<head>
<script>
window.addEventListener("load",init);
function init()
  {document.getElementById("form").addEventListener("submit",function(e)
     {e.preventDefault();});}
</script>
</head>
<body>
<form id="form">
  <input type="submit">
</form>
</body>
...

You can call that parameter anything, and you can also define that function somewhere else.

...
<script>
window.addEventListener("load",init);
function init()
  {document.getElementById("form").addEventListener("submit",handleSubmit);}
function handleSubmit(event)
  {event.preventDefault();}
</script>
...


问:
Use element to style inside

The emb is not a class but an element. Can I use this element to style the div or, the only way to do it is making emb a class such as .emb?

  Hello

```

答:
You need to use emb as a class or id for styling your div tag and you can also use a separate css file.

```<code><div class="emb">
Hello
</div>

<style>

    .emb {
   font-weight: 500;
   font-style: italic;
   background: transparent;
   font-size: 18px
    }

</style>
</code>```

Here you can also use in-line css also.

```<code><div style="font-weight: 500;
       font-style: italic;
       background: transparent;
       font-size: 18px;">
Hello
</div>
</code>```

Title: Use element to style inside <div>

Body:
You need to use emb as a class or id for styling your div tag and you can also use a separate css file.

<div class="emb">
Hello
</div>

<style>

    .emb {
   font-weight: 500;
   font-style: italic;
   background: transparent;
   font-size: 18px
    }

</style>

Here you can also use in-line css also.

<div style="font-weight: 500;
       font-style: italic;
       background: transparent;
       font-size: 18px;">
Hello
</div>


问:
Changing location of 3D object in Unity
I need a simple script to change XYZ location of  3d object (.obj) on Unity3D.  I click on a button and object must change his location to a new certain location. I don't know C#. Can you help me please?
Sorry for my English</p>

答:
Create an empty game object and drag this script onto it.</p>
```<code>using UnityEngine;

public class LocationController : MonoBehaviour
{
    // Drag the object you want to move into this field
    [SerializeField] private GameObject _objectToChangeLocation;

    // Enter your desired new location
    [SerializeField] private Vector3 _newLocation;

    // For your button component, drag the game object holding this script
    // and select this method
    public void ChangeLocation()
    {
        _objectToChangeLocation.transform.position = _newLocation;
    }
}
</code>```

Title: Changing location of 3D object in Unity

Body:
Create an empty game object and drag this script onto it.

using UnityEngine;

public class LocationController : MonoBehaviour
{
    // Drag the object you want to move into this field
    [SerializeField] private GameObject _objectToChangeLocation;

    // Enter your desired new location
    [SerializeField] private Vector3 _newLocation;

    // For your button component, drag the game object holding this script
    // and select this method
    public void ChangeLocation()
    {
        _objectToChangeLocation.transform.position = _newLocation;
    }
}


问:
How to track at which point a variable gets changed?
I have a BOOL instance variable which -for some reason- some time later always reads NO even if I set it to YES (Yes, I am not so stupid to write or read the wrong variable, trust me). I spent an hour searching my whole project for any possibilities where that variable might be set to NO but can't find it.

Is there a way to trace changes of it's value, i.e. to let the debugger halt at exactly the position where the variable is about to be modified?

答:
Found a solution without hacking the code:

Launch debugger with breakpoints enabled

Set a breakpoint at some point where the variable in question is in scope

Run. When it halts, inspect the debugger and find that variable.

Right-click on it and choose "Watch Variable".


问:
Error when running Pytest with Delta Lake Tables
I am working in the VDI of a company and they use their own artifactory for security reasons.
Currently I am writing unit tests to perform tests for a function that deletes entries from a delta table. When I started, I received an error of unresolved dependencies, because my spark session was configured in a way that it would load jars from maven. I was able to solve this issue by loading these jars locally from /opt/spark/jars. Now my code looks like this:

```<code>class TestTransformation(unittest.TestCase):
    @classmethod
    def test_ksu_deletion(self):
        self.spark = SparkSession.builder\
                        .appName('SPARK_DELETION')\
                        .config("spark.delta.logStore.class", "org.apache.spark.sql.delta.storage.S3SingleDriverLogStore")\
                        .config("spark.jars", "/opt/spark/jars/delta-core_2.12-0.7.0.jar, /opt/spark/jars/hadoop-aws-3.2.0.jar")\
                        .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")\
                        .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog")\
                        .getOrCreate()
        os.environ["KSU_DELETION_OBJECT"]="UNITTEST/"
        deltatable = DeltaTable.forPath(self.spark, "/projects/some/path/snappy.parquet")
        deltatable.delete(col("DATE") < get_current()
</code>```

However, I am getting the error message:

```<code>E     py4j.protocol.Py4JJavaError: An error occurred while calling z:io.delta.tables.DeltaTable.forPath.
E     : java.lang.NoSuchMethodError: org.apache.spark.sql.AnalysisException.<init>(Ljava/lang/String;Lscala/Option;Lscala/Option;Lscala/Option;Lscala/Option;)V
</code>```

Do you have any idea by what this is caused? I am assuming it has to do with the way I am configuring spark.sql.extions and/or the spark.sql.catalog, but to be honest, I am quite a newb in Spark.
I would greatly appreciate any hint.

Thanks a lot in advance!

Edit:
We are using Spark 3.0.2 (Scala 2.12.10). According to https://docs.delta.io/latest/releases.html, this should be compatible. Apart from the SparkSession, I trimmed down the subsequent code to

```<code>df.spark.read.parquet(Path/to/file.snappy.parquet)
</code>```

and now I am getting the error message

```<code>java.lang.IncompatibleClassChangeError: class org.apache.spark.sql.catalyst.plans.logical.DeltaDelete has interface org.apache.spark.sql.catalyst.plans.logical.UnaryNode as super class
</code>```

As I said, I am quite new to (Py)Spark, so please dont hesitate to mention things you consider completely obvious.

Edit 2: I checked the Python path I am exporting in the Shell before running the code and I can see the following:

Could this cause any problem? I dont understand why I do not get this error when running the code within pipenv (with spark-submit)

答:
It looks like that you're using incompatible version of the Delta lake library. 0.7.0 was for Spark 3.0, but you're using another version - either lower, or higher. Consult Delta releases page to find mapping between Delta version & required Spark versions.

If you're using Spark 3.1 or 3.2, consider using delta-spark Python package that will install all necessary dependencies, so you just import DeltaTable class.

Update: Yes, this happens because of the conflicting versions - you need to remove delta-spark and pyspark Python package, and install pyspark==3.0.2 explicitly.

P.S. Also, look onto pytest-spark package that can simplify specification of configuration for all tests.  You can find examples of it + Delta here.

Body:
I am working in the VDI of a company and they use their own artifactory for security reasons.
Currently I am writing unit tests to perform tests for a function that deletes entries from a delta table. When I started, I received an error of unresolved dependencies, because my spark session was configured in a way that it would load jars from maven. I was able to solve this issue by loading these jars locally from /opt/spark/jars. Now my code looks like this:

class TestTransformation(unittest.TestCase):
    @classmethod
    def test_ksu_deletion(self):
        self.spark = SparkSession.builder\
                        .appName('SPARK_DELETION')\
                        .config("spark.delta.logStore.class", "org.apache.spark.sql.delta.storage.S3SingleDriverLogStore")\
                        .config("spark.jars", "/opt/spark/jars/delta-core_2.12-0.7.0.jar, /opt/spark/jars/hadoop-aws-3.2.0.jar")\
                        .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")\
                        .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog")\
                        .getOrCreate()
        os.environ["KSU_DELETION_OBJECT"]="UNITTEST/"
        deltatable = DeltaTable.forPath(self.spark, "/projects/some/path/snappy.parquet")
        deltatable.delete(col("DATE") < get_current()

However, I am getting the error message:

E     py4j.protocol.Py4JJavaError: An error occurred while calling z:io.delta.tables.DeltaTable.forPath.
E     : java.lang.NoSuchMethodError: org.apache.spark.sql.AnalysisException.<init>(Ljava/lang/String;Lscala/Option;Lscala/Option;Lscala/Option;Lscala/Option;)V

Do you have any idea by what this is caused? I am assuming it has to do with the way I am configuring spark.sql.extions and/or the spark.sql.catalog, but to be honest, I am quite a newb in Spark.
I would greatly appreciate any hint.

Thanks a lot in advance!

Edit:
We are using Spark 3.0.2 (Scala 2.12.10). According to https://docs.delta.io/latest/releases.html, this should be compatible. Apart from the SparkSession, I trimmed down the subsequent code to

df.spark.read.parquet(Path/to/file.snappy.parquet)

and now I am getting the error message

java.lang.IncompatibleClassChangeError: class org.apache.spark.sql.catalyst.plans.logical.DeltaDelete has interface org.apache.spark.sql.catalyst.plans.logical.UnaryNode as super class

As I said, I am quite new to (Py)Spark, so please dont hesitate to mention things you consider completely obvious.

Edit 2: I checked the Python path I am exporting in the Shell before running the code and I can see the following:

Could this cause any problem? I dont understand why I do not get this error when running the code within pipenv (with spark-submit)


问:
Chain Max and Where in Linq
Given this code:

```<code>Book[] books = new Book[3]
    {
        new Book("100", "Title1"),
        new Book("200", "Title2"),
        new Book("200", "Title3"),
    };

getBookWithMostPages() {
    var max = books.Max(book => book.pages);
    return books.FirstOrDefault((book) => book.pages == max);
}
</code>```

Is it possible (there is any documented way) to chain Max and FirstOrDefault and return the same result ?

答:
.NET 6 introduced the MaxBy operator. I think that might be what you're looking for:

```<code>var book = books.MaxBy(b => b.Pages);
</code>```

Here's the implementation in the reference source so if you're using the older version of .NET you should be able to just copy it into your codebase. If of course that's what you want...

Title: Chain Max and Where in Linq

Body:
Given this code:

Book[] books = new Book[3]
    {
        new Book("100", "Title1"),
        new Book("200", "Title2"),
        new Book("200", "Title3"),
    };

getBookWithMostPages() {
    var max = books.Max(book => book.pages);
    return books.FirstOrDefault((book) => book.pages == max);
}

Is it possible (there is any documented way) to chain Max and FirstOrDefault and return the same result ?

Body:
.NET 6 introduced the MaxBy operator. I think that might be what you're looking for:

var book = books.MaxBy(b => b.Pages);

Here's the implementation in the reference source so if you're using the older version of .NET you should be able to just copy it into your codebase. If of course that's what you want...


问:
How to parse a single escape character between escape characters using ANTLR
I have a string like RANDOM = "SOMEGIBBERISH ("DOG CAT-DOG","DOG CAT-DOG")". For quoted string literals I use:

```<code>StringLiteralSQ : UnterminatedStringLiteralSQ '\'' ;
UnterminatedStringLiteralSQ : '\'' (~['\r\n] | '\\' (. | EOF))* ;
StringLiteralDQ : UnterminatedStringLiteralDQ '"' ;
UnterminatedStringLiteralDQ : '"' (~[\r\n] | '\\' (. | EOF))* ;
</code>```

This parses the above mentioned String. I need to identify them words as comma separated tokens like this DOG CAT-DOG. for this I use something like

```<code>options : name EQUALS value
  | OPTIONS L_PAREN (name EQUALS value) (COMMA (name EQUALS value)* R_PAREN
  ;
</code>```

However, when I make the string of this format RANDOM = "SOMEGIBBERISH ("DOG CAT-DOG"DOG CAT-DOG")", it fails with an out-of-memory error.

I wanted to parse the strings that I have been parsing before and also parse this kind of string ("DOG CAT-DOG"DOG CAT-DOG") and consider it a single token maybe. How can I do that?

答:
Your question is a bit confusing, so I'm not sure I understand what you are after. You ask for handling escaped characters, but then you don't show any input which uses escapes.

However, I think you are making things way too complicated. Look in other grammars to see how they define string tokens, including escape handling. Here's a typical example:

```<code>fragment SINGLE_QUOTE: '\'';
fragment DOUBLE_QUOTE: '"';

DOUBLE_QUOTED_TEXT: (
        DOUBLE_QUOTE ('\\'? .)*? DOUBLE_QUOTE
    )+
;

SINGLE_QUOTED_TEXT: (
        SINGLE_QUOTE ('\\'? .)*? SINGLE_QUOTE
    )+
;
</code>```

Body:
I have a string like RANDOM = "SOMEGIBBERISH ("DOG CAT-DOG","DOG CAT-DOG")". For quoted string literals I use:

StringLiteralSQ : UnterminatedStringLiteralSQ '\'' ;
UnterminatedStringLiteralSQ : '\'' (~['\r\n] | '\\' (. | EOF))* ;
StringLiteralDQ : UnterminatedStringLiteralDQ '"' ;
UnterminatedStringLiteralDQ : '"' (~[\r\n] | '\\' (. | EOF))* ;

This parses the above mentioned String. I need to identify them words as comma separated tokens like this DOG CAT-DOG. for this I use something like

options : name EQUALS value
  | OPTIONS L_PAREN (name EQUALS value) (COMMA (name EQUALS value)* R_PAREN
  ;

However, when I make the string of this format RANDOM = "SOMEGIBBERISH ("DOG CAT-DOG"DOG CAT-DOG")", it fails with an out-of-memory error.

I wanted to parse the strings that I have been parsing before and also parse this kind of string ("DOG CAT-DOG"DOG CAT-DOG") and consider it a single token maybe. How can I do that?

Body:
Your question is a bit confusing, so I'm not sure I understand what you are after. You ask for handling escaped characters, but then you don't show any input which uses escapes.

However, I think you are making things way too complicated. Look in other grammars to see how they define string tokens, including escape handling. Here's a typical example:

fragment SINGLE_QUOTE: '\'';
fragment DOUBLE_QUOTE: '"';

DOUBLE_QUOTED_TEXT: (
        DOUBLE_QUOTE ('\\'? .)*? DOUBLE_QUOTE
    )+
;

SINGLE_QUOTED_TEXT: (
        SINGLE_QUOTE ('\\'? .)*? SINGLE_QUOTE
    )+
;


问:
SwiftUI Conditionally disable modifier
So say I want to conditionally enable or disable a modifier on a view such as matched geometry effect? As silly as this looks, how would I do this?</p>
```<code>Image("Test")
   .scaleEffect(self.selectedImageScale)
   .offset(self.selectedImageOffset)
   .aspectRatio(contentMode: .fit)
if disabled {
   .matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
}
</code>```

答:
You can't put an if around a modifier, but you can use a ternary statement inside the parameters of the modifier:

```<code>.matchedGeometryEffect(id: disabled ? 0 : selectedImage.id, in: self.namespace)
</code>```

Not sure if 0 works here for a "disabled" id, depends on your ids.

Title: SwiftUI Conditionally disable modifier

Body:
So say I want to conditionally enable or disable a modifier on a view such as matched geometry effect? As silly as this looks, how would I do this?

Image("Test")
   .scaleEffect(self.selectedImageScale)
   .offset(self.selectedImageOffset)
   .aspectRatio(contentMode: .fit)
if disabled {
   .matchedGeometryEffect(id: selectedImage.id, in: self.namespace)
}

Body:
You can't put an if around a modifier, but you can use a ternary statement inside the parameters of the modifier:

.matchedGeometryEffect(id: disabled ? 0 : selectedImage.id, in: self.namespace)

Not sure if 0 works here for a "disabled" id, depends on your ids.


问:
Bash Script - Check if user is logged in or not
I'm trying to write a script that checks if the user (that is sent as an argument) is logged in or not. I want the answer to return 0 to the shell if the user is logged in and 1 to the shell if the user is not logged in.

But I have run into some problem. I get the message "You need to enter a user" everytime i try to run the script even if I send a user as an argument.

```<code>#!/bin/bash

function checkUser
{
  status=0

  for u in $(who | awk '{print $1}' | sort | uniq)
  do
    if [ "$u" = "$1" ]; then
      status=1
    fi
  done

  if [ "$status" = "1" ]; then
    echo "$user is logged in."
    exit 0
  else
    echo "$user is not logged in."
    exit 1
  fi
}
if [[ $1 -eq 0 ]] ; then
  echo 'You need to enter a user'
  read u
else
  user=$1
fi
</code>```

答:
```<code>echo "Enter Username: "
read check
_user="$(id -u -n)"
if [ "$check" = "$_user" ]
then
echo "User Logged In"
else
echo "User Not Logged In"
fi
</code>```

This will do your work perfectly fine!

Body:
I'm trying to write a script that checks if the user (that is sent as an argument) is logged in or not. I want the answer to return 0 to the shell if the user is logged in and 1 to the shell if the user is not logged in.

But I have run into some problem. I get the message "You need to enter a user" everytime i try to run the script even if I send a user as an argument.

#!/bin/bash

function checkUser
{
  status=0

  for u in $(who | awk '{print $1}' | sort | uniq)
  do
    if [ "$u" = "$1" ]; then
      status=1
    fi
  done

  if [ "$status" = "1" ]; then
    echo "$user is logged in."
    exit 0
  else
    echo "$user is not logged in."
    exit 1
  fi
}
if [[ $1 -eq 0 ]] ; then
  echo 'You need to enter a user'
  read u
else
  user=$1
fi

Body:
echo "Enter Username: "
read check
_user="$(id -u -n)"
if [ "$check" = "$_user" ]
then
echo "User Logged In"
else
echo "User Not Logged In"
fi

This will do your work perfectly fine!


问:
Need to get an average of a dictionary Key from a JSON file
I have a JSON file with this format:

```<code>{
    "people":    [
        {
            "name": "John Smith",
            "age":19,
            "member": false
        },
        {
            "name": "John Doe",
            "age": 23,
            "member": false
        },
        {
            "name": "Michael Johnson",
            "age":19,
            "member": false
        },
        {
            "name": "Daniel Katz",
            "age":17,
            "member": false
        }
    ]
}
</code>```

I need to load it as a Python object and calculate the age average. However, any For loop I tried running on this file after opening the file resulted in some sort of TypeError. Any suggestions on how to perform this?

import json
with open('students.json') as f:
    data = json.load(f)
    data_people = data['people']```

答:
get list of peoples and use sum on its age key:

import json

text = """{
    "people":    [
        {
            "name": "John Smith",
            "age": 19,
            "member": false
        },
        {
            "name": "John Doe",
            "age": 23,
            "member": false
        },
        {
            "name": "Michael Johnson",
            "age": 19,
            "member": false
        },
        {
            "name": "Daniel Katz",
            "age": 17,
            "member": false
        }
    ]
}"""

data = json.loads(text)
# or
# with open('students.json') as f:
#    data = json.load(f)

average = lambda l: sum(map(lambda x: x["age"], l ))/ len(l)
print(average(data["people"]))
```

output: 19.5

Body:
I have a JSON file with this format:

{
    "people":    [
        {
            "name": "John Smith",
            "age":19,
            "member": false
        },
        {
            "name": "John Doe",
            "age": 23,
            "member": false
        },
        {
            "name": "Michael Johnson",
            "age":19,
            "member": false
        },
        {
            "name": "Daniel Katz",
            "age":17,
            "member": false
        }
    ]
}

I need to load it as a Python object and calculate the age average. However, any For loop I tried running on this file after opening the file resulted in some sort of TypeError. Any suggestions on how to perform this?

import json
with open('students.json') as f:
    data = json.load(f)
    data_people = data['people']

Body:
get list of peoples and use sum on its age key:

import json

text = """{
    "people":    [
        {
            "name": "John Smith",
            "age": 19,
            "member": false
        },
        {
            "name": "John Doe",
            "age": 23,
            "member": false
        },
        {
            "name": "Michael Johnson",
            "age": 19,
            "member": false
        },
        {
            "name": "Daniel Katz",
            "age": 17,
            "member": false
        }
    ]
}"""

data = json.loads(text)
# or
# with open('students.json') as f:
#    data = json.load(f)

average = lambda l: sum(map(lambda x: x["age"], l ))/ len(l)
print(average(data["people"]))

output: 19.5


问:
'ConfigureServices returning a System.IServiceProvider isn't supported.'
I need ti use this AutoFac in ASP core 3.0

When I use this code in startu up:

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    return services.BuildAutofacServiceProvider();
}
</code>```

It show me this error:

'ConfigureServices returning an System.IServiceProvider isn't supported.'

And I change the program.cs by this:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
</code>```

But it not solved.

This is BuildAutofacServiceProvider() Code:

```<code>public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services)
{
    var ContainerBuilder = new ContainerBuilder();
    ContainerBuilder.Populate(services);
    ContainerBuilder.AddService();
    var container = ContainerBuilder.Build();

    return new AutofacServiceProvider(container);
}
</code>```

How can I solve this problem?

答:
Instead of Host use WebHost in Program.cs

It work for me ...

Body:
I need ti use this AutoFac in ASP core 3.0

When I use this code in startu up:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    return services.BuildAutofacServiceProvider();
}

It show me this error:

'ConfigureServices returning an System.IServiceProvider isn't supported.'

And I change the program.cs by this:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

But it not solved.

This is BuildAutofacServiceProvider() Code:

public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services)
{
    var ContainerBuilder = new ContainerBuilder();
    ContainerBuilder.Populate(services);
    ContainerBuilder.AddService();
    var container = ContainerBuilder.Build();

    return new AutofacServiceProvider(container);
}

How can I solve this problem?


问:
Java Preferences doesn't work in Windows 7
Recently I build an Java application. I use Java Preferences to store some information. When I ran my application in windows XP, the application run perfectly. I can store information and get the stored information. But when I ran it in Windows 7, Java Preference failed to store the information. Is there any solution?</p>

答:
Have you tried it with UAC off?

System preferences can't be set from Java without UAC off or UAC elevation.

Personal/User preferences CAN be.

Edit See my old question at: Is there a system-wide version of the Preferences API?


答:
That occurs because you set background style white. Change this line in your condition. I would remove style elememnt. But you can set transparent background. What you are like!

if (count == 0) {
   // property.style.backgroundColor = "white";
   property.removeAttribute('style');
  ...
```
<p><strong>Working example</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>      var count = 1;
      function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
          property.removeAttribute('style');
          count = 1;
        } else {

          property.style.backgroundColor = color;
          count = 0;
        }
      }</code>```

      .button {
        background-color: #4caf50; /* Green */
        border: none;
        color: white;
        padding: 16px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        transition-duration: 0.4s;
        cursor: pointer;
      }

      .button1 {
        background-color: white;
        color: black;
        border: 2px solid #4caf50;
      }

      .button1:hover {
        background-color: red;
        color: black;
        border: 2px solid #4caf50;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <style>

    </style>

    <script>

    </script>
  </head>

  <body>
    <h2>Hoverable Buttons</h2>
    <button
      id="buttonGreen"
      class="button button1"
      onclick="setColor('buttonGreen', '#122256')"
      ;
    >
      Green1
    </button>
  </body>
</html></code>```

Note But better to use classes and then js toggle function.

Title: Button hover does not work after I change button color using JS

Body:
I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs.  However, Hover works when the page is loaded but after the color changes, it doesn't work. The code is below:

var count = 1;

function setColor(btn, color) {
  var property = document.getElementById(btn);
  if (count == 0) {
    property.style.backgroundColor = "white";
    count = 1;
  } else {
    property.style.backgroundColor = color;
    count = 0;
  }
}

.button {
  background-color: #4caf50;
  /* Green */
  border: none;
  color: white;
  padding: 16px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  transition-duration: 0.4s;
  cursor: pointer;
}

.button1 {
  background-color: white;
  color: black;
  border: 2px solid #4caf50;
}

.button1:hover {
  background-color: red;
  color: black;
  border: 2px solid #4caf50;
}

 Hoverable Buttons

<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>

After I click the button event occurs and the color changes to dark blue and the hover do not work.

Body:
That occurs because you set background style white. Change this line in your condition. I would remove style elememnt. But you can set transparent background. What you are like!

if (count == 0) {
   // property.style.backgroundColor = "white";
   property.removeAttribute('style');
  ...

Working example

      var count = 1;
      function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
          property.removeAttribute('style');
          count = 1;
        } else {

          property.style.backgroundColor = color;
          count = 0;
        }
      }

      .button {
        background-color: #4caf50; /* Green */
        border: none;
        color: white;
        padding: 16px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        transition-duration: 0.4s;
        cursor: pointer;
      }

      .button1 {
        background-color: white;
        color: black;
        border: 2px solid #4caf50;
      }

      .button1:hover {
        background-color: red;
        color: black;
        border: 2px solid #4caf50;
      }

<html>
  <head>
    <style>

    </style>

    <script>

    </script>
  </head>

  <body>
    <h2>Hoverable Buttons</h2>
    <button
      id="buttonGreen"
      class="button button1"
      onclick="setColor('buttonGreen', '#122256')"
      ;
    >
      Green1
    </button>
  </body>
</html>

Note But better to use classes and then js toggle function.


问:
Joblib doesn't run on multiple cores
I need to fit multiple classifiers (from scikit-learn) and score them.

```<code>clf1.fit(x_fit,Y_fit)
clf2.fit(x_fit,Y_fit)
clf3.fit(x_fit,Y_fit)
clf4.fit(x_fit,Y_fit)

acc1 = clf1.score(x_score,Y_score)
acc2 = clf2.score(x_score,Y_score)
acc3 = clf3score(x_score,Y_score)
acc4 = clf4.score(x_score,Y_score)
</code>```

This turns out to be very slow. Therefore I want to make use of joblib and make my code execute in parallel. Here is my code

```<code>def fit_score(x_fit, Y_fit, x_score, Y_score, clf):
    clf.fit(x_fit, Y_fit)
    return clf.score(x_score, Y_score)

acc1, acc2, acc3, acc4 = Parallel(n_jobs=4)(delayed(fit_score)(x_fit, Y_fit, x_score, Y_score, clf) for clf in [clf1, clf2, clf3, clf4])
</code>```

Unfortunately this doesn’t seem to work very well. I am observing CPU usage with htop and it appears that this is still running on only one single core. I searched for a comparable thread, however most people are suffering from an increased runtime caused by the overhead from using parallel. But in my case it doesn't seem to use parallel at all.

Am I doing anything wrong?

Thanks for your help!

答:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

By using this natively optimized libs you can get much better performance even on limited number of cores.

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

Title: Joblib doesn't run on multiple cores

Body:
I need to fit multiple classifiers (from scikit-learn) and score them.

clf1.fit(x_fit,Y_fit)
clf2.fit(x_fit,Y_fit)
clf3.fit(x_fit,Y_fit)
clf4.fit(x_fit,Y_fit)

acc1 = clf1.score(x_score,Y_score)
acc2 = clf2.score(x_score,Y_score)
acc3 = clf3score(x_score,Y_score)
acc4 = clf4.score(x_score,Y_score)

This turns out to be very slow. Therefore I want to make use of joblib and make my code execute in parallel. Here is my code

def fit_score(x_fit, Y_fit, x_score, Y_score, clf):
    clf.fit(x_fit, Y_fit)
    return clf.score(x_score, Y_score)

acc1, acc2, acc3, acc4 = Parallel(n_jobs=4)(delayed(fit_score)(x_fit, Y_fit, x_score, Y_score, clf) for clf in [clf1, clf2, clf3, clf4])

Unfortunately this doesn’t seem to work very well. I am observing CPU usage with htop and it appears that this is still running on only one single core. I searched for a comparable thread, however most people are suffering from an increased runtime caused by the overhead from using parallel. But in my case it doesn't seem to use parallel at all.

Am I doing anything wrong?

Thanks for your help!

Body:
You can try using accelerated implementations of algorithms - such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex

By using this natively optimized libs you can get much better performance even on limited number of cores.

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()


问:
How to pass POST parameters with HTML SSE?
I've got a block of code here that uses HTML 5 SSE - the EventSource object, which lets a php script push updates to the webpage. However, I'm interested in also passing parameters to the script. How can I do that?

Here's the code:

```<code>if(typeof(EventSource) !== "undefined")
    {
        var source = new EventSource("get_message.php");
        source.onmessage=function(event)
        {
            document.getElementById("message-window").innerHTML+=event.data + "<br>";
        };
    }
else
    {
        document.getElementById("message-window").innerHTML="Sorry, your browser does not support server-sent events...";
     }
</code>```

The closest thing I can think of is to use AJAX, as in

```<code>$.post("get_message.php", {largest_id: 30}, function(data, status){ some function });
</code>```

However, I'm not sure how to write the jQuery for this?

答: The downside of submitting a POST request to initiate EventSource is reconnection to the event stream, which is part of the specification. Since the browser must be able to reestablish the connection to the same EventSource, identifying the request with POST data would mean posting the same data again on every reconnect attempt. This is the intended use of POST request according to initial RFC 2616 and providing alternate URL or separate mechanism for reconnection would probably overcomplicate the SSE implementation for browser JavaScript and is also a practical design problem when you use POST query to initiate EventSource.

Body:
I've got a block of code here that uses HTML 5 SSE - the EventSource object, which lets a php script push updates to the webpage. However, I'm interested in also passing parameters to the script. How can I do that?

Here's the code:

if(typeof(EventSource) !== "undefined")
    {
        var source = new EventSource("get_message.php");
        source.onmessage=function(event)
        {
            document.getElementById("message-window").innerHTML+=event.data + "
";
        };
    }
else
    {
        document.getElementById("message-window").innerHTML="Sorry, your browser does not support server-sent events...";
     }

The closest thing I can think of is to use AJAX, as in

$.post("get_message.php", {largest_id: 30}, function(data, status){ some function });

However, I'm not sure how to write the jQuery for this?


问:
Github API number of watch over time
I am trying to fetch the number of watches over time using Python, I have tried "https://api.github.com/repos/octocat/hello-world/subscription" that is listed on the Github API webpage, but seems no longer work, I am a bit confused. I am just trying to get "created_at" under subscription. Any suggestions? Thank you.</p>

答:
To get the number of watchers you can do this:</p>
```<code>#get number of watchers
url = f"https://api.github.com/repos/{git_owner_repository}/{git_repository_name}"
response = requests.get(url, auth=(username, GITHUB_TOKEN))
response.raise_for_status()
response_dict = response.json()
watchers = response_dict['watchers_count']

#get all the watchers:
url = f"https://api.github.com/repos/octocat/hello-world/subscribers?simple=yes&per_page={watchers}"
response_watcher = requests.get(url, auth=(username, GITHUB_TOKEN))
response_watcher.raise_for_status()
response_watcher = response.json()
for watcher in response_watcher:
    user_url = watcher['url']
    watcher_name = watcher['login']
    response_user = requests.get(user_url, auth=(username, GITHUB_TOKEN))
    response_user.raise_for_status()
    response_dict_user = response.json()
    created_at= response_dict_user['created_at']
    print(f"watcher name: {watcher_name}, created_at: {created_at}")
</code>```

Title: Github API number of watch over time

Body:
To get the number of watchers you can do this:

#get number of watchers
url = f"https://api.github.com/repos/{git_owner_repository}/{git_repository_name}"
response = requests.get(url, auth=(username, GITHUB_TOKEN))
response.raise_for_status()
response_dict = response.json()
watchers = response_dict['watchers_count']

#get all the watchers:
url = f"https://api.github.com/repos/octocat/hello-world/subscribers?simple=yes&per_page={watchers}"
response_watcher = requests.get(url, auth=(username, GITHUB_TOKEN))
response_watcher.raise_for_status()
response_watcher = response.json()
for watcher in response_watcher:
    user_url = watcher['url']
    watcher_name = watcher['login']
    response_user = requests.get(user_url, auth=(username, GITHUB_TOKEN))
    response_user.raise_for_status()
    response_dict_user = response.json()
    created_at= response_dict_user['created_at']
    print(f"watcher name: {watcher_name}, created_at: {created_at}")


问:
Initialize dictionary inside dictionary C# vs Python
Why dictionary inside dictionary needs to be explicit in c# e.g. see the following code d1,d2 are fine but on d3 compiler throwing a fit.

```<code>var d1 = new Dictionary<string, string> { { "1", "1" } }; //works
var d2 = new Dictionary<string, Dictionary<string, string>> { { "1", d1 } }; //works
var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", { { "1", "1" } } }} //does not work
</code>```

Python does same and much simpler way

```<code>d1:dict={'1':1}
d2:dict = {'1':{'1':1}}
</code>```

答:
You've left out the new Dictionary<string, string> part (and one closing }):

```<code>var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", new Dictionary<string, string> { { "1", "1" } } } };
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−^
</code>```

You need to tell C# what concrete instance to create because you could be using a Dictionary subclass:

```<code>class SomeDictionarySubclass<K, V> : Dictionary<K, V> {
    // ...
}
// ...
var d3 = new Dictionary<string, Dictionary<string, string>> {
    { "1", new SomeDictionarySubclass<string, string> { { "1", "1" } } }
};
</code>```

Body:
Why dictionary inside dictionary needs to be explicit in c# e.g. see the following code d1,d2 are fine but on d3 compiler throwing a fit.

var d1 = new Dictionary<string, string> { { "1", "1" } }; //works
var d2 = new Dictionary<string, Dictionary<string, string>> { { "1", d1 } }; //works
var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", { { "1", "1" } } }} //does not work

Python does same and much simpler way

d1:dict={'1':1}
d2:dict = {'1':{'1':1}}

Body:
You've left out the new Dictionary<string, string> part (and one closing }):

var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", new Dictionary<string, string> { { "1", "1" } } } };
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−^

You need to tell C# what concrete instance to create because you could be using a Dictionary subclass:

class SomeDictionarySubclass<K, V> : Dictionary<K, V> {
    // ...
}
// ...
var d3 = new Dictionary<string, Dictionary<string, string>> {
    { "1", new SomeDictionarySubclass<string, string> { { "1", "1" } } }
};


问:
Gmail like file upload with jQuery
I would like to upload files just like google mail does. I would want to use jQuery and PHP to do it is there anyway of getting the progressbar etc.?

Here I added a video of how google does it. http://dl.getdropbox.com/u/5910/Jing/2009-04-02_1948.swf

No flash, no perl or cgi please..

I guess I can live without the progressbar now I am actually searching for information about jquery plugins or just what things I would need to look at

答: Uploadify is another swf (sorry) upload button that uses jquery. Same idea as what Javier mentioned.</p>

OwnerDisplayName: Thomaschaaf

ContentLicense: CC BY-SA 2.5

Title: Gmail like file upload with jQuery

LastEditorDisplayName: Thomaschaaf

OwnerDisplayName: NetHawk


答:
You can use statistics.mean on your dictionary:

```<code>import json
from statistics import mean

with open('students.json') as f:
    data = json.load(f)

avg_age = mean(p['age'] for p in data['people'])
</code>```

output: 19.5

Title: Need to get an average of a dictionary Key from a JSON file

Body:
You can use statistics.mean on your dictionary:

import json
from statistics import mean

with open('students.json') as f:
    data = json.load(f)

avg_age = mean(p['age'] for p in data['people'])

output: 19.5


问:
Image and plotly plot side by side in R markdown
I am trying to show an image and a plot (plotly gauge) side-by-side in R markdown, however only a blank graph shows for the image. I have imported the image into plotly and am attempting to use subplot to show them side by side. Any advice on what I'm missing?</p>
```<code>
# Photo
photo <- plot_ly(domain = list(x = c(0, 0.5), y = c(0, 1)))%>%
  layout(
    images = list(source =  "C:/Users/Name/Documents//Image.PNG"
      ))

# Gauge value
x <- mean(df$variable)

# Plot
fig1 <- plot_ly(
  value = x,
  number = list(suffix = "%"),
  title = list(text = "Title"),
  type = "indicator",
  mode = "gauge+number",
  gauge = list(
    axis =list(range = list(NULL, 100)),
    steps = list(
      list(range = c(0, 78), color = "white"),
      list(range = c(78, 88), color = "green"),
      list(range = c(88, 100), color = "white")),
    bar = list(color = "black")),
  domain = list(x = c(0.5, 1), y = c(0, 1)))

subplot(photo, add_trace(fig1))
</code>```

答:
I didn't try in RMarkdown but I would try this:

```<code>library(plotly)
library(EBImage) # BiocManager::install("EBImage")

p1 <- plot_ly(economics, x = ~pop)

img <- readImage("mobiussolid.png")
p2 <- plot_ly(type = "image", z = img*255) %>%
  layout(margin=list(l=10, r=10, b=0, t=0),
         xaxis=list(showticklabels=FALSE, ticks=""),
         yaxis=list(showticklabels=FALSE, ticks=""))

subplot(p1, p2)
</code>```

Body:
I am trying to show an image and a plot (plotly gauge) side-by-side in R markdown, however only a blank graph shows for the image. I have imported the image into plotly and am attempting to use subplot to show them side by side. Any advice on what I'm missing?

# Photo
photo <- plot_ly(domain = list(x = c(0, 0.5), y = c(0, 1)))%>%
  layout(
    images = list(source =  "C:/Users/Name/Documents//Image.PNG"
      ))

# Gauge value
x <- mean(df$variable)

# Plot
fig1 <- plot_ly(
  value = x,
  number = list(suffix = "%"),
  title = list(text = "Title"),
  type = "indicator",
  mode = "gauge+number",
  gauge = list(
    axis =list(range = list(NULL, 100)),
    steps = list(
      list(range = c(0, 78), color = "white"),
      list(range = c(78, 88), color = "green"),
      list(range = c(88, 100), color = "white")),
    bar = list(color = "black")),
  domain = list(x = c(0.5, 1), y = c(0, 1)))

subplot(photo, add_trace(fig1))

Body:
I didn't try in RMarkdown but I would try this:

library(plotly)
library(EBImage) # BiocManager::install("EBImage")

p1 <- plot_ly(economics, x = ~pop)

img <- readImage("mobiussolid.png")
p2 <- plot_ly(type = "image", z = img*255) %>%
  layout(margin=list(l=10, r=10, b=0, t=0),
         xaxis=list(showticklabels=FALSE, ticks=""),
         yaxis=list(showticklabels=FALSE, ticks=""))

subplot(p1, p2)


问:
I'm getting the classic "Permission denied while connecting to upstream" while trying to deploy my flask app on an Nginx server, Ubuntu 21.10 instance
I know the question has been asked a million times, and I've tried almost every 'solution' to no avail. I'm thinking that my problem could be unique.

uwsgi.ini:

```<code>module = wsgi:app
master = true
processes = 5
socket = elekto.sock
chmod-socket = 666
vacuum = true
die-on-term = true
logto = /home/richardgrecoson/elekto/elekto.log
</code>```

/etc/nginx/sites-enabled/elekto :

```<code>server {
    listen 80;
    server_name my_ip;
location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/richardgrecoson/elekto/elekto.sock;
    }
}
</code>```

/etc/systemd/system/elekto.service

```<code>[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=richardgrecoson
Group=www-data
WorkingDirectory=/home/richardgrecoson/elekto
Environment="PATH=/home/richardgrecoson/elekto/.venv/bin"
ExecStart=/home/richardgrecoson/elekto/.venv/bin/uwsgi --ini uwsgi.ini

[Install]
WantedBy=multi-user.target
</code>```

答:
Your NGINX is not allowed to r/w/x on the socket file. Lets try some things.

Change the permission of the socket to 0777 and check it with ls /home/richardgrecoson/elekto/elekto.sock

In general it is important that the runuser of NGINX is allowed to r/w/x the socket. The runuser of nginx is "normally" nginx. Check this by typing ps -elf |grep nginx

If it is NGINX I would change the permissions of the socket back to 660 and change the user and group to nginx.

With this the nginx user will have access to the socket.

If you want to use a different runuser for the socket as for nginx, create a new user and add it to the nginx group
usermod -a -G nginx yourusername. This will work with 660 as well.

Body:
I know the question has been asked a million times, and I've tried almost every 'solution' to no avail. I'm thinking that my problem could be unique.

uwsgi.ini:

module = wsgi:app
master = true
processes = 5
socket = elekto.sock
chmod-socket = 666
vacuum = true
die-on-term = true
logto = /home/richardgrecoson/elekto/elekto.log

/etc/nginx/sites-enabled/elekto :

server {
    listen 80;
    server_name my_ip;
location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/richardgrecoson/elekto/elekto.sock;
    }
}

/etc/systemd/system/elekto.service

[Unit]
Description=uWSGI instance to serve myproject
After=network.target

[Service]
User=richardgrecoson
Group=www-data
WorkingDirectory=/home/richardgrecoson/elekto
Environment="PATH=/home/richardgrecoson/elekto/.venv/bin"
ExecStart=/home/richardgrecoson/elekto/.venv/bin/uwsgi --ini uwsgi.ini

[Install]
WantedBy=multi-user.target