问:
Lines on printout of iText7 PDF have different length on paper
Only some of our testers report a strange look of all lines on the printout of an iText7 generated PDF (see image). The generated PDF looks perfect and the flaw only appears on paper. Most users have no issue, whatsoever.

Any suggestions regarding known issues of printers, drivers or hints on how to reproduce or localize the problem would be appreciated. Anything I could do on iText7 side?

```<code>PdfCanvas canvas = new PdfCanvas(pdfPage)
canvas.moveTo(x1,y1);
canvas.lineTo(x2,y2);
canvas.closePathStroke();
</code>```

The PDF can be found here: PDF

答:
Making prior comments an actual answer...

I could reproduce the issue with your example document:

using Chrome on Windows with a Brother printer I also get those extra line segments;

using Adobe Reader instead of Chrome I don't.

Looking into the PDF, though, I didn't see anything that should cause that issue.

Thus, while there is nothing wrong with your kind of line drawing to start with, I proposed drawing the rectangles as rectangles (instead of multiple lines), or using filled thin rectangles instead of lines. I hoped one of those options is supported by Chrome printing.

And indeed you commented:

I'm now printing thin rectangles instead of lines and it works flawlessly.

So, while the bug was not yours from the start, changing your code to draw the borders differently solved the issue for you.

Body:
Only some of our testers report a strange look of all lines on the printout of an iText7 generated PDF (see image). The generated PDF looks perfect and the flaw only appears on paper. Most users have no issue, whatsoever.

Any suggestions regarding known issues of printers, drivers or hints on how to reproduce or localize the problem would be appreciated. Anything I could do on iText7 side?

PdfCanvas canvas = new PdfCanvas(pdfPage)
canvas.moveTo(x1,y1);
canvas.lineTo(x2,y2);
canvas.closePathStroke();

The PDF can be found here: PDF


来源: stackexchange

问:
Alternative for StringRelatedField
I am trying to get following user with their names instead of PrimaryKey, I tried to use StringRelatedField. It worked for GET request, but it does not allow to write. Could not find any alternatives for this. I want to get json result as this:

```<code>{
    "id": 1,
    "user": "admin",
    "following": "user_1"
}
</code>```

I assume instead of using StringRelatedField I should redefine create in serializers, am I right?

model.py

```<code>class Follow(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='follower'
    )
    following = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='following'
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'following'],
                name='unique_user_following'
            )
        ]

    def __str__(self) -> str:
        return self.following
</code>```

serializer.py

```<code>class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugField(
        read_only=True,
        default=serializers.CurrentUserDefault()
    )
    # following = serializers.StringRelatedField()

    class Meta:
        model = Follow
        fields = ('id', 'user', 'following',)

        validators = [
            serializers.UniqueTogetherValidator(
                queryset=Follow.objects.all(),
                fields=('user', 'following',)
            )
        ]

    def validate_following(self, value):
        if value == self.context.get('request').user:
            raise serializers.ValidationError(
                'You can not follow yourslef!'
            )
        return value
</code>```

views.py

```<code>class FollowViewSet(viewsets.ModelViewSet):
    serializer_class = FollowSerializer

    def get_queryset(self):
        new_queryset = Follow.objects.filter(user=self.request.user)
        return new_queryset

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
</code>```

答:
A SlugRelatedField allows to also perform a lookup when writing and thus retrieve in this case the user with the given username.

You thus can implement this as:

```<code>from django.contrib.auth import get_user_model

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugField(
        read_only=True,
        default=serializers.CurrentUserDefault()
    )
    following = serializers.<strong>SlugRelatedField(</strong>
        slug_field='username',
        queryset=get_user_model().objects.all()
    <strong>)</strong>

    class Meta:
        model = Follow
        fields = ('id', 'user', 'following',)
        # …

    # …</code>```

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

ContentLicense: CC BY-SA 4.0

Title: Alternative for StringRelatedField

Body:
I am trying to get following user with their names instead of PrimaryKey, I tried to use StringRelatedField. It worked for GET request, but it does not allow to write. Could not find any alternatives for this. I want to get json result as this:

{
    "id": 1,
    "user": "admin",
    "following": "user_1"
}

I assume instead of using StringRelatedField I should redefine create in serializers, am I right?

model.py

class Follow(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='follower'
    )
    following = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='following'
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'following'],
                name='unique_user_following'
            )
        ]

    def __str__(self) -> str:
        return self.following

serializer.py

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugField(
        read_only=True,
        default=serializers.CurrentUserDefault()
    )
    # following = serializers.StringRelatedField()

    class Meta:
        model = Follow
        fields = ('id', 'user', 'following',)

        validators = [
            serializers.UniqueTogetherValidator(
                queryset=Follow.objects.all(),
                fields=('user', 'following',)
            )
        ]

    def validate_following(self, value):
        if value == self.context.get('request').user:
            raise serializers.ValidationError(
                'You can not follow yourslef!'
            )
        return value

views.py

class FollowViewSet(viewsets.ModelViewSet):
    serializer_class = FollowSerializer

    def get_queryset(self):
        new_queryset = Follow.objects.filter(user=self.request.user)
        return new_queryset

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

Body:
A SlugRelatedField allows to also perform a lookup when writing and thus retrieve in this case the user with the given username.

You thus can implement this as:

from django.contrib.auth import get_user_model

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugField(
        read_only=True,
        default=serializers.CurrentUserDefault()
    )
    following = serializers.SlugRelatedField(
        slug_field='username',
        queryset=get_user_model().objects.all()
    )

    class Meta:
        model = Follow
        fields = ('id', 'user', 'following',)
        # …

    # …

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


问:
jq: populate object bedides of field exists
I'm using this filter in:

```<code>map({
    name,
    deceased: (.deceased? // empty | split(" ") | first | strptime("%Y/%m/%d") | strftime("%F"))
})
</code>```

input objects are:

{
    "name": "name1",
    "birth": "1950/05/05",
    "deceased": "1982/05/19"
}
{
    "name": "name2",
    "birth": "1982/05/19"
}
```
<p>I'm getting:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  }
]

</code>```

I need to get:

[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  },
  {
    "name": "name2"
  }
]
```

Any ideas?

答:
You can test for existence using has

```<code>map(
  {name} +
  if has("deceased")
  then {deceased: (.deceased | strptime("%Y/%m/%d") | strftime("%F"))}
  else {}
  end
)
</code>```

[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  },
  {
    "name": "name2"
  }
]
```
<p>Demo</p>
<hr />
<p>If <code>.deceased</code> can only exist as string, then this would be equivalent:</p>
```map(
  {name, deceased}
  | .deceased |= (strings | strptime("%Y/%m/%d") | strftime("%F"))
)
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  },
  {
    "name": "name2"
  }
]
</code>```

Demo

Body:
I'm using this filter in:

map({
    name,
    deceased: (.deceased? // empty | split(" ") | first | strptime("%Y/%m/%d") | strftime("%F"))
})

input objects are:

{
    "name": "name1",
    "birth": "1950/05/05",
    "deceased": "1982/05/19"
}
{
    "name": "name2",
    "birth": "1982/05/19"
}

I'm getting:

[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  }
]

I need to get:

[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  },
  {
    "name": "name2"
  }
]

Any ideas?

Body:
You can test for existence using has

map(
  {name} +
  if has("deceased")
  then {deceased: (.deceased | strptime("%Y/%m/%d") | strftime("%F"))}
  else {}
  end
)

[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  },
  {
    "name": "name2"
  }
]

Demo

If .deceased can only exist as string, then this would be equivalent:

map(
  {name, deceased}
  | .deceased |= (strings | strptime("%Y/%m/%d") | strftime("%F"))
)

[
  {
    "name": "name1",
    "deceased": "1982-05-19"
  },
  {
    "name": "name2"
  }
]

Demo


问:
How to use select() inside between() inside filter() to subset data dplyr r
What I have:
I have a large dataset with columns for a few measured variables, SiteID and Seconds.

What I would like to do:
For each of my study sites (SiteID), I would like to filter out rows for a specific time period (Seconds). I have the following code, which works only if the values in Seconds are unique to each study site, for example:

```<code># create example data
data <- data.frame(SiteID = rep(c("A", "B", "C", "D", "E"), each = 10),
                   Seconds = rep(c(1:50)))

# filter the data
data.subset <- data %>%
  filter(between(Seconds, 2, 8) | # for SiteID = "A"
  filter(between(Seconds, 14, 16) | # for SiteID = "B"
  filter(between(Seconds, 23, 30) | # for SiteID = "C"
  filter(between(Seconds, 36, 39) | # for SiteID = "D"
  filter(between(Seconds, 44, 49)) # for SiteID = "E"
</code>```

The code above would give me what I want, which is:

```<code>SiteID    Seconds
A         2
A         3
A         4
A         5
A         6
A         7
A         8
B         14
B         15
B         16
C         23
C         24
C         25
C         26
C         27
C         28
C         29
C         30
D         36
D         37
D         38
D         39
E         44
E         45
E         46
E         47
E         48
E         49
</code>```

What problem I'm facing: The problem I have is that in my dataset, the range of Seconds for each SiteID are not unique as in the example above, but looks more like the following:

```<code># create example data
data <- data.frame(SiteID = rep(c("A", "B", "C", "D", "E"), each = 10),
                   Seconds = rep(c(1:10)))
</code>```

But I would like to subset the data as such: For site A, keep only 2-8 seconds. For site B, keep only 3-6 seconds. For site C, keep only 8-10 seconds. For site D, keep only 1-6 seconds. For site E, keep only 2-9 seconds.

I need help modifying the dplyr code above for me to do this. If I used the same code as above, the data set remains exactly the same and is not filtered the way I want it to because the numbers for each SiteID are in a similar range. I have tried using select() as the first term inside between() to filter out only the rows with a specific SiteID, but it is returning an error:

```<code># modified code
data.subset <- data %>%
  filter(between(select(data, Seconds & SiteID == "A"), 2, 8) |
  filter(between(select(data, Seconds & SiteID == "B"), 3, 6) |
  filter(between(select(data, Seconds & SiteID == "C"), 8, 10) |
  filter(between(select(data, Seconds & SiteID == "D"), 1, 6) |
  filter(between(select(data, Seconds & SiteID == "E"), 2, 9))
</code>```
```<code>#  error message:
Error: Problem with `filter()` input `..1`.
i Input `..1` is `between(...)`.
x Must subset columns with a valid subscript vector.
x Subscript has the wrong type `logical`.
i It must be numeric or character.
</code>```

Basically if I were to use base R, I would need to do something like the following as the first term inside the between() function in place of just Seconds:

```<code>data$Seconds[data$SiteID == "A"]
</code>```

I hope it is clear what I'm trying to do with dplyr. My desired outcome would look like this:

```<code>SiteID    Seconds
A         2
A         3
A         4
A         5
A         6
A         7
A         8
B         3
B         4
B         5
B         6
C         8
C         9
C         10
D         1
D         2
D         3
D         4
D         5
D         6
E         2
E         3
E         4
E         5
E         6
E         7
E         8
E         9
</code>```

答:
Combine multiple conditions using & -

```<code>library(dplyr)

data %>%
  filter(SiteID == "A" & between(Seconds, 2, 8) |
         SiteID == "B" & between(Seconds, 3, 6) |
         SiteID == "C" & between(Seconds, 8, 10)|
         SiteID == "D" & between(Seconds, 1, 6) |
         SiteID == "E" & between(Seconds, 2, 9))
</code>```

Body:
What I have:
I have a large dataset with columns for a few measured variables, SiteID and Seconds.

What I would like to do:
For each of my study sites (SiteID), I would like to filter out rows for a specific time period (Seconds). I have the following code, which works only if the values in Seconds are unique to each study site, for example:

# create example data
data <- data.frame(SiteID = rep(c("A", "B", "C", "D", "E"), each = 10),
                   Seconds = rep(c(1:50)))

# filter the data
data.subset <- data %>%
  filter(between(Seconds, 2, 8) | # for SiteID = "A"
  filter(between(Seconds, 14, 16) | # for SiteID = "B"
  filter(between(Seconds, 23, 30) | # for SiteID = "C"
  filter(between(Seconds, 36, 39) | # for SiteID = "D"
  filter(between(Seconds, 44, 49)) # for SiteID = "E"

The code above would give me what I want, which is:

SiteID    Seconds
A         2
A         3
A         4
A         5
A         6
A         7
A         8
B         14
B         15
B         16
C         23
C         24
C         25
C         26
C         27
C         28
C         29
C         30
D         36
D         37
D         38
D         39
E         44
E         45
E         46
E         47
E         48
E         49

What problem I'm facing: The problem I have is that in my dataset, the range of Seconds for each SiteID are not unique as in the example above, but looks more like the following:

# create example data
data <- data.frame(SiteID = rep(c("A", "B", "C", "D", "E"), each = 10),
                   Seconds = rep(c(1:10)))

But I would like to subset the data as such: For site A, keep only 2-8 seconds. For site B, keep only 3-6 seconds. For site C, keep only 8-10 seconds. For site D, keep only 1-6 seconds. For site E, keep only 2-9 seconds.

I need help modifying the dplyr code above for me to do this. If I used the same code as above, the data set remains exactly the same and is not filtered the way I want it to because the numbers for each SiteID are in a similar range. I have tried using select() as the first term inside between() to filter out only the rows with a specific SiteID, but it is returning an error:

# modified code
data.subset <- data %>%
  filter(between(select(data, Seconds & SiteID == "A"), 2, 8) |
  filter(between(select(data, Seconds & SiteID == "B"), 3, 6) |
  filter(between(select(data, Seconds & SiteID == "C"), 8, 10) |
  filter(between(select(data, Seconds & SiteID == "D"), 1, 6) |
  filter(between(select(data, Seconds & SiteID == "E"), 2, 9))

#  error message:
Error: Problem with `filter()` input `..1`.
i Input `..1` is `between(...)`.
x Must subset columns with a valid subscript vector.
x Subscript has the wrong type `logical`.
i It must be numeric or character.

Basically if I were to use base R, I would need to do something like the following as the first term inside the between() function in place of just Seconds:

data$Seconds[data$SiteID == "A"]

I hope it is clear what I'm trying to do with dplyr. My desired outcome would look like this:

SiteID    Seconds
A         2
A         3
A         4
A         5
A         6
A         7
A         8
B         3
B         4
B         5
B         6
C         8
C         9
C         10
D         1
D         2
D         3
D         4
D         5
D         6
E         2
E         3
E         4
E         5
E         6
E         7
E         8
E         9

Body:
Combine multiple conditions using & -

library(dplyr)

data %>%
  filter(SiteID == "A" & between(Seconds, 2, 8) |
         SiteID == "B" & between(Seconds, 3, 6) |
         SiteID == "C" & between(Seconds, 8, 10)|
         SiteID == "D" & between(Seconds, 1, 6) |
         SiteID == "E" & between(Seconds, 2, 9))


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
If you want to know exactly if the files are different or not then there isn't a better solution than yours -- comparing sequentially.

However you can make some heuristics that can tell you with some kind of probability if the files are identical.
1) Check file size; that's the easiest.
2) Take a random file position and compare block of bytes starting at this position in the two files.
3) Repeat step 2) to achieve the needed probability.

You should compute and test how many reads (and size of block) are useful for your program.

ContentLicense: CC BY-SA 3.0

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
Javascritpt - Looping through an array
So i just started learning js and i can't solve this excercise:

Create a file named looping-through-arrays.js.

In that file, define a variable named pets that references this array:

['cat', 'dog', 'rat']

Create a for loop that changes each string in the array so that they
are plural.

You will use a statement like this inside the for loop:

pets[i] = pets[i] + 's'

I tried something like this code but apparently it doesn't work:

```<code>let pets = ["cat", "dog", "rat"];
for(let i = 0; i <= pets.length; i++){
  pets[i] = pets[i] + "s";
};
console.log(pets);
</code>```

答:
```<code>//Try this one
 let pets = ["cat", "dog", "rat"];
    for(let i = 0; i < pets.length; i++){
      pets[i] = pets[i] + "s";
    };
    console.log(pets);
</code>```

Title: Javascritpt - Looping through an array

Body:
So i just started learning js and i can't solve this excercise:

Create a file named looping-through-arrays.js.

In that file, define a variable named pets that references this array:

['cat', 'dog', 'rat']

Create a for loop that changes each string in the array so that they
are plural.

You will use a statement like this inside the for loop:

pets[i] = pets[i] + 's'

I tried something like this code but apparently it doesn't work:

let pets = ["cat", "dog", "rat"];
for(let i = 0; i <= pets.length; i++){
  pets[i] = pets[i] + "s";
};
console.log(pets);


问:
Sending multiple data in one page Jquery
İmage

Hello, I want to update multiple data in one page. But when I create a form for each row of textarea, only the first textarea value is updated. How do I do this with jquery? Thank you.

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
    $(document).ready(function() {
        $(".form").click(function() {
            var text = $("#text").val();
            var id = $("#id").val();
            $.post("../../app/modules/content/update.php", {
                "text": text,
                "id": id
            }, function(cevap) {
                $('#status').html('Güncellendi').show();
            });
        });
    });
</script>

<div class="row">

    <?php
    $query = $veri->selectToplu('contents_temp');
    foreach ($query as $query) { ?>

        <span class="col-md-3 mb-2">
            <div class="card">
                <?php
                if (isset($query['video'])) {
                    echo "<video controls='' style='height: 187px;' src='" . $query['video'] . "' class='bs-card-video'></video>";
                } else {
                    echo "<img class='card-img-top' style='height: 187px;' src='" . $query['img1'] . "'>";
                }
                ?>
                <div class="card-body text-center">
                    <span deleteid="<?php echo $query['id'] ?>" style="position:absolute; right:0; top:0;" class="btn btn-sm btn-danger delete">x</span>
                    <form action="" method="POST">
                        <textarea style="height: 7rem" name="text" id="text" class="form-control" col="5" rows="10"><?php echo $query['text'] ?></textarea>
                        <input type="hidden" name="id" id="id" value="<?php echo $query['id']; ?>">
                        <button type="submit" class="btn btn-primary btn-sm mt-1 form" onclick="buton();">Güncelle</button>
                        <div id="status"></div>
                    </form>
                </div>
            </div>
        </span>
    <?php } ?>
</code>```

答:
First, remove all the id attributes from the form inputs. This is because id is not unique and won't help much in your case.

Then in your jquery, you use $(this).find() to select the submitted form's inputs instead of $('#element'). Try this

PHP/HTML Part

```<code><div class="row">
    <?php
    $query = $veri->selectToplu('contents_temp');
    foreach ($query as $query) { ?>
        <span class="col-md-3 mb-2">
            <div class="card">
                <?php
                if (isset($query['video'])) {
                    echo "<video controls='' style='height: 187px;' src='" . $query['video'] . "' class='bs-card-video'></video>";
                } else {
                    echo "<img class='card-img-top' style='height: 187px;' src='" . $query['img1'] . "'>";
                }
                ?>
                <div class="card-body text-center">
                    <span deleteid="<?php echo $query['id'] ?>" style="position:absolute; right:0; top:0;" class="btn btn-sm btn-danger delete">x</span>
                    <form action="" method="POST" class="form">
                        <textarea style="height: 7rem" name="text" class="form-control" col="5" rows="10"><?php echo $query['text'] ?></textarea>
                        <input type="hidden" name="id" value="<?php echo $query['id']; ?>">
                        <button type="submit" class="btn btn-primary btn-sm mt-1">Güncelle</button>
                        <div class="status"></div>
                    </form>
                </div>
            </div>
        </span>
    <?php } ?>
</div>
</code>```

jQuery/JavaScript Part

```<code>$(document).ready(function() {
    $(".form").submit(function(e) {
        e.preventDefault();
        var text    = $(this).find('[name="text"]').val();
        var id      = $(this).find('[name="id"]').val();
        var $status = $(this).find('.status');

        $.post("../../app/modules/content/update.php", {
            "text": text,
            "id": id
        }, function(cevap) {
            $status.html('Güncellendi').show();
        });
    });
});
</code>```

Body:
İmage

Hello, I want to update multiple data in one page. But when I create a form for each row of textarea, only the first textarea value is updated. How do I do this with jquery? Thank you.

    <?php
    $query = $veri->selectToplu('contents_temp');
    foreach ($query as $query) { ?>

                <?php
                if (isset($query['video'])) {
                    echo "<video controls='' style='height: 187px;' src='" . $query['video'] . "' class='bs-card-video'></video>";
                } else {
                    echo "";
                }
                ?>

                    <span deleteid="<?php echo $query['id'] ?>" style="position:absolute; right:0; top:0;" class="btn btn-sm btn-danger delete">x
                    <form action="" method="POST">
                        <textarea style="height: 7rem" name="text" id="text" class="form-control" col="5" rows="10"><?php echo $query['text'] ?></textarea>
                        <input type="hidden" name="id" id="id" value="<?php echo $query['id']; ?>">
                        <button type="submit" class="btn btn-primary btn-sm mt-1 form" onclick="buton();">Güncelle</button>

                    </form>

    <?php } ?>

Body:
First, remove all the id attributes from the form inputs. This is because id is not unique and won't help much in your case.

Then in your jquery, you use $(this).find() to select the submitted form's inputs instead of $('#element'). Try this

PHP/HTML Part

<div class="row">
    <?php
    $query = $veri->selectToplu('contents_temp');
    foreach ($query as $query) { ?>
        <span class="col-md-3 mb-2">
            <div class="card">
                <?php
                if (isset($query['video'])) {
                    echo "<video controls='' style='height: 187px;' src='" . $query['video'] . "' class='bs-card-video'></video>";
                } else {
                    echo "<img class='card-img-top' style='height: 187px;' src='" . $query['img1'] . "'>";
                }
                ?>
                <div class="card-body text-center">
                    <span deleteid="<?php echo $query['id'] ?>" style="position:absolute; right:0; top:0;" class="btn btn-sm btn-danger delete">x</span>
                    <form action="" method="POST" class="form">
                        <textarea style="height: 7rem" name="text" class="form-control" col="5" rows="10"><?php echo $query['text'] ?></textarea>
                        <input type="hidden" name="id" value="<?php echo $query['id']; ?>">
                        <button type="submit" class="btn btn-primary btn-sm mt-1">Güncelle</button>
                        <div class="status"></div>
                    </form>
                </div>
            </div>
        </span>
    <?php } ?>
</div>

jQuery/JavaScript Part

$(document).ready(function() {
    $(".form").submit(function(e) {
        e.preventDefault();
        var text    = $(this).find('[name="text"]').val();
        var id      = $(this).find('[name="id"]').val();
        var $status = $(this).find('.status');

        $.post("../../app/modules/content/update.php", {
            "text": text,
            "id": id
        }, function(cevap) {
            $status.html('Güncellendi').show();
        });
    });
});


问:
ERROR ----> Task :expo-permissions:compileDebugKotlin FAILED
The Kotlin Gradle plugin was loaded multiple times in different subprojects, which is not supported and may break the build.

This might happen in subprojects that apply the Kotlin plugins with the Gradle 'plugins { ... }' DSL if they specify explicit versions, even if the versions are equal.
Please add the Kotlin plugin to the common parent project or the root project, then remove the versions in the subprojects.

If the parent project does not need the plugin, add 'apply false' to the plugin line.
See: https://docs.gradle.org/current/userguide/plugins.html#sec:subprojects_plugins_dsl
The Kotlin plugin was loaded in the following projects: ':expo-av', ':react-native-agora'

Task :expo-permissions:compileDebugKotlin FAILED

```<code>Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings
175 actionable tasks: 2 executed, 173 up-to-date
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (12, 50): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (19, 52): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (40, 36): Unresolved reference: R
</code>```

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':expo-permissions:compileDebugKotlin'.

Compilation error. See log for more details

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 17s

```<code>error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (12, 50): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (19, 52): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (40, 36): Unresolved reference: R
</code>```

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':expo-permissions:compileDebugKotlin'.

Compilation error. See log for more details

答: If you created a project using 'npx', delete 'expo' dependencies from package.json. It works for me.</p>

Body:
The Kotlin Gradle plugin was loaded multiple times in different subprojects, which is not supported and may break the build.

This might happen in subprojects that apply the Kotlin plugins with the Gradle 'plugins { ... }' DSL if they specify explicit versions, even if the versions are equal.
Please add the Kotlin plugin to the common parent project or the root project, then remove the versions in the subprojects.

If the parent project does not need the plugin, add 'apply false' to the plugin line.
See: https://docs.gradle.org/current/userguide/plugins.html#sec:subprojects_plugins_dsl
The Kotlin plugin was loaded in the following projects: ':expo-av', ':react-native-agora'

Task :expo-permissions:compileDebugKotlin FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.2/userguide/command_line_interface.html#sec:command_line_warnings
175 actionable tasks: 2 executed, 173 up-to-date
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (12, 50): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (19, 52): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (40, 36): Unresolved reference: R

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':expo-permissions:compileDebugKotlin'.

Compilation error. See log for more details

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 17s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (12, 50): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (19, 52): Unresolved reference: R
e: /Users/development/Projects/myapp/node_modules/react-native-unimodules/node_modules/expo-permissions/android/src/main/java/expo/modules/permissions/requesters/BackgroundLocationRequester.kt: (40, 36): Unresolved reference: R

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':expo-permissions:compileDebugKotlin'.

Compilation error. See log for more details


问:
Polymorphic associations break in rails 6.1
I have inherited some legacy rails code with workarounds around standard polymorphic associations. These used to work up until rails 5. Now I am trying to upgrade to rails6.1 and they break and I have no clue as to how to fix them.

Problem:
We have following 2 tables:

posts

id

text

...

comments

id

commentable_id

commentable_type

...

A post has 3 types of comments -

Admin comment

Anonymous comment

User comment

We have modeled this as polymorphic relationship as follows:

```<code># comment.rb
class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end
</code>```
```<code># post.rb
class Post < ActiveRecord::Base
  has_many :comments, as :commentable, dependent: :destroy, inverse_of: :post

  has_many :admin_comments, -> { where commentable_type: "AdminComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post

  has_many :user_comments, -> { where commentable_type: "UserComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post

  has_many :anonymous_comments, -> { where commentable_type: "AnonymousComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post
end
</code>```

With this setup, I could fetch either all comments by doing -

```<code>p = Post.find(123)
p.comments
</code>```

or fetch comments by specific type of user -

```<code>p = Post.find(123)
p.user_comments
p.anonymous_comments
</code>```

With rails 6.1 this setup does not work.
When trying to run rails console It fails with error:

ruby2.7.x/lib/ruby/gems/2.7.0/gems/activesupport-6.1.4.1/lib/active_support/core_ext/hash/keys.rb:52:in `block in assert_valid_keys': Unknown key: :foreign_type. Valid keys are: :class_name, :anonymous_class, :primary_key, :foreign_key, :dependent, :validate, :inverse_of, :strict_loading, :autosave, :before_add, :after_add, :before_remove, :after_remove, :extend, :counter_cache, :join_table, :index_errors, :ensuring_owner_was (ArgumentError)

After looking for potential answers online, the closest I could get was by adding as: :commentable to each association like -

```<code>  has_many :user_comments, -> { where commentable_type: "UserComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post, as: :commentable
</code>```

But this does not get me correct result set. It generates sql as follows -

SELECT comments.* FROM comments WHERE comments.commentable_id = 123 AND comments.commentable_type = 'Post' AND comments.commentable_type = 'UserComment'

without as: :commentable it would generate sql as -

SELECT comments.* FROM comments WHERE comments.commentable_id = 123  AND comments.commentable_type = 'UserComment'

I am kinda lost and would appreciate any help!

Thanks!

答:
This looks like an extremely confused and misguided attempt at a combination of  Single Table Inheritance and a polymorphic assocations with no understanding of how either works and I doubt the code actually worked as intended in earlier versions.

STI

In a STI setup you use the type inheritance column (type by default) to specify what class ActiveRecord will load by when retrieving the rows from the database. That means your comments table should have a string column named type containing values such as UserComment and AdminComment.

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class UserComment < Comment
end

class AdminComment < Comment
end

# ...
```
<p>When you setup a has many assocation pointing to a STI model you should set the condition on the <code>type</code> column of the table - not <code>commentable_type</code>:</p>
<pre class="lang-ruby prettyprint-override"><code>class Post < ActiveRecord::Base
  has_many :comments
  has_many :user_comments, -> { where(type: 'UserComment') }
  has_many :admin_comments, -> { where(type: 'AdminComment') }
  # ...
end
</code>```
```<code>irb(main):002:0> puts Post.joins(:user_comments).to_sql
</code>```

SELECT "posts".* FROM "posts"
INNER JOIN "comments"
ON "comments"."type" = 'UserComment'
AND "comments"."post_id" = "posts"."id"
```
<h2>Polymorhic assocations</h2>
<p>Polymorphic assocations are really just a dirty cheat to get around the Object Relational Impedience Missmatch problem. By using a integer column together with a varchar column you can create a single assocation that points to any table - this would be for example attaching comments to posts, videos, images or even other comments. Thats what the <code>commentable_type</code> column should actually be containing.</p>
<p>To change the assocations from the previous example to be polymorphic you just have to add the <code>as:</code> option to tell Rails what <code>belongs_to</code> assocation to look for:</p>
<pre class="lang-ruby prettyprint-override"><code>class Post < ActiveRecord::Base
  has_many :comments, as: :commentable
  has_many :user_comments,
    -> { where(type: 'UserComment') },
    as: :commentable
  has_many :admin_comments,
    -> { where(type: 'AdminComment') },
    as: :commentable
end
</code>```

Otherwise it will just assume that you're looking for an assocation named post on the other end - and as: tells ActiveRecord that its a polymorphic assocation:

```<code>irb(main):002:0> puts Post.joins(:user_comments).to_sql
</code>```

SELECT "posts".* FROM "posts"
INNER JOIN "comments" ON "comments"."commentable_type" = 'Post'
AND "comments"."type" = 'UserComment'
AND "comments"."commentable_id" = "posts"."id"
```

You don't have to configure the foreign_key, foreign_type or class_name option (this one was dead wrong) as it all can be derived from the name.

Body:
I have inherited some legacy rails code with workarounds around standard polymorphic associations. These used to work up until rails 5. Now I am trying to upgrade to rails6.1 and they break and I have no clue as to how to fix them.

Problem:
We have following 2 tables:

posts

id

text

...

comments

id

commentable_id

commentable_type

...

A post has 3 types of comments -

Admin comment

Anonymous comment

User comment

We have modeled this as polymorphic relationship as follows:

# comment.rb
class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

# post.rb
class Post < ActiveRecord::Base
  has_many :comments, as :commentable, dependent: :destroy, inverse_of: :post

  has_many :admin_comments, -> { where commentable_type: "AdminComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post

  has_many :user_comments, -> { where commentable_type: "UserComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post

  has_many :anonymous_comments, -> { where commentable_type: "AnonymousComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post
end

With this setup, I could fetch either all comments by doing -

p = Post.find(123)
p.comments

or fetch comments by specific type of user -

p = Post.find(123)
p.user_comments
p.anonymous_comments

With rails 6.1 this setup does not work.
When trying to run rails console It fails with error:

ruby2.7.x/lib/ruby/gems/2.7.0/gems/activesupport-6.1.4.1/lib/active_support/core_ext/hash/keys.rb:52:in `block in assert_valid_keys': Unknown key: :foreign_type. Valid keys are: :class_name, :anonymous_class, :primary_key, :foreign_key, :dependent, :validate, :inverse_of, :strict_loading, :autosave, :before_add, :after_add, :before_remove, :after_remove, :extend, :counter_cache, :join_table, :index_errors, :ensuring_owner_was (ArgumentError)

After looking for potential answers online, the closest I could get was by adding as: :commentable to each association like -

  has_many :user_comments, -> { where commentable_type: "UserComment" },
    class_name: 'Comment', foreign_key: :commentable_id,
    foreign_type: :commentable_type, dependent: :destroy, inverse_of: :post, as: :commentable

But this does not get me correct result set. It generates sql as follows -

SELECT comments.* FROM comments WHERE comments.commentable_id = 123 AND comments.commentable_type = 'Post' AND comments.commentable_type = 'UserComment'

without as: :commentable it would generate sql as -

SELECT comments.* FROM comments WHERE comments.commentable_id = 123  AND comments.commentable_type = 'UserComment'

I am kinda lost and would appreciate any help!

Thanks!

Body:
This looks like an extremely confused and misguided attempt at a combination of  Single Table Inheritance and a polymorphic assocations with no understanding of how either works and I doubt the code actually worked as intended in earlier versions.

STI

In a STI setup you use the type inheritance column (type by default) to specify what class ActiveRecord will load by when retrieving the rows from the database. That means your comments table should have a string column named type containing values such as UserComment and AdminComment.

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class UserComment < Comment
end

class AdminComment < Comment
end

# ...

When you setup a has many assocation pointing to a STI model you should set the condition on the type column of the table - not commentable_type:

class Post < ActiveRecord::Base
  has_many :comments
  has_many :user_comments, -> { where(type: 'UserComment') }
  has_many :admin_comments, -> { where(type: 'AdminComment') }
  # ...
end

irb(main):002:0> puts Post.joins(:user_comments).to_sql

SELECT "posts".* FROM "posts"
INNER JOIN "comments"
ON "comments"."type" = 'UserComment'
AND "comments"."post_id" = "posts"."id"

Polymorhic assocations

Polymorphic assocations are really just a dirty cheat to get around the Object Relational Impedience Missmatch problem. By using a integer column together with a varchar column you can create a single assocation that points to any table - this would be for example attaching comments to posts, videos, images or even other comments. Thats what the commentable_type column should actually be containing.

To change the assocations from the previous example to be polymorphic you just have to add the as: option to tell Rails what belongs_to assocation to look for:

class Post < ActiveRecord::Base
  has_many :comments, as: :commentable
  has_many :user_comments,
    -> { where(type: 'UserComment') },
    as: :commentable
  has_many :admin_comments,
    -> { where(type: 'AdminComment') },
    as: :commentable
end

Otherwise it will just assume that you're looking for an assocation named post on the other end - and as: tells ActiveRecord that its a polymorphic assocation:

irb(main):002:0> puts Post.joins(:user_comments).to_sql

SELECT "posts".* FROM "posts"
INNER JOIN "comments" ON "comments"."commentable_type" = 'Post'
AND "comments"."type" = 'UserComment'
AND "comments"."commentable_id" = "posts"."id"

You don't have to configure the foreign_key, foreign_type or class_name option (this one was dead wrong) as it all can be derived from the name.


问:
is there an excel function that turns the text color of a cell into a value?
I need to perform some averageif and sumif functions on a database whose criteria is defined by the colour of the text in each row.

Currently, I am manually assigning to each row a value based on the colour of the text (1 for red and 2 for black) in order to perform calculations. The problem is that my file if huge and it's not possible to keep assigning values manually.

I was wondering if there was some excel function that returns a value based on the colour of the text (or any other solution that saves time).

Thank you

答:
I believe the story is not entirely as you say it is, because to my knowledge, you can't store a colour in a database :-)

So, in my opinion, you have two columns in database, one with some label, the other with some value (1 or 2) and you have decided to merge both informations into one column in Excel, where you want the value 1 to be represented by a red colour and 2 by a black colour. (Most probably you either want to emphasize the presence of those values)

For that reason, you can use conditional formatting, as I'm showing you in the following screenshot (using green instead of black):

You can, obviously, choose to hide the column with the value, that won't make a difference for the conditional formatting:

Obviously, your Sumif and AverageIf functions will be based on the values of the B column.


问:
C++ : read a csv file and extract some parts
A .csv file is written like this:

```<code>    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....
</code>```

now I want to create a function, i.e.

```<code>      double find_and_extract (string sss)
</code>```

when this function is used with a keyword as its parameter, for example

```<code>      find_and_extract (W3005U00-X30BOJ00-1);
</code>```

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

```<code>    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }
</code>```

Could anyone help me out to point out the errors?

答: Check out strtok(). This is actually a pretty trivial task, and should be a good learning project if you are still new to C++.

Body:
A .csv file is written like this:

    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....

now I want to create a function, i.e.

      double find_and_extract (string sss)

when this function is used with a keyword as its parameter, for example

      find_and_extract (W3005U00-X30BOJ00-1);

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }

Could anyone help me out to point out the errors?


问:
add text and button in a background image flutter
I'm a student new to flutter. I want to add a Text and a button on this background image. how should I do that  using flutter. appreciate your help on this.

text -"Hello there"

button - Get Started

image description

```<code>    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';

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

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            color: Colors.black,
            child: Stack(
              children: [
                Positioned.fill(
                  child: Opacity(
                    opacity: 0.4,
                    child:
                        Image.asset('assets/images/person1.png', fit: BoxFit.cover),
                  ),
                )
              ],
            ),
          ),
        );
      }

}
</code>```

答:
Hello Nidew here is a SImple And Basic Example what you want...

hope this will resolve your issue

```<code>Scaffold(
      body: Stack(
        children: [
          SizedBox(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: Image.asset('assets/images/app_icon.png',fit: BoxFit.fill,),
          ),
          Column(
            children: [
              const Align(alignment: Alignment.topLeft,child: Text('Hello',style: TextStyle(fontSize: 50,fontWeight: FontWeight.bold),)),
              const Spacer(),
              const Align(alignment: Alignment.centerLeft,child: Text('Hello Second Text')),
              const Spacer(),

              Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: ElevatedButton(
                    onPressed: (){

                    },
                    child: const Text('Press me'),
                    style: ElevatedButton.styleFrom(
                      minimumSize: Size(MediaQuery.of(context).size.width,40)
                    ),
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    )
</code>```

Body:
I'm a student new to flutter. I want to add a Text and a button on this background image. how should I do that  using flutter. appreciate your help on this.

text -"Hello there"

button - Get Started

image description

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';

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

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            color: Colors.black,
            child: Stack(
              children: [
                Positioned.fill(
                  child: Opacity(
                    opacity: 0.4,
                    child:
                        Image.asset('assets/images/person1.png', fit: BoxFit.cover),
                  ),
                )
              ],
            ),
          ),
        );
      }

}

Body:
Hello Nidew here is a SImple And Basic Example what you want...

hope this will resolve your issue

Scaffold(
      body: Stack(
        children: [
          SizedBox(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: Image.asset('assets/images/app_icon.png',fit: BoxFit.fill,),
          ),
          Column(
            children: [
              const Align(alignment: Alignment.topLeft,child: Text('Hello',style: TextStyle(fontSize: 50,fontWeight: FontWeight.bold),)),
              const Spacer(),
              const Align(alignment: Alignment.centerLeft,child: Text('Hello Second Text')),
              const Spacer(),

              Padding(
                padding: const EdgeInsets.only(bottom: 20),
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: ElevatedButton(
                    onPressed: (){

                    },
                    child: const Text('Press me'),
                    style: ElevatedButton.styleFrom(
                      minimumSize: Size(MediaQuery.of(context).size.width,40)
                    ),
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    )


问:
What is the best way to store data from text file into C++ in order to Edit
I am building a Contact Management System in which I have console C++ application and I want to store contacts in a address text file like this.

```<code>1
John Doe
134 main st.
south bend, IN. 38744
574-444-5554
</code>```

I want to be able to store multiple contacts to the file, then read the file into memory, but not sure if I should store into an array, vector or some other data structure.

I need /want to be able to ADD,  Edit,  Search by Last Name,  ID  (1, etc..)

Currently, when I put data in a text file, I can open it and read it out, but it's not stored in any organized data structure.

Example of how I'm reading the file:

```<code>    string myText;
    // Read from the text file
    ifstream MyReadFile("address.txt");
    // Use a while loop together with the getline() function to read the file line by line
    while (getline(MyReadFile, myText)) {
        // Output the text from the file
        cout << myText << "\n";
    }
    // Close the file
    MyReadFile.close();
</code>```

答:
C++ is an object oriented language. It helps you to abstract your real world problems into objects, consisting of data and methods, operating on this data.

So, one of the first idea could then be to translate a "Contact" into an object. And such an object (or class) would have properties or data members that belong together and then make up a "Contact"

Example: You could define a class contact like this:

```<code>#include <string>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};
};
</code>```

With that all attributes that make up a contact, are together in on object and can be easliy handled.

And if you need an instance of such a Contact, you could simply write Contact c and you can easily access all data with e.g. c.name.

This makes life already very simple.

Next. The methods. What can you or do you want to do with ONE contact. The only requirement that you have at the moment is, to read the data from or write them to a stream. C++ will help you also here. You know already about the iostream facilities and that you can for example use the inserter operator << to write to any stream. It does not matter if the stream is a std::cout or any file stream or even std::ostringstream. It will always work.

That is nice, but how to add such functionality to your "Contact" object? This can be done be overwriting operators <<  and >> for your object. The class would now look like this:

```<code>#include <iostream>
#include <string>
#include <iomanip>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};

    friend std::istream& operator >> (std::istream& is, Contact& c) {
        is >> c.ID;
        std::getline(is >> std::ws, c.name);
        std::getline(is, c.street);
        std::getline(is, c.city);
        std::getline(is, c.phone);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Contact& c) {
        return os << c.ID << '\n' << c.name << '\n' << c.street << '\n'
            << c.city << '\n' << c.phone << '\n';
    }
};
</code>```

Now you need to think about more abstractions. You want to have not only one instance of a contact, but many of them. And you want to work with this data, so for example, searching, adding, sorting or whatever.

This can of course not be done with the above object as is. We need to store one or many objects of it.

And for this the absolute standard approach is to use a std::vector. The std::vector can hold 0..many other objects and is ideally suited for your requirements. You can write simply std::vector<Contact> contacts; and you immediately can have many instances of "Contacts".

But in C++ you would go one step ahead. Because you want to operate on these many "contacts", you would encapsulyte also this in a new, different object. Let us call this "Database". And here you would add all functions that work with a "Contact". So, the data is a std::vector<Contact> and the mehods will operate on this data. Let us start with input and output.

Next source code:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <iomanip>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};

    friend std::istream& operator >> (std::istream& is, Contact& c) {
        is >> c.ID;
        std::getline(is >> std::ws, c.name);
        std::getline(is, c.street);
        std::getline(is, c.city);
        std::getline(is, c.phone);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Contact& c) {
        return os << c.ID << '\n' << c.name << '\n' << c.street << '\n'
            << c.city << '\n' << c.phone << '\n';
    }
};

struct Database {

    std::vector<Contact> data{};

    friend std::istream& operator >> (std::istream& is, Database& d) {
        d.data.clear();
        Contact tmp;
        while (is >> tmp)
            d.data.push_back(tmp);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Database& d) {
        for (const Contact& c : d.data)
            os << c;
        return os;
    }
};
</code>```

This is now already very powerful. If you have a Database d, you can output the complete database to the console with on simple statement: std::cout << d;. This will show all data on std::cout. And all functionionality is encapsulated in the classes. That is a big advantage. Imagine that you make a modfication in the "Contact" class. The "outer" world will not be affected and continue to work without any modification.

Let us go now to a full example. For this I would like to remind you that our class is now working together with any type of stream. So, I will put some test data in a std::istringstream instead of a file. Let us have a look:

```<code>#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iomanip>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};

    friend std::istream& operator >> (std::istream& is, Contact& c) {
        is >> c.ID;
        std::getline(is >> std::ws, c.name);
        std::getline(is, c.street);
        std::getline(is, c.city);
        std::getline(is, c.phone);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Contact& c) {
        return os << c.ID << '\n' << c.name << '\n' << c.street << '\n'
            << c.city << '\n' << c.phone << '\n';
    }
};

struct Database {

    std::vector<Contact> data{};

    friend std::istream& operator >> (std::istream& is, Database& d) {
        d.data.clear();
        Contact tmp;
        while (is >> tmp)
            d.data.push_back(tmp);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Database& d) {
        for (const Contact& c : d.data)
            os << c;
        return os;
    }
};

std::istringstream in{ R"(1
John Doe
134 main st.
south bend, IN. 38744
574-444-5554
2
Jane Doe
2 second  st.
north , IN. 5678
543-123-456
3
x y
z  st.
city
phone)" };

int main() {
    Database d{};

    in >> d;
    std::cout << d;
}
</code>```

Of course you now need to add many more functions to your "Database" class. Whatever you need.

And if you want to restructure the "Contact" class. Also no problem. It will continue to work.

I hope that this example gave you and idea on hiw things could be done.

Body:
I am building a Contact Management System in which I have console C++ application and I want to store contacts in a address text file like this.

1
John Doe
134 main st.
south bend, IN. 38744
574-444-5554

I want to be able to store multiple contacts to the file, then read the file into memory, but not sure if I should store into an array, vector or some other data structure.

I need /want to be able to ADD,  Edit,  Search by Last Name,  ID  (1, etc..)

Currently, when I put data in a text file, I can open it and read it out, but it's not stored in any organized data structure.

Example of how I'm reading the file:

    string myText;
    // Read from the text file
    ifstream MyReadFile("address.txt");
    // Use a while loop together with the getline() function to read the file line by line
    while (getline(MyReadFile, myText)) {
        // Output the text from the file
        cout << myText << "\n";
    }
    // Close the file
    MyReadFile.close();

Body:
C++ is an object oriented language. It helps you to abstract your real world problems into objects, consisting of data and methods, operating on this data.

So, one of the first idea could then be to translate a "Contact" into an object. And such an object (or class) would have properties or data members that belong together and then make up a "Contact"

Example: You could define a class contact like this:

#include <string>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};
};

With that all attributes that make up a contact, are together in on object and can be easliy handled.

And if you need an instance of such a Contact, you could simply write Contact c and you can easily access all data with e.g. c.name.

This makes life already very simple.

Next. The methods. What can you or do you want to do with ONE contact. The only requirement that you have at the moment is, to read the data from or write them to a stream. C++ will help you also here. You know already about the iostream facilities and that you can for example use the inserter operator << to write to any stream. It does not matter if the stream is a std::cout or any file stream or even std::ostringstream. It will always work.

That is nice, but how to add such functionality to your "Contact" object? This can be done be overwriting operators <<  and >> for your object. The class would now look like this:

#include <iostream>
#include <string>
#include <iomanip>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};

    friend std::istream& operator >> (std::istream& is, Contact& c) {
        is >> c.ID;
        std::getline(is >> std::ws, c.name);
        std::getline(is, c.street);
        std::getline(is, c.city);
        std::getline(is, c.phone);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Contact& c) {
        return os << c.ID << '\n' << c.name << '\n' << c.street << '\n'
            << c.city << '\n' << c.phone << '\n';
    }
};

Now you need to think about more abstractions. You want to have not only one instance of a contact, but many of them. And you want to work with this data, so for example, searching, adding, sorting or whatever.

This can of course not be done with the above object as is. We need to store one or many objects of it.

And for this the absolute standard approach is to use a std::vector. The std::vector can hold 0..many other objects and is ideally suited for your requirements. You can write simply std::vector<Contact> contacts; and you immediately can have many instances of "Contacts".

But in C++ you would go one step ahead. Because you want to operate on these many "contacts", you would encapsulyte also this in a new, different object. Let us call this "Database". And here you would add all functions that work with a "Contact". So, the data is a std::vector<Contact> and the mehods will operate on this data. Let us start with input and output.

Next source code:

#include <iostream>
#include <vector>
#include <string>
#include <iomanip>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};

    friend std::istream& operator >> (std::istream& is, Contact& c) {
        is >> c.ID;
        std::getline(is >> std::ws, c.name);
        std::getline(is, c.street);
        std::getline(is, c.city);
        std::getline(is, c.phone);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Contact& c) {
        return os << c.ID << '\n' << c.name << '\n' << c.street << '\n'
            << c.city << '\n' << c.phone << '\n';
    }
};

struct Database {

    std::vector<Contact> data{};

    friend std::istream& operator >> (std::istream& is, Database& d) {
        d.data.clear();
        Contact tmp;
        while (is >> tmp)
            d.data.push_back(tmp);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Database& d) {
        for (const Contact& c : d.data)
            os << c;
        return os;
    }
};

This is now already very powerful. If you have a Database d, you can output the complete database to the console with on simple statement: std::cout << d;. This will show all data on std::cout. And all functionionality is encapsulated in the classes. That is a big advantage. Imagine that you make a modfication in the "Contact" class. The "outer" world will not be affected and continue to work without any modification.

Let us go now to a full example. For this I would like to remind you that our class is now working together with any type of stream. So, I will put some test data in a std::istringstream instead of a file. Let us have a look:

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iomanip>

struct Contact {
    int ID{};
    std::string name{};
    std::string street{};
    std::string city{};
    std::string phone{};

    friend std::istream& operator >> (std::istream& is, Contact& c) {
        is >> c.ID;
        std::getline(is >> std::ws, c.name);
        std::getline(is, c.street);
        std::getline(is, c.city);
        std::getline(is, c.phone);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Contact& c) {
        return os << c.ID << '\n' << c.name << '\n' << c.street << '\n'
            << c.city << '\n' << c.phone << '\n';
    }
};

struct Database {

    std::vector<Contact> data{};

    friend std::istream& operator >> (std::istream& is, Database& d) {
        d.data.clear();
        Contact tmp;
        while (is >> tmp)
            d.data.push_back(tmp);
        return is;
    }
    friend std::ostream& operator << (std::ostream& os, const Database& d) {
        for (const Contact& c : d.data)
            os << c;
        return os;
    }
};

std::istringstream in{ R"(1
John Doe
134 main st.
south bend, IN. 38744
574-444-5554
2
Jane Doe
2 second  st.
north , IN. 5678
543-123-456
3
x y
z  st.
city
phone)" };

int main() {
    Database d{};

    in >> d;
    std::cout << d;
}

Of course you now need to add many more functions to your "Database" class. Whatever you need.

And if you want to restructure the "Contact" class. Also no problem. It will continue to work.

I hope that this example gave you and idea on hiw things could be done.


问:
Expose rabbitmq managment via kubernetes ingrress
I have a kubernetes cluster with a deployment of rabbitmq. I want to expose the rabbitmanagment UI in that way I can access to it in my browser. To do that I have a deployment, service and ingress file:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rabbitmq
  template:
    metadata:
      labels:
        app: rabbitmq
    spec:
      containers:
        - image: rabbitmq:3.8.9-management
          name: rabbitmq
          ports:
            - containerPort: 5672
            - containerPort: 15672
          resources: {}
      restartPolicy: Always
</code>```

The service:

```<code>apiVersion: v1
kind: Service
metadata:
  name: rabbitmq
spec:
  ports:
    - name: "5672"
      port: 5672
      targetPort: 5672
    - name: "15672"
      port: 15672
      targetPort: 15672
  selector:
    app: rabbitmq
</code>```

Ingress file

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
spec:
  rules:
  - http:
      paths:
      - path: /rabbitmq
        pathType: Prefix
        backend:
          service:
            name: rabbitmq
            port:
              number: 15672
</code>```

When I type http://localhost/rabbitmq in my browser I get this nginx error: {"error":"Object Not Found","reason":"Not Found"}

But when I enter in some other pod and I type: curl http://rabbitmq:15672 It get the a response of the website.

Im new to kubernetes, I havent found any relevant solution to my problem, If someone could help me I would very grateful!!

Thanks for reading.

答:
Try:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  ingressClassName: nginx  # <-- assumed you only have 1 ingress-nginx
  rules:
  - http:
      paths:
      - path: /rabbitmq(/|$)(.*)
        ...
</code>```

Request to http://localhost/rabbitmq will be seen by your rabbitmq service as /

Body:
I have a kubernetes cluster with a deployment of rabbitmq. I want to expose the rabbitmanagment UI in that way I can access to it in my browser. To do that I have a deployment, service and ingress file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rabbitmq
  template:
    metadata:
      labels:
        app: rabbitmq
    spec:
      containers:
        - image: rabbitmq:3.8.9-management
          name: rabbitmq
          ports:
            - containerPort: 5672
            - containerPort: 15672
          resources: {}
      restartPolicy: Always

The service:

apiVersion: v1
kind: Service
metadata:
  name: rabbitmq
spec:
  ports:
    - name: "5672"
      port: 5672
      targetPort: 5672
    - name: "15672"
      port: 15672
      targetPort: 15672
  selector:
    app: rabbitmq

Ingress file

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
spec:
  rules:
  - http:
      paths:
      - path: /rabbitmq
        pathType: Prefix
        backend:
          service:
            name: rabbitmq
            port:
              number: 15672

When I type http://localhost/rabbitmq in my browser I get this nginx error: {"error":"Object Not Found","reason":"Not Found"}

But when I enter in some other pod and I type: curl http://rabbitmq:15672 It get the a response of the website.

Im new to kubernetes, I havent found any relevant solution to my problem, If someone could help me I would very grateful!!

Thanks for reading.

Body:
Try:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  ingressClassName: nginx  # <-- assumed you only have 1 ingress-nginx
  rules:
  - http:
      paths:
      - path: /rabbitmq(/|$)(.*)
        ...

Request to http://localhost/rabbitmq will be seen by your rabbitmq service as /


问:
Why does putting a table inside a flex container with align-items: center mess up scrolling on overflow?
I am trying to create a responsive table by letting the table be scrollable in the x-axis.  The code below works as I want.  However, if I add align-items: center; to the body's styling, the table won't scroll anymore.  Why is that, and is there a good way to work around this?

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

body {
  display: flex;
  flex-flow: column nowrap;
}

table {
  width: 100%;
  border: 1px solid #ddd;
}

div {
  overflow-x:auto;
}

</style>
</head>
<body>

<h2>Responsive Table</h2>
<p>This paragraph should be centred, as well as the table below.</p>

<div>
  <table>
    <tr>
      ...
    </tr>
    ...
  </table>
</div>

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

Here is a js-fiddle: https://jsfiddle.net/p72g5ast/

答:
Give div fixed width for table overflow.

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

Responsive Table

This paragraph should be centred, as well as the table below.

          Test
          Test
          Test
          Test
          Test
          Test
          Test

          Test
          Test
          Test
          Test
          Test
          Test
          Test

          Test
          Test
          Test
          Test
          Test
          Test
          Test

          Test
          Test
          Test
          Test
          Test
          Test
          Test

          Test
          Test
          Test
          Test
          Test
          Test
          Test

          Test
          Test
          Test
          Test
          Test
          Test
          Test

```

Body:
I am trying to create a responsive table by letting the table be scrollable in the x-axis.  The code below works as I want.  However, if I add align-items: center; to the body's styling, the table won't scroll anymore.  Why is that, and is there a good way to work around this?

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Responsive Table

This paragraph should be centred, as well as the table below.

      ...

    ...

Here is a js-fiddle: https://jsfiddle.net/p72g5ast/

Body:
Give div fixed width for table overflow.

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      display: flex;
      flex-flow: column nowrap;
      align-items:center;
    }
    table {
      width: 100%;
      border: 1px solid #ddd;
    }
    .tablewrapper {
      width:130px;
      overflow-x:auto;
    }
  </style>
</head>
<body>
  <h2>Responsive Table</h2>
  <p>This paragraph should be centred, as well as the table below.</p>
  <div class="tablewrapper">
    <table>
     <tbody>
        <tr>
          <th>Test</th>
          <th>Test</th>
          <th>Test</th>
          <th>Test</th>
          <th>Test</th>
          <th>Test</th>
          <th>Test</th>
        </tr>
        <tr>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
        </tr>
        <tr>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
        </tr>
        <tr>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
        </tr>
        <tr>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
        </tr>
        <tr>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
          <td>Test</td>
        </tr>
    </tbody>
  </table>
  </div>
</body>
</html>


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
I'm not sure who advised against the use of XML for persistence in your case, but it would seem to me that given the potential total size of your persisted data, XML is perfect for you because of its simple integration into .NET applications.

It sounds to me like we're only talking about 100 records with a maximum of 10 fields on a single record.  That could easily be preprocessed from XML persisted data and dealt with in memory.  I do agree with NoCarrier about potentially using LINQ to query.

You're looking for simplicity and your users sound like they could do without the 3rd party dependency.

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: phennings


问:
Minimum Commit Message Length
Is there a way to encourage(force) users to enter a commit message of at least X characters? excluding white space. I'm trying to stop commit messages that are just a blank space long or a couple of characters, instead encourage messages that have been thought about, that are at the very least X(50) characters.</p>

答:
I think this is really a people problem rather than a software problem. If developers are committing without messages they clearly don't understand why commit messages are important. You need to make sure everyone understands that good commit messages are expected, and ideally you'd ensure this while doing code reviews

Having said that a minimum commit message pretxnchangegroup hook does have some benefit. It can prevent accidental commits with no message, and may provide a bit of a nudge to correct bad behaviour. But it really does need to be coupled with education on why you need good commit messages else you risk developers writing their own hooks (pretxncommit I think) that pad the commit message to overcome your minimum length rule.

Title: Minimum Commit Message Length


问:
Tic-tac-toe game does not terminate in case of a draw
I am making a tic-tac-toe game using assembly language. It does not terminate in case of a draw. How can I rectify it?

Below is the code:

```<code>data segment
    new_line db 13, 10, "$"

    game_draw db "_|_|_", 13, 10
              db "_|_|_", 13, 10
              db "_|_|_", 13, 10, "$"

    game_pointer db 9 DUP(?)

    win_flag db 0
    player db "0$"

    game_over_message db "Game ended", 13, 10, "$"
    game_start_message db "Welcome", 13, 10, "$"
    player_message db "PLAYER $"
    win_message db " WIN!$"
    type_message db "TYPE A POSITION: $"
    tra db 'want to play again? (y/n):$'
    drw db "the game is draw! $"

ends

stack segment
    dw   128  dup(?)
ends

extra segment

ends

code segment

start:
    ; set segment registers
    mov     ax, data
    mov     ds, ax
    mov     ax, extra
    mov     es, ax

    ; game start
    call    set_game_pointer

main_loop:
    call    clear_screen

    lea     dx, game_start_message
    call    print

    lea     dx, new_line
    call    print

    lea     dx, player_message
    call    print
    lea     dx, player
    call    print

    lea     dx, new_line
    call    print

    lea     dx, game_draw
    call    print

    lea     dx, new_line
    call    print

    lea     dx, type_message
    call    print

    ; read draw position
    call    read_keyboard

    ; calculate draw position
    sub     al, 49
    mov     bh, 0
    mov     bl, al
    call update_draw

    call    check

    ; check if game ends
    cmp     win_flag, 1
    je     game_over ;STEPH CHANGES

    call    change_player

   jmp      main_loop

change_player:
    lea     si, player
    xor     ds:[si], 1

    ret
  update_draw:
    mov     bl, game_pointer[bx]
    mov     bh, 0

    lea     si, player

    cmp     ds:[si], "0"
    je      draw_x

    cmp     ds:[si], "1"
    je      draw_o

    draw_x:
    mov     cl, "x"
    jmp     update

    draw_o:
    mov     cl, "o"
    jmp     update

    update:
    mov     ds:[bx], cl

    ret

check:
    call    check_line
    ret

check_line:
    mov     cx, 0

    check_line_loop:
    cmp     cx, 0
    je      first_line

    cmp     cx, 1
    je      second_line

    cmp     cx, 2
    je      third_line

    call    check_column
    ret

    first_line:
    mov     si, 0
    jmp     do_check_line

    second_line:
    mov     si, 3
    jmp     do_check_line

    third_line:
    mov     si, 6
    jmp     do_check_line

    do_check_line:
    inc     cx

    mov     bh, 0
    mov     bl, game_pointer[si]
    mov     al, ds:[bx]
    cmp     al, "_"
    je      check_line_loop

    inc     si
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_line_loop

    inc     si
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_line_loop

    mov     win_flag, 1
    ret

check_column:
    mov     cx, 0

    check_column_loop:
    cmp     cx, 0
    je      first_column

    cmp     cx, 1
    je      second_column

    cmp     cx, 2
    je      third_column

    call    check_diagonal
    ret

    first_column:
    mov     si, 0
    jmp     do_check_column

    second_column:
    mov     si, 1
    jmp     do_check_column

    third_column:
    mov     si, 2
    jmp     do_check_column

    do_check_column:
    inc     cx

    mov     bh, 0
    mov     bl, game_pointer[si]
    mov     al, ds:[bx]
    cmp     al, "_"
    je      check_column_loop

    add     si, 3
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_column_loop

    add     si, 3
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_column_loop

    mov     win_flag, 1
    ret

check_diagonal:
    mov     cx, 0

    check_diagonal_loop:
    cmp     cx, 0
    je      first_diagonal

    cmp     cx, 1
    je      second_diagonal

    ret

    first_diagonal:
    mov     si, 0
    mov     dx, 4 ;jump size
    jmp     do_check_diagonal

    second_diagonal:
    mov     si, 2
    mov     dx, 2
    jmp     do_check_diagonal

    do_check_diagonal:
    inc     cx

    mov     bh, 0
    mov     bl, game_pointer[si]
    mov     al, ds:[bx]
    cmp     al, "_"
    je      check_diagonal_loop

    add     si, dx
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_diagonal_loop

    add     si, dx
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_diagonal_loop

    mov     win_flag, 1
    ret

game_over:
    call    clear_screen

    lea     dx, game_start_message
    call    print

    lea     dx, new_line
    call    print

    lea     dx, game_draw
    call    print

    lea     dx, new_line
    call    print

    lea     dx, game_over_message
    call    print

    lea     dx, player_message
    call    print

    lea     dx, player
    call    print

    lea     dx, win_message
    call    print

    jmp     fim

set_game_pointer:
    lea     si, game_draw
    lea     bx, game_pointer

    mov     cx, 9

    loop_1:
    cmp     cx, 6
    je      add_1

    cmp     cx, 3
    je      add_1

    jmp     add_2

    add_1:
    add     si, 1
    jmp     add_2

    add_2:
    mov     ds:[bx], si
    add     si, 2

    inc     bx
    loop    loop_1

    ret

print:      ; print dx content
    mov     ah, 9
    int     21h

    ret

clear_screen:       ; get and set video mode
    mov     ah, 0fh
    int     10h

    mov     ah, 0
    int     10h

    ret

read_keyboard:  ; read keybord and return content in ah
    mov     ah, 1
    int     21h
    ret

    ret

fim:
    jmp     fim

code ends

end start
</code>```

答:
I added the line below under ;set segment registers

```<code>mov     bp,9
</code>```

After ;check if game ends  I added the code below to calculate draw position

```<code>;Calculate draw position
sub bp,1
cmp bp,0
je game_drawn
</code>```

Below game_over: I added game_drawn to print game draw message

```<code>game_drawn:
call    clear_screen

lea     dx, game_start_message
call    print

lea     dx, new_line
call    print

lea     dx, game_draw
call    print

lea     dx, new_line
call    print

lea     dx, game_draw_message
call    print

lea     dx, player_message
call    print

jmp     fim
</code>```

Body:
I am making a tic-tac-toe game using assembly language. It does not terminate in case of a draw. How can I rectify it?

Below is the code:

data segment
    new_line db 13, 10, "$"

    game_draw db "_|_|_", 13, 10
              db "_|_|_", 13, 10
              db "_|_|_", 13, 10, "$"

    game_pointer db 9 DUP(?)

    win_flag db 0
    player db "0$"

    game_over_message db "Game ended", 13, 10, "$"
    game_start_message db "Welcome", 13, 10, "$"
    player_message db "PLAYER $"
    win_message db " WIN!$"
    type_message db "TYPE A POSITION: $"
    tra db 'want to play again? (y/n):$'
    drw db "the game is draw! $"

ends

stack segment
    dw   128  dup(?)
ends

extra segment

ends

code segment

start:
    ; set segment registers
    mov     ax, data
    mov     ds, ax
    mov     ax, extra
    mov     es, ax

    ; game start
    call    set_game_pointer

main_loop:
    call    clear_screen

    lea     dx, game_start_message
    call    print

    lea     dx, new_line
    call    print

    lea     dx, player_message
    call    print
    lea     dx, player
    call    print

    lea     dx, new_line
    call    print

    lea     dx, game_draw
    call    print

    lea     dx, new_line
    call    print

    lea     dx, type_message
    call    print

    ; read draw position
    call    read_keyboard

    ; calculate draw position
    sub     al, 49
    mov     bh, 0
    mov     bl, al
    call update_draw

    call    check

    ; check if game ends
    cmp     win_flag, 1
    je     game_over ;STEPH CHANGES

    call    change_player

   jmp      main_loop

change_player:
    lea     si, player
    xor     ds:[si], 1

    ret
  update_draw:
    mov     bl, game_pointer[bx]
    mov     bh, 0

    lea     si, player

    cmp     ds:[si], "0"
    je      draw_x

    cmp     ds:[si], "1"
    je      draw_o

    draw_x:
    mov     cl, "x"
    jmp     update

    draw_o:
    mov     cl, "o"
    jmp     update

    update:
    mov     ds:[bx], cl

    ret

check:
    call    check_line
    ret

check_line:
    mov     cx, 0

    check_line_loop:
    cmp     cx, 0
    je      first_line

    cmp     cx, 1
    je      second_line

    cmp     cx, 2
    je      third_line

    call    check_column
    ret

    first_line:
    mov     si, 0
    jmp     do_check_line

    second_line:
    mov     si, 3
    jmp     do_check_line

    third_line:
    mov     si, 6
    jmp     do_check_line

    do_check_line:
    inc     cx

    mov     bh, 0
    mov     bl, game_pointer[si]
    mov     al, ds:[bx]
    cmp     al, "_"
    je      check_line_loop

    inc     si
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_line_loop

    inc     si
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_line_loop

    mov     win_flag, 1
    ret

check_column:
    mov     cx, 0

    check_column_loop:
    cmp     cx, 0
    je      first_column

    cmp     cx, 1
    je      second_column

    cmp     cx, 2
    je      third_column

    call    check_diagonal
    ret

    first_column:
    mov     si, 0
    jmp     do_check_column

    second_column:
    mov     si, 1
    jmp     do_check_column

    third_column:
    mov     si, 2
    jmp     do_check_column

    do_check_column:
    inc     cx

    mov     bh, 0
    mov     bl, game_pointer[si]
    mov     al, ds:[bx]
    cmp     al, "_"
    je      check_column_loop

    add     si, 3
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_column_loop

    add     si, 3
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_column_loop

    mov     win_flag, 1
    ret

check_diagonal:
    mov     cx, 0

    check_diagonal_loop:
    cmp     cx, 0
    je      first_diagonal

    cmp     cx, 1
    je      second_diagonal

    ret

    first_diagonal:
    mov     si, 0
    mov     dx, 4 ;jump size
    jmp     do_check_diagonal

    second_diagonal:
    mov     si, 2
    mov     dx, 2
    jmp     do_check_diagonal

    do_check_diagonal:
    inc     cx

    mov     bh, 0
    mov     bl, game_pointer[si]
    mov     al, ds:[bx]
    cmp     al, "_"
    je      check_diagonal_loop

    add     si, dx
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_diagonal_loop

    add     si, dx
    mov     bl, game_pointer[si]
    cmp     al, ds:[bx]
    jne     check_diagonal_loop

    mov     win_flag, 1
    ret

game_over:
    call    clear_screen

    lea     dx, game_start_message
    call    print

    lea     dx, new_line
    call    print

    lea     dx, game_draw
    call    print

    lea     dx, new_line
    call    print

    lea     dx, game_over_message
    call    print

    lea     dx, player_message
    call    print

    lea     dx, player
    call    print

    lea     dx, win_message
    call    print

    jmp     fim

set_game_pointer:
    lea     si, game_draw
    lea     bx, game_pointer

    mov     cx, 9

    loop_1:
    cmp     cx, 6
    je      add_1

    cmp     cx, 3
    je      add_1

    jmp     add_2

    add_1:
    add     si, 1
    jmp     add_2

    add_2:
    mov     ds:[bx], si
    add     si, 2

    inc     bx
    loop    loop_1

    ret

print:      ; print dx content
    mov     ah, 9
    int     21h

    ret

clear_screen:       ; get and set video mode
    mov     ah, 0fh
    int     10h

    mov     ah, 0
    int     10h

    ret

read_keyboard:  ; read keybord and return content in ah
    mov     ah, 1
    int     21h
    ret

    ret

fim:
    jmp     fim

code ends

end start

Body:
I added the line below under ;set segment registers

mov     bp,9

After ;check if game ends  I added the code below to calculate draw position

;Calculate draw position
sub bp,1
cmp bp,0
je game_drawn

Below game_over: I added game_drawn to print game draw message

game_drawn:
call    clear_screen

lea     dx, game_start_message
call    print

lea     dx, new_line
call    print

lea     dx, game_draw
call    print

lea     dx, new_line
call    print

lea     dx, game_draw_message
call    print

lea     dx, player_message
call    print

jmp     fim