问:
How to fix 'TypeError: __init__() got an unexpected keyword argument 'sender''
I am trying to create a django model instance with a django-rest-framework serializer ModelSerializer class. This is my Serializer code:

```<code>class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        fields = ['sender', 'chat_room', 'content', 'sending_date']
</code>```

and this is my view when I try to make a model instance out of it:

```<code>class SendMessage(APIView):
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAuthenticated]

def post(self, request):
    try:
        message_type = request.data['message_type']

        if message_type == ('text' or 'image' or 'audio'):

            if message_type == 'text':

                message_serializer = MessageSerializer(sender=request.user, chat_room=ChatRoom.objects.get(
                    id=request.data['chat_room_id']), content=MessageContent(text=request.data['text']))
                message = Message(message_serializer.data)

            elif message_type == 'image':
                message = MessageSerializer(sender=request.user.id, chat_room=request.data['chat_room_id'],
                                            content=MessageContent(image=request.FILES['image']))

            elif message_type == 'audio':
                message = MessageSerializer(sender=request.user.id, chat_room=request.data['chat_room_id'],
                                            content=MessageContent(image=request.FILES['image']))

            if message.chat_room.users.all().filter(id=request.user.id).exists():
                message.save()

                if message_type == 'image':
                    resize_photo(message.content.image, MessageContent.image_width, MessageContent.image_height)

                if message_type == 'audio':
                    if (not message.content.name.lower().endswith('mp4')) and os.get_size(message.content) > 25000:
                        message.delete()
                        raise FileSourceError

                message.save()
                return Response(status=status.HTTP_201_CREATED)
            else:
                return Response(status=status.HTTP_401_UNAUTHORIZED)

        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

    except KeyError or FileSourceError:
        return Response(status=status.HTTP_400_BAD_REQUEST)
</code>```

This is my message model:

```<code>class Message(models.Model):
    sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE)

    chat_room = models.ForeignKey(ChatRoom, related_name='chat_room', on_delete=models.CASCADE)

    content = models.OneToOneField(MessageContent, on_delete=models.CASCADE)

    is_read_by = models.ManyToManyField(User, related_name="is_read_by")

    sending_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('sending_date',)
</code>```

However, when I run this code, I get

TypeError: init() got an unexpected keyword argument 'sender'

If I delete the sender argument I get

TypeError: init() got an unexpected keyword argument 'chat_room'

and so on. I checked if my ModelSerializer was making the right serializer fields with

print(repr(MessageSerializer()))

in the django python shell, and I got

```<code>MessageSerializer():
    sender = PrimaryKeyRelatedField(queryset=User.objects.all())
    chat_room = PrimaryKeyRelatedField(queryset=ChatRoom.objects.all())
    content = PrimaryKeyRelatedField(queryset=MessageContent.objects.all(), validators=[<UniqueValidator(queryset=Message.objects.all())>])
    sending_date = DateTimeField(read_only=True)
</code>```

which means that my serializer has these fields (sender, chat_room, etc.)
Why do I get this error and how do I fix this? Thank you for your time!

答:
In the model.py file in one of the class attributes change

identification = models.IntegerField()

In the model.py file in one of the class attributes change

```<code>identification = models.IntegerField ()
</code>```

Do not leave anything inside the parentheses, then in the console check with the following command

```<code>python manage.py check application_name
</code>```

Body:
I am trying to create a django model instance with a django-rest-framework serializer ModelSerializer class. This is my Serializer code:

class MessageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        fields = ['sender', 'chat_room', 'content', 'sending_date']

and this is my view when I try to make a model instance out of it:

class SendMessage(APIView):
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAuthenticated]

def post(self, request):
    try:
        message_type = request.data['message_type']

        if message_type == ('text' or 'image' or 'audio'):

            if message_type == 'text':

                message_serializer = MessageSerializer(sender=request.user, chat_room=ChatRoom.objects.get(
                    id=request.data['chat_room_id']), content=MessageContent(text=request.data['text']))
                message = Message(message_serializer.data)

            elif message_type == 'image':
                message = MessageSerializer(sender=request.user.id, chat_room=request.data['chat_room_id'],
                                            content=MessageContent(image=request.FILES['image']))

            elif message_type == 'audio':
                message = MessageSerializer(sender=request.user.id, chat_room=request.data['chat_room_id'],
                                            content=MessageContent(image=request.FILES['image']))

            if message.chat_room.users.all().filter(id=request.user.id).exists():
                message.save()

                if message_type == 'image':
                    resize_photo(message.content.image, MessageContent.image_width, MessageContent.image_height)

                if message_type == 'audio':
                    if (not message.content.name.lower().endswith('mp4')) and os.get_size(message.content) > 25000:
                        message.delete()
                        raise FileSourceError

                message.save()
                return Response(status=status.HTTP_201_CREATED)
            else:
                return Response(status=status.HTTP_401_UNAUTHORIZED)

        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)

    except KeyError or FileSourceError:
        return Response(status=status.HTTP_400_BAD_REQUEST)

This is my message model:

class Message(models.Model):
    sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE)

    chat_room = models.ForeignKey(ChatRoom, related_name='chat_room', on_delete=models.CASCADE)

    content = models.OneToOneField(MessageContent, on_delete=models.CASCADE)

    is_read_by = models.ManyToManyField(User, related_name="is_read_by")

    sending_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('sending_date',)

However, when I run this code, I get

TypeError: init() got an unexpected keyword argument 'sender'

If I delete the sender argument I get

TypeError: init() got an unexpected keyword argument 'chat_room'

and so on. I checked if my ModelSerializer was making the right serializer fields with

print(repr(MessageSerializer()))

in the django python shell, and I got

MessageSerializer():
    sender = PrimaryKeyRelatedField(queryset=User.objects.all())
    chat_room = PrimaryKeyRelatedField(queryset=ChatRoom.objects.all())
    content = PrimaryKeyRelatedField(queryset=MessageContent.objects.all(), validators=[<UniqueValidator(queryset=Message.objects.all())>])
    sending_date = DateTimeField(read_only=True)

which means that my serializer has these fields (sender, chat_room, etc.)
Why do I get this error and how do I fix this? Thank you for your time!

Body:
In the model.py file in one of the class attributes change

identification = models.IntegerField()

In the model.py file in one of the class attributes change

identification = models.IntegerField ()

Do not leave anything inside the parentheses, then in the console check with the following command

python manage.py check application_name


来源: stackexchange

问:
Asp.NET custom server control event handler not firing on second postback
I'm developing a custom server control in Asp.NET (.NET 3.5) which inherits the CompositeControl class.  Inside my control I'm overriding the CreateChildControls() method to generate a mixture of html and Asp.NET server controls.  Some of the Asp.NET controls which are added are LinkButtons (which each have their Command event handler set to a method within my control).  What I'm finding is that the first time one of these LinkButtons is clicked a postback is triggered and the event handler method is correctly fired.  Inside this event handler method CreateChildControls() is explicitly called to regenerate the control in response to the postback.  What I then find is that subsequent clicks of the LinkButtons postbacks fail to raise the event handler method.

I assume that the way I'm handling the regeneration of the control on postback must be at fault, but I can't figure out what to do - I am aware of the fact that on that first postback CreateChildControls() is called twice which probably isn't ideal but since CreateChildControls is called before any events are raised, I don't see a way around this.

A simplified version of my control class is shown below:

```<code>public class SearchResults : CompositeControl
{
    private int PageIndex = 0;

    protected override void CreateChildControls()
    {
            //do stuff here e.g.
            LinkButton prevLink = new LinkButton();
            prevLink.Text = "< Prev";
            prevLink.CommandArgument = (PageIndex - 1).ToString();
            prevLink.Command += new CommandEventHandler(PagerLinkCommand);
            this.Controls.Add(prevLink);
    }

    protected void PagerLinkCommand(object sender, CommandEventArgs e)
    {
        PageIndex = int.Parse(e.CommandArgument.ToString());
        CreateChildControls();
    }
}
</code>```

EDIT
The problem here was caused by the fact that the control is used in a Sitecore site and I had forgotten to register the control type in the web.config file with a <typesThatShouldNotBeExpanded> entry.  This entry is used to prevent server controls from having their events messed up by Sitecore - this can cause similar problems for standard server controls such as ListView, GridView and Repeater etc.  My web.config was modified as shown below:

```<code>  <typesThatShouldNotBeExpanded>
    <type>System.Web.UI.WebControls.Repeater</type>
    <type>System.Web.UI.WebControls.DataList</type>
    <type>System.Web.UI.WebControls.GridView</type>
    <type>MyNamespace.MyCustomControl</type> <!-- This is the bit I added -->
  </typesThatShouldNotBeExpanded>
</code>```

答:
Apologies... this is not a complete answer, but a debugging suggestion that is too long for a comment:

In your browser save an HTML copy of your page for initial load, postback load, and second postback.  Then compare the files using your favorite comparison tool.  Eliminate obvious differences like search results, etc.  This can help you pinpoint any issues with control IDs, missing controls, etc.

The two absolute keys to successful dynamically created controls are

1) Creating them at the correct time during the page lifecycle

2) Re-creating the EXACT SAME control hierarchy (including IDs) on postback

ContentLicense: CC BY-SA 3.0

Body:
I'm developing a custom server control in Asp.NET (.NET 3.5) which inherits the CompositeControl class.  Inside my control I'm overriding the CreateChildControls() method to generate a mixture of html and Asp.NET server controls.  Some of the Asp.NET controls which are added are LinkButtons (which each have their Command event handler set to a method within my control).  What I'm finding is that the first time one of these LinkButtons is clicked a postback is triggered and the event handler method is correctly fired.  Inside this event handler method CreateChildControls() is explicitly called to regenerate the control in response to the postback.  What I then find is that subsequent clicks of the LinkButtons postbacks fail to raise the event handler method.

I assume that the way I'm handling the regeneration of the control on postback must be at fault, but I can't figure out what to do - I am aware of the fact that on that first postback CreateChildControls() is called twice which probably isn't ideal but since CreateChildControls is called before any events are raised, I don't see a way around this.

A simplified version of my control class is shown below:

public class SearchResults : CompositeControl
{
    private int PageIndex = 0;

    protected override void CreateChildControls()
    {
            //do stuff here e.g.
            LinkButton prevLink = new LinkButton();
            prevLink.Text = "< Prev";
            prevLink.CommandArgument = (PageIndex - 1).ToString();
            prevLink.Command += new CommandEventHandler(PagerLinkCommand);
            this.Controls.Add(prevLink);
    }

    protected void PagerLinkCommand(object sender, CommandEventArgs e)
    {
        PageIndex = int.Parse(e.CommandArgument.ToString());
        CreateChildControls();
    }
}

EDIT
The problem here was caused by the fact that the control is used in a Sitecore site and I had forgotten to register the control type in the web.config file with a <typesThatShouldNotBeExpanded> entry.  This entry is used to prevent server controls from having their events messed up by Sitecore - this can cause similar problems for standard server controls such as ListView, GridView and Repeater etc.  My web.config was modified as shown below:

  <typesThatShouldNotBeExpanded>
    <type>System.Web.UI.WebControls.Repeater</type>
    <type>System.Web.UI.WebControls.DataList</type>
    <type>System.Web.UI.WebControls.GridView</type>
    <type>MyNamespace.MyCustomControl</type>
  </typesThatShouldNotBeExpanded>


问:
pyzbar missing a module attribute that does actually exist?
Win 10 x64, Python 2.7, Spyder IDE

I'm using some code from Adrian Rosebrock's OpenCV blog...

```<code>import pyzbar
import cv2

# load the input image
image = cv2.imread("barcode_example.png")

# find the barcodes in the image and decode each of the barcodes
barcodes = pyzbar.pyzbar.decode(image)

# loop over the detected barcodes
for barcode in barcodes:
    # extract the bounding box location of the barcode and draw the
    # bounding box surrounding the barcode on the image
    (x, y, w, h) = barcode.rect
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # the barcode data is a bytes object so if we want to draw it on
    # our output image we need to convert it to a string first
    barcodeData = barcode.data.decode("utf-8")
    barcodeType = barcode.type

    # draw the barcode data and barcode type on the image
    text = "{} ({})".format(barcodeData, barcodeType)
    cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
        0.5, (0, 0, 255), 2)

# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)
</code>```

I keep getting the following error...

```<code>AttributeError: 'module' object has no attribute 'pyzbar'
</code>```

Yet when I check the module in Spyder it does indeed have said artibute...

I've tried running from the command line with the same result.

I have also checked to see if my installation of zbar is working & it is with no problems

Is this an issue with the Python bindings or something really obvious?

答:
Try:

```<code>import pyzbar.pyzbar as pyzbar
</code>```

Works for me.

ContentLicense: CC BY-SA 4.0

Body:
Win 10 x64, Python 2.7, Spyder IDE

I'm using some code from Adrian Rosebrock's OpenCV blog...

import pyzbar
import cv2

# load the input image
image = cv2.imread("barcode_example.png")

# find the barcodes in the image and decode each of the barcodes
barcodes = pyzbar.pyzbar.decode(image)

# loop over the detected barcodes
for barcode in barcodes:
    # extract the bounding box location of the barcode and draw the
    # bounding box surrounding the barcode on the image
    (x, y, w, h) = barcode.rect
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # the barcode data is a bytes object so if we want to draw it on
    # our output image we need to convert it to a string first
    barcodeData = barcode.data.decode("utf-8")
    barcodeType = barcode.type

    # draw the barcode data and barcode type on the image
    text = "{} ({})".format(barcodeData, barcodeType)
    cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
        0.5, (0, 0, 255), 2)

# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

I keep getting the following error...

AttributeError: 'module' object has no attribute 'pyzbar'

Yet when I check the module in Spyder it does indeed have said artibute...

I've tried running from the command line with the same result.

I have also checked to see if my installation of zbar is working & it is with no problems

Is this an issue with the Python bindings or something really obvious?

Body:
Try:

import pyzbar.pyzbar as pyzbar

Works for me.


问:
Django Filter Choice Field displays correct values but wont filter
I'm using the Django filter app: https://github.com/carltongibson/django-filter

I'm making a web-comic app and what I'm trying to accomplish is a drop-down filter field that displays the distinct values for that field. In this case, the series field.

After reading their docs. And stack overflow questions like this one or this one . I can make the filter form display the correct drop down values. But when I attempt to filter by them, my result queryset returns no values!

There must be something in the docs I'm not understanding. Here's my hopefully relevant code.

models.py

```<code>class ComicPanel(models.Model):
    #... Other fields

    series = models.CharField(max_length = 255, null = False, blank = False, default = getMainSeriesName)

    # Other Filter Fields
    chapter = models.FloatField(null = True, blank = True)

    episode = models.IntegerField(null = True, blank = True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['series','chapter', 'episode'])
            ]

    def __str__(self):
        return self.title

    def save(self):
        super(ComicPanel, self).save()
</code>```

filters.py

```<code>import django_filters
from .models import ComicPanel

# Grab Distinct values for series
def getUniqueSeries():
    series_dicts = ComicPanel.objects.all().values_list('series').distinct()
    series_list = []
    i = 0
    for item in series_dicts:
            series_list.append((i,item[0]))
            i = i+1
    return series_list

class ComicPanelFilter(django_filters.FilterSet):

    series = django_filters.ChoiceFilter(choices = getUniqueSeries())

    class Meta:
        model = ComicPanel
        fields = ['chapter', 'episode']
</code>```

views.py

```<code>def view_archive(request):
    comic_list = ComicPanel.objects.all()
    comic_filter = ComicPanelFilter(request.GET, queryset=comic_list)
    paginator = Paginator(comic_filter.qs, 8)

    page = request.GET.get('page', 1)
    try:
        comics = paginator.page(page)
    except (PageNotAnInteger, TypeError):
        comics = paginator.page(1)
    except EmptyPage:
        comics = paginator.page(paginator.num_pages)

    return render(request, 'comics/comic_archive.html', context = {'filter': comic_filter, 'comics': comics})
</code>```

template.html

```<code>...

<form class="form" method="GET">
    {% csrf_token %}
    <table class="my_classes">
      <thead>
        <tr>
          <th scope="col">Filter Comics: </th>
          <th scope="col"></th>
        </tr>
      </thead>
          <tbody>
                {% for field in filter.form %}
                    <tr>
                        <th scope="row"> {{ field.name }}</th>
                        <td>{{ field }}</td>
                    </tr>
                {% endfor %}
          </tbody>
      </table>
        <button type="submit" class="btn btn-outline-dark">Filter</button>
</form>

       ...

{% if comics %}
    {% for comic in comics %}
            ...
    {% endfor %}

<!-- if no comics -->
{% else %}
        <p class = "my_class"> Looks like you don't have any comics! Upload some? </p>
{% endif %}

</code>```

Results:

My filter form displays the correct, distinct series for the drop down items. But When I filter by any value, the queryset returns no comics

I've also tried using the ModelChoiceFilter in my filters class with a similar result (but the values show up in a Tuple format):

```<code>series=django_filters.ModelChoiceFilter(queryset=ComicPanel.objects.all().values_list('series').distinct())
</code>```

Can someone please tell me what I'm doing wrong?

答:
My mistake was pretty silly actually,

If we look at the Django docs for field.choices:

The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.

So this method:

```<code># Grab Distinct values for series
def getUniqueSeries():
     series_dicts = ComicPanel.objects.all().values_list('series').distinct()
     series_list = []
     i = 0
     for item in series_dicts:
            series_list.append((i,item[0]))
            i = i+1
     return series_list
</code>```

returns a list that looks like: [(0,'series1'), (1, 'series2'), ...]

For my model, the first value of the tuple needs to be the series name.
So the list should look like:
[('series1','series1'), ('series2', 'series2'), ...]

So the simple fix is to change this line:

```<code>series_list.append((i,item[0]))
</code>```

to this:

```<code>series_list.append((item[0],item[0]))
</code>```

Body:
I'm using the Django filter app: https://github.com/carltongibson/django-filter

I'm making a web-comic app and what I'm trying to accomplish is a drop-down filter field that displays the distinct values for that field. In this case, the series field.

After reading their docs. And stack overflow questions like this one or this one . I can make the filter form display the correct drop down values. But when I attempt to filter by them, my result queryset returns no values!

There must be something in the docs I'm not understanding. Here's my hopefully relevant code.

models.py

class ComicPanel(models.Model):
    #... Other fields

    series = models.CharField(max_length = 255, null = False, blank = False, default = getMainSeriesName)

    # Other Filter Fields
    chapter = models.FloatField(null = True, blank = True)

    episode = models.IntegerField(null = True, blank = True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['series','chapter', 'episode'])
            ]

    def __str__(self):
        return self.title

    def save(self):
        super(ComicPanel, self).save()

filters.py

import django_filters
from .models import ComicPanel

# Grab Distinct values for series
def getUniqueSeries():
    series_dicts = ComicPanel.objects.all().values_list('series').distinct()
    series_list = []
    i = 0
    for item in series_dicts:
            series_list.append((i,item[0]))
            i = i+1
    return series_list

class ComicPanelFilter(django_filters.FilterSet):

    series = django_filters.ChoiceFilter(choices = getUniqueSeries())

    class Meta:
        model = ComicPanel
        fields = ['chapter', 'episode']

views.py

def view_archive(request):
    comic_list = ComicPanel.objects.all()
    comic_filter = ComicPanelFilter(request.GET, queryset=comic_list)
    paginator = Paginator(comic_filter.qs, 8)

    page = request.GET.get('page', 1)
    try:
        comics = paginator.page(page)
    except (PageNotAnInteger, TypeError):
        comics = paginator.page(1)
    except EmptyPage:
        comics = paginator.page(paginator.num_pages)

    return render(request, 'comics/comic_archive.html', context = {'filter': comic_filter, 'comics': comics})

template.html

...

<form class="form" method="GET">
    {% csrf_token %}

          Filter Comics:

                {% for field in filter.form %}

                         {{ field.name }}
                        {{ field }}

                {% endfor %}

        <button type="submit" class="btn btn-outline-dark">Filter</button>
</form>

       ...

{% if comics %}
    {% for comic in comics %}
            ...
    {% endfor %}

{% else %}

 Looks like you don't have any comics! Upload some?

{% endif %}

Results:

My filter form displays the correct, distinct series for the drop down items. But When I filter by any value, the queryset returns no comics

I've also tried using the ModelChoiceFilter in my filters class with a similar result (but the values show up in a Tuple format):

series=django_filters.ModelChoiceFilter(queryset=ComicPanel.objects.all().values_list('series').distinct())

Can someone please tell me what I'm doing wrong?

Body:
My mistake was pretty silly actually,

If we look at the Django docs for field.choices:

The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.

So this method:

# Grab Distinct values for series
def getUniqueSeries():
     series_dicts = ComicPanel.objects.all().values_list('series').distinct()
     series_list = []
     i = 0
     for item in series_dicts:
            series_list.append((i,item[0]))
            i = i+1
     return series_list

returns a list that looks like: [(0,'series1'), (1, 'series2'), ...]

For my model, the first value of the tuple needs to be the series name.
So the list should look like:
[('series1','series1'), ('series2', 'series2'), ...]

So the simple fix is to change this line:

series_list.append((i,item[0]))

to this:

series_list.append((item[0],item[0]))


问:
MERGE command results in gaps in sequence numbers
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

```<code>-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

```<code>INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.

答: Per the Snowflake documentation, Snowflake does not guarantee there will be no gaps in sequences. https://docs.snowflake.net/manuals/user-guide/querying-sequences.html.</p>

Body:
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.


问:
Conventional Routing in ASP.NET Core API
Problem:

I'm creating an API Application with NET Core 3.1.
I'd like to avoid to set route attribute over every ApiControllers and Actions. I tryed a lot of combinations over UseEndpoints to set a conventional route, but i'm failing.

With some configuration I can't get the Api working, with some others I get this exception during startup:

InvalidOperationException: Action 'ApiIsWorking' does not have an
  attribute route. Action methods on controllers annotated with
  ApiControllerAttribute must be attribute routed.

How can i set the startup.cs to auto map controllers with their class name and actions with their method name?

Thank you!

Some code:

startup.cs

```<code>...
services.AddControllers()
...

app.UseHttpsRedirection()
   .UseRouting()
   .UseAuthentication()
   .UseEndpoints(endpoints => ?? )
   .UseCoreHttpContext()
   .UseServerConfiguration();
</code>```

controller.cs

```<code>[ApiController]
public class BaseAPI : ControllerBase
{
        [HttpGet]
        public string ApiIsWorking()
        {
            return "API is working!";
        }
}
</code>```

Solution:

As Reza Aghaei says in the solution, the error was to add the ApiController attribute. After I removed it, the command UseEndpoints start to work.

My mistake was to add the attribute to be able to recognize which classes should be exposed via API. It wasn't necessary because UseEndpoints maps only the classes that inherit from ControllerBase.

Warning:

1) Conventional Routing require [FromBody] attribute in actions params.

2) I highlight Zinov's response about conventional routing problems with Swashbuckle in .NET Core

答:
Here is my advice if you are going down this road of using conventional routing with .net core.
After you finish your API implementation you are going to add some documentation to it. People normally use this nuget package Swashbuckle.AspNetCore, which implements the later standard of OpenAPI(Swagger). But here is the problem when you use conventional routing and you want to generate the documentation with this tool.

if you are using conventional routing (as opposed to attribute routing), any controllers and the actions on those controllers that use conventional routing will not be represented in ApiExplorer, which means Swashbuckle won't be able to find those controllers and generate Swagger operations from them

For more information refer to this link : Swashbuckle
Hope this saves you a lot of headaches in the future with the documentation for your api

Body:
Problem:

I'm creating an API Application with NET Core 3.1.
I'd like to avoid to set route attribute over every ApiControllers and Actions. I tryed a lot of combinations over UseEndpoints to set a conventional route, but i'm failing.

With some configuration I can't get the Api working, with some others I get this exception during startup:

InvalidOperationException: Action 'ApiIsWorking' does not have an
  attribute route. Action methods on controllers annotated with
  ApiControllerAttribute must be attribute routed.

How can i set the startup.cs to auto map controllers with their class name and actions with their method name?

Thank you!

Some code:

startup.cs

...
services.AddControllers()
...

app.UseHttpsRedirection()
   .UseRouting()
   .UseAuthentication()
   .UseEndpoints(endpoints => ?? )
   .UseCoreHttpContext()
   .UseServerConfiguration();

controller.cs

[ApiController]
public class BaseAPI : ControllerBase
{
        [HttpGet]
        public string ApiIsWorking()
        {
            return "API is working!";
        }
}

Solution:

As Reza Aghaei says in the solution, the error was to add the ApiController attribute. After I removed it, the command UseEndpoints start to work.

My mistake was to add the attribute to be able to recognize which classes should be exposed via API. It wasn't necessary because UseEndpoints maps only the classes that inherit from ControllerBase.

Warning:

1) Conventional Routing require [FromBody] attribute in actions params.

2) I highlight Zinov's response about conventional routing problems with Swashbuckle in .NET Core


问:
ZeroBrain Studio cant open utf-16 le codind ini file
Im tryin to open uft 16 le code ini file in Zerobarane Studio and get error: Binary file is shown as read-only as it is only partially loaded.
However it opens fine in win 10 notepad.</p>

答: You can use version 1.90 of ZeroBrane Studio, as it has better handling of binary files, but it will not decode UTF-16 files for you, as it expects UTF-8 encoding.</p>


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答:
Generics.
(also - don't try to cram and pass yourself off as an expert on something.  A good interviewer will figure that out very, very quickly.)</p>

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: plinth


问:
How to find all the colors between two colors?
I need to pick two colors, then find X colors (or tones) between them, each one separated with the same 'distance' of the other.

I still don't understand how colors are formed. Should I try using HSV, RGB, or hex?

答:
The simplest thing to do is to take the RGB values of the first and the second color and interpolate them together ie.

```<code>$b1 = $color1['blue'];
$b2 = $color2['blue'];

for($i=0; $i<$X; $i++){
    $b = round($b1 + (1.0 * ($b2 - $b1) * $i / $X));
    // Do the same for the red / green values
}
</code>```

EDIT:  You can also use the HSV value instead of the RGB value

Body:
The simplest thing to do is to take the RGB values of the first and the second color and interpolate them together ie.

$b1 = $color1['blue'];
$b2 = $color2['blue'];

for($i=0; $i<$X; $i++){
    $b = round($b1 + (1.0 * ($b2 - $b1) * $i / $X));
    // Do the same for the red / green values
}

EDIT:  You can also use the HSV value instead of the RGB value


问:
Image size issue while taking a screenshot of the secondary monitor
I am trying to save a screenshot of the second monitor which has a different resolution/DPI  than the primary monitor (I am not totally familiar with these terminologies so I am not very sure), this is the code that I am using:

public void SaveScreenshot(Screen screen)
{
    using (Bitmap bitmap = new Bitmap(screen.Bounds.Width, screen.Bounds.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            int x = screen.Bounds.Left;
            int y = screen.Bounds.Top;
            int w = screen.Bounds.Width;
            int h = screen.Bounds.Height;
            g.CopyFromScreen(x, y, 0, 0, new Size(w, h));
        }

        bitmap.Save("screenshot.bmp");
    }
}
```

The problem is that the resulting image doesn't have the whole picture, instead, it has a larger and cropped one.

Actual:

result:

I don't know what I'm doing wrong.

答:
I managed to solve it by using EnumDisplaySettings:

using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ScreenResolution
{
    class ScreenResolutionHandler
    {
        const int ENUM_CURRENT_SETTINGS = -1;
        public static Rectangle GetRealRectangle(Screen screen)
        {
            DEVMODE dm = new DEVMODE();
            dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
            EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm);
            return new Rectangle(dm.dmPositionX, dm.dmPositionY, dm.dmPelsWidth, dm.dmPelsHeight);
        }

        [DllImport("user32.dll")]
        public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);

        [StructLayout(LayoutKind.Sequential)]
        public struct DEVMODE
        {
            private const int CCHDEVICENAME = 0x20;
            private const int CCHFORMNAME = 0x20;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
            public string dmDeviceName;
            public short dmSpecVersion;
            public short dmDriverVersion;
            public short dmSize;
            public short dmDriverExtra;
            public int dmFields;
            public int dmPositionX;
            public int dmPositionY;
            public ScreenOrientation dmDisplayOrientation;
            public int dmDisplayFixedOutput;
            public short dmColor;
            public short dmDuplex;
            public short dmYResolution;
            public short dmTTOption;
            public short dmCollate;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
            public string dmFormName;
            public short dmLogPixels;
            public int dmBitsPerPel;
            public int dmPelsWidth;
            public int dmPelsHeight;
            public int dmDisplayFlags;
            public int dmDisplayFrequency;
            public int dmICMMethod;
            public int dmICMIntent;
            public int dmMediaType;
            public int dmDitherType;
            public int dmReserved1;
            public int dmReserved2;
            public int dmPanningWidth;
            public int dmPanningHeight;
        }
    }
}

```

<p>and editing the original code to</p>

<pre class="lang-cs prettyprint-override"><code>public void SaveScreenshot(Screen screen)
{
    Rectangle rect = ScreenResolutionHandler.GetRealRectangle(screen);
    int x = rect.X;
    int y = rect.Y;
    int w = rect.Width;
    int h = rect.Height;

    using (Bitmap bitmap = new Bitmap(w, h))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.CopyFromScreen(x,y, 0, 0, new Size(w, h));
        }

        bitmap.Save("screenshot.bmp");
    }
}
</code>```

Update:

As @Jimi suggested, eventually I had to enable per-monitor dpi-awareness to maintain the quality of the image when putting it on the Form

app.manifest

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>

        <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

        <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

        <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

        <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
</compatibility>

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
        <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
        <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness>
    </windowsSettings>
</application>
```

Body:
I am trying to save a screenshot of the second monitor which has a different resolution/DPI  than the primary monitor (I am not totally familiar with these terminologies so I am not very sure), this is the code that I am using:

public void SaveScreenshot(Screen screen)
{
    using (Bitmap bitmap = new Bitmap(screen.Bounds.Width, screen.Bounds.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            int x = screen.Bounds.Left;
            int y = screen.Bounds.Top;
            int w = screen.Bounds.Width;
            int h = screen.Bounds.Height;
            g.CopyFromScreen(x, y, 0, 0, new Size(w, h));
        }

        bitmap.Save("screenshot.bmp");
    }
}

The problem is that the resulting image doesn't have the whole picture, instead, it has a larger and cropped one.

Actual:

result:

I don't know what I'm doing wrong.

Body:
I managed to solve it by using EnumDisplaySettings:

using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ScreenResolution
{
    class ScreenResolutionHandler
    {
        const int ENUM_CURRENT_SETTINGS = -1;
        public static Rectangle GetRealRectangle(Screen screen)
        {
            DEVMODE dm = new DEVMODE();
            dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
            EnumDisplaySettings(screen.DeviceName, ENUM_CURRENT_SETTINGS, ref dm);
            return new Rectangle(dm.dmPositionX, dm.dmPositionY, dm.dmPelsWidth, dm.dmPelsHeight);
        }

        [DllImport("user32.dll")]
        public static extern bool EnumDisplaySettings(string lpszDeviceName, int iModeNum, ref DEVMODE lpDevMode);

        [StructLayout(LayoutKind.Sequential)]
        public struct DEVMODE
        {
            private const int CCHDEVICENAME = 0x20;
            private const int CCHFORMNAME = 0x20;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
            public string dmDeviceName;
            public short dmSpecVersion;
            public short dmDriverVersion;
            public short dmSize;
            public short dmDriverExtra;
            public int dmFields;
            public int dmPositionX;
            public int dmPositionY;
            public ScreenOrientation dmDisplayOrientation;
            public int dmDisplayFixedOutput;
            public short dmColor;
            public short dmDuplex;
            public short dmYResolution;
            public short dmTTOption;
            public short dmCollate;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
            public string dmFormName;
            public short dmLogPixels;
            public int dmBitsPerPel;
            public int dmPelsWidth;
            public int dmPelsHeight;
            public int dmDisplayFlags;
            public int dmDisplayFrequency;
            public int dmICMMethod;
            public int dmICMIntent;
            public int dmMediaType;
            public int dmDitherType;
            public int dmReserved1;
            public int dmReserved2;
            public int dmPanningWidth;
            public int dmPanningHeight;
        }
    }
}

and editing the original code to

public void SaveScreenshot(Screen screen)
{
    Rectangle rect = ScreenResolutionHandler.GetRealRectangle(screen);
    int x = rect.X;
    int y = rect.Y;
    int w = rect.Width;
    int h = rect.Height;

    using (Bitmap bitmap = new Bitmap(w, h))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.CopyFromScreen(x,y, 0, 0, new Size(w, h));
        }

        bitmap.Save("screenshot.bmp");
    }
}

Update:

As @Jimi suggested, eventually I had to enable per-monitor dpi-awareness to maintain the quality of the image when putting it on the Form

app.manifest

<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
        <!-- A list of the Windows versions that this application has been tested on
           and is designed to work with. Uncomment the appropriate elements
           and Windows will automatically select the most compatible environment. -->

        <!-- Windows Vista -->
        <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->

        <!-- Windows 7 -->
        <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

        <!-- Windows 8 -->
        <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

        <!-- Windows 8.1 -->
        <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

        <!-- Windows 10 -->
        <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
</compatibility>

<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings>
        <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <!-- legacy -->
        <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness> <!-- falls back to pm if pmv2 is not available -->
    </windowsSettings>
</application>


问:
Wordpress Graphql - Can I filter by acf column?
I'm trying to filter my query result of spost (my cpt), but I can not find the option to filter by acf columns. Is there any way for WPGraphQL to filter result by acf?

答:
There is no way to filter connection by ACF field, due to how costly this feature would be on the database. The only alternative at the moment is adding there parameter to connection using WPGraphQL connection API.

https://docs.wpgraphql.com/extending/connections/


问:
Runtime element substition in a tree structure
I'm implementing a REST API client in c++ that needs to be able to discover the structure of the API at runtime. The structure of the REST API could change during the program execution as well. The API model is based on json arrays and objects. If an array is returned it means the retrieved element is a node and if an object is returned it means the retrieved element is a leaf.

In order to represent the data I'm modeling I decided to use the composite pattern to give a common interface to users to the tree structure (node or leaf).

And to provide hooks to my model to some GUI or CLI I decided to use the Visitor pattern in order to visit the nodes and leaves.

I tried to implement the discovery part of the model using the Visitor pattern as well but it is clearly not suited for the task because I need to replace previously allocated objects of a derived type to another type (eg: a leaf becomes a node). Which seems to me impossible using the Visitor pattern because an object can't replace itself.

I tried to add some container classes to wrap my objects but I ended up in a similar situation where I need an object to replace itself.

I read online about design patterns to try and find one that could help me out but I haven't found any that seems suitable.

Here's the code I have so far - the most relevant part is at the end (class Discover):

```<code>#include <string>
#include <deque>
#include <stack>
#include <iostream>

class Visitor;

class Element{
public:
  Element(std::string name, Element* parent) : name{ name }, parent{ parent }{}
  std::string get_name(){
    return name;
  }
  std::string get_url(){
    std::stack<std::string> url_stack;
    Element* ancestor = parent;
    url_stack.push(name);
    while(ancestor != NULL){
      url_stack.push(ancestor->name);
      ancestor = ancestor->parent;
    }
    std::string url;
    while(!url_stack.empty()){
      url.append(url_stack.top());
      url_stack.pop();
    }
    return url;
  }
  Element* get_parent(void){
    return parent;
  }
  virtual ~Element(void){};
  virtual void accept(Visitor& visitor) = 0;
private:
  std::string name;
  Element* parent;
};

class ElementEmpty : public Element{
public:
  ElementEmpty(std::string name, Element* parent = NULL) : Element(name, parent){}
  virtual void accept(Visitor& visitor);
};

class ElementLeaf : public Element{
public:
  ElementLeaf(std::string name, std::string value, Element* parent = NULL) : Element(name, parent), value{ value }{}
  virtual void accept(Visitor& visitor);
  std::string value;
};

class ElementComposite : public Element{
public:
  ElementComposite(std::string name, std::deque<std::string> value_names, Element* parent = NULL) : Element(name, parent){
    for(auto& vn : value_names){
      values.emplace_back(new ElementEmpty(vn, this));
    }
  }
  ~ElementComposite(){
    while(!values.empty()){
      delete values.back();
      values.pop_back();
    }
  }
  virtual void accept(Visitor& visitor);
  std::deque<Element*> values;
};

class Visitor{
public:
  virtual void visit(ElementEmpty& empty) = 0;
  virtual void visit(ElementLeaf& leaf) = 0;
  virtual void visit(ElementComposite& composite) = 0;
};

void ElementEmpty::accept(Visitor& visitor){
  visitor.visit(*this);
}

void ElementLeaf::accept(Visitor& visitor){
  visitor.visit(*this);
}

void ElementComposite::accept(Visitor& visitor){
  visitor.visit(*this);
}

class Printer : public Visitor{
public:
  virtual void visit(ElementEmpty& empty){
    std::cout << empty.get_name() << " is empty" << std::endl;
  }
  virtual void visit(ElementLeaf& leaf){
    std::cout << leaf.get_name() << " is a leaf with value" << leaf.value << std::endl;
  }
  virtual void visit(ElementComposite& composite){
    std::cout << composite.get_name() << " is composite, visiting childrens" << std::endl;
    for(auto& v : composite.values){
      v->accept(*this);
    }
  }
};

class Discover : public Visitor{
public:
  virtual void visit(ElementEmpty& empty){
    discover(&empty);
  }
  virtual void visit(ElementLeaf& leaf){
    discover(&leaf);
  }
  virtual void visit(ElementComposite& composite){
    discover(&composite);
    for(auto& v : composite.values){
      v->accept(*this);
    }
  }
private:
  void discover(Element* element){
    std::string url = element->get_url();
    //HTTP GET (pseudo-code here to avoid adding irelevant code)
    json_val value = http_get(url);
    Element* new_element;
    if(value.is_array()){
      new_element = new ElementComposite(element->get_name(), value.as_array().as_deque(), element->get_parent());
    }
    else if(value.is_object()){
      new_element = new ElementLeaf(element->get_name(), value.as_string(), element->get_parent());
    }
    else{
      new_element = new ElementEmpty(element->get_name(), element->get_parent());
    }

    //TODO: How to set element to new_element? it's impossible since we are currently in element->accept()....
  }

};
</code>```

Is there any way I could manage to replace previously allocated objects at runtime without having to add an array of pointers to the created objects and changing them when needed?

Thanks!

答:
For all the Elements you allocate in the provided code, you do so dynamically, by calling new.

Will that also be true for ALL elements that discover() might get called on?

If so, at the root of the call somewhere, will be the true owner of that Element. How about changing the interface of discover(), for example, so that it returns a pointer to the new Element, all the way down the call chain to the true owner of the old Element? Then that owner could just delete the old Element, and start storing the pointer to the freshly allocated Element in its place.

Of, course, the usual - don't use raw pointers, use std::unique_ptr or std::shared_ptr, or whatever else is suitable, etc. But the above code transformation is still possible with those as well.

Body:
I'm implementing a REST API client in c++ that needs to be able to discover the structure of the API at runtime. The structure of the REST API could change during the program execution as well. The API model is based on json arrays and objects. If an array is returned it means the retrieved element is a node and if an object is returned it means the retrieved element is a leaf.

In order to represent the data I'm modeling I decided to use the composite pattern to give a common interface to users to the tree structure (node or leaf).

And to provide hooks to my model to some GUI or CLI I decided to use the Visitor pattern in order to visit the nodes and leaves.

I tried to implement the discovery part of the model using the Visitor pattern as well but it is clearly not suited for the task because I need to replace previously allocated objects of a derived type to another type (eg: a leaf becomes a node). Which seems to me impossible using the Visitor pattern because an object can't replace itself.

I tried to add some container classes to wrap my objects but I ended up in a similar situation where I need an object to replace itself.

I read online about design patterns to try and find one that could help me out but I haven't found any that seems suitable.

Here's the code I have so far - the most relevant part is at the end (class Discover):

#include <string>
#include <deque>
#include <stack>
#include <iostream>

class Visitor;

class Element{
public:
  Element(std::string name, Element* parent) : name{ name }, parent{ parent }{}
  std::string get_name(){
    return name;
  }
  std::string get_url(){
    std::stack<std::string> url_stack;
    Element* ancestor = parent;
    url_stack.push(name);
    while(ancestor != NULL){
      url_stack.push(ancestor->name);
      ancestor = ancestor->parent;
    }
    std::string url;
    while(!url_stack.empty()){
      url.append(url_stack.top());
      url_stack.pop();
    }
    return url;
  }
  Element* get_parent(void){
    return parent;
  }
  virtual ~Element(void){};
  virtual void accept(Visitor& visitor) = 0;
private:
  std::string name;
  Element* parent;
};

class ElementEmpty : public Element{
public:
  ElementEmpty(std::string name, Element* parent = NULL) : Element(name, parent){}
  virtual void accept(Visitor& visitor);
};

class ElementLeaf : public Element{
public:
  ElementLeaf(std::string name, std::string value, Element* parent = NULL) : Element(name, parent), value{ value }{}
  virtual void accept(Visitor& visitor);
  std::string value;
};

class ElementComposite : public Element{
public:
  ElementComposite(std::string name, std::deque<std::string> value_names, Element* parent = NULL) : Element(name, parent){
    for(auto& vn : value_names){
      values.emplace_back(new ElementEmpty(vn, this));
    }
  }
  ~ElementComposite(){
    while(!values.empty()){
      delete values.back();
      values.pop_back();
    }
  }
  virtual void accept(Visitor& visitor);
  std::deque<Element*> values;
};

class Visitor{
public:
  virtual void visit(ElementEmpty& empty) = 0;
  virtual void visit(ElementLeaf& leaf) = 0;
  virtual void visit(ElementComposite& composite) = 0;
};

void ElementEmpty::accept(Visitor& visitor){
  visitor.visit(*this);
}

void ElementLeaf::accept(Visitor& visitor){
  visitor.visit(*this);
}

void ElementComposite::accept(Visitor& visitor){
  visitor.visit(*this);
}

class Printer : public Visitor{
public:
  virtual void visit(ElementEmpty& empty){
    std::cout << empty.get_name() << " is empty" << std::endl;
  }
  virtual void visit(ElementLeaf& leaf){
    std::cout << leaf.get_name() << " is a leaf with value" << leaf.value << std::endl;
  }
  virtual void visit(ElementComposite& composite){
    std::cout << composite.get_name() << " is composite, visiting childrens" << std::endl;
    for(auto& v : composite.values){
      v->accept(*this);
    }
  }
};

class Discover : public Visitor{
public:
  virtual void visit(ElementEmpty& empty){
    discover(&empty);
  }
  virtual void visit(ElementLeaf& leaf){
    discover(&leaf);
  }
  virtual void visit(ElementComposite& composite){
    discover(&composite);
    for(auto& v : composite.values){
      v->accept(*this);
    }
  }
private:
  void discover(Element* element){
    std::string url = element->get_url();
    //HTTP GET (pseudo-code here to avoid adding irelevant code)
    json_val value = http_get(url);
    Element* new_element;
    if(value.is_array()){
      new_element = new ElementComposite(element->get_name(), value.as_array().as_deque(), element->get_parent());
    }
    else if(value.is_object()){
      new_element = new ElementLeaf(element->get_name(), value.as_string(), element->get_parent());
    }
    else{
      new_element = new ElementEmpty(element->get_name(), element->get_parent());
    }

    //TODO: How to set element to new_element? it's impossible since we are currently in element->accept()....
  }

};

Is there any way I could manage to replace previously allocated objects at runtime without having to add an array of pointers to the created objects and changing them when needed?

Thanks!


问:
JQuery remove .append after 5 seconds
Oh gosh here a lot today - oops

Folks, best way to do this:

```<code>$j('.done').append('Your services have been updated');
</code>```

(that bits done)

but then remove the append  after say 5 seconds so that if a person resubmits a form(allowed) the append does not continue adding the text? i.e updated once "Your services have been updated", twice would read "Your services have been updated Your services have been updated" but I would only want Your services have been updated to show once

答:
I know its kinda late but I wanna share to you my solution as I added this to my global functionality .

function alert(elem,content,type,posi){

    //elem - element to be inserted
    //content - content of the alert box (based from bootstrap)
    //type -  alert type
    //posi - either append or prepend

    //primary, secondary, success, warning, info, danger, light, dark
    if(type == undefined)
       type = 'info';

    elem.find('.glb-alert').remove();
    var a = '
'+content+'
';

    if(posi == undefined|| posi == 'prepend')
       elem.prepend(a).find('.glb-alert').delay(1200).fadeOut();
    else if(posi == 'append')
       elem.append(a).find('.glb-alert').delay(1200).fadeOut();

}```

Title: JQuery remove .append after 5 seconds

Body:
Oh gosh here a lot today - oops

Folks, best way to do this:

$j('.done').append('Your services have been updated');

(that bits done)

but then remove the append  after say 5 seconds so that if a person resubmits a form(allowed) the append does not continue adding the text? i.e updated once "Your services have been updated", twice would read "Your services have been updated Your services have been updated" but I would only want Your services have been updated to show once

Body:
I know its kinda late but I wanna share to you my solution as I added this to my global functionality .

function alert(elem,content,type,posi){

    //elem - element to be inserted
    //content - content of the alert box (based from bootstrap)
    //type -  alert type
    //posi - either append or prepend

    //primary, secondary, success, warning, info, danger, light, dark
    if(type == undefined)
       type = 'info';

    elem.find('.glb-alert').remove();
    var a = '<div class="alert alert-danger col-md-12 glb-alert" role="alert" >'+content+'</div>';

    if(posi == undefined|| posi == 'prepend')
       elem.prepend(a).find('.glb-alert').delay(1200).fadeOut();
    else if(posi == 'append')
       elem.append(a).find('.glb-alert').delay(1200).fadeOut();

}


问:
How to return a vector of pairs
I am trying to solve this challenge from testdome. I think my approach to the solution is not optimal (or even correct). But before changing my approach I was wondering is it possible to return a vector of pairs? if yes, how?.
Below you will see the challenge, and afterwards my code.
Thank you.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){

            if (list[i]+list[j] == sum)
                list1.push_back(std::make_pair(list[i], list[j]) );
        }
        tracker--;
    }

    return list1; // I am stuck here

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif
```

<p><strong>EDIT</strong></p>

<p>Initially, this was my solution. But once I posted it on testdome, I am getting zero correct answers out of 4 categories. It is test number 5. That is why I thought, returning only one answer was wrong.</p>

<pre class="lang-c++ prettyprint-override"><code>
#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
            if (list[i]+list[j] == sum)

                return result=std::make_pair(list[i], list[j]);
        }
        tracker--;
    }

    return std::make_pair(-1,-1);

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif
</code>```

答:
If you are using C++17, you have two options:

use auto return type deduction

auto create_vector_of_pairs() {
    std::vector<std::pair<int, int>> v;
    v.emplace_back(1, 2);
    v.emplace_back(3, 4);
    v.emplace_back(5, 6);
    return v;
}
```

<ol start="2">
<li>use <code>std::vector<std::pair<...>></code> as return type</li>
</ol>

<pre class="lang-cpp prettyprint-override"><code>std::vector<std::pair<int, int>> create_vector_of_pairs() {
    std::vector<std::pair<int, int>> v;
    v.emplace_back(1, 2);
    v.emplace_back(3, 4);
    v.emplace_back(5, 6);
    return v;
}
</code>```

Then, whatever option from above you choose, in your main function you could do something like:

std::vector<std::pair<int, int>> v = create_vector_of_pairs();
```

<p>or</p>

<pre class="lang-cpp prettyprint-override"><code>auto v = create_vector_of_pairs();
</code>```

Title: How to return a vector of pairs

Body:
I am trying to solve this challenge from testdome. I think my approach to the solution is not optimal (or even correct). But before changing my approach I was wondering is it possible to return a vector of pairs? if yes, how?.
Below you will see the challenge, and afterwards my code.
Thank you.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){

            if (list[i]+list[j] == sum)
                list1.push_back(std::make_pair(list[i], list[j]) );
        }
        tracker--;
    }

    return list1; // I am stuck here

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif

EDIT

Initially, this was my solution. But once I posted it on testdome, I am getting zero correct answers out of 4 categories. It is test number 5. That is why I thought, returning only one answer was wrong.

#include <stdexcept>
#include <iostream>
#include <vector>
#include <utility>

std::pair<int, int> findTwoSum(const std::vector<int>& list, int sum)
{
    int tracker = list.size();
    std::pair <int, int> result;
    std::vector <std::pair <int,int>> list1(100);
    for (int i = 0; i < (int)list.size(); i++){
        for (int j = ((int)list.size()-tracker); j < (int)list.size(); j++){
            if (list[i]+list[j] == sum)

                return result=std::make_pair(list[i], list[j]);
        }
        tracker--;
    }

    return std::make_pair(-1,-1);

    //throw std::logic_error("Waiting to be implemented");
}

#ifndef RunTests
int main()
{
    std::vector<int> list = {3, 1, 5, 7, 5, 9};
    std::pair<int, int> indices = findTwoSum(list, 10);
    std::cout << indices.first << '\n' << indices.second;
}
#endif

Body:
If you are using C++17, you have two options:

use auto return type deduction

auto create_vector_of_pairs() {
    std::vector<std::pair<int, int>> v;
    v.emplace_back(1, 2);
    v.emplace_back(3, 4);
    v.emplace_back(5, 6);
    return v;
}

use std::vector<std::pair<...>> as return type

std::vector<std::pair<int, int>> create_vector_of_pairs() {
    std::vector<std::pair<int, int>> v;
    v.emplace_back(1, 2);
    v.emplace_back(3, 4);
    v.emplace_back(5, 6);
    return v;
}

Then, whatever option from above you choose, in your main function you could do something like:

std::vector<std::pair<int, int>> v = create_vector_of_pairs();

or

auto v = create_vector_of_pairs();


问:
ColdFusion: When to define session variables?
When a user requests a page, is this when a session is started for that user? From what I can tell, a session is started as soon as you make a page request...

If this is the case, when do you create session variables? i.e. username, password, preferences, etc... just any time?

答:
Yes the session scope for the user is setup on the first request. However it depends on your preference as to when you want to set various flags and values. You probably don't want to put password in the session scope though.

What I like to do is put user specific values in a user struct. So on request start I'd check for the variable and setup if it doesn't exist. For example...

```<code><cfif not structkeyexists(session, "user")>
    <cfset session.user = {
        authorized = false
        , admin = false
        , username = ''
        , accountid = ''
        <!--- etc --->
    } />
</cfif>
</code>```

When the user logs in you can then fill in the appropriate values and set session.user.authorized = true

When the user logs out the nice thing about this approach is you can just delete the users struct.

```<code><cfset structdelete(session, "user") />
</code>```

Then on the next page the check will be made again for the user struct and created if it doesn't exist.

Body:
Yes the session scope for the user is setup on the first request. However it depends on your preference as to when you want to set various flags and values. You probably don't want to put password in the session scope though.

What I like to do is put user specific values in a user struct. So on request start I'd check for the variable and setup if it doesn't exist. For example...

<cfif not structkeyexists(session, "user")>
    <cfset session.user = {
        authorized = false
        , admin = false
        , username = ''
        , accountid = ''
        <!--- etc --->
    } />
</cfif>

When the user logs in you can then fill in the appropriate values and set session.user.authorized = true

When the user logs out the nice thing about this approach is you can just delete the users struct.

<cfset structdelete(session, "user") />

Then on the next page the check will be made again for the user struct and created if it doesn't exist.


问:
ESP32 AsyncWebServer
I currently trying to setup an Async Web Server on the ESP32. But unfortunately I don't get the code to run. I'm usign platform io on windows 10.

```<code>#include <Arduino.h>
#include <ESPAsyncWebServer.h>

const char* ssid = "myAP";
const char* password = "123456789";

AsyncWebServer server(80);

</code>```

setup() and loop() are empty.
If I try to compile the code these message shows up.

```<code>compilation terminated.
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp: In constructor 'AsyncPrinter::AsyncPrinter(AsyncClient*, size_t)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp:48:11: error: 'panic' was not declared in this scope
     panic(); //What should we do?
           ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp: In member function 'int AsyncPrinter::connect(IPAddress, uint16_t)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp:71:11: error: 'panic' was not declared in this scope
     panic();
           ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp: In member function 'size_t AsyncPrinter::_sendBuffer()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp:182:11: error: 'panic' was not declared in this scope
     panic(); // Connection should be aborted instead
           ^
                       ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCPbuffer.cpp: In member function 'size_t AsyncTCPbuffer::_handleRxBuffer(uint8_t*, size_t)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCPbuffer.cpp:469:21: error: 'panic' was not declared in this scope
               panic(); //TODO: What action should this be ?

C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'bool AsyncClient::operator==(const AsyncClient&)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:331:66: error: 'ip_addr_t {aka struct ip_addr}' has no membec
r named 'addr'
   return (_pcb != NULL && other._pcb != NULL && (_pcb->remote_ip.addr == other._pcb->remote_ip.addr) && (_pcb->remote_port == other._pcb->remote_port));
                                                                  ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'void AsyncClient::_dns_found(const ip_addr*)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:707:31: error: 'const struct ip_addr' has no member named 'addr'
     connect(IPAddress(ipaddr->addr), _connect_port);
                               ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'uint32_t AsyncClient::getRemoteAddress()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:837:26: error: 'ip_addr_t {aka struct ip_addr}' has no member named 'addr'
   return _pcb->remote_ip.addr;
                          ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'uint32_t AsyncClient::getLocalAddress()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:849:25: error: 'ip_addr_t {aka struct ip_addr}' has no member named 'addr'
   return _pcb->local_ip.addr;
                         ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'void AsyncServer::begin()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:1122:14: error: 'ip_addr_t {aka struct ip_addr}' has no member named 'addr'
   local_addr.addr = (uint32_t) _addr;
              ^
</code>```

答:
You're using the wrong async TCP library. The one you're using is for the ESP8266, not the ESP32.

Here's its PlatformIO library registry entry:

https://platformio.org/lib/show/305/ESPAsyncTCP

You're seeing errors because it's trying to call functions that are available on the ESP8266 and not the ESP32.

You want the AsyncTCP library:

https://platformio.org/lib/show/1826/AsyncTCP

You should update your platformio.lib file to include this library instead of ESPAsyncTCP. You may also need to remove the build or library directory to get rid of the old library.

Title: ESP32 AsyncWebServer

Body:
I currently trying to setup an Async Web Server on the ESP32. But unfortunately I don't get the code to run. I'm usign platform io on windows 10.

#include <Arduino.h>
#include <ESPAsyncWebServer.h>

const char* ssid = "myAP";
const char* password = "123456789";

AsyncWebServer server(80);

setup() and loop() are empty.
If I try to compile the code these message shows up.

compilation terminated.
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp: In constructor 'AsyncPrinter::AsyncPrinter(AsyncClient*, size_t)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp:48:11: error: 'panic' was not declared in this scope
     panic(); //What should we do?
           ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp: In member function 'int AsyncPrinter::connect(IPAddress, uint16_t)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp:71:11: error: 'panic' was not declared in this scope
     panic();
           ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp: In member function 'size_t AsyncPrinter::_sendBuffer()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\AsyncPrinter.cpp:182:11: error: 'panic' was not declared in this scope
     panic(); // Connection should be aborted instead
           ^
                       ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCPbuffer.cpp: In member function 'size_t AsyncTCPbuffer::_handleRxBuffer(uint8_t*, size_t)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCPbuffer.cpp:469:21: error: 'panic' was not declared in this scope
               panic(); //TODO: What action should this be ?

C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'bool AsyncClient::operator==(const AsyncClient&)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:331:66: error: 'ip_addr_t {aka struct ip_addr}' has no membec
r named 'addr'
   return (_pcb != NULL && other._pcb != NULL && (_pcb->remote_ip.addr == other._pcb->remote_ip.addr) && (_pcb->remote_port == other._pcb->remote_port));
                                                                  ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'void AsyncClient::_dns_found(const ip_addr*)':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:707:31: error: 'const struct ip_addr' has no member named 'addr'
     connect(IPAddress(ipaddr->addr), _connect_port);
                               ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'uint32_t AsyncClient::getRemoteAddress()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:837:26: error: 'ip_addr_t {aka struct ip_addr}' has no member named 'addr'
   return _pcb->remote_ip.addr;
                          ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'uint32_t AsyncClient::getLocalAddress()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:849:25: error: 'ip_addr_t {aka struct ip_addr}' has no member named 'addr'
   return _pcb->local_ip.addr;
                         ^
C:\Users\x\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp: In member function 'void AsyncServer::begin()':
C:\Users\xanix\.platformio\lib\ESPAsyncTCP_ID305\src\ESPAsyncTCP.cpp:1122:14: error: 'ip_addr_t {aka struct ip_addr}' has no member named 'addr'
   local_addr.addr = (uint32_t) _addr;
              ^


问:
Save tracked GPS Data with Java Script
I have written some code that tracks the GPS-Data of a user:
index.html:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
      <title>Document</title>
      <script type="text/javascript" src="tracking.js"></script>
  </head>
  <body>

    <button class="btn btn-success m-5" onclick="getLocation()">start tracking</button>

    <button class="btn btn-danger m-5" onclick="endTrack()">end tracking</button>

  </body>
</html>
</code>```

tracking.js:

```<code>var id;
var data = [];
var startTime;

function getLocation() {
    startTime = Date.now();

    if (navigator.geolocation) {
        id = navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var pos = {
        lat: position.coords.latitude,
        long: position.coords.longitude,
        time: Date.now() - startTime
    }

    data.push(pos);

    console.log("Latitude: " + position.coords.latitude +
    " Longitude: " + position.coords.longitude);
}

function endTrack() {
    console.log("tracking ended");
    navigator.geolocation.clearWatch(id);
}

function getData() {
    return data;
}
</code>```

The tracking works fine but I also need to save the data. Best for me would be if the data was saved in a file, e.g. a text file but since I am using Java Script I think this is not possible because it's client side. I know that you can create files and write in files with php but I don't know how to combine php and js in my case to get the data stored in data[] in a file when clicking the end tracking button. How would I do that?

EDIT:
I am now sending my data via ajax:

```<code>function getData() {
    var send = JSON.stringify(data);
    console.log(send)
    jQuery.post('save.php', {'data': send}, function(data, status) {
        alert("Data: " + data + "\nStatus: " + status);
    })
}
</code>```

and receive it like that:

```<code>$data = $_POST['data'];
timestamp = date('Y-m-d_H-i-s');
$datei = fopen($timestamp.".txt","x");
fwrite($datei, $data, 100);
fclose($datei);
</code>```

The problem is if I send a string that looks like that:
 [{"lat":80.08359300000001,"long":8.4771352,"time":2},{"lat":80.08359300000001,"long":8.4771352,"time":2001}]
only 100 characters are printed in the text-file, the console.log(send) shows all characters and also alert("Data: " + data + "\nStatus: " + status); shows all data, only the text-file gives a shortened version. I use XAMPP.
I also tried to increase post_max_size and upload_max_size in the php.ini but it doesn't help as well. Why aren't all characters shown? Is there a limit for post (I looked around in other posts and they all said there isn't) or is something wrong with the php or what is it? Btw: I get no error, maybe there is one in the php code but this is not shown to me because it is in another file.

答:
I found the problem: In the php-file was a limit for the amount of characters:

```<code>fwrite($datei, $data, 100);
</code>```

I just needed to change the "100"

Title: Save tracked GPS Data with Java Script

Body:
I have written some code that tracks the GPS-Data of a user:
index.html:

<!DOCTYPE html>

      <meta charset="UTF-8">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
      <title>Document</title>

    <button class="btn btn-success m-5" onclick="getLocation()">start tracking</button>

    <button class="btn btn-danger m-5" onclick="endTrack()">end tracking</button>

tracking.js:

var id;
var data = [];
var startTime;

function getLocation() {
    startTime = Date.now();

    if (navigator.geolocation) {
        id = navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var pos = {
        lat: position.coords.latitude,
        long: position.coords.longitude,
        time: Date.now() - startTime
    }

    data.push(pos);

    console.log("Latitude: " + position.coords.latitude +
    " Longitude: " + position.coords.longitude);
}

function endTrack() {
    console.log("tracking ended");
    navigator.geolocation.clearWatch(id);
}

function getData() {
    return data;
}

The tracking works fine but I also need to save the data. Best for me would be if the data was saved in a file, e.g. a text file but since I am using Java Script I think this is not possible because it's client side. I know that you can create files and write in files with php but I don't know how to combine php and js in my case to get the data stored in data[] in a file when clicking the end tracking button. How would I do that?

EDIT:
I am now sending my data via ajax:

function getData() {
    var send = JSON.stringify(data);
    console.log(send)
    jQuery.post('save.php', {'data': send}, function(data, status) {
        alert("Data: " + data + "\nStatus: " + status);
    })
}

and receive it like that:

$data = $_POST['data'];
timestamp = date('Y-m-d_H-i-s');
$datei = fopen($timestamp.".txt","x");
fwrite($datei, $data, 100);
fclose($datei);

The problem is if I send a string that looks like that:
 [{"lat":80.08359300000001,"long":8.4771352,"time":2},{"lat":80.08359300000001,"long":8.4771352,"time":2001}]
only 100 characters are printed in the text-file, the console.log(send) shows all characters and also alert("Data: " + data + "\nStatus: " + status); shows all data, only the text-file gives a shortened version. I use XAMPP.
I also tried to increase post_max_size and upload_max_size in the php.ini but it doesn't help as well. Why aren't all characters shown? Is there a limit for post (I looked around in other posts and they all said there isn't) or is something wrong with the php or what is it? Btw: I get no error, maybe there is one in the php code but this is not shown to me because it is in another file.

Body:
I found the problem: In the php-file was a limit for the amount of characters:

fwrite($datei, $data, 100);

I just needed to change the "100"


问:
Kubernetes Statefulset access and downtime
I did read up on StatefulSets which I want to use for some stateful applications, and was wondering about two things?

1) Do I need to put a service in front? Or do I just dns query the single instances, and they do have a static ip like with a service by default, disregarding what pod runs behind?

2) How does a statefulset behave when a given pod X is down? I suppose with my theory of it having a kind of "internal" service, it will just hold back any requests done while the pod behind the IP is down until a new one is there?

答:
1) Do I need to put a service in front? Or do I just dns query the
  single instances, and they do have a static ip like with a service by
  default, disregarding what pod runs behind?

StatefulSets currently require a Headless Service to be responsible for the network identity of the Pods. You are responsible for creating this Service.

2) How does a statefulset behave when a given pod X is down? I suppose
  with my theory of it having a kind of "internal" service, it will just
  hold back any requests done while the pod behind the IP is down until
  a new one is there?

StatefulSet ensures that, at any time, there is at most one Pod with a given identity running in a cluster. This is referred to as at most one semantics provided by a StatefulSet.The StatefulSet also recreates Pods if they’re deleted, similar to what a ReplicaSet does for stateless Pods.


问:
datatables is not working when fetching data from database
I am using DataTables to have a pagination.

I think I set the script correctly, since I followed the instruction in their website. But feel free to pinpoint if there's any wrong/mistake to the indicated script link

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Admin Reservation Management</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/datepicker3.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

```

<p>And now this is my table and stuff, I am fetching the datas from my database.</p>

<p>I did some research here in Stackoverflow, regarding to this issue and the results that I've found was they did not put  and  which I included, but feel free to pinpoint if I haven't included any.*</p>

<p><strong>php</strong></p>

```

Manage Room

 Super Admin Reservation Management

                             Room Number
                             Room Availability
                             Action

    <?php
    $connection = mysqli_connect("localhost", "root");
    $db = mysqli_select_db($connection, 'db_hotelreservation');

    $query = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status ='Booked'";
    $query_run = mysqli_query($connection, $query);
    $resultCheck = mysqli_num_rows($query_run);
    if($resultCheck > 0)
    {
        while($row = mysqli_fetch_assoc($query_run))
        {

            ?>

                     <?php echo $row['ID'];?>
                     <?php echo $row['room_number']; ?>
                     <?php echo $row['room_status'];?>
                     <?php echo $row['room_type'];?>
                     <?php echo $row['first_name'] . " " .$row['last_name']?>
                     <?php echo $row['check_in'];?>
                     <?php echo $row['check_out'];?>
                     <?php echo $row['contact_number'];?>
                     <?php echo $row['numberof_days'] ." ". "day/s";?>
                     <?php echo $row['calculated_price'];?>

                    <form action="approve.php" method="POST" onclick="return confirm('Are you sure you want to Approve this Booking?');">
                        <input type="hidden" name="id" value="<?php echo $row['ID'] ?>" style="">
                        <input type="submit" name="update" class="btn btn-success" value="Approve">
                    </form>
                    <button type="button" class="btn btn-primary viewbtn">View Details</button>

            <?php
        }
    }
    else{
        echo "No Records Found";
    }
    ?>

```

答: This might be because of delayed data binding, you can try datatable ajax approach to bind the data. Refer datatable option.</p>

Body:
I am using DataTables to have a pagination.

I think I set the script correctly, since I followed the instruction in their website. But feel free to pinpoint if there's any wrong/mistake to the indicated script link

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Admin Reservation Management</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/datepicker3.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

And now this is my table and stuff, I am fetching the datas from my database.

I did some research here in Stackoverflow, regarding to this issue and the results that I've found was they did not put  and  which I included, but feel free to pinpoint if I haven't included any.*

php

Manage Room

 Super Admin Reservation Management

                             Room Number
                             Room Availability
                             Action

    <?php
    $connection = mysqli_connect("localhost", "root");
    $db = mysqli_select_db($connection, 'db_hotelreservation');

    $query = "SELECT * FROM tbl_reservation WHERE room_status = 'Pending' OR room_status ='Booked'";
    $query_run = mysqli_query($connection, $query);
    $resultCheck = mysqli_num_rows($query_run);
    if($resultCheck > 0)
    {
        while($row = mysqli_fetch_assoc($query_run))
        {

            ?>

                     <?php echo $row['ID'];?>
                     <?php echo $row['room_number']; ?>
                     <?php echo $row['room_status'];?>
                     <?php echo $row['room_type'];?>
                     <?php echo $row['first_name'] . " " .$row['last_name']?>
                     <?php echo $row['check_in'];?>
                     <?php echo $row['check_out'];?>
                     <?php echo $row['contact_number'];?>
                     <?php echo $row['numberof_days'] ." ". "day/s";?>
                     <?php echo $row['calculated_price'];?>

                    <form action="approve.php" method="POST" onclick="return confirm('Are you sure you want to Approve this Booking?');">
                        <input type="hidden" name="id" value="<?php echo $row['ID'] ?>" style="">
                        <input type="submit" name="update" class="btn btn-success" value="Approve">
                    </form>
                    <button type="button" class="btn btn-primary viewbtn">View Details</button>

            <?php
        }
    }
    else{
        echo "No Records Found";
    }
    ?>


问:
Slow initial connection to Google Cloud App Engine
Initial connections to my website are extremely slow (100+ seconds). How can I diagnose the issue?

Using the Chrome dev tool network tab, I see that the issue is "initial connection" and not things like SSL or Waiting/TTFB.

This only happens for the first page visit to the website for a given device; after the first page loads, everything on the website is very fast. This consistently happens for new devices, on the same device if I don't visit the website for X days, and on the same device if I clear the cache and browsing history.

The website is a Django app is hosted using Google Cloud App Engine with 2 flexible instances.

User traffic to the website is low, so I doubt the issue is load balancing or traffic spikes.

Thanks!

答:
If only the first connection is slow, it might be because the instance is starting and you do not have minimum idle instances and warmup requests enabled. This configuration will make you have instances ready for taking traffic and the latency will be slower in the first connection.

As it is stated in the documentation:

If you set a minimum number of idle instances, pending latency will
  have less effect on your application's performance. Because App Engine
  keeps idle instances in reserve, it is unlikely that requests will
  enter the pending queue except in exceptionally high load spikes. You
  will need to test your application and expected traffic volume to
  determine the ideal number of instances to keep in reserve.

Also you can find more information about warmup requests in this documentation about Configuring Warmup Requests to Improve Performance


问:
Cannot create an instance of class ViewModel
I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

Lifecycle owner:-

```<code>public class MainActivity extends LifecycleActivity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_user);
        PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
        viewModel.loadPosts();
        viewModel.getPost().observe(this, new Observer<Post>() {
            @Override
            public void onChanged(@Nullable Post post) {
                if(post != null) {
                    textView.setText(post.toString());
                }
            }
        });
    }
}
</code>```

ViewModel:-

```<code>public class PostViewModel extends ViewModel {
    private MediatorLiveData<Post> post;
    private PostRepository postRepo;

    PostViewModel() {
        post = new MediatorLiveData<>();
        postRepo = new PostRepository();
    }

    public LiveData<Post> loadPosts() {
        post.addSource(postRepo.getPost(),
                post -> this.post.setValue(post)
        );
        return post;
    }

    @NonNull
    public LiveData<Post> getPost() {
        return post;
    }
}
</code>```

答:
In my case, it was gradle a dependencies problem.

If you are using Livedata,,

build.gradle(Module.app)

not

```<code>implementation 'android.arch.lifecycle:extensions:1.1.1'
kapt 'android.arch.lifecycle:common-java8:1.1.1'
</code>```

use these

```<code>implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
kapt 'androidx.lifecycle:lifecycle-common-java8:2.2.0'
</code>```

Body:
I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

Lifecycle owner:-

public class MainActivity extends LifecycleActivity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_user);
        PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
        viewModel.loadPosts();
        viewModel.getPost().observe(this, new Observer<Post>() {
            @Override
            public void onChanged(@Nullable Post post) {
                if(post != null) {
                    textView.setText(post.toString());
                }
            }
        });
    }
}

ViewModel:-

public class PostViewModel extends ViewModel {
    private MediatorLiveData<Post> post;
    private PostRepository postRepo;

    PostViewModel() {
        post = new MediatorLiveData<>();
        postRepo = new PostRepository();
    }

    public LiveData<Post> loadPosts() {
        post.addSource(postRepo.getPost(),
                post -> this.post.setValue(post)
        );
        return post;
    }

    @NonNull
    public LiveData<Post> getPost() {
        return post;
    }
}

Body:
In my case, it was gradle a dependencies problem.

If you are using Livedata,,

build.gradle(Module.app)

not

implementation 'android.arch.lifecycle:extensions:1.1.1'
kapt 'android.arch.lifecycle:common-java8:1.1.1'

use these

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
kapt 'androidx.lifecycle:lifecycle-common-java8:2.2.0'