问:
Using dataclasses with Cython
I'm using cython for code obfuscation, so performance is not an issue at the moment. The problem is with using dataclasses.

There is no error during compilation time when cythonize code that contains dataclass definitions. But when running the code, I get a TypeError: <field> is a field but has no type annotation.

Here is the code I'm trying to cythonize:

from dataclasses import dataclass, field
from typing import Dict, Any, List

@dataclass
class dataclass_test:
    ddict: Dict[str, Any]
    sstr: str
    bbool: bool
    llist: List[str]
    ffloat: float
    llist1: List[str] = field(default_factory=list)
```

<p>Running the code without cythonization works fine. But after cythonization I get the following error message:</p>

``` File "dataclass_.py", line 4, in init dataclass_
    @dataclass   File "/home/aryskin/miniconda3/envs/tf113_gpu_conda/lib/python3.7/dataclasses.py", line 991, in dataclass
    return wrap(_cls)   File "/home/aryskin/miniconda3/envs/tf113_gpu_conda/lib/python3.7/dataclasses.py", line 983, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)   File "/home/aryskin/miniconda3/envs/tf113_gpu_conda/lib/python3.7/dataclasses.py", line 857, in _process_class
    raise TypeError(f'{name!r} is a field but has no type annotation') TypeError: 'llist1' is a field but has no type annotation
```

Is there any way to avoid this problem without or with minimal rewriting of the source code?

答:
Until support for this is merged into Cython, a workaround is to manually add the __annotations__ attribute to your class and repeat your type annotations:

```<code>@dataclass
class Fieldset:
    label: str
    fields: List[Field] = []

    __annotations__ = {
        'label': str,
        'fields': List[Field],
    }
</code>```

Title: Using dataclasses with Cython

Body:
I'm using cython for code obfuscation, so performance is not an issue at the moment. The problem is with using dataclasses.

There is no error during compilation time when cythonize code that contains dataclass definitions. But when running the code, I get a TypeError: <field> is a field but has no type annotation.

Here is the code I'm trying to cythonize:

from dataclasses import dataclass, field
from typing import Dict, Any, List

@dataclass
class dataclass_test:
    ddict: Dict[str, Any]
    sstr: str
    bbool: bool
    llist: List[str]
    ffloat: float
    llist1: List[str] = field(default_factory=list)

Running the code without cythonization works fine. But after cythonization I get the following error message:

 File "dataclass_.py", line 4, in init dataclass_
    @dataclass   File "/home/aryskin/miniconda3/envs/tf113_gpu_conda/lib/python3.7/dataclasses.py", line 991, in dataclass
    return wrap(_cls)   File "/home/aryskin/miniconda3/envs/tf113_gpu_conda/lib/python3.7/dataclasses.py", line 983, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)   File "/home/aryskin/miniconda3/envs/tf113_gpu_conda/lib/python3.7/dataclasses.py", line 857, in _process_class
    raise TypeError(f'{name!r} is a field but has no type annotation') TypeError: 'llist1' is a field but has no type annotation

Is there any way to avoid this problem without or with minimal rewriting of the source code?

Body:
Until support for this is merged into Cython, a workaround is to manually add the __annotations__ attribute to your class and repeat your type annotations:

@dataclass
class Fieldset:
    label: str
    fields: List[Field] = []

    __annotations__ = {
        'label': str,
        'fields': List[Field],
    }


来源: stackexchange

问:
AJAX upload triggered from a specific select option
I'm looking to add an option to my layout page to allow people to upload new logos on the fly. Currently users can select the image they'd like via a drop-down select element. I'd like to add an option at the end which allows them to upload a new image. I'd then refresh the image select elements with the new addition.

HTML example:

```<code><select name='image_select' id='image_select_id' class='input_select' title='Select Image 1'>
  <option value='0' selected = 'selected'>--Select Logo--</option>
  <option value='test.jpg'>test.jpg</option>
  <option value='test2.jpg'>test2.jpg</option>
  <option value='add' class='upload_option'>Add new image...</option>
</select>
</code>```

I'm using AJAXUpload for other uploading functions, but the iFrame doesn't seem to play nice in this instance. Does anyone have any suggestions about how to make this work?

答: The only way to uplaod an image in a AJAX way is via an iframe. If i had to advise a way i would have it so that. The user selects Add new images. An onselect function detects this and displays a form in a html box underneath. You have that form's "target" set to the ID of the iframe. Also have a onSubmit command on the form. The user hits submit, the file is sent though an iframe, you can then use the onSubmit tag to get your javascript to pull up a loading bar or what ever you want.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to add an option to my layout page to allow people to upload new logos on the fly. Currently users can select the image they'd like via a drop-down select element. I'd like to add an option at the end which allows them to upload a new image. I'd then refresh the image select elements with the new addition.

HTML example:

<select name='image_select' id='image_select_id' class='input_select' title='Select Image 1'>
  <option value='0' selected = 'selected'>--Select Logo--</option>
  <option value='test.jpg'>test.jpg</option>
  <option value='test2.jpg'>test2.jpg</option>
  <option value='add' class='upload_option'>Add new image...</option>
</select>

I'm using AJAXUpload for other uploading functions, but the iFrame doesn't seem to play nice in this instance. Does anyone have any suggestions about how to make this work?


问:
Android Studio - How to perform doubleClick in Kotlin?
A boring thing when some more advanced technologies impose their standards is to have to do with the "double click" to perform an action. But what I'm looking for is an easy way to implement it without having to rewrite the code a thousand times.

I would like to implement double click in my project using Kotlin.
Could someone help me?
Thanks in Advance

just to know: I would like a way to understand how to do double click or to prevent  that user do a doubleclick

答:
you can use this code its like double click if you dont like it you can read about Gesture Listener.</p>

```<code>var doubleClick: Boolean? = false
yourview.setOnClickListener {
        if (doubleClick!!) {
            //Code here when they double click
        }
        doubleClick = true
        Handler().postDelayed({ doubleClick = false }, 2000)
       }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
you can use this code its like double click if you dont like it you can read about Gesture Listener.

var doubleClick: Boolean? = false
yourview.setOnClickListener {
        if (doubleClick!!) {
            //Code here when they double click
        }
        doubleClick = true
        Handler().postDelayed({ doubleClick = false }, 2000)
       }


问:
How to send an email with attachment from R in windows
I have a scheduled an R script running from a windows machine.

After it finishes, I wish this script to automatically send an email with some log file attached.

Using shell() with some other scripts may be possible, but I was wondering if there is a better solution within R.
Thanks.

答:
Here is a simple code snippet for sending an e-mail by using "mailR" package</p>

```<code>library(mailR)

# 1. Sender
sender <- "x@me.com"

# 2. Recipients
recipients <- c("y@you.com", "z@our.com")

# 3. Attached files
list_files_attached_location <- c("mtcars.csv")
list_files_attached_names <- c("mtcars name")
list_files_attached_description <- c("mtcars desc")

# 4. Send email
tryCatch({
  send.mail(from = sender,
            to = recipients,
            subject = "Your subject",
            body = "Your mail body",
            smtp = list(
              host.name = "smtp.gmail.com",
              port = 465,
              user.name = sender,
              passwd = "psw",
              ssl = TRUE),
            authenticate = TRUE,
            send = TRUE,
            attach.files = list_files_attached_location,
            file.names = list_files_attached_names,
            file.descriptions = list_files_attached_description,
            debug = TRUE
  )
},
error = function(e) {
  print(e)
  stop()
})
</code>```

Body:
Here is a simple code snippet for sending an e-mail by using "mailR" package

library(mailR)

# 1. Sender
sender <- "x@me.com"

# 2. Recipients
recipients <- c("y@you.com", "z@our.com")

# 3. Attached files
list_files_attached_location <- c("mtcars.csv")
list_files_attached_names <- c("mtcars name")
list_files_attached_description <- c("mtcars desc")

# 4. Send email
tryCatch({
  send.mail(from = sender,
            to = recipients,
            subject = "Your subject",
            body = "Your mail body",
            smtp = list(
              host.name = "smtp.gmail.com",
              port = 465,
              user.name = sender,
              passwd = "psw",
              ssl = TRUE),
            authenticate = TRUE,
            send = TRUE,
            attach.files = list_files_attached_location,
            file.names = list_files_attached_names,
            file.descriptions = list_files_attached_description,
            debug = TRUE
  )
},
error = function(e) {
  print(e)
  stop()
})


问:
If i execute the same test case two times, is there a way to generate report.html with a timestamp in the file name?
I have a question related with report.html that maybe someone could help me to clarify

If i execute the same test case two times, is there a way to generate report.html with a timestamp in the file name so after 2 executions i have 2 reports.html.

for example:
report_20200529_15:00:00.html
report_20200529:15:05:00.html

Thanks in advance for your help

答:
This is covered in the robot framework user guide, in a section titled timestamping output files:

All output files listed in this section can be automatically timestamped with the option --timestampoutputs (-T). When this option is used, a timestamp in the format YYYYMMDD-hhmmss is placed between the extension and the base name of each file.


问:
Fastest way to select multiple elements from a list to build a dataframe
I have a list that contains multiple data.frames. I want to select every nth data.frame from the list and combine them into a single data.frame which can be written to a csv.

Here is an example of the list structure:

```<code>one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                     last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                        last_name  = c('Davis', 'Proctor') )

one.list <- list()

one.list[[1]]$title <- one.title
one.list[[1]]$author <- one.author
one.list[[2]]$title <- second.title
one.list[[2]]$author <- second.author
</code>```

Here's my current solution that produces a single data frame for the 'authors' fields:

```<code>build_author_table <- function(result.l){

  list_to_df <- function(i){

  x <- result.l[[i]]$author

  return(x)
}

authors_df_l <-(lapply(1:length(result.l), FUN = list_to_df))

authors_df <- do.call("rbind", lapply(authors_df_l, as.data.frame))

return(authors_df)
}
</code>```

This produces the output I want:

```<code>    first_name last_name
1      Susan     Smith
2      Alice   Johnson
3      Sarah     Davis
4       Mary   Proctor
</code>```

But as you can probably imagine, when scaled to thousands of records with much larger text fields in the data.frame, it is painfully slow.

Can anyone suggest a faster, more efficient way to produce the final data.frame?

答:
Your construction code didn't work, but I built one that I think resembles what you're shooting at.

```<code>List of 2
 $ :List of 2
  ..$ title :'data.frame':  1 obs. of  2 variables:
  .. ..$ id   : Factor w/ 1 level "1a": 1
  .. ..$ title: Factor w/ 1 level "first title": 1
  ..$ author:'data.frame':  2 obs. of  2 variables:
  .. ..$ first_name: Factor w/ 2 levels "Alice","Susan": 2 1
  .. ..$ last_name : Factor w/ 2 levels "Johnson","Smith": 2 1
 $ :List of 2
  ..$ title :'data.frame':  1 obs. of  2 variables:
  .. ..$ id   : Factor w/ 1 level "2b": 1
  .. ..$ title: Factor w/ 1 level "second_title": 1
  ..$ author:'data.frame':  2 obs. of  2 variables:
  .. ..$ first_name: Factor w/ 2 levels "Mary","Sarah": 2 1
  .. ..$ last_name : Factor w/ 2 levels "Davis","Proctor": 1 2
</code>```

If this is what you were thinking of, this works splendidly, you do get a warning because the character strings are factors. These can be ignored, or when building the initial dataframe use stringAsFactors = F as an argument

```<code>library(purrr)
map_dfr(one.list, "author")
</code>```

Body:
I have a list that contains multiple data.frames. I want to select every nth data.frame from the list and combine them into a single data.frame which can be written to a csv.

Here is an example of the list structure:

one.title <- data.frame(id = '1a', title = 'first title')

one.author <- data.frame(first_name = c('Susan', 'Alice'),
                     last_name  = c('Smith', 'Johnson') )

second.title <- data.frame(id = '2b', title = 'second_title')

second.author <- data.frame(first_name = c('Sarah', 'Mary'),
                        last_name  = c('Davis', 'Proctor') )

one.list <- list()

one.list[[1]]$title <- one.title
one.list[[1]]$author <- one.author
one.list[[2]]$title <- second.title
one.list[[2]]$author <- second.author

Here's my current solution that produces a single data frame for the 'authors' fields:

build_author_table <- function(result.l){

  list_to_df <- function(i){

  x <- result.l[[i]]$author

  return(x)
}

authors_df_l <-(lapply(1:length(result.l), FUN = list_to_df))

authors_df <- do.call("rbind", lapply(authors_df_l, as.data.frame))

return(authors_df)
}

This produces the output I want:

    first_name last_name
1      Susan     Smith
2      Alice   Johnson
3      Sarah     Davis
4       Mary   Proctor

But as you can probably imagine, when scaled to thousands of records with much larger text fields in the data.frame, it is painfully slow.

Can anyone suggest a faster, more efficient way to produce the final data.frame?

Body:
Your construction code didn't work, but I built one that I think resembles what you're shooting at.

List of 2
 $ :List of 2
  ..$ title :'data.frame':  1 obs. of  2 variables:
  .. ..$ id   : Factor w/ 1 level "1a": 1
  .. ..$ title: Factor w/ 1 level "first title": 1
  ..$ author:'data.frame':  2 obs. of  2 variables:
  .. ..$ first_name: Factor w/ 2 levels "Alice","Susan": 2 1
  .. ..$ last_name : Factor w/ 2 levels "Johnson","Smith": 2 1
 $ :List of 2
  ..$ title :'data.frame':  1 obs. of  2 variables:
  .. ..$ id   : Factor w/ 1 level "2b": 1
  .. ..$ title: Factor w/ 1 level "second_title": 1
  ..$ author:'data.frame':  2 obs. of  2 variables:
  .. ..$ first_name: Factor w/ 2 levels "Mary","Sarah": 2 1
  .. ..$ last_name : Factor w/ 2 levels "Davis","Proctor": 1 2

If this is what you were thinking of, this works splendidly, you do get a warning because the character strings are factors. These can be ignored, or when building the initial dataframe use stringAsFactors = F as an argument

library(purrr)
map_dfr(one.list, "author")


问:
how to add foriegnkey object and connnect it a post object through a single endpoint in Django rest Framework
models.py

```<code>class PostAdvertisment(models.Model):
    # post=models.ForeignKey(Post,on_delete=models.CASCADE,null=True,blank=True)
    created_at=models.DateTimeField(auto_now_add=True)
    title=models.CharField(max_length=255,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    advertizing_content= models.TextField(null =True ,blank=True)
    def __str__(self):
        return f'{self.title}'
class Post(models.Model):

    # created_at=models.DateTimeField(efault=datetime.now, blank=True)

    created_at=models.DateTimeField(auto_now_add=True)
    author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post")
    title=models.CharField(max_length=128,null=True,blank=True)
    rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True)

    # rating=models.IntegerField(null=True,blank=True)
    content=models.TextField(null=True,blank=True)
    review=models.CharField(max_length=250,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters")
    tags = TaggableManager(blank=True)
    comments=models.ManyToManyField('Comment',blank=True,related_name="comments_post")
    anonymous = models.BooleanField(default=False, blank=True)
    fake = models.BooleanField(default=False, blank=True)

    genuine = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_genuines")
    spam = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_spames")
    advertisement=models.ForeignKey(PostAdvertisment,on_delete=models.CASCADE,null=True,blank=True)

    def __str__(self):
        return f'{self.content}'
    def get_absolute_url(self):
        return reverse('post:post_detail' , kwargs={'post_id':Post.id})
</code>```

so here is my serializers.py

```<code>class PostSerializer(TaggitSerializer,serializers.ModelSerializer):
    tags = TagListSerializerField()
    author = serializers.StringRelatedField(read_only=True)
    comments = CommentSerializer(many=True, required=False, read_only=True)
    # title = serializers.CharField()

    advertisement = PostAdvertisementSerializer()
    # advertisement = serializers.SlugRelatedField(
    #     queryset=PostAdvertisment.objects.all(),
    #     slug_field='advertisement'
    #      )
    # category_name = serializers.CharField(source='advertisement.title')
    class Meta:
        model = Post
        fields = ('id','title','rate','author','content','review','url','tags', 'fake','comments', 'created_at', 'anonymous','advertisement')
    # def create(self, validated_data):
    #     tag = validated_data.pop('advertisement')
    #     tag_instance, created =PostAdvertisment.objects.get_or_create(title=tag)
    #     article_instance = Post.objects.create(**validated_data, advertisement=tag_instance)
    #     return article_instance
    # def create(self, validated_data):
    #     serializer = self.get_serializer(data=self.request.data)
    #     advertisment =  self.request.data.pop('advertisement')
    #     company_instance = PostAdvertisment.objects.filter(id=advertisment).first()
    #     if not serializer.is_valid():
    #         print(serializer.errors)
    #     data = serializer.validated_data
    #     serializer.save(PostAdvertisment=company_instance)
    #     headers = self.get_success_headers(serializer.data)
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    def create(self,validated_data):
        advertisement=validated_data.pop('advertisement')

        post=  Post.objects.create(**validated_data)
        for advertise in advertisement:
            PostAdvertisment.object.create(**advertise)
        return post
</code>```

so the commented part of the code is something which  I've Tried
differnt appraoches gave me differnt kidn of error but none of them have worked

```<code>https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
</code>```

I've followeed this
but its no use when ever i try to post an object either that advertisment might be null or it gives me some kind of strange error depening  on the create method i have used

```<code>"advertisement":[]
this is what the error

{
    "advertisement": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got list."
        ]
    }
}
</code>```

when i changed it to {}

```<code>"advertisement": null
</code>```

but when i tried to give data to it

```<code>AttributeError at /api/post/
type object 'PostAdvertisment' has no attribute 'object'

Request Method: POST
Request URL: http://localhost:8000/api/post/
</code>```

im not sure how to add data to nested objects

答:
You missprinted, not PostAdvertisment.object.create(**advertise) but PostAdvertisment.objects.create(**advertise) you missed "s".
Advice you to read the error(traceback).</p>

Body:
models.py

class PostAdvertisment(models.Model):
    # post=models.ForeignKey(Post,on_delete=models.CASCADE,null=True,blank=True)
    created_at=models.DateTimeField(auto_now_add=True)
    title=models.CharField(max_length=255,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    advertizing_content= models.TextField(null =True ,blank=True)
    def __str__(self):
        return f'{self.title}'
class Post(models.Model):

    # created_at=models.DateTimeField(efault=datetime.now, blank=True)

    created_at=models.DateTimeField(auto_now_add=True)
    author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post")
    title=models.CharField(max_length=128,null=True,blank=True)
    rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True)

    # rating=models.IntegerField(null=True,blank=True)
    content=models.TextField(null=True,blank=True)
    review=models.CharField(max_length=250,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters")
    tags = TaggableManager(blank=True)
    comments=models.ManyToManyField('Comment',blank=True,related_name="comments_post")
    anonymous = models.BooleanField(default=False, blank=True)
    fake = models.BooleanField(default=False, blank=True)

    genuine = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_genuines")
    spam = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_spames")
    advertisement=models.ForeignKey(PostAdvertisment,on_delete=models.CASCADE,null=True,blank=True)

    def __str__(self):
        return f'{self.content}'
    def get_absolute_url(self):
        return reverse('post:post_detail' , kwargs={'post_id':Post.id})

so here is my serializers.py

class PostSerializer(TaggitSerializer,serializers.ModelSerializer):
    tags = TagListSerializerField()
    author = serializers.StringRelatedField(read_only=True)
    comments = CommentSerializer(many=True, required=False, read_only=True)
    # title = serializers.CharField()

    advertisement = PostAdvertisementSerializer()
    # advertisement = serializers.SlugRelatedField(
    #     queryset=PostAdvertisment.objects.all(),
    #     slug_field='advertisement'
    #      )
    # category_name = serializers.CharField(source='advertisement.title')
    class Meta:
        model = Post
        fields = ('id','title','rate','author','content','review','url','tags', 'fake','comments', 'created_at', 'anonymous','advertisement')
    # def create(self, validated_data):
    #     tag = validated_data.pop('advertisement')
    #     tag_instance, created =PostAdvertisment.objects.get_or_create(title=tag)
    #     article_instance = Post.objects.create(**validated_data, advertisement=tag_instance)
    #     return article_instance
    # def create(self, validated_data):
    #     serializer = self.get_serializer(data=self.request.data)
    #     advertisment =  self.request.data.pop('advertisement')
    #     company_instance = PostAdvertisment.objects.filter(id=advertisment).first()
    #     if not serializer.is_valid():
    #         print(serializer.errors)
    #     data = serializer.validated_data
    #     serializer.save(PostAdvertisment=company_instance)
    #     headers = self.get_success_headers(serializer.data)
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    def create(self,validated_data):
        advertisement=validated_data.pop('advertisement')

        post=  Post.objects.create(**validated_data)
        for advertise in advertisement:
            PostAdvertisment.object.create(**advertise)
        return post

so the commented part of the code is something which  I've Tried
differnt appraoches gave me differnt kidn of error but none of them have worked

https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

I've followeed this
but its no use when ever i try to post an object either that advertisment might be null or it gives me some kind of strange error depening  on the create method i have used

"advertisement":[]
this is what the error

{
    "advertisement": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got list."
        ]
    }
}

when i changed it to {}

"advertisement": null

but when i tried to give data to it

AttributeError at /api/post/
type object 'PostAdvertisment' has no attribute 'object'

Request Method: POST
Request URL: http://localhost:8000/api/post/

im not sure how to add data to nested objects


问:
Deploy existing Prestashop to server using Docker
I've created PrestaShop store on server. Is there any possible way to use docker for my store and migrate it into another server using docker? I know that I'll need docker-compose but to be honest I don't know what to do with files on current server.</p>

答:
You can use this docker-compose.yml :

```<code>version: "3"
services:
  prestashop:
    image: prestashop/prestashop
    networks:
      mycustomnetwork:
    ports:
      - 82:80
    links:
      - mariadb:mariadb
    depends_on:
      - mariadb
    volumes:
      - ./src:/var/www/html
      - ./src/modules:/var/www/html/modules
      - ./src/themes:/var/www/html/themes
      - ./src/override:/var/www/html/override
    environment:
      - PS_DEV_MODE=1
      - DB_SERVER=mariadb
      - DB_USER=root
      - DB_PASSWD=mycustompassword
      - DB_NAME=prestashop
      - PS_INSTALL_AUTO=0

  mariadb:
    image: mariadb
    networks:
      mycustomnetwork:
    volumes:
      - presta_db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=mycustompassword
      - MYSQL_DATABASE=prestashop

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    networks:
      mycustomnetwork:
    links:
      - mariadb:mariadb
    ports:
      - 1235:80
    depends_on:
      - mariadb
    environment:
      - PMA_HOST=mariadb
      - PMA_USER=root
      - PMA_PASSWORD=mycustompassword

volumes:
  presta_db:

networks:
  mycustomnetwork:
    external: true
</code>```

Replace mycustomnetwork and mycustompassword

Then run docker-compose up

Web url : localhost:82

PHP MyAdmin url : localhost:1235

Body:
You can use this docker-compose.yml :

version: "3"
services:
  prestashop:
    image: prestashop/prestashop
    networks:
      mycustomnetwork:
    ports:
      - 82:80
    links:
      - mariadb:mariadb
    depends_on:
      - mariadb
    volumes:
      - ./src:/var/www/html
      - ./src/modules:/var/www/html/modules
      - ./src/themes:/var/www/html/themes
      - ./src/override:/var/www/html/override
    environment:
      - PS_DEV_MODE=1
      - DB_SERVER=mariadb
      - DB_USER=root
      - DB_PASSWD=mycustompassword
      - DB_NAME=prestashop
      - PS_INSTALL_AUTO=0

  mariadb:
    image: mariadb
    networks:
      mycustomnetwork:
    volumes:
      - presta_db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=mycustompassword
      - MYSQL_DATABASE=prestashop

  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    networks:
      mycustomnetwork:
    links:
      - mariadb:mariadb
    ports:
      - 1235:80
    depends_on:
      - mariadb
    environment:
      - PMA_HOST=mariadb
      - PMA_USER=root
      - PMA_PASSWORD=mycustompassword

volumes:
  presta_db:

networks:
  mycustomnetwork:
    external: true

Replace mycustomnetwork and mycustompassword

Then run docker-compose up

Web url : localhost:82

PHP MyAdmin url : localhost:1235


问:
ProjectLocker and TortoiseGit
I am trying to setup ProjectLocker with TortoiseGit.
I have followed all the steps needed but keep getting the following error when I try to push to the remote server

Pushing to git-davidmz@pl3.projectlocker.com:gemscope.git

ERROR:gitosis.serve.main:Arguments to command look dangerous

fatal: The remote end hung up unexpectedly

I can't find what is wrong and hope someone can help me with the settings that are wrong.

P.S

I used this website
http://www.webupdate24.com/git-in-windows-with-tortoisegit-client-projectlocker-free-git-hosting.html

答:
I would recommend connecting from the bash command line to troubleshoot. TortoiseGit relies on msysgit to be installed underneath.

Further, use gitolite instead of gitosis as gitosis is no longer actively developed.

Your issue is probably with what key you are presenting and how you set up your admin repository.

Hope this helps.

Title: ProjectLocker and TortoiseGit


问:
Bullet gem not logging from Rails console
I am trying to use the Bullet gem to profile some mySql queries.  in config/environments/development.rb, I enable it:

```<code>config.after_initialize do
  Bullet.enable = true
  Bullet.bullet_logger = true
  Bullet.rails_logger = true
  Bullet.raise = true
end
</code>```

I then run a simple import command from the console:

```<code>Item.import_file "import/file1.txt"
</code>```

log/bullet.log is empty.  I see all of the mysql queries go by in the console, just no output.  Does bullet work in the Rails console?  If so, any idea what I'm doing wrong?

Thanks,
Kevin

答:
I think you need to call Bullet.profile:

  Bullet.profile { User.first.as_json } # or something
```

Body:
I am trying to use the Bullet gem to profile some mySql queries.  in config/environments/development.rb, I enable it:

config.after_initialize do
  Bullet.enable = true
  Bullet.bullet_logger = true
  Bullet.rails_logger = true
  Bullet.raise = true
end

I then run a simple import command from the console:

Item.import_file "import/file1.txt"

log/bullet.log is empty.  I see all of the mysql queries go by in the console, just no output.  Does bullet work in the Rails console?  If so, any idea what I'm doing wrong?

Thanks,
Kevin


问:
SwiftUI ScrollView stops working in ZStack under Rectangle with gradient
I'm having this issue where when I put a rectangle over a ScrollView with a gradient fill the scrollview stops reacting to touch.

The aim is to fade out items at the bottom of the scrollview so they don't clash with a custom bottom navigation view in the parent view.

I've tried to use a .frame modifier to make the fades height only the bottom quarter or so to hopefully stop blocking the scrollview but it didnt work.

Does anyone know a way around this?

```<code>import Foundation
import SwiftUI
import CoreData

struct TestView: View {

    var managedObjectContext:NSManagedObjectContext
    var spendings:FetchedResults<Spending>
    var expenses:FetchedResults<Expense>
    var settings:FetchedResults<Settings>
    @State private var showAddSpending:Bool = false

       @Binding var selection:Int

    var body: some View{
        VStack{
            HStack{
                Text("Spending").padding()

            }.padding(.horizontal)

            ZStack{

                //List items
                ScrollView{
                    ForEach(self.spendings) { spend in
                        //if(spend.currentMonth == true){
                        HStack{
                            // IS EXPANDED
                            if spend.isExpanded {

                                VStack{

                                    HStack{
                                        //NAME
                                        if(spend.currentMonth){
                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .foregroundColor(Color .orange)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        } else {

                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        }

                                        //AMOUNT
                                        Text("\(spend.amount)")

                                            .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                        //DELETE
                                        DeleteStyle(text: "multiply", symbol: true)
                                            .onTapGesture {
                                                self.managedObjectContext.delete(spend)
                                                do {
                                                    try self.managedObjectContext.save()
                                                }catch{
                                                    print(error)
                                                }
                                        }
                                    }
                                    VStack{

                                        //CATEGORY
                                        Text("Category: \(spend.category)")

                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)

                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            } else {

                                // ISNT EXPANDED
                                HStack{
                                    //NAME
                                    if(spend.currentMonth){
                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .foregroundColor(Color .orange)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }
                                    } else {

                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }

                                    }

                                    Spacer()

                                    //AMOUNT
                                    Text("\(spend.amount)")

                                        .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                    //DELETE
                                    DeleteStyle(text: "multiply", symbol: true).onTapGesture {
                                        self.managedObjectContext.delete(spend)
                                        do {
                                            try self.managedObjectContext.save()
                                        }catch{
                                            print(error)
                                        }
                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            }
                        }
                    }
                    .foregroundColor(Color (UIColor .secondaryLabel))
                }.padding(.horizontal)

                //Button to add new item
                VStack{
                    Spacer()
                    HStack{
                        Spacer()
                        /*
                         Text("Total: £\(calculateTotalSpendingForCurrentMonth())")
                         .foregroundColor(.white)
                         .padding(15)
                         .background(Color .orange)
                         .cornerRadius(40)
                         */
                        if spendings.isEmpty {
                            HStack{
                                Text("Record a spend")
                                Image(systemName: "arrow.right")
                            }
                            .foregroundColor(Color (UIColor .secondaryLabel))
                            .padding(.bottom, 90)
                            .padding(.horizontal, 40)
                        }
                        VStack{
                            Button(action: {
                                self.showAddSpending = true
                            }) {
                                NavStyle(text: "plus", symbol: true)

                            }.sheet(isPresented: $showAddSpending) {
                                AddSpendingView(managedObjectContext: self.managedObjectContext, spendings: self.spendings, expenses: self.expenses)
                            }

                        }

                    }

                }

                //Black Fade at bottom
                VStack{
                    Spacer()
                    Rectangle()
                        .fill (
                            LinearGradient(gradient: Gradient(colors: [.clear, .black]),
                                           startPoint: .center, endPoint: .bottom)
                    )
                }
            }
        }.background(Color (UIColor.secondarySystemBackground))
    }
}
</code>```

答:
Ideally this would be done using overlay to show a gradient on top of the scroll view with allowsHitTesting(false) so that the user can still scroll, but this currently doesn't work (which is possibly a SwiftUI bug).

But I was able to make this work using a ZStack and frame as you suggested. This is a drop-in replacement for ScrollView which includes an extra parameter fadeDistance which determines the height (for vertical scrolling) and/or the width (for horizontal scrolling) of the fade out effect:

```<code>struct FadingScrollView<Content: View>: View {
    let fadeDistance: CGFloat
    let axes: Axis.Set
    let showsIndicators: Bool
    let content: Content

    init(
        fadeDistance: CGFloat,
        _ axes: Axis.Set = .vertical,
        showsIndicators: Bool = true,
        @ViewBuilder content: () -> Content
    ) {
        self.fadeDistance = fadeDistance
        self.axes = axes
        self.showsIndicators = showsIndicators
        self.content = content()
    }

    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            ScrollView(axes, showsIndicators: showsIndicators) {
                // Pad the content depending on the axes so that bottom or trailing
                // part of the content isn't faded when scrolling all the way to the end.
                if axes == .vertical {
                    HStack(spacing: 0) {
                        content
                        Spacer()
                    }
                    Spacer(minLength: fadeDistance)
                } else if axes == .horizontal {
                    HStack(spacing: 0) {
                        VStack(spacing: 0) {
                            content
                            Spacer()
                        }
                        Spacer(minLength: fadeDistance)
                    }
                } else {
                    HStack(spacing: 0) {
                        content
                        Spacer(minLength: fadeDistance)
                    }
                    Spacer(minLength: fadeDistance)
                }
            }

            if axes.contains(.vertical) {
                fadeGradient(for: .vertical)
                    .frame(height: fadeDistance)
                    .allowsHitTesting(false) // Maybe Apple will make this work in the future
            }

            if axes.contains(.horizontal) {
                fadeGradient(for: .horizontal)
                    .frame(width: fadeDistance)
                    .allowsHitTesting(false) // Maybe Apple will make this work in the future
            }
        }
    }

    private func fadeGradient(for axis: Axis) -> some View {
        LinearGradient(
            gradient: Gradient(colors: [
                Color(.systemBackground).opacity(0),
                Color(.systemBackground).opacity(1)
            ]),
            startPoint: axis == .vertical ? .top : .leading,
            endPoint: axis == .vertical ? .bottom : .trailing
        )
    }
}
</code>```

Body:
I'm having this issue where when I put a rectangle over a ScrollView with a gradient fill the scrollview stops reacting to touch.

The aim is to fade out items at the bottom of the scrollview so they don't clash with a custom bottom navigation view in the parent view.

I've tried to use a .frame modifier to make the fades height only the bottom quarter or so to hopefully stop blocking the scrollview but it didnt work.

Does anyone know a way around this?

import Foundation
import SwiftUI
import CoreData

struct TestView: View {

    var managedObjectContext:NSManagedObjectContext
    var spendings:FetchedResults<Spending>
    var expenses:FetchedResults<Expense>
    var settings:FetchedResults<Settings>
    @State private var showAddSpending:Bool = false

       @Binding var selection:Int

    var body: some View{
        VStack{
            HStack{
                Text("Spending").padding()

            }.padding(.horizontal)

            ZStack{

                //List items
                ScrollView{
                    ForEach(self.spendings) { spend in
                        //if(spend.currentMonth == true){
                        HStack{
                            // IS EXPANDED
                            if spend.isExpanded {

                                VStack{

                                    HStack{
                                        //NAME
                                        if(spend.currentMonth){
                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .foregroundColor(Color .orange)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        } else {

                                            Text("\(spend.name)")
                                                .lineLimit(1)
                                                .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                                .onLongPressGesture {
                                                    spend.currentMonth.toggle()
                                            }
                                        }

                                        //AMOUNT
                                        Text("\(spend.amount)")

                                            .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                        //DELETE
                                        DeleteStyle(text: "multiply", symbol: true)
                                            .onTapGesture {
                                                self.managedObjectContext.delete(spend)
                                                do {
                                                    try self.managedObjectContext.save()
                                                }catch{
                                                    print(error)
                                                }
                                        }
                                    }
                                    VStack{

                                        //CATEGORY
                                        Text("Category: \(spend.category)")

                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)

                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            } else {

                                // ISNT EXPANDED
                                HStack{
                                    //NAME
                                    if(spend.currentMonth){
                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .foregroundColor(Color .orange)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }
                                    } else {

                                        Text("\(spend.name)")
                                            .lineLimit(1)
                                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                                            .onLongPressGesture {
                                                spend.currentMonth.toggle()
                                        }

                                    }

                                    Spacer()

                                    //AMOUNT
                                    Text("\(spend.amount)")

                                        .frame(minWidth: 0, maxWidth: 70, alignment: .trailing)

                                    //DELETE
                                    DeleteStyle(text: "multiply", symbol: true).onTapGesture {
                                        self.managedObjectContext.delete(spend)
                                        do {
                                            try self.managedObjectContext.save()
                                        }catch{
                                            print(error)
                                        }
                                    }
                                }

                                .onTapGesture {
                                    spend.isExpanded.toggle()
                                }

                            }
                        }
                    }
                    .foregroundColor(Color (UIColor .secondaryLabel))
                }.padding(.horizontal)

                //Button to add new item
                VStack{
                    Spacer()
                    HStack{
                        Spacer()
                        /*
                         Text("Total: £\(calculateTotalSpendingForCurrentMonth())")
                         .foregroundColor(.white)
                         .padding(15)
                         .background(Color .orange)
                         .cornerRadius(40)
                         */
                        if spendings.isEmpty {
                            HStack{
                                Text("Record a spend")
                                Image(systemName: "arrow.right")
                            }
                            .foregroundColor(Color (UIColor .secondaryLabel))
                            .padding(.bottom, 90)
                            .padding(.horizontal, 40)
                        }
                        VStack{
                            Button(action: {
                                self.showAddSpending = true
                            }) {
                                NavStyle(text: "plus", symbol: true)

                            }.sheet(isPresented: $showAddSpending) {
                                AddSpendingView(managedObjectContext: self.managedObjectContext, spendings: self.spendings, expenses: self.expenses)
                            }

                        }

                    }

                }

                //Black Fade at bottom
                VStack{
                    Spacer()
                    Rectangle()
                        .fill (
                            LinearGradient(gradient: Gradient(colors: [.clear, .black]),
                                           startPoint: .center, endPoint: .bottom)
                    )
                }
            }
        }.background(Color (UIColor.secondarySystemBackground))
    }
}

Body:
Ideally this would be done using overlay to show a gradient on top of the scroll view with allowsHitTesting(false) so that the user can still scroll, but this currently doesn't work (which is possibly a SwiftUI bug).

But I was able to make this work using a ZStack and frame as you suggested. This is a drop-in replacement for ScrollView which includes an extra parameter fadeDistance which determines the height (for vertical scrolling) and/or the width (for horizontal scrolling) of the fade out effect:

struct FadingScrollView<Content: View>: View {
    let fadeDistance: CGFloat
    let axes: Axis.Set
    let showsIndicators: Bool
    let content: Content

    init(
        fadeDistance: CGFloat,
        _ axes: Axis.Set = .vertical,
        showsIndicators: Bool = true,
        @ViewBuilder content: () -> Content
    ) {
        self.fadeDistance = fadeDistance
        self.axes = axes
        self.showsIndicators = showsIndicators
        self.content = content()
    }

    var body: some View {
        ZStack(alignment: .bottomTrailing) {
            ScrollView(axes, showsIndicators: showsIndicators) {
                // Pad the content depending on the axes so that bottom or trailing
                // part of the content isn't faded when scrolling all the way to the end.
                if axes == .vertical {
                    HStack(spacing: 0) {
                        content
                        Spacer()
                    }
                    Spacer(minLength: fadeDistance)
                } else if axes == .horizontal {
                    HStack(spacing: 0) {
                        VStack(spacing: 0) {
                            content
                            Spacer()
                        }
                        Spacer(minLength: fadeDistance)
                    }
                } else {
                    HStack(spacing: 0) {
                        content
                        Spacer(minLength: fadeDistance)
                    }
                    Spacer(minLength: fadeDistance)
                }
            }

            if axes.contains(.vertical) {
                fadeGradient(for: .vertical)
                    .frame(height: fadeDistance)
                    .allowsHitTesting(false) // Maybe Apple will make this work in the future
            }

            if axes.contains(.horizontal) {
                fadeGradient(for: .horizontal)
                    .frame(width: fadeDistance)
                    .allowsHitTesting(false) // Maybe Apple will make this work in the future
            }
        }
    }

    private func fadeGradient(for axis: Axis) -> some View {
        LinearGradient(
            gradient: Gradient(colors: [
                Color(.systemBackground).opacity(0),
                Color(.systemBackground).opacity(1)
            ]),
            startPoint: axis == .vertical ? .top : .leading,
            endPoint: axis == .vertical ? .bottom : .trailing
        )
    }
}


问:
Should Nginx and Flask run in the same container
The ideal is to have one process per container, but there is a strong affinity between Flask+uwsgi and Nginx.

Currently we run them together, but should we refactor ?

答:
Yes, it's a good idea to refactor. Try to make service ephemeral and run only one main process in it. So, in the end, you need to have something like this:

```<code>version: '3.4'
services:
  web:
    build:
      dockerfile: Dockerfile
      context: .
    ports:
      - 8000:8000
    volumes:
      - .:/app/
    env_file:
      - common.env
  nginx:
    restart: always
    image: nginx:1.18-alpine
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./deployment/nginx.conf:/etc/nginx/conf.d/default.conf
      - ./deployment/config.conf:/etc/nginx/nginx.conf
    command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\";'"
    depends_on:
      - web
</code>```

It's designed to have only one main process in a container, in that case if your application fails the container will be down.

Body:
Yes, it's a good idea to refactor. Try to make service ephemeral and run only one main process in it. So, in the end, you need to have something like this:

version: '3.4'
services:
  web:
    build:
      dockerfile: Dockerfile
      context: .
    ports:
      - 8000:8000
    volumes:
      - .:/app/
    env_file:
      - common.env
  nginx:
    restart: always
    image: nginx:1.18-alpine
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./deployment/nginx.conf:/etc/nginx/conf.d/default.conf
      - ./deployment/config.conf:/etc/nginx/nginx.conf
    command: "/bin/sh -c 'while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g \"daemon off;\";'"
    depends_on:
      - web

It's designed to have only one main process in a container, in that case if your application fails the container will be down.


问:
how to insert video path, video name in mysql database in php.?
I want to store video path and name in MySQL database but actually only stored the some fields information which i used in the form. and video stored the test upload folder

I have tried but video path(location) and name not store in database.

Here my code,

```<code><form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br><br>
<input type="button" value="Upload File" onclick="uploadFile()">
</form>
</code>```

Controller:

public function Insert_vedio()
{

```<code>$vedio_data=array(
 'title'=>$this->input->post('Title'),
 'v_name'=>$this->input->post('fileName'),
 );
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
    echo "$fileName upload is complete";
} else {
    echo "move_uploaded_file function failed";
}
</code>```

}

答:
Actually I have not mention Title and name in view part. Here My actual code. name is video file name, but don't understand how to give the vedio name.  </p>

```<code><form id="upload_form" enctype="multipart/form-data" method="post">
<div class="form-group">
     <label for="e1"> Title</label>
     <input type="text" placeholder="Movie Tile" name="Title" id="e1" class="form-control">

     <input type="file" name="file1" id="file1"><br><br>
     <input type="button" value="Upload File" onclick="uploadFile()">
     <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
     <h6 id="status" style="color:red"></h6>
     <p id="loaded_n_total"></p>

    <div class="osahan-area text-center mt-3">
        <button class="btn btn-outline-primary">Save Changes</button>
    </div>
  </div>
</form>
</code>```

Body:
I want to store video path and name in MySQL database but actually only stored the some fields information which i used in the form. and video stored the test upload folder

I have tried but video path(location) and name not store in database.

Here my code,

<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1">

<input type="button" value="Upload File" onclick="uploadFile()">
</form>

Controller:

public function Insert_vedio()
{

$vedio_data=array(
 'title'=>$this->input->post('Title'),
 'v_name'=>$this->input->post('fileName'),
 );
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
    echo "$fileName upload is complete";
} else {
    echo "move_uploaded_file function failed";
}

}

Body:
Actually I have not mention Title and name in view part. Here My actual code. name is video file name, but don't understand how to give the vedio name.

<form id="upload_form" enctype="multipart/form-data" method="post">
<div class="form-group">
     <label for="e1"> Title</label>
     <input type="text" placeholder="Movie Tile" name="Title" id="e1" class="form-control">

     <input type="file" name="file1" id="file1"><br><br>
     <input type="button" value="Upload File" onclick="uploadFile()">
     <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
     <h6 id="status" style="color:red"></h6>
     <p id="loaded_n_total"></p>

    <div class="osahan-area text-center mt-3">
        <button class="btn btn-outline-primary">Save Changes</button>
    </div>
  </div>
</form>


问:
Hyperlink on bars in ChartJS in react
I am using chartjs-2 in react functional component (please find the code here: https://codesandbox.io/s/elastic-brook-okkce?file=/src/Dashboard.jsx)

I have rendered 4 bars here and I want to have a specific handler function defined for onClick event on each bar.
Like there are 4 types in the bar labels and on clicking on each bar I want to display something specific to the type of the bar clicked.
How to implement this?

```<code>function Dashboard(props) {
  const classes = useStyles();
  const [data, setdata] = React.useState({
    labels: ["type1", "type2", "type3", "type4"],
    datasets: [
      {
        label: "text that comes on hover",
        backgroundColor: [
          //................................................colors of the bars............
          "#3e95cd",
          "#8e5ea2",
          "#3cba9f",
          "#e8c3b9",
          "#c45850"
        ],
        barThickness: 80,
        data: [50, 100, 75, 20, 0] //......................values for each bar...........
      }
    ]
  });

  const getChartData = canvas => {
    return data;
  };
  return (
    <React.Fragment>
      <div
        className={classes.chart}
        style={{ position: "relative", width: 900, height: 450 }}
      >
        <Bar
          options={{
            responsive: true,
            maintainAspectRatio: true,
            legend: { display: false },
            title: {
              display: true,
              text: "Title for the graph"
            }
          }}
          data={getChartData}
        />
      </div>
    </React.Fragment>
  );
}

export default Dashboard;
</code>```

答:
You can use onElementsClick. Please check the below code:

```<code><Bar
    options={{
        responsive: true,
        maintainAspectRatio: true,
        legend: {display: false},
        title: {
            display: true,
            text: "Title for the graph"
        }
    }}
    onElementsClick={(e) => {
        console.log(e, 'e')
    }}
    data={getChartData}
/>
</code>```

Title: Hyperlink on bars in ChartJS in react

Body:
I am using chartjs-2 in react functional component (please find the code here: https://codesandbox.io/s/elastic-brook-okkce?file=/src/Dashboard.jsx)

I have rendered 4 bars here and I want to have a specific handler function defined for onClick event on each bar.
Like there are 4 types in the bar labels and on clicking on each bar I want to display something specific to the type of the bar clicked.
How to implement this?

function Dashboard(props) {
  const classes = useStyles();
  const [data, setdata] = React.useState({
    labels: ["type1", "type2", "type3", "type4"],
    datasets: [
      {
        label: "text that comes on hover",
        backgroundColor: [
          //................................................colors of the bars............
          "#3e95cd",
          "#8e5ea2",
          "#3cba9f",
          "#e8c3b9",
          "#c45850"
        ],
        barThickness: 80,
        data: [50, 100, 75, 20, 0] //......................values for each bar...........
      }
    ]
  });

  const getChartData = canvas => {
    return data;
  };
  return (
    <React.Fragment>

        <Bar
          options={{
            responsive: true,
            maintainAspectRatio: true,
            legend: { display: false },
            title: {
              display: true,
              text: "Title for the graph"
            }
          }}
          data={getChartData}
        />

    </React.Fragment>
  );
}

export default Dashboard;

Body:
You can use onElementsClick. Please check the below code:

<Bar
    options={{
        responsive: true,
        maintainAspectRatio: true,
        legend: {display: false},
        title: {
            display: true,
            text: "Title for the graph"
        }
    }}
    onElementsClick={(e) => {
        console.log(e, 'e')
    }}
    data={getChartData}
/>


问:
Use jQuery to auto select text inside a span tag when clicked
I have a div which contains a series of span tags, each containing a string of text. I'd like to attach a jQuery click event to all of the spans so that when the text inside any span is clicked, the entire line of text (dom > innerText object) will be auto selected to facilitate the drag/drop or copy/paste of the text string.

For example, my content is...

```<code><div id="mySpans">
  <span> This is my text </span>
  <span> This is my text </span>
</div>
</code>```

If the cursor is clicked on any text inside a span, I want to select the text within that span, so that it can be drag/dropped (without the span tags, just the innerText of the span) as a copy.

Does jQuery have an easy means to do this?

EDIT: A more detailed explanation of what I'm trying to accomplish:

Without aid of script, in order to copy a block of text, the user has to manually drag select a selection rectangle across the text block. The text then becomes selected signaling that a click & drag event will pick up all of the selected text. So I'm trying to create script that allows a single click on the text to automatically select the text for the user so they don't have to manually do it themselves.

答:
use DOM ranges: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html</p>

```<code>var span = ...
var range = document.createRange();
range.setStartBefore(span.firstChild);
range.setEndAfter(span.lastChild);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a div which contains a series of span tags, each containing a string of text. I'd like to attach a jQuery click event to all of the spans so that when the text inside any span is clicked, the entire line of text (dom > innerText object) will be auto selected to facilitate the drag/drop or copy/paste of the text string.

For example, my content is...

   This is my text
   This is my text

If the cursor is clicked on any text inside a span, I want to select the text within that span, so that it can be drag/dropped (without the span tags, just the innerText of the span) as a copy.

Does jQuery have an easy means to do this?

EDIT: A more detailed explanation of what I'm trying to accomplish:

Without aid of script, in order to copy a block of text, the user has to manually drag select a selection rectangle across the text block. The text then becomes selected signaling that a click & drag event will pick up all of the selected text. So I'm trying to create script that allows a single click on the text to automatically select the text for the user so they don't have to manually do it themselves.

Body:
use DOM ranges: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html

var span = ...
var range = document.createRange();
range.setStartBefore(span.firstChild);
range.setEndAfter(span.lastChild);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);


问:
Bootstrap 4 Split Navbar - Responsive Dropdown Below not Beside
I have a navbar with a split dropdown. The particular portion of the HTML I'm interested in is this:

```<code>         <li class="nav-item">
            <div class="btn-group">
                <a href="http://www.bhastings.com/blog" target="_blank" class="nav-link">Blog</a>
                <a class="nav-link dropdown-toggle dropdown-toggle-split" id="dropdownMenuLink_blog" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <span class="sr-only">Toggle Dropdown for Blog Links</span>
                </a>
                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuLink_blog">
                      <div class="dropdown-header">Categories | <a href="http://bhastings.com/blog" target="_blank" style="color: #bc5b16;">Blog Main</a></div>
                      <a class="dropdown-item" href="http://bhastings.com/blog?cat=20" target="_blank"><small><em>Articles for Everyone</em></small></a>
                      <a class="dropdown-item" href="http://bhastings.com/blog?cat=8" target="_blank"><small><em>Access to Justice Commentary</em></small></a>
                      <a class="dropdown-item" href="http://bhastings.com/blog?cat=5" target="_blank"><small><em>Law Commentary</em></small></a>
                      <a class="dropdown-item" href="http://bhastings.com/blog?cat=6" target="_blank"><small><em>Legal Futurism</em></small></a>
                      <a class="dropdown-item" href="http://bhastings.com/blog?cat=4" target="_blank"><small><em>Resources for Lawyers</em></small></a>
                      <a class="dropdown-item" href="http://bhastings.com/blog?cat=36" target="_blank"><small><em>Technology</em></small></a>
                </div>
            </div>
          </li>
</code>```

And the entire navbar looks like this:

```<code><nav class="navbar navbar-toggleable-sm fixed-top">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <i class="fa fa-bars fa-lg" aria-hidden="true"></i>
  </button>
  <a class="navbar-brand" href="#home">Brandon D. Hastings<small class="hidden-md-down"> BBA(Dist.), JD</small></a>
  <div class="navbar-collapse collapse" id="navbarNavDropdown">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#about">About<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#law">Law</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#technology">Technology</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#media">Media</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink_more" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">More</a>
        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink_more">
          <a class="dropdown-item" href="#miscinfo">More About Me</a>
          <div class="dropdown-divider"></div>
          <div class="dropdown-header"><em>New Tab / Window</em></div>
          <a class="dropdown-item" href="http://(bitly not allowed)/BHastings_CV" target="_blank">Curriculum Vitae</a>
          <a class="dropdown-item" href="http://bhastings.com/blog/category/resources-for-lawyers/" target="_blank">Resources for Lawyers</a>
        </div>
      </li>
      <li class="nav-item">
        <div class="btn-group">
            <a href="http://www.bhastings.com/blog" target="_blank" class="nav-link">Blog</a>
            <a class="nav-link dropdown-toggle dropdown-toggle-split" id="dropdownMenuLink_blog" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <span class="sr-only">Toggle Dropdown for Blog Links</span>
            </a>
            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuLink_blog">
                  <div class="dropdown-header">Categories | <a href="http://bhastings.com/blog" target="_blank" style="color: #bc5b16;">Blog Main</a></div>
                  <a class="dropdown-item" href="http://bhastings.com/blog?cat=20" target="_blank"><small><em>Articles for Everyone</em></small></a>
                  <a class="dropdown-item" href="http://bhastings.com/blog?cat=8" target="_blank"><small><em>Access to Justice Commentary</em></small></a>
                  <a class="dropdown-item" href="http://bhastings.com/blog?cat=5" target="_blank"><small><em>Law Commentary</em></small></a>
                  <a class="dropdown-item" href="http://bhastings.com/blog?cat=6" target="_blank"><small><em>Legal Futurism</em></small></a>
                  <a class="dropdown-item" href="http://bhastings.com/blog?cat=4" target="_blank"><small><em>Resources for Lawyers</em></small></a>
                  <a class="dropdown-item" href="http://bhastings.com/blog?cat=36" target="_blank"><small><em>Technology</em></small></a>
            </div>
        </div>
      </li>
      <li class="nav-item btn btn-danger btn-sm">
        <a class="nav-link text-white url-firm" href="http://www.quaylawcentre.com/Lawyer-Profiles/Brandon-Hastings-B-b-a-dist-j-d.shtml" target="_blank">Get in Touch<span class="sr-only"></span></a>
      </li>
    </ul>
  </div>
</nav>
</code>```

The result is something like this in small screens:

Having a split link in a navbar is a bit hacky to begin with, but notwithstanding that, I'm wondering if anyone knows a way to get the dropdown to pop back "in line" so that it looks more like the "More" dropdown:

?

Thanks in advance! :)

答:
Just add container class in the btn-group div.
The misalignment is because of the btn-group class is defined as flex item. Try adding container class, it may solve the issue.

       Blog

       Toggle Dropdown for Blog Links

Categories | Blog Main

          Articles for Everyone
          Access to Justice Commentary
          Law Commentary
          Legal Futurism
          Resources for Lawyers
          Technology

```

Body:
I have a navbar with a split dropdown. The particular portion of the HTML I'm interested in is this:

                Blog

                    Toggle Dropdown for Blog Links

Categories | Blog Main

                      Articles for Everyone
                      Access to Justice Commentary
                      Law Commentary
                      Legal Futurism
                      Resources for Lawyers
                      Technology

And the entire navbar looks like this:

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Brandon D. Hastings BBA(Dist.), JD

        About(current)

        Law

        Technology

        Media

        More

          More About Me

New Tab / Window

          Curriculum Vitae
          Resources for Lawyers

            Blog

                Toggle Dropdown for Blog Links

Categories | Blog Main

                  Articles for Everyone
                  Access to Justice Commentary
                  Law Commentary
                  Legal Futurism
                  Resources for Lawyers
                  Technology

        Get in Touch

The result is something like this in small screens:

Having a split link in a navbar is a bit hacky to begin with, but notwithstanding that, I'm wondering if anyone knows a way to get the dropdown to pop back "in line" so that it looks more like the "More" dropdown:

?

Thanks in advance! :)

Body:
Just add container class in the btn-group div.
The misalignment is because of the btn-group class is defined as flex item. Try adding container class, it may solve the issue.

    <div class="container p-0 btn-group">
       <a href="http://www.bhastings.com/blog" target="_blank" class="nav-link">Blog</a>
       <a class="nav-link dropdown-toggle dropdown-toggle-split" id="dropdownMenuLink_blog" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
       <span class="sr-only">Toggle Dropdown for Blog Links</span>
       </a>
       <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuLink_blog">
          <div class="dropdown-header">Categories | <a href="http://bhastings.com/blog" target="_blank" style="color: #bc5b16;">Blog Main</a></div>
          <a class="dropdown-item" href="http://bhastings.com/blog?cat=20" target="_blank"><small><em>Articles for Everyone</em></small></a>
          <a class="dropdown-item" href="http://bhastings.com/blog?cat=8" target="_blank"><small><em>Access to Justice Commentary</em></small></a>
          <a class="dropdown-item" href="http://bhastings.com/blog?cat=5" target="_blank"><small><em>Law Commentary</em></small></a>
          <a class="dropdown-item" href="http://bhastings.com/blog?cat=6" target="_blank"><small><em>Legal Futurism</em></small></a>
          <a class="dropdown-item" href="http://bhastings.com/blog?cat=4" target="_blank"><small><em>Resources for Lawyers</em></small></a>
          <a class="dropdown-item" href="http://bhastings.com/blog?cat=36" target="_blank"><small><em>Technology</em></small></a>
       </div>
    </div>


问:
C# play Spotify Uri
I am trying to create a music player using the Spotify api.
The main functionality is therefore to play music.
Thanks to the API I get the spotify URI of the music I want to play but I don't know how to play this music from the URI.
Thanks</p>

答:
This isn't exactly a supported Feature of Spotify.

A few things to consider:

The API Documentation

The Web Player SDK

You could try to use the Web API to get a token, and the data you need such as the URL.
Once you have this, you could embed a browser in your app to act as the player. Perhaps with something like CefSharp even. The WinForm, WPF, or whatever UI you provide could then use the API to/ Web Player to send the correct on the fly commands to control / play the music.

Title: C# play Spotify Uri


问:
How do I remove accents from characters in a PHP string?
I'm attempting to remove accents from characters in PHP string as the first step to making the string usable in a URL.

I'm using the following code:

```<code>$input = "Fóø Bår";

setlocale(LC_ALL, "en_US.utf8");
$output = iconv("utf-8", "ascii//TRANSLIT", $input);

print($output);
</code>```

The output I would expect would be something like this:

```<code>F'oo Bar
</code>```

However, instead of the accented characters being transliterated they are replaced with question marks:

```<code>F?? B?r
</code>```

Everything I can find online indicates that setting the locale will fix this problem, however I'm already doing this.  I've already checked the following details:

The locale I am setting is supported by the server (included in the list produced by locale -a)

The source and target encodings (UTF-8 and ASCII) are supported by the server's version of iconv (included in the list produced by iconv -l)

The input string is UTF-8 encoded (verified using PHP's mb_check_encoding function, as suggested in the answer by mercator)

The call to setlocale is successful (it returns 'en_US.utf8' rather than FALSE)

The cause of the problem:

The server is using the wrong implementation of iconv.  It has the glibc version instead of the required libiconv version.

Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the GNU libiconv library. It will most likely end up with more consistent results.

  – PHP manual's introduction to iconv

Details about the iconv implementation that is used by PHP are included in the output of the phpinfo function.

(I'm not able to re-compile PHP with the correct iconv library on the server I'm working with for this project so the answer I've accepted below is the one that was most useful for removing accents without iconv support.)

答:
What's wrong with this one? Works with UTF8

```<code>function strip_accents($s){
  return str_replace(
    explode(' ', preg_replace('/ +/', ' ', 'č ć ž š đ  Č Ć Ž Š Đ  à á â ã ä ç è é ê ë ì í î ï ñ ò ó ô õ ö ù ú û ü ý ÿ À Á Â Ã Ä Ç È É Ê Ë Ì Í Î Ï Ñ Ò Ó Ô Õ Ö Ù Ú Û Ü Ý')),
    explode(' ', preg_replace('/ +/', ' ', 'c c z s dj C C Z S DJ a a a a a c e e e e i i i i n o o o o o u u u u y y A A A A A C E E E E I I I I N O O O O O U U U U Y')),
    $s);
}
</code>```

It can be faster by not using preg_replace, but speed was not my goal here.

Body:
I'm attempting to remove accents from characters in PHP string as the first step to making the string usable in a URL.

I'm using the following code:

$input = "Fóø Bår";

setlocale(LC_ALL, "en_US.utf8");
$output = iconv("utf-8", "ascii//TRANSLIT", $input);

print($output);

The output I would expect would be something like this:

F'oo Bar

However, instead of the accented characters being transliterated they are replaced with question marks:

F?? B?r

Everything I can find online indicates that setting the locale will fix this problem, however I'm already doing this.  I've already checked the following details:

The locale I am setting is supported by the server (included in the list produced by locale -a)

The source and target encodings (UTF-8 and ASCII) are supported by the server's version of iconv (included in the list produced by iconv -l)

The input string is UTF-8 encoded (verified using PHP's mb_check_encoding function, as suggested in the answer by mercator)

The call to setlocale is successful (it returns 'en_US.utf8' rather than FALSE)

The cause of the problem:

The server is using the wrong implementation of iconv.  It has the glibc version instead of the required libiconv version.

Note that the iconv function on some systems may not work as you expect. In such case, it'd be a good idea to install the GNU libiconv library. It will most likely end up with more consistent results.

  – PHP manual's introduction to iconv

Details about the iconv implementation that is used by PHP are included in the output of the phpinfo function.

(I'm not able to re-compile PHP with the correct iconv library on the server I'm working with for this project so the answer I've accepted below is the one that was most useful for removing accents without iconv support.)

Body:
What's wrong with this one? Works with UTF8

function strip_accents($s){
  return str_replace(
    explode(' ', preg_replace('/ +/', ' ', 'č ć ž š đ  Č Ć Ž Š Đ  à á â ã ä ç è é ê ë ì í î ï ñ ò ó ô õ ö ù ú û ü ý ÿ À Á Â Ã Ä Ç È É Ê Ë Ì Í Î Ï Ñ Ò Ó Ô Õ Ö Ù Ú Û Ü Ý')),
    explode(' ', preg_replace('/ +/', ' ', 'c c z s dj C C Z S DJ a a a a a c e e e e i i i i n o o o o o u u u u y y A A A A A C E E E E I I I I N O O O O O U U U U Y')),
    $s);
}

It can be faster by not using preg_replace, but speed was not my goal here.


问:
Here-api TransitRadius for intermediate waypoints
I'm using a following request to calculate a driving route. What is the correct syntax for specifying the transit radius? For some reason the transit radius isn't honoured for the intermediate waypoint (waypoint1) while working correctly for the final waypoint.

https://route.api.here.com/routing/7.2/calculateroute.json?app_id={appId&app_code={appCode}&waypoint0=geo!50.035035,19.925015;1500&waypoint1=geo!50.06684315082262,19.923276861182046;1500&waypoint2=geo!50.07842990411413,20.032238457351923;1500&mode=fastest;car;traffic:enabled&arrival=2020-05-29T17:27:42.000Z&routeAttributes=shape

I've done an experiment comparison with and without requesting a transfer radius. It seems to be honoured for start and endpoints only.

答:
I sent the same request using the routing v7 and authenticated with the APIKEY and I am not getting a loop, but the route leaves the highway, to access the park gate and then comes back onto the highway. I am not able to recreate the loop that you are getting.

Call used

https://route.ls.hereapi.com/routing/7.2/calculateroute.json?xnlp=CL_JSMv3.1.16.1&apikey=&waypoint0=50.035035%2C19.925015%3B1500&waypoint1=50.06684315082262%2C19.923276861182046&waypoint2=50.07842990411413%2C20.032238457351923%3B1500&mode=fastest%3Bcar%3Btraffic%3Aenabled&arrival=2020-05-29T17%3A27%3A42.000Z&routeAttributes=shape&representation=display```


问:
Upload a file in admin and then download from the website Django
I am trying to create a website, where customer can upload a file in an Admin section, and after any person can download this file from the website. Preferably any files like pdf, exe, doc (is it possible?) I am able to upload a file in Admin and it shows it on the website. It downloads the file with a correct name (saved in media) but shows a failure , file missing.

So far I have :

setting.py

```<code>STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'
</code>```

models.py

```<code>class TEACHING(models.Model):

    title = models.CharField(max_length=100)

    content = models.TextField()

    date_posted = models.DateTimeField(auto_now_add=True)

    excercise = models.FileField(upload_to="files/", default='default value')

    def __str__(self):

        return self.title
</code>```

views.py

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

    context = { 'teaches' : TEACHING.objects.all()}

    return render(request, 'blog/teaching.html', context)
</code>```

urls.py

```<code>if settings.DEBUG:

    urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
</code>```

teaching.html

```<code>{% for teach in teaches %}
    <a href="{{ teach.excercise }}" download>Download</a>
{% endfor %}
</code>```

答:
Managing files docs

You should get URL from your File field

```<code><a href="{{ teach.excercise.url }}" download>Download</a>
</code>```

Body:
I am trying to create a website, where customer can upload a file in an Admin section, and after any person can download this file from the website. Preferably any files like pdf, exe, doc (is it possible?) I am able to upload a file in Admin and it shows it on the website. It downloads the file with a correct name (saved in media) but shows a failure , file missing.

So far I have :

setting.py

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

models.py

class TEACHING(models.Model):

    title = models.CharField(max_length=100)

    content = models.TextField()

    date_posted = models.DateTimeField(auto_now_add=True)

    excercise = models.FileField(upload_to="files/", default='default value')

    def __str__(self):

        return self.title

views.py

def teaching(request):

    context = { 'teaches' : TEACHING.objects.all()}

    return render(request, 'blog/teaching.html', context)

urls.py

if settings.DEBUG:

    urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)

    urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

teaching.html

{% for teach in teaches %}
    Download
{% endfor %}

Body:
Managing files docs

You should get URL from your File field

<a href="{{ teach.excercise.url }}" download>Download</a>


问:
How to get these rows from many to many table, which contains 0 in exact column?
```<code>a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 11
6| 15 | 0
7| 15 | 234
8| 14 | 0
</code>```

So I want to return only these a_id which all rows in b_id are 0. In this case it would be a_id = 14.

```<code>a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 0
6| 15 | 0
7| 15 | 0
8| 14 | 0
</code>```

In second case it would be 14 and 15

What I tried:

```<code>select a_id
from id_table
group by a_id
having max(b_id) > 0
</code>```

答:
You can use aggregation, and filter with a having clause:

```<code>select a_id
from mytable
group by a_id
having max(b_id) = 0
</code>```

This assumes no negative value in b_id. Otherwise you could do:

```<code>having max(b_id <> 0) = 0

</code>```

Body:
a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 11
6| 15 | 0
7| 15 | 234
8| 14 | 0

So I want to return only these a_id which all rows in b_id are 0. In this case it would be a_id = 14.

a|a_id|b_id
1| 13 | 0
2| 14 | 0
3| 13 | 57
4| 13 | 0
5| 15 | 0
6| 15 | 0
7| 15 | 0
8| 14 | 0

In second case it would be 14 and 15

What I tried:

select a_id
from id_table
group by a_id
having max(b_id) > 0

Body:
You can use aggregation, and filter with a having clause:

select a_id
from mytable
group by a_id
having max(b_id) = 0

This assumes no negative value in b_id. Otherwise you could do:

having max(b_id <> 0) = 0


问:
PUT Request working with Angular but with Postman/Insomnia it returns 401
So a while back I was able to create login, register, edit user and get all users functions. These worked fine as I was able to register a user. Login them in and then also edit those credentials. Of course some JWT tokens were used for authentication. I used an API call on Postman to edit current users:
PUT Request

This worked fine until recently where even if I add the Bearer token unto the Authorization header, I still get a "401 Unauthorized" error. This also happens when I use Insomnia to try the same request. I am using Angular as the front-end and its service(s) is still working fine as I am able to both login and register users. Whilst in postman/insomnia I am only able to login and get the bearer token. All other POST/GET requests linked to the  /users/ no longer work.

Other GET requests work fine and return a 200 response.

This is the output from a PUT request:

```<code>PUT /users/11 HTTP/1.1
</code>```

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjkiLCJuYmYiOjE1OTA2NTUxMjcsImV4cCI6MTU5MTI1OTkyNywiaWF0IjoxNTkwNjU1MTI3fQ.eYd4oUpE7i4PXByt2aUI-4OGCl0N_vGCmaBgib28uTQ

Content-Type: application/json

User-Agent: PostmanRuntime/7.25.0

Accept: /

Cache-Control: no-cache

Postman-Token: cea6f9a6-46bb-41b1-a711-7fc1f8886858

Host: localhost:5000

Accept-Encoding: gzip, deflate, br

Connection: keep-alive

Content-Length: 29

{
    "Password": "Eskimo_321"
}

HTTP/1.1 401 Unauthorized

Transfer-Encoding: chunked

Server: Microsoft-IIS/10.0

WWW-Authenticate: Bearer

X-Powered-By: ASP.NET

Date: Thu, 28 May 2020 09:38:10 GMT

答:
Found the issue, had rebuilt my project and had forgotten to add:

```<code>app.UseAuthentication();
</code>```

on the Startup.cs file. All the routes needed authorization except the Login and register routes.

Body:
So a while back I was able to create login, register, edit user and get all users functions. These worked fine as I was able to register a user. Login them in and then also edit those credentials. Of course some JWT tokens were used for authentication. I used an API call on Postman to edit current users:
PUT Request

This worked fine until recently where even if I add the Bearer token unto the Authorization header, I still get a "401 Unauthorized" error. This also happens when I use Insomnia to try the same request. I am using Angular as the front-end and its service(s) is still working fine as I am able to both login and register users. Whilst in postman/insomnia I am only able to login and get the bearer token. All other POST/GET requests linked to the  /users/ no longer work.

Other GET requests work fine and return a 200 response.

This is the output from a PUT request:

PUT /users/11 HTTP/1.1

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjkiLCJuYmYiOjE1OTA2NTUxMjcsImV4cCI6MTU5MTI1OTkyNywiaWF0IjoxNTkwNjU1MTI3fQ.eYd4oUpE7i4PXByt2aUI-4OGCl0N_vGCmaBgib28uTQ

Content-Type: application/json

User-Agent: PostmanRuntime/7.25.0

Accept: /

Cache-Control: no-cache

Postman-Token: cea6f9a6-46bb-41b1-a711-7fc1f8886858

Host: localhost:5000

Accept-Encoding: gzip, deflate, br

Connection: keep-alive

Content-Length: 29

{
    "Password": "Eskimo_321"
}

HTTP/1.1 401 Unauthorized

Transfer-Encoding: chunked

Server: Microsoft-IIS/10.0

WWW-Authenticate: Bearer

X-Powered-By: ASP.NET

Date: Thu, 28 May 2020 09:38:10 GMT

Body:
Found the issue, had rebuilt my project and had forgotten to add:

app.UseAuthentication();

on the Startup.cs file. All the routes needed authorization except the Login and register routes.


问:
Padding missing on one side of scrollable div
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="moh">
    <div></div>
</div></code>```

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

答:
#moh
    {
    background:red;
    overflow-x:auto;
    width:100px;
    padding:5px;
}

#moh div
{
    /* width:500px; */
    height:50px;
    background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>

</head>

<body>
<div id="moh">
    <div></div>
</div>
</html></code>```

The padding on the right hand side doesn't appear because, the total width of the parent div is 100px(width) + 10px(padding) while the width for the chid div is explicitly set to 500px.

Since the chid div is a block level element and width property greater than that of the parent, it will move past the parent element and hide the right border from the parent div.

Solutions

either remove the width attribute in the child div (so it will take full width of the parent)

or set the width of the parent to at least 500px which is the width of the child element

Body:
Take a look at my snippet.
The parent div has a scrollbar and a child div.
Why is the padding (5px) missing on the right side?

#moh
{
  background:red;
  overflow-x:auto;
  width:100px;
  padding:5px; // this padding should be on all 4 sides
}

#moh div
{
  width:500px;
  height:50px;
  background:green;
}

To get the bounty I want to know the reason for the missing padding. Maybe there is a name for this phenomenon. Or may it be a browser bug?

It would be excellent to know the part in the CSS or HTML specification which is responsible for the missing padding. But this is not required to get the bounty (Because I know it's hard to find).

Body:
#moh
    {
    background:red;
    overflow-x:auto;
    width:100px;
    padding:5px;
}

#moh div
{
    /* width:500px; */
    height:50px;
    background:green;
}

<html>
<head>

</head>

<body>
<div id="moh">
    <div></div>
</div>
</html>

The padding on the right hand side doesn't appear because, the total width of the parent div is 100px(width) + 10px(padding) while the width for the chid div is explicitly set to 500px.

Since the chid div is a block level element and width property greater than that of the parent, it will move past the parent element and hide the right border from the parent div.

Solutions

either remove the width attribute in the child div (so it will take full width of the parent)

or set the width of the parent to at least 500px which is the width of the child element


问:
Javascript overwrite certain object keys
So, i have an object, for example

```<code>let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "home",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "gold",
                    "href": "contact"
                }
            }
        }
    };
</code>```

And i have a second object:

```<code>let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                },
                2: {
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };
</code>```

Now i want to update the first object keys that exist in the second object. So the object looks like this:

```<code>let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };
</code>```

What is the easiest way of aproaching this problem?
Thanks in advance,
Jari

答:
You can achieve this in different ways, one approach could be to loop for each buttons and merge them with Object.assign().

Here's a rough example, keys from objectA will be preserved and updated (merged) with the values of the corresponding keys from objectB (new key's letter will be added) :

// Initial values.
var objectA = {
  0: {
    a: "A0",
    b: "B0",
    c: "C0"
  },
  1: {
    a: "A1",
    c: "C1",
    d: "D1"
  },
  2: {
    b: "B2"
  },
  3: {
    d: "D3",
    e: "E3",
    f: "F3"
  },
};

// Update values.
var objectB = {
  1: {
    a: "A1(updated)",
    b: "B1(added)",
    c: "C1(updated)"
  },
  2: {
    a: "A2(added)",
    b: "B2(updated)",
    c: "C2(added)"
  },
  3: {
    a: "A3",
    c: "C3",
    d: "D3(updated)"
  },
  10: {
    z: "Z10"
  },
  11: {
    y: "Y11"
  },
};

/**
 * Update one object values with the values of an other object.
 */
function updateObjectValues(obj1, obj2) {
  for (var key in obj1) {
    // Skip key from obj2 that is not in obj1.
    if (!obj2.hasOwnProperty(key)) continue;

    // Update (merge) the key object from obj1 with obj2.
    obj1[key] = Object.assign(obj1[key], obj2[key]);
  }
}

updateObjectValues(objectA, objectB);

console.info(objectA);```

Body:
So, i have an object, for example

let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "home",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "gold",
                    "href": "contact"
                }
            }
        }
    };

And i have a second object:

let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                },
                2: {
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };

Now i want to update the first object keys that exist in the second object. So the object looks like this:

let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };

What is the easiest way of aproaching this problem?
Thanks in advance,
Jari