问:
Why don't my buttons work when going to the menu from the game after hitting escape?
I'm making a game and can't get the buttons on the menu within the main game to work once escape is pressed. The buttons on the main menu work before the main game is started, but don't once the game has run.

I tried moving about the buttons to make sure they do not overlap, but I have no clue what to do from here.

```<code>import pygame
import sys
from pygame.locals import *

pygame.init()

class Tile(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('white')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeUp(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeDown(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeLeft(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeRight(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class Collectible(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('green')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = pygame.Surface((32, 64))
        self.image.fill('red')
        self.rect = self.image.get_rect(topleft = pos)
        self.direction = pygame.math.Vector2(0, 0)
        self.speed = 7.5
        self.gravity = 0.1
        self.jump_speed = -1
        self.isJump = False
        self.alive = True

    def movement(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_d] and keys[pygame.K_LSHIFT]:
            self.direction.x = 5
        elif keys[pygame.K_a] and keys[pygame.K_LSHIFT]:
            self.direction.x = -5
        elif keys[pygame.K_d]:
            self.direction.x = 1
        elif keys[pygame.K_a]:
            self.direction.x = -1
        else:
            self.direction.x = 0
        if keys[pygame.K_SPACE] or keys[K_w]:
            self.jump()

    def jump(self):
        if self.colliding:
            self.direction.y = -2
            self.colliding = False

    def grav(self):
        self.direction.y += self.gravity
        self.rect.y += self.direction.y

    def update(self):
        self.movement()
        self.grav()

class Button():
    def __init__(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.clicked = False

    def draw(self, surface):
        action = False
        #get mouse position
        pos = pygame.mouse.get_pos()
        #check mouseover and clicked conditions
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True
        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False
        #draw button on screen
        surface.blit(self.image, (self.rect.x, self.rect.y))
        return action

class World:
    def __init__(self, game_map, surface):
        self.display_surface = surface
        self.setup_world(game_map)
        self.world_shift = 0

    def setup_world(self, game_map):
        self.tiles = pygame.sprite.Group()
        self.collectibles = pygame.sprite.Group()
        self.player = pygame.sprite.GroupSingle()
        self.spikes = pygame.sprite.Group()
        for row_num, row in enumerate(game_map):
            for column_num, block in enumerate(row):
                x = column_num * tile_size
                y = row_num * tile_size
                if block == 'X':
                    tile = Tile((x, y), tile_size)
                    self.tiles.add(tile)
                if block == 'C':
                    tile = Collectible((x, y), tile_size)
                    self.collectibles.add(tile)
                if block == 'P':
                    tile = Player((x, y))
                    self.player.add(tile)
                if block == 'U':
                    tile = SpikeUp((x, y), tile_size)
                    self.spikes.add(tile)
                if block == 'D':
                    tile = SpikeDown((x, y), tile_size)
                    self.spikes.add(tile)
                if block == 'L':
                    tile = SpikeLeft((x, y), tile_size)
                    self.spikes.add(tile)
                if block == 'R':
                    tile = SpikeRight((x, y), tile_size)
                    self.spikes.add(tile)

    def scroll_y(self):
        player = self.player.sprite
        player_y = player.rect.centery
        direction_y = player.direction.y

        if player_y < 200 and direction_y < 0:
            self.world_shift = 7.5
            player.speed = 0
        elif player_y > 600 and direction_y > 0:
            self.world_shift = -7.5
            player.speed = 0
        else:
            self.world_shift = 0
            player.speed = 7.5

    def h_move_collision(self):
        player = self.player.sprite
        player.rect.x += player.direction.x * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.x < 0:
                    player.rect.left = sprite.rect.right
                elif player.direction.x > 0:
                    player.rect.right = sprite.rect.left

    def v_move_collision(self):
        player = self.player.sprite
        player.rect.y += player.direction.y * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.y > 0:
                    player.direction.y = 0
                    player.rect.bottom = sprite.rect.top
                    player.colliding = True
                elif player.direction.y < 0:
                    player.rect.top = sprite.rect.bottom
                    player.direction.y = 0

    def spike_collision(self):
        player = self.player.sprite

        for sprite in self.spikes.sprites():
            if sprite.rect.colliderect(player.rect):
                print("Death")
                player.alive = False

    def collectible_collision(self):
        player = self.player.sprite

        for sprite in self.collectibles.sprites():
            if sprite.rect.colliderect(player.rect):
                print("Collected")

    def run(self):
        screen.fill('black')

        #level
        self.tiles.update(self.world_shift)
        self.tiles.draw(self.display_surface)
        self.collectibles.update(self.world_shift)
        self.collectibles.draw(self.display_surface)
        self.spikes.update(self.world_shift)
        self.spikes.draw(self.display_surface)
        self.scroll_y()

        #player
        self.h_move_collision()
        self.v_move_collision()
        self.spike_collision()
        self.collectible_collision()
        self.player.update()
        self.player.draw(self.display_surface)

        pygame.display.update()

font = pygame.font.SysFont("arialblack", 40)
tile_size = 64

game_map = ['----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '---------------',
            '----------------',
            '--P-U-D-L-R-C-X-',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX'
           ]

screen_width = len(game_map[0]) * tile_size
screen_height = 800

screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
world = World(game_map, screen)

resume_img = pygame.image.load("button_resume.png").convert_alpha()
quit_img = pygame.image.load("button_quit.png").convert_alpha()
play_img = pygame.image.load('button_play.png').convert_alpha()

resume_button = Button(250, screen_height/2, resume_img, 1)
quit_button = Button(screen_width - 350, screen_height/2, quit_img, 1)
play_button = Button(250, screen_height/2, play_img, 1)

state = 'starting'
keys = pygame.key.get_pressed()
run = True
while run == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    clock.tick(60)

    if state == 'starting':
        if play_button.draw(screen):
            print('play clicked')
            state = 'main'
            screen.fill('black')
        if quit_button.draw(screen):
            pygame.quit()
            sys.exit()

    if state == 'main':
        world.run()
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    state = 'menu'
                    screen.fill('black')
                    if quit_button.draw(screen):
                        print('quit pressed')
                        pygame.quit()
                        sys.exit()
                    if resume_button.draw(screen):
                        print('resume pressed')
                        state = 'main'
</code>```

Body:
I'm making a game and can't get the buttons on the menu within the main game to work once escape is pressed. The buttons on the main menu work before the main game is started, but don't once the game has run.

I tried moving about the buttons to make sure they do not overlap, but I have no clue what to do from here.

import pygame
import sys
from pygame.locals import *

pygame.init()

class Tile(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('white')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeUp(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeDown(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeLeft(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class SpikeRight(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('blue')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class Collectible(pygame.sprite.Sprite):
    def __init__(self, pos, size):
        super().__init__()
        self.image = pygame.Surface((size, size))
        self.image.fill('green')
        self.rect = self.image.get_rect(topleft = pos)

    def update(self, y_shift):
        self.rect.y += y_shift

class Player(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = pygame.Surface((32, 64))
        self.image.fill('red')
        self.rect = self.image.get_rect(topleft = pos)
        self.direction = pygame.math.Vector2(0, 0)
        self.speed = 7.5
        self.gravity = 0.1
        self.jump_speed = -1
        self.isJump = False
        self.alive = True

    def movement(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_d] and keys[pygame.K_LSHIFT]:
            self.direction.x = 5
        elif keys[pygame.K_a] and keys[pygame.K_LSHIFT]:
            self.direction.x = -5
        elif keys[pygame.K_d]:
            self.direction.x = 1
        elif keys[pygame.K_a]:
            self.direction.x = -1
        else:
            self.direction.x = 0
        if keys[pygame.K_SPACE] or keys[K_w]:
            self.jump()

    def jump(self):
        if self.colliding:
            self.direction.y = -2
            self.colliding = False

    def grav(self):
        self.direction.y += self.gravity
        self.rect.y += self.direction.y

    def update(self):
        self.movement()
        self.grav()

class Button():
    def __init__(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.clicked = False

    def draw(self, surface):
        action = False
        #get mouse position
        pos = pygame.mouse.get_pos()
        #check mouseover and clicked conditions
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True
        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False
        #draw button on screen
        surface.blit(self.image, (self.rect.x, self.rect.y))
        return action

class World:
    def __init__(self, game_map, surface):
        self.display_surface = surface
        self.setup_world(game_map)
        self.world_shift = 0

    def setup_world(self, game_map):
        self.tiles = pygame.sprite.Group()
        self.collectibles = pygame.sprite.Group()
        self.player = pygame.sprite.GroupSingle()
        self.spikes = pygame.sprite.Group()
        for row_num, row in enumerate(game_map):
            for column_num, block in enumerate(row):
                x = column_num * tile_size
                y = row_num * tile_size
                if block == 'X':
                    tile = Tile((x, y), tile_size)
                    self.tiles.add(tile)
                if block == 'C':
                    tile = Collectible((x, y), tile_size)
                    self.collectibles.add(tile)
                if block == 'P':
                    tile = Player((x, y))
                    self.player.add(tile)
                if block == 'U':
                    tile = SpikeUp((x, y), tile_size)
                    self.spikes.add(tile)
                if block == 'D':
                    tile = SpikeDown((x, y), tile_size)
                    self.spikes.add(tile)
                if block == 'L':
                    tile = SpikeLeft((x, y), tile_size)
                    self.spikes.add(tile)
                if block == 'R':
                    tile = SpikeRight((x, y), tile_size)
                    self.spikes.add(tile)

    def scroll_y(self):
        player = self.player.sprite
        player_y = player.rect.centery
        direction_y = player.direction.y

        if player_y < 200 and direction_y < 0:
            self.world_shift = 7.5
            player.speed = 0
        elif player_y > 600 and direction_y > 0:
            self.world_shift = -7.5
            player.speed = 0
        else:
            self.world_shift = 0
            player.speed = 7.5

    def h_move_collision(self):
        player = self.player.sprite
        player.rect.x += player.direction.x * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.x < 0:
                    player.rect.left = sprite.rect.right
                elif player.direction.x > 0:
                    player.rect.right = sprite.rect.left

    def v_move_collision(self):
        player = self.player.sprite
        player.rect.y += player.direction.y * player.speed

        for sprite in self.tiles.sprites():
            if sprite.rect.colliderect(player.rect):
                if player.direction.y > 0:
                    player.direction.y = 0
                    player.rect.bottom = sprite.rect.top
                    player.colliding = True
                elif player.direction.y < 0:
                    player.rect.top = sprite.rect.bottom
                    player.direction.y = 0

    def spike_collision(self):
        player = self.player.sprite

        for sprite in self.spikes.sprites():
            if sprite.rect.colliderect(player.rect):
                print("Death")
                player.alive = False

    def collectible_collision(self):
        player = self.player.sprite

        for sprite in self.collectibles.sprites():
            if sprite.rect.colliderect(player.rect):
                print("Collected")

    def run(self):
        screen.fill('black')

        #level
        self.tiles.update(self.world_shift)
        self.tiles.draw(self.display_surface)
        self.collectibles.update(self.world_shift)
        self.collectibles.draw(self.display_surface)
        self.spikes.update(self.world_shift)
        self.spikes.draw(self.display_surface)
        self.scroll_y()

        #player
        self.h_move_collision()
        self.v_move_collision()
        self.spike_collision()
        self.collectible_collision()
        self.player.update()
        self.player.draw(self.display_surface)

        pygame.display.update()

font = pygame.font.SysFont("arialblack", 40)
tile_size = 64

game_map = ['----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '----------------',
            '---------------',
            '----------------',
            '--P-U-D-L-R-C-X-',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX',
            'XXXXXXXXXXXXXXXX'
           ]

screen_width = len(game_map[0]) * tile_size
screen_height = 800

screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
world = World(game_map, screen)

resume_img = pygame.image.load("button_resume.png").convert_alpha()
quit_img = pygame.image.load("button_quit.png").convert_alpha()
play_img = pygame.image.load('button_play.png').convert_alpha()

resume_button = Button(250, screen_height/2, resume_img, 1)
quit_button = Button(screen_width - 350, screen_height/2, quit_img, 1)
play_button = Button(250, screen_height/2, play_img, 1)

state = 'starting'
keys = pygame.key.get_pressed()
run = True
while run == True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    clock.tick(60)

    if state == 'starting':
        if play_button.draw(screen):
            print('play clicked')
            state = 'main'
            screen.fill('black')
        if quit_button.draw(screen):
            pygame.quit()
            sys.exit()

    if state == 'main':
        world.run()
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    state = 'menu'
                    screen.fill('black')
                    if quit_button.draw(screen):
                        print('quit pressed')
                        pygame.quit()
                        sys.exit()
                    if resume_button.draw(screen):
                        print('resume pressed')
                        state = 'main'


来源: stackexchange

问:
php spark serve Uncaught Error: Call to undefined function CodeIgniter\CLI\mb_strpos()
I'm new to PHP and trying to open the CodeIgniter 4 welcome page by using localhost (I don't have any server programs like XAMPP since it's a company computer and PHP works fine with its built-in server.)

When I try to run the command: php spark serve on the terminal, it gives an error like this:

```<code>Uncaught Error: Call to undefined function CodeIgniter\CLI\mb_strpos() in C:\Users\50290536\Desktop\php-test\system\CLI\CLI.php:776

</code>```

I enabled the necessary extensions in the php.ini file and the file: php_mbstring.dll is available in the directory php/ext.

I also tried to run the command: php spark to see if spark works fine but in that case, I got the following error:

```<code>The framework needs the following extension(s) installed and loaded: curl, intl, mbstring at SYSTEMPATH\Codeigniter.php:224
</code>```

All these extensions are enabled in the php.ini file and their respective .dll files are available in the directory php/ext.

Details:

PHP version: v8.2

CodeIgniter 4 framework version: v4.2.10

Currently enabled PHP modules after running the command: php -m

```<code>bcmath
calendar
Core
ctype
date
dom
filter
hash
iconv
json
libxml
mysqlnd
pcre
PDO
Phar
random
readline
Reflection
session
SimpleXML
SPL
standard
tokenizer
xml
xmlreader
xmlwriter
zlib
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to PHP and trying to open the CodeIgniter 4 welcome page by using localhost (I don't have any server programs like XAMPP since it's a company computer and PHP works fine with its built-in server.)

When I try to run the command: php spark serve on the terminal, it gives an error like this:

Uncaught Error: Call to undefined function CodeIgniter\CLI\mb_strpos() in C:\Users\50290536\Desktop\php-test\system\CLI\CLI.php:776

I enabled the necessary extensions in the php.ini file and the file: php_mbstring.dll is available in the directory php/ext.

I also tried to run the command: php spark to see if spark works fine but in that case, I got the following error:

The framework needs the following extension(s) installed and loaded: curl, intl, mbstring at SYSTEMPATH\Codeigniter.php:224

All these extensions are enabled in the php.ini file and their respective .dll files are available in the directory php/ext.

Details:

PHP version: v8.2

CodeIgniter 4 framework version: v4.2.10

Currently enabled PHP modules after running the command: php -m

bcmath
calendar
Core
ctype
date
dom
filter
hash
iconv
json
libxml
mysqlnd
pcre
PDO
Phar
random
readline
Reflection
session
SimpleXML
SPL
standard
tokenizer
xml
xmlreader
xmlwriter
zlib


问:
Vue js routers?
I have passed an object to a component and i want to display it with vue js router by passing params.

I made routers but i'm stuck in by passing params to check id. if id is true then display the object data in dom.

Title: Vue js routers?


问:
SwiftUI - iOS 16 - Using Binding with NavigationStack
I have following View Structure e.g.: Root View -> Detail View -> Edit View -> Detail Edit View

So the user can use a NavigationLink with (value: ...) to get to the next view.

How do I pass a Binding from Edit View to Detail Edit View? With the old NavigationView & -Link there wasn't a problem but now the Root View uses .navigationDestination to call each View an here of course I don't have access to the @States from Edit View.

My current workaround:
I'm creating a ObservableObject with a singleton and pass the @State from Edit View on init() call. From there on I'm working with the ObservableObject attribute (in Edit View & Detail Edit View)


问:
Flask Response when using get_json is not working
I'm using the Flask 'Response' function to stream-download a zip file. If I add the zip file from the same route as the Response function is called, the file download works fine. However, if I'm letting the user select files from a datatable and then fetch the selected file names in javascript and send it back to the flask route via ajax it does not work.

```<code>@app.route('/myLandingRoute/', methods=['POST'])
def myLandingRoute():
  if request.method == 'POST':
    if request.form.get('btDownload1') == 'Download1':
      zs = ZipStream()
      name = os.path.basename(os.path.abspath('/TestOnC'))
      sFullPath = 'C:/DlTest/TestOnC/A_File.txt'
      sRelPath = 'A_File.txt'
      zs.add_path(sFullPath, sRelPath)
      return Response(
        zs,
        mimetype="application/zip",
        headers={
          "Content-Disposition": f"attachment; filename={name}.zip",
          "Last-Modified": zs.last_modified,
        }
      )
  return render_template('myFiles.html',)
</code>```

The difference is that in the working case, the html button, being a '<input type="submit" ...' control is calling the same 'landing' route that renders all the controls the first time. While the button that is used for the datatable selected files is first calling a javascript function before calling a 'download_selected_files' route via ajax.

In this code the download button is first calling a javascript function that make a list of the files that have been selected in the datatable. The jsonified list is then sent via ajax to the 'download_selected_files' route. In the route I'm able to fetch the selected files returned from ajax, and generate the paths to correspond the correct placement on the server disk, but now the Reponse function does not download the zipped file.

```<code>@app.route('/my_download_selected_files/', methods=['POST'])
def my_download_selected_files():
  if request.method == 'POST':
    objJson = myFlaskRequest.get_json()
    arrFileNames = objJson["File_Names"]
    zs = ZipStream()
    for sFileName in arrFileNames:
      sPathAndFile = os.path.join(session['sPath'], sFileName)
      sName = os.path.basename(os.path.abspath(sPathAndFile ))
      zs.add_path(sPathAndFile , session['sPath'])
      return Response(
        zs,
        mimetype="application/zip",
        headers={
          "Content-Disposition": f"attachment; filename={sName}.zip",
          "Last-Modified": zs.last_modified,
        }
      )
  return jsonify({"bErr": False})
</code>```

I've also tried to let ajax call in the javascript funtion call the 'myLandingRoute' instead of the 'my_download_selected_files' route. But when I'm doing that I'm not able to find the json object, with the list of files, in the request dict. While when I send to the 'my_download_selected_files' route it is there. I've looked for it in the form part of the request dict, but could not find it there either. Running out of good ideas what to try to get this to run. Greately appreciated if anybody can point me onto the good track.

Body:
I'm using the Flask 'Response' function to stream-download a zip file. If I add the zip file from the same route as the Response function is called, the file download works fine. However, if I'm letting the user select files from a datatable and then fetch the selected file names in javascript and send it back to the flask route via ajax it does not work.

@app.route('/myLandingRoute/', methods=['POST'])
def myLandingRoute():
  if request.method == 'POST':
    if request.form.get('btDownload1') == 'Download1':
      zs = ZipStream()
      name = os.path.basename(os.path.abspath('/TestOnC'))
      sFullPath = 'C:/DlTest/TestOnC/A_File.txt'
      sRelPath = 'A_File.txt'
      zs.add_path(sFullPath, sRelPath)
      return Response(
        zs,
        mimetype="application/zip",
        headers={
          "Content-Disposition": f"attachment; filename={name}.zip",
          "Last-Modified": zs.last_modified,
        }
      )
  return render_template('myFiles.html',)

The difference is that in the working case, the html button, being a '<input type="submit" ...' control is calling the same 'landing' route that renders all the controls the first time. While the button that is used for the datatable selected files is first calling a javascript function before calling a 'download_selected_files' route via ajax.

In this code the download button is first calling a javascript function that make a list of the files that have been selected in the datatable. The jsonified list is then sent via ajax to the 'download_selected_files' route. In the route I'm able to fetch the selected files returned from ajax, and generate the paths to correspond the correct placement on the server disk, but now the Reponse function does not download the zipped file.

@app.route('/my_download_selected_files/', methods=['POST'])
def my_download_selected_files():
  if request.method == 'POST':
    objJson = myFlaskRequest.get_json()
    arrFileNames = objJson["File_Names"]
    zs = ZipStream()
    for sFileName in arrFileNames:
      sPathAndFile = os.path.join(session['sPath'], sFileName)
      sName = os.path.basename(os.path.abspath(sPathAndFile ))
      zs.add_path(sPathAndFile , session['sPath'])
      return Response(
        zs,
        mimetype="application/zip",
        headers={
          "Content-Disposition": f"attachment; filename={sName}.zip",
          "Last-Modified": zs.last_modified,
        }
      )
  return jsonify({"bErr": False})

I've also tried to let ajax call in the javascript funtion call the 'myLandingRoute' instead of the 'my_download_selected_files' route. But when I'm doing that I'm not able to find the json object, with the list of files, in the request dict. While when I send to the 'my_download_selected_files' route it is there. I've looked for it in the form part of the request dict, but could not find it there either. Running out of good ideas what to try to get this to run. Greately appreciated if anybody can point me onto the good track.


问:
Scrolling text in Bootstrap & CSS
I am coding a website in Django and I am using Bootstrap as a CSS-framework. This is the hero section of my site:

.hero {
  background: url('/static/bwm/BWM_red.png');
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hero vh-100 d-flex align-items-center">
  <div class="container">
    <p class="display-4 text-danger" data-aos="fade-up" data-aos-delay="150">
      <strong>Brussels Weekend Munch</strong>
    </p>
    <p class="display-6 text-danger" data-aos="fade-up" data-aos-delay="250">
      <strong>Every Second Saturday of the month!</strong>
    </p>
    <h4 class="text-danger" data-aos="fade-up" data-aos-delay="150">
      <strong>Feel right at home exploring life/identity/relationships at the Brussels Weekend Munch.</strong>
    </h4>
  </div>
</div></code>```

I need the words life/identity/relationships to replace each other in a vertical scrolling way. So the site displays life. Then the word life scrolls down and "identity" scrolls down and takes its place in the sentence etc...

I found a few examples of this on the web, but I fail to translate this code to my site without messing up my layout. How can I code this in CSS?

Thanks in advance!

Jo

Title: Scrolling text in Bootstrap & CSS

Body:
I am coding a website in Django and I am using Bootstrap as a CSS-framework. This is the hero section of my site:

.hero {
  background: url('/static/bwm/BWM_red.png');
  background-position: center;
  background-size: cover;
  background-attachment: fixed;
  align-items: center;
}

      Brussels Weekend Munch

      Every Second Saturday of the month!

      Feel right at home exploring life/identity/relationships at the Brussels Weekend Munch.

I need the words life/identity/relationships to replace each other in a vertical scrolling way. So the site displays life. Then the word life scrolls down and "identity" scrolls down and takes its place in the sentence etc...

I found a few examples of this on the web, but I fail to translate this code to my site without messing up my layout. How can I code this in CSS?

Thanks in advance!

Jo


问:
Sign In into website before opening the workbook from that site using VBA
I want to open an excel workbook containing JIRA information from a URL. It works just fine, it opens the file I wanted but the thing is that my company has a step verification with our smart phone to log in.

So, since I haven't log in into the JIRA platform, the file it opens shows there is no data, so I need to log in first for the workbook to show data.

I don't know how Excel opens a workbook. I tried to log in from all my browsers and it doesn't work. I tried manually and it should bring something. Any ideas?
Here is the code I'm using:

```<code>Dim targetWB As Workbook
targetWB = Globals.ThisAddIn.Application.Workbooks.Open("https://mapopsjira.company.com/sr/jira.issueviews:searchrequest-excel-current-fields/temp/SearchRequest.xls?jqlQuery=SQLQuery")

        If targetWB.Sheets(1).Range("A5").Value = "No Issues Found" Then
            targetWB.Close(False)
            MsgBox("No Issues were found, please try again later or Sign in first", vbInformation)
            GoTo EndOfCode
        End If
</code>```

Body:
I want to open an excel workbook containing JIRA information from a URL. It works just fine, it opens the file I wanted but the thing is that my company has a step verification with our smart phone to log in.

So, since I haven't log in into the JIRA platform, the file it opens shows there is no data, so I need to log in first for the workbook to show data.

I don't know how Excel opens a workbook. I tried to log in from all my browsers and it doesn't work. I tried manually and it should bring something. Any ideas?
Here is the code I'm using:

Dim targetWB As Workbook
targetWB = Globals.ThisAddIn.Application.Workbooks.Open("https://mapopsjira.company.com/sr/jira.issueviews:searchrequest-excel-current-fields/temp/SearchRequest.xls?jqlQuery=SQLQuery")

        If targetWB.Sheets(1).Range("A5").Value = "No Issues Found" Then
            targetWB.Close(False)
            MsgBox("No Issues were found, please try again later or Sign in first", vbInformation)
            GoTo EndOfCode
        End If


问:
Manipulate pixel data to smooth an image (avoiding: "imageSmoothingQuality") working in chrome but not in firefox
I want to compress a base64 image to 100px and then smoothen it to make it look better.

I understand that imageSmoothingQuality does not work in firefox.

With the help of ChatGPT I have written a method to manipulate the pixels of the image directly to achieve a smoothing effect.

For some reason the smoothing works in chrome but not in firefox. Any idea why?

```<code>//this function compresses a base64 image to a given max height and width, it also keeps the aspect ratio
  // if the given size is 100px it will also smoothen the pixels of the image to make it look better
  compressImage(image: string, size: number) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.src = image;
    var MAX_WIDTH = size;
    var MAX_HEIGHT = size;
    var width = img.width;
    var height = img.height;

    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }
    canvas.width = width;
    canvas.height = height;

    if (size === 100) {
      // this smoothes the pixels of the image to make it look better
      // ctx!.imageSmoothingEnabled = true;
      // ctx!.imageSmoothingQuality = 'high';
      //imageSmoothingQuality is not supported in firefox, so we use the following code to smooth the image. The results are identical!
      // for unknown reasons the following code alsoe doesn't work in firefox :(

      // Get the pixel data of the image on the canvas
      var imageData = ctx?.getImageData(0, 0, canvas.width, canvas.height);

      // Manipulate the pixel data to smooth the image
      // Loop through the rows of pixels in the image
      if (imageData != null) {
        for (var y = 0; y < imageData.height; y++) {
          // Loop through the columns of pixels in the image
          for (var x = 0; x < imageData.width; x++) {
            // Get the index of the current pixel in the pixel data array
            var index = (y * imageData.width + x) * 4;

            // Get the red, green, blue, and alpha values of the current pixel
            var r = imageData.data[index];
            var g = imageData.data[index + 1];
            var b = imageData.data[index + 2];
            var a = imageData.data[index + 3];

            // Calculate the average of the red, green, and blue values
            var avg = (r + g + b) / 3;

            // Set the red, green, and blue values of the current pixel to the average value
            imageData.data[index] = avg;
            imageData.data[index + 1] = avg;
            imageData.data[index + 2] = avg;
          }
        }
        // Draw the modified pixel data back onto the canvas
        ctx!.putImageData(imageData, 0, 0);
      }
    }

    ctx?.drawImage(img, 0, 0, width, height);
    return canvas.toDataURL('image/png');
  }
</code>```

Body:
I want to compress a base64 image to 100px and then smoothen it to make it look better.

I understand that imageSmoothingQuality does not work in firefox.

With the help of ChatGPT I have written a method to manipulate the pixels of the image directly to achieve a smoothing effect.

For some reason the smoothing works in chrome but not in firefox. Any idea why?

//this function compresses a base64 image to a given max height and width, it also keeps the aspect ratio
  // if the given size is 100px it will also smoothen the pixels of the image to make it look better
  compressImage(image: string, size: number) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.src = image;
    var MAX_WIDTH = size;
    var MAX_HEIGHT = size;
    var width = img.width;
    var height = img.height;

    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }
    canvas.width = width;
    canvas.height = height;

    if (size === 100) {
      // this smoothes the pixels of the image to make it look better
      // ctx!.imageSmoothingEnabled = true;
      // ctx!.imageSmoothingQuality = 'high';
      //imageSmoothingQuality is not supported in firefox, so we use the following code to smooth the image. The results are identical!
      // for unknown reasons the following code alsoe doesn't work in firefox :(

      // Get the pixel data of the image on the canvas
      var imageData = ctx?.getImageData(0, 0, canvas.width, canvas.height);

      // Manipulate the pixel data to smooth the image
      // Loop through the rows of pixels in the image
      if (imageData != null) {
        for (var y = 0; y < imageData.height; y++) {
          // Loop through the columns of pixels in the image
          for (var x = 0; x < imageData.width; x++) {
            // Get the index of the current pixel in the pixel data array
            var index = (y * imageData.width + x) * 4;

            // Get the red, green, blue, and alpha values of the current pixel
            var r = imageData.data[index];
            var g = imageData.data[index + 1];
            var b = imageData.data[index + 2];
            var a = imageData.data[index + 3];

            // Calculate the average of the red, green, and blue values
            var avg = (r + g + b) / 3;

            // Set the red, green, and blue values of the current pixel to the average value
            imageData.data[index] = avg;
            imageData.data[index + 1] = avg;
            imageData.data[index + 2] = avg;
          }
        }
        // Draw the modified pixel data back onto the canvas
        ctx!.putImageData(imageData, 0, 0);
      }
    }

    ctx?.drawImage(img, 0, 0, width, height);
    return canvas.toDataURL('image/png');
  }


问:
Set the location and visibility of a card in Flet
I am making a website in Flet.
There is a button in the appbar:

loginbutton = ft.TextButton(text = "Login", on_click=login, tooltip = "Login with your API key")
```
<p>and a card:</p>
<pre class="lang-py prettyprint-override"><code>card = ft.Card(content=ft.Text("This is a login card"), width = 400)
</code>```

And I want to make it like:
Not real (a bit like the dropdown menu)

The login card will appear near the login button once the button is clicked, and disappear if the mouse clicked places other than the button and the card. How am I able to do this?

Body:
I am making a website in Flet.
There is a button in the appbar:

loginbutton = ft.TextButton(text = "Login", on_click=login, tooltip = "Login with your API key")

and a card:

card = ft.Card(content=ft.Text("This is a login card"), width = 400)

And I want to make it like:
Not real (a bit like the dropdown menu)

The login card will appear near the login button once the button is clicked, and disappear if the mouse clicked places other than the button and the card. How am I able to do this?


问:
kubernetes configMapRef merge issue
Why kubernetes merge config maps?
I have deployment config

```<code>---
apiVersion: apps/v1
kind: Deployment
...
    spec:
      containers:
            - configMapRef:
                name: **testa**-env
</code>```

My config map testa-env looks

```<code>apiVersion: v1
kind: ConfigMap
data:
  AAAA: testA
</code>```

Also i have another deployment in same namespace with config map BBB: testB
Then i go to my pods and make export and see that configs has been merged?! On podA i see both configs

```<code>podA> export

AAAA: testA
BBBB: testB
</code>```

Also looks output on pod B.
So another developer can steal all config not for his project!
I have been rechecked this on 3 different clusters and have same result

Title: kubernetes configMapRef merge issue

Body:
Why kubernetes merge config maps?
I have deployment config

---
apiVersion: apps/v1
kind: Deployment
...
    spec:
      containers:
            - configMapRef:
                name: **testa**-env

My config map testa-env looks

apiVersion: v1
kind: ConfigMap
data:
  AAAA: testA

Also i have another deployment in same namespace with config map BBB: testB
Then i go to my pods and make export and see that configs has been merged?! On podA i see both configs

podA> export

AAAA: testA
BBBB: testB

Also looks output on pod B.
So another developer can steal all config not for his project!
I have been rechecked this on 3 different clusters and have same result


问:
Tailwind Css Responsive Class Not Working
enter image description here
I am Adding Tailwind Responsive Class's But it's not working.

This is my Build Script.
enter image description here

I run => npm run build but it's not working.
It shows me this
enter image description here

Is there any solution?

navbar responsiveeee


问:
How can I automatically re-scale a rectangular image after rotating with Jetpack Compose?
In my app, users can take pictures vertically or horizontally, and may want to rotate the image after taking it. To solve this, we have a rotate feature in-app that they can use to modify the image.

The issue with this, is that, when rotating, the image could be cut-off on each side. (see pictures)

Before rotating:

After rotating:

When paging, you can see the image stretching beyond its own screen:

Here is the code I have so far. The modifier is going to an Image composable in ImageZoomView.

```<code>val rotationAnim by animateFloatAsState(
    targetValue = viewModel.slides[page].rotation.value.toFloat(),
    animationSpec = tween(durationMillis = 200, easing = FastOutLinearInEasing)
)

Column(
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    ImageZoomView(
        modifier = Modifier
            .rotate(rotationAnim)
            .weight(1f),
        bitmap = bmp,
        zoomable = viewModel.zoomable.value
    )
}
</code>```

The weight(1f) part of the Modifier is automatically scaling the image when the page loads, but this never gets re-calculated when the rotation takes place.

Some things I've tried to no avail:

Set the weight to a mutable state, and then overwrite it whenever rotation changes.

Move rotate to the parent Column

Skip the animation

Loading with the rotation hard-coded to 90 also cuts off the edges exactly the same as the screenshots.

Body:
In my app, users can take pictures vertically or horizontally, and may want to rotate the image after taking it. To solve this, we have a rotate feature in-app that they can use to modify the image.

The issue with this, is that, when rotating, the image could be cut-off on each side. (see pictures)

Before rotating:

After rotating:

When paging, you can see the image stretching beyond its own screen:

Here is the code I have so far. The modifier is going to an Image composable in ImageZoomView.

val rotationAnim by animateFloatAsState(
    targetValue = viewModel.slides[page].rotation.value.toFloat(),
    animationSpec = tween(durationMillis = 200, easing = FastOutLinearInEasing)
)

Column(
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    ImageZoomView(
        modifier = Modifier
            .rotate(rotationAnim)
            .weight(1f),
        bitmap = bmp,
        zoomable = viewModel.zoomable.value
    )
}

The weight(1f) part of the Modifier is automatically scaling the image when the page loads, but this never gets re-calculated when the rotation takes place.

Some things I've tried to no avail:

Set the weight to a mutable state, and then overwrite it whenever rotation changes.

Move rotate to the parent Column

Skip the animation

Loading with the rotation hard-coded to 90 also cuts off the edges exactly the same as the screenshots.


问:
How to create button menu?
recently started getting acquainted with "Bot UI Kit”, and here I got the question of how to create a pagination for embed. Yes, I found on the Internet how to make the contents of the embed, but for my tasks it is necessary that the content does not change, but change View(namely select menu).

That is, when moving to the next page in the pagination, changes discord.SelectOption. Here is the code I use to reflect this interaction that the picture[guthub]:

@app_commands.command()
async def menu(self, interaction: discord.Integration):
    menu = Select(
        placeholder='Choose something...',
        options=[
            discord.SelectOption(
                label='label1',
                value='1',
                emoji='<:emoji:1052662876948668436>'
            ),
            discord.SelectOption(
                label='Label2',
                value='2',
                emoji='<:sucrose:1052662935845085214>'
            )
    ]
    )

    first_page = Button(
        emoji='⬅',
        style=discord.ButtonStyle.blurple,
        disabled=True
    )
    pervision_page = Button(
        emoji='⏮',
        style=discord.ButtonStyle.green,
        disabled=True
    )
    next_page = Button(
        emoji='⏭',
        style=discord.ButtonStyle.green
                        )
    last_page = Button(
        emoji='➡',
        style=discord.ButtonStyle.blurple
    )

    view = View()
    view.add_item(menu)
    view.add_item(first_page)
    view.add_item(pervision_page)
    view.add_item(next_page)
    view.add_item(last_page)

    await interaction.response.send_message(embed=embed, view=view)
```

Title: How to create button menu?


问:
older version of flutter plugins that compatible with SDK 31
I just finished developing an app but when I compile to apk the following error appear

Warning: The plugin geolocator_android requires Android SDK version 33.
For more information about build configuration, see https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
Warning: The plugin google_api_headers requires Android SDK version 32.
For more information about build configuration, see https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
Warning: The plugin url_launcher_android requires Android SDK version 33.
For more information about build configuration, see https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.

my plugins at pubspec.yaml:

Any recommendation to rollback these 3 problematic plugin version that fits SDK 31?

Thanks.


问:
need help in usps integration for my laravel project
i have searched alot in internet and didnt find out any proper documentations for usps means they only provide few services like:

Rate Calculator (Both domestic and international)
Zip code lookup by address
City/State lookup by zip code
Verify address
Create Priority Shipping Labels
Create Open & Distribute Shipping Labels
Create International Shipping Labels (Express, Priority, First Class)
Service Delivery Calculator
Confirm Tracking

but how could i integrate but proper shipping using usps apis and the label printing and then tracking api for that shipments


问:
VBA for FrontPage
As a learning exercise and to do something productive, I decided to write a VBA macro for one of my "very old" FrontPage websites.  Actually I'm in the process of trying to escape from FrontPage(FP)...

This seemingly simple project, I am familiar with VBA for Excel and Access, was to open a series of current web pages in FP and save them to a different folder so I could begin to remove all of the FP stuff without affecting the working parts of the website.

I Google-ed "FrontPage" and "VBA" extensively but there seems to be a dearth of useful information out there.  Any references I did find pointed to pages/sites that are no longer active.  So I muddled along with what information I did find and this is the result:

```<code>Sub OpenAndSaveAsPages()
Dim objPageWindow As PageWindowEx
Dim objFileOpen As FileDialog
Dim strFolder As String
Dim strFile As Variant
Dim intCount As Integer
Dim strURL As String
'File Open dialog object.
Set objFileOpen = FrontPage.Application.FileDialog(msoFileDialogOpen)
'startup folder default is the root folder of the active Web site
strFolder = ActiveWeb.RootFolder
' clean up unwanted stuff in the URL
strFolder = Replace(strFolder, "file:///", "")
strFolder = Replace(strFolder, "/", "\")
objFileOpen.InitialFileName = strFolder
If objFileOpen.Show < 0 Then
    For Each strFile In objFileOpen.SelectedItems
' Open web file in FP
        ActiveWebWindow.PageWindows.Add strFile
' at this point all I wanted to do was a SAVEAS to save the file to a different folder
' so I wanted to do something like below but could not figure it out
'           objPageWindow.SaveAs objPageWindow.Document.Url
    Next
End If
' Now all the selected file are open in FrontPage and I will iterate through them
For Each objPageWindow In ActiveWebWindow.PageWindows
' the URL for the currently select page
    strURL = objPageWindow.Document.Url
' probably some extra work here to change the URL to a different folder and filename
    strURL = Replace(strURL, Mid(strURL, InStrRev(strURL, ".", Len(strURL)), Len(strURL) + 1 - InStrRev(strURL, ".", Len(strURL))), Mid(strURL, InStrRev(strURL, ".", Len(strURL)), Len(strURL) + 1 - InStrRev(strURL, ".", Len(strURL))), 1)
    strURL = Replace(strURL, Left(strURL, InStrRev(strURL, "/", Len(strURL))), Left(strURL, InStrRev(strURL, "/", Len(strURL))) & "temp/", 1)
    objPageWindow.SaveAs strURL
    objPageWindow.Close
Next
End Sub
</code>```

OK, it works but for sure it is probably not the most efficient and for sure not elegant.

So, my questions are:

are there and good references for FP VBA that you can recommend (I'm not a professional programmer, just someone that like to ...).  I work well in using examples to achieve and  learn.

Can someone sharpen up my code, with explanations, of course.

Note, I'm not trying to write any code to actually modify the code in these pages.  I may get to that, but for now it appears that a "SAVEAS" results in code which is already fairly clean of the FP stuff.

Many thanks....RDK

Title: VBA for FrontPage

Body:
As a learning exercise and to do something productive, I decided to write a VBA macro for one of my "very old" FrontPage websites.  Actually I'm in the process of trying to escape from FrontPage(FP)...

This seemingly simple project, I am familiar with VBA for Excel and Access, was to open a series of current web pages in FP and save them to a different folder so I could begin to remove all of the FP stuff without affecting the working parts of the website.

I Google-ed "FrontPage" and "VBA" extensively but there seems to be a dearth of useful information out there.  Any references I did find pointed to pages/sites that are no longer active.  So I muddled along with what information I did find and this is the result:

Sub OpenAndSaveAsPages()
Dim objPageWindow As PageWindowEx
Dim objFileOpen As FileDialog
Dim strFolder As String
Dim strFile As Variant
Dim intCount As Integer
Dim strURL As String
'File Open dialog object.
Set objFileOpen = FrontPage.Application.FileDialog(msoFileDialogOpen)
'startup folder default is the root folder of the active Web site
strFolder = ActiveWeb.RootFolder
' clean up unwanted stuff in the URL
strFolder = Replace(strFolder, "file:///", "")
strFolder = Replace(strFolder, "/", "\")
objFileOpen.InitialFileName = strFolder
If objFileOpen.Show < 0 Then
    For Each strFile In objFileOpen.SelectedItems
' Open web file in FP
        ActiveWebWindow.PageWindows.Add strFile
' at this point all I wanted to do was a SAVEAS to save the file to a different folder
' so I wanted to do something like below but could not figure it out
'           objPageWindow.SaveAs objPageWindow.Document.Url
    Next
End If
' Now all the selected file are open in FrontPage and I will iterate through them
For Each objPageWindow In ActiveWebWindow.PageWindows
' the URL for the currently select page
    strURL = objPageWindow.Document.Url
' probably some extra work here to change the URL to a different folder and filename
    strURL = Replace(strURL, Mid(strURL, InStrRev(strURL, ".", Len(strURL)), Len(strURL) + 1 - InStrRev(strURL, ".", Len(strURL))), Mid(strURL, InStrRev(strURL, ".", Len(strURL)), Len(strURL) + 1 - InStrRev(strURL, ".", Len(strURL))), 1)
    strURL = Replace(strURL, Left(strURL, InStrRev(strURL, "/", Len(strURL))), Left(strURL, InStrRev(strURL, "/", Len(strURL))) & "temp/", 1)
    objPageWindow.SaveAs strURL
    objPageWindow.Close
Next
End Sub

OK, it works but for sure it is probably not the most efficient and for sure not elegant.

So, my questions are:

are there and good references for FP VBA that you can recommend (I'm not a professional programmer, just someone that like to ...).  I work well in using examples to achieve and  learn.

Can someone sharpen up my code, with explanations, of course.

Note, I'm not trying to write any code to actually modify the code in these pages.  I may get to that, but for now it appears that a "SAVEAS" results in code which is already fairly clean of the FP stuff.

Many thanks....RDK


问:
Wordpress WooCommerce get cross sell prducts for Composite Products using GraphQL
I am trying to get cross-sell products of composite products. But I couldn't find it in the GraphQL IDE. Is there any way to query cross-sell products for composite products?


问:
No such table - Discord.py - Sqlite3 database error
I'm in the process of making a bot that has some different functions. The bot is able to register when someone checks in and checks out. When someone checks out it adds +1 to a database and saves it.

I've run into the problem that it won't connect to my database. Have tried using "Import os" and doing this by through with couldn't get it to work. I have made a file called "attendance.db" out in my folder where I also have my python file. Can't figure out what I'm doing wrong, so does anyone know how I can fix my problem?

```<code>import discord
import sqlite3

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('!check-in'):
        conn = sqlite3.connect('attendance.db')
        c = conn.cursor()

        c.execute('SELECT * FROM attendance WHERE user_id = ? AND checked_in = 1', (message.author.id,))
        result = c.fetchone()
        if result:
            await message.channel.send('You are already checked in!')
        else:
            c.execute('INSERT INTO attendance (user_id, checked_in) VALUES (?, 1)', (message.author.id,))
            conn.commit()
            await message.channel.send('You are now checked in!')

        conn.close()

    if message.content.startswith('!check-out'):
        conn = sqlite3.connect('attendance.db')
        c = conn.cursor()

        c.execute('SELECT * FROM attendance WHERE user_id = ? AND checked_in = 1', (message.author.id,))
        result = c.fetchone()
        if result:
            c.execute('UPDATE attendance SET checked_in = 0 WHERE user_id = ?', (message.author.id,))
            c.execute('UPDATE stats SET num_checked_out = num_checked_out + 1 WHERE id = 1')
            conn.commit()
            await message.channel.send('You are now checked out!')
        else:
            await message.channel.send('You are not checked in!')

        conn.close()

    if message.content.startswith('!info'):
        conn = sqlite3.connect('attendance.db')
        c = conn.cursor()

        c.execute('SELECT num_checked_out FROM stats WHERE id = 1')
        num_checked_out = c.fetchone()[0]

        await message.channel.send('{} users have checked out.'.format(num_checked_out))

        conn.close()
</code>```

Getting this error in my terminal

```<code>Traceback (most recent call last):
  File "C:\Users\rober\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\rober\Desktop\discord\main.py", line 24, in on_message
    c.execute('SELECT * FROM attendance WHERE user_id = ? AND checked_in = 1', (message.author.id,))
sqlite3.OperationalError: no such table: attendance
</code>```

Body:
I'm in the process of making a bot that has some different functions. The bot is able to register when someone checks in and checks out. When someone checks out it adds +1 to a database and saves it.

I've run into the problem that it won't connect to my database. Have tried using "Import os" and doing this by through with couldn't get it to work. I have made a file called "attendance.db" out in my folder where I also have my python file. Can't figure out what I'm doing wrong, so does anyone know how I can fix my problem?

import discord
import sqlite3

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('!check-in'):
        conn = sqlite3.connect('attendance.db')
        c = conn.cursor()

        c.execute('SELECT * FROM attendance WHERE user_id = ? AND checked_in = 1', (message.author.id,))
        result = c.fetchone()
        if result:
            await message.channel.send('You are already checked in!')
        else:
            c.execute('INSERT INTO attendance (user_id, checked_in) VALUES (?, 1)', (message.author.id,))
            conn.commit()
            await message.channel.send('You are now checked in!')

        conn.close()

    if message.content.startswith('!check-out'):
        conn = sqlite3.connect('attendance.db')
        c = conn.cursor()

        c.execute('SELECT * FROM attendance WHERE user_id = ? AND checked_in = 1', (message.author.id,))
        result = c.fetchone()
        if result:
            c.execute('UPDATE attendance SET checked_in = 0 WHERE user_id = ?', (message.author.id,))
            c.execute('UPDATE stats SET num_checked_out = num_checked_out + 1 WHERE id = 1')
            conn.commit()
            await message.channel.send('You are now checked out!')
        else:
            await message.channel.send('You are not checked in!')

        conn.close()

    if message.content.startswith('!info'):
        conn = sqlite3.connect('attendance.db')
        c = conn.cursor()

        c.execute('SELECT num_checked_out FROM stats WHERE id = 1')
        num_checked_out = c.fetchone()[0]

        await message.channel.send('{} users have checked out.'.format(num_checked_out))

        conn.close()

Getting this error in my terminal

Traceback (most recent call last):
  File "C:\Users\rober\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\rober\Desktop\discord\main.py", line 24, in on_message
    c.execute('SELECT * FROM attendance WHERE user_id = ? AND checked_in = 1', (message.author.id,))
sqlite3.OperationalError: no such table: attendance


问:
Multiple date formats conversion
I am ingesting data from a excel spreadsheet. Half the date has a date format the other half has a excel numerical value (e.g. 44834 = 30/09/2022)

How do you run through the data and standardise the date format.

```<code>df.withColumn("Changed_date", when(to_date(f.col("applicationdate"), "MM/dd/yyyy").isNotNull(), to_date(f.col("applicationdate"), "MM/dd/yyyy"))
.when(f.expr("date_add('1899-12-31', cast(applicationdate as int)").isNotNull(),f.expr("date_add('1899-12-31', cast(applicationdate as int)")).otherwise( to_date("1899-12-31", "MM-dd-yyyy")))
</code>```

Title: Multiple date formats conversion

Body:
I am ingesting data from a excel spreadsheet. Half the date has a date format the other half has a excel numerical value (e.g. 44834 = 30/09/2022)

How do you run through the data and standardise the date format.

df.withColumn("Changed_date", when(to_date(f.col("applicationdate"), "MM/dd/yyyy").isNotNull(), to_date(f.col("applicationdate"), "MM/dd/yyyy"))
.when(f.expr("date_add('1899-12-31', cast(applicationdate as int)").isNotNull(),f.expr("date_add('1899-12-31', cast(applicationdate as int)")).otherwise( to_date("1899-12-31", "MM-dd-yyyy")))


问:
Symfony : multiple mercure subscriptions
I've developed an app based on this tutorial : https://symfonycasts.com/screencast/turbo

By the way, my app is broadcasting HTML updates on several topics, ie : chat-messages, notifications, chat-channels

So, every pages of my app is subscribing to these topics, and everything works beautifully on a local server, but as soon as I'm deploying this app online, every ajax calls are taking very much time, and the app is stucked.

When I'm disabling the mercure "subscribing" part, everything is working perfectly, but I really don't understand why...

Here is my setup :

Debian 11 VPS

PHP8.1

Mercure 0.14.2

Nginx with a reverse proxy configured on the mercure hub

I've tried to configure apache instead of nginx, but I've got the same problem


问:
Is there a way to import prewritten JSON data into MongoDB when a new user is created but also have it tied to the new user?
I'm building a studying tool that essentially consists of multiple flashcards (in the thousands). I would like to know if there is a unique way or method where the prewritten flashcards can be duplicated and tied to every user who signs up? Or perhaps having the data prewritten inside a JSON file and then upon user creation having it imported into MongoDB with a userID field that the data becomes unique to every individual user. The reason for this is because the flashcards will be using a spaced repetition algorithm and as a result I can't have one users results be carried over globally for every user. It would need to be unique to that user.

Thanks in advance for any help!

So far I've built the flashcard model and tied it to the algorithm however it updates globally across all users. Im havign a bit of trouble with breaking down some of the logic to make it unique to each user.


问:
CryptoJS AES encrypt & C# AES Decrypt causes IV block size error
I'm getting "Specified initialization vector (IV) does not match the block size for this algorithm" when trying to decrypt on C# using System.Security.Cryptography.AES.

I encrypt with Crypto-JS:

```<code>var key = CryptoJS.MD5("secret");
var iv = CryptoJS.MD5("deviceID");

encrypted = CryptoJS.AES.encrypt(pass, key, {iv:iv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7 }).toString();
decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv:iv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7 }).toString(CryptoJS.enc.Utf8);
</code>```

Decrypt with C#:

```<code>byte[] iv = Encoding.UTF8.GetBytes(hexIv);
byte[] key = Encoding.UTF8.GetBytes(hexKey);
byte[] cipher = Encoding.UTF8.GetBytes(sCipher);

using (Aes aes = Aes.Create())
{
    aes.Key = key;
    aes.IV = iv; // HERE I GOT ERROR (IV) does not match the block size

    aes.Mode = CipherMode.ECB;
    aes.Padding = PaddingMode.PKCS7;

    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

    using (MemoryStream msDecrypt = new MemoryStream(cipher))
    {
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            {
                try
                {
                    decrypted = srDecrypt.ReadToEnd();
                }
                catch (Exception err)
                {
                    throw;
                }
            }
        }
    }
}
</code>```

C# iv is a 32 bytes size
Both IV's are the same MD5 hash

AES Object Screenshot

Body:
I'm getting "Specified initialization vector (IV) does not match the block size for this algorithm" when trying to decrypt on C# using System.Security.Cryptography.AES.

I encrypt with Crypto-JS:

var key = CryptoJS.MD5("secret");
var iv = CryptoJS.MD5("deviceID");

encrypted = CryptoJS.AES.encrypt(pass, key, {iv:iv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7 }).toString();
decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv:iv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.Pkcs7 }).toString(CryptoJS.enc.Utf8);

Decrypt with C#:

byte[] iv = Encoding.UTF8.GetBytes(hexIv);
byte[] key = Encoding.UTF8.GetBytes(hexKey);
byte[] cipher = Encoding.UTF8.GetBytes(sCipher);

using (Aes aes = Aes.Create())
{
    aes.Key = key;
    aes.IV = iv; // HERE I GOT ERROR (IV) does not match the block size

    aes.Mode = CipherMode.ECB;
    aes.Padding = PaddingMode.PKCS7;

    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

    using (MemoryStream msDecrypt = new MemoryStream(cipher))
    {
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            {
                try
                {
                    decrypted = srDecrypt.ReadToEnd();
                }
                catch (Exception err)
                {
                    throw;
                }
            }
        }
    }
}

C# iv is a 32 bytes size
Both IV's are the same MD5 hash

AES Object Screenshot


问:
passing authorization from a Blazor identified user to a sub site in ASP.NET forms (SSO)
Since Blazor doesn't support RDLC reports. We host a sub site under the blazor main site, as a ASP.NET Forms application. users are identified in the Blazor main site using the MS identity framework. when we redirect the users to the Repors sub site we would like to send the authentication to the Reports site. SSO that is, any examples how to implement this ?

nothing yet --------


问:
How to group the dataframe for transformation
I have the following dataframe with schema:

```<code><bound method DataFrame.printSchema of DataFrame[outer_value: string, value01: string, value02: string, value03: string, value04: string, value05: string, value06: string, value07: string, value08: string, value09: string, value10: string, value11: string, value12: string, value13: string, value14: string, value15: string, value16: string, value17: string, value18: string, value19: string, value20: string, value21: string, value22: string, value23: string, value24: string, value25: string, value26: string, value27: string, value28: string, value29: string, value30: string, value31: string, value32: string, value33: string, value34: string, value35: string, value36: string, value37: string, value38: string, value39: string, value40: string, value41: string, value42: string, value43: string, value44: string, value45: string, value46: string, value47: string, value48: string, value49: string, value50: string, value51: string, value52: string, value53: string, value54: string, value55: string]>
</code>```

I would like to group the columns by 5 (divide 55 by 5 to create 11 column groups) and populate another dataframe with the following schema.

```<code>> [outer_value: string, value01: string, value02: string, value03:
> string, value04: string, value05:string]
</code>```

The Image the below represents the first group of 5 columns used to populate the target schema. Likewise, the next group will be formed  as : outer_value, value 6, value7, value 8, value 9, value 10.

it goes like that until the 11 groups are processed and each group populated the target dataframe.

Eventually, one row in the source data frame will end up as 11 rows in the target data frame.

How to achieve this?

Body:
I have the following dataframe with schema:

<bound method DataFrame.printSchema of DataFrame[outer_value: string, value01: string, value02: string, value03: string, value04: string, value05: string, value06: string, value07: string, value08: string, value09: string, value10: string, value11: string, value12: string, value13: string, value14: string, value15: string, value16: string, value17: string, value18: string, value19: string, value20: string, value21: string, value22: string, value23: string, value24: string, value25: string, value26: string, value27: string, value28: string, value29: string, value30: string, value31: string, value32: string, value33: string, value34: string, value35: string, value36: string, value37: string, value38: string, value39: string, value40: string, value41: string, value42: string, value43: string, value44: string, value45: string, value46: string, value47: string, value48: string, value49: string, value50: string, value51: string, value52: string, value53: string, value54: string, value55: string]>

I would like to group the columns by 5 (divide 55 by 5 to create 11 column groups) and populate another dataframe with the following schema.

> [outer_value: string, value01: string, value02: string, value03:
> string, value04: string, value05:string]

The Image the below represents the first group of 5 columns used to populate the target schema. Likewise, the next group will be formed  as : outer_value, value 6, value7, value 8, value 9, value 10.

it goes like that until the 11 groups are processed and each group populated the target dataframe.

Eventually, one row in the source data frame will end up as 11 rows in the target data frame.

How to achieve this?


问:
How to load a custom model downloaded from hugging face
I am checking all the answers but most of them use Bert for everything, how can I load a custom model which is cloned from hugging face to make inferences, infereces are speech to text

I did a fine tunning on whisper with custom data, inferences works calling the hugging face cloud, but after clone the repo is not working, dont know how to load locally


问:
How to extrude a surface along a line with cadquery python
I would like to extrude a step surface previously imported with the cadquery python library (or any other useful library!). The extrusion will be along a line, line built by providing x,y,z coordinnates of the start/end point. I have multiple line so I would like to orient the surface to be sur the normal is aligned with the line.
I manage to build the lines and everything (with lineTo function) but can't manage to extrude a surface along it. Could someone help?

Thank you !


问:
No version in Accept header produces successful request result
I have this @PostMapping on my controller:

```<code>@PostMapping(value = Endpoints.PERMANENT, produces = MediaType.APPLICATION_JSON_VALUE)
</code>```

I want to add versioning to my API so I updated it to accept the version in the Accept header:

```<code>@PostMapping(value = Endpoints.PERMANENT, produces = {"application/vnd.myapp.v1+json"})
</code>```

If I now send a POST to that endpoint and include application/vnd.myapp.v1+json in the Acccept header the request is successful. If I change the value in my Accept header to application/vnd.pricegenerator.v2+json I get this(which is as expected):

```<code>{
    "statusMessage": "Not Acceptable"
}
</code>```

If however, I send nothing in my Accept header the request still succeeds. Why is this and how can I resolve it?

Body:
I have this @PostMapping on my controller:

@PostMapping(value = Endpoints.PERMANENT, produces = MediaType.APPLICATION_JSON_VALUE)

I want to add versioning to my API so I updated it to accept the version in the Accept header:

@PostMapping(value = Endpoints.PERMANENT, produces = {"application/vnd.myapp.v1+json"})

If I now send a POST to that endpoint and include application/vnd.myapp.v1+json in the Acccept header the request is successful. If I change the value in my Accept header to application/vnd.pricegenerator.v2+json I get this(which is as expected):

{
    "statusMessage": "Not Acceptable"
}

If however, I send nothing in my Accept header the request still succeeds. Why is this and how can I resolve it?


问:
fastapi's class as dependency override in unit testing
Using the parameter supplied in the request body, I wanted to instantiate an object. For instance, if the request body contains type=push I desired to instantiate in this manner.

```<code>    if channel_type.upper() == "PUSH":
       return NotificationService(Push())
</code>```

I am able to achieve this through classes as dependency of fastapi as following:

```<code>def factory(channel_type):
    if channel_type.upper() == "PUSH":
        return NotificationService(Push())
    elif channel_type.upper() == "EMAIL":
        return NotificationService(Email())
    else:
        return NotificationService(Sms())

class NotificationRequest:
    def __init__(self, type: str = Body("push")):
        self.service = factory(type)

class MessageRequest(BaseModel):
    title: str
    message: str
    payload: Dict = {}

@router.post("/", response_model=dict)
def notify(message: MessageRequest, request: NotificationRequest = Depends()) -> Any:
    request.service.send(users=get_users(), message=Message(
        title=message.title, message=message.message, payload=message.payload
    ))
    return {"success": True}

</code>```

However, I wanted to override the NotificationRequest dependency in the unit test so that I could provide fake instances of real classes:

```<code>def get_factory(channel_type):
    if channel_type.upper() == "PUSH":
        return NotificationService(FakePush())
    elif channel_type.upper() == "EMAIL":
        return NotificationService(FakeEmail())
    else:
        return NotificationService(FakeSms())
</code>```

I have tried following:

```<code>app.dependency_overrides[factory] = lambda: get_factory
</code>```

which fails because the factory is not injected through the dependency.

How can we give a parameter to the body and inject a dependency into the function to produce a fake instance for unit testing?

Body:
Using the parameter supplied in the request body, I wanted to instantiate an object. For instance, if the request body contains type=push I desired to instantiate in this manner.

    if channel_type.upper() == "PUSH":
       return NotificationService(Push())

I am able to achieve this through classes as dependency of fastapi as following:

def factory(channel_type):
    if channel_type.upper() == "PUSH":
        return NotificationService(Push())
    elif channel_type.upper() == "EMAIL":
        return NotificationService(Email())
    else:
        return NotificationService(Sms())

class NotificationRequest:
    def __init__(self, type: str = Body("push")):
        self.service = factory(type)

class MessageRequest(BaseModel):
    title: str
    message: str
    payload: Dict = {}

@router.post("/", response_model=dict)
def notify(message: MessageRequest, request: NotificationRequest = Depends()) -> Any:
    request.service.send(users=get_users(), message=Message(
        title=message.title, message=message.message, payload=message.payload
    ))
    return {"success": True}

However, I wanted to override the NotificationRequest dependency in the unit test so that I could provide fake instances of real classes:

def get_factory(channel_type):
    if channel_type.upper() == "PUSH":
        return NotificationService(FakePush())
    elif channel_type.upper() == "EMAIL":
        return NotificationService(FakeEmail())
    else:
        return NotificationService(FakeSms())

I have tried following:

app.dependency_overrides[factory] = lambda: get_factory

which fails because the factory is not injected through the dependency.

How can we give a parameter to the body and inject a dependency into the function to produce a fake instance for unit testing?


问:
*ngIf and optional chaining
I am currently refactoring some old code and thus dealing with many redundant conditional checks. Here is a short example:

```<code><div *ngIf="user" title="{{user?.name}}">
    <span>Age: {{user?.age}}<span>
</div>
</code>```

Most entries like 'user age', are a no-brainer, because we already know that the user exists. There is a clear hierarchy in the usage of encapsulated HTML tags.

I am concerned with the order within the tag. Can i safely remove the conditional check in 'user name'?

Title: *ngIf and optional chaining

Body:
I am currently refactoring some old code and thus dealing with many redundant conditional checks. Here is a short example:

    Age: {{user?.age}}

Most entries like 'user age', are a no-brainer, because we already know that the user exists. There is a clear hierarchy in the usage of encapsulated HTML tags.

I am concerned with the order within the tag. Can i safely remove the conditional check in 'user name'?


问:
How to access web API server running on Windows with Iphone that is connected on a Macbook in C#
I'm buidling a blazor hybrid project and I want to test my application on an Iphone.
The Iphone is connected with a Macbook. The Macbook is connected in Visual studio using the Paired to Mac method.
I have an API project that is running in the background to receive calls from their specific endpoints. On an android real device and android emulators everything is working fine but I know with IOS this doesn't work the same. The API calls are not getting hit once I deployed the app on an Iphone.
So what I want to achieve is to connect to local web services (on my windows machine) from iOS real device that is connected with a mac book.
This is what I currently have :

MauiProgram.cs

```<code>
private static HttpClient BuildHttpClient()
        {
            string url = DeviceInfo.Platform == DevicePlatform.Android ? "https://10.0.2.2:7128" : "https://localhost:7128";

#if DEBUG
            HttpsClientHandlerService handler = new HttpsClientHandlerService();
            HttpClient client = new HttpClient(handler.GetPlatformMessageHandler()) { BaseAddress = new Uri(url) };
#else
            client = new HttpClient(BaseAddress = new Uri(url));
#endif
            return client;
        }
</code>```

HttpsClientHandlerService

```<code>
public class HttpsClientHandlerService
    {
        public HttpMessageHandler GetPlatformMessageHandler()
        {
#if ANDROID
            var handler = new CustomAndroidMessageHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
            {
                if (cert.Issuer.Equals("CN=localhost"))
                    return true;
                return errors == System.Net.Security.SslPolicyErrors.None;
            };
            return handler;
#elif IOS
            var handler = new NSUrlSessionHandler
            {
                TrustOverrideForUrl = IsHttpsLocalhost
            };
            return handler;

#else
            throw new PlatformNotSupportedException("Only Android and iOS supported.");
#endif
        }

#if IOS
        public bool IsHttpsLocalhost(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
        {
            //if (url.StartsWith("https://localhost"))
            //    return true;
            return true;
        }
#endif
    }

#if ANDROID
    internal sealed class CustomAndroidMessageHandler : Xamarin.Android.Net.AndroidMessageHandler
    {
        protected override Javax.Net.Ssl.IHostnameVerifier GetSSLHostnameVerifier(Javax.Net.Ssl.HttpsURLConnection connection)
            => new CustomHostnameVerifier();

        private sealed class CustomHostnameVerifier : Java.Lang.Object, Javax.Net.Ssl.IHostnameVerifier
        {
            public bool Verify(string hostname, Javax.Net.Ssl.ISSLSession session)
            {
                return Javax.Net.Ssl.HttpsURLConnection.DefaultHostnameVerifier.Verify(hostname, session) ||
                    hostname == "10.0.2.2" || hostname == Constants.Hostname && session.PeerPrincipal?.Name == "CN=localhost";
            }
        }
    }
</code>```

launchSettings.json in the API project

```<code>
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:28563",
      "sslPort": 44342
    }
  },
  "profiles": {
    "EventApplicationAPI": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:7128;http://10.100.0.152:7128",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

Changing the ip address if the app is running on an ios device. Tried using ngrok as well but without positive results

Body:
I'm buidling a blazor hybrid project and I want to test my application on an Iphone.
The Iphone is connected with a Macbook. The Macbook is connected in Visual studio using the Paired to Mac method.
I have an API project that is running in the background to receive calls from their specific endpoints. On an android real device and android emulators everything is working fine but I know with IOS this doesn't work the same. The API calls are not getting hit once I deployed the app on an Iphone.
So what I want to achieve is to connect to local web services (on my windows machine) from iOS real device that is connected with a mac book.
This is what I currently have :

MauiProgram.cs

private static HttpClient BuildHttpClient()
        {
            string url = DeviceInfo.Platform == DevicePlatform.Android ? "https://10.0.2.2:7128" : "https://localhost:7128";

#if DEBUG
            HttpsClientHandlerService handler = new HttpsClientHandlerService();
            HttpClient client = new HttpClient(handler.GetPlatformMessageHandler()) { BaseAddress = new Uri(url) };
#else
            client = new HttpClient(BaseAddress = new Uri(url));
#endif
            return client;
        }

HttpsClientHandlerService

public class HttpsClientHandlerService
    {
        public HttpMessageHandler GetPlatformMessageHandler()
        {
#if ANDROID
            var handler = new CustomAndroidMessageHandler();
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
            {
                if (cert.Issuer.Equals("CN=localhost"))
                    return true;
                return errors == System.Net.Security.SslPolicyErrors.None;
            };
            return handler;
#elif IOS
            var handler = new NSUrlSessionHandler
            {
                TrustOverrideForUrl = IsHttpsLocalhost
            };
            return handler;

#else
            throw new PlatformNotSupportedException("Only Android and iOS supported.");
#endif
        }

#if IOS
        public bool IsHttpsLocalhost(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
        {
            //if (url.StartsWith("https://localhost"))
            //    return true;
            return true;
        }
#endif
    }

#if ANDROID
    internal sealed class CustomAndroidMessageHandler : Xamarin.Android.Net.AndroidMessageHandler
    {
        protected override Javax.Net.Ssl.IHostnameVerifier GetSSLHostnameVerifier(Javax.Net.Ssl.HttpsURLConnection connection)
            => new CustomHostnameVerifier();

        private sealed class CustomHostnameVerifier : Java.Lang.Object, Javax.Net.Ssl.IHostnameVerifier
        {
            public bool Verify(string hostname, Javax.Net.Ssl.ISSLSession session)
            {
                return Javax.Net.Ssl.HttpsURLConnection.DefaultHostnameVerifier.Verify(hostname, session) ||
                    hostname == "10.0.2.2" || hostname == Constants.Hostname && session.PeerPrincipal?.Name == "CN=localhost";
            }
        }
    }

launchSettings.json in the API project

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:28563",
      "sslPort": 44342
    }
  },
  "profiles": {
    "EventApplicationAPI": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:7128;http://10.100.0.152:7128",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Changing the ip address if the app is running on an ios device. Tried using ngrok as well but without positive results


问:
Converting CompletableFuture to Kotlin counterpart
I've been trying to convert some Java code into Kotlin, but I am having trouble when it comes to CompletableFuture.  I have the following code:

public CompletableFuture<Integer> updateAsync(@NotNull String sqlStatement, @NotNull SQLConsumer<PreparedStatement> psPreparer) throws UncheckedSQLException
{
    return CompletableFuture.supplyAsync(() -> this.update(sqlStatement, psPreparer), this.threadPool);
}
```

I usually leverage the Java to Kotlin conversion tool within Intelij, but when I do it for this, it converts it but still uses CompleteableFuture.

What is the Kotlin equivalent to using CompleteableFuture that would not require too much refactoring?  Or, should I just keep using CompletableFuture in Kotlin?

Thank you

Body:
I've been trying to convert some Java code into Kotlin, but I am having trouble when it comes to CompletableFuture.  I have the following code:

public CompletableFuture<Integer> updateAsync(@NotNull String sqlStatement, @NotNull SQLConsumer<PreparedStatement> psPreparer) throws UncheckedSQLException
{
    return CompletableFuture.supplyAsync(() -> this.update(sqlStatement, psPreparer), this.threadPool);
}

I usually leverage the Java to Kotlin conversion tool within Intelij, but when I do it for this, it converts it but still uses CompleteableFuture.

What is the Kotlin equivalent to using CompleteableFuture that would not require too much refactoring?  Or, should I just keep using CompletableFuture in Kotlin?

Thank you


问:
Original error: 'POST /element' / 'GET /session/bda49419-373f-4ae8-8d8e-1537553bf008/source' cannot be proxied
After the tap by coordinates action used by W3C, I am trying to call the driver again to find the element and that's when it throws the error.

When I use driver.getpageSource(), it gives me the below error.

```<code>GET /session/bda49419-373f-4ae8-8d8e-1537553bf008/source' cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed). Check the server log and/or the logcat output for more details
</code>```

When I directly call driver.findElement(), it gives me this error.

```<code>An unknown server-side error occurred while processing the command. Original error: 'POST /element' cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed). Check the server log and/or the logcat output for more details
Build info: version: '4.6.0', revision: '79f1c02ae20'
</code>```

I was trying to automate the app using the Appium and first step was to call the driver.findElements and then I went to tap by coordinates using w3c actions (PointerOptions),and after the above step, I had driver.findElement() and it gave me the above errors.

Body:
After the tap by coordinates action used by W3C, I am trying to call the driver again to find the element and that's when it throws the error.

When I use driver.getpageSource(), it gives me the below error.

GET /session/bda49419-373f-4ae8-8d8e-1537553bf008/source' cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed). Check the server log and/or the logcat output for more details

When I directly call driver.findElement(), it gives me this error.

An unknown server-side error occurred while processing the command. Original error: 'POST /element' cannot be proxied to UiAutomator2 server because the instrumentation process is not running (probably crashed). Check the server log and/or the logcat output for more details
Build info: version: '4.6.0', revision: '79f1c02ae20'

I was trying to automate the app using the Appium and first step was to call the driver.findElements and then I went to tap by coordinates using w3c actions (PointerOptions),and after the above step, I had driver.findElement() and it gave me the above errors.


问:
Reset Angular form control value dynamically on a specific condition (RxWeb Forms)
We are using Angular 14.x.x on our project. We handle a lot of data in forms.

Form validation happens with the help of RxWeb

The bug:

The value of a form date picker never resets after initialization.

The problem:

If the date is chosen once, there is no going back - the client has to either delete the date manually form the input, reload the webpage or accept that he'll be using the selected date in the form.

The flow of the bug:

The user chooses a specific value from a radio button, which will reveal the date picker.

The user chooses the desired date.

The user decides that he actually doesn't want a date. So he hides the date picker with the radio button by choosing a different value.

Though the form is hidden, the date is still saved in the form as the initially picked value.

The implementation:

```<code>@required({ conditionalExpression: (formObject: SicknessRefund) => formObject.isEmployeeHealthy === "true" })
    @minDate({ fieldName: 'refundStart', message: "Should be after the refund period." })
    @maxDate({ fieldName: 'refundEnd', message: "Should be before the refund period." })
    @maxDate({ value: new Date(), message: "Should be before or precisely today's date."})
    @date()
    public lastAbsenceDay: string;
</code>```

Body:
We are using Angular 14.x.x on our project. We handle a lot of data in forms.

Form validation happens with the help of RxWeb

The bug:

The value of a form date picker never resets after initialization.

The problem:

If the date is chosen once, there is no going back - the client has to either delete the date manually form the input, reload the webpage or accept that he'll be using the selected date in the form.

The flow of the bug:

The user chooses a specific value from a radio button, which will reveal the date picker.

The user chooses the desired date.

The user decides that he actually doesn't want a date. So he hides the date picker with the radio button by choosing a different value.

Though the form is hidden, the date is still saved in the form as the initially picked value.

The implementation:

@required({ conditionalExpression: (formObject: SicknessRefund) => formObject.isEmployeeHealthy === "true" })
    @minDate({ fieldName: 'refundStart', message: "Should be after the refund period." })
    @maxDate({ fieldName: 'refundEnd', message: "Should be before the refund period." })
    @maxDate({ value: new Date(), message: "Should be before or precisely today's date."})
    @date()
    public lastAbsenceDay: string;


问:
Issue connecting SPSS Modeler 18.3 & 18.4 to DB2WoC Databases - Null values rendered as the value in the previous record
I am having an issue connecting SPSS Modeler 18.3 & 18.4 to DB2WoC Databases - Null values rendered as the value in the previous record.</p>
```<code>  For instance record 1 contains the values - 1,2012-12-12,<null>,"Strength"
               record 2 contains the values - 2,<null>,17,"Bluebell"
               record 3 contains the values - <null>,<null>,<null>,<null>

 These are being rendered as :
record 1  - 1,2012-12-12,<null>,"Strength"
record 2  - 2,2012-12-12,17,"Bluebell"
record 3  - 2,2012-12-12,17,"Bluebell"

Any ideas how to solve this?

Expected results were:
record 1  - 1,2012-12-12,<null>,"Strength"
record 2  - 2,<null>,17,"Bluebell"
record 3  - <null>,<null>,<null>,<null>
</code>```

Body:
I am having an issue connecting SPSS Modeler 18.3 & 18.4 to DB2WoC Databases - Null values rendered as the value in the previous record.

  For instance record 1 contains the values - 1,2012-12-12,<null>,"Strength"
               record 2 contains the values - 2,<null>,17,"Bluebell"
               record 3 contains the values - <null>,<null>,<null>,<null>

 These are being rendered as :
record 1  - 1,2012-12-12,<null>,"Strength"
record 2  - 2,2012-12-12,17,"Bluebell"
record 3  - 2,2012-12-12,17,"Bluebell"

Any ideas how to solve this?

Expected results were:
record 1  - 1,2012-12-12,<null>,"Strength"
record 2  - 2,<null>,17,"Bluebell"
record 3  - <null>,<null>,<null>,<null>


问:
Error: No Keychain password item found for profile
Trying to notarize Electron app.

Generated “App Manager” API key on https://appstoreconnect.apple.com/access/api.

Ran xcrun notarytool store-credentials test referencing AuthKey_*.p8 API key.

Wrote following notarize.js @electron/notarize script.

const { existsSync } = require("fs")
const { homedir } = require("os")
const { join } = require("path")
const electronNotarize = require("@electron/notarize")

module.exports = async function (context) {
  if (process.platform !== "darwin") {
    return
  }

  const appId = context.packager.config.appId

  const appPath = join(
    context.appOutDir,
    `${context.packager.appInfo.productFilename}.app`
  )

  console.log(`Notarizing ${appId} found at ${appPath}…`)

  await electronNotarize.notarize({
    appPath: appPath,
    keychain: `${homedir()}/Library/Keychains/login.keychain-db`,
    keychainProfile: "test",
    tool: "notarytool",
  })

  console.log(`Notarized ${appId} found at ${appPath}`)
}
```

When I run electron-builder build script which triggers afterSign which runs notarize.js, following error is thrown.

Error: No Keychain password item found for profile: test

What am I missing?

Body:
Trying to notarize Electron app.

Generated “App Manager” API key on https://appstoreconnect.apple.com/access/api.

Ran xcrun notarytool store-credentials test referencing AuthKey_*.p8 API key.

Wrote following notarize.js @electron/notarize script.

const { existsSync } = require("fs")
const { homedir } = require("os")
const { join } = require("path")
const electronNotarize = require("@electron/notarize")

module.exports = async function (context) {
  if (process.platform !== "darwin") {
    return
  }

  const appId = context.packager.config.appId

  const appPath = join(
    context.appOutDir,
    `${context.packager.appInfo.productFilename}.app`
  )

  console.log(`Notarizing ${appId} found at ${appPath}…`)

  await electronNotarize.notarize({
    appPath: appPath,
    keychain: `${homedir()}/Library/Keychains/login.keychain-db`,
    keychainProfile: "test",
    tool: "notarytool",
  })

  console.log(`Notarized ${appId} found at ${appPath}`)
}

When I run electron-builder build script which triggers afterSign which runs notarize.js, following error is thrown.

Error: No Keychain password item found for profile: test

What am I missing?