问:
Issue with camera ofset and collisions in pygame
I'm currently trying to code a simple platform game on pygame but I have issues with the collisions when I try to add the camera functionality to the game.

Here is my code:

To don't make the question too large I'll cut the parts of the code that include the movement, the collision and the drawing.

Index.py

removed the init and setup_tiles functions.

```<code>import pygame
from settings import *
from tiles import *
from player import *
from camera import *

pygame.init()

class Window:

  def game_loop(self):

    while not self.crashed:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.crashed = True

        self.movement()

        self.window.blit(self.background, (0, 0))
        self.all_sprites.clear(self.window, self.background)
        self.player.update(self.all_sprites)
        self.camera.update(self.player)
        self.player.draw(self.window)
        # self.all_sprites.draw(self.window)
        for sprite in self.all_sprites:
            self.window.blit(sprite.image, self.camera.apply(sprite))

        pygame.display.flip()

        self.clock.tick(60)

    quit()
    pygame.quit()

def movement(self):
    keys = pygame.key.get_pressed()

    if keys[pygame.K_w]:
        self.player.velocity_y = -3
        self.player.rect.y += self.player.velocity_y
        for sprite in self.all_sprites:
            if self.player.collide_Y(sprite):
                self.player.rect.y = self.player.rect.y - self.player.velocity_y

    elif keys[pygame.K_s]:
        self.player.velocity_y = 3
        self.player.rect.y += self.player.velocity_y
        for sprite in self.all_sprites:
            if self.player.collide_Y(sprite):
                self.player.rect.y = self.player.rect.y - self.player.velocity_y

    if keys[pygame.K_a]:
        self.player.velocity_x = -3
        self.player.rect.x += self.player.velocity_x
        for sprite in self.all_sprites:
            if self.player.collide_X(sprite):
                self.player.rect.x = self.player.rect.x - self.player.velocity_x

    elif keys[pygame.K_d]:
        self.player.velocity_x = 3
        self.player.rect.x += self.player.velocity_x
        for sprite in self.all_sprites:
            if self.player.collide_X(sprite):
                self.player.rect.x = self.player.rect.x - self.player.velocity_x

window = Window()

window.game_loop()
</code>```

Tiles.py

```<code>import pygame
from settings import *

class Tiles(pygame.sprite.Sprite):

    def __init__(self, file, pos):
        pygame.sprite.Sprite.__init__(self)
        self.bitmap = pygame.image.load(file)
        self.bitmap = pygame.transform.scale(self.bitmap, (TILE_SIZE, TILE_SIZE))
        self.image = pygame.Surface((TILE_SIZE, TILE_SIZE), pygame.HWSURFACE | pygame.SRCALPHA)
        self.image.blit(self.bitmap, (0, 0))
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = pos
</code>```

Player.py

removed the init function

```<code>import pygame
from settings import *

class Player(pygame.sprite.Sprite):

def draw(self, window):
    window.blit(self.image, (self.rect.x, self.rect.y))

def collide_X(self, sprite):
    if (self.rect.x + self.width >= sprite.rect.x >= self.rect.x and self.rect.y + self.height >= sprite.rect.y + TILE_SIZE >=
        self.rect.y) or (self.rect.x + self.width >= sprite.rect.x + TILE_SIZE >= self.rect.x
        and self.rect.y + self.height >= sprite.rect.y + TILE_SIZE >= self.rect.y) or (self.rect.x + self.width >= sprite.rect.x >= self.rect.x and
        sprite.rect.y + TILE_SIZE >= self.rect.y + self.height >= sprite.rect.y >= self.rect.y):
        print 'True'
        return True
    else:
        return False

def collide_Y(self, sprite):
    if (self.rect.y + self.height + self.velocity_y >= sprite.rect.y >= self.rect.y and self.rect.x + self.width >=
        sprite.rect.x >= self.rect.x) or (self.rect.y + self.height >= sprite.rect.y + TILE_SIZE >= self.rect.y + self.velocity_y
        and self.rect.x + self.width >= sprite.rect.x >= self.rect.x):
        return True
    else:
        return False
</code>```

Camera.py

```<code>import pygame
from settings import *

class Camera:
    def __init__(self, width, height):
        self.camera = pygame.Rect(0, 0, width, height)
        self.width = width
        self.height = height

    def apply(self, target):
        return target.rect.move(self.camera.topleft)

    def update(self, target):
        x = - target.rect.x + int(WIDTH/2)
        y = - target.rect.y + int(HEIGHT/2)
        self.camera = pygame.Rect(x, y, self.width, self.height)
</code>```

Settings.py

```<code>WIDTH = 800
HEIGHT = 600

TILE_SIZE = 32

LEVEL_1 = [
    'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'TTTTTTTTTB                    V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                                                     V',
    'B                                                     V',
    'B                                                     V',
    'B              VTTTTTTTTTTTTTTTTTTTTTTTTB             V',
    'B                             V                       V',
    'B                             V                       V',
    'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT'
]

LEVEL_1_WIDTH = len(LEVEL_1[0])*TILE_SIZE
LEVEL_1_HEIGHT = len(LEVEL_1)*TILE_SIZE
</code>```

Collision without Camera

This is the collision without the camera, as you can see it works fine.

Collision with Camera

When I add the camera functionality this is what happens

If you want to test it remove the # from the game_loop and comment the drawing using the camera apply.

```<code>    # self.all_sprites.draw(self.window)
    for sprite in self.all_sprites:
        self.window.blit(sprite.image, self.camera.apply(sprite))
</code>```

I'm using python 2.7 in a Window 10 x64 machine.

答:
You simply are not applying the camera transform to your player instance: It is drawn in absolute game coordinates, while everything else is drawn in camera coordinates.

The collision checks, on the other hand, are always done in game absolute coordinates.

You have  to apply the camera to your player, before drawing it as well. As your code is, t looks like you simply have to add the player to the all_sprites group, and remove the Player.draw method altogether. And then, if you wish, correct something on the Camera.update method so that when at the border of the map, the player is not always centered on the screen.

Body:
I'm currently trying to code a simple platform game on pygame but I have issues with the collisions when I try to add the camera functionality to the game.

Here is my code:

To don't make the question too large I'll cut the parts of the code that include the movement, the collision and the drawing.

Index.py

removed the init and setup_tiles functions.

import pygame
from settings import *
from tiles import *
from player import *
from camera import *

pygame.init()

class Window:

  def game_loop(self):

    while not self.crashed:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.crashed = True

        self.movement()

        self.window.blit(self.background, (0, 0))
        self.all_sprites.clear(self.window, self.background)
        self.player.update(self.all_sprites)
        self.camera.update(self.player)
        self.player.draw(self.window)
        # self.all_sprites.draw(self.window)
        for sprite in self.all_sprites:
            self.window.blit(sprite.image, self.camera.apply(sprite))

        pygame.display.flip()

        self.clock.tick(60)

    quit()
    pygame.quit()

def movement(self):
    keys = pygame.key.get_pressed()

    if keys[pygame.K_w]:
        self.player.velocity_y = -3
        self.player.rect.y += self.player.velocity_y
        for sprite in self.all_sprites:
            if self.player.collide_Y(sprite):
                self.player.rect.y = self.player.rect.y - self.player.velocity_y

    elif keys[pygame.K_s]:
        self.player.velocity_y = 3
        self.player.rect.y += self.player.velocity_y
        for sprite in self.all_sprites:
            if self.player.collide_Y(sprite):
                self.player.rect.y = self.player.rect.y - self.player.velocity_y

    if keys[pygame.K_a]:
        self.player.velocity_x = -3
        self.player.rect.x += self.player.velocity_x
        for sprite in self.all_sprites:
            if self.player.collide_X(sprite):
                self.player.rect.x = self.player.rect.x - self.player.velocity_x

    elif keys[pygame.K_d]:
        self.player.velocity_x = 3
        self.player.rect.x += self.player.velocity_x
        for sprite in self.all_sprites:
            if self.player.collide_X(sprite):
                self.player.rect.x = self.player.rect.x - self.player.velocity_x

window = Window()

window.game_loop()

Tiles.py

import pygame
from settings import *

class Tiles(pygame.sprite.Sprite):

    def __init__(self, file, pos):
        pygame.sprite.Sprite.__init__(self)
        self.bitmap = pygame.image.load(file)
        self.bitmap = pygame.transform.scale(self.bitmap, (TILE_SIZE, TILE_SIZE))
        self.image = pygame.Surface((TILE_SIZE, TILE_SIZE), pygame.HWSURFACE | pygame.SRCALPHA)
        self.image.blit(self.bitmap, (0, 0))
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = pos

Player.py

removed the init function

import pygame
from settings import *

class Player(pygame.sprite.Sprite):

def draw(self, window):
    window.blit(self.image, (self.rect.x, self.rect.y))

def collide_X(self, sprite):
    if (self.rect.x + self.width >= sprite.rect.x >= self.rect.x and self.rect.y + self.height >= sprite.rect.y + TILE_SIZE >=
        self.rect.y) or (self.rect.x + self.width >= sprite.rect.x + TILE_SIZE >= self.rect.x
        and self.rect.y + self.height >= sprite.rect.y + TILE_SIZE >= self.rect.y) or (self.rect.x + self.width >= sprite.rect.x >= self.rect.x and
        sprite.rect.y + TILE_SIZE >= self.rect.y + self.height >= sprite.rect.y >= self.rect.y):
        print 'True'
        return True
    else:
        return False

def collide_Y(self, sprite):
    if (self.rect.y + self.height + self.velocity_y >= sprite.rect.y >= self.rect.y and self.rect.x + self.width >=
        sprite.rect.x >= self.rect.x) or (self.rect.y + self.height >= sprite.rect.y + TILE_SIZE >= self.rect.y + self.velocity_y
        and self.rect.x + self.width >= sprite.rect.x >= self.rect.x):
        return True
    else:
        return False

Camera.py

import pygame
from settings import *

class Camera:
    def __init__(self, width, height):
        self.camera = pygame.Rect(0, 0, width, height)
        self.width = width
        self.height = height

    def apply(self, target):
        return target.rect.move(self.camera.topleft)

    def update(self, target):
        x = - target.rect.x + int(WIDTH/2)
        y = - target.rect.y + int(HEIGHT/2)
        self.camera = pygame.Rect(x, y, self.width, self.height)

Settings.py

WIDTH = 800
HEIGHT = 600

TILE_SIZE = 32

LEVEL_1 = [
    'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'TTTTTTTTTB                    V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                             V                       V',
    'B                                                     V',
    'B                                                     V',
    'B                                                     V',
    'B              VTTTTTTTTTTTTTTTTTTTTTTTTB             V',
    'B                             V                       V',
    'B                             V                       V',
    'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT'
]

LEVEL_1_WIDTH = len(LEVEL_1[0])*TILE_SIZE
LEVEL_1_HEIGHT = len(LEVEL_1)*TILE_SIZE

Collision without Camera

This is the collision without the camera, as you can see it works fine.

Collision with Camera

When I add the camera functionality this is what happens

If you want to test it remove the # from the game_loop and comment the drawing using the camera apply.

    # self.all_sprites.draw(self.window)
    for sprite in self.all_sprites:
        self.window.blit(sprite.image, self.camera.apply(sprite))

I'm using python 2.7 in a Window 10 x64 machine.


来源: stackexchange

问:
How to construct a c++ fstream from a POSIX file descriptor?
I'm basically looking for a C++ version of fdopen().  I did a bit of research on this and it is one of those things that seems like it should be easy, but turns out to be very complicated.  Am I missing something in this belief (i.e. it really is easy)?  If not, is there a good library out there somewhere to handle this?

EDIT: Moved my example solution to a separate answer.

答: It actually is quite easy. Nicolai M. Josuttis has released fdstream in conjunction with his book The C++ Standard Library - A Tutorial and Reference. You can find the 184 line implementation here.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Ajax success function location.reload for individual php file
I have a feed page on my website (very similar to facebook) that enables me to like and comment on posts. I'm using ajax to update the posts, however, after a like, rather than each individual post reloading, the whole feed does (not the whole page itself, it just returns to the top of the feed).

I believe this is because each post is using a file named feedLikes.php that are all being reloaded rather than just that one specific post. I'm not sure how to only make that one post reload. below is my code.

From feed.php below, you can see i am searching for all the posts within the database. Each one of these posts is given a feedID like so:

```<code>$findShouts = $pdo->prepare('SELECT * FROM feed WHERE name IN (SELECT scoutingUsername FROM scout WHERE scoutedUsername =? OR scoutingUsername =?)  ORDER BY timestamp DESC');

//execute query and variables
$findShouts->execute([$username, $username]);

if ($findShouts->rowCount() > 0)
    {

//get the shouts for each scout
while($row = $findShouts->fetch(PDO::FETCH_ASSOC)){

$shoutID[]              = $row['id'];
$shoutUsername[]        = $row["username"];
$shoutName[]            = $row["name"];
$shoutText[]            = $row["text"];
$shoutTimestamp[]       = $row["timestamp"];
}

$shoutCount = count($shoutUsername);

for($indexShout=0; $indexShout < $shoutCount; $indexShout++) {

print'
<div class=feedNewShout>

<div class=shoutInformation>

<div class=shoutName>
<p>'. $shoutName[$indexShout] .'</p>
</div>

<div class=shoutTimestamp>
<p>'. timeElapsed("$shoutTimestamp[$indexShout]", 2) .'</p>
</div>

<div class=shoutText>
<p>'. $shoutText[$indexShout] .'</p>
</div>

<input type="hidden" name="feedID" class="feedID" value="'. $shoutID[$indexShout] .'">

<div class=likesAndComments>

<div class=likesAjax data-id="'.$shoutID[$indexShout] .'">
</div>

<div class=commentsAjax data-id="'.$shoutID[$indexShout] .'">
</div>

<div class=deleteShoutAjax data-id="'.$shoutID[$indexShout] .'">
</div>

</div>
</div>
</div>';

}
unset($shoutID);
unset($shoutUsername);
unset($shoutName);
unset($shoutText);
unset($shoutTimestamp);
}
</code>```

From this i use a jquery Ajax call in feedLikesAjax.js to find each individual feedID needed:

```<code>$(document).ready(function()
{
$(".likesAjax").each(function() {
    var feedID = $(this).attr("data-id");

 $.ajax({
  url: "feedLikes.php",
  cache: false,
    type: "POST",
     data: {feedID: feedID},
     dataType: "html",
  success: function(html){
    $(".likesAjax[data-id='"+ feedID +"']").empty();
    $(".likesAjax[data-id='"+ feedID +"']").append(html);
  }
});
});

});
</code>```

I use this information and pass it to feedLikes.php:

```<code>if (isset($_POST['feedID']))

    {

 $feedID = ($_POST['feedID']);

$findHasUserLiked = $pdo->prepare('SELECT username FROM feedLikes WHERE feedID =? and username=?');

//execute query and variables
$findHasUserLiked->execute([$feedID, $username]);

if ($findHasUserLiked->rowCount() > 0)
    {

$hasUserLiked = $findHasUserLiked->fetchColumn();

echo<<<_END

<form action="feedLikes.php" id="unlikePostForm$feedID" method="post">

<button type="submit" class="unLikeButton"></button>

<input type="hidden" name="feedIDForUnlike" class="feedIDForUnlike$feedID" value="$feedID">

</form>

_END;

?>
<script type="text/javascript">
$(document).ready(function()
{

 $('#unlikePostForm<?php echo $feedID ?>').on('submit', function (e) {
    e.preventDefault();

var feedIDUnlike = $(".feedIDForUnlike<?php echo $feedID ?>").val();

     $.ajax({
      url: "feedLikesClicked.php",
      cache: false,
        type: "POST",
         data: {feedIDUnlike: feedIDUnlike},
         dataType: "html",
      success: function(html){
    location.reload();
      }
    });
    });
});

</script>

<?php

}

 else

 {

echo<<<_END

 <form action="feedLikes.php" id="likePostForm$feedID" method="post">

<button type="submit" class="likeButton"></button>

<input type="hidden" name="feedIDForLike" class="feedIDForLike$feedID" value="$feedID">

</form>

_END;

?>
<script type="text/javascript">
$(document).ready(function()
{

 $('#likePostForm<?php echo $feedID ?>').on('submit', function (e) {
    e.preventDefault();

var feedIDLike = $(".feedIDForLike<?php echo $feedID ?>").val();

     $.ajax({
      url: "feedLikesClicked.php",
      cache: false,
        type: "POST",
         data: {feedIDLike: feedIDLike},
         dataType: "html",
      success: function(html){
    location.reload();
      }
    });
    });
});

</script>

<?php

 }

 $likesNumber = $pdo->prepare('SELECT count(*) FROM feedLikes WHERE feedID =?');

//execute query and variables
$likesNumber->execute([$feedID]);

$numberOfLikes = $likesNumber->fetchColumn();

print'
<div class=numberOfLikes data-id="'.$feedID .'">
<p>'. $numberOfLikes .'</p>
</div>';

}

?>
</code>```

Like i said it all works perfectly apart from the reloading. Now i know the location.reload that is used on success is actually reloading every feedLikes.php for every post. But i'm really stuck on how to just reload the current feedLikes.php post that is needed for that specific post. I thought this would be really simple, and it maybe, but i cant find it anywhere.

Really grateful for any help. Thank you

答:
There are lots of ways to do this. To achieve what you are actually asking you need to modify your jQuery success function to target only the div element for the post you are interested in. Either by adding a unique ID to the HTML, or using a selector based on the class and data-id attributes to identify that specific post.

Then yout PHP needs to only return the HTML which you want to modify and you have your jQuery success function insert that into the div for the relevant post.

Having said that, for what you are trying to do is there really any need to reload the post? You could have your PHP script just return the new number of likes and whether or not current user has liked the post and then update those values in your success call.

You could optimise your code a lot, the feedLikesAjax.js script is calling feedLikes.php once the page is loaded, creating a new ajax request for each post. You could combine the code from feedLikes.php into feed.php and have the server output the page with all the data immediately, and get rid of feedLikesAjax.js altogether. You could replace the likes and unlikes forms with a single button for each post and right now you are setting an event handler for each form individually, if you give them all a common class you can just use a single event handler.

EDIT

To answer your comment:

You don't need another query in your while statement. You can expand your first query using a left join to have it also include data from the feedLikes table in the returned results or you can use another subquery to your original query to add another column to your returned results. Something along the lines of this should give you a userLiked row with a value of 1 or 0 for liked/not liked. You might have to edit it a bit to get it working for you, I'm not an SQL guru by any means.

```<code>SELECT *, (SELECT COUNT(L.username) FROM feedLikes L WHERE L.feedID = F.id AND L.username = F.username) AS userLiked
FROM feed F
WHERE name IN (SELECT scoutingUsername FROM scout WHERE scoutedUsername =? OR scoutingUsername =?)
ORDER BY timestamp DESC
</code>```

Body:
I have a feed page on my website (very similar to facebook) that enables me to like and comment on posts. I'm using ajax to update the posts, however, after a like, rather than each individual post reloading, the whole feed does (not the whole page itself, it just returns to the top of the feed).

I believe this is because each post is using a file named feedLikes.php that are all being reloaded rather than just that one specific post. I'm not sure how to only make that one post reload. below is my code.

From feed.php below, you can see i am searching for all the posts within the database. Each one of these posts is given a feedID like so:

$findShouts = $pdo->prepare('SELECT * FROM feed WHERE name IN (SELECT scoutingUsername FROM scout WHERE scoutedUsername =? OR scoutingUsername =?)  ORDER BY timestamp DESC');

//execute query and variables
$findShouts->execute([$username, $username]);

if ($findShouts->rowCount() > 0)
    {

//get the shouts for each scout
while($row = $findShouts->fetch(PDO::FETCH_ASSOC)){

$shoutID[]              = $row['id'];
$shoutUsername[]        = $row["username"];
$shoutName[]            = $row["name"];
$shoutText[]            = $row["text"];
$shoutTimestamp[]       = $row["timestamp"];
}

$shoutCount = count($shoutUsername);

for($indexShout=0; $indexShout < $shoutCount; $indexShout++) {

print'

'. $shoutName[$indexShout] .'

'. timeElapsed("$shoutTimestamp[$indexShout]", 2) .'

'. $shoutText[$indexShout] .'

<input type="hidden" name="feedID" class="feedID" value="'. $shoutID[$indexShout] .'">

';

}
unset($shoutID);
unset($shoutUsername);
unset($shoutName);
unset($shoutText);
unset($shoutTimestamp);
}

From this i use a jquery Ajax call in feedLikesAjax.js to find each individual feedID needed:

$(document).ready(function()
{
$(".likesAjax").each(function() {
    var feedID = $(this).attr("data-id");

 $.ajax({
  url: "feedLikes.php",
  cache: false,
    type: "POST",
     data: {feedID: feedID},
     dataType: "html",
  success: function(html){
    $(".likesAjax[data-id='"+ feedID +"']").empty();
    $(".likesAjax[data-id='"+ feedID +"']").append(html);
  }
});
});

});

I use this information and pass it to feedLikes.php:

if (isset($_POST['feedID']))

    {

 $feedID = ($_POST['feedID']);

$findHasUserLiked = $pdo->prepare('SELECT username FROM feedLikes WHERE feedID =? and username=?');

//execute query and variables
$findHasUserLiked->execute([$feedID, $username]);

if ($findHasUserLiked->rowCount() > 0)
    {

$hasUserLiked = $findHasUserLiked->fetchColumn();

echo<<<_END

<form action="feedLikes.php" id="unlikePostForm$feedID" method="post">

<button type="submit" class="unLikeButton"></button>

<input type="hidden" name="feedIDForUnlike" class="feedIDForUnlike$feedID" value="$feedID">

</form>

_END;

?>

<?php

}

 else

 {

echo<<<_END

 <form action="feedLikes.php" id="likePostForm$feedID" method="post">

<button type="submit" class="likeButton"></button>

<input type="hidden" name="feedIDForLike" class="feedIDForLike$feedID" value="$feedID">

</form>

_END;

?>

<?php

 }

 $likesNumber = $pdo->prepare('SELECT count(*) FROM feedLikes WHERE feedID =?');

//execute query and variables
$likesNumber->execute([$feedID]);

$numberOfLikes = $likesNumber->fetchColumn();

print'

'. $numberOfLikes .'

';

}

?>

Like i said it all works perfectly apart from the reloading. Now i know the location.reload that is used on success is actually reloading every feedLikes.php for every post. But i'm really stuck on how to just reload the current feedLikes.php post that is needed for that specific post. I thought this would be really simple, and it maybe, but i cant find it anywhere.

Really grateful for any help. Thank you

Body:
There are lots of ways to do this. To achieve what you are actually asking you need to modify your jQuery success function to target only the div element for the post you are interested in. Either by adding a unique ID to the HTML, or using a selector based on the class and data-id attributes to identify that specific post.

Then yout PHP needs to only return the HTML which you want to modify and you have your jQuery success function insert that into the div for the relevant post.

Having said that, for what you are trying to do is there really any need to reload the post? You could have your PHP script just return the new number of likes and whether or not current user has liked the post and then update those values in your success call.

You could optimise your code a lot, the feedLikesAjax.js script is calling feedLikes.php once the page is loaded, creating a new ajax request for each post. You could combine the code from feedLikes.php into feed.php and have the server output the page with all the data immediately, and get rid of feedLikesAjax.js altogether. You could replace the likes and unlikes forms with a single button for each post and right now you are setting an event handler for each form individually, if you give them all a common class you can just use a single event handler.

EDIT

To answer your comment:

You don't need another query in your while statement. You can expand your first query using a left join to have it also include data from the feedLikes table in the returned results or you can use another subquery to your original query to add another column to your returned results. Something along the lines of this should give you a userLiked row with a value of 1 or 0 for liked/not liked. You might have to edit it a bit to get it working for you, I'm not an SQL guru by any means.

SELECT *, (SELECT COUNT(L.username) FROM feedLikes L WHERE L.feedID = F.id AND L.username = F.username) AS userLiked
FROM feed F
WHERE name IN (SELECT scoutingUsername FROM scout WHERE scoutedUsername =? OR scoutingUsername =?)
ORDER BY timestamp DESC


问:
Zip subfolders using ZipOutputStream
ZipOutputStream only zips files in a folder. I want to zip subfolders also. How can I achieve this?

答:
You have to recursively explore your directory in order to add all files in the zip.

See this small helper if you wish:

```<code> using ICSharpCode.SharpZipLib.Zip;
    using ICSharpCode.SharpZipLib.Checksums;
    using System.IO;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using System.Text.RegularExpressions;

   namespace Zip
{
    /// <summary>
    /// Uses Sharpziplib so as to create a non flat zip archive
    /// </summary>
    public abstract class ZipManager
    {
        /// <summary>
        /// will zip directory .\toto as .\toto.zip
        /// </summary>
        /// <param name="stDirToZip"></param>
        /// <returns></returns>
        public static string CreateZip(string stDirToZip)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(stDirToZip);
                string stZipPath = di.Parent.FullName + "\\" + di.Name + ".zip";

                CreateZip(stZipPath, stDirToZip);

                return stZipPath;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Main method
        /// </summary>
        /// <param name="stZipPath">path of the archive wanted</param>
        /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param>
        public static void CreateZip(string stZipPath, string stDirToZip)
        {
            try
            {
                //Sanitize inputs
                stDirToZip = Path.GetFullPath(stDirToZip);
                stZipPath = Path.GetFullPath(stZipPath);

                Console.WriteLine("Zip directory " + stDirToZip);

                //Recursively parse the directory to zip
                Stack<FileInfo> stackFiles = DirExplore(stDirToZip);

                ZipOutputStream zipOutput = null;

                if (File.Exists(stZipPath))
                    File.Delete(stZipPath);

                Crc32 crc = new Crc32();
                zipOutput = new ZipOutputStream(File.Create(stZipPath));
                zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression

                Console.WriteLine(stackFiles.Count + " files to zip.\n");

                int index = 0;
                foreach (FileInfo fi in stackFiles)
                {
                    ++index;
                    int percent = (int)((float)index / ((float)stackFiles.Count / 100));
                    if (percent % 1 == 0)
                    {
                        Console.CursorLeft = 0;
                        Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done.");
                    }
                    FileStream fs = File.OpenRead(fi.FullName);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    //Create the right arborescence within the archive
                    string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1);
                    ZipEntry entry = new ZipEntry(stFileName);

                    entry.DateTime = DateTime.Now;

                    // set Size and the crc, because the information
                    // about the size and crc should be stored in the header
                    // if it is not set it is automatically written in the footer.
                    // (in this case size == crc == -1 in the header)
                    // Some ZIP programs have problems with zip files that don't store
                    // the size and crc in the header.
                    entry.Size = fs.Length;
                    fs.Close();

                    crc.Reset();
                    crc.Update(buffer);

                    entry.Crc = crc.Value;

                    zipOutput.PutNextEntry(entry);

                    zipOutput.Write(buffer, 0, buffer.Length);
                }
                zipOutput.Finish();
                zipOutput.Close();
                zipOutput = null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static private Stack<FileInfo> DirExplore(string stSrcDirPath)
        {
            try
            {
                Stack<DirectoryInfo> stackDirs = new Stack<DirectoryInfo>();
                Stack<FileInfo> stackPaths = new Stack<FileInfo>();

                DirectoryInfo dd = new DirectoryInfo(Path.GetFullPath(stSrcDirPath));

                stackDirs.Push(dd);
                while (stackDirs.Count > 0)
                {
                    DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop();

                    try
                    {
                        //Process .\files
                        foreach (FileInfo fileInfo in currentDir.GetFiles())
                        {
                            stackPaths.Push(fileInfo);
                        }

                        //Process Subdirectories
                        foreach (DirectoryInfo diNext in currentDir.GetDirectories())
                            stackDirs.Push(diNext);
                    }
                    catch (Exception)
                    {//Might be a system directory
                    }
                }
                return stackPaths;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static char[] _stSchon = new char[] { '-', '\\', '|', '/' };
    }
}
</code>```

Title: Zip subfolders using ZipOutputStream

Body:
You have to recursively explore your directory in order to add all files in the zip.

See this small helper if you wish:

 using ICSharpCode.SharpZipLib.Zip;
    using ICSharpCode.SharpZipLib.Checksums;
    using System.IO;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using System.Text.RegularExpressions;

   namespace Zip
{
    /// <summary>
    /// Uses Sharpziplib so as to create a non flat zip archive
    /// </summary>
    public abstract class ZipManager
    {
        /// <summary>
        /// will zip directory .\toto as .\toto.zip
        /// </summary>
        /// <param name="stDirToZip"></param>
        /// <returns></returns>
        public static string CreateZip(string stDirToZip)
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(stDirToZip);
                string stZipPath = di.Parent.FullName + "\\" + di.Name + ".zip";

                CreateZip(stZipPath, stDirToZip);

                return stZipPath;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Main method
        /// </summary>
        /// <param name="stZipPath">path of the archive wanted</param>
        /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param>
        public static void CreateZip(string stZipPath, string stDirToZip)
        {
            try
            {
                //Sanitize inputs
                stDirToZip = Path.GetFullPath(stDirToZip);
                stZipPath = Path.GetFullPath(stZipPath);

                Console.WriteLine("Zip directory " + stDirToZip);

                //Recursively parse the directory to zip
                Stack<FileInfo> stackFiles = DirExplore(stDirToZip);

                ZipOutputStream zipOutput = null;

                if (File.Exists(stZipPath))
                    File.Delete(stZipPath);

                Crc32 crc = new Crc32();
                zipOutput = new ZipOutputStream(File.Create(stZipPath));
                zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression

                Console.WriteLine(stackFiles.Count + " files to zip.\n");

                int index = 0;
                foreach (FileInfo fi in stackFiles)
                {
                    ++index;
                    int percent = (int)((float)index / ((float)stackFiles.Count / 100));
                    if (percent % 1 == 0)
                    {
                        Console.CursorLeft = 0;
                        Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done.");
                    }
                    FileStream fs = File.OpenRead(fi.FullName);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    //Create the right arborescence within the archive
                    string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1);
                    ZipEntry entry = new ZipEntry(stFileName);

                    entry.DateTime = DateTime.Now;

                    // set Size and the crc, because the information
                    // about the size and crc should be stored in the header
                    // if it is not set it is automatically written in the footer.
                    // (in this case size == crc == -1 in the header)
                    // Some ZIP programs have problems with zip files that don't store
                    // the size and crc in the header.
                    entry.Size = fs.Length;
                    fs.Close();

                    crc.Reset();
                    crc.Update(buffer);

                    entry.Crc = crc.Value;

                    zipOutput.PutNextEntry(entry);

                    zipOutput.Write(buffer, 0, buffer.Length);
                }
                zipOutput.Finish();
                zipOutput.Close();
                zipOutput = null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static private Stack<FileInfo> DirExplore(string stSrcDirPath)
        {
            try
            {
                Stack<DirectoryInfo> stackDirs = new Stack<DirectoryInfo>();
                Stack<FileInfo> stackPaths = new Stack<FileInfo>();

                DirectoryInfo dd = new DirectoryInfo(Path.GetFullPath(stSrcDirPath));

                stackDirs.Push(dd);
                while (stackDirs.Count > 0)
                {
                    DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop();

                    try
                    {
                        //Process .\files
                        foreach (FileInfo fileInfo in currentDir.GetFiles())
                        {
                            stackPaths.Push(fileInfo);
                        }

                        //Process Subdirectories
                        foreach (DirectoryInfo diNext in currentDir.GetDirectories())
                            stackDirs.Push(diNext);
                    }
                    catch (Exception)
                    {//Might be a system directory
                    }
                }
                return stackPaths;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private static char[] _stSchon = new char[] { '-', '\\', '|', '/' };
    }
}

ContentLicense: CC BY-SA 2.5


问:
how could I convert c++ to python
```<code>#include <iostream>
using namespace std;

int main() {
  int n;
  int i;
  int k;
  cout << "please insert n";

  cin >> n; k=0 ;

  for (i = n; i > 1; i--) {
    cout << "/n "<< k << "+" << i << "=" << i + k++;
  }

  return 0;
}
</code>```

I'm trying to reproduce the above code in python, but I'm not sure what I'm getting wrong. I'm not sure how to start at a number, then decrement until the condition is met. Here's what I have so far:

```<code>k=0
n=4
for i in range(n)
 if i > 1 :
  i-=1
  k+=1
print(i+k++)
</code>```

What am I doing wrong?

答:
You need a for loop that decrements.</p>

```<code># range(4,1,-1) would give a list of [4,3,2]
# for loop iterates through each number.
k = 0
n = 4
# This iterates from n = 4 to 1
# decrementing one step at a time, needn't specifically handle i in your loop body.
# So i would get values of 4,3,2
for i in range(n,1,-1):
    print(k,i)
    # no ++ operator in python.
    k+=1
</code>```

Title: how could I convert c++ to python

Body:
#include <iostream>
using namespace std;

int main() {
  int n;
  int i;
  int k;
  cout << "please insert n";

  cin >> n; k=0 ;

  for (i = n; i > 1; i--) {
    cout << "/n "<< k << "+" << i << "=" << i + k++;
  }

  return 0;
}

I'm trying to reproduce the above code in python, but I'm not sure what I'm getting wrong. I'm not sure how to start at a number, then decrement until the condition is met. Here's what I have so far:

k=0
n=4
for i in range(n)
 if i > 1 :
  i-=1
  k+=1
print(i+k++)

What am I doing wrong?

Body:
You need a for loop that decrements.

# range(4,1,-1) would give a list of [4,3,2]
# for loop iterates through each number.
k = 0
n = 4
# This iterates from n = 4 to 1
# decrementing one step at a time, needn't specifically handle i in your loop body.
# So i would get values of 4,3,2
for i in range(n,1,-1):
    print(k,i)
    # no ++ operator in python.
    k+=1


问:
What exactly does np.fft.fft return?
I'm confused about understanding FFT's and how to apply them in python. From my understanding applying an fft to a 10-pixel 1D array should contain a list of 10 numbers (+2 for the "DC" component): (A_0, P_0, A_1, P_1, A_2, P_2, A_3, P_3, A_4, P_4, A_5, P_5)

A_0 = Amplitude of the average value, "DC" \lambda = \infty component
P_0 = Flat wave, so phase doesn't say anything meaningful
A_1 = Amplitude of the fundamental, \lambda = 1a
P_1 = Phase of the fundamental frequency component
A_2 = Amplitude of the first harmonic \lambda = 2a
P_2 = Phase of the first harmonic frequency component
A_3 = Amplitude of the second harmonic \lambda = 3a
P_3 = Phase of the second harmonic frequency component
A_4 = Amplitude of the third harmonic \lambda = 4a
P_4 = Phase of the third harmonic frequency component
A_5 = Amplitude of the Nyquist frequency
P_5 = Phase of the Nyquist
```

<p>where <code>a</code> is the period. The Nyquist frequency is the highest frequency component that is present in the 1D array. The array below is of length 10 therefore 10 pixels. The fastest frequency possible is one in which the max value is in pixel <code>i</code> and the min value is in pixel <code>i+1</code>. In other words the Nyquist frequency ( <code>f_{Nyq} = pixel_{total}/2</code> ) for 10 pixels is 5.</p>

<p>Looking at the code below, when I use <code>np.fft.fft(array)</code> I get 10 numbers. What are these 10 numbers?</p>

```one_d_pixel_vals =  np.array([0.3, 0.4, 1.3, 3.4, 4.5, 4.2, 2.8, 2.4, 1.4, 0.1])
print(one_d_pixel_vals)

plt.plot(one_d_pixel_vals)
plt.yticks(np.arange(5))
plt.xticks(np.arange(9))
plt.grid(True)
plt.show()

one_d_fft = np.fft.fft(one_d_pixel_vals, norm='ortho')
print(one_d_fft)
print(len(one_d_fft))

>>> [ 6.57753753 +0.00000000e+00j -3.27588825 -6.42423464e-01j
0.01065311 +6.25512087e-01j  0.22429031 -4.34214340e-01j
0.25814049 -7.06019011e-02j -0.06324555 -1.12346671e-15j
0.25814049 +7.06019011e-02j  0.22429031 +4.34214340e-01j
0.01065311 -6.25512087e-01j -3.27588825 +6.42423464e-01j]
10
```

答:
No, your interpretation is erroneous.

a[0] is the mean.

a[1] = np.conjugate(a[-1]) : represent the fundamental a[1]*exp(jwt)+a[-1]*exp(-jwt).

a[k],a[-k] represent the k-th harmonic.

so the Fourier representation is sum(a[k] exp (kwt)) , k = -n//2 .. n//2 .

Title: What exactly does np.fft.fft return?

Body:
I'm confused about understanding FFT's and how to apply them in python. From my understanding applying an fft to a 10-pixel 1D array should contain a list of 10 numbers (+2 for the "DC" component): (A_0, P_0, A_1, P_1, A_2, P_2, A_3, P_3, A_4, P_4, A_5, P_5)

A_0 = Amplitude of the average value, "DC" \lambda = \infty component
P_0 = Flat wave, so phase doesn't say anything meaningful
A_1 = Amplitude of the fundamental, \lambda = 1a
P_1 = Phase of the fundamental frequency component
A_2 = Amplitude of the first harmonic \lambda = 2a
P_2 = Phase of the first harmonic frequency component
A_3 = Amplitude of the second harmonic \lambda = 3a
P_3 = Phase of the second harmonic frequency component
A_4 = Amplitude of the third harmonic \lambda = 4a
P_4 = Phase of the third harmonic frequency component
A_5 = Amplitude of the Nyquist frequency
P_5 = Phase of the Nyquist

where a is the period. The Nyquist frequency is the highest frequency component that is present in the 1D array. The array below is of length 10 therefore 10 pixels. The fastest frequency possible is one in which the max value is in pixel i and the min value is in pixel i+1. In other words the Nyquist frequency ( f_{Nyq} = pixel_{total}/2 ) for 10 pixels is 5.

Looking at the code below, when I use np.fft.fft(array) I get 10 numbers. What are these 10 numbers?

one_d_pixel_vals =  np.array([0.3, 0.4, 1.3, 3.4, 4.5, 4.2, 2.8, 2.4, 1.4, 0.1])
print(one_d_pixel_vals)

plt.plot(one_d_pixel_vals)
plt.yticks(np.arange(5))
plt.xticks(np.arange(9))
plt.grid(True)
plt.show()

one_d_fft = np.fft.fft(one_d_pixel_vals, norm='ortho')
print(one_d_fft)
print(len(one_d_fft))

>>> [ 6.57753753 +0.00000000e+00j -3.27588825 -6.42423464e-01j
0.01065311 +6.25512087e-01j  0.22429031 -4.34214340e-01j
0.25814049 -7.06019011e-02j -0.06324555 -1.12346671e-15j
0.25814049 +7.06019011e-02j  0.22429031 +4.34214340e-01j
0.01065311 -6.25512087e-01j -3.27588825 +6.42423464e-01j]
10


问:
PyInstaller, spec file, ImportError: No module named 'blah'
I am trying to build a python script via PyInstaller.  I have used the following commands to configure, generate a spec file, and build:

```<code>wget pyinstaller.zip, extracted it, python Configure.py, etc, then:

python pyinstaller/Makespec.py --onefile myscript.py
python pyinstaller/Build.py myscript.spec
</code>```

Here is the spec file it generated:

```<code># -*- mode: python -*-
a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'icinga.py'],
             pathex=['/home/user/projects/icinga_python/releases/v2.1'])
pyz = PYZ(a.pure)
exe = EXE( pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=os.path.join('dist', 'myscript'),
          debug=False,
          strip=False,
          upx=True,
          console=1 )
</code>```

This built an executable file in dist/ directory.  When trying to run this file, I get the following:

```<code>Traceback (most recent call last):
  File "<string>", line 12, in <module>
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 455, in importHook
    raise ImportError, "No module named %s" % fqname
ImportError: No module named mysql
</code>```

If I moved this executable into the directory of the actual Python code, it gave different results:

```<code>Traceback (most recent call last):
  File "<string>", line 12, in <module>
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 436, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 521, in doimport
    exec co in mod.__dict__
  File "CLUSTER/mysql/icingasql.py", line 13, in <module>
    import urllib2
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 455, in importHook
    raise ImportError, "No module named %s" % fqname
ImportError: No module named urllib2
</code>```

In the ... pyinstaller docs  I see that --onefile is the option I need/want, but for some reason not everything is being compiled in.

The script is not really including anything fancy, just little quick modules I wrote for sql statements, and parsing certain websites.

答:
just gonna add my 2 cents because I encountered the same problem today - 6 years later :D

For Windows:

```<code>1) cmd => rightclick => with admin rights
2) Enter in cmd: "pip install pyinstaller"
3) navigate in cmd to the folder of "yourMain.py"
4) Enter in cmd: "pyinstaller --onefile --windowed yourMain.py"

5) If you import other scripts / data in "yourMain.py":
Manually enter the folder "dist" (gets created - where "yourMain.exe" should be by now),
and copy your scripts or folder structure there

(e.g. /assets/sounds; /assets/graphics; /scripts; anotherscript.py )
</code>```

Then I was able to run the exe by double clicking.

Turned out to be pretty easy. What did the trick for me was the "--onefile" and adding my other files to the "dist" folder.

The "--windowed" is just so the python command window won't pop up when you start the exe.

Body:
I am trying to build a python script via PyInstaller.  I have used the following commands to configure, generate a spec file, and build:

wget pyinstaller.zip, extracted it, python Configure.py, etc, then:

python pyinstaller/Makespec.py --onefile myscript.py
python pyinstaller/Build.py myscript.spec

Here is the spec file it generated:

# -*- mode: python -*-
a = Analysis([os.path.join(HOMEPATH,'support/_mountzlib.py'), os.path.join(HOMEPATH,'support/useUnicode.py'), 'icinga.py'],
             pathex=['/home/user/projects/icinga_python/releases/v2.1'])
pyz = PYZ(a.pure)
exe = EXE( pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=os.path.join('dist', 'myscript'),
          debug=False,
          strip=False,
          upx=True,
          console=1 )

This built an executable file in dist/ directory.  When trying to run this file, I get the following:

Traceback (most recent call last):
  File "<string>", line 12, in <module>
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 455, in importHook
    raise ImportError, "No module named %s" % fqname
ImportError: No module named mysql

If I moved this executable into the directory of the actual Python code, it gave different results:

Traceback (most recent call last):
  File "<string>", line 12, in <module>
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 436, in importHook
    mod = _self_doimport(nm, ctx, fqname)
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 521, in doimport
    exec co in mod.__dict__
  File "CLUSTER/mysql/icingasql.py", line 13, in <module>
    import urllib2
  File "/home/user/projects/myscript/releases/v2.1/pyinstaller/iu.py", line 455, in importHook
    raise ImportError, "No module named %s" % fqname
ImportError: No module named urllib2

In the ... pyinstaller docs  I see that --onefile is the option I need/want, but for some reason not everything is being compiled in.

The script is not really including anything fancy, just little quick modules I wrote for sql statements, and parsing certain websites.

Body:
just gonna add my 2 cents because I encountered the same problem today - 6 years later :D

For Windows:

1) cmd => rightclick => with admin rights
2) Enter in cmd: "pip install pyinstaller"
3) navigate in cmd to the folder of "yourMain.py"
4) Enter in cmd: "pyinstaller --onefile --windowed yourMain.py"

5) If you import other scripts / data in "yourMain.py":
Manually enter the folder "dist" (gets created - where "yourMain.exe" should be by now),
and copy your scripts or folder structure there

(e.g. /assets/sounds; /assets/graphics; /scripts; anotherscript.py )

Then I was able to run the exe by double clicking.

Turned out to be pretty easy. What did the trick for me was the "--onefile" and adding my other files to the "dist" folder.

The "--windowed" is just so the python command window won't pop up when you start the exe.


问:
Dynamically load shared library while running
I'd like to know if it is possible to load a Linux shared library (extension being .so) into a program that is already running. T

he library that I'm wanting to load is a plugin to modify aspects of the program.

I'd like to load the plugin at any time while the program is running.

EDIT 10/22: This question is years old and I sincerely apologise for the sheer poor quality and utter stupidity of this question.

答: This is one of the core concepts of shared library. You should start by looking at dlopen functions and examples


问:
Text-align in left in boxlayout

user.kv

```<code>#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size
</code>```

How to add background color of user list

How to shift in left align

答:
Text Alignment - Button/Label

By default the text image (texture) is only just large enough to contain the characters and is positioned in the center. The valign property will have no effect and halign will only have an effect if your text has newlines; a single line of text will appear to be centered even though halign is set to left (by default).

In order for the alignment properties to take effect, set the text_size, which specifies the size of the bounding box within which text is aligned. For instance, the following code binds this size to the size of the Button/Label, so text will be aligned within the widget bounds. This will also automatically wrap the text of the Button/Label to remain within this area.

The padding_x is horizontal padding of the text inside the widget box. It defaults to 0. The following code has a value of 5 so that the text is not close to the right border.

Left Alignment

```<code>text_size: self.size
valign: "middle"
padding_x: 5
</code>```

Background Colour

Background color, in the format (r, g, b, a).

This acts as a multiplier to the texture colour. The default texture is grey, so just setting the background color will give a darker result. To set a plain color, set the background_normal to ''.

```<code>background_color: (1, 1, 0, 1)
</code>```

Solution - Text Left Align & Background Colour

```<code><SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size
    background_color: (1, 1, 0, 1)
    text_size: self.size
    valign: "middle"
    padding_x: 5
</code>```

Output

Title: Text-align in left in boxlayout

Body:
user.kv

#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size

How to add background color of user list

How to shift in left align

Body:
Text Alignment - Button/Label

By default the text image (texture) is only just large enough to contain the characters and is positioned in the center. The valign property will have no effect and halign will only have an effect if your text has newlines; a single line of text will appear to be centered even though halign is set to left (by default).

In order for the alignment properties to take effect, set the text_size, which specifies the size of the bounding box within which text is aligned. For instance, the following code binds this size to the size of the Button/Label, so text will be aligned within the widget bounds. This will also automatically wrap the text of the Button/Label to remain within this area.

The padding_x is horizontal padding of the text inside the widget box. It defaults to 0. The following code has a value of 5 so that the text is not close to the right border.

Left Alignment

text_size: self.size
valign: "middle"
padding_x: 5

Background Colour

Background color, in the format (r, g, b, a).

This acts as a multiplier to the texture colour. The default texture is grey, so just setting the background color will give a darker result. To set a plain color, set the background_normal to ''.

background_color: (1, 1, 0, 1)

Solution - Text Left Align & Background Colour

<SelectableButton>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
        Rectangle:
            pos: self.pos
            size: self.size
    background_color: (1, 1, 0, 1)
    text_size: self.size
    valign: "middle"
    padding_x: 5

Output


问:
How to filter users in mysql database based on their star rating
So I am Currently working on a project where I need to filter active users based on the star rating from a select input field.

Below is my users table

```<code>| id | username | firstname | lastname | description | active |
---------------------------------------------------------------
| 2  | kay      | Albert    | Kojo     | Tall        | 1      |
| 3  | kay123   | Mary      | Thompson | Tall        | 1      |
| 4  | kay124   | Francis   | Addai    |             | 1      |
</code>```

Below is my user_reviews table

```<code>| id | user_id| rating |
------------------------
| 1  |   2    |  5     |
| 2  |   3    |  3     |
</code>```

Below is my current query:

```<code>$ratings = mysqli_real_escape_string($db, $_POST['rating']);

SELECT
  *,
  users.id,
  FORMAT(AVG( user_reviews.rating ), 1) AS rating_value,
  count( user_reviews.user_id ) AS review_count
FROM
  users
  LEFT JOIN user_reviews ON users.id = user_reviews.user_id
WHERE
  users.username LIKE '%%'
AND users.active = 1 AND (users.description != "" OR users.description IS
  NOT NULL)
GROUP BY
  users.id
HAVING
  $ratings <= rating_value
ORDER BY
  review_count DESC
</code>```

The above query only returns users who are found in user_reviews table. I would be very glad if someone can help me retrieve users who are in the user_reviews table and users who are not.

答:
Change

```<code> GROUP BY
   users.id
 HAVING
   $ratings <= rating_value
</code>```

To

```<code> GROUP BY
   users.id
 HAVING
   (rating >= $ratings or rating IS NULL )
</code>```

That should solve your missing records.

Body:
So I am Currently working on a project where I need to filter active users based on the star rating from a select input field.

Below is my users table

| id | username | firstname | lastname | description | active |
---------------------------------------------------------------
| 2  | kay      | Albert    | Kojo     | Tall        | 1      |
| 3  | kay123   | Mary      | Thompson | Tall        | 1      |
| 4  | kay124   | Francis   | Addai    |             | 1      |

Below is my user_reviews table

| id | user_id| rating |
------------------------
| 1  |   2    |  5     |
| 2  |   3    |  3     |

Below is my current query:

$ratings = mysqli_real_escape_string($db, $_POST['rating']);

SELECT
  *,
  users.id,
  FORMAT(AVG( user_reviews.rating ), 1) AS rating_value,
  count( user_reviews.user_id ) AS review_count
FROM
  users
  LEFT JOIN user_reviews ON users.id = user_reviews.user_id
WHERE
  users.username LIKE '%%'
AND users.active = 1 AND (users.description != "" OR users.description IS
  NOT NULL)
GROUP BY
  users.id
HAVING
  $ratings <= rating_value
ORDER BY
  review_count DESC

The above query only returns users who are found in user_reviews table. I would be very glad if someone can help me retrieve users who are in the user_reviews table and users who are not.

Body:
Change

 GROUP BY
   users.id
 HAVING
   $ratings <= rating_value

To

 GROUP BY
   users.id
 HAVING
   (rating >= $ratings or rating IS NULL )

That should solve your missing records.


问:
How to capitalize the first character of every sentence
Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.

This is what I have to far and I can't seem to get it right:

```<code>    //Create method to process string.
    private string Sentences(string input)
    {
        //Capitalize first letter of input.
        char firstLetter = char.ToUpper(input[0]);

        //Combine the capitalize letter with the rest of the input.
        input = firstLetter.ToString() + input.Substring(1);

        //Create a char array to hold all characters in input.
        char[] letters = new char[input.Length];

        //Read the characters from input into the array.
        for (int i = 0; i < input.Length; i++)
        {
            letters[i] = input[i];
        }

        //Loop through array to test for punctuation and capitalize a character 2 index away.
        for (int index = 0; index < letters.Length; index++)
        {
            if(char.IsPunctuation(letters[index]))
            {
                if (!((index + 2) >= letters.Length))
                {
                    char.ToUpper(letters[index+ 2]);
                }
            }
        }

        for(int ind = 0; ind < letters.Length; ind++)
        {
            input += letters[ind].ToString();
        }

        return input;
    }
</code>```

答:
You could use Linq.Aggregate n - see comments in code and code output for explanation how it work's.

This one will respect "Bla. blubb" as well - you need to check for whitespaces after ".?!"

```<code>using System;
using System.Linq;

internal class Program
{
    static string Capitalize(string oldSentence )
    {
        return

            // this will look at oldSentence char for char, we start with a
            // new string "" (the accumulator, short acc)
            // and inspect each char c of oldSentence

            // comment all the Console.Writelines in this function, thats
            // just so you see whats done by Aggregate, not needed for it to
            // work

            oldSentence
            .Aggregate("", (acc, c) =>
             {
                 System.Console.WriteLine("Accumulated: " + acc);
                 System.Console.WriteLine("Cecking:     " + c);

                 // if the accumulator is empty or the last character of
                 // trimmed acc is a ".?!" we append the
                 // upper case of c to it
                 if (acc.Length == 0 || ".?!".Any(p => p == acc.Trim().Last())) // (*)
                     acc += char.ToUpper(c);
                 else
                     acc += c; // else we add it unmodified

                 System.Console.WriteLine($"After:      {acc}\n");

                 return acc; // this returns the acc for the next iteration/next c
            });
    }

    static void Main(string[] args)
    {
        Console.SetBufferSize(120, 1000);
        var oldSentence = "This is a testSentence. some occurences "
            + "need capitalization! for examlpe here. or here? maybe "
            + "yes, maybe not.";

        var newSentence = Capitalize(oldSentence);

        Console.WriteLine(new string('*', 80));
        Console.WriteLine(newSentence);
        Console.ReadLine();
    }
}
</code>```

(*)

".?!".Any(p => p == ... )) means does the string ".?!" contain any character that equals ...

acc.Trim().Last() means: remove whitespaces in front/on end of acc and give me the last character

.Last() and .Any() are also Linq. Most of the Linq-esc extension can be found here: https://msdn.microsoft.com/en-us/library/9eekhta0(v=vs.110).aspx

Output (snipped - its rather longish ;o)

```<code>Accumulated:
Cecking:     T
After:      T

Accumulated: T
Cecking:     h
After:      Th

Accumulated: Th
Cecking:     i
After:      Thi

Accumulated: Thi
Cecking:     s
After:      This

Accumulated: This
Cecking:
After:      This

Accumulated: This
Cecking:     i
After:      This i

Accumulated: This i
Cecking:     s
After:      This is

<snipp - .. you get the idea how Aggregate works ...>

Accumulated: This is a testSentence.
Cecking:     s
After:      This is a testSentence. S

<snipp>

Accumulated: This is a testSentence. Some occurences need capitalization!
Cecking:     f
After:      This is a testSentence. Some occurences need capitalization! F

<snipp>
********************************************************************************
This is a testSentence. Some occurences need capitalization! For examlpe here. Or here? Maybe yes, maybe not.
</code>```

Body:
Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.

This is what I have to far and I can't seem to get it right:

    //Create method to process string.
    private string Sentences(string input)
    {
        //Capitalize first letter of input.
        char firstLetter = char.ToUpper(input[0]);

        //Combine the capitalize letter with the rest of the input.
        input = firstLetter.ToString() + input.Substring(1);

        //Create a char array to hold all characters in input.
        char[] letters = new char[input.Length];

        //Read the characters from input into the array.
        for (int i = 0; i < input.Length; i++)
        {
            letters[i] = input[i];
        }

        //Loop through array to test for punctuation and capitalize a character 2 index away.
        for (int index = 0; index < letters.Length; index++)
        {
            if(char.IsPunctuation(letters[index]))
            {
                if (!((index + 2) >= letters.Length))
                {
                    char.ToUpper(letters[index+ 2]);
                }
            }
        }

        for(int ind = 0; ind < letters.Length; ind++)
        {
            input += letters[ind].ToString();
        }

        return input;
    }

Body:
You could use Linq.Aggregate n - see comments in code and code output for explanation how it work's.

This one will respect "Bla. blubb" as well - you need to check for whitespaces after ".?!"

using System;
using System.Linq;

internal class Program
{
    static string Capitalize(string oldSentence )
    {
        return

            // this will look at oldSentence char for char, we start with a
            // new string "" (the accumulator, short acc)
            // and inspect each char c of oldSentence

            // comment all the Console.Writelines in this function, thats
            // just so you see whats done by Aggregate, not needed for it to
            // work

            oldSentence
            .Aggregate("", (acc, c) =>
             {
                 System.Console.WriteLine("Accumulated: " + acc);
                 System.Console.WriteLine("Cecking:     " + c);

                 // if the accumulator is empty or the last character of
                 // trimmed acc is a ".?!" we append the
                 // upper case of c to it
                 if (acc.Length == 0 || ".?!".Any(p => p == acc.Trim().Last())) // (*)
                     acc += char.ToUpper(c);
                 else
                     acc += c; // else we add it unmodified

                 System.Console.WriteLine($"After:      {acc}\n");

                 return acc; // this returns the acc for the next iteration/next c
            });
    }

    static void Main(string[] args)
    {
        Console.SetBufferSize(120, 1000);
        var oldSentence = "This is a testSentence. some occurences "
            + "need capitalization! for examlpe here. or here? maybe "
            + "yes, maybe not.";

        var newSentence = Capitalize(oldSentence);

        Console.WriteLine(new string('*', 80));
        Console.WriteLine(newSentence);
        Console.ReadLine();
    }
}

(*)

".?!".Any(p => p == ... )) means does the string ".?!" contain any character that equals ...

acc.Trim().Last() means: remove whitespaces in front/on end of acc and give me the last character

.Last() and .Any() are also Linq. Most of the Linq-esc extension can be found here: https://msdn.microsoft.com/en-us/library/9eekhta0(v=vs.110).aspx

Output (snipped - its rather longish ;o)

Accumulated:
Cecking:     T
After:      T

Accumulated: T
Cecking:     h
After:      Th

Accumulated: Th
Cecking:     i
After:      Thi

Accumulated: Thi
Cecking:     s
After:      This

Accumulated: This
Cecking:
After:      This

Accumulated: This
Cecking:     i
After:      This i

Accumulated: This i
Cecking:     s
After:      This is

<snipp - .. you get the idea how Aggregate works ...>

Accumulated: This is a testSentence.
Cecking:     s
After:      This is a testSentence. S

<snipp>

Accumulated: This is a testSentence. Some occurences need capitalization!
Cecking:     f
After:      This is a testSentence. Some occurences need capitalization! F

<snipp>
********************************************************************************
This is a testSentence. Some occurences need capitalization! For examlpe here. Or here? Maybe yes, maybe not.


问:
Why Either value is not discarded?
Have the following in ghci:

```<code>:m + Control.Monad.Error
let f x = Right x

Left 1.0 >> Right 1 >>= f
</code>```

gives

```<code>Left 1.0
</code>```

As I understand >> operator discards monadic result of the first argument,
but I see that here it is preserved. Could you please explain?

http://hackage.haskell.org/package/base-4.10.0.0/docs/src/Data.Either.html#Either

strangely, that link doesn't show how Either is implementing methods of Monad typeclass.

答:
Notice the definition contradicts your belief about discarding the left value of a sequence operator:

```<code>instance Monad (Either e) where
    Left  l >>= _ = Left l
    Right r >>= k = k r
</code>```

In fact, in the case of Left the Right value is discarded.

See the source which can be found by clicking on the Monad instance under the Either declaration in the haddocks.

Title: Why Either value is not discarded?

Body:
Have the following in ghci:

:m + Control.Monad.Error
let f x = Right x

Left 1.0 >> Right 1 >>= f

gives

Left 1.0

As I understand >> operator discards monadic result of the first argument,
but I see that here it is preserved. Could you please explain?

http://hackage.haskell.org/package/base-4.10.0.0/docs/src/Data.Either.html#Either

strangely, that link doesn't show how Either is implementing methods of Monad typeclass.

Body:
Notice the definition contradicts your belief about discarding the left value of a sequence operator:

instance Monad (Either e) where
    Left  l >>= _ = Left l
    Right r >>= k = k r

In fact, in the case of Left the Right value is discarded.

See the source which can be found by clicking on the Monad instance under the Either declaration in the haddocks.


问:
How to perform two results with a single $('#id').on('change', function);
I have let's say sets of div:

```<code><body>
<div id="div1" style="display: block">
    <p> paragraph here </p>``
    <img>
    <table></table>
</div>

<div id="div2" style="display: none">
    <p> paragraph here </p>
    <img>
    <table></table>
</div>
</code>```

I surrounded each contents with div.

Now I have two radio buttons:

```<code><label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block">
</code>```

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

```<code>$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);
</code>```

but here, when I tried the second button:

```<code>$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');
</code>```

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

答:
If you want the radio button to change what div is visible, you can try with the code below.

```<code>$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  var id = $(this).attr("id").replace("button","");
  $("#div" + id).css('display', 'block');
});
</code>```

$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  var id = $(this).attr("id").replace("button","");
  $("#div" + id).css('display', 'block');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" style=" display: block ">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2" style="display: none ">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block ">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block "></code>```

If you want to make it a bit smarter try this code. I've changed the radio button value to div1 and div2

```<code>$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  $("#" + $(this).val()).css('display', 'block');
});
</code>```

$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  $("#" + $(this).val()).css('display', 'block');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" style=" display: block ">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2" style="display: none ">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="div1">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="div2"></code>```

Body:
I have let's say sets of div:

 paragraph here
``

 paragraph here

I surrounded each contents with div.

Now I have two radio buttons:

 Button1
<input id="button1" name="button" type="radio" value="block">
 Button2
<input id="button2" name="button" type="radio" value="block">

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);

but here, when I tried the second button:

$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

Body:
If you want the radio button to change what div is visible, you can try with the code below.

$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  var id = $(this).attr("id").replace("button","");
  $("#div" + id).css('display', 'block');
});

$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  var id = $(this).attr("id").replace("button","");
  $("#div" + id).css('display', 'block');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" style=" display: block ">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2" style="display: none ">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block ">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block ">

If you want to make it a bit smarter try this code. I've changed the radio button value to div1 and div2

$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  $("#" + $(this).val()).css('display', 'block');
});

$('[id^=button]').on('change', function() {
  $('[id^=div]').css('display', 'none');
  $("#" + $(this).val()).css('display', 'block');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" style=" display: block ">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2" style="display: none ">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="div1">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="div2">


问:
Swift: property that is a UIView subclass implementing a protocol
Here's the scenario. I have a number of different views I want to show, depending on the model object I'm showing the user. So I've set up a protocol whereby any view that implements it can be presented.

```<code>class MyItem { /* some model properties */ }

protocol ItemView: class {
    // some protocol methods (e.g. updateWithItem(), etc)
    func setupItem(item: MyItem)
}

class SpecificItemView: UIView, ItemView { /* there will be multiple classes like this */
    func setupItem(item: MyItem) {
        // do item setup
    }
}

class AnotherItemView: UIView, ItemView {
    func setupItem(item: MyItem) {
        // do DIFFERENT item setup
    }
}
</code>```

Then when I go to use them in a view controller, I've been given one of my ItemView classes:

```<code>class MyViewController: UIViewController {

    var itemView: ItemView? // could be a SpecificItemView or AnotherItemView

    override func viewDidLoad() {
        itemView?.setupItem(MyItem())
        itemView?.removeFromSuperview() /* this line won't compile */
    }
}
</code>```

Everything works except that last line, where I try to call up to a UIView method (removeFromSuperview). No surprise there, since ItemView has no relation to UIView.

In Objective C I would solve this issue by specifying my itemView ivar like so:

```<code>@property (nonatomic, strong) UIView<ItemView> *itemView;
</code>```

But I can't seem to find a similar syntax for Swift. I suspect there is no way to use this pattern in Swift. How do I achieve my overall goal of interchangeable UIView classes in a Swift-friendly manner?

One hacky solution I've found so far, is to add any UIView methods I call (e.g. removeFromSuperview) to my ItemView protocol.

Another suggestion I got, not on SO, from Maurice Kelly, was to  make a UIView subclass, implementing the ItemView protocol, that both SpecificItemView and AnotherItemView can descend from. You can see it implemented in this gist. While that solves the issue of encapsulating class AND protocol in a single type (e.g. var itemView: ItemViewParentClass) it basically makes the protocol pointless, since you're now implementing all the protocol's methods in your parent class and overriding them in your subclasses. The single biggest drawback of this solutions is that you have to cast instances of subclasses (SpecificItemView) to the new hypthetical parent class (ItemViewParentClass) when you refer to them in your View Controller.

答:
Perhaps the following (in Swift 4) would do the trick?</p>

```<code>class MyViewController: UIViewController {
    typealias T = UIView & ItemView

    var itemView: T?
}
</code>```

Body:
Here's the scenario. I have a number of different views I want to show, depending on the model object I'm showing the user. So I've set up a protocol whereby any view that implements it can be presented.

class MyItem { /* some model properties */ }

protocol ItemView: class {
    // some protocol methods (e.g. updateWithItem(), etc)
    func setupItem(item: MyItem)
}

class SpecificItemView: UIView, ItemView { /* there will be multiple classes like this */
    func setupItem(item: MyItem) {
        // do item setup
    }
}

class AnotherItemView: UIView, ItemView {
    func setupItem(item: MyItem) {
        // do DIFFERENT item setup
    }
}

Then when I go to use them in a view controller, I've been given one of my ItemView classes:

class MyViewController: UIViewController {

    var itemView: ItemView? // could be a SpecificItemView or AnotherItemView

    override func viewDidLoad() {
        itemView?.setupItem(MyItem())
        itemView?.removeFromSuperview() /* this line won't compile */
    }
}

Everything works except that last line, where I try to call up to a UIView method (removeFromSuperview). No surprise there, since ItemView has no relation to UIView.

In Objective C I would solve this issue by specifying my itemView ivar like so:

@property (nonatomic, strong) UIView<ItemView> *itemView;

But I can't seem to find a similar syntax for Swift. I suspect there is no way to use this pattern in Swift. How do I achieve my overall goal of interchangeable UIView classes in a Swift-friendly manner?

One hacky solution I've found so far, is to add any UIView methods I call (e.g. removeFromSuperview) to my ItemView protocol.

Another suggestion I got, not on SO, from Maurice Kelly, was to  make a UIView subclass, implementing the ItemView protocol, that both SpecificItemView and AnotherItemView can descend from. You can see it implemented in this gist. While that solves the issue of encapsulating class AND protocol in a single type (e.g. var itemView: ItemViewParentClass) it basically makes the protocol pointless, since you're now implementing all the protocol's methods in your parent class and overriding them in your subclasses. The single biggest drawback of this solutions is that you have to cast instances of subclasses (SpecificItemView) to the new hypthetical parent class (ItemViewParentClass) when you refer to them in your View Controller.

Body:
Perhaps the following (in Swift 4) would do the trick?

class MyViewController: UIViewController {
    typealias T = UIView & ItemView

    var itemView: T?
}


问:
Google API PHP client with Composer
I made a WP plugin which depends on the Youtube API. So, to do it well, I use Google API PHP client.

My issue is quite simple: the Google API PHP client is huge (more than 12 000 files), including clients for all Google services, when I just need to use Youtube service. So I'm not confortable committing all those files to the WP plugins repo when most of them are useless in my case.

So, right now, my composer.json looks like this:

```<code>{
    "require": {
        "google/apiclient": "^2.0"
    }
}
</code>```

Any way to use only the Youtube API client (using composer if it's possible)?

答:
This is not for the feign of heart but it is doable.

Go to this branch of the repo https://github.com/google/google-api-php-client/tree/v1-master

Grab the full src/Google directory you will need all of that.

In the src/Google/Service directory is the stuff for all the different APIs.  Remove everything except for YouTube.

cross your fingers it should work.

This wont remove all 12000 files but it should give you just what you absolutely need.  I used to do this but its been a few years.

Title: Google API PHP client with Composer

Body:
I made a WP plugin which depends on the Youtube API. So, to do it well, I use Google API PHP client.

My issue is quite simple: the Google API PHP client is huge (more than 12 000 files), including clients for all Google services, when I just need to use Youtube service. So I'm not confortable committing all those files to the WP plugins repo when most of them are useless in my case.

So, right now, my composer.json looks like this:

{
    "require": {
        "google/apiclient": "^2.0"
    }
}

Any way to use only the Youtube API client (using composer if it's possible)?


问:
Testing a function that may produce different outputs every time it is called
Given the function:

```<code>static boolean chance(int percentage) {
    return percentage != 0 && random.nextInt(101) <= percentage;
}
</code>```

and a test for that function:

```<code>@Test
public void chance_AlwaysFalse_Percentage0() {
    assertFalse(chance(0));
}
</code>```

The test does not provide with certainty that chance will always return true. I could change the change function to the following:

```<code>static boolean chance(int percentage) {
    return random.nextInt(101) <= percentage;
}
</code>```

and the test would still pass. However, there is a very small chance that random.nextInt(100) will return 0, which would make the function return true, making the test fail.

I could execute this test a billion times as well, but given the nature of random numbers, there is still a minimal chance of failure.

How should I go about testing a function like this? Should it be tested at all? What is a better approach to this problem?

答:
Software random number generators are not random

They are deterministic if they are seeded with the same seed.
I also corrected the comparison logic to be correct in the range check.

Testable Implementation

```<code>import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Random;

@ParametersAreNonnullByDefault
public class Q47336122
{
    private final Random random;

    public Q47336122(final long seed)
    {
        this.random = new Random(seed);
    }

    public boolean chance(final int percentage)
    {
        if (percentage <= 0) { return false; }
        else if (percentage >= 100) { return true; }
        else
        {
            final int r = this.random.nextInt(100);
            return r > 0 && r <= percentage;
        }
    }
}
</code>```

Deterministic Test

```<code>import org.junit.Test;

import javax.annotation.ParametersAreNonnullByDefault;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@ParametersAreNonnullByDefault
public class Q47336122Test
{

    @Test
    public void testChance()
    {
        final Q47336122 q = new Q47336122(1000L);
        /* poor man's code generator */
//        for (int i=0; i <= 100; i++) {
//        System.out.println(String.format("assertThat(q.chance(%d),is(%s));", i, q.chance(i)));
//        }
        assertThat(q.chance(0),is(false));
        assertThat(q.chance(1),is(false));
        assertThat(q.chance(2),is(false));
        assertThat(q.chance(3),is(false));
        assertThat(q.chance(4),is(false));
        assertThat(q.chance(5),is(false));
        assertThat(q.chance(6),is(false));
        assertThat(q.chance(7),is(false));
        assertThat(q.chance(8),is(false));
        assertThat(q.chance(9),is(false));
        assertThat(q.chance(10),is(false));
        assertThat(q.chance(11),is(false));
        assertThat(q.chance(12),is(false));
        assertThat(q.chance(13),is(false));
        assertThat(q.chance(14),is(false));
        assertThat(q.chance(15),is(false));
        assertThat(q.chance(16),is(false));
        assertThat(q.chance(17),is(false));
        assertThat(q.chance(18),is(true));
        assertThat(q.chance(19),is(false));
        assertThat(q.chance(20),is(false));
        assertThat(q.chance(21),is(false));
        assertThat(q.chance(22),is(false));
        assertThat(q.chance(23),is(false));
        assertThat(q.chance(24),is(true));
        assertThat(q.chance(25),is(false));
        assertThat(q.chance(26),is(false));
        assertThat(q.chance(27),is(false));
        assertThat(q.chance(28),is(false));
        assertThat(q.chance(29),is(false));
        assertThat(q.chance(30),is(false));
        assertThat(q.chance(31),is(false));
        assertThat(q.chance(32),is(false));
        assertThat(q.chance(33),is(false));
        assertThat(q.chance(34),is(false));
        assertThat(q.chance(35),is(false));
        assertThat(q.chance(36),is(true));
        assertThat(q.chance(37),is(false));
        assertThat(q.chance(38),is(true));
        assertThat(q.chance(39),is(false));
        assertThat(q.chance(40),is(true));
        assertThat(q.chance(41),is(false));
        assertThat(q.chance(42),is(true));
        assertThat(q.chance(43),is(false));
        assertThat(q.chance(44),is(false));
        assertThat(q.chance(45),is(false));
        assertThat(q.chance(46),is(false));
        assertThat(q.chance(47),is(false));
        assertThat(q.chance(48),is(false));
        assertThat(q.chance(49),is(false));
        assertThat(q.chance(50),is(true));
        assertThat(q.chance(51),is(true));
        assertThat(q.chance(52),is(false));
        assertThat(q.chance(53),is(true));
        assertThat(q.chance(54),is(false));
        assertThat(q.chance(55),is(true));
        assertThat(q.chance(56),is(false));
        assertThat(q.chance(57),is(true));
        assertThat(q.chance(58),is(false));
        assertThat(q.chance(59),is(false));
        assertThat(q.chance(60),is(true));
        assertThat(q.chance(61),is(false));
        assertThat(q.chance(62),is(false));
        assertThat(q.chance(63),is(true));
        assertThat(q.chance(64),is(true));
        assertThat(q.chance(65),is(true));
        assertThat(q.chance(66),is(true));
        assertThat(q.chance(67),is(true));
        assertThat(q.chance(68),is(true));
        assertThat(q.chance(69),is(false));
        assertThat(q.chance(70),is(false));
        assertThat(q.chance(71),is(true));
        assertThat(q.chance(72),is(true));
        assertThat(q.chance(73),is(true));
        assertThat(q.chance(74),is(true));
        assertThat(q.chance(75),is(false));
        assertThat(q.chance(76),is(true));
        assertThat(q.chance(77),is(true));
        assertThat(q.chance(78),is(true));
        assertThat(q.chance(79),is(false));
        assertThat(q.chance(80),is(true));
        assertThat(q.chance(81),is(false));
        assertThat(q.chance(82),is(true));
        assertThat(q.chance(83),is(true));
        assertThat(q.chance(84),is(true));
        assertThat(q.chance(85),is(true));
        assertThat(q.chance(86),is(true));
        assertThat(q.chance(87),is(true));
        assertThat(q.chance(88),is(true));
        assertThat(q.chance(89),is(true));
        assertThat(q.chance(90),is(true));
        assertThat(q.chance(91),is(true));
        assertThat(q.chance(92),is(true));
        assertThat(q.chance(93),is(true));
        assertThat(q.chance(94),is(true));
        assertThat(q.chance(95),is(true));
        assertThat(q.chance(96),is(true));
        assertThat(q.chance(97),is(true));
        assertThat(q.chance(98),is(true));
        assertThat(q.chance(99),is(true));
        assertThat(q.chance(100),is(true));
    }
}
</code>```

No matter how many times you run this test it will always pass.

It is a trivial exercise for the reader to expand this to test for thousands or millions of inputs. As long as the seed is the same as when the test data is generated, it will pass when tested.

An injectable random number generator instance would be a better design and would make testing even easier in cases where the random number source is actually not deterministic.

static methods are an anti-pattern and is the crux of your problem with testing as it stands, there is nothing here that can not be fixed with some simple refactoring to get rid of the static stuff and make it deterministic and testable as my code shows.

Body:
Given the function:

static boolean chance(int percentage) {
    return percentage != 0 && random.nextInt(101) <= percentage;
}

and a test for that function:

@Test
public void chance_AlwaysFalse_Percentage0() {
    assertFalse(chance(0));
}

The test does not provide with certainty that chance will always return true. I could change the change function to the following:

static boolean chance(int percentage) {
    return random.nextInt(101) <= percentage;
}

and the test would still pass. However, there is a very small chance that random.nextInt(100) will return 0, which would make the function return true, making the test fail.

I could execute this test a billion times as well, but given the nature of random numbers, there is still a minimal chance of failure.

How should I go about testing a function like this? Should it be tested at all? What is a better approach to this problem?

Body:
Software random number generators are not random

They are deterministic if they are seeded with the same seed.
I also corrected the comparison logic to be correct in the range check.

Testable Implementation

import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Random;

@ParametersAreNonnullByDefault
public class Q47336122
{
    private final Random random;

    public Q47336122(final long seed)
    {
        this.random = new Random(seed);
    }

    public boolean chance(final int percentage)
    {
        if (percentage <= 0) { return false; }
        else if (percentage >= 100) { return true; }
        else
        {
            final int r = this.random.nextInt(100);
            return r > 0 && r <= percentage;
        }
    }
}

Deterministic Test

import org.junit.Test;

import javax.annotation.ParametersAreNonnullByDefault;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@ParametersAreNonnullByDefault
public class Q47336122Test
{

    @Test
    public void testChance()
    {
        final Q47336122 q = new Q47336122(1000L);
        /* poor man's code generator */
//        for (int i=0; i <= 100; i++) {
//        System.out.println(String.format("assertThat(q.chance(%d),is(%s));", i, q.chance(i)));
//        }
        assertThat(q.chance(0),is(false));
        assertThat(q.chance(1),is(false));
        assertThat(q.chance(2),is(false));
        assertThat(q.chance(3),is(false));
        assertThat(q.chance(4),is(false));
        assertThat(q.chance(5),is(false));
        assertThat(q.chance(6),is(false));
        assertThat(q.chance(7),is(false));
        assertThat(q.chance(8),is(false));
        assertThat(q.chance(9),is(false));
        assertThat(q.chance(10),is(false));
        assertThat(q.chance(11),is(false));
        assertThat(q.chance(12),is(false));
        assertThat(q.chance(13),is(false));
        assertThat(q.chance(14),is(false));
        assertThat(q.chance(15),is(false));
        assertThat(q.chance(16),is(false));
        assertThat(q.chance(17),is(false));
        assertThat(q.chance(18),is(true));
        assertThat(q.chance(19),is(false));
        assertThat(q.chance(20),is(false));
        assertThat(q.chance(21),is(false));
        assertThat(q.chance(22),is(false));
        assertThat(q.chance(23),is(false));
        assertThat(q.chance(24),is(true));
        assertThat(q.chance(25),is(false));
        assertThat(q.chance(26),is(false));
        assertThat(q.chance(27),is(false));
        assertThat(q.chance(28),is(false));
        assertThat(q.chance(29),is(false));
        assertThat(q.chance(30),is(false));
        assertThat(q.chance(31),is(false));
        assertThat(q.chance(32),is(false));
        assertThat(q.chance(33),is(false));
        assertThat(q.chance(34),is(false));
        assertThat(q.chance(35),is(false));
        assertThat(q.chance(36),is(true));
        assertThat(q.chance(37),is(false));
        assertThat(q.chance(38),is(true));
        assertThat(q.chance(39),is(false));
        assertThat(q.chance(40),is(true));
        assertThat(q.chance(41),is(false));
        assertThat(q.chance(42),is(true));
        assertThat(q.chance(43),is(false));
        assertThat(q.chance(44),is(false));
        assertThat(q.chance(45),is(false));
        assertThat(q.chance(46),is(false));
        assertThat(q.chance(47),is(false));
        assertThat(q.chance(48),is(false));
        assertThat(q.chance(49),is(false));
        assertThat(q.chance(50),is(true));
        assertThat(q.chance(51),is(true));
        assertThat(q.chance(52),is(false));
        assertThat(q.chance(53),is(true));
        assertThat(q.chance(54),is(false));
        assertThat(q.chance(55),is(true));
        assertThat(q.chance(56),is(false));
        assertThat(q.chance(57),is(true));
        assertThat(q.chance(58),is(false));
        assertThat(q.chance(59),is(false));
        assertThat(q.chance(60),is(true));
        assertThat(q.chance(61),is(false));
        assertThat(q.chance(62),is(false));
        assertThat(q.chance(63),is(true));
        assertThat(q.chance(64),is(true));
        assertThat(q.chance(65),is(true));
        assertThat(q.chance(66),is(true));
        assertThat(q.chance(67),is(true));
        assertThat(q.chance(68),is(true));
        assertThat(q.chance(69),is(false));
        assertThat(q.chance(70),is(false));
        assertThat(q.chance(71),is(true));
        assertThat(q.chance(72),is(true));
        assertThat(q.chance(73),is(true));
        assertThat(q.chance(74),is(true));
        assertThat(q.chance(75),is(false));
        assertThat(q.chance(76),is(true));
        assertThat(q.chance(77),is(true));
        assertThat(q.chance(78),is(true));
        assertThat(q.chance(79),is(false));
        assertThat(q.chance(80),is(true));
        assertThat(q.chance(81),is(false));
        assertThat(q.chance(82),is(true));
        assertThat(q.chance(83),is(true));
        assertThat(q.chance(84),is(true));
        assertThat(q.chance(85),is(true));
        assertThat(q.chance(86),is(true));
        assertThat(q.chance(87),is(true));
        assertThat(q.chance(88),is(true));
        assertThat(q.chance(89),is(true));
        assertThat(q.chance(90),is(true));
        assertThat(q.chance(91),is(true));
        assertThat(q.chance(92),is(true));
        assertThat(q.chance(93),is(true));
        assertThat(q.chance(94),is(true));
        assertThat(q.chance(95),is(true));
        assertThat(q.chance(96),is(true));
        assertThat(q.chance(97),is(true));
        assertThat(q.chance(98),is(true));
        assertThat(q.chance(99),is(true));
        assertThat(q.chance(100),is(true));
    }
}

No matter how many times you run this test it will always pass.

It is a trivial exercise for the reader to expand this to test for thousands or millions of inputs. As long as the seed is the same as when the test data is generated, it will pass when tested.

An injectable random number generator instance would be a better design and would make testing even easier in cases where the random number source is actually not deterministic.

static methods are an anti-pattern and is the crux of your problem with testing as it stands, there is nothing here that can not be fixed with some simple refactoring to get rid of the static stuff and make it deterministic and testable as my code shows.


问:
Get distance/displacement between two points
I need to return the distance between two points (p1 = (x1,y1) and p2 = (x2,y2)) but return the negative distance if p2's values are less then p1's.

So that this example is true:
https://i.imgur.com/ZbN8CkG.png

√((x1-x2)² + (y1-y2)²) will always return a positive value, as distance cannot be negative. But what I need is more similar to displacement.

Can anyone help?

答:
If it only has to be negative if the first point has a larger x value then you could just check if x1 is greater than x2 and if it is, multiply your result by -1.
That is unless I'm missing something</p>