问:
What is wrong with my PHP WordPress code?
This is my code in index.php of the WordPress theme:

```<code><div id="content">
            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "";
                } else {
                    $specialprt = "prt-right";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">
                <div class="prt-img">
                    <?php echo bdw_get_images($post->the_ID, 'medium'); ?>
                </div>
                <div class="prt-tags">
                    <?php the_tags(' ', ''); ?>
                </div>
                <h2 class="prt-title">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
                </h2>
                <span class="prt-small">Posted on <?php the_time('l F jS') ?> by <?php the_author() ?></span>
                <p><?php the_excerpt(); ?></p>
                <p><?php edit_post_link('Edit', '', ''); ?></p>
            </div>
            <?php $counter++; ?>
            <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- #content -->
</code>```

Problems:

All the posts have the same image. Why?

Page loads very slow. Why?

Can anybody give a hand of help? :)

Thanks.

UPDATE:

I have better results with this:

```<code><div id="content">
            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "prt-right";
                } else {
                    $specialprt = "";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">
                <div class="prt-img">
                    <?php
                    $args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID );
                    $attachments = get_posts($args);
                    if ($attachments) {
                        foreach ( $attachments as $attachment ) {
                            the_attachment_link( $attachment->ID , true, false, false );
                        }
                    } else {
                        echo "<img src=\"<?php bloginfo('stylesheet_directory'); ?>/images/no-image.jpg\" width=\"250\" height=\"155\" />";
                    }
                    ?>
                </div>
                <div class="prt-tags">
                    <?php the_tags(' ', ''); ?>
                </div>
                <h2 class="prt-title">
                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
                </h2>
                <span class="prt-small">Posted on <?php the_time('l F jS') ?> by <?php the_author() ?></span>
                <p><?php the_excerpt(); ?></p>
                <p><?php edit_post_link('Edit', '', ''); ?></p>
            </div>
            <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- #content -->
</code>```

答:
try putting the counter in while like this:</p>

```<code><?php while (have_posts()) : the_post();$counter++;?>

<?php
if ($counter % 2) {
                $specialprt = "";
            } else {
                $specialprt = "prt-right";
            }
 ?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my code in index.php of the WordPress theme:

            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "";
                } else {
                    $specialprt = "prt-right";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">

                    <?php echo bdw_get_images($post->the_ID, 'medium'); ?>

                    <?php the_tags(' ', ''); ?>

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                Posted on <?php the_time('l F jS') ?> by <?php the_author() ?>

<?php the_excerpt(); ?>

<?php edit_post_link('Edit', '', ''); ?>

            <?php $counter++; ?>
            <?php endwhile; ?>
            <?php endif; ?>

Problems:

All the posts have the same image. Why?

Page loads very slow. Why?

Can anybody give a hand of help? :)

Thanks.

UPDATE:

I have better results with this:

            <?php if (have_posts()) : ?>
            <?php $counter = "0"; ?>
            <?php while (have_posts()) : the_post(); $counter++; ?>
            <?php
                if ($counter % 2) {
                    $specialprt = "prt-right";
                } else {
                    $specialprt = "";
                }
            ?>
            <div class="partial <?php echo $specialprt; ?>" id="post-<?php the_ID(); ?>">

                    <?php
                    $args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID );
                    $attachments = get_posts($args);
                    if ($attachments) {
                        foreach ( $attachments as $attachment ) {
                            the_attachment_link( $attachment->ID , true, false, false );
                        }
                    } else {
                        echo "<img src=\"<?php bloginfo('stylesheet_directory'); ?>/images/no-image.jpg\" width=\"250\" height=\"155\" />";
                    }
                    ?>

                    <?php the_tags(' ', ''); ?>

                    <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>

                Posted on <?php the_time('l F jS') ?> by <?php the_author() ?>

<?php the_excerpt(); ?>

<?php edit_post_link('Edit', '', ''); ?>

            <?php endwhile; ?>
            <?php endif; ?>

Body:
try putting the counter in while like this:

<?php while (have_posts()) : the_post();$counter++;?>

<?php
if ($counter % 2) {
                $specialprt = "";
            } else {
                $specialprt = "prt-right";
            }
 ?>


来源: stackexchange

问:
SessionNotCreatedException only support Chrome version 80
I have this code below and it throw the SessionNotCreatedException on the last line.

```<code>chrome_options = Options()
LANG = 'fr,fr_FR'
chrome_options.add_experimental_option('prefs', {'intl.accept_languages': LANG})
chrome_options.add_argument("--user-data-dir=chrome-data")
browser = webdriver.Chrome(options=chrome_options)
</code>```

SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 80

However, I am already using version 80 ! Downloaded here : https://chromedriver.storage.googleapis.com/index.html?path=80.0.3987.106/

答:
Alternative which worked : SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

However, the silent log mode doesn't work...

```<code>os.environ['WDM_LOG_LEVEL'] = '0'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this code below and it throw the SessionNotCreatedException on the last line.

chrome_options = Options()
LANG = 'fr,fr_FR'
chrome_options.add_experimental_option('prefs', {'intl.accept_languages': LANG})
chrome_options.add_argument("--user-data-dir=chrome-data")
browser = webdriver.Chrome(options=chrome_options)

SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 80

However, I am already using version 80 ! Downloaded here : https://chromedriver.storage.googleapis.com/index.html?path=80.0.3987.106/

Body:
Alternative which worked : SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

However, the silent log mode doesn't work...

os.environ['WDM_LOG_LEVEL'] = '0'


问:
Java.How to use multiple variables and iterate over a multiple objects in for loop?
For starters, i'm new in Java

I'm trying like

```<code>for(forWriting  f : treeSet, forDrawing f2 : treeSet2)
</code>```

but it doesn't work like that

It works only when i use one variable and iterate over a single object, like that

```<code>for(forWriting  f : treeSet)
</code>```

How can i do it in Java? Thanks for your help!

答:
In addition to this answer, you might also want to make sure you 1) iterate over each element and 2) prevent IndexOutOfBound-Exceptions (Pseudo):</p>

```<code>int max_length = max(treeSet1.length, treeSet2.length);
for(int i = 0; i < max_length; i++) {
    if(i < treeSet1.length) {
        forWriting f = treeSet1.get_by_index(i);
        // Do stuff for forWriting here
    }
    if(i < treeSet2.length) {
        forDrawing f2 = treeSet2.get_by_index(i);
        // Do stuff for forDrawing here
    }
}
</code>```

Body:
For starters, i'm new in Java

I'm trying like

for(forWriting  f : treeSet, forDrawing f2 : treeSet2)

but it doesn't work like that

It works only when i use one variable and iterate over a single object, like that

for(forWriting  f : treeSet)

How can i do it in Java? Thanks for your help!

Body:
In addition to this answer, you might also want to make sure you 1) iterate over each element and 2) prevent IndexOutOfBound-Exceptions (Pseudo):

int max_length = max(treeSet1.length, treeSet2.length);
for(int i = 0; i < max_length; i++) {
    if(i < treeSet1.length) {
        forWriting f = treeSet1.get_by_index(i);
        // Do stuff for forWriting here
    }
    if(i < treeSet2.length) {
        forDrawing f2 = treeSet2.get_by_index(i);
        // Do stuff for forDrawing here
    }
}


问:
Drawing Bowling Pins (pyramid) with Recursion in Ada
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

```<code>I I I I I
 I I I I
  I I I
   I I
    I
n = 5
</code>```

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

```<code>I I I
I I
I
n = 3
</code>```

and that's using

THIS CODE NOW WORKS

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

</code>```

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

```<code>Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.
</code>```

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

答:
The way you develop a recursive algorithm is to pretend that you already have a subprogram that does what you want, except for the first bit, and you know, or can figure out, how to do the first bit. Then your algorithm is

```<code>Do the first bit
Call the subprogram to do the rest on what remains,
   taking into account the effect of the first bit, if necessary
</code>```

The trick is that "Call the subprogram to do the rest" is a recursive call to the subprogram you're creating.

It's always possible that the subprogram may be called when there's nothing to do, so you have to take that into account:

```<code>if Ending Condition then
   Do any final actions

   return [expression];
end if;

Do the first bit
Call the subprogram to do the rest
</code>```

And you're done. By repreatedly doing the first bit until the ending condition is True, you end up doing the whole thing.

As an example, the function Get_Line in Ada.Text_IO may be implemented (this is not how it is usually implemented) by thinking, "I know how to get the first Character of the line. If I have a function to return the rest of the line, then I can return the first Character concatenated with the function result." So:

```<code>function Get_Line return String is
   C : Character;
begin
   Get (Item => C);

   return C & Get_Line;
end Get_Line;
</code>```

But what if we're already at the end of a line, so there's no line to get?

```<code>function Get_Line return String is
   C : Character;
begin
   if End_Of_Line then
      Skip_Line;

      return "";
   end if;

   Get (Item => C);

   return C & Get_Line;
end Get_Line;
</code>```

For your problem the first bit is printing a row with an indent and a number of pins, and the ending condition is when there are no more rows to print.

For your pyramid problem, this tail recursion scheme doesn't work. You need to do "middle recursion":

```<code>if Level = 1 then
   Print the line for Level

   return
end if

Print the top line for Level
Recurse for Level - 1
Print the bottom line for Level
</code>```

Body:
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

I I I I I
 I I I I
  I I I
   I I
    I
n = 5

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

I I I
I I
I
n = 3

and that's using

THIS CODE NOW WORKS

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

Body:
The way you develop a recursive algorithm is to pretend that you already have a subprogram that does what you want, except for the first bit, and you know, or can figure out, how to do the first bit. Then your algorithm is

Do the first bit
Call the subprogram to do the rest on what remains,
   taking into account the effect of the first bit, if necessary

The trick is that "Call the subprogram to do the rest" is a recursive call to the subprogram you're creating.

It's always possible that the subprogram may be called when there's nothing to do, so you have to take that into account:

if Ending Condition then
   Do any final actions

   return [expression];
end if;

Do the first bit
Call the subprogram to do the rest

And you're done. By repreatedly doing the first bit until the ending condition is True, you end up doing the whole thing.

As an example, the function Get_Line in Ada.Text_IO may be implemented (this is not how it is usually implemented) by thinking, "I know how to get the first Character of the line. If I have a function to return the rest of the line, then I can return the first Character concatenated with the function result." So:

function Get_Line return String is
   C : Character;
begin
   Get (Item => C);

   return C & Get_Line;
end Get_Line;

But what if we're already at the end of a line, so there's no line to get?

function Get_Line return String is
   C : Character;
begin
   if End_Of_Line then
      Skip_Line;

      return "";
   end if;

   Get (Item => C);

   return C & Get_Line;
end Get_Line;

For your problem the first bit is printing a row with an indent and a number of pins, and the ending condition is when there are no more rows to print.

For your pyramid problem, this tail recursion scheme doesn't work. You need to do "middle recursion":

if Level = 1 then
   Print the line for Level

   return
end if

Print the top line for Level
Recurse for Level - 1
Print the bottom line for Level


问:
MSWord how to unlink/break first link to excel document, without breaking remaining set of hyperlinks
I want to set up a word template, which has a linked excel table via a field with following code:

{LINK Excel.SheetMacroEnabled.12 D:\calendar.xlsm calendar!namedR \f 4 \h \* MERGEFORMAT}

The table resides in excel and is updated daily. The excel has several columns and one of them has a set of hyperlinks to various websites in rows. When I try to break the link to the table, in order to create rest of the document and archive it via the following code, I always get all of the links (including hyperlinks to websites) in the linked table broken.
The funny thing is that when I do it manually and select the table in Word it breaks only the link to the excel table, leaving the hyperlinks in a table column intact. This is the desired programmatic outcome. I tried 2 following macros and none of them works. Is there a way to achieve it via VBA without breaking all the links in a linked table?

```<code>Sub ConvertTableLink()

    Dim myField As Field

   For Each myField In ActiveDocument.Fields
      If myField.Type = wdFieldLink Then
         myField.Unlink
      End If
   Next

End Sub

Sub ConvertTableLinkTake2()

   ActiveDocument.Fields(1).Update
   ActiveDocument.Fields(1).Unlink

End Sub

</code>```

答:
It's not obvious why your links are remaining when you unlink the LINK field manually but not with VBA. Generally speaking, I see the same behavior whichever way I do it here - the links remain blue so they still look like links, but they aren't.

You can do your own "unlink" that should preserve the hyperlinks using this, assuming the LINK is the first LINK field in the document:

```<code>Sub replaceLinkByResult1()
Dim fld As Word.Field
Dim rng As Word.Range
For Each fld In ActiveDocument.Fields
  If fld.Type = wdFieldLink Then
    Set rng = fld.Result.Tables(1).Range
    rng.Copy
    fld.Delete
    rng.Paste
    Exit For
  End If
Next
End Sub
</code>```

If Copy/Paste doesn't work or you prefer to avoid it, the following should also work:

```<code>Sub replaceLinkByResult2()
Dim fld As Word.Field
Dim rng1 As Word.Range
Dim rng2 As Word.Range
For Each fld In ActiveDocument.Fields
  If fld.Type = wdFieldLink Then
    Set rng1 = fld.Result.Tables(1).Range
    Set rng2 = rng1.Duplicate
    rng2.Collapse wdCollapseEnd
    rng2.Start = rng2.Start + 1
    rng2.InsertParagraph
    rng2.Start = rng2.Start + 1
    rng2.FormattedText = rng1.FormattedText
    fld.Delete
    Set rng2 = Nothing
    Set rng1 = Nothing
    Exit For
  End If
Next
End Sub
</code>```

Body:
I want to set up a word template, which has a linked excel table via a field with following code:

{LINK Excel.SheetMacroEnabled.12 D:\calendar.xlsm calendar!namedR \f 4 \h \* MERGEFORMAT}

The table resides in excel and is updated daily. The excel has several columns and one of them has a set of hyperlinks to various websites in rows. When I try to break the link to the table, in order to create rest of the document and archive it via the following code, I always get all of the links (including hyperlinks to websites) in the linked table broken.
The funny thing is that when I do it manually and select the table in Word it breaks only the link to the excel table, leaving the hyperlinks in a table column intact. This is the desired programmatic outcome. I tried 2 following macros and none of them works. Is there a way to achieve it via VBA without breaking all the links in a linked table?

Sub ConvertTableLink()

    Dim myField As Field

   For Each myField In ActiveDocument.Fields
      If myField.Type = wdFieldLink Then
         myField.Unlink
      End If
   Next

End Sub

Sub ConvertTableLinkTake2()

   ActiveDocument.Fields(1).Update
   ActiveDocument.Fields(1).Unlink

End Sub

Body:
It's not obvious why your links are remaining when you unlink the LINK field manually but not with VBA. Generally speaking, I see the same behavior whichever way I do it here - the links remain blue so they still look like links, but they aren't.

You can do your own "unlink" that should preserve the hyperlinks using this, assuming the LINK is the first LINK field in the document:

Sub replaceLinkByResult1()
Dim fld As Word.Field
Dim rng As Word.Range
For Each fld In ActiveDocument.Fields
  If fld.Type = wdFieldLink Then
    Set rng = fld.Result.Tables(1).Range
    rng.Copy
    fld.Delete
    rng.Paste
    Exit For
  End If
Next
End Sub

If Copy/Paste doesn't work or you prefer to avoid it, the following should also work:

Sub replaceLinkByResult2()
Dim fld As Word.Field
Dim rng1 As Word.Range
Dim rng2 As Word.Range
For Each fld In ActiveDocument.Fields
  If fld.Type = wdFieldLink Then
    Set rng1 = fld.Result.Tables(1).Range
    Set rng2 = rng1.Duplicate
    rng2.Collapse wdCollapseEnd
    rng2.Start = rng2.Start + 1
    rng2.InsertParagraph
    rng2.Start = rng2.Start + 1
    rng2.FormattedText = rng1.FormattedText
    fld.Delete
    Set rng2 = Nothing
    Set rng1 = Nothing
    Exit For
  End If
Next
End Sub


问:
How can I have multiple Swiper slideshows on a single page?
I'm using Swiper Slideshow. I'm using this particular version. Here's the exact code I'm using.

When adding a second Swiper, the pagination doesn't work properly.

I tried giving a different class to the second Swiper container but it didn't work.

How can I have two of this in the same page?

Thanks.

答:
In my case, the issue was with using multiple auto-initialized instances while using Framework7 Core to update slide results based on the data values.

The missing piece for this use case was assigning an id to the swiper container, for example:

```<code><div class="swiper-container swiper-init" id="swiper-instance-{{
userId}}">
</code>```

This little bit of magic causes everything to work again, otherwise it tries to re-use the Swiper instances and gets very confused about which one the instance belongs to. Once again Vladimir has thought of everything :)

Body:
In my case, the issue was with using multiple auto-initialized instances while using Framework7 Core to update slide results based on the data values.

The missing piece for this use case was assigning an id to the swiper container, for example:

<div class="swiper-container swiper-init" id="swiper-instance-{{
userId}}">

This little bit of magic causes everything to work again, otherwise it tries to re-use the Swiper instances and gets very confused about which one the instance belongs to. Once again Vladimir has thought of everything :)


问:
Entity Framework Core: How to return queryable<class> with 'using'?
ToList() can work.

```<code>public List<class> Get()
{
     using (var db = new dbcontext())
     {
          return db.class.ToList();
     }
}
</code>```

But AsQueryable() cannot work. How to get it working with using? I want to use queryable because it can get data faster than ToList().

EDIT

Decided to use dapper for select. EF Core for CUD. dapper's ToList()/Queryable faster in select comparing to EF's ToList() if want to use using().

Get 100k rows with using()

Dapper ToList()/Queryable = 250 to 300ms

EF's ToList() = 1300ms to 1500ms

Get 100k rows without using()

EF's Queryable = 0.03ms.

Really like EF's queryable due to its fastest performance but no choice because I need to dispose, if not, bad performance when too many users like 500k users. Decided to use dapper instead for select.

答:
It is not possible in a single method, you need to manage the lifetime of the DbContext outside Get method.

The .ToList() variant works because when calling .ToList() entity framework queries the data and stores the resulting objects. After that you do not need to query the database to access the data, hence the DbContext is not required anymore to access the list items.

When using Queryable you defer the query to a later point in time. This allows EF Core to create more efficient DB queries, because Linq Operatos like Where() can be translated to SQL when calling ToList() or similar methods. The DbContext is required to execute the actual SQL query and thus it needs to be kept alive.

Also take a look at https://learn.microsoft.com/en-us/ef/ef6/fundamentals/working-with-dbcontext#lifetime for some guidelines on the lifetime of DbContext. The article is for EF6, but the concept applies to EF Core as well.

Body:
ToList() can work.

public List<class> Get()
{
     using (var db = new dbcontext())
     {
          return db.class.ToList();
     }
}

But AsQueryable() cannot work. How to get it working with using? I want to use queryable because it can get data faster than ToList().

EDIT

Decided to use dapper for select. EF Core for CUD. dapper's ToList()/Queryable faster in select comparing to EF's ToList() if want to use using().

Get 100k rows with using()

Dapper ToList()/Queryable = 250 to 300ms

EF's ToList() = 1300ms to 1500ms

Get 100k rows without using()

EF's Queryable = 0.03ms.

Really like EF's queryable due to its fastest performance but no choice because I need to dispose, if not, bad performance when too many users like 500k users. Decided to use dapper instead for select.


问:
Flyway migration after jpa tables have been created
I'm using flyway database migration tool with a spring boot jpa project. When I run the server first flyway wants to migrate sqls, but tables have not created yet. In this case flyway returns an error which like

Caused by: org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateSqlException:
Migration V1__countries_and_states.sql failed
SQL State  : 42S02
Error Code : 1146
Message    : Table 'wallet.country' doesn't exist
Location   : db/migration/V1__countries_and_states.sql (/root/IdeaProjects/service/target/classes/db/migration/V1__countries_and_states.sql)
Line       : 1

I configured application.properties file with these options:

spring.flyway.baseline-on-migrate=true

spring.flyway.enabled=true

spring.flyway.clean-on-validation-error=true

spring.flyway.init-on-migrate=true

I want that my migration will have been successfully  done.

答: Can be used configuration properties like: flyway.out-of-order = true. It says flyway works after hibernate/jpa has been created/updated tables.


问:
(Swift/FireStore)How to put URL to StringArray
```<code> func fetchData(){

        let saveDocument = Firestore.firestore()

       guard let user = Auth.auth().currentUser else{
                      return
                  }

            let uploadDocument = saveDocument.collection("upLoad").document(user.uid) .collection("Posts")

    uploadDocument.getDocuments { (querySnapshot, error) in

            if error != nil {
                print("error")
            } else {
                for document in querySnapshot!.documents {
                    if let foodValue =

        document.data()["FoodImage"] as? String{

     self.foodImageArray.append(foodValue)
            }
print(self.foodImageArray)
                }
</code>```

　↑ This time , I can print foodImageArray

```<code>  var foodImageArray: [String] = []
 override func viewDidLoad() {
        super.viewDidLoad()
        fetchData()
 print(foodImageArray)
    }
</code>```

↑However ,this time when i try to print out the item,
it printed out like [](null)

I want to put my Items in foodImageArray
and show them in cell

How can I put my items taken by cloudFirestore to foodImageArray?

答:
You need to print out once the fetch is completed which takes time and is run as a background task. To get the result you received when you print, modify fetchData to look like this:

func fetchData(completion: @escaping () -> Void) {

    let saveDocument = Firestore.firestore()

    guard let user = Auth.auth().currentUser else{
        return
    }

    let uploadDocument = saveDocument.collection("upLoad").document(user.uid).collection("Posts")

    uploadDocument.getDocuments { (querySnapshot, error) in

        if error != nil {
            print("error")
        } else {
            for document in querySnapshot!.documents {
                if let foodValue = document.data()["FoodImage"] as? String{
                    self.foodImageArray.append(foodValue)
                }
            }
        }
        completion?()
    }
}
```

<p>And call <code>fetchData</code> like this:</p>

<pre class="lang-swift prettyprint-override"><code>var foodImageArray: [String] = []
override func viewDidLoad() {
    super.viewDidLoad()
    fetchData {
        print(self.foodImageArray)
    }
}
</code>```

Note: This is only an example a much better approach is to pass the array as a parameter in the completion block.

Body:
 func fetchData(){

        let saveDocument = Firestore.firestore()

       guard let user = Auth.auth().currentUser else{
                      return
                  }

            let uploadDocument = saveDocument.collection("upLoad").document(user.uid) .collection("Posts")

    uploadDocument.getDocuments { (querySnapshot, error) in

            if error != nil {
                print("error")
            } else {
                for document in querySnapshot!.documents {
                    if let foodValue =

        document.data()["FoodImage"] as? String{

     self.foodImageArray.append(foodValue)
            }
print(self.foodImageArray)
                }

　↑ This time , I can print foodImageArray

  var foodImageArray: [String] = []
 override func viewDidLoad() {
        super.viewDidLoad()
        fetchData()
 print(foodImageArray)
    }

↑However ,this time when i try to print out the item,
it printed out like [](null)

I want to put my Items in foodImageArray
and show them in cell

How can I put my items taken by cloudFirestore to foodImageArray?

Body:
You need to print out once the fetch is completed which takes time and is run as a background task. To get the result you received when you print, modify fetchData to look like this:

func fetchData(completion: @escaping () -> Void) {

    let saveDocument = Firestore.firestore()

    guard let user = Auth.auth().currentUser else{
        return
    }

    let uploadDocument = saveDocument.collection("upLoad").document(user.uid).collection("Posts")

    uploadDocument.getDocuments { (querySnapshot, error) in

        if error != nil {
            print("error")
        } else {
            for document in querySnapshot!.documents {
                if let foodValue = document.data()["FoodImage"] as? String{
                    self.foodImageArray.append(foodValue)
                }
            }
        }
        completion?()
    }
}

And call fetchData like this:

var foodImageArray: [String] = []
override func viewDidLoad() {
    super.viewDidLoad()
    fetchData {
        print(self.foodImageArray)
    }
}

Note: This is only an example a much better approach is to pass the array as a parameter in the completion block.


问:
mysql query: how to get the number of yes/no votes per day
I have to create a mysql query to get a voting distribution of each day exceeding a particular date, something like this...

```<code>    date          yes_votes    no_votes
------------------------------------------
    2010-01-07    21           22
    2010-01-07    2            0
</code>```

My table is like this..

```<code>    post_votes
--------------------------
    id(longint)
    date(timestamp)
    flag(tinyint) // this stores the yes/no votes 1-yes, 2-no
</code>```

I am stuck at this....

```<code>SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)
</code>```

this gives the total number of votes per day, but not the distribution that I want.

答:
```<code>SELECT COUNT(*) AS count
     , DATE(date)
     , SUM(flag = 1) AS yes_votes
     , SUM(flag = 2) AS no_votes
FROM post_votes
WHERE date > '2010-07-01'
GROUP BY DATE(date)
</code>```

This is a trick that works in MySQL, as flag=1 will either be True or False. But True = 1 and False = 0 in MySQL so you can add the 1s and 0s using the SUM() function.

Other solutions with IF or CASE would be better for clarity or if there is any chance you want to move the database to another RDBMS.

Comments not related to the question:

It's bad habit to use reserved words like date or count for naming fields or tables.

It's also not good to use "date" when you actually store a timestamp. Names should reflect use.

For table names it's recommended to use singular (post_vote) and not plural - although many use plural, it gets confusing in the end. Plural is good for some fields or calulated fields, like your yes_votes and no_votes where we have a counting.

Body:
I have to create a mysql query to get a voting distribution of each day exceeding a particular date, something like this...

    date          yes_votes    no_votes
------------------------------------------
    2010-01-07    21           22
    2010-01-07    2            0

My table is like this..

    post_votes
--------------------------
    id(longint)
    date(timestamp)
    flag(tinyint) // this stores the yes/no votes 1-yes, 2-no

I am stuck at this....

SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)

this gives the total number of votes per day, but not the distribution that I want.

Body:
SELECT COUNT(*) AS count
     , DATE(date)
     , SUM(flag = 1) AS yes_votes
     , SUM(flag = 2) AS no_votes
FROM post_votes
WHERE date > '2010-07-01'
GROUP BY DATE(date)

This is a trick that works in MySQL, as flag=1 will either be True or False. But True = 1 and False = 0 in MySQL so you can add the 1s and 0s using the SUM() function.

Other solutions with IF or CASE would be better for clarity or if there is any chance you want to move the database to another RDBMS.

Comments not related to the question:

It's bad habit to use reserved words like date or count for naming fields or tables.

It's also not good to use "date" when you actually store a timestamp. Names should reflect use.

For table names it's recommended to use singular (post_vote) and not plural - although many use plural, it gets confusing in the end. Plural is good for some fields or calulated fields, like your yes_votes and no_votes where we have a counting.


问:
This version of ChromeDriver only supports Chrome version 79 - Python
This error drives me crazy. My code is:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import chromedriver_binary
from selenium.webdriver.common.by import By
import time
from influxdb import InfluxDBClient
chrome_options = Options()
chrome_options.add_argument("--headless")
chromedriver_binary =
"/home/dario/scripts/cron_run/web_app_login_checker/chromedriver/chromedriver"
driver = webdriver.Chrome(chromedriver_binary, options=chrome_options)
</code>```

If I do:

```<code> ./chromedriver -v
 ChromeDriver 79.0.3945.36 (3582db32b33893869b8c1339e8f4d9ed1816f143-refs/branch-
 heads/3945@{#614})
</code>```

It's the right version.

Full traceback is:

```<code>    Traceback (most recent call last):
    File "grafana.py", line 12, in <module>
    driver = webdriver.Chrome(chromedriver_binary, options=chrome_options)
    File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
    packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
    File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
   self.start_session(capabilities, browser_profile)
   File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/webdriver.py", line 252, in
   start_session
   response = self.execute(Command.NEW_SESSION, parameters)
   File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
   self.error_handler.check_response(response)
   File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/errorhandler.py", line 242, in
   check_response
   raise exception_class(message, screen, stacktrace)
   selenium.common.exceptions.SessionNotCreatedException: Message: session
   not created: This version of ChromeDriver only supports Chrome version
   79
</code>```

None of the already discussed topics here on Stack Overflow helped me.

答:
Check your chrome version

Download the same version of the chrome driver
Check the latest driver here

Update your driver in the reference folder.

In my case, I am using the windows 10 and python I've updated with the latest chromedriver.exe file (for Chrome v83)

Body:
This error drives me crazy. My code is:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import chromedriver_binary
from selenium.webdriver.common.by import By
import time
from influxdb import InfluxDBClient
chrome_options = Options()
chrome_options.add_argument("--headless")
chromedriver_binary =
"/home/dario/scripts/cron_run/web_app_login_checker/chromedriver/chromedriver"
driver = webdriver.Chrome(chromedriver_binary, options=chrome_options)

If I do:

 ./chromedriver -v
 ChromeDriver 79.0.3945.36 (3582db32b33893869b8c1339e8f4d9ed1816f143-refs/branch-
 heads/3945@{#614})

It's the right version.

Full traceback is:

    Traceback (most recent call last):
    File "grafana.py", line 12, in <module>
    driver = webdriver.Chrome(chromedriver_binary, options=chrome_options)
    File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
    packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    desired_capabilities=desired_capabilities)
    File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
   self.start_session(capabilities, browser_profile)
   File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/webdriver.py", line 252, in
   start_session
   response = self.execute(Command.NEW_SESSION, parameters)
   File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
   self.error_handler.check_response(response)
   File
   "/home/dario/scripts/cron_run/web_app_login_checker/lib/python3.6/site-
   packages/selenium/webdriver/remote/errorhandler.py", line 242, in
   check_response
   raise exception_class(message, screen, stacktrace)
   selenium.common.exceptions.SessionNotCreatedException: Message: session
   not created: This version of ChromeDriver only supports Chrome version
   79

None of the already discussed topics here on Stack Overflow helped me.


问:
Saving object in React.useState
I have a form in my react project, and I want the value of each field to be stored in the state.
instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)</p>

```<code>import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}
</code>```

答:
You can use useState hook. Check this

```<code>const [state, setState] = useState({ name, email });
</code>```

To set the state similar to setState in class based component:

```<code>setState({name: 'react', email: 'react'})
</code>```

To access the state value:

```<code>import React, { useState } from 'react';

export const UserData = () => {
const [state, setState] = useState({ name, email });
  return(
     <form>
        <input type="text" placeholder="Name" value={state.name} />
        <input type="email" placeholder="Email" value={state.email}  />
        <button>Confirm</button>
     </form>
  )
}
</code>```

Title: Saving object in React.useState

Body:
I have a form in my react project, and I want the value of each field to be stored in the state.
instead of having multiple states for each field, how can I store the form value as an object in the state? and more importantly how can I access it? (with react hooks)

import React from 'react';

export const UserData = () => {
  return(
     <form>
        <input type="text" placeholder="Name" />
        <input type="email" placeholder="Email" />
        <button>Confirm</button>
     </form>
  )
}

Body:
You can use useState hook. Check this

const [state, setState] = useState({ name, email });

To set the state similar to setState in class based component:

setState({name: 'react', email: 'react'})

To access the state value:

import React, { useState } from 'react';

export const UserData = () => {
const [state, setState] = useState({ name, email });
  return(
     <form>
        <input type="text" placeholder="Name" value={state.name} />
        <input type="email" placeholder="Email" value={state.email}  />
        <button>Confirm</button>
     </form>
  )
}


问:
Smartsheet API - copy and paste rows within the same sheet
Is it possible to copy and paste rows within in a single sheet with smartsheet api?
I am using python.

When I try the following (using the same sheet id)

```<code>response = smartsheet_client.Sheets.copy_rows(
 <MySheetID>,
 smartsheet.models.CopyOrMoveRowDirective({
            'row_ids': [<MyRowID>],
            'to': smartsheet.models.CopyOrMoveRowDestination({
              'sheet_id': <MySheetID>
            })
          })
        )
</code>```

I get the following error
"Cannot copy or move row(s) within the same sheet."

答: Copy the rows to a temporary sheet and then copy them to the base sheet ?</p>

Body:
Is it possible to copy and paste rows within in a single sheet with smartsheet api?
I am using python.

When I try the following (using the same sheet id)

response = smartsheet_client.Sheets.copy_rows(
 <MySheetID>,
 smartsheet.models.CopyOrMoveRowDirective({
            'row_ids': [<MyRowID>],
            'to': smartsheet.models.CopyOrMoveRowDestination({
              'sheet_id': <MySheetID>
            })
          })
        )

I get the following error
"Cannot copy or move row(s) within the same sheet."


问:
Strip span from h1 in Python (Beautiful soup)
I'm unable to delete the span from the H1 - I need just the H1 text without the text within the span:

```<code>page = requests.get("https://www.bbc.co.uk/weather/524901")
soup = BeautifulSoup(page.content, 'html.parser')
weather_desc_today = soup.find(class_="wr-day__weather-type-description").get_text()
weather_location = soup.find('h1').text
print (weather_location)

</code>```

Outputs:

```<code>Moscow - Weather warnings issued
</code>```

When I need just 'Moscow'

Here's the HTML:

```<code><h1 id="wr-location-name-id" tabindex="-1" class="wr-c-location__name gel-paragon">Moscow<span class="gs-u-vh wr-c-warnings-issued"> - <!-- -->Weather warnings issued</span></h1>
</code>```

答:
You can use find.

```<code>weather_location = soup.find('h1').find(text=True)

OUT: Moscow
</code>```

Body:
I'm unable to delete the span from the H1 - I need just the H1 text without the text within the span:

page = requests.get("https://www.bbc.co.uk/weather/524901")
soup = BeautifulSoup(page.content, 'html.parser')
weather_desc_today = soup.find(class_="wr-day__weather-type-description").get_text()
weather_location = soup.find('h1').text
print (weather_location)

Outputs:

Moscow - Weather warnings issued

When I need just 'Moscow'

Here's the HTML:

Moscow - Weather warnings issued

Body:
You can use find.

weather_location = soup.find('h1').find(text=True)

OUT: Moscow


问:
Detect Image Problems
I really don't know what it is called (distortion or something else)
But I would like to detect lens camera problems for some different types of images by using emgucv (or opencv)

Any ideas about which algorithms to use would be appreciated

Second image seems to have high noise, but is there any way to understand high noise via opencv?

答:
This is very difficult to achieve generically without reference data or a homogeneity sample. However, I have developed a recommendation analyzing the Average SNR (Signal to Noise) ratio of the image. The algorithm divides the input image into a specified number of "sub images' based on a specified kernel size in order to evaluate each independently for local SNR. The computed SNRs for each sub image are then mean averaged to provide an indicator for the global SNR of the image.

You will need to test this approach exhaustively, however it shows promise on the following three images, producing AvgSNR;

Image #1 - AvgSNR = 0.9

Image #2 - AvgSNR = 7.0

Image #3 - AvgSNR = 0.6

NOTE: See how the "clean" control image produces a much higher AvgSNR.

The only variable to consider is the kernel size. I would recommend keeping this at a size that will support will even the smallest of your potential input images. 30 pixels square should likely be appropriate for many images.

I enclose my test code with annotation:

class Program
{
    static void Main(string[] args)
    {
        // List of file names to load.
        List<string> fileNames = new List<string>()
        {
            "IifXZ.png",
            "o1z7p.jpg",
            "NdQtj.jpg"
        };

        // For each image
        foreach (string fileName in fileNames)
        {
            // Determine local file path
            string path = Path.Combine(Environment.CurrentDirectory, @"TestImages\", fileName);
            // Load the image
            Image<Bgr, byte> inputImage = new Image<Bgr, byte>(path);

            // Compute the AvgSNR with a kernel of 30x30
            Console.WriteLine(ComputeAverageSNR(30, inputImage.Convert<Gray, byte>()));

            // Display the image
            CvInvoke.NamedWindow("Test");
            CvInvoke.Imshow("Test", inputImage);
            while (CvInvoke.WaitKey() != 27) { }
        }

        // Pause for evaluation
        Console.ReadKey();
    }

    static double ComputeAverageSNR(int kernelSize, Image<Gray, byte> image)
    {
        // Calculate the number of sub-divisions given the kernel size
        int widthSubDivisions, heightSubDivisions;
        widthSubDivisions = (int)Math.Floor((double)image.Width / kernelSize);
        heightSubDivisions = (int)Math.Floor((double)image.Height / kernelSize);
        int totalNumberSubDivisions = widthSubDivisions * heightSubDivisions;
        Rectangle ROI = new Rectangle(0, 0, kernelSize, kernelSize);

        double avgSNR = 0;
        // Foreach sub-divions, calculate the SNR and sum to the avgSNR
        for (int v = 0; v < heightSubDivisions; v++)
        {
            for (int u = 0; u < widthSubDivisions; u++)
            {
                // Iterate the sub-division position
                ROI.Location = new Point(u * kernelSize, v * kernelSize);
                // Calculate the SNR of this sub-division
                avgSNR += ComputeSNR(image.GetSubRect(ROI));
            }
        }

        avgSNR /= totalNumberSubDivisions;

        return avgSNR;
    }

    static double ComputeSNR(Image<Gray, byte> image)
    {
        // Local varibles
        double mean, sigma, snr;

        // Calculate the mean pixel value for the sub-division
        int population = image.Width * image.Height;
        mean = CvInvoke.Sum(image).V0 / population;

        // Calculate the Sigma of the sub-division population
        double sumDeltaSqu = 0;
        for (int v = 0; v < image.Height; v++)
        {
            for (int u = 0; u < image.Width; u++)
            {
                sumDeltaSqu += Math.Pow(image.Data[v, u, 0] - mean, 2);
            }
        }
        sumDeltaSqu /= population;
        sigma = Math.Pow(sumDeltaSqu, 0.5);

        // Calculate and return the SNR value
        snr = sigma == 0 ? mean : mean / sigma;
        return snr;
    }
}
```

NOTE: Without a reference, it is not possible to differentiate between natural variance/fidelity and "noise". For example, a highly texture background, or a scene with few homogeneous regions will yield a high AvgSNR. This approach will perform best when the evaluated scene consists mostly of plain, mono-color surfaces, such as the server room or shop front. Grass for example would contain a large amount of texture and therefore "noise".

Title: Detect Image Problems

Body:
This is very difficult to achieve generically without reference data or a homogeneity sample. However, I have developed a recommendation analyzing the Average SNR (Signal to Noise) ratio of the image. The algorithm divides the input image into a specified number of "sub images' based on a specified kernel size in order to evaluate each independently for local SNR. The computed SNRs for each sub image are then mean averaged to provide an indicator for the global SNR of the image.

You will need to test this approach exhaustively, however it shows promise on the following three images, producing AvgSNR;

Image #1 - AvgSNR = 0.9

Image #2 - AvgSNR = 7.0

Image #3 - AvgSNR = 0.6

NOTE: See how the "clean" control image produces a much higher AvgSNR.

The only variable to consider is the kernel size. I would recommend keeping this at a size that will support will even the smallest of your potential input images. 30 pixels square should likely be appropriate for many images.

I enclose my test code with annotation:

class Program
{
    static void Main(string[] args)
    {
        // List of file names to load.
        List<string> fileNames = new List<string>()
        {
            "IifXZ.png",
            "o1z7p.jpg",
            "NdQtj.jpg"
        };

        // For each image
        foreach (string fileName in fileNames)
        {
            // Determine local file path
            string path = Path.Combine(Environment.CurrentDirectory, @"TestImages\", fileName);
            // Load the image
            Image<Bgr, byte> inputImage = new Image<Bgr, byte>(path);

            // Compute the AvgSNR with a kernel of 30x30
            Console.WriteLine(ComputeAverageSNR(30, inputImage.Convert<Gray, byte>()));

            // Display the image
            CvInvoke.NamedWindow("Test");
            CvInvoke.Imshow("Test", inputImage);
            while (CvInvoke.WaitKey() != 27) { }
        }

        // Pause for evaluation
        Console.ReadKey();
    }

    static double ComputeAverageSNR(int kernelSize, Image<Gray, byte> image)
    {
        // Calculate the number of sub-divisions given the kernel size
        int widthSubDivisions, heightSubDivisions;
        widthSubDivisions = (int)Math.Floor((double)image.Width / kernelSize);
        heightSubDivisions = (int)Math.Floor((double)image.Height / kernelSize);
        int totalNumberSubDivisions = widthSubDivisions * heightSubDivisions;
        Rectangle ROI = new Rectangle(0, 0, kernelSize, kernelSize);

        double avgSNR = 0;
        // Foreach sub-divions, calculate the SNR and sum to the avgSNR
        for (int v = 0; v < heightSubDivisions; v++)
        {
            for (int u = 0; u < widthSubDivisions; u++)
            {
                // Iterate the sub-division position
                ROI.Location = new Point(u * kernelSize, v * kernelSize);
                // Calculate the SNR of this sub-division
                avgSNR += ComputeSNR(image.GetSubRect(ROI));
            }
        }

        avgSNR /= totalNumberSubDivisions;

        return avgSNR;
    }

    static double ComputeSNR(Image<Gray, byte> image)
    {
        // Local varibles
        double mean, sigma, snr;

        // Calculate the mean pixel value for the sub-division
        int population = image.Width * image.Height;
        mean = CvInvoke.Sum(image).V0 / population;

        // Calculate the Sigma of the sub-division population
        double sumDeltaSqu = 0;
        for (int v = 0; v < image.Height; v++)
        {
            for (int u = 0; u < image.Width; u++)
            {
                sumDeltaSqu += Math.Pow(image.Data[v, u, 0] - mean, 2);
            }
        }
        sumDeltaSqu /= population;
        sigma = Math.Pow(sumDeltaSqu, 0.5);

        // Calculate and return the SNR value
        snr = sigma == 0 ? mean : mean / sigma;
        return snr;
    }
}

NOTE: Without a reference, it is not possible to differentiate between natural variance/fidelity and "noise". For example, a highly texture background, or a scene with few homogeneous regions will yield a high AvgSNR. This approach will perform best when the evaluated scene consists mostly of plain, mono-color surfaces, such as the server room or shop front. Grass for example would contain a large amount of texture and therefore "noise".


答:
you are almost at the solution :)

i would recommend the use of an IF condition in a SUM method like so:

```<code>SELECT SUM(IF(flag = 'yes',1,0)) AS yes_count,
       SUM(IF(flag = 'no',1,0)) AS no_count,
       DATE(date)
FROM post_votes
WHERE date > '2010-07-01'
GROUP BY DATE(date)
</code>```

this will allow for the function to add 1 to each sum only if the value is equal to yes/no

Title: mysql query: how to get the number of yes/no votes per day

Body:
you are almost at the solution :)

i would recommend the use of an IF condition in a SUM method like so:

SELECT SUM(IF(flag = 'yes',1,0)) AS yes_count,
       SUM(IF(flag = 'no',1,0)) AS no_count,
       DATE(date)
FROM post_votes
WHERE date > '2010-07-01'
GROUP BY DATE(date)

this will allow for the function to add 1 to each sum only if the value is equal to yes/no


问:
In what order does a minheap sort?
I've been reading various definitions on minHeap and maxHeap. I stumbled upon statements which say:

minHeap is used to sort in descending order.

maxHeap is used to sort in ascending order.

Statements taken from the "Note" in https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/ .
But when I implement minHeap using PriorityQueue<Integer> in Java with default comparator, and poll() it, I get the minimum element. Why is that?
Thanks to anybody who's trying to help :).

答:
The basic idea is to sort in place. Every time the algorithm polls from the heap, the heaps size shrinks by one. So one place at the end of the array is not part of the heap anymore. In this index the n-th smallest number is placed.

```<code>// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
    // Move current root to end
    swap(arr[0], arr[i]);

    // call max heapify on the reduced heap
    heapify(arr, i, 0);
}
</code>```

So the explanation why your algorithm using a PriorityQueue behaves so oddly is that you use a separate array for output. You could either switch to a max-heap and stick to your approach or fill the output-array in reverse. Both should produce the same behavior.

Title: In what order does a minheap sort?

Body:
The basic idea is to sort in place. Every time the algorithm polls from the heap, the heaps size shrinks by one. So one place at the end of the array is not part of the heap anymore. In this index the n-th smallest number is placed.

// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
    // Move current root to end
    swap(arr[0], arr[i]);

    // call max heapify on the reduced heap
    heapify(arr, i, 0);
}

So the explanation why your algorithm using a PriorityQueue behaves so oddly is that you use a separate array for output. You could either switch to a max-heap and stick to your approach or fill the output-array in reverse. Both should produce the same behavior.


答: AsQueryable does not have data in memory. It's just a query and you are delaying the data allocation until it's used as for example ToList. You can further query on AsQueryable only condition your dbcontext should be open.

Title: Entity Framework Core: How to return queryable<class> with 'using'?


问:
Saving excel range as a picture
I have an Excel sheet that has several charts and images which is used as a dashboard. I need to save the content in the area as an image. I found this code to save the area as an image:

```<code>Set sht = ActiveWorkbook.Sheets("Graphical Dashboard")
Set strRng = sht.Range("I1:AC124") ' range to be copied

strRng.CopyPicture xlScreen, xlPicture
lWidth = strRng.Width
lHeight = strRng.Height

Set Cht = sht.ChartObjects.Add(Left:=0, Top:=0, Width:=lWidth, Height:=lHeight)
Cht.Activate
Set oCht = Charts.Add

With oCht
    .Paste
    .Export Filename:=ThisWorkbook.Path & "\SavedRange.jpg", Filtername:="JPG"
End With

Cht.Delete
</code>```

But, the problem is, although it saves an image which matches the area of the selected range, the image is blank. Additionally, it adds another sheet named 'Chart' and pastes the blank image to sheet.

答:
First I select the range I need to copy and use the method .CopyPicture, then I clear all current pictures out of the workbook if the type is msoPicture, then I paste the image into the worksheet in order to add it to the chart, I then add the copied picture to the chart, export it, and remove the chart when I'm finished.</p>

```<code>Dim oCht, oChtArea, pic
Range("B2:AI5").CopyPicture
'On Error Resume Next

For Each pic In ThisWorkbook.Sheets("MonthlyRevenue").Shapes 'Deleting pics before copying next one in
    If pic.Type = msoPicture Then
        Debug.Print pic.Name
        pic.Delete
    End If
Next

With ThisWorkbook.Sheets("MonthlyRevenue").Pictures.Paste
    .Left = Range("C15").Left
    .Top = Range("C15").Top
    .Name = "monthRevPic"
End With

For Each pic In ThisWorkbook.Sheets("MonthlyRevenue").Shapes
    If pic.Type = msoPicture Then
        Debug.Print pic.Name
        pic.Copy
        'SavePicture pic, "C:\temp\tempchart.jpg"
        Set oCht = ActiveSheet.ChartObjects.Add(0, 0, pic.Width, pic.Height)
        Set oChtArea = oCht.Chart
        With oChtArea
            .Paste
            .Export ("C:\temp\tempchart.jpg")
        End With
        oCht.Delete
    End If
Next
</code>```

Title: Saving excel range as a picture

Body:
I have an Excel sheet that has several charts and images which is used as a dashboard. I need to save the content in the area as an image. I found this code to save the area as an image:

Set sht = ActiveWorkbook.Sheets("Graphical Dashboard")
Set strRng = sht.Range("I1:AC124") ' range to be copied

strRng.CopyPicture xlScreen, xlPicture
lWidth = strRng.Width
lHeight = strRng.Height

Set Cht = sht.ChartObjects.Add(Left:=0, Top:=0, Width:=lWidth, Height:=lHeight)
Cht.Activate
Set oCht = Charts.Add

With oCht
    .Paste
    .Export Filename:=ThisWorkbook.Path & "\SavedRange.jpg", Filtername:="JPG"
End With

Cht.Delete

But, the problem is, although it saves an image which matches the area of the selected range, the image is blank. Additionally, it adds another sheet named 'Chart' and pastes the blank image to sheet.

Body:
First I select the range I need to copy and use the method .CopyPicture, then I clear all current pictures out of the workbook if the type is msoPicture, then I paste the image into the worksheet in order to add it to the chart, I then add the copied picture to the chart, export it, and remove the chart when I'm finished.

Dim oCht, oChtArea, pic
Range("B2:AI5").CopyPicture
'On Error Resume Next

For Each pic In ThisWorkbook.Sheets("MonthlyRevenue").Shapes 'Deleting pics before copying next one in
    If pic.Type = msoPicture Then
        Debug.Print pic.Name
        pic.Delete
    End If
Next

With ThisWorkbook.Sheets("MonthlyRevenue").Pictures.Paste
    .Left = Range("C15").Left
    .Top = Range("C15").Top
    .Name = "monthRevPic"
End With

For Each pic In ThisWorkbook.Sheets("MonthlyRevenue").Shapes
    If pic.Type = msoPicture Then
        Debug.Print pic.Name
        pic.Copy
        'SavePicture pic, "C:\temp\tempchart.jpg"
        Set oCht = ActiveSheet.ChartObjects.Add(0, 0, pic.Width, pic.Height)
        Set oChtArea = oCht.Chart
        With oChtArea
            .Paste
            .Export ("C:\temp\tempchart.jpg")
        End With
        oCht.Delete
    End If
Next


问:
How to set the PATH environment variable in Jenkins configuration on Windows?
When I run my build process on Windows Server 2008, it fails with the error message like

Cannot run program "foo": CreateProcess: error=2, The system cannot find the file specified

I've already had a similar issue on Ubuntu Server and resolved it by adding the path to the folder with the binaries installed globally by Composer to the PATH variable in Jenkins config (Manage Jenkins -> Configure System -> Global properties -> Environment variables: name=PATH, value=$PATH:$COMPOSER_HOME/vendor/bin/):

(Due to a permissions moving COMPOSER_HOME outside of the /root directory was also needed to another one, accessible for Jenkins, was also needed.)

Now I tried the same on Windows, but it doesn't work. So, maybe I'm just setting the PATH wrong. What I've tried:

```<code>PATH
$PATH:D:\path\to\COMPOSER_HOME\vendor\bin

PATH
$PATH;D:\path\to\COMPOSER_HOME\vendor\bin

PATH
%PATH%D:\path\to\COMPOSER_HOME\vendor\bin

PATH
%PATH%;D:\path\to\COMPOSER_HOME\vendor\bin
</code>```

How to set the PATH environment variable in Jenkins configs correctly working on Windows?

答:
Couldn't get other it to work by the other answers. Ended up setting the variable in my slave node launcher (batch) script:</p>

```<code>SET PATH=C:\cygwin64\bin;%PATH%
java -jar agent.jar -jnlpUrl ...
</code>```

Body:
When I run my build process on Windows Server 2008, it fails with the error message like

Cannot run program "foo": CreateProcess: error=2, The system cannot find the file specified

I've already had a similar issue on Ubuntu Server and resolved it by adding the path to the folder with the binaries installed globally by Composer to the PATH variable in Jenkins config (Manage Jenkins -> Configure System -> Global properties -> Environment variables: name=PATH, value=$PATH:$COMPOSER_HOME/vendor/bin/):

(Due to a permissions moving COMPOSER_HOME outside of the /root directory was also needed to another one, accessible for Jenkins, was also needed.)

Now I tried the same on Windows, but it doesn't work. So, maybe I'm just setting the PATH wrong. What I've tried:

PATH
$PATH:D:\path\to\COMPOSER_HOME\vendor\bin

PATH
$PATH;D:\path\to\COMPOSER_HOME\vendor\bin

PATH
%PATH%D:\path\to\COMPOSER_HOME\vendor\bin

PATH
%PATH%;D:\path\to\COMPOSER_HOME\vendor\bin

How to set the PATH environment variable in Jenkins configs correctly working on Windows?

Body:
Couldn't get other it to work by the other answers. Ended up setting the variable in my slave node launcher (batch) script:

SET PATH=C:\cygwin64\bin;%PATH%
java -jar agent.jar -jnlpUrl ...


问:
Is there a way to save an Image with a View on it in React Native?
I have this image with the image of a ruler superimposed on it,as you can see in this image, and I want to save the image with the ruler on it to the camera roll . The ruler is a View component on the Image loaded from the camera roll. I am not able to find a way to do this. Can someone help?</p>

答:
You can use following github repository to superimpose image on video and image.

https://github.com/sagark1510/react-native-video-watermark

Using this git repo i am superimpose image on video succesfully.

This git repo produce some configuration error you need to solve those error.

You can also try this npm and git repository

```<code>npm i react-native-image-marker
</code>```

https://www.npmjs.com/package/react-native-image-marker

https://github.com/JimmyDaddy/react-native-image-marker

Body:
You can use following github repository to superimpose image on video and image.

https://github.com/sagark1510/react-native-video-watermark

Using this git repo i am superimpose image on video succesfully.

This git repo produce some configuration error you need to solve those error.

You can also try this npm and git repository

npm i react-native-image-marker

https://www.npmjs.com/package/react-native-image-marker

https://github.com/JimmyDaddy/react-native-image-marker


问:
getting a "Cannot read property 'getFoodX' of undefined" error
So I am trying to write a basic Snake Game and getting an undefined error although I don't see anything wrong with my code after reviewing it. I am getting the same error for this.apple.getFoodX when removing the if condition causing the error with getFood.

```<code>class Game {

    constructor(canvas, extent) {
        this.canvas = canvas;
        this.extent = extent;
        this.cellSize = canvas.width / extent;
        this.context = canvas.getContext('2d');
        this.initGame();
        this.gameOver = false;
        setInterval(x => {
            this.loop()
        }, 350);
    }

    drawLine(x1, y1, x2, y2) {
        this.context.beginPath();
        this.context.moveTo(x1, y1);
        this.context.lineTo(x2, y2);
        this.context.stroke();

    }

    drawGrid() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        for (let i = 1; i <= this.extent; i++) {
            this.drawLine(i * this.cellSize, 0, i * this.cellSize, this.canvas.height);
            this.drawLine(0, i * this.cellSize, this.canvas.width, i * this.cellSize);
        }
    }

    newApple() {
        this.apple.create(this.extent);
    }

    getAppleX() {
        return this.apple.getFoodX();
    }
    getAppleY() {
        return this.apple.getFoodY();
    }
    getExtent() {
        return this.extent;
    }
    genFood() {
        this.apple.create(extent);
    }

    loop() {
        if(this.gameOver === false) {
            this.snake.update();
        }
        if(this.gameOver === false) {
            this.drawGrid();
            this.snake.draw();
            this.apple.draw();
        }

    }
    draw() {
        this.drawGrid();
        this.snake.draw();
        this.apple.draw();

    }

    initGame() {
        this.snake = new Snake([{x:7,y:8},{x:8,y:8},{x:9,y:8,}],this.cellSize, this.context, this.extent, 'ArrowRight');
        this.apple = new Apple(5,10,this.cellSize,this.context);
    }
    gameEnds() {
        this.gameOver = true;
    }
}

class Apple{
    constructor(x,y,cellSize,context) {
        this.x = x;
        this.y = y;
        this.cellSize = cellSize;
        this.context = context;
        this.newApple = {x:0,y:0};
    }

    draw() {
        this.context.fillStyle = 'green';
        this.context.fillRect(this.x * this.cellSize, this.y * this.cellSize, this.cellSize, this.cellSize);
    }

    create(extent) {
        this.newApple = {x: Math.floor(Math.random() * extent),y: Math.floor(Math.random() * extent)};
        this.x = this.newApple.x;
        this.y = this.newApple.y;

        for(let i = 0; i < this.snake.snakeArray.length; i++) {
            if (this.newApple.x == this.snake.snakeArray[i].x && this.newApple.y == this.snake.snakeArray[i].y) {
                this.newApple = {x: Math.floor(Math.random() * extent),y: Math.floor(Math.random() * extent)};
                this.x = this.newApple.x;
                this.y = this.newApple.y;
            }
        }
    }
    getFoodX() {
        return this.x;
    }
    getFoodY(){
        return this.y;
    }
}

class Snake {
    constructor(snakeArray, cellSize,context,extent,pressedKey) {
        this.cellSize = cellSize;
        this.context = context;
        this.extent = extent;
        this.pressedKey = pressedKey;
        this.snakeArray = snakeArray;
        //this.snakeArray.push(startingPos);
        this.snakeHead = {x: this.snakeArray[this.snakeArray.length-1].x, y:this.snakeArray[this.snakeArray.length-1].y};
        document.addEventListener('keyup', event => {
            this.handleKeyUp(event);
        });
    }

    handleKeyUp(event) {
        if (event.code === 'ArrowUp' || event.code === 'ArrowDown' || event.code === 'ArrowLeft' || event.code === 'ArrowRight') {
            this.pressedKey = event.code;
        }
    }

    update() {
        let newSnakeHead = {x:0,y:0};
        if (this.pressedKey === 'ArrowUp') {
            newSnakeHead = {x: this.snakeHead.x, y: this.snakeHead.y-1};
        } else if (this.pressedKey === 'ArrowRight') {
            newSnakeHead = {x: this.snakeHead.x+1, y: this.snakeHead.y};
        } else if (this.pressedKey === 'ArrowDown') {
            newSnakeHead = {x: this.snakeHead.x, y: this.snakeHead.y+1};
        } else if (this.pressedKey === 'ArrowLeft') {
            newSnakeHead = {x: this.snakeHead.x-1, y: this.snakeHead.y};
        }
        if(newSnakeHead.x === this.game.getFoodX() && newSnakeHead.y === this.game.getFoodY()) {
            this.snakeArray.push(newSnakeHead);
            this.game.genFood();
        }
        else {
            this.snakeArray.shift();
            if(this.outOfBounds(newSnakeHead, this.extent) === true || this.snakeHit(newSnakeHead, this.extent) === true) {
                this.game.gameEnds();
            }
            else{
                this.snakeArray.push(newSnakeHead);
            }
            }
    }
    draw() {
        for(let i = 0; i< this.snakeArray.length-1; i++) {
            this.drawSquare(this.snakeArray[i].x, this.snakeArray[i].y, 'red');
        }
        this.drawSquare(this.snakeHead.x,this.snakeHead.y,'yellow');
    }

    outOfBounds(newSnakeHead,extent) {
        if(newSnakeHead.x > extent || newSnakeHead.x < 0 || newSnakeHead.y > extent || newSnakeHead.y < 0 ) {
            this.game.gameEnds();
            return true;
        }
    }

    snakeHit(newSnakeHead) {
            for(let i = 0; i< this.snakeArray.length; i++) {
                if (newSnakeHead.x == this.snakeArray[i].x && newSnakeHead.y == this.snakeArray[i].y) {
                    this.game.gameEnds();
                    return true;
                }
            }
    }

    drawSquare(x,y,color) {
        this.context.fillStyle = color;
        this.context.fillRect(x * this.cellSize, y * this.cellSize, this.cellSize, this.cellSize);
    }
}

const canvas = document.getElementById('myCanvas');
const game = new Game(canvas, '16');
</code>```

Any help is appreciated!

答:
You're trying to access the game object inside Snake class with this but it's not a part of Snake class. So I think, in your update() method inside Snake class, following statement is the culprit:-

```<code>if(newSnakeHead.x === this.game.getFoodX() && newSnakeHead.y === this.game.getFoodY()) {
            this.snakeArray.push(newSnakeHead);
            this.game.genFood();
        }
</code>```

You can create a reference to your game in Snake constructor like:-

```<code>constructor(snakeArray, cellSize,context,extent,pressedKey,game) {
        this.cellSize = cellSize;
        this.context = context;
        this.extent = extent;
        this.pressedKey = pressedKey;
        this.snakeArray = snakeArray;
        this.game = game;
        //this.snakeArray.push(startingPos);
        this.snakeHead = {x: this.snakeArray[this.snakeArray.length-1].x, y:this.snakeArray[this.snakeArray.length-1].y};
        document.addEventListener('keyup', event => {
            this.handleKeyUp(event);
        });
    }
</code>```

and in your Game class:-

```<code>initGame() {
        this.snake = new Snake([{x:7,y:8},{x:8,y:8},{x:9,y:8,}],this.cellSize, this.context, this.extent, 'ArrowRight',this);
        this.apple = new Apple(5,10,this.cellSize,this.context);
    }
</code>```

Pass additional this parameter. That will help you set the correct reference to the game property in your Snake class.

Body:
So I am trying to write a basic Snake Game and getting an undefined error although I don't see anything wrong with my code after reviewing it. I am getting the same error for this.apple.getFoodX when removing the if condition causing the error with getFood.

class Game {

    constructor(canvas, extent) {
        this.canvas = canvas;
        this.extent = extent;
        this.cellSize = canvas.width / extent;
        this.context = canvas.getContext('2d');
        this.initGame();
        this.gameOver = false;
        setInterval(x => {
            this.loop()
        }, 350);
    }

    drawLine(x1, y1, x2, y2) {
        this.context.beginPath();
        this.context.moveTo(x1, y1);
        this.context.lineTo(x2, y2);
        this.context.stroke();

    }

    drawGrid() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
        for (let i = 1; i <= this.extent; i++) {
            this.drawLine(i * this.cellSize, 0, i * this.cellSize, this.canvas.height);
            this.drawLine(0, i * this.cellSize, this.canvas.width, i * this.cellSize);
        }
    }

    newApple() {
        this.apple.create(this.extent);
    }

    getAppleX() {
        return this.apple.getFoodX();
    }
    getAppleY() {
        return this.apple.getFoodY();
    }
    getExtent() {
        return this.extent;
    }
    genFood() {
        this.apple.create(extent);
    }

    loop() {
        if(this.gameOver === false) {
            this.snake.update();
        }
        if(this.gameOver === false) {
            this.drawGrid();
            this.snake.draw();
            this.apple.draw();
        }

    }
    draw() {
        this.drawGrid();
        this.snake.draw();
        this.apple.draw();

    }

    initGame() {
        this.snake = new Snake([{x:7,y:8},{x:8,y:8},{x:9,y:8,}],this.cellSize, this.context, this.extent, 'ArrowRight');
        this.apple = new Apple(5,10,this.cellSize,this.context);
    }
    gameEnds() {
        this.gameOver = true;
    }
}

class Apple{
    constructor(x,y,cellSize,context) {
        this.x = x;
        this.y = y;
        this.cellSize = cellSize;
        this.context = context;
        this.newApple = {x:0,y:0};
    }

    draw() {
        this.context.fillStyle = 'green';
        this.context.fillRect(this.x * this.cellSize, this.y * this.cellSize, this.cellSize, this.cellSize);
    }

    create(extent) {
        this.newApple = {x: Math.floor(Math.random() * extent),y: Math.floor(Math.random() * extent)};
        this.x = this.newApple.x;
        this.y = this.newApple.y;

        for(let i = 0; i < this.snake.snakeArray.length; i++) {
            if (this.newApple.x == this.snake.snakeArray[i].x && this.newApple.y == this.snake.snakeArray[i].y) {
                this.newApple = {x: Math.floor(Math.random() * extent),y: Math.floor(Math.random() * extent)};
                this.x = this.newApple.x;
                this.y = this.newApple.y;
            }
        }
    }
    getFoodX() {
        return this.x;
    }
    getFoodY(){
        return this.y;
    }
}

class Snake {
    constructor(snakeArray, cellSize,context,extent,pressedKey) {
        this.cellSize = cellSize;
        this.context = context;
        this.extent = extent;
        this.pressedKey = pressedKey;
        this.snakeArray = snakeArray;
        //this.snakeArray.push(startingPos);
        this.snakeHead = {x: this.snakeArray[this.snakeArray.length-1].x, y:this.snakeArray[this.snakeArray.length-1].y};
        document.addEventListener('keyup', event => {
            this.handleKeyUp(event);
        });
    }

    handleKeyUp(event) {
        if (event.code === 'ArrowUp' || event.code === 'ArrowDown' || event.code === 'ArrowLeft' || event.code === 'ArrowRight') {
            this.pressedKey = event.code;
        }
    }

    update() {
        let newSnakeHead = {x:0,y:0};
        if (this.pressedKey === 'ArrowUp') {
            newSnakeHead = {x: this.snakeHead.x, y: this.snakeHead.y-1};
        } else if (this.pressedKey === 'ArrowRight') {
            newSnakeHead = {x: this.snakeHead.x+1, y: this.snakeHead.y};
        } else if (this.pressedKey === 'ArrowDown') {
            newSnakeHead = {x: this.snakeHead.x, y: this.snakeHead.y+1};
        } else if (this.pressedKey === 'ArrowLeft') {
            newSnakeHead = {x: this.snakeHead.x-1, y: this.snakeHead.y};
        }
        if(newSnakeHead.x === this.game.getFoodX() && newSnakeHead.y === this.game.getFoodY()) {
            this.snakeArray.push(newSnakeHead);
            this.game.genFood();
        }
        else {
            this.snakeArray.shift();
            if(this.outOfBounds(newSnakeHead, this.extent) === true || this.snakeHit(newSnakeHead, this.extent) === true) {
                this.game.gameEnds();
            }
            else{
                this.snakeArray.push(newSnakeHead);
            }
            }
    }
    draw() {
        for(let i = 0; i< this.snakeArray.length-1; i++) {
            this.drawSquare(this.snakeArray[i].x, this.snakeArray[i].y, 'red');
        }
        this.drawSquare(this.snakeHead.x,this.snakeHead.y,'yellow');
    }

    outOfBounds(newSnakeHead,extent) {
        if(newSnakeHead.x > extent || newSnakeHead.x < 0 || newSnakeHead.y > extent || newSnakeHead.y < 0 ) {
            this.game.gameEnds();
            return true;
        }
    }

    snakeHit(newSnakeHead) {
            for(let i = 0; i< this.snakeArray.length; i++) {
                if (newSnakeHead.x == this.snakeArray[i].x && newSnakeHead.y == this.snakeArray[i].y) {
                    this.game.gameEnds();
                    return true;
                }
            }
    }

    drawSquare(x,y,color) {
        this.context.fillStyle = color;
        this.context.fillRect(x * this.cellSize, y * this.cellSize, this.cellSize, this.cellSize);
    }
}

const canvas = document.getElementById('myCanvas');
const game = new Game(canvas, '16');

Any help is appreciated!

Body:
You're trying to access the game object inside Snake class with this but it's not a part of Snake class. So I think, in your update() method inside Snake class, following statement is the culprit:-

if(newSnakeHead.x === this.game.getFoodX() && newSnakeHead.y === this.game.getFoodY()) {
            this.snakeArray.push(newSnakeHead);
            this.game.genFood();
        }

You can create a reference to your game in Snake constructor like:-

constructor(snakeArray, cellSize,context,extent,pressedKey,game) {
        this.cellSize = cellSize;
        this.context = context;
        this.extent = extent;
        this.pressedKey = pressedKey;
        this.snakeArray = snakeArray;
        this.game = game;
        //this.snakeArray.push(startingPos);
        this.snakeHead = {x: this.snakeArray[this.snakeArray.length-1].x, y:this.snakeArray[this.snakeArray.length-1].y};
        document.addEventListener('keyup', event => {
            this.handleKeyUp(event);
        });
    }

and in your Game class:-

initGame() {
        this.snake = new Snake([{x:7,y:8},{x:8,y:8},{x:9,y:8,}],this.cellSize, this.context, this.extent, 'ArrowRight',this);
        this.apple = new Apple(5,10,this.cellSize,this.context);
    }

Pass additional this parameter. That will help you set the correct reference to the game property in your Snake class.


问:
Disabling SSL Certificate Validation in Spring RestTemplate
I am having two Spring-based web apps A and B, on two different machines.

I want to make an HTTPS call from web app A to web app B, however, I am using a self-signed certificate in Machine B. So my HTTPS request fails.

How can I disable HTTPS certificate validation when using RestTemplate in Spring? I want to disable validation because both web app A and B are within the internal network, but data transfer has to happen over HTTPS

答:
If you are using rest template, you can use this piece of code</p>

```<code>    fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
        val timeout = envTimeout.toInt()
        val config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build()

        val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }

        val sslContext: SSLContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build()

        val csf = SSLConnectionSocketFactory(sslContext)

        val client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(config)
            .setSSLSocketFactory(csf)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build()
        return HttpComponentsClientHttpRequestFactory(client)
    }

    @Bean
    fun getRestTemplate(): RestTemplate {
        return RestTemplate(getClientHttpRequestFactory())
    }
</code>```

Body:
If you are using rest template, you can use this piece of code

    fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
        val timeout = envTimeout.toInt()
        val config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build()

        val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }

        val sslContext: SSLContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build()

        val csf = SSLConnectionSocketFactory(sslContext)

        val client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(config)
            .setSSLSocketFactory(csf)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build()
        return HttpComponentsClientHttpRequestFactory(client)
    }

    @Bean
    fun getRestTemplate(): RestTemplate {
        return RestTemplate(getClientHttpRequestFactory())
    }


问:
Ping between aws and gcp
I have created a Site to Site VPN connection between VPC of Google cloud Platform and AWS in North Virginia region for both the VPCs. But the problem is I have been getting a very high ping and low bandwidth while communicating between the instances. Can any one tell me the reason for this?
image showing the ping data

The ping is very high considering they are in a very close region. Please help.

答:
Multiple reason behind the cause :
1) verify gcp network performance by gcping
2) verify the tcp size and rtt for bandwidth
3) verify with iperf or tcpdump for throughput

https://cloud.google.com/community/tutorials/network-throughput

Title: Ping between aws and gcp


问:
Why can't I use a DataTrigger to set TextBox.IsEnabled = True?
In my application, I have a TextBox that I want to enable/disable based on an enum in my datacontext. The enum has three values (Anyone, Me, Someone) and I want to enable the Textbox when the value "Someone" is set. I am able to hack a solution by setting the value in reverse (see below). However, can someone please explain why the first solution didn't work?

This does not work...

```<code><TextBox Text="{Binding ModifiedUser, UpdateSourceTrigger=PropertyChanged}"
         IsEnabled="False">
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ModifiedBy}"
                             Value="Someone">
                    <Setter Property="IsEnabled"
                            Value="True" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
</code>```

Strangely, this code does work.

```<code><TextBox Text="{Binding ModifiedUser, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ModifiedBy}"
                             Value="Anyone">
                    <Setter Property="IsEnabled"
                            Value="False" />
                </DataTrigger>
                <DataTrigger Binding="{Binding ModifiedBy}"
                             Value="Me">
                    <Setter Property="IsEnabled"
                            Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
</code>```

答:
you have to set the initial isEnabled in your style too. otherwise your "local" IsEnabled=false will always win!

change your style and it will work.

```<code><TextBox Text="{Binding ModifiedUser, UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding ModifiedBy}"
                         Value="Someone">
                <Setter Property="IsEnabled"
                        Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>
</code>```

Body:
In my application, I have a TextBox that I want to enable/disable based on an enum in my datacontext. The enum has three values (Anyone, Me, Someone) and I want to enable the Textbox when the value "Someone" is set. I am able to hack a solution by setting the value in reverse (see below). However, can someone please explain why the first solution didn't work?

This does not work...

<TextBox Text="{Binding ModifiedUser, UpdateSourceTrigger=PropertyChanged}"
         IsEnabled="False">
    <TextBox.Style>

        </Style>
    </TextBox.Style>
</TextBox>

Strangely, this code does work.

<TextBox Text="{Binding ModifiedUser, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.Style>

        </Style>
    </TextBox.Style>
</TextBox>

Body:
you have to set the initial isEnabled in your style too. otherwise your "local" IsEnabled=false will always win!

change your style and it will work.

<TextBox Text="{Binding ModifiedUser, UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="IsEnabled" Value="False" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding ModifiedBy}"
                         Value="Someone">
                <Setter Property="IsEnabled"
                        Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>