问:
Collisions in pygame help and how to stop it from running into to walls when you are using angle and velocity to move
I am most likely not initializing the rectangles properly, so the player constantly "wall jumps" which is not intended.
I am most likely not initializing the rectangles properly, so the player constantly "wall jumps" which is not intended.
I am most likely not initializing the rectangles properly, so the player constantly "wall jumps" which is not intended.

This is the Main:

```<code>import pygame
import wall
import Player
import math

pygame.init()
pygame.display.set_caption("Tanki")
pygame.display.set_icon(pygame.image.load("mainIcon.png"))

running = True
screen = pygame.display.set_mode((300, 500))

WALLS = pygame.sprite.Group()
fence = \
    [wall.Wall(0, 0, 300, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(290, 0, 10, 500, pygame.Color(255, 255, 255), screen),
     wall.Wall(0, 0, 10, 500, pygame.Color(255, 255, 255), screen),
     wall.Wall(0, 490, 300, 10, pygame.Color(255, 255, 255), screen),
     # boundry
     wall.Wall(10 + 60, 235, 50, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 60 + 50 + 60, 235, 50, 10, pygame.Color(255, 255, 255), screen),
     # middle blocks
     wall.Wall(100, ((245 + 500 - 60) / 2) - 5, 100, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(100, ((235 + 60) / 2) - 5, 100, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666, 440, 66.666 + 80, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666, 430, 10, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666 * 2 + 80 - 11, 430, 10, 10, pygame.Color(255, 255, 255), screen),
     # everythin around the goal
     wall.Wall(10 + 66.666 + 10, 430, 66.666 + 80 - 11 - 9, 10, pygame.Color(0, 0, 200), screen),
     # the bottom goal MAKE A CLASS FOR THIS
     wall.Wall(10 + 66.666, 50, 66.666 + 80, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666, 60, 10, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666 * 2 + 80 - 11, 60, 10, 10, pygame.Color(255, 255, 255), screen),
     # everythin around the goal
     wall.Wall(10 + 66.666 + 10, 60, 66.666 + 80 - 11 - 9, 10, pygame.Color(200, 0, 0), screen)
     # the top goal

     ]

tmp = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, 0)
pro = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, tmp)
for eachwall in fence:
    WALLS.add(eachwall)
count = 1
while running:
    count += 1
    print(pro.getAngle() % 360)
    if (count % 10 == 0):
        tmp.updatetmp(pro)
    screen.fill(pygame.Color(0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                pro.setAngle(pro.getAngle() - 10)
            if event.key == pygame.K_RIGHT:
                pro.setAngle(pro.getAngle() + 10)
            if event.key == pygame.K_UP:
                pro.setVel(0.05)
            if event.key == pygame.K_DOWN:
                pro.setVel(-0.05)
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                pro.setVel(0)
    b = True
    for block in WALLS:
        if (pygame.sprite.collide_rect(pro, block)):
            b = False
            print("A")

    a = pro.update(WALLS, screen,b)

    for awall in WALLS:
        awall.draw()
    pygame.display.update()
</code>```

This is Player

```<code>import pygame
import math

class Player(pygame.sprite.Sprite):
    direction = 'right'

    def __init__(self, color, width, height, x, y, velocity, angle, past):
        # Pygame constructor
        pygame.sprite.Sprite.__init__(self)
        self.past = past
        # Init. variables
        self.angle = angle
        self.velocity = velocity
        self.color = color
        self.width = width
        self.height = height
        self.x = x
        self.y = y
        # Create sprite
        self.image = pygame.Surface([width, height])
        self.image.fill(self.color)
        self.rect = self.image.get_rect(topleft = (self.x, self.y))

        #############################
    def setColor(self, color):
        self.color = color
    def setX(self, X):
        self.x = X
    def setY(self, Y):
        self.y = Y
    def setVel(self, vel):
        self.velocity = vel
    def setAngle(self, ANGLE):
        self.angle = ANGLE
    ##############################
    def getColor(self):
        return self.color

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def getVel(self):
        return self.velocity

    def getAngle(self):
        return self.angle
#################################
    def draw(self, screen):
        # Draw player on the screen
        pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height], 0)

    def deg_to_rad(self):
        return int(self.angle * math.pi) / 180

    def rad_to_offset(self, offset):  # insert better func name.
        radians = self.deg_to_rad()
        x = math.cos(radians) * offset
        y = math.sin(radians) * offset
        return [x, y]

    def move(self, walls, go):

        if go:
            forward = self.rad_to_offset(self.velocity)
            self.x += forward[0]
            self.y += forward[1]
        else:
            print("collided")

    def update(self, walls, screen, go):
        if(self.angle>=360):
            self.angle = self.angle%360
        hit = self.move(walls, go)
        self.draw(screen)
        return hit
    def updatetmp(self, Player):
        self.angle = Player.getAngle()
        self.velocity = Player.getVel()
        self.color = Player.getColor()
        self.x = Player.getX()
        self.y = Player.getY()
</code>```

This is the Wall class

```<code>import pygame

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color, screen):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.screen = screen
        self.image = pygame.Surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft = (self.x, self.y))

    def get_rectangle(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

    def draw(self):
        pygame.draw.rect(self.screen, self.color, (self.x, self.y, self.width, self.height), 0)
</code>```

答:
Operations like pygame.sprite.collide_rect() or pygame.sprite.spritecollide() use the .rect attribute of the Sprite object to perform the collision test.

The object player is located by the floating point attributes .x and .y. You have to synchronize this location to the (integral) .rect attribute in update, to make the collision test work:

class Player(pygame.sprite.Sprite):
    # [...]

    def update(self, walls, screen, go):
        if(self.angle>=360):
            self.angle = self.angle%360
        hit = self.move(walls, go)

        self.rect.topleft = (round(self.x), round(self.y)) # <-----
        self.draw(screen)
        return hit
```

<p>Further more it is not necessary to iterate all <code>WALLS</code>:</p>

<blockquote>
  <pre class="lang-py prettyprint-override"><code>for block in WALLS:
   if pygame.sprite.collide_rect(pro, block):
       b = False
       print("A")
</code>```

Use pygame.sprite.spritecollide() instead of ``pygame.sprite.collide_rect()`

if pygame.sprite.spritecollide(pro, WALLS, False):
    b = False
    print("A")
```

<hr>

<p>Note, it is not necessary to implement <code>draw()</code> methods in <code>Player</code> and <code>Wall</code>. You can use the <code>draw()</code> method of the <code>Group</code>. This handy method uses the <code>.rect</code> and <code>.image</code> attributes of the contained Sprite objects, to draw them.</p>

<p>Delete the <code>draw</code> method of <code>Player</code> and <code>Wall</code>.
Add the players and walls to groups and invoke <code>draw()</code> on the groups:</p>

<pre class="lang-py prettyprint-override"><code>fence = \
    [wall.Wall(0, 0, 300, 10, pygame.Color(255, 255, 255), screen),
     # [...]
    ]

tmp = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, 0)
pro = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, tmp)

WALLS = pygame.sprite.Group(fence)
players = pygame.sprite.Group([tmp, pro])

count = 1
while running:
    count += 1

    # [...]

    WALLS.draw(screen)
    players.draw(screen)
    pygame.display.update()
</code>```

Body:
I am most likely not initializing the rectangles properly, so the player constantly "wall jumps" which is not intended.
I am most likely not initializing the rectangles properly, so the player constantly "wall jumps" which is not intended.
I am most likely not initializing the rectangles properly, so the player constantly "wall jumps" which is not intended.

This is the Main:

import pygame
import wall
import Player
import math

pygame.init()
pygame.display.set_caption("Tanki")
pygame.display.set_icon(pygame.image.load("mainIcon.png"))

running = True
screen = pygame.display.set_mode((300, 500))

WALLS = pygame.sprite.Group()
fence = \
    [wall.Wall(0, 0, 300, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(290, 0, 10, 500, pygame.Color(255, 255, 255), screen),
     wall.Wall(0, 0, 10, 500, pygame.Color(255, 255, 255), screen),
     wall.Wall(0, 490, 300, 10, pygame.Color(255, 255, 255), screen),
     # boundry
     wall.Wall(10 + 60, 235, 50, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 60 + 50 + 60, 235, 50, 10, pygame.Color(255, 255, 255), screen),
     # middle blocks
     wall.Wall(100, ((245 + 500 - 60) / 2) - 5, 100, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(100, ((235 + 60) / 2) - 5, 100, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666, 440, 66.666 + 80, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666, 430, 10, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666 * 2 + 80 - 11, 430, 10, 10, pygame.Color(255, 255, 255), screen),
     # everythin around the goal
     wall.Wall(10 + 66.666 + 10, 430, 66.666 + 80 - 11 - 9, 10, pygame.Color(0, 0, 200), screen),
     # the bottom goal MAKE A CLASS FOR THIS
     wall.Wall(10 + 66.666, 50, 66.666 + 80, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666, 60, 10, 10, pygame.Color(255, 255, 255), screen),
     wall.Wall(10 + 66.666 * 2 + 80 - 11, 60, 10, 10, pygame.Color(255, 255, 255), screen),
     # everythin around the goal
     wall.Wall(10 + 66.666 + 10, 60, 66.666 + 80 - 11 - 9, 10, pygame.Color(200, 0, 0), screen)
     # the top goal

     ]

tmp = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, 0)
pro = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, tmp)
for eachwall in fence:
    WALLS.add(eachwall)
count = 1
while running:
    count += 1
    print(pro.getAngle() % 360)
    if (count % 10 == 0):
        tmp.updatetmp(pro)
    screen.fill(pygame.Color(0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                pro.setAngle(pro.getAngle() - 10)
            if event.key == pygame.K_RIGHT:
                pro.setAngle(pro.getAngle() + 10)
            if event.key == pygame.K_UP:
                pro.setVel(0.05)
            if event.key == pygame.K_DOWN:
                pro.setVel(-0.05)
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                pro.setVel(0)
    b = True
    for block in WALLS:
        if (pygame.sprite.collide_rect(pro, block)):
            b = False
            print("A")

    a = pro.update(WALLS, screen,b)

    for awall in WALLS:
        awall.draw()
    pygame.display.update()

This is Player

import pygame
import math

class Player(pygame.sprite.Sprite):
    direction = 'right'

    def __init__(self, color, width, height, x, y, velocity, angle, past):
        # Pygame constructor
        pygame.sprite.Sprite.__init__(self)
        self.past = past
        # Init. variables
        self.angle = angle
        self.velocity = velocity
        self.color = color
        self.width = width
        self.height = height
        self.x = x
        self.y = y
        # Create sprite
        self.image = pygame.Surface([width, height])
        self.image.fill(self.color)
        self.rect = self.image.get_rect(topleft = (self.x, self.y))

        #############################
    def setColor(self, color):
        self.color = color
    def setX(self, X):
        self.x = X
    def setY(self, Y):
        self.y = Y
    def setVel(self, vel):
        self.velocity = vel
    def setAngle(self, ANGLE):
        self.angle = ANGLE
    ##############################
    def getColor(self):
        return self.color

    def getX(self):
        return self.x

    def getY(self):
        return self.y

    def getVel(self):
        return self.velocity

    def getAngle(self):
        return self.angle
#################################
    def draw(self, screen):
        # Draw player on the screen
        pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height], 0)

    def deg_to_rad(self):
        return int(self.angle * math.pi) / 180

    def rad_to_offset(self, offset):  # insert better func name.
        radians = self.deg_to_rad()
        x = math.cos(radians) * offset
        y = math.sin(radians) * offset
        return [x, y]

    def move(self, walls, go):

        if go:
            forward = self.rad_to_offset(self.velocity)
            self.x += forward[0]
            self.y += forward[1]
        else:
            print("collided")

    def update(self, walls, screen, go):
        if(self.angle>=360):
            self.angle = self.angle%360
        hit = self.move(walls, go)
        self.draw(screen)
        return hit
    def updatetmp(self, Player):
        self.angle = Player.getAngle()
        self.velocity = Player.getVel()
        self.color = Player.getColor()
        self.x = Player.getX()
        self.y = Player.getY()

This is the Wall class

import pygame

class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color, screen):
        pygame.sprite.Sprite.__init__(self)
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.color = color
        self.screen = screen
        self.image = pygame.Surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft = (self.x, self.y))

    def get_rectangle(self):
        return pygame.Rect(self.x, self.y, self.width, self.height)

    def draw(self):
        pygame.draw.rect(self.screen, self.color, (self.x, self.y, self.width, self.height), 0)

Body:
Operations like pygame.sprite.collide_rect() or pygame.sprite.spritecollide() use the .rect attribute of the Sprite object to perform the collision test.

The object player is located by the floating point attributes .x and .y. You have to synchronize this location to the (integral) .rect attribute in update, to make the collision test work:

class Player(pygame.sprite.Sprite):
    # [...]

    def update(self, walls, screen, go):
        if(self.angle>=360):
            self.angle = self.angle%360
        hit = self.move(walls, go)

        self.rect.topleft = (round(self.x), round(self.y)) # <-----
        self.draw(screen)
        return hit

Further more it is not necessary to iterate all WALLS:

for block in WALLS:
   if pygame.sprite.collide_rect(pro, block):
       b = False
       print("A")

Use pygame.sprite.spritecollide() instead of ``pygame.sprite.collide_rect()`

if pygame.sprite.spritecollide(pro, WALLS, False):
    b = False
    print("A")

Note, it is not necessary to implement draw() methods in Player and Wall. You can use the draw() method of the Group. This handy method uses the .rect and .image attributes of the contained Sprite objects, to draw them.

Delete the draw method of Player and Wall.
Add the players and walls to groups and invoke draw() on the groups:

fence = \
    [wall.Wall(0, 0, 300, 10, pygame.Color(255, 255, 255), screen),
     # [...]
    ]

tmp = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, 0)
pro = Player.Player(pygame.Color(0, 255, 0), 20, 20, 140, 455, 0.05, 180, tmp)

WALLS = pygame.sprite.Group(fence)
players = pygame.sprite.Group([tmp, pro])

count = 1
while running:
    count += 1

    # [...]

    WALLS.draw(screen)
    players.draw(screen)
    pygame.display.update()


来源: stackexchange

问:
Can I make a style for last level in multilevel list with CSS?
I have a large multilevel list like this:

li
{
  list-style-type: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
    <li>level1 item</li>
    <li>level1 item
      <ul>
        <li>level2 item</li>
        <li>level2 item
          <ul>
            <li>level3 item</li>
          </ul>
        </li>
      </ul>
    </li>
    <li>level1 item
      <ul>
        <li>level2 item</li>
        <li>level2 item</li>
      </ul>
    </li>
</ul></code>```

And I need to make a special style for items on the last level only, i.e. if item hasn't any subitems it must have a special style. I could use classes but the problem is that this list is very large and it's not mine so I can't somehow modify the list itself, I can only write the css for it (or write js code, but I don't want to do it)

答:
Check if element has any child, if not apply css</p>

```<code>$('li').each(function(){
{
    If(!$(this).children().length)
    {
        $(this).addClass("className");
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a large multilevel list like this:

li
{
  list-style-type: none;
}

level1 item

level1 item

level2 item

level2 item

level3 item

level1 item

level2 item

level2 item

And I need to make a special style for items on the last level only, i.e. if item hasn't any subitems it must have a special style. I could use classes but the problem is that this list is very large and it's not mine so I can't somehow modify the list itself, I can only write the css for it (or write js code, but I don't want to do it)

Body:
Check if element has any child, if not apply css

$('li').each(function(){
{
    If(!$(this).children().length)
    {
        $(this).addClass("className");
    }
});


问:
Searching a field inside a leaf in a mongo collection with regex
I have the following mongo collection with records as seen in the json example record below which represents one record. My goal is for example to search for the word "CONST" and find records where the "FullName" field inside the "Aliases" subtree contains this word. Taking the record shown as example, it should hit because the leaves 533-1 and 533-2 inside the "Aliases" tree contain the string "CONST" on their respective "FullName" fields. If the Aliases tree contained only the 533-3 leaf inside tree for example, it wouldn't hit.

I use C# and the MongoDb.Driver package and to search with Regex for normal fields - e.g. for "Key" on this collection shown I use "Builders.Filter.And(filter, Builders.Filter.Regex("Key", new BsonRegularExpression("")))" pattern to add a condition. But for these fields inside the "Aliases" subtree I don't know how to add a condition. What would be the simplest way to make a search on this field?

Please note that under "Aliases" each leaf has a different name (533-1, 533-2 etc). Each name of each leaf is unique in every record in the entire collection.
Record example:

```<code>{
"_id" : "128c5c57-ae95-4a08-9fb8-d6eade663908",
"_t" : "Company",
"ActiveFrom" : "20190813154343",
"ActiveTo" : "30001001000001",
"GroupId" : "38547478-88ef-4caf-a6ce-1a9e6a85a59b",
"Key" : "533",
"FullName" : "RED BRIGADES",
"Countries" : [
    "ITALY"
],
"MoreInfo" : null,
"RecordDetail" : "<RecordDetail></RecordDetail>",
"Aliases" : {
    "533-1" : {
        "Key" : "533-1",
        "FullName" : "BRIGADAS ROJAS PARA LA CONSTRUCCIÓN DEL PARTIDO COMUNISTA COMBATIENTE",
        "OriginalKey" : "533"
    },
    "533-2" : {
        "Key" : "533-2",
        "FullName" : "BRIGADES ROUGES POUR LA CONSTRUCTION DU PARTI COMMUNISTE COMBATTANT",
        "OriginalKey" : "533"
    },
    "533-3" : {
        "Key" : "533-3",
        "FullName" : "BRIGATE ROSSE",
        "OriginalKey" : "533"
    },
    "533-4" : {
        "Key" : "533-4",
        "FullName" : "BRIGATE ROSSE PER LA COSTRUZIONE DEL PARTITO COMUNISTA COMBATTENTE",
        "OriginalKey" : "533"
    }
}
</code>```

}

答:
This might run slower than Ryan's query, but this is readable for you to grok it and you to optimize it.

```<code>db.Companies.aggregate([
    // Add temporary field deconstructed_aliases to every document of collection
    {
        $addFields: {
            deconstructed_aliases: {
                $objectToArray: "$Aliases"
            }
        }
    },
    // Unwind this newly created temporary field deconstructed_aliases
    {
        $unwind: "$deconstructed_aliases"
    },
    // Match on fullName now
    {
        $match: {
            "deconstructed_aliases.v.FullName": {
                $regex: new RegExp('CONST', 'i')
            }
        }
    },
    // Project needed fields
    {
        $project: {
            _id: 0,
            key: "$deconstructed_aliases.v.Key",
            fullName: "$deconstructed_aliases.v.FullName"
        }
    }
]);
</code>```

The C# driver does not seem to have a addField helper method in the aggregate fluent interface.

Also there's no direct support for objectToArray operator needed to normalize the object, hence creating magic strings as a workaround.

Here's a corresponding C# program -

```<code>using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            MongoClient client = new MongoClient("mongodb://localhost:27017/test");
            IMongoDatabase database = client.GetDatabase("test");
            IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("Companies");

            string searchTerm = "CONST";
            string searchResult = FetchKeysBySearchTerm(collection, searchTerm).Result.ToJson();
            Console.WriteLine(searchResult);
        }

        public async static Task<List<BsonDocument>> FetchKeysBySearchTerm(IMongoCollection<BsonDocument> collection, string searchTerm)
        {
            string addFieldStage = @"{ $addFields: { deconstructed_aliases: { $objectToArray: ""$Aliases"" } } }";
            string unwindStage = @"{ $unwind: ""$deconstructed_aliases"" }";
            string projectStage = @"{ $project: { _id: 0, key: ""$deconstructed_aliases.v.Key"", fullName: ""$deconstructed_aliases.v.FullName"" } }";

            var aggregate = collection.Aggregate()
                                      .AppendStage<BsonDocument>(addFieldStage)
                                      .AppendStage<BsonDocument>(unwindStage)
                                      .Match(Builders<BsonDocument>.Filter.Regex("deconstructed_aliases.v.FullName", new BsonRegularExpression(searchTerm, "i")))
                                      .AppendStage<BsonDocument>(projectStage);

            List<BsonDocument> searchResults = await aggregate.ToListAsync();
            return searchResults;
        }
    }
}
</code>```

Here's the sample response -

```<code>[{ "key" : "533-1", "fullName" : "BRIGADAS ROJAS PARA LA CONSTRUCCIÓN DEL PARTIDO COMUNISTA COMBATIENTE" }, { "key" : "533-2", "fullName" : "BRIGADES ROUGES POUR LA CONSTRUCTION DU PARTI COMMUNISTE COMBATTANT" }]
</code>```

Body:
I have the following mongo collection with records as seen in the json example record below which represents one record. My goal is for example to search for the word "CONST" and find records where the "FullName" field inside the "Aliases" subtree contains this word. Taking the record shown as example, it should hit because the leaves 533-1 and 533-2 inside the "Aliases" tree contain the string "CONST" on their respective "FullName" fields. If the Aliases tree contained only the 533-3 leaf inside tree for example, it wouldn't hit.

I use C# and the MongoDb.Driver package and to search with Regex for normal fields - e.g. for "Key" on this collection shown I use "Builders.Filter.And(filter, Builders.Filter.Regex("Key", new BsonRegularExpression("")))" pattern to add a condition. But for these fields inside the "Aliases" subtree I don't know how to add a condition. What would be the simplest way to make a search on this field?

Please note that under "Aliases" each leaf has a different name (533-1, 533-2 etc). Each name of each leaf is unique in every record in the entire collection.
Record example:

{
"_id" : "128c5c57-ae95-4a08-9fb8-d6eade663908",
"_t" : "Company",
"ActiveFrom" : "20190813154343",
"ActiveTo" : "30001001000001",
"GroupId" : "38547478-88ef-4caf-a6ce-1a9e6a85a59b",
"Key" : "533",
"FullName" : "RED BRIGADES",
"Countries" : [
    "ITALY"
],
"MoreInfo" : null,
"RecordDetail" : "<RecordDetail></RecordDetail>",
"Aliases" : {
    "533-1" : {
        "Key" : "533-1",
        "FullName" : "BRIGADAS ROJAS PARA LA CONSTRUCCIÓN DEL PARTIDO COMUNISTA COMBATIENTE",
        "OriginalKey" : "533"
    },
    "533-2" : {
        "Key" : "533-2",
        "FullName" : "BRIGADES ROUGES POUR LA CONSTRUCTION DU PARTI COMMUNISTE COMBATTANT",
        "OriginalKey" : "533"
    },
    "533-3" : {
        "Key" : "533-3",
        "FullName" : "BRIGATE ROSSE",
        "OriginalKey" : "533"
    },
    "533-4" : {
        "Key" : "533-4",
        "FullName" : "BRIGATE ROSSE PER LA COSTRUZIONE DEL PARTITO COMUNISTA COMBATTENTE",
        "OriginalKey" : "533"
    }
}

}

Body:
This might run slower than Ryan's query, but this is readable for you to grok it and you to optimize it.

db.Companies.aggregate([
    // Add temporary field deconstructed_aliases to every document of collection
    {
        $addFields: {
            deconstructed_aliases: {
                $objectToArray: "$Aliases"
            }
        }
    },
    // Unwind this newly created temporary field deconstructed_aliases
    {
        $unwind: "$deconstructed_aliases"
    },
    // Match on fullName now
    {
        $match: {
            "deconstructed_aliases.v.FullName": {
                $regex: new RegExp('CONST', 'i')
            }
        }
    },
    // Project needed fields
    {
        $project: {
            _id: 0,
            key: "$deconstructed_aliases.v.Key",
            fullName: "$deconstructed_aliases.v.FullName"
        }
    }
]);

The C# driver does not seem to have a addField helper method in the aggregate fluent interface.

Also there's no direct support for objectToArray operator needed to normalize the object, hence creating magic strings as a workaround.

Here's a corresponding C# program -

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            MongoClient client = new MongoClient("mongodb://localhost:27017/test");
            IMongoDatabase database = client.GetDatabase("test");
            IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("Companies");

            string searchTerm = "CONST";
            string searchResult = FetchKeysBySearchTerm(collection, searchTerm).Result.ToJson();
            Console.WriteLine(searchResult);
        }

        public async static Task<List<BsonDocument>> FetchKeysBySearchTerm(IMongoCollection<BsonDocument> collection, string searchTerm)
        {
            string addFieldStage = @"{ $addFields: { deconstructed_aliases: { $objectToArray: ""$Aliases"" } } }";
            string unwindStage = @"{ $unwind: ""$deconstructed_aliases"" }";
            string projectStage = @"{ $project: { _id: 0, key: ""$deconstructed_aliases.v.Key"", fullName: ""$deconstructed_aliases.v.FullName"" } }";

            var aggregate = collection.Aggregate()
                                      .AppendStage<BsonDocument>(addFieldStage)
                                      .AppendStage<BsonDocument>(unwindStage)
                                      .Match(Builders<BsonDocument>.Filter.Regex("deconstructed_aliases.v.FullName", new BsonRegularExpression(searchTerm, "i")))
                                      .AppendStage<BsonDocument>(projectStage);

            List<BsonDocument> searchResults = await aggregate.ToListAsync();
            return searchResults;
        }
    }
}

Here's the sample response -

[{ "key" : "533-1", "fullName" : "BRIGADAS ROJAS PARA LA CONSTRUCCIÓN DEL PARTIDO COMUNISTA COMBATIENTE" }, { "key" : "533-2", "fullName" : "BRIGADES ROUGES POUR LA CONSTRUCTION DU PARTI COMMUNISTE COMBATTANT" }]


问:
hiding overlay after some time just like standard video player
i am making a custom video player in which there is an overlay containing the controls of the video player

my player starts to work in full length and height.

now i want to hide the overlay after 5 seconds i stop the mouse over.

now the problem is that when the below function mouse over in .ts file is called the synchronization of the timer is harmed.

so if i move my mouse continuously the overlay starts to flicker.

please provide me the solution to the problem.

following is my html code

```<code><div class="video-container" #videoFullscreen>
    <div class="video-wrapper" mouse-move>
      <video class="video video-js" data-dashjs-player  id="myVideo"  autoplay #videoPlayer>
        <source src="{{ videoSource }}" type="video/mp4" />
      </video>

      <!-- overlay -->
      <div class="overlay" [class.hideOverlay]="hideTop">
        <!-- top controls  -->
          .
          .
          <!-- lower controls  -->

        </div>
      </div>
</code>```

this is my type script code

```<code>@HostListener('document:mousemove', [ '$event' ]) //fuction to display and hide element sue to mouseover
    onMouseMove($event) {
            this.hideTop = false;
            setTimeout(() => {
                this.hideTop = true;
            }, 5000);
    }
</code>```

this is my css code :

```<code>.overlay {
    display: flex;
}
.hideOverlay {
    display:none;
}
</code>```

please help me to solve this problem.

答:
Apologies that my answer is in jQuery, but the concept is fairly basic

What we need to do is check if the timeout event has already been fired, and reset it on a mousemove event during that time.  This is done by checking if the class for hiding the element is applied or not

```<code>
//Timer variable
var timer;
//Detect mousemove event on parent element
$("html").on("mousemove", "#outer", function() {

//Is the element already hidden?
  if ($("#inner").hasClass("hide")) {
  //Show the element
    $("#inner").removeClass("hide")
  } else {
  //Reset the timer to 5 seconds
    clearTimeout(timer);
    timer = setTimeout(hideBox, 5000);
  }
})

function hideBox() {
  $("#inner").addClass("hide")
}
</code>```

https://jsfiddle.net/xcL52zf3/1/

You'll need to swap out the jQuery event handlers and element targetting with the equivalent for you TypeScript library

Body:
i am making a custom video player in which there is an overlay containing the controls of the video player

my player starts to work in full length and height.

now i want to hide the overlay after 5 seconds i stop the mouse over.

now the problem is that when the below function mouse over in .ts file is called the synchronization of the timer is harmed.

so if i move my mouse continuously the overlay starts to flicker.

please provide me the solution to the problem.

following is my html code

      <video class="video video-js" data-dashjs-player  id="myVideo"  autoplay #videoPlayer>
        <source src="{{ videoSource }}" type="video/mp4" />
      </video>

          .
          .

this is my type script code

@HostListener('document:mousemove', [ '$event' ]) //fuction to display and hide element sue to mouseover
    onMouseMove($event) {
            this.hideTop = false;
            setTimeout(() => {
                this.hideTop = true;
            }, 5000);
    }

this is my css code :

.overlay {
    display: flex;
}
.hideOverlay {
    display:none;
}

please help me to solve this problem.

Body:
Apologies that my answer is in jQuery, but the concept is fairly basic

What we need to do is check if the timeout event has already been fired, and reset it on a mousemove event during that time.  This is done by checking if the class for hiding the element is applied or not

//Timer variable
var timer;
//Detect mousemove event on parent element
$("html").on("mousemove", "#outer", function() {

//Is the element already hidden?
  if ($("#inner").hasClass("hide")) {
  //Show the element
    $("#inner").removeClass("hide")
  } else {
  //Reset the timer to 5 seconds
    clearTimeout(timer);
    timer = setTimeout(hideBox, 5000);
  }
})

function hideBox() {
  $("#inner").addClass("hide")
}

https://jsfiddle.net/xcL52zf3/1/

You'll need to swap out the jQuery event handlers and element targetting with the equivalent for you TypeScript library


问:
Regular expression troubles, escaped quotes
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

```<code>"Hello\" World" "Hello Universe" Hi
</code>```

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

```<code>public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}
</code>```

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind

答:
I'm pretty sure you can't do this by just tokenising on a regex.  If you need to deal with nested and escaped delimiters, you need to write a parser. See e.g. http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html

There will be open source parsers which can do what you want, although I don't know any.  You should also check out the StreamTokenizer class.

ContentLicense: CC BY-SA 3.0

Body:
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

"Hello\" World" "Hello Universe" Hi

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind


答:
This would work:

```<code>(?<=[(,])[^(:]+
</code>```

(?<=[(,]) - make sure the previous char is an open parenthesis or a comma

[^(:]+ - match everything which is not an open parenthesis nor colon

https://regex101.com/r/8Yocnm/1

Title: Regular expression to match a string between parenthesis and comma, but with multiple parenthesis present

Body:
I am trying to use regex to match strings (which are species names+codes, e.g. diadema1479) in a phylogenetic tree in parenthetical notation, but I'm not being successful to deal with all the parenthesis.

Here's a sample of my data

(diadema1479:0.20268621848058304691,longipes1483:0.18941326141716441356):0.05754190478991345892,((sp1_11269:0.08954446656323425402,(davidovi11375:0.12866818058352805232):0.02407442773179632040):0.11326732171695803875,(((S_willeyi:0.16019503647856672690,(((((S_sp2:0.13155607959902493320,S_sp3:0.04602288122852762897):0.09795419683476988548,S_sp4:0.03464730266968370220):0.06696262102745857703,S_sp5_Lombok:0.00000100000050002909):0.01699644302538915949,((S_javensis:0.12205647213742974733,(S_sp6:0.07046365005123975123,((yayukae12168:0.01496242382530112158,(yayukae12109:0.01287526689678352571...

When I use:

/(?<=\()[^:]+/g

It matches, for example, 'diadema1479' and 'davidovi11375', but includes all extra parenthesis in '((((S_sp2'. How can I set it not to match any parenthesis at all?

Thanks!

Body:
This would work:

(?<=[(,])[^(:]+

(?<=[(,]) - make sure the previous char is an open parenthesis or a comma

[^(:]+ - match everything which is not an open parenthesis nor colon

https://regex101.com/r/8Yocnm/1


问:
Updating SQL database with DataGrid in WPF
so I have an administration menu item on my application that pulls from my viewModel as the ItemSource which is pulled from SQL and added to an ObservableCollection.

Admin panel

I would like for it to update the SQL when you press the update permissions button. Here is my DataGrid

XAML:

```<code><GroupBox  Header="Update User Permissions">
    <DataGrid ItemsSource="{x:Static model:ViewModel.Users}" AutoGenerateColumns="False" IsTextSearchEnabled="True">
        <DataGrid.Columns>
            <DataGridTextColumn IsReadOnly="True" Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn IsReadOnly="True" Header="Username" Binding="{Binding Username}"/>
            <DataGridCheckBoxColumn Header="Add Truck" Binding="{Binding CanAddTruck}"/>
            <DataGridCheckBoxColumn Header="Park Truck" Binding="{Binding CanParkTruck}"/>
            <DataGridCheckBoxColumn Header="Load Truck" Binding="{Binding CanLoadTruck}"/>
            <DataGridCheckBoxColumn Header="Admin" Binding="{Binding IsAdmin}"/>
        </DataGrid.Columns>
    </DataGrid>
</GroupBox>
<UniformGrid Columns="2" Grid.Row="2">
    <Button Content="Cancel"/>
    <Button Content="Update permissions" Command="{Binding SaveUserDB_Command}" />
</UniformGrid>
</code>```

User Model:

```<code>public AllUsers()
{
    SaveUserDB_Command = new RelayCommand(SaveUserDB_Command_Execute, SaveUserDB_Command_CanExecute);
}

public AllUsers(SqlDataReader reader)
{
    Name = reader.GetString("Name");
    Username = reader.GetString("Username");
    CanAddTruck = Convert.ToBoolean(reader["CanAddTruck"]);
    CanParkTruck = Convert.ToBoolean(reader["CanParkTruck"]);
    CanLoadTruck = Convert.ToBoolean(reader["CanLoadTruck"]);
    IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
}

private string _Name;
public string Name
{
    get { return _Name; }
    set { _Name = value; RaisePropertyChanged("Name"); }
}

private string _Username;
public string Username
{
    get { return _Username; }
    set { _Username = value; RaisePropertyChanged("Username"); }
}

private bool _CanAddTruck;
public bool CanAddTruck
{
    get { return _CanAddTruck; }
    set { _CanAddTruck = value; RaisePropertyChanged("CanAddTruck"); }
}

private bool _CanParkTruck;
public bool CanParkTruck
{
    get { return _CanParkTruck; }
    set { _CanParkTruck = value; RaisePropertyChanged("CanParkTruck"); }
}

private bool _CanLoadTruck;
public bool CanLoadTruck
{
    get { return _CanLoadTruck; }
    set { _CanLoadTruck = value; RaisePropertyChanged("CanLoadTruck"); }
}

private bool _IsAdmin;
public bool IsAdmin
{
    get { return _IsAdmin; }
    set { _IsAdmin = value; RaisePropertyChanged("IsAdmin"); }
}

public RelayCommand SaveUserDB_Command { get; private set; }

void SaveUserDB_Command_Execute(object param)
{
    Debug.Print("Not Working");
    using var conn = new SqlConnection(Settings.Default.ConnectionString);

    conn.Open();
    string query = @"IF EXISTS(SELECT * FROM dbo.Permissions WHERE Username = @user)
                    UPDATE dbo.Permissions
                    SET CanAddTruck = @addTruck, CanParkTruck = @parkTruck, CanLoadTruck = @loadTruck, IsAdmin = @admin
                    WHERE Username = @user
                ELSE
                    INSERT INTO dbo.Permissions(Name, Username, CanAddTruck, CanParkTruck, CanLoadTruck, IsAdmin) VALUES(@name, @user, @addTruck, @parkTruck, @loadTruck, @admin);";

    var cmd = new SqlCommand(query, conn);
    cmd.Parameters.AddWithValue("@name", Name);
    cmd.Parameters.AddWithValue("@user", Username);
    cmd.Parameters.AddWithValue("@addTruck", CanAddTruck);
    cmd.Parameters.AddWithValue("@parkTruck", CanParkTruck);
    cmd.Parameters.AddWithValue("@loadTruck", CanLoadTruck);
    cmd.Parameters.AddWithValue("@admin", IsAdmin);
    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}
bool SaveUserDB_Command_CanExecute(object param)
{
    return true;
}
</code>```

View Model:

```<code>public static void GetUsers()
{
    Users.Clear();

    using var conn = new SqlConnection(Settings.Default.ConnectionString);

    conn.Open();
    string qry = "SELECT * FROM dbo.Permissions";
    var cmd = new SqlCommand(qry, conn);

    var reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        Users.Add(new AllUsers(reader));
    }
    conn.Close();
}

public static ObservableCollection<AllUsers> Users { get; set; } = new ObservableCollection<AllUsers>();
</code>```

Pressing the update permissions button should see all changes in the DataGrid and replicate to the SQL. I would imagine I would need to get the rows values but am lost on how to. Some assistance would be appreciated!

Thank you.

答:
This should be a comment, but I can't make them.

From you're code it doesn't seems like you have initialized SaveUserDB_Command.
There are SaveUserDB_Command_CanExecute and SaveUserDB_Command_Execute but they are useless if there is not a RelayCommand object calling them.

------- UPDATE -------

Since RelayCommand is a class that implements the ICommand Interface that you need to implement yourself i'm not sure how you designed the constructor.

Let's suppose it is something like

```<code>public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
    this.execute = execute;
    this.canExecute = canExecute;
}
</code>```

You need to initialize SaveUserDB_Command like

```<code>SaveUserDB_Command = new RelayCommand(SaveUserDB_Command_Execute, SaveUserDB_Command_CanExecute);
</code>```

Body:
so I have an administration menu item on my application that pulls from my viewModel as the ItemSource which is pulled from SQL and added to an ObservableCollection.

Admin panel

I would like for it to update the SQL when you press the update permissions button. Here is my DataGrid

XAML:

<GroupBox  Header="Update User Permissions">
    <DataGrid ItemsSource="{x:Static model:ViewModel.Users}" AutoGenerateColumns="False" IsTextSearchEnabled="True">
        <DataGrid.Columns>
            <DataGridTextColumn IsReadOnly="True" Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn IsReadOnly="True" Header="Username" Binding="{Binding Username}"/>
            <DataGridCheckBoxColumn Header="Add Truck" Binding="{Binding CanAddTruck}"/>
            <DataGridCheckBoxColumn Header="Park Truck" Binding="{Binding CanParkTruck}"/>
            <DataGridCheckBoxColumn Header="Load Truck" Binding="{Binding CanLoadTruck}"/>
            <DataGridCheckBoxColumn Header="Admin" Binding="{Binding IsAdmin}"/>
        </DataGrid.Columns>
    </DataGrid>
</GroupBox>
<UniformGrid Columns="2" Grid.Row="2">
    <Button Content="Cancel"/>
    <Button Content="Update permissions" Command="{Binding SaveUserDB_Command}" />
</UniformGrid>

User Model:

public AllUsers()
{
    SaveUserDB_Command = new RelayCommand(SaveUserDB_Command_Execute, SaveUserDB_Command_CanExecute);
}

public AllUsers(SqlDataReader reader)
{
    Name = reader.GetString("Name");
    Username = reader.GetString("Username");
    CanAddTruck = Convert.ToBoolean(reader["CanAddTruck"]);
    CanParkTruck = Convert.ToBoolean(reader["CanParkTruck"]);
    CanLoadTruck = Convert.ToBoolean(reader["CanLoadTruck"]);
    IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
}

private string _Name;
public string Name
{
    get { return _Name; }
    set { _Name = value; RaisePropertyChanged("Name"); }
}

private string _Username;
public string Username
{
    get { return _Username; }
    set { _Username = value; RaisePropertyChanged("Username"); }
}

private bool _CanAddTruck;
public bool CanAddTruck
{
    get { return _CanAddTruck; }
    set { _CanAddTruck = value; RaisePropertyChanged("CanAddTruck"); }
}

private bool _CanParkTruck;
public bool CanParkTruck
{
    get { return _CanParkTruck; }
    set { _CanParkTruck = value; RaisePropertyChanged("CanParkTruck"); }
}

private bool _CanLoadTruck;
public bool CanLoadTruck
{
    get { return _CanLoadTruck; }
    set { _CanLoadTruck = value; RaisePropertyChanged("CanLoadTruck"); }
}

private bool _IsAdmin;
public bool IsAdmin
{
    get { return _IsAdmin; }
    set { _IsAdmin = value; RaisePropertyChanged("IsAdmin"); }
}

public RelayCommand SaveUserDB_Command { get; private set; }

void SaveUserDB_Command_Execute(object param)
{
    Debug.Print("Not Working");
    using var conn = new SqlConnection(Settings.Default.ConnectionString);

    conn.Open();
    string query = @"IF EXISTS(SELECT * FROM dbo.Permissions WHERE Username = @user)
                    UPDATE dbo.Permissions
                    SET CanAddTruck = @addTruck, CanParkTruck = @parkTruck, CanLoadTruck = @loadTruck, IsAdmin = @admin
                    WHERE Username = @user
                ELSE
                    INSERT INTO dbo.Permissions(Name, Username, CanAddTruck, CanParkTruck, CanLoadTruck, IsAdmin) VALUES(@name, @user, @addTruck, @parkTruck, @loadTruck, @admin);";

    var cmd = new SqlCommand(query, conn);
    cmd.Parameters.AddWithValue("@name", Name);
    cmd.Parameters.AddWithValue("@user", Username);
    cmd.Parameters.AddWithValue("@addTruck", CanAddTruck);
    cmd.Parameters.AddWithValue("@parkTruck", CanParkTruck);
    cmd.Parameters.AddWithValue("@loadTruck", CanLoadTruck);
    cmd.Parameters.AddWithValue("@admin", IsAdmin);
    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}
bool SaveUserDB_Command_CanExecute(object param)
{
    return true;
}

View Model:

public static void GetUsers()
{
    Users.Clear();

    using var conn = new SqlConnection(Settings.Default.ConnectionString);

    conn.Open();
    string qry = "SELECT * FROM dbo.Permissions";
    var cmd = new SqlCommand(qry, conn);

    var reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        Users.Add(new AllUsers(reader));
    }
    conn.Close();
}

public static ObservableCollection<AllUsers> Users { get; set; } = new ObservableCollection<AllUsers>();

Pressing the update permissions button should see all changes in the DataGrid and replicate to the SQL. I would imagine I would need to get the rows values but am lost on how to. Some assistance would be appreciated!

Thank you.

Body:
This should be a comment, but I can't make them.

From you're code it doesn't seems like you have initialized SaveUserDB_Command.
There are SaveUserDB_Command_CanExecute and SaveUserDB_Command_Execute but they are useless if there is not a RelayCommand object calling them.

------- UPDATE -------

Since RelayCommand is a class that implements the ICommand Interface that you need to implement yourself i'm not sure how you designed the constructor.

Let's suppose it is something like

public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
    this.execute = execute;
    this.canExecute = canExecute;
}

You need to initialize SaveUserDB_Command like

SaveUserDB_Command = new RelayCommand(SaveUserDB_Command_Execute, SaveUserDB_Command_CanExecute);


问:
Excel VBA - Copy andpaste formula without incrementing
I have a number of formulas similar to this one:

```<code>=MID('Sheet1'!O40,1,5)
</code>```

I'm trying to copy and paste this formula to a blank cell without incrementing the cell reference and updating the worksheet reference.

Desired End Result:

```<code>=MID('Sheet2'!O40,1,5)
</code>```

I've used the below code as a test sample but the copied formula auto increments the cell reference. Is there anyway to copy and paste formulas without incrementing?

```<code>Range("E2").Copy
Range("E126").PasteSpecial xlPasteFormulas
</code>```

答:
I've come up with a solution below:</p>

```<code>Range("E126").Formula = Range("E2").Formula
Set r = Range("E126").SpecialCells(xlCellTypeFormulas)
r.Replace What:="Sheet1", Replacement:="Sheet2", LookAt:=xlPart
</code>```

Body:
I have a number of formulas similar to this one:

=MID('Sheet1'!O40,1,5)

I'm trying to copy and paste this formula to a blank cell without incrementing the cell reference and updating the worksheet reference.

Desired End Result:

=MID('Sheet2'!O40,1,5)

I've used the below code as a test sample but the copied formula auto increments the cell reference. Is there anyway to copy and paste formulas without incrementing?

Range("E2").Copy
Range("E126").PasteSpecial xlPasteFormulas

Body:
I've come up with a solution below:

Range("E126").Formula = Range("E2").Formula
Set r = Range("E126").SpecialCells(xlCellTypeFormulas)
r.Replace What:="Sheet1", Replacement:="Sheet2", LookAt:=xlPart


问:
update part of the key
Q:

If I have a composite key combined from 4 fields for example, can I update one of them?

I mean can I execute a statement like this:

```<code>UPDATE tb
SET firstCol = '15', secondCol = 'test2'
WHERE firstCol = '1' AND serial = '2';
</code>```

Given:

my table name is: tb

my fields are: firstCol, secondCol, serial

my keys are: firstCol , serial

Any suggestions? Did I miss some concept?

thanks.

答:
Of course you can do that, why?
Do you have a problem doing that?</p>

Title: update part of the key

Body:
Q:

If I have a composite key combined from 4 fields for example, can I update one of them?

I mean can I execute a statement like this:

UPDATE tb
SET firstCol = '15', secondCol = 'test2'
WHERE firstCol = '1' AND serial = '2';

Given:

my table name is: tb

my fields are: firstCol, secondCol, serial

my keys are: firstCol , serial

Any suggestions? Did I miss some concept?

thanks.


问:
Call local host server with parameters
I am running the Flask server on port 81. I want my server to show a normal page at / and a debug page at /debug. When I enter localhost:81 I get the normal page. When I try to navigate to localhost\debug:81 or localhost/81:81 I get a "Not Found" error. What am I doing wrong?

```<code>app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/debug')
def index_debug():
    return render_template('index.html', debug=true)
</code>```

答:
You have to have the project structure like this:

index.py
templates/
      index.html```

and your param debug has to be debug=True

Title: Call local host server with parameters

Body:
I am running the Flask server on port 81. I want my server to show a normal page at / and a debug page at /debug. When I enter localhost:81 I get the normal page. When I try to navigate to localhost\debug:81 or localhost/81:81 I get a "Not Found" error. What am I doing wrong?

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/debug')
def index_debug():
    return render_template('index.html', debug=true)

Body:
You have to have the project structure like this:

index.py
templates/
      index.html

and your param debug has to be debug=True


问:
React-native Axios is working in iOS but not calling in Android
I can't seem to get the following Axios call to work on Android.
It's not hitting the server and showing the error : [Error: Network Error].
The same code works on iOS. Do I have to do something special to enable
network requests for Android on React Native?

```<code> var url = 'https://***.****.com/api/list';
 axios.get(url,
           { headers: {'Content-Type': 'application/json'}}
          ).then((response) => {
               console.log("response = ",response.data)
          })
          .catch((error) => {
              console.log("error = ", error)
          });
</code>```

I got this error in console :

```<code>error = >  Error: Network Error
    at createError (index.bundle?platfor…minify=false:117949)
    at XMLHttpRequest.handleError (index.bundle?platfor…minify=false:117857)
    at XMLHttpRequest.dispatchEvent (index.bundle?platfor…&minify=false:32349)
    at XMLHttpRequest.setReadyState (index.bundle?platfor…&minify=false:31433)
    at XMLHttpRequest.__didCompleteResponse (index.bundle?platfor…&minify=false:31260)
    at index.bundle?platfor…&minify=false:31370
    at RCTDeviceEventEmitter.emit (index.bundle?platfor…e&minify=false:5652)
    at MessageQueue.__callFunction (index.bundle?platfor…e&minify=false:5080)
    at index.bundle?platfor…e&minify=false:4793
    at MessageQueue.__guard (index.bundle?platfor…e&minify=false:5034)
</code>```

答:
it could be your error is like this issue: https://stackoverflow.com/a/16302527/7714108

You need to get on deeper in your Error object, if you get

javax.net.ssl.SSLHandshakeException:

  java.security.cert.CertPathValidatorException:
      Trust anchor for certification path not found.

your error is about misconfigured server.

I have this problem on Android 6.0 - API 23 (Marsmallow) and earlier. I don't know why happen only to me from those api and earlier. I am using Expo sdk 35, and I tried with axios, fetch and XMLHttpRequest, and the error always is pretty similar "Network Error". But apart of that, for debugging I am using React Native Debugger, then my curiosity is about why when I enable Network Inspect, this error is gone.

Body:
I can't seem to get the following Axios call to work on Android.
It's not hitting the server and showing the error : [Error: Network Error].
The same code works on iOS. Do I have to do something special to enable
network requests for Android on React Native?

 var url = 'https://***.****.com/api/list';
 axios.get(url,
           { headers: {'Content-Type': 'application/json'}}
          ).then((response) => {
               console.log("response = ",response.data)
          })
          .catch((error) => {
              console.log("error = ", error)
          });

I got this error in console :

error = >  Error: Network Error
    at createError (index.bundle?platfor…minify=false:117949)
    at XMLHttpRequest.handleError (index.bundle?platfor…minify=false:117857)
    at XMLHttpRequest.dispatchEvent (index.bundle?platfor…&minify=false:32349)
    at XMLHttpRequest.setReadyState (index.bundle?platfor…&minify=false:31433)
    at XMLHttpRequest.__didCompleteResponse (index.bundle?platfor…&minify=false:31260)
    at index.bundle?platfor…&minify=false:31370
    at RCTDeviceEventEmitter.emit (index.bundle?platfor…e&minify=false:5652)
    at MessageQueue.__callFunction (index.bundle?platfor…e&minify=false:5080)
    at index.bundle?platfor…e&minify=false:4793
    at MessageQueue.__guard (index.bundle?platfor…e&minify=false:5034)


问:
Ambiguous behaviour of strcmp()
Please note that I have checked the relevant questions to this title, but from my point of view they are not related to this question.

Initially I thought that program1 and program2 would give me the same result.

```<code>//Program 1

char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));

//Output: -4

</code>```

```<code>//Program 2
printf("%d", strcmp("abcd", "efgh"));

//Output: -1
</code>```

Only difference that I can spot is that in the program2 I have passed string literal, while in program I've passed char * as the argument of the strcmp() function.

Why there is a difference between the behaviour of these seemingly same program?

Platform: Linux mint
compiler: g++

Edit: Actually the program1 always prints the difference of ascii code of the first mismatched characters, but the program2 print -1 if the ascii code of the first mismatched character in string2 is greater than that of string1 and vice versa.

答:
It is indeed surprising that strcmp returns 2 different values for these calls, but it is not incompatible with the C Standard:

strcmp() returns a negative value if the first string is lexicographically before the second string. Both -4 and -1 are negative values.

As pointed by others, the code generated for the different calls is different:

the compiler generates a call to the library function in the first program

the compiler is able to determine the result of the comparison and generates an explicit result of -1 for the second case where both arguments are string literals.

In order to perform this compile time evaluation, strcmp must be defined in a subtile way in <string.h> so the compiler can determine that the program refers to the C library's implementation and not an alternative that might behave differently. Tracing the corresponding prototype in recent GNU libc include files is a bit difficult with a number of nested macros eventually leading to a hidden prototype.

Note that more recent versions of both gcc and clang will perform the optimisation in both cases as can be tested on Godbolt Compiler Explorer, but neither combines this optmisation with that of printf to generate the even more compact code puts("-1");. They seem to convert printf to puts only for string literal formats without arguments.

Title: Ambiguous behaviour of strcmp()

Body:
Please note that I have checked the relevant questions to this title, but from my point of view they are not related to this question.

Initially I thought that program1 and program2 would give me the same result.

//Program 1

char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));

//Output: -4

//Program 2
printf("%d", strcmp("abcd", "efgh"));

//Output: -1

Only difference that I can spot is that in the program2 I have passed string literal, while in program I've passed char * as the argument of the strcmp() function.

Why there is a difference between the behaviour of these seemingly same program?

Platform: Linux mint
compiler: g++

Edit: Actually the program1 always prints the difference of ascii code of the first mismatched characters, but the program2 print -1 if the ascii code of the first mismatched character in string2 is greater than that of string1 and vice versa.


问:
IE11 doesn't accept font-weights that aren't multiples of 100
I have an app that takes in font weights such as 380 and 350 for branding purposes and these fonts work perfectly fine in Chrome and Firefox. However, when I go onto IE11, the font weights are much more bolded, seemingly adopting the font weights of other text that uses a font weight that is a multiple of 100. I went into the console and changed these font weights to 400 and it does change to a lighter text but is there any way I could get it to be exactly 350/380? I couldn't find anything useful online about this. </p>

答:
Unfortunately, IE11 does not support font weight variations that deviate from multiples of 100s. My suggestion would be to use a media query to change the font weight that is the closest to 350/380 for IE11. So you'll set the font weight in IE11 to 400 specifically.

/* Other browsers will have font-weight of 380 */
body {
  font-weight: 380;
}

/* Target IE11 and set font-weight to 400 */
@media (-ms-high-contrast: active), (-ms-high-contrast: none) {
  body {
    font-weight: 400;
  }
}
```


问:
Firebase cloud messaging multiple devices and a single account
How can I know if the user reinstalls the app or is using 2 devices with the same account? Is it possible to detect it?

A user has an FCM token per device, without a unique device id I don't know how to differentiate them.

答:
Firebase Cloud Messaging only knows about app instances, a single app installed on a single device.

If your app associated that with users, the logic of how to do so is application specific. If you want to alert the user on all their devices, you'll want to store multiple tokens per user. If you want to only alert the user on their active or most recently active device, you'll only want to store a single token per user. All these scenarios are possible, but you'll have to implement as part of your application logic.

Also see:

When to register an FCM token for a user

How to handle multiple Firebase FCM tokens per user?

Receiving the same token for different users when using firebase messaging

Is FCM (firebase cloud messaging) Token for one device or for one account?


问:
IE Problem - jQuery append inside a table tag for each Ajax request
I am appending some html inside a table tag while performing each Ajax request.I need to show the appended html immediatly after performing the ajax request.
It is working fine in FF, but in IE it shows the appended html only after completing all the ajax requests.

Following is the code

```<code>while(cond)

{

$.ajax({
                // other codes
                success: function(data) {
                    $('#tblPOUpdateResult tr:last').after(GetHtmlFromProblems(data));
                }
            });
}

function GetHtmlFromProblems(data) {

    var output = "";
    output = "<tr><td>" + data.PurchaseOrderNumber + "</td><td>";

    if (data.Result.WasSuccessful == true) {
        output = output + "<div style='color: green'> Sucess </div></td><td>";
    }
    else {
        output = output + "<div style='color: red'>Failed</div></td><td>";
    }

    if (data.Result.Problems.PurchaseOrderNotFound == true) {
        output = output + "Purchase order was not found";
    }

    if (data.Result.Problems.NoChangesToSave == true) {
        output = output + "There is no change to update <br />";
    }

    if (data.Result.Problems.PurchaseOrderIsForADifferentVendor == true) {
        output = output + "Purchase Order belongs to a different vendor <br />";
    }

    if (data.Result.Problems.PurchaseOrderIsNotDirectShip == true) {
        output = output + "Purchase Order is not Direct ShipSet <br />";
    }

    if (data.Result.Problems.LineIsNotForSpecifiedPart == true) {
        output = output + "Purchase Order Line is specified for different part <br />";
    }

    if (data.Result.Problems.QuantityReceivedExceedsQuantityOrdered == true) {
        output = output + "Quantity received exceeded quanity ordered <br />";
    }

    if (data.Result.HasAnyProblem == false) {
        output = output + "There is no problem<br />";
    }
    output = output + "</td></tr>";

    return output;
}
</code>```

Html Page:

```<code><div id="PurchaseOrderUpdateResults">
                    <table cellspacing='0' class='grid_table bordered no_table_padding no_wrap_table' id="tblPOUpdateResult">
                        <tbody>
                            <tr>
                                <th>
                                    Purchase Order Number
                                </th>
                                <th>
                                    Status
                                </th>
                                <th>
                                    Problems
                                </th>
                            </tr>
                        </tbody>
                    </table>
                </div>
</code>```

Any help is much appreciated :) I m using IE 7.

答:
Try the table-layout property as given here:

http://msdn.microsoft.com/en-us/library/ms531161%28v=VS.85%29.aspx

You can optimize table rendering
  performance by specifying the
  tableLayout property. This property
  causes Windows Internet Explorer to
  render the table one row at a time,
  providing users with information at a
  faster pace.

HTH

Body:
I am appending some html inside a table tag while performing each Ajax request.I need to show the appended html immediatly after performing the ajax request.
It is working fine in FF, but in IE it shows the appended html only after completing all the ajax requests.

Following is the code

while(cond)

{

$.ajax({
                // other codes
                success: function(data) {
                    $('#tblPOUpdateResult tr:last').after(GetHtmlFromProblems(data));
                }
            });
}

function GetHtmlFromProblems(data) {

    var output = "";
    output = "
" + data.PurchaseOrderNumber + "	";

    if (data.Result.WasSuccessful == true) {
        output = output + "
 Sucess
	";
    }
    else {
        output = output + "
Failed
	";
    }

    if (data.Result.Problems.PurchaseOrderNotFound == true) {
        output = output + "Purchase order was not found";
    }

    if (data.Result.Problems.NoChangesToSave == true) {
        output = output + "There is no change to update
";
    }

    if (data.Result.Problems.PurchaseOrderIsForADifferentVendor == true) {
        output = output + "Purchase Order belongs to a different vendor
";
    }

    if (data.Result.Problems.PurchaseOrderIsNotDirectShip == true) {
        output = output + "Purchase Order is not Direct ShipSet
";
    }

    if (data.Result.Problems.LineIsNotForSpecifiedPart == true) {
        output = output + "Purchase Order Line is specified for different part
";
    }

    if (data.Result.Problems.QuantityReceivedExceedsQuantityOrdered == true) {
        output = output + "Quantity received exceeded quanity ordered
";
    }

    if (data.Result.HasAnyProblem == false) {
        output = output + "There is no problem
";
    }
    output = output + "
";

    return output;
}

Html Page:

                                    Purchase Order Number

                                    Status

                                    Problems

Any help is much appreciated :) I m using IE 7.


问:
Cannot connect to Redis Server
I have following Error when trying to run applicaiton:

It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING

```<code>RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING]
StackExchange.Redis.ConnectionMultiplexer.Connect(ConfigurationOptions  configuration, TextWriter log) in c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:767
Microsoft.Web.Redis.StackExchangeClientConnection..ctor(ProviderConfiguration configuration) +263
Microsoft.Web.Redis.<>c__DisplayClass3.<.ctor>b__1() +26
Microsoft.Web.Redis.RedisSharedConnection.TryGetConnection() +107
Microsoft.Web.Redis.RedisConnectionWrapper..ctor(ProviderConfiguration configuration, String id) +334
Microsoft.Web.Redis.RedisSessionStateProvider.GetItemFromSessionStore(Boolean isWriteLockRequired, HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +997
Microsoft.Web.Redis.RedisSessionStateProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +128
System.Web.SessionState.SessionStateModule.GetSessionStateItem() +111
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +778
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +254
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

答:
Most probably your connection time out is very less, also set AbortOnConnectFail to false . Below code is for reference hope it helps!</p>

```<code>var config = new ConfigurationOptions()
            {
                KeepAlive = 0,
                AllowAdmin = true,
                EndPoints = { { "127.0.0.1", 6379 },{ "127.0.0.2", 6379 } },
                ConnectTimeout = 5000,
                ConnectRetry = 5,
                SyncTimeout = 5000,
                AbortOnConnectFail = false,
            };
</code>```

Title: Cannot connect to Redis Server

Body:
I have following Error when trying to run applicaiton:

It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING

RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING]
StackExchange.Redis.ConnectionMultiplexer.Connect(ConfigurationOptions  configuration, TextWriter log) in c:\TeamCity\buildAgent\work\58bc9a6df18a3782\StackExchange.Redis\StackExchange\Redis\ConnectionMultiplexer.cs:767
Microsoft.Web.Redis.StackExchangeClientConnection..ctor(ProviderConfiguration configuration) +263
Microsoft.Web.Redis.<>c__DisplayClass3.<.ctor>b__1() +26
Microsoft.Web.Redis.RedisSharedConnection.TryGetConnection() +107
Microsoft.Web.Redis.RedisConnectionWrapper..ctor(ProviderConfiguration configuration, String id) +334
Microsoft.Web.Redis.RedisSessionStateProvider.GetItemFromSessionStore(Boolean isWriteLockRequired, HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +997
Microsoft.Web.Redis.RedisSessionStateProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +128
System.Web.SessionState.SessionStateModule.GetSessionStateItem() +111
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +778
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +254
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Body:
Most probably your connection time out is very less, also set AbortOnConnectFail to false . Below code is for reference hope it helps!

var config = new ConfigurationOptions()
            {
                KeepAlive = 0,
                AllowAdmin = true,
                EndPoints = { { "127.0.0.1", 6379 },{ "127.0.0.2", 6379 } },
                ConnectTimeout = 5000,
                ConnectRetry = 5,
                SyncTimeout = 5000,
                AbortOnConnectFail = false,
            };