问:
Django rest framework error AssertionError `child` is a required argument
when developing my application I ran into a problem

```<code>AssertionError at /api/update/
`child` is a required argument.
Request Method: GET
Request URL:    http://45.56.80.77/api/update/?token=1234567&ifloorplan=2
Django Version: 3.0.6
Exception Type: AssertionError
Exception Value:
`child` is a required argument.
Exception Location: /root/Env/ifloorplan/lib/python3.8/site-packages/rest_framework/serializers.py in __init__, line 591
Python Executable:  /usr/local/bin/uwsgi
Python Version: 3.8.2
Python Path:
['.',
 '',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/root/Env/ifloorplan/lib/python3.8/site-packages']
Server time:    Mon, 1 Jun 2020 07:18:31 +0000
</code>```

that is, I tried to update and create in the database a record of this kind

```<code>[
    {
        "id": 2,
        "level": [
            {
                "id": 2,
                "plan_level": {
                    "img": null,
                    "img_height": null,
                    "img_width": null,
                    "position_x": null,
                    "position_y": null,
                    "level": null
                },
                "images": [
                    {
                        "id": 2,
                        "cam": [
                            {
                                "id": 2,
                                "ken_burns": {
                                    "effect": null,
                                    "start_pos_x": null,
                                    "start_pos_y": null,
                                    "finish_pos_x": null,
                                    "finish_pos_y": null,
                                    "start_width": null,
                                    "start_height": null,
                                    "finish_width": null,
                                    "finish_height": null,
                                    "cam": null
                                },
                                "rotation": 0.34,
                                "pos_x": 21.0,
                                "pos_y": 234.0,
                                "width": 1234.0,
                                "height": 234.0,
                                "img": 2
                            },
                            {
                                "id": 3,
                                "ken_burns": {
                                    "effect": null,
                                    "start_pos_x": null,
                                    "start_pos_y": null,
                                    "finish_pos_x": null,
                                    "finish_pos_y": null,
                                    "start_width": null,
                                    "start_height": null,
                                    "finish_width": null,
                                    "finish_height": null,
                                    "cam": null
                                },
                                "rotation": 4.0,
                                "pos_x": 354.0,
                                "pos_y": 345.0,
                                "width": 345.0,
                                "height": 345.0,
                                "img": 2
                            }
                        ],
                        "img": "/media/ifloorplans_source/test.jpg",
                        "level": 2
                    }
                ],
                "tabLabel": "1 st",
                "plan": 2
            }
        ],
        "textColor": "WQ2123",
        "bgColor": "SA2132",
        "camColor": "CV1234",
        "author": 14
    }
]
</code>```

here is my serializer.py

```<code>from django.contrib.auth.models import User
from .models import (
    IFloorPlan,
    Level,
    PlanImg,
    Image,
    Cam,
    KenBurns,

)
from rest_framework import serializers

class KenBurnsSerializer(serializers.ListSerializer):
    # plan = IFloorPlanSerializer(required=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [KenBurns(**item) for item in validated_data]
        return KenBurns.objects.bulk_create(predictions)

    class Meta:
        model = KenBurns
        fields = '__all__'

class CamSerializer(serializers.ListSerializer):
    ken_burns = KenBurnsSerializer()

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [Cam(**item) for item in validated_data]
        return Cam.objects.bulk_create(predictions)

    class Meta:
        model = Cam
        fields = '__all__'

class ImageSerializer(serializers.ListSerializer):
    cam = CamSerializer(many=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [Image(**item) for item in validated_data]
        return Image.objects.bulk_create(predictions)

    class Meta:
        model = Image
        fields = '__all__'

class PlanImgSerializer(serializers.ListSerializer):
    # plan = IFloorPlanSerializer(required=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [PlanImg(**item) for item in validated_data]
        return PlanImg.objects.bulk_create(predictions)

    class Meta:
        model = PlanImg
        fields = '__all__'

class LevelSerializer(serializers.ListSerializer):
    plan_level = PlanImgSerializer()
    images = ImageSerializer(many=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [Level(**item) for item in validated_data]
        return Level.objects.bulk_create(predictions)

    class Meta:
        model = Level
        fields = '__all__'

class IFloorPlanSerializer(serializers.Serializer):
    level = LevelSerializer(many=True)

    class Meta:
        list_serializer_class = LevelSerializer
        model = IFloorPlan
        fields = '__all__'

</code>```

views.py

```<code>from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import IFloorPlanSerializer
from rest_framework.views import APIView
from .models import IFloorPlan
from public.models import ApiToken
# Create your views here.

@api_view(['GET', ])
def get_ifloorplan(request):
    if "token" in request.GET and "ifloorplan" in request.GET:
        token_obj = ApiToken.objects.filter(token=request.GET["token"])
        if token_obj:
            plans = IFloorPlan.objects.filter(id=request.GET["ifloorplan"])
            serializer = IFloorPlanSerializer(plans, many=True)
            return Response(serializer.data)
        else:
            return JsonResponse({"message": "Don't valid token"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({"message": "Don't valid GET parameter"}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PUT', 'GET',])
def update_ifloorplan(request):
    if "token" in request.GET and "ifloorplan" in request.GET:
        token_obj = ApiToken.objects.filter(token=request.GET["token"])
        if token_obj:
            plans = IFloorPlan.objects.filter(id=request.GET["ifloorplan"])
            serializer = IFloorPlanSerializer(plans, data=request.data, many=True)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({"message": "Update successful"}, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return JsonResponse({"message": "Don't valid token"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({"message": "Don't valid GET parameter"}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST', 'GET'])
def create_ifloorplan(request):
    if "token" in request.GET:
        token_obj = ApiToken.objects.get(token=request.GET["token"])
        if token_obj:
            plans = IFloorPlan(author=token_obj.user)
            serializer = IFloorPlanSerializer(plans, data=request.data, many=True)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({"message": "Create successful"}, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return JsonResponse({"message": "Don't valid token"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({"message": "Don't valid GET parameter"}, status=status.HTTP_400_BAD_REQUEST)

</code>```

models.py

```<code>from django.db import models
from django.contrib.auth.models import User

class IFloorPlan(models.Model):
    textColor = models.CharField(max_length=10, blank=True, null=True)
    bgColor = models.CharField(max_length=10, blank=True, null=True)
    camColor = models.CharField(max_length=10, blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

class Level(models.Model):
    plan = models.ForeignKey(IFloorPlan, on_delete=models.CASCADE, related_name='level', blank=True, null=True)
    tabLabel = models.CharField(max_length=100, blank=True, null=True)

class PlanImg(models.Model):
    level = models.ForeignKey(Level, on_delete=models.CASCADE, related_name='plan_level', blank=True, null=True)
    img = models.ImageField(upload_to='ifloorplans_source/', blank=True, null=True)
    img_height = models.FloatField(blank=True, null=True)
    img_width = models.FloatField(blank=True, null=True)
    position_x = models.FloatField(blank=True, null=True)
    position_y = models.FloatField(blank=True, null=True)

class Image(models.Model):
    level = models.ForeignKey(Level, on_delete=models.CASCADE, related_name='images', blank=True, null=True)
    img = models.ImageField(upload_to='ifloorplans_source/', blank=True, null=True)

class Cam(models.Model):
    rotation = models.FloatField(blank=True, null=True)
    pos_x = models.FloatField(blank=True, null=True)
    pos_y = models.FloatField(blank=True, null=True)
    img = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='cam', blank=True, null=True)
    width = models.FloatField(blank=True, null=True)
    height = models.FloatField(blank=True, null=True)

class KenBurns(models.Model):
    cam = models.ForeignKey(Cam, on_delete=models.CASCADE, related_name='ken_burns', blank=True, null=True)
    effect = models.BooleanField(default=False, blank=True, null=True)
    start_pos_x = models.FloatField(blank=True, null=True)
    start_pos_y = models.FloatField(blank=True, null=True)
    finish_pos_x = models.FloatField(blank=True, null=True)
    finish_pos_y = models.FloatField(blank=True, null=True)
    start_width = models.FloatField(blank=True, null=True)
    start_height = models.FloatField(blank=True, null=True)
    finish_width = models.FloatField(blank=True, null=True)
    finish_height = models.FloatField(blank=True, null=True)

</code>```

I can’t solve this problem already the second day
At first there was a problem with the inability to update multiple tables. So I decided to use the list serializer to update and create records in the table. I will be glad of any help

答:
A ListSerializer is basically a container for other serializers and can only contain one specific serializer, which is set as it's "child" serializer.

Your LevelSerializer extends ListSerializer but does not provide a this child attribute. This is typically not the way to use a ListSerializer - extending it is only needed for very special cases. In the common case, you want create a normal serializer for the Level model and set it as a field with many=True as argument. This will create a list serializer under the hood as described in in the documentation

You make the mistake several times, but this should get you started in the right direction:

class LevelSerializer(serializers.ModelSerializer)
    class Meta:
        model = Level
        fields = ('plan', 'tabLabel')

class IFloorPlanSerializer(serializers.Serializer):
    level = LevelSerializer(many=True)
```

<p>To extend the list serializer and provide a custom update method:</p>

```class LevelListSerializer(serializers.ListSerializer):
    child = LevelSerializer()

    def update(self, instance, validated_data):
        # instance is the queryset, validated_data a list of dicts
        # See [the documentation](https://github.com/encode/django-rest-framework/blob/master/docs/api-guide/serializers.md#customizing-multiple-update) for an example.

class IFloorPlanSerializer(serializers.Serializer):
    level = LevelListSerializer()
```

Body:
when developing my application I ran into a problem

AssertionError at /api/update/
`child` is a required argument.
Request Method: GET
Request URL:    http://45.56.80.77/api/update/?token=1234567&ifloorplan=2
Django Version: 3.0.6
Exception Type: AssertionError
Exception Value:
`child` is a required argument.
Exception Location: /root/Env/ifloorplan/lib/python3.8/site-packages/rest_framework/serializers.py in __init__, line 591
Python Executable:  /usr/local/bin/uwsgi
Python Version: 3.8.2
Python Path:
['.',
 '',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/root/Env/ifloorplan/lib/python3.8/site-packages']
Server time:    Mon, 1 Jun 2020 07:18:31 +0000

that is, I tried to update and create in the database a record of this kind

[
    {
        "id": 2,
        "level": [
            {
                "id": 2,
                "plan_level": {
                    "img": null,
                    "img_height": null,
                    "img_width": null,
                    "position_x": null,
                    "position_y": null,
                    "level": null
                },
                "images": [
                    {
                        "id": 2,
                        "cam": [
                            {
                                "id": 2,
                                "ken_burns": {
                                    "effect": null,
                                    "start_pos_x": null,
                                    "start_pos_y": null,
                                    "finish_pos_x": null,
                                    "finish_pos_y": null,
                                    "start_width": null,
                                    "start_height": null,
                                    "finish_width": null,
                                    "finish_height": null,
                                    "cam": null
                                },
                                "rotation": 0.34,
                                "pos_x": 21.0,
                                "pos_y": 234.0,
                                "width": 1234.0,
                                "height": 234.0,
                                "img": 2
                            },
                            {
                                "id": 3,
                                "ken_burns": {
                                    "effect": null,
                                    "start_pos_x": null,
                                    "start_pos_y": null,
                                    "finish_pos_x": null,
                                    "finish_pos_y": null,
                                    "start_width": null,
                                    "start_height": null,
                                    "finish_width": null,
                                    "finish_height": null,
                                    "cam": null
                                },
                                "rotation": 4.0,
                                "pos_x": 354.0,
                                "pos_y": 345.0,
                                "width": 345.0,
                                "height": 345.0,
                                "img": 2
                            }
                        ],
                        "img": "/media/ifloorplans_source/test.jpg",
                        "level": 2
                    }
                ],
                "tabLabel": "1 st",
                "plan": 2
            }
        ],
        "textColor": "WQ2123",
        "bgColor": "SA2132",
        "camColor": "CV1234",
        "author": 14
    }
]

here is my serializer.py

from django.contrib.auth.models import User
from .models import (
    IFloorPlan,
    Level,
    PlanImg,
    Image,
    Cam,
    KenBurns,

)
from rest_framework import serializers

class KenBurnsSerializer(serializers.ListSerializer):
    # plan = IFloorPlanSerializer(required=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [KenBurns(**item) for item in validated_data]
        return KenBurns.objects.bulk_create(predictions)

    class Meta:
        model = KenBurns
        fields = '__all__'

class CamSerializer(serializers.ListSerializer):
    ken_burns = KenBurnsSerializer()

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [Cam(**item) for item in validated_data]
        return Cam.objects.bulk_create(predictions)

    class Meta:
        model = Cam
        fields = '__all__'

class ImageSerializer(serializers.ListSerializer):
    cam = CamSerializer(many=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [Image(**item) for item in validated_data]
        return Image.objects.bulk_create(predictions)

    class Meta:
        model = Image
        fields = '__all__'

class PlanImgSerializer(serializers.ListSerializer):
    # plan = IFloorPlanSerializer(required=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [PlanImg(**item) for item in validated_data]
        return PlanImg.objects.bulk_create(predictions)

    class Meta:
        model = PlanImg
        fields = '__all__'

class LevelSerializer(serializers.ListSerializer):
    plan_level = PlanImgSerializer()
    images = ImageSerializer(many=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        predictions = [Level(**item) for item in validated_data]
        return Level.objects.bulk_create(predictions)

    class Meta:
        model = Level
        fields = '__all__'

class IFloorPlanSerializer(serializers.Serializer):
    level = LevelSerializer(many=True)

    class Meta:
        list_serializer_class = LevelSerializer
        model = IFloorPlan
        fields = '__all__'

views.py

from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import IFloorPlanSerializer
from rest_framework.views import APIView
from .models import IFloorPlan
from public.models import ApiToken
# Create your views here.

@api_view(['GET', ])
def get_ifloorplan(request):
    if "token" in request.GET and "ifloorplan" in request.GET:
        token_obj = ApiToken.objects.filter(token=request.GET["token"])
        if token_obj:
            plans = IFloorPlan.objects.filter(id=request.GET["ifloorplan"])
            serializer = IFloorPlanSerializer(plans, many=True)
            return Response(serializer.data)
        else:
            return JsonResponse({"message": "Don't valid token"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({"message": "Don't valid GET parameter"}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['PUT', 'GET',])
def update_ifloorplan(request):
    if "token" in request.GET and "ifloorplan" in request.GET:
        token_obj = ApiToken.objects.filter(token=request.GET["token"])
        if token_obj:
            plans = IFloorPlan.objects.filter(id=request.GET["ifloorplan"])
            serializer = IFloorPlanSerializer(plans, data=request.data, many=True)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({"message": "Update successful"}, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return JsonResponse({"message": "Don't valid token"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({"message": "Don't valid GET parameter"}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST', 'GET'])
def create_ifloorplan(request):
    if "token" in request.GET:
        token_obj = ApiToken.objects.get(token=request.GET["token"])
        if token_obj:
            plans = IFloorPlan(author=token_obj.user)
            serializer = IFloorPlanSerializer(plans, data=request.data, many=True)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse({"message": "Create successful"}, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        else:
            return JsonResponse({"message": "Don't valid token"}, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({"message": "Don't valid GET parameter"}, status=status.HTTP_400_BAD_REQUEST)

models.py

from django.db import models
from django.contrib.auth.models import User

class IFloorPlan(models.Model):
    textColor = models.CharField(max_length=10, blank=True, null=True)
    bgColor = models.CharField(max_length=10, blank=True, null=True)
    camColor = models.CharField(max_length=10, blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

class Level(models.Model):
    plan = models.ForeignKey(IFloorPlan, on_delete=models.CASCADE, related_name='level', blank=True, null=True)
    tabLabel = models.CharField(max_length=100, blank=True, null=True)

class PlanImg(models.Model):
    level = models.ForeignKey(Level, on_delete=models.CASCADE, related_name='plan_level', blank=True, null=True)
    img = models.ImageField(upload_to='ifloorplans_source/', blank=True, null=True)
    img_height = models.FloatField(blank=True, null=True)
    img_width = models.FloatField(blank=True, null=True)
    position_x = models.FloatField(blank=True, null=True)
    position_y = models.FloatField(blank=True, null=True)

class Image(models.Model):
    level = models.ForeignKey(Level, on_delete=models.CASCADE, related_name='images', blank=True, null=True)
    img = models.ImageField(upload_to='ifloorplans_source/', blank=True, null=True)

class Cam(models.Model):
    rotation = models.FloatField(blank=True, null=True)
    pos_x = models.FloatField(blank=True, null=True)
    pos_y = models.FloatField(blank=True, null=True)
    img = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='cam', blank=True, null=True)
    width = models.FloatField(blank=True, null=True)
    height = models.FloatField(blank=True, null=True)

class KenBurns(models.Model):
    cam = models.ForeignKey(Cam, on_delete=models.CASCADE, related_name='ken_burns', blank=True, null=True)
    effect = models.BooleanField(default=False, blank=True, null=True)
    start_pos_x = models.FloatField(blank=True, null=True)
    start_pos_y = models.FloatField(blank=True, null=True)
    finish_pos_x = models.FloatField(blank=True, null=True)
    finish_pos_y = models.FloatField(blank=True, null=True)
    start_width = models.FloatField(blank=True, null=True)
    start_height = models.FloatField(blank=True, null=True)
    finish_width = models.FloatField(blank=True, null=True)
    finish_height = models.FloatField(blank=True, null=True)

I can’t solve this problem already the second day
At first there was a problem with the inability to update multiple tables. So I decided to use the list serializer to update and create records in the table. I will be glad of any help

Body:
A ListSerializer is basically a container for other serializers and can only contain one specific serializer, which is set as it's "child" serializer.

Your LevelSerializer extends ListSerializer but does not provide a this child attribute. This is typically not the way to use a ListSerializer - extending it is only needed for very special cases. In the common case, you want create a normal serializer for the Level model and set it as a field with many=True as argument. This will create a list serializer under the hood as described in in the documentation

You make the mistake several times, but this should get you started in the right direction:

class LevelSerializer(serializers.ModelSerializer)
    class Meta:
        model = Level
        fields = ('plan', 'tabLabel')

class IFloorPlanSerializer(serializers.Serializer):
    level = LevelSerializer(many=True)

To extend the list serializer and provide a custom update method:

class LevelListSerializer(serializers.ListSerializer):
    child = LevelSerializer()

    def update(self, instance, validated_data):
        # instance is the queryset, validated_data a list of dicts
        # See [the documentation](https://github.com/encode/django-rest-framework/blob/master/docs/api-guide/serializers.md#customizing-multiple-update) for an example.

class IFloorPlanSerializer(serializers.Serializer):
    level = LevelListSerializer()


来源: stackexchange

问:
Random float value is repeating
I'm trying to get my code to recreate a random x and y value if there is already another object occupying the chosen value. But for some reason, the loop just keeps giving me the same float value causing it to loop forever instead of creating new value and then checking that one against previous x and y variables. Here's the code. Let me know if you need anymore.</p>

```<code>static int numberOfDots = 5;
static int windowSize = 400;

float[] pos = new float[2];
float[] vel = new float[2];
float[] acc = new float[2];
float dotSize = 0;
float dotMass = 0;
float dotWidth = 0;
float dotRadius = 0;
float[] centrePos = new float[2];

float[][] dots = new float[numberOfDots][10];

//for making dots
boolean first = true;
boolean creationCollision = false;
boolean dotCollision = false;

// pos means x and y positions
// vel means x and y velocity
// centrePos means centre of the dot x and y
// dotMass isnt implemented yet
    public boolean collisionOnCreate() {
        //compare all dots
        for (int i = 0; i < dots.length; i++) {
            //against any dots later in the array
            // since they will already have compared themselves to dots previous in the array
            // - dont need to loop over them again
            for (int a = i + 1; a < dots.length; a++) {
                if (dots[a][0] != 0) {
                    creationCollision = dots[i][1] + dots[i][8] > dots[a][1] && dots[i][1] + dots[i][8] < dots[a][1] + dots[a][8] || dots[i][1] > dots[a][1] && dots[i][1] < dots[a][1] + dots[a][8] || dots[i][0] > dots[a][0] && dots[i][0] < dots[a][0] + dots[a][8] || dots[i][0] + dots[i][8] > dots[a][0] && dots[i][0] + dots[i][8] < dots[a][0] + dots[a][8];
                    System.out.println(dots[a][0] + " " + dots[a][1]);
                }
                //check if the left-most part of the dot is anywhere between the leftmost and right most part of another dot
                //check if the rightmost part of the dot is anywhere between the left most and right most part of another dot
                //check if the top part of the dot is anywhere between the top and bottom part of another dot
                //check if the bottom of the dot is anywhere between the top and bottom part of another dot
                // I know its long but its easier then running a bunch of if statements to do the same task
            }
        }
        return creationCollision;
    }

    public void createDots(int i) {
        pos[0] = r.nextFloat() * 300;
        pos[1] = r.nextFloat() * 300;
        dotWidth = r.nextFloat() * 30;
        if (dotWidth < 5) {
            dotWidth *= 10;
        }
        dotRadius = dotWidth / 2;
        dotMass = r.nextFloat() / 10;
        centrePos[0] = centrePos[0] + dotRadius;
        centrePos[1] = pos[1] + dotRadius;
        vel[0] = r.nextFloat() / 10;
        vel[1] = r.nextFloat() / 10;
        check(i);
    }

    public void check(int i) {
        collisionOnCreate();
        if (creationCollision) {
            createDots(i);
            System.out.println("collision on creation");
        } else {
            setValues(i);
            System.out.println("dot number " + i + " is created");
        }
    }

    public void setValues(int i) {
        dots[i][0] = pos[0];
        dots[i][1] = pos[1];
        dots[i][2] = vel[0];
        dots[i][3] = vel[1];
        dots[i][4] = dotRadius;
        dots[i][5] = centrePos[0];
        dots[i][6] = centrePos[1];
        dots[i][7] = dotMass;
        dots[i][8] = dotWidth;
    }

    //create an array of dots and assign them values for x, y, radius, etc.
    public float[][] Dots() {
        if (first == true) {
            for (int i = 0; i < numberOfDots; i++) {
                    createDots(i);
            }
            first = false;
        } else {
            for (int i = 0; i < numberOfDots; i++) {
                // update values
                dots[i][0] = dots[i][0] + dots[i][2];
                dots[i][1] = dots[i][1] + dots[i][3];
                centrePos[0] = dots[i][0] + dots[i][4];
                centrePos[1] = dots[i][1] + dots[i][4];
                dots[i][5] = centrePos[0];
                dots[i][6] = centrePos[1];
                collisionOnWall(i);
            }
        }
        repaint();
        return dots;
    }
</code>```

答:
I don't think the problem is with random number generation. Instead there is something wrong with the logic of creation / checking.

It seems that first, inside of createDots(), you assign values to some variables that are meant to represent a new dot (why don't make a dedicated class for that?). Then you don't add that new dot to dots array but instead you go straight to checking if there are any collisions.

However, you only check the values that are already present in the dots array, without taking into account the newly created one.

Another thing, that creationCollision condition is really unreadable to me. You should use some parentheses just for the clarity. Plus make sure it is actually doing what you want it to.

ContentLicense: CC BY-SA 4.0

Title: Random float value is repeating

Body:
I'm trying to get my code to recreate a random x and y value if there is already another object occupying the chosen value. But for some reason, the loop just keeps giving me the same float value causing it to loop forever instead of creating new value and then checking that one against previous x and y variables. Here's the code. Let me know if you need anymore.

static int numberOfDots = 5;
static int windowSize = 400;

float[] pos = new float[2];
float[] vel = new float[2];
float[] acc = new float[2];
float dotSize = 0;
float dotMass = 0;
float dotWidth = 0;
float dotRadius = 0;
float[] centrePos = new float[2];

float[][] dots = new float[numberOfDots][10];

//for making dots
boolean first = true;
boolean creationCollision = false;
boolean dotCollision = false;

// pos means x and y positions
// vel means x and y velocity
// centrePos means centre of the dot x and y
// dotMass isnt implemented yet
    public boolean collisionOnCreate() {
        //compare all dots
        for (int i = 0; i < dots.length; i++) {
            //against any dots later in the array
            // since they will already have compared themselves to dots previous in the array
            // - dont need to loop over them again
            for (int a = i + 1; a < dots.length; a++) {
                if (dots[a][0] != 0) {
                    creationCollision = dots[i][1] + dots[i][8] > dots[a][1] && dots[i][1] + dots[i][8] < dots[a][1] + dots[a][8] || dots[i][1] > dots[a][1] && dots[i][1] < dots[a][1] + dots[a][8] || dots[i][0] > dots[a][0] && dots[i][0] < dots[a][0] + dots[a][8] || dots[i][0] + dots[i][8] > dots[a][0] && dots[i][0] + dots[i][8] < dots[a][0] + dots[a][8];
                    System.out.println(dots[a][0] + " " + dots[a][1]);
                }
                //check if the left-most part of the dot is anywhere between the leftmost and right most part of another dot
                //check if the rightmost part of the dot is anywhere between the left most and right most part of another dot
                //check if the top part of the dot is anywhere between the top and bottom part of another dot
                //check if the bottom of the dot is anywhere between the top and bottom part of another dot
                // I know its long but its easier then running a bunch of if statements to do the same task
            }
        }
        return creationCollision;
    }

    public void createDots(int i) {
        pos[0] = r.nextFloat() * 300;
        pos[1] = r.nextFloat() * 300;
        dotWidth = r.nextFloat() * 30;
        if (dotWidth < 5) {
            dotWidth *= 10;
        }
        dotRadius = dotWidth / 2;
        dotMass = r.nextFloat() / 10;
        centrePos[0] = centrePos[0] + dotRadius;
        centrePos[1] = pos[1] + dotRadius;
        vel[0] = r.nextFloat() / 10;
        vel[1] = r.nextFloat() / 10;
        check(i);
    }

    public void check(int i) {
        collisionOnCreate();
        if (creationCollision) {
            createDots(i);
            System.out.println("collision on creation");
        } else {
            setValues(i);
            System.out.println("dot number " + i + " is created");
        }
    }

    public void setValues(int i) {
        dots[i][0] = pos[0];
        dots[i][1] = pos[1];
        dots[i][2] = vel[0];
        dots[i][3] = vel[1];
        dots[i][4] = dotRadius;
        dots[i][5] = centrePos[0];
        dots[i][6] = centrePos[1];
        dots[i][7] = dotMass;
        dots[i][8] = dotWidth;
    }

    //create an array of dots and assign them values for x, y, radius, etc.
    public float[][] Dots() {
        if (first == true) {
            for (int i = 0; i < numberOfDots; i++) {
                    createDots(i);
            }
            first = false;
        } else {
            for (int i = 0; i < numberOfDots; i++) {
                // update values
                dots[i][0] = dots[i][0] + dots[i][2];
                dots[i][1] = dots[i][1] + dots[i][3];
                centrePos[0] = dots[i][0] + dots[i][4];
                centrePos[1] = dots[i][1] + dots[i][4];
                dots[i][5] = centrePos[0];
                dots[i][6] = centrePos[1];
                collisionOnWall(i);
            }
        }
        repaint();
        return dots;
    }


问:
Optimisation of badly performing Linq query in C#
I got the following function, _Context is a databaseContext and Users is a table in the database.

The database consists of ~1 million entries. The Guid of the table Users is indexed (see code shown below).

How can I optimize GetUserByGuid so that it returns faster? As of now it can take up to a minute to return an answer, which is way too slow.

```<code>public void GetUserByGuid(string guid, int page, DateTime from, DateTime to)
{
    var users = _Context.Users
                        .Where(x => x.Guid.Equals(guid) &&
                                    (DateTime.Compare(from.Date, x.TimeDone.Date) <= 0) &&
                                    (DateTime.Compare(x.TimeDone.Date, to.Date) <= 0))
                        .OrderByDescending(x => x.TimeDone)
                        .Skip(page * 10)
                        .Take(10)
                        .ToList();
}
</code>```

The Users table is created as follows:

```<code>CREATE TABLE [dbo].[Users]
(
    [Id]       INT IDENTITY (1, 1) NOT NULL,
    [TimeDone] DATETIME NOT NULL,
    [Guid]     CHAR(64) NOT NULL
);
GO

CREATE NONCLUSTERED INDEX [IX_TimeDone]
ON [dbo].[Users]([TimeDone] ASC) WITH (FILLFACTOR = 90);
GO

CREATE NONCLUSTERED INDEX [IX_Guid]
ON [dbo].[Users]([Guid] ASC) WITH (FILLFACTOR = 90);
</code>```

答:
Not sure that EF core can translate DateTime.Compare into SQL (and if not an you are using EF Core before 3.0 version it will fetch all the data into memory and will perform all operations on the client side) and you don't need it to compare datetimes in your EF query, just compare them directly, to handle the date part only for toDate add one day and use exclusive comparison:

```<code>var fromDate = from.Date;
var toDate = to.Date.AddDays(1);
var users = _Context.Users.Where(x => x.Guid.Equals(guid) &&
                            (from.Date <= x.TimeDone) &&
                            (x.TimeDone < to.Date))
                            .OrderByDescending(x => x.TimeDone)
                            .Skip(page * 10)
                            .Take(10)
                            .ToList();
</code>```

Or use DbFunctions.DateDiffDay:

```<code>DbFunctions.DateDiffDay(from, x.TimeDone) >= 0
&& DbFunctions.DateDiffDay(x.TimeDone, to) >= 0 // if I have not messed the comparison order
</code>```

Body:
I got the following function, _Context is a databaseContext and Users is a table in the database.

The database consists of ~1 million entries. The Guid of the table Users is indexed (see code shown below).

How can I optimize GetUserByGuid so that it returns faster? As of now it can take up to a minute to return an answer, which is way too slow.

public void GetUserByGuid(string guid, int page, DateTime from, DateTime to)
{
    var users = _Context.Users
                        .Where(x => x.Guid.Equals(guid) &&
                                    (DateTime.Compare(from.Date, x.TimeDone.Date) <= 0) &&
                                    (DateTime.Compare(x.TimeDone.Date, to.Date) <= 0))
                        .OrderByDescending(x => x.TimeDone)
                        .Skip(page * 10)
                        .Take(10)
                        .ToList();
}

The Users table is created as follows:

CREATE TABLE [dbo].[Users]
(
    [Id]       INT IDENTITY (1, 1) NOT NULL,
    [TimeDone] DATETIME NOT NULL,
    [Guid]     CHAR(64) NOT NULL
);
GO

CREATE NONCLUSTERED INDEX [IX_TimeDone]
ON [dbo].[Users]([TimeDone] ASC) WITH (FILLFACTOR = 90);
GO

CREATE NONCLUSTERED INDEX [IX_Guid]
ON [dbo].[Users]([Guid] ASC) WITH (FILLFACTOR = 90);

Body:
Not sure that EF core can translate DateTime.Compare into SQL (and if not an you are using EF Core before 3.0 version it will fetch all the data into memory and will perform all operations on the client side) and you don't need it to compare datetimes in your EF query, just compare them directly, to handle the date part only for toDate add one day and use exclusive comparison:

var fromDate = from.Date;
var toDate = to.Date.AddDays(1);
var users = _Context.Users.Where(x => x.Guid.Equals(guid) &&
                            (from.Date <= x.TimeDone) &&
                            (x.TimeDone < to.Date))
                            .OrderByDescending(x => x.TimeDone)
                            .Skip(page * 10)
                            .Take(10)
                            .ToList();

Or use DbFunctions.DateDiffDay:

DbFunctions.DateDiffDay(from, x.TimeDone) >= 0
&& DbFunctions.DateDiffDay(x.TimeDone, to) >= 0 // if I have not messed the comparison order


问:
How can I allow ctrl+a with TextBox in winform?
I'm asking the question already asked (and even answered) here:
Why are some textboxes not accepting Control + A shortcut to select all by default

But that answer doesn't work for me. I have this code:

```<code>public class LoginForm : Form
{
    private TextBox tbUsername;

    public LoginForm()
    {
        tbUsername = new TextBox();
        tbUsername.ShortcutsEnabled = true;
        tbUsername.Multiline = false;
        Controls.Add(tbUsername);
    }
}
</code>```

The textbox shows up, I can write on it, I can cut, copy and paste text on it without any problems.
But when I try to press Ctrl+A I only hear a "bling" similar to the bling that you hear if you try to erase text from an empty textbox (try it with your browser's address bar).

答:
This is my code, it is working fine  </p>

```<code>private void mainSimPlus_KeyDown(object sender, KeyEventArgs e)
            {
                e.Handled = true;
                if (e.Control == true && e.KeyCode == Keys.A)
                {
                    if (SelectAllTextBox(txt1))
                        return;
                    if (SelectAllTextBox(txt2))
                        return;
                }
            }
            private bool SelectAllTextBox(TextBox txt)
            {
                if (txt.Focused)
                {
                    txt.SelectAll();
                    return true;
                }
                else
                    return false;
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm asking the question already asked (and even answered) here:
Why are some textboxes not accepting Control + A shortcut to select all by default

But that answer doesn't work for me. I have this code:

public class LoginForm : Form
{
    private TextBox tbUsername;

    public LoginForm()
    {
        tbUsername = new TextBox();
        tbUsername.ShortcutsEnabled = true;
        tbUsername.Multiline = false;
        Controls.Add(tbUsername);
    }
}

The textbox shows up, I can write on it, I can cut, copy and paste text on it without any problems.
But when I try to press Ctrl+A I only hear a "bling" similar to the bling that you hear if you try to erase text from an empty textbox (try it with your browser's address bar).

Body:
This is my code, it is working fine

private void mainSimPlus_KeyDown(object sender, KeyEventArgs e)
            {
                e.Handled = true;
                if (e.Control == true && e.KeyCode == Keys.A)
                {
                    if (SelectAllTextBox(txt1))
                        return;
                    if (SelectAllTextBox(txt2))
                        return;
                }
            }
            private bool SelectAllTextBox(TextBox txt)
            {
                if (txt.Focused)
                {
                    txt.SelectAll();
                    return true;
                }
                else
                    return false;
            }


问:
Clojure function not returning a map
I am new to Clojure and functional programming. I have a basic idea about the data structures in Clojure such as maps, lists, and vectors.

I am trying to write a function that returns a nested map. The map is correctly displayed inside the function. The below code is from the read-customer-file function

```<code>([input-list new-map place-holder]
        (if (not-empty input-list)
            (do
                (def string-input (str (first input-list)))
                (def cust-id (get (first input-list) 0))
                (def cust-name (get (first input-list) 1))
                (def cust-address (get (first input-list) 2))
                (def cust-phone (get (first input-list) 3))
                (def temp-map (conj new-map {(keyword cust-id) {:cust-name cust-name, :cust-address cust-address, :cust-phone cust-phone}}))
                (read-customer-file (rest input-list) temp-map ())
            )
            (do
                (map str new-map)
                ;(print (get-in new-map [:1 :cust-name]))
                (print new-map)
            )
        )
    )
</code>```

This takes an input of list of vectors as below:

```<code>([3 Fan Yuhong 165 Happy Lane 345-4533] [2 Sue Jones 43 Rose Court Street 345-7867] [1 John Smith 123 Here Street 456-4567])
</code>```

and returns  a nested-map as below:

```<code>{:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}}
</code>```

This is what I am trying to achieve and is working perfectly fine within the function. However, if I try to define a variable outside the function with the value of the return type, I do not get a nested-map but a list of strings. For this, I just remove the (print new-map) part.

```<code>(do
    (map str new-map)
)
</code>```

And call it from outside the function definition as follows:

```<code>(def customer-info-list read-customer-file)
(println (customer-info-list))
</code>```

The result I get is different from what I expected and cannot perform the map-related functionalities such as get and get-in.

```<code>([:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}] [:2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}] [:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}])
</code>```

I would very much appreciate any kind of help with this. I am aware that my code is a bit messy and I should use let instead of def for variable names. But I am just starting Clojure and this is my first program.

UPDATE

I solved the problem. What I did is change the map into a sorted-map inside the function. So the last return from the function will be a sorted map.

```<code>(do
    (into (sorted-map) new-map)
)
</code>```

However, the returned value will still be a string if assigned to a variable., so I converted it to a sorted-map once again. Then it finally got converted to a nested-map.

```<code>(def customer-info-list read-customer-file)
(def cust-map (into (sorted-map) (customer-info-list)))
(println cust-map)
(println (get-in cust-map [:1 :cust-name]))
(println (get cust-map :2))
</code>```

The output from the above three print statements is as expected.

```<code>{:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}}
John Smith
{:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}
</code>```

答:
there is a number of mistakes in your code, connected with the lack of basic clojure knowledge:

1) don't use def/defn inside functions, rather use let

2) adding to a map is usually done with assoc

3) it is always better to return some significant value from the function, and introspect it outside.

i would rewrite your function in a more clojure way like this:
(i intentonaally keep placeholder argument, though it isn't used anywhere in your code, so i can't infer it's purpose)

```<code>(defn read-customer-file [input-list new-map placeholder]
  (if-let [[[id name address phone] & input-tail] (seq input-list)]
    (read-customer-file input-tail
                        (assoc new-map (keyword id)
                               {:cust-name name
                                :cust-address address
                                :cust-phone phone})
                        ())
    new-map))
</code>```

in repl:

```<code>user> (read-customer-file [["a" "b" "c" "d"] ["e" "f" "g" "h"]] {} ())
;;=> {:a {:cust-name "b", :cust-address "c", :cust-phone "d"},
;;    :e {:cust-name "f", :cust-address "g", :cust-phone "h"}}
</code>```

but what you really need, is some higher order data processing function like map:

```<code>(defn read-customer-file [input-list placeholder]
  (into {}
        (map (fn [[id name address phone]]
               [(keyword id) {:cust-name name
                              :cust-phone phone
                              :cust-address address}])
             input-list)))

user> (read-customer-file [["a" "b" "c" "d"] ["e" "f" "g" "h"]] {})
;;=> {:a {:cust-name "b", :cust-phone "d", :cust-address "c"},
;;    :e {:cust-name "f", :cust-phone "h", :cust-address "g"}}
</code>```

or reduce:

```<code>(defn read-customer-file [input-list placeholder]
  (reduce (fn [res [id name address phone]]
            (assoc res (keyword id) {:cust-name name
                                     :cust-phone phone
                                     :cust-address address}))
          {} input-list))
</code>```

also, it's always a good idea to abstract out your business logic (in your case file record to customer conversion) to some specialized function, to keep the processing function more general:

```<code>(defn file-rec->customer [[id name address phone]]
  [(keyword id) {:cust-name name
                 :cust-address address
                 :cust-phone phone}])

(defn read-data-file [record-processor input-list placeholder]
  (into {} (map record-processor) input-list))

user> (read-data-file file-rec->customer [["a" "b" "c" "d"] ["e" "f" "g" "h"]] {})
;;=> {:a {:cust-name "b", :cust-address "c", :cust-phone "d"},
;;    :e {:cust-name "f", :cust-address "g", :cust-phone "h"}}
</code>```

Title: Clojure function not returning a map

Body:
I am new to Clojure and functional programming. I have a basic idea about the data structures in Clojure such as maps, lists, and vectors.

I am trying to write a function that returns a nested map. The map is correctly displayed inside the function. The below code is from the read-customer-file function

([input-list new-map place-holder]
        (if (not-empty input-list)
            (do
                (def string-input (str (first input-list)))
                (def cust-id (get (first input-list) 0))
                (def cust-name (get (first input-list) 1))
                (def cust-address (get (first input-list) 2))
                (def cust-phone (get (first input-list) 3))
                (def temp-map (conj new-map {(keyword cust-id) {:cust-name cust-name, :cust-address cust-address, :cust-phone cust-phone}}))
                (read-customer-file (rest input-list) temp-map ())
            )
            (do
                (map str new-map)
                ;(print (get-in new-map [:1 :cust-name]))
                (print new-map)
            )
        )
    )

This takes an input of list of vectors as below:

([3 Fan Yuhong 165 Happy Lane 345-4533] [2 Sue Jones 43 Rose Court Street 345-7867] [1 John Smith 123 Here Street 456-4567])

and returns  a nested-map as below:

{:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}}

This is what I am trying to achieve and is working perfectly fine within the function. However, if I try to define a variable outside the function with the value of the return type, I do not get a nested-map but a list of strings. For this, I just remove the (print new-map) part.

(do
    (map str new-map)
)

And call it from outside the function definition as follows:

(def customer-info-list read-customer-file)
(println (customer-info-list))

The result I get is different from what I expected and cannot perform the map-related functionalities such as get and get-in.

([:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}] [:2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}] [:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}])

I would very much appreciate any kind of help with this. I am aware that my code is a bit messy and I should use let instead of def for variable names. But I am just starting Clojure and this is my first program.

UPDATE

I solved the problem. What I did is change the map into a sorted-map inside the function. So the last return from the function will be a sorted map.

(do
    (into (sorted-map) new-map)
)

However, the returned value will still be a string if assigned to a variable., so I converted it to a sorted-map once again. Then it finally got converted to a nested-map.

(def customer-info-list read-customer-file)
(def cust-map (into (sorted-map) (customer-info-list)))
(println cust-map)
(println (get-in cust-map [:1 :cust-name]))
(println (get cust-map :2))

The output from the above three print statements is as expected.

{:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}}
John Smith
{:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}

Body:
there is a number of mistakes in your code, connected with the lack of basic clojure knowledge:

1) don't use def/defn inside functions, rather use let

2) adding to a map is usually done with assoc

3) it is always better to return some significant value from the function, and introspect it outside.

i would rewrite your function in a more clojure way like this:
(i intentonaally keep placeholder argument, though it isn't used anywhere in your code, so i can't infer it's purpose)

(defn read-customer-file [input-list new-map placeholder]
  (if-let [[[id name address phone] & input-tail] (seq input-list)]
    (read-customer-file input-tail
                        (assoc new-map (keyword id)
                               {:cust-name name
                                :cust-address address
                                :cust-phone phone})
                        ())
    new-map))

in repl:

user> (read-customer-file [["a" "b" "c" "d"] ["e" "f" "g" "h"]] {} ())
;;=> {:a {:cust-name "b", :cust-address "c", :cust-phone "d"},
;;    :e {:cust-name "f", :cust-address "g", :cust-phone "h"}}

but what you really need, is some higher order data processing function like map:

(defn read-customer-file [input-list placeholder]
  (into {}
        (map (fn [[id name address phone]]
               [(keyword id) {:cust-name name
                              :cust-phone phone
                              :cust-address address}])
             input-list)))

user> (read-customer-file [["a" "b" "c" "d"] ["e" "f" "g" "h"]] {})
;;=> {:a {:cust-name "b", :cust-phone "d", :cust-address "c"},
;;    :e {:cust-name "f", :cust-phone "h", :cust-address "g"}}

or reduce:

(defn read-customer-file [input-list placeholder]
  (reduce (fn [res [id name address phone]]
            (assoc res (keyword id) {:cust-name name
                                     :cust-phone phone
                                     :cust-address address}))
          {} input-list))

also, it's always a good idea to abstract out your business logic (in your case file record to customer conversion) to some specialized function, to keep the processing function more general:

(defn file-rec->customer [[id name address phone]]
  [(keyword id) {:cust-name name
                 :cust-address address
                 :cust-phone phone}])

(defn read-data-file [record-processor input-list placeholder]
  (into {} (map record-processor) input-list))

user> (read-data-file file-rec->customer [["a" "b" "c" "d"] ["e" "f" "g" "h"]] {})
;;=> {:a {:cust-name "b", :cust-address "c", :cust-phone "d"},
;;    :e {:cust-name "f", :cust-address "g", :cust-phone "h"}}


答:
You don't appear to ever set dots[i] to your new values here:

```<code>public void createDots(int i) {
    pos[0] = r.nextFloat() * 300;
    pos[1] = r.nextFloat() * 300;
    dotWidth = r.nextFloat() * 30;
    if (dotWidth < 5) {
        dotWidth *= 10;
    }
    dotRadius = dotWidth / 2;
    dotMass = r.nextFloat() / 10;
    centrePos[0] = centrePos[0] + dotRadius;
    centrePos[1] = pos[1] + dotRadius;
    vel[0] = r.nextFloat() / 10;
    vel[1] = r.nextFloat() / 10;
    check(i);
}
</code>```

Looks like you want to call setValues(i) at the end, just before check(i).

Title: Random float value is repeating

Body:
You don't appear to ever set dots[i] to your new values here:

public void createDots(int i) {
    pos[0] = r.nextFloat() * 300;
    pos[1] = r.nextFloat() * 300;
    dotWidth = r.nextFloat() * 30;
    if (dotWidth < 5) {
        dotWidth *= 10;
    }
    dotRadius = dotWidth / 2;
    dotMass = r.nextFloat() / 10;
    centrePos[0] = centrePos[0] + dotRadius;
    centrePos[1] = pos[1] + dotRadius;
    vel[0] = r.nextFloat() / 10;
    vel[1] = r.nextFloat() / 10;
    check(i);
}

Looks like you want to call setValues(i) at the end, just before check(i).


问:
Powershell Script runs independently but gives 'method invocation failed' error when run as an executable
The following is my powershell script snippet to fetch all the installed applications:

```<code>$tPatchObject = @() #initialize array

#invoking the native powershell(32 bit/64 bit)
$tPatchObject =  &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Childitem "HKLM://SOFTWARE//Microsoft//Windows//CurrentVersion//Uninstall//*" | Get-ItemProperty | Sort-Object DisplayName -Unique;};

#appending applications from a different path to same array
$tPatchObject += &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Childitem "HKLM://SOFTWARE//Wow6432Node//Microsoft//Windows//CurrentVersion//Uninstall//*" | Get-ItemProperty | Sort-Object DisplayName -Unique}
</code>```

When being tested on a Windows server 2008 R2 system, it gives proper output if executed directly from the powershell. But the same script when executed as part of an executable compiled in Golang gives error

Method Invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'.

Facing this issue only on a Windows server 2008 system. My assumption is the problem occurring because of the invocation  of&"powershell.exe"

答:
try this, LookPath

cmd := `Get-Childitem "HKLM://SOFTWARE//Microsoft//...`

ps, _ := exec.LookPath("powershell.exe")
args := append([]string{"-NoProfile", "-NonInteractive", cmd})

out, _ := exec.Command(ps, args...).Output()
```

Body:
The following is my powershell script snippet to fetch all the installed applications:

$tPatchObject = @() #initialize array

#invoking the native powershell(32 bit/64 bit)
$tPatchObject =  &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Childitem "HKLM://SOFTWARE//Microsoft//Windows//CurrentVersion//Uninstall//*" | Get-ItemProperty | Sort-Object DisplayName -Unique;};

#appending applications from a different path to same array
$tPatchObject += &"$env:systemroot\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -Command {Get-Childitem "HKLM://SOFTWARE//Wow6432Node//Microsoft//Windows//CurrentVersion//Uninstall//*" | Get-ItemProperty | Sort-Object DisplayName -Unique}

When being tested on a Windows server 2008 R2 system, it gives proper output if executed directly from the powershell. But the same script when executed as part of an executable compiled in Golang gives error

Method Invocation failed because [System.Management.Automation.PSObject] doesn't contain a method named 'op_Addition'.

Facing this issue only on a Windows server 2008 system. My assumption is the problem occurring because of the invocation  of&"powershell.exe"


问:
Does declaring a vector with size offer any improvements over using push_back in C++
Let us say we know the size of a vector we will be needing, (say 'n').

Does using vector<int> Array(n); offer any improvements over using Array.push_back(element) one by one?

Which is recommended and why?

答:
The first one should be better than the second. Why? std::vector is a dynamic size vector. It means that if u wanna push over its limit, it is gonna resize. How this resize is happening? Allocating new memory, copying everything, and deleting the previous one. This means that using push_back() may trigger this allocation if the capacity is not enough. The first one makes the std::vector with the required capacity from the beginning so no moving required when inserting elements

Note that u can make a std::vector of a specific capacity, and then push_back() is not gonna do any additional allocation, which shall be quite efficient


问:
c# wcf webservice accept json dynamic data
I want my c# Webservice to accept dynamic data.

right now i am doing this

class:

```<code> [DataContractFormat]
    public class person
    {

        public string name { get; set; }
        public string address { get; set; }
        public string age { get; set; }
    }
</code>```

method

```<code>public string person(person p)
        {

            string name = p.name;
            return name;
        }

[WebInvoke(UriTemplate = "/person/do",
        Method = "POST",
         RequestFormat = WebMessageFormat.Json,
          ResponseFormat = WebMessageFormat.Json
               )]
        string person(person p);
</code>```

this is my json body

```<code>{
    "name":"",
    "address":"",
    "age":""
}
</code>```

I don't want to define properties in the class, and I want it to accept any data I send to it. now its accepting the "name":"", "address":"", "age":"
eg: if I want I sud be able to give date-of-birth without defining it in class. Hope you would understand

答:
I see what you mean.Normally, after WCF service is started, you can view its help document to view the data format received by WCF service.

```<code>      [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result PostUserData(UserData user);
</code>```

This is the definition of WCF service interface.

```<code>        public class UserData
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }
    [DataMember(Name = "Password")]
    public string Password { get; set; }
    [DataMember(Name = "Email")]
    public string Email { get; set; }
}
</code>```

This is the definition of UserData class,which has three properties: name, password,email.

According to your description, if we send a Josn not in the above format to the WCF service, the WCF service will receive the JSON without error.

But now there's a problem. You don't define these attributes in class. How do you receive them?You can only parse JSON to get data.Of course, you can send what you call dynamic data to the WCF service, but when you receive it, you only parse the data yourself.

Body:
I want my c# Webservice to accept dynamic data.

right now i am doing this

class:

 [DataContractFormat]
    public class person
    {

        public string name { get; set; }
        public string address { get; set; }
        public string age { get; set; }
    }

method

public string person(person p)
        {

            string name = p.name;
            return name;
        }

[WebInvoke(UriTemplate = "/person/do",
        Method = "POST",
         RequestFormat = WebMessageFormat.Json,
          ResponseFormat = WebMessageFormat.Json
               )]
        string person(person p);

this is my json body

{
    "name":"",
    "address":"",
    "age":""
}

I don't want to define properties in the class, and I want it to accept any data I send to it. now its accepting the "name":"", "address":"", "age":"
eg: if I want I sud be able to give date-of-birth without defining it in class. Hope you would understand

Body:
I see what you mean.Normally, after WCF service is started, you can view its help document to view the data format received by WCF service.

      [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Result PostUserData(UserData user);

This is the definition of WCF service interface.

        public class UserData
{
    [DataMember(Name = "Name")]
    public string Name { get; set; }
    [DataMember(Name = "Password")]
    public string Password { get; set; }
    [DataMember(Name = "Email")]
    public string Email { get; set; }
}

This is the definition of UserData class,which has three properties: name, password,email.

According to your description, if we send a Josn not in the above format to the WCF service, the WCF service will receive the JSON without error.

But now there's a problem. You don't define these attributes in class. How do you receive them?You can only parse JSON to get data.Of course, you can send what you call dynamic data to the WCF service, but when you receive it, you only parse the data yourself.


问:
Dynamically passing the column name as well the values in python mysql query
This is the following code

```<code>pythonlist = ['Name','Mno']
datalist = ["qwerty",'234']
sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = '"+ "','".join(datalist) + "' INTO OUTFILE filename"
print(sql)
</code>```

OUTPUT:

```<code>SELECT Name,Mno FROM data WHERE Name= 'qwerty','234'
</code>```

DESIRED OUTPUT:

```<code>SELECT Name,Mno FROM data WHERE Name = 'qwerty' and Mno = 234
</code>```

Do note the removal of quotations marks in 'mno'.

The reason I am doing this is due because the column names, as well as values corresponding it to, will change frequently

答:
Try this:</p>

```<code>data = {'Name': 'qwerty' , 'Mno' : '234'}

sql = "SELECT " + ", ".join(data.keys()) + " FROM data WHERE " + str(list(data.keys())[0]) + "  = '" + \
      str(data[list(data.keys())[0]]) + "' and " +\
      str(list(data.keys())[1]) + " = " + str(data[list(data.keys())[1]])

print(sql)
</code>```

Body:
This is the following code

pythonlist = ['Name','Mno']
datalist = ["qwerty",'234']
sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = '"+ "','".join(datalist) + "' INTO OUTFILE filename"
print(sql)

OUTPUT:

SELECT Name,Mno FROM data WHERE Name= 'qwerty','234'

DESIRED OUTPUT:

SELECT Name,Mno FROM data WHERE Name = 'qwerty' and Mno = 234

Do note the removal of quotations marks in 'mno'.

The reason I am doing this is due because the column names, as well as values corresponding it to, will change frequently

Body:
Try this:

data = {'Name': 'qwerty' , 'Mno' : '234'}

sql = "SELECT " + ", ".join(data.keys()) + " FROM data WHERE " + str(list(data.keys())[0]) + "  = '" + \
      str(data[list(data.keys())[0]]) + "' and " +\
      str(list(data.keys())[1]) + " = " + str(data[list(data.keys())[1]])

print(sql)


问:
Page not found in django, pycharm?
I am working with django project to create a website
when i set the first url it works properly but when i add new url after products/new/ then it shows page not found

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/products/new/
Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order:

Here is folders,

```<code>products.urls.py:

from django.urls import path
from . import views

urlpatterns = [
path('', views.index),
path('new', views.new)
]
</code>```

views.py:

```<code>from django.http import HttpResponse
from django.shortcuts import render

def index(request):
return HttpResponse('Hello world')

def new(request):
return HttpResponse('New Products!!!!!!!!!!!!!')
</code>```

apps.py:

```<code>from django.apps import AppConfig

class ProductsConfig(AppConfig):
name = 'products'
</code>```

pyshop.urls.py:

```<code>"""pyshop URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import:  from my_app import views
2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
1. Add an import:  from other_app.views import Home
2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('products/', include('products.urls'))
]
</code>```

And here is the error

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/products/new/ Using the URLconf defined in
  pyshop.urls, Django tried these URL patterns, in this order:

admin/
 products/
 products/ new

The current path, products/new/, didn't match any of these.

答:
Note

Use singular name instead of plurals for your apps:

product instead of products.

Templates directory

First create templates directory into your products app and then create another directory in templates folder name must be your app name (products).

```<code>products # app name
   templates # templates folder
       products # again app name
          aboutme.html # here your all html pages
          mypage2.html
</code>```

Views.py

```<code>from django.http import HttpResponse
from django.shortcuts import render

def index(request):
    return HttpResponse('Hello world')

def new(request):
    return HttpResponse('New Products!!!!!!!!!!!!!')

#or if you want to return html page then
def aboutme(request):
   return render(request,'products/aboutme.html')
</code>```

product app urls.py

```<code>from django.urls import path
from . import views

urlpatterns = [
path('', views.index),
path('new', views.new),
path('all-about-me/', views.aboutme,name = 'about_me'), # get rid of hard coded urls so always use name parameter to give some name to your view.
]
</code>```

Project urls.py file

Add here all apps urls.

```<code>from django.contrib import admin
from django.urls import path, include

urlpatterns = [
     path('admin/', admin.site.urls),
     path('products/', include('products.urls'))
]
</code>```

Add your app into setting

```<code>INSTALLED_APPS = [
    # others goes here

    'products.apps.ProductsConfig',# your products app

]
</code>```

Your project directories must be like above as well as code.

You are missing any above step which i described above and confusing in URLS.

http://127.0.0.1:8000 it shows PageNotFound 404 because you are not defined any index page into main URLS.py

http://127.0.0.1:8000/products it shows 'Hello world' (called index view).

http://127.0.0.1:8000/products/new it shows  'New Products!!!!!!!!!!!!!' (called new view).

http://127.0.0.1:8000/products/all-about-me it render aboutme.html (called aboutme view )

still confused leave a comment.

Title: Page not found in django, pycharm?

Body:
I am working with django project to create a website
when i set the first url it works properly but when i add new url after products/new/ then it shows page not found

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/products/new/
Using the URLconf defined in pyshop.urls, Django tried these URL patterns, in this order:

Here is folders,

products.urls.py:

from django.urls import path
from . import views

urlpatterns = [
path('', views.index),
path('new', views.new)
]

views.py:

from django.http import HttpResponse
from django.shortcuts import render

def index(request):
return HttpResponse('Hello world')

def new(request):
return HttpResponse('New Products!!!!!!!!!!!!!')

apps.py:

from django.apps import AppConfig

class ProductsConfig(AppConfig):
name = 'products'

pyshop.urls.py:

"""pyshop URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import:  from my_app import views
2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
1. Add an import:  from other_app.views import Home
2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('products/', include('products.urls'))
]

And here is the error

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/products/new/ Using the URLconf defined in
  pyshop.urls, Django tried these URL patterns, in this order:

admin/
 products/
 products/ new

The current path, products/new/, didn't match any of these.

Body:
Note

Use singular name instead of plurals for your apps:

product instead of products.

Templates directory

First create templates directory into your products app and then create another directory in templates folder name must be your app name (products).

products # app name
   templates # templates folder
       products # again app name
          aboutme.html # here your all html pages
          mypage2.html

Views.py

from django.http import HttpResponse
from django.shortcuts import render

def index(request):
    return HttpResponse('Hello world')

def new(request):
    return HttpResponse('New Products!!!!!!!!!!!!!')

#or if you want to return html page then
def aboutme(request):
   return render(request,'products/aboutme.html')

product app urls.py

from django.urls import path
from . import views

urlpatterns = [
path('', views.index),
path('new', views.new),
path('all-about-me/', views.aboutme,name = 'about_me'), # get rid of hard coded urls so always use name parameter to give some name to your view.
]

Project urls.py file

Add here all apps urls.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
     path('admin/', admin.site.urls),
     path('products/', include('products.urls'))
]

Add your app into setting

INSTALLED_APPS = [
    # others goes here

    'products.apps.ProductsConfig',# your products app

]

Your project directories must be like above as well as code.

You are missing any above step which i described above and confusing in URLS.

http://127.0.0.1:8000 it shows PageNotFound 404 because you are not defined any index page into main URLS.py

http://127.0.0.1:8000/products it shows 'Hello world' (called index view).

http://127.0.0.1:8000/products/new it shows  'New Products!!!!!!!!!!!!!' (called new view).

http://127.0.0.1:8000/products/all-about-me it render aboutme.html (called aboutme view )

still confused leave a comment.


问:
EHCache with Terracotta Vs Infinispan
We are working in the design phase of new project where we need to decide the caching framework. We need decide whether to go with EHCache with Terracotta or Infinispan for caching requirement? Can anyone provide me the advantages & disadvantages of EHCache and Infinispan?

Thanks in advance.

答:
Is your environment distributed?  If so, Infinispan would have an advantage of scalability due to its p2p design.  Even in standalone (non-clustered mode), you'd get to take advantage of the non-blocking nature of Infinispan internals, state of the art eviction algorithms (LIRS), etc.  Have a look at this article for a discussion of Infinispan as a local cache.

DISCLAIMER: I am the founder and project lead of Infinspan.

Title: EHCache with Terracotta Vs Infinispan


问:
Get error compiling example of gtk example from https://www.gtk.org/docs/getting-started/hello-world/
Hi i am trying to compile the Hello World of gtk from the official website. I done everything asked and I installed GTK by msys2 package manager. My cmd cant detect the package-config directory. I have done setting path for my msys264 on the environment variable. I am sorry if it sounded confusing as I am begineer. TQ.</p>

```<code>C:\Users\60182\Desktop\vc>gcc `pkg-config --cflags gtk+-3.0` -o hello-world-gtk hello-world-gtk.c `pkg-config --libs gtk+-3.0`

gcc: error: `pkg-config: No such file or directory
gcc: error: gtk+-3.0`: No such file or directory
gcc: error: `pkg-config: No such file or directory
gcc: error: gtk+-3.0`: No such file or directory
gcc: error: unrecognized command-line option '--cflags'
gcc: error: unrecognized command-line option '--libs'
</code>```

答:
I can see the problem. Windows shell does not work like linux shells. The backtick character is used for passing the output of one command as a parameter to another.

So in order to do this manually, you can do something like this. First run the command pkg-config --cflags gtk+-3.0 and then pkg-config --libs gtk+-3.0. I don't know what the output will be, but assume the outputs are just "foo" and "bar" and that it looks like this:

```<code>C:\Users\60182\Desktop\vc>pkg-config --cflags gtk+-3.0
foo

C:\Users\60182\Desktop\vc>pkg-config --libs gtk+-3.0
bar
</code>```

Then you do this:

```<code>C:\Users\60182\Desktop\vc>gcc foo -o hello-world-gtk hello-world-gtk.c bar
</code>```

Body:
Hi i am trying to compile the Hello World of gtk from the official website. I done everything asked and I installed GTK by msys2 package manager. My cmd cant detect the package-config directory. I have done setting path for my msys264 on the environment variable. I am sorry if it sounded confusing as I am begineer. TQ.

C:\Users\60182\Desktop\vc>gcc `pkg-config --cflags gtk+-3.0` -o hello-world-gtk hello-world-gtk.c `pkg-config --libs gtk+-3.0`

gcc: error: `pkg-config: No such file or directory
gcc: error: gtk+-3.0`: No such file or directory
gcc: error: `pkg-config: No such file or directory
gcc: error: gtk+-3.0`: No such file or directory
gcc: error: unrecognized command-line option '--cflags'
gcc: error: unrecognized command-line option '--libs'

Body:
I can see the problem. Windows shell does not work like linux shells. The backtick character is used for passing the output of one command as a parameter to another.

So in order to do this manually, you can do something like this. First run the command pkg-config --cflags gtk+-3.0 and then pkg-config --libs gtk+-3.0. I don't know what the output will be, but assume the outputs are just "foo" and "bar" and that it looks like this:

C:\Users\60182\Desktop\vc>pkg-config --cflags gtk+-3.0
foo

C:\Users\60182\Desktop\vc>pkg-config --libs gtk+-3.0
bar

Then you do this:

C:\Users\60182\Desktop\vc>gcc foo -o hello-world-gtk hello-world-gtk.c bar


问:
Having issues with my first python web scraper
I am trying to scrape information on a website called supremecommunity for a personal project. They have an archive of items from different seasons and I am trying to put that information into a csv. My code includes a loop that I got from this github page https://github.com/CharlieAIO/Supreme-Community-Scraper/blob/master/sup.py

below is the code that I am working with, it will run without error but the csv remains empty save for the headers that I set. Am I doing something wrong here? Is the website denying my request? Any help or direction appreciated.

```<code>import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.text,"html.parser")
    cards = soup.find_all('div',{'class':'card card-2'})

    for card in cards:
        item = card.find("div",{"class":"card-details"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        price = card.find("span",{"class":"label-price"}).text
        price = price.replace(" ","")
        price = price.replace("\n","")
        upvotes = card.find("p",{"class":"upvotes hidden"}).text
        downvotes = card.find("p",{"class":"downvotes hidden"}).text

        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()
</code>```

答:
This is one of the ways you can fetch all the aforementioned fields from that webpage other than the prices as they are not available in there yet. To check it, you can click on each image and toggle the price tab. I've used .select() instead of .find_all() to make it concise. Once you execute the script, you should get a data-ridden csv file containing the required fields accordingly.

```<code>import csv
import requests
from bs4 import BeautifulSoup

base = 'https://www.supremecommunity.com{}'
link = 'https://www.supremecommunity.com/season/fall-winter2011/overview/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"lxml")

with open("supremecommunity.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerow(['item_name','item_image','upvote','downvote'])

    for card in soup.select('[class$="d-card"]'):
        item_name = card.select_one('.card__top')['data-itemname']
        item_image = base.format(card.select_one('img.prefill-img').get('data-src'))
        upvote = card.select_one('.progress-bar-success > span').get_text(strip=True)
        downvote = card.select_one('.progress-bar-danger > span').get_text(strip=True)
        writer.writerow([item_name,item_image,upvote,downvote])
        print(item_name,item_image,upvote,downvote)
</code>```

Body:
I am trying to scrape information on a website called supremecommunity for a personal project. They have an archive of items from different seasons and I am trying to put that information into a csv. My code includes a loop that I got from this github page https://github.com/CharlieAIO/Supreme-Community-Scraper/blob/master/sup.py

below is the code that I am working with, it will run without error but the csv remains empty save for the headers that I set. Am I doing something wrong here? Is the website denying my request? Any help or direction appreciated.

import requests
from bs4 import BeautifulSoup as bs

urls = ['https://www.supremecommunity.com/season/fall-winter2011/overview/']
open("SupremeData.csv","w")

filename = "SupremeData.csv"

headers = "Item,Image,Price,Upvotes,Downvotes"

f = open(filename, "w")
f.write(headers)

for link in urls:

    r = requests.get(link)
    soup = bs(r.text,"html.parser")
    cards = soup.find_all('div',{'class':'card card-2'})

    for card in cards:
        item = card.find("div",{"class":"card-details"})["data-itemname"]
        img = card.find("img",{"class":"prefill-img"})["src"]
        image = f'https://supremecommunity.com{img}'
        price = card.find("span",{"class":"label-price"}).text
        price = price.replace(" ","")
        price = price.replace("\n","")
        upvotes = card.find("p",{"class":"upvotes hidden"}).text
        downvotes = card.find("p",{"class":"downvotes hidden"}).text

        f.write(item + "," + image + "," + price + "," + upvotes + "," + downvotes + "\n")

f.close()

Body:
This is one of the ways you can fetch all the aforementioned fields from that webpage other than the prices as they are not available in there yet. To check it, you can click on each image and toggle the price tab. I've used .select() instead of .find_all() to make it concise. Once you execute the script, you should get a data-ridden csv file containing the required fields accordingly.

import csv
import requests
from bs4 import BeautifulSoup

base = 'https://www.supremecommunity.com{}'
link = 'https://www.supremecommunity.com/season/fall-winter2011/overview/'

r = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(r.text,"lxml")

with open("supremecommunity.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerow(['item_name','item_image','upvote','downvote'])

    for card in soup.select('[class$="d-card"]'):
        item_name = card.select_one('.card__top')['data-itemname']
        item_image = base.format(card.select_one('img.prefill-img').get('data-src'))
        upvote = card.select_one('.progress-bar-success > span').get_text(strip=True)
        downvote = card.select_one('.progress-bar-danger > span').get_text(strip=True)
        writer.writerow([item_name,item_image,upvote,downvote])
        print(item_name,item_image,upvote,downvote)


问:
What are Keys in the Stateless widgets class?
In the flutter docs there's sample code for a stateless widget subclass as shown:

```<code>class GreenFrog extends StatelessWidget {
  const GreenFrog({ Key key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Container(color: const Color(0xFF2DBD3A));
  }
}
</code>```

and this

```<code>class Frog extends StatelessWidget {
  const Frog({
    Key key,
    this.color: const Color(0xFF2DBD3A),
    this.child,
  }) : super(key: key);

  final Color color;

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return new Container(color: color, child: child);
  }
}
</code>```

What is a key and when should this super constructor be used? It seems like if you have your own constructor you must have {Key key} why? I've seen other examples where the super keyword is not used so this is where my confusion is.

答:
What are Keys?

Keys are IDs for widgets. All widgets have them, not just StatelessWidgets. They are used by the Element tree to determine if a widget can be reused or if it needs to be rebuilt. When no key is specified (the usual case), then the widget type is used to determine this.

Why use Keys?

Keys are useful for maintaining state when the number or position of widgets changes. If there is no key then the Flutter framework can get confused about which widget changed.

When to use Keys?

Only use them when the framework needs your help to know which widget to update.

Most of the time you don't need to use keys. Since keys are mostly only useful for maintaining state, if you have a stateless widget whose children are all stateless, then there is no need to use a key on it. It won't hurt to use a key in this case, but it also won't help.

There are some micro-optimizations you can make using keys. See this article.

Where to use Keys?

Put the key at the part of the widget tree where the reordering or addition/deletion is taking place. For example, if you are reordering the items of a ListView whose children are ListTile widgets, then add the keys to the ListTile widgets.

What kind of Keys to use?

A key is just an id, but the kind of ID you use can vary.

ValueKey

A ValueKey is a local key that takes a simple value like a string or integer.

ObjectKey

If you widget is displaying more complex data than a single value, then you can use an ObjectKey for that widget.

UniqueKey

This type of key is guaranteed to give you a unique ID every time. If you use it, though, do NOT put it in the build method. Otherwise your widget will never have the same ID and so the Element tree will never find a match to reuse.

GlobalKey

GlobalKeys can be used to maintain state across your app, but use them sparingly because they are similar to global variables. It is often preferable to use a state management solution instead.

Examples of using Keys

AnimatedLists

Changing the position in a column/row

TextFormField

References

Keys! What are they good for?

Using Keys in Flutter

Body:
In the flutter docs there's sample code for a stateless widget subclass as shown:

class GreenFrog extends StatelessWidget {
  const GreenFrog({ Key key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Container(color: const Color(0xFF2DBD3A));
  }
}

and this

class Frog extends StatelessWidget {
  const Frog({
    Key key,
    this.color: const Color(0xFF2DBD3A),
    this.child,
  }) : super(key: key);

  final Color color;

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return new Container(color: color, child: child);
  }
}

What is a key and when should this super constructor be used? It seems like if you have your own constructor you must have {Key key} why? I've seen other examples where the super keyword is not used so this is where my confusion is.


答:
With

```<code>vector<int> Array(n);
</code>```

you create a vector that contains n elements, all memory needed for those elements is allocated immediately.

When you use e.g.

```<code>Array.push_back(value);
</code>```

then the vector needs to be resized, which could mean the memory have to be reallocated and all the contents have to be copied to the new memory.

Instead of creating an array with a set size, you could instead preallocate (or reserve) memory:

```<code>vector<int> Array;  // An empty vector
Array.reserve(n);   // Reserve memory, but keep the size as zero (it's still empty)
Array.push_back(value);  // No reallocation needed, size is now one
</code>```

This is useful when you have a vector of objects that can't be default-constructed.

Important concepts to learn: The vector size and its capacity and what the difference between them is.

The capacity is the number of elements the vector have allocated memory for.

The size is the current number of elements in the vector.

It's quite common for the capacity to be different from the size. And it must always be true that capacity >= size.

Title: Does declaring a vector with size offer any improvements over using push_back in C++

Body:
Let us say we know the size of a vector we will be needing, (say 'n').

Does using vector<int> Array(n); offer any improvements over using Array.push_back(element) one by one?

Which is recommended and why?

Body:
With

vector<int> Array(n);

you create a vector that contains n elements, all memory needed for those elements is allocated immediately.

When you use e.g.

Array.push_back(value);

then the vector needs to be resized, which could mean the memory have to be reallocated and all the contents have to be copied to the new memory.

Instead of creating an array with a set size, you could instead preallocate (or reserve) memory:

vector<int> Array;  // An empty vector
Array.reserve(n);   // Reserve memory, but keep the size as zero (it's still empty)
Array.push_back(value);  // No reallocation needed, size is now one

This is useful when you have a vector of objects that can't be default-constructed.

Important concepts to learn: The vector size and its capacity and what the difference between them is.

The capacity is the number of elements the vector have allocated memory for.

The size is the current number of elements in the vector.

It's quite common for the capacity to be different from the size. And it must always be true that capacity >= size.


问:
Why is the default MaxMetaspaceSize on Java very large?
I checked the default MaxMetaspaceSize on the JVM by printing JVM parameters as follows

```<code>java -XX:+PrintFlagsFinal -version | grep MaxMetaspaceSize
    uintx MaxMetaspaceSize                          = 18446744073709547520                    {product}
java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)
</code>```

Given that these JVM parameter values are shown in bytes, the default MaxMetaspaceSize is about 18 Exabytes!

Can someone please explain why the default MaxMetaspaceSize value is so large?

答:
18446744073709547520 = 0xFFFFFFFFFFFFF000

This is basically the maximum possible 64-bit integer (rounded to the page size).

The idea is to have MaxMetaspaceSize unlimited by default.

Body:
I checked the default MaxMetaspaceSize on the JVM by printing JVM parameters as follows

java -XX:+PrintFlagsFinal -version | grep MaxMetaspaceSize
    uintx MaxMetaspaceSize                          = 18446744073709547520                    {product}
java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)

Given that these JVM parameter values are shown in bytes, the default MaxMetaspaceSize is about 18 Exabytes!

Can someone please explain why the default MaxMetaspaceSize value is so large?


问:
Nested SQL IN statement for cell with more than 1 value

How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

```<code>select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')
</code>```

but it returns no value, no nope, i'm not allowed to alter the database design.

答:
Your database design is not optimal, because it is storing CSV values.  That being said, here is one way to get the output you want using LISTAGG (11g+):

```<code>SELECT
    c."Key",
    LISTAGG(s.Name, ',') WITHIN GROUP (ORDER BY s.Dept) Departments
FROM ConfigDB c
LEFT JOIN StaffDB s
    ON ',' || c."Value" || ',' LIKE '%,' || s.Dept || '%,'
GROUP BY
    c."Key";
</code>```

Demo

Note that we compare the CSV list of departments in the config table to each scalar value in the staff table using this logic, for example:

```<code>,A,B,C, LIKE '%,A,%'
</code>```

That is, we tag on commas onto the CSV string of departments, so that we may search for each possible scalar department surrounded by commas.

Body:
How do i write the SQL such that it will return me

tom,ken,jerry

I tried this SQL as

select name
  from staffDB
 where dept in (select value
                  from ConfigDB
                 where key = 'dept')

but it returns no value, no nope, i'm not allowed to alter the database design.

Body:
Your database design is not optimal, because it is storing CSV values.  That being said, here is one way to get the output you want using LISTAGG (11g+):

SELECT
    c."Key",
    LISTAGG(s.Name, ',') WITHIN GROUP (ORDER BY s.Dept) Departments
FROM ConfigDB c
LEFT JOIN StaffDB s
    ON ',' || c."Value" || ',' LIKE '%,' || s.Dept || '%,'
GROUP BY
    c."Key";

Demo

Note that we compare the CSV list of departments in the config table to each scalar value in the staff table using this logic, for example:

,A,B,C, LIKE '%,A,%'

That is, we tag on commas onto the CSV string of departments, so that we may search for each possible scalar department surrounded by commas.


问:
How to define volume mounts for logs in Kubernates deployments and access service through public IP?

Question first Part:
Every time I deploy latest service my data is lost so I want to mount
some volume so that my data is not lost and also want to sync same
volume mount to multiple services for data sharing.

Question Second Part:
how could I access service using public IP, It's accessible on local network but not publicly

Here is the deployment file I write:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: setup
  labels:
    app: setup
spec:
  replicas: 1
  selector:
    matchLabels:
      app: setup
  template:
    metadata:
      labels:
        app: setup
    spec:
      containers:
      - name: setup
        image: esmagic/setup:1.0
        ports:
        - containerPort: 8081
---
apiVersion: v1
kind: Service
metadata:
  name: setup
  labels:
    app: setup
spec:
  ports:
  - name: tcp-8081-8081-setup
    port: 8081
    targetPort: 8081
    protocol: TCP
  selector:
    app: setup
  type: LoadBalancer
  externalIPs:
    - 192.168.1.249
  sessionAffinity: None
  externalTrafficPolicy: Cluster
status:
  loadBalancer: {}
</code>```

答:
For the first one, you have to define volume mounts in spec container and define volume in spec, and for second one you have to define public IP in external IPs

Deployment file after changes:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: setup
  labels:
    app: setup
spec:
  replicas: 1
  selector:
    matchLabels:
      app: setup
  template:
    metadata:
      labels:
        app: setup
    spec:
      containers:
      - name: setup
        image: esmagic/setup:1.0
        ports:
        - containerPort: 8081
        volumeMounts:
          - name: sync-dir
            mountPath: /abc/xyz #Any Real path like (/opt/software)
      volumes:
      - name: sync-dir
        hostPath:
          path: /abc/xyz
---
apiVersion: v1
kind: Service
metadata:
  name: setup
  labels:
    app: setup
spec:
  ports:
  - name: tcp-8081-8081-setup
    port: 8081
    targetPort: 8081
    protocol: TCP
  selector:
    app: setup
  type: LoadBalancer
  externalIPs:
    - 192.168.1.249 #Here comes public IP or write both
  sessionAffinity: None
  externalTrafficPolicy: Cluster
status:
  loadBalancer: {}
</code>```

And also visit this guide for more details about the volume mount as said by Arghya Sadhu

Body:
Question first Part:
Every time I deploy latest service my data is lost so I want to mount
some volume so that my data is not lost and also want to sync same
volume mount to multiple services for data sharing.

Question Second Part:
how could I access service using public IP, It's accessible on local network but not publicly

Here is the deployment file I write:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: setup
  labels:
    app: setup
spec:
  replicas: 1
  selector:
    matchLabels:
      app: setup
  template:
    metadata:
      labels:
        app: setup
    spec:
      containers:
      - name: setup
        image: esmagic/setup:1.0
        ports:
        - containerPort: 8081
---
apiVersion: v1
kind: Service
metadata:
  name: setup
  labels:
    app: setup
spec:
  ports:
  - name: tcp-8081-8081-setup
    port: 8081
    targetPort: 8081
    protocol: TCP
  selector:
    app: setup
  type: LoadBalancer
  externalIPs:
    - 192.168.1.249
  sessionAffinity: None
  externalTrafficPolicy: Cluster
status:
  loadBalancer: {}

Body:
For the first one, you have to define volume mounts in spec container and define volume in spec, and for second one you have to define public IP in external IPs

Deployment file after changes:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: setup
  labels:
    app: setup
spec:
  replicas: 1
  selector:
    matchLabels:
      app: setup
  template:
    metadata:
      labels:
        app: setup
    spec:
      containers:
      - name: setup
        image: esmagic/setup:1.0
        ports:
        - containerPort: 8081
        volumeMounts:
          - name: sync-dir
            mountPath: /abc/xyz #Any Real path like (/opt/software)
      volumes:
      - name: sync-dir
        hostPath:
          path: /abc/xyz
---
apiVersion: v1
kind: Service
metadata:
  name: setup
  labels:
    app: setup
spec:
  ports:
  - name: tcp-8081-8081-setup
    port: 8081
    targetPort: 8081
    protocol: TCP
  selector:
    app: setup
  type: LoadBalancer
  externalIPs:
    - 192.168.1.249 #Here comes public IP or write both
  sessionAffinity: None
  externalTrafficPolicy: Cluster
status:
  loadBalancer: {}

And also visit this guide for more details about the volume mount as said by Arghya Sadhu