问:
spring-context and spring-web 4.2.4.RELEASE
Why I need to include spring-context in my new spring boot project to work ?

I have this in my pom.xml

```<code> <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
  </dependency>
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
  </dependency>
</code>```

I can see inside spring-web dependency, the dependency spring-context

if I remove spring-context from my pom.xml, the application does not run.

Below is the error I get :

```<code>Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nameOfController'
</code>```

答:
Do you see the spring-context to be provided with spring-web or really that it just depends on it? You might want to do yourself a favor and use the spring boot starter artefacts that actually come with all required dependencies and don't mark any of them as "provided".

In your case, it would be spring-boot-starter-web.

Body:
Why I need to include spring-context in my new spring boot project to work ?

I have this in my pom.xml

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
  </dependency>
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
  </dependency>

I can see inside spring-web dependency, the dependency spring-context

if I remove spring-context from my pom.xml, the application does not run.

Below is the error I get :

Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nameOfController'


来源: stackexchange

问:
how to drop a bomb in character position in a pygame game
I'm making a pygame game where a character is currently moving around on a screen and can buy items from a shop. I want the character to be able to drop the bombs that he buys from the shop in the location of the player (I need to fix this). I'm attaching my whole code along with some screen shots. Any help is appreciated, thank you.

```<code> import pygame

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
# char_rect = char.get_rect()

x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0
shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

bag = {'bomb': 0}
print(bag["bomb"])
class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_q")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)

def redrawGameWindow():
    global walkCount
    screen.fill([166, 166, 166])

    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))

    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0

    buy = pygame.key.get_pressed()
    if buy[pygame.K_SPACE] and bag["bomb"] >= 1:
        screen.blit(bomb_pic,(x,y))
    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_q]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

        redrawGameWindow()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False

        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True[![enter image description here][1]][1]
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()

main()
</code>```

答:
Add a list for the bombs:

bombs = []
```

<p>Add the position of the bomb to the list, when <kbd>space</kbd> is pressed. Use the event loop and the <code>KEYDOWN</code> event to spawn bombs, because you want to drap only on bomb when the key is pressed rather than multiple bombs when the key is hold down:</p>

<pre class="lang-py prettyprint-override"><code>def main():
    global bombs

    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key = pygame.K_SPACE and bag["bomb"] >= 1:
                    bombs.append((x, y))

            # [...]
</code>```

Draw the bombs in redrawGameWindow in a loop:

def redrawGameWindow():
    # [...]

    for pos in bombs:
        screen.blit(bomb_pic, pos)
    pygame.display.update()
```

ContentLicense: CC BY-SA 4.0

Body:
I'm making a pygame game where a character is currently moving around on a screen and can buy items from a shop. I want the character to be able to drop the bombs that he buys from the shop in the location of the player (I need to fix this). I'm attaching my whole code along with some screen shots. Any help is appreciated, thank you.

 import pygame

pygame.font.init()

width = 900
height = 600

screen = pygame.display.set_mode([width, height])

walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
             pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
             pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]

walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
            pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
            pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]

char = pygame.image.load('standing.png')
bomb_pic = pygame.transform.scale(pygame.image.load('bomb.png'), (20,20))
# char_rect = char.get_rect()

x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
left = False
right = False
down = False
up = False
walkCount = 0
shop = pygame.transform.scale(pygame.image.load("shop.png"), (60, 60))

clock = pygame.time.Clock()
FPS = 60

bag = {'bomb': 0}
print(bag["bomb"])
class Button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):

        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 20)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (
                self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

def shop_run():
    shop_bomb = Button((0, 200, 0), 820, 150, 60, 20, text="Bomb_q")
    bright_green = (0, 255, 0)
    green = (0, 200, 0)
    shop_bomb.draw(screen)

def redrawGameWindow():
    global walkCount
    screen.fill([166, 166, 166])

    pygame.draw.rect(screen, (0, 0, 0), (800, 0, 100, 600))
    if x + char.get_width() < 60 and y + char.get_height() < 60:
        shop_run()

    screen.blit(shop, (0, 0))

    if walkCount + 1 >= 27:
        walkCount = 0

    if left:
        screen.blit(walkLeft[walkCount // 3], (x, y))
        walkCount += 1

    elif right:
        screen.blit(walkRight[walkCount // 3], (x, y))
        walkCount += 1

    elif down:
        screen.blit(char, (x, y))
        walkcount = 0

    elif up:
        screen.blit(char, (x, y))
        walkcount = 0

    else:
        screen.blit(char, (x, y))
        walkCount = 0

    buy = pygame.key.get_pressed()
    if buy[pygame.K_SPACE] and bag["bomb"] >= 1:
        screen.blit(bomb_pic,(x,y))
    pygame.display.update()

def main():
    run = True
    # shopper()
    pygame.display.set_caption("bomb-mania")

    global x
    global y
    global width
    global height
    global vel

    global isJump
    global jumpCount

    global left
    global right
    global down
    global up

    global walkCount

    global bomb_pic
    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if x + char.get_width() < 60 and y + char.get_height() < 60:
                buy = pygame.key.get_pressed()
                if buy[pygame.K_q]:
                    bag["bomb"] += 1
                    print(bag["bomb"])

        redrawGameWindow()

        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT] and x > vel - 15:
            x -= vel
            left = True
            right = False
            down = False
            up = False

        elif keys[pygame.K_RIGHT] and x < 800 - vel - width:
            x += vel
            left = False
            right = True[![enter image description here][1]][1]
            down = False
            up = False

        elif keys[pygame.K_DOWN] and y < 600 - height:
            y += vel
            left = False
            right = False
            down = True
            up = False

        elif keys[pygame.K_UP] and y > vel - 15:
            y -= vel
            left = False
            right = False
            down = False
            up = True

        else:
            left = False
            right = False
            down = False
            up = False
            walkCount = 0

        clock.tick(FPS)
        pygame.display.flip()

main()

Body:
Add a list for the bombs:

bombs = []

Add the position of the bomb to the list, when space is pressed. Use the event loop and the KEYDOWN event to spawn bombs, because you want to drap only on bomb when the key is pressed rather than multiple bombs when the key is hold down:

def main():
    global bombs

    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                if event.key = pygame.K_SPACE and bag["bomb"] >= 1:
                    bombs.append((x, y))

            # [...]

Draw the bombs in redrawGameWindow in a loop:

def redrawGameWindow():
    # [...]

    for pos in bombs:
        screen.blit(bomb_pic, pos)
    pygame.display.update()


问:
Angular7 Mat-select intercept change
In my use case scenario I have a dropdown box (mat-select) which fills several input fields. Any change will fill the fields differently. Since the user could change a field I want to ask the user before the final change is executed if (s)he agree to clear(or change) all fields. In case of a NO the selection change will not happen and all fields should remain.

I tried to reduce the use case to a sample. I can select an item from the  dropdown and do some further actions.

```<code>  <mat-select (selectionChange)="intercept($event.value)">
    <mat-option *ngFor="let food of foods" [value]="food.value" >
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</code>```

But at the time the selectionchange is exectued the content of the dropdown is already changed. For the sample I would like to have e.g.

Select e.g. Pizza

Popup appears

!The dropdown remains on the original selection and after the popup disappears a change happen!

Select e.g. Tacos

Popup appears

!The dropdown remains on the original selection (=Tacos) and after the popup disappears a change happen!

I have no clue how to intercept the change event before the change happen.

答:
Here's what i do.

template:

```<code><mat-select [ngModel]="something"
            (ngModelChange)="changeSomething($event, ngModelControl)"
            #ngModelControl="ngModel">
   ...
</mat-select>
</code>```

code:

```<code>changeSomething(value: any, ngModelControl: NgModel) {
  if (<<false for whatever reason>>) {
    // reset mat-select
    ngModelControl.control.setValue(this.something);
  } else {
    this.something = value;
  }
}
</code>```

Title: Angular7 Mat-select intercept change

Body:
In my use case scenario I have a dropdown box (mat-select) which fills several input fields. Any change will fill the fields differently. Since the user could change a field I want to ask the user before the final change is executed if (s)he agree to clear(or change) all fields. In case of a NO the selection change will not happen and all fields should remain.

I tried to reduce the use case to a sample. I can select an item from the  dropdown and do some further actions.

  <mat-select (selectionChange)="intercept($event.value)">
    <mat-option *ngFor="let food of foods" [value]="food.value" >
      {{food.viewValue}}
    </mat-option>
  </mat-select>

But at the time the selectionchange is exectued the content of the dropdown is already changed. For the sample I would like to have e.g.

Select e.g. Pizza

Popup appears

!The dropdown remains on the original selection and after the popup disappears a change happen!

Select e.g. Tacos

Popup appears

!The dropdown remains on the original selection (=Tacos) and after the popup disappears a change happen!

I have no clue how to intercept the change event before the change happen.

Body:
Here's what i do.

template:

<mat-select [ngModel]="something"
            (ngModelChange)="changeSomething($event, ngModelControl)"
            #ngModelControl="ngModel">
   ...
</mat-select>

code:

changeSomething(value: any, ngModelControl: NgModel) {
  if (<<false for whatever reason>>) {
    // reset mat-select
    ngModelControl.control.setValue(this.something);
  } else {
    this.something = value;
  }
}


问:
Can someone explain this regular expression?
```<code>(.*)([0-9]{6})|(.*)([0-9]{4})
</code>```

<p>Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ? </p>

答:
it means any characters followed by either 6 or 4 digits

you think you could write it like this (.*)(\d{4}|\d{6}) but the capturing groups would change

ContentLicense: CC BY-SA 3.0

Body:
(.*)([0-9]{6})|(.*)([0-9]{4})

Does it mean pick up a number that is either 6 digits or 4 digits ? Is there a concise way to write it ?


问:
Sending a TCP message using PHP
I have an application that is listening on a port for TCP messages, and i need to write a PHP script that can send them.

This is what i am using for sending the TCP message but i dont know what is going wrong and i keep getting error 500. I am using Laravel.

```<code>public function tcp_msg(Request $request){

 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    if ($socket === false) {
        $m1 = "Socket no creado";
        return $m1;
    }

    $msg = $request->Mensaje;
    $len = strlen($msg);

    $msg_error = 'Conexion no establecida';

    $conexion = socket_connect($socket, '127.0.0.1', 8688);

    if ($conexion === false) {
        $m2 = "No conectado";
        return $m2;
    }

    $resultado = socket_sendto($socket, $msg, $len, 0, '127.0.0.1', 8688);

    if($resultado){
        socket_close($socket);
        return $msg;
    }

    return $msg;

}
</code>```

答:
This looks quite ok - usually you just need socket_create() and socket_sendto() to send a correct message.

You can remove the part with:

```<code>$msg_error = 'Conexion no establecida';

$conexion = socket_connect($socket, '127.0.0.1', 8688);

if ($conexion === false) {
    $m2 = "No conectado";
    return $m2;
}
</code>```

Refering to https://www.php.net/manual/en/function.socket-sendto.php

```<code><?php
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)

    $msg = "Ping !";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);
    socket_close($sock);
?>
</code>```

You may have to check if the listener to the port 8688 is working... socket_sendto() returns the number of bytes sent to the remote host, or FALSE if an error occurred.

Title: Sending a TCP message using PHP

Body:
I have an application that is listening on a port for TCP messages, and i need to write a PHP script that can send them.

This is what i am using for sending the TCP message but i dont know what is going wrong and i keep getting error 500. I am using Laravel.

public function tcp_msg(Request $request){

 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    if ($socket === false) {
        $m1 = "Socket no creado";
        return $m1;
    }

    $msg = $request->Mensaje;
    $len = strlen($msg);

    $msg_error = 'Conexion no establecida';

    $conexion = socket_connect($socket, '127.0.0.1', 8688);

    if ($conexion === false) {
        $m2 = "No conectado";
        return $m2;
    }

    $resultado = socket_sendto($socket, $msg, $len, 0, '127.0.0.1', 8688);

    if($resultado){
        socket_close($socket);
        return $msg;
    }

    return $msg;

}

Body:
This looks quite ok - usually you just need socket_create() and socket_sendto() to send a correct message.

You can remove the part with:

$msg_error = 'Conexion no establecida';

$conexion = socket_connect($socket, '127.0.0.1', 8688);

if ($conexion === false) {
    $m2 = "No conectado";
    return $m2;
}

Refering to https://www.php.net/manual/en/function.socket-sendto.php

<?php
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)

    $msg = "Ping !";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);
    socket_close($sock);
?>

You may have to check if the listener to the port 8688 is working... socket_sendto() returns the number of bytes sent to the remote host, or FALSE if an error occurred.


问:
Discord.py - Is there a way to use *args or a parameter with multiple words without it being the last parameter?
Here is the current command:

```<code>`async def namemembers(self, ctx, members, name, *args):`
</code>```

This works fine enough, but I would like to add more parameters after *args, or if there is another way to use the name parameter to allow spaces and multiple words. If I try to do something like:

```<code>`async def namemembers(self, ctx, members, name, *args, worlds):`
</code>```

To define the world, it always says that world is a required argument that is missing. "Worlds" are split by a / but it still considers the / as part of the *args. Ideally I would have a command like this:

```<code>`async def nameM(self, ctx, name, *, worlds):`
</code>```

Which would allow me to use the name parameter with many words. Since currently using it this way "allows" me to input multiple words, but the bot sends back only the first word anyway.

Hopefully my question makes sense.

答:
No. *args is ambiguous because it takes any number of arguments, so there would be no way for Python to know when you're done with *args and onto worlds.

Python doesn't know and won't allow you to force worlds to be a kwarg only.

As a rule of thumb, you write methods with arguments in the following order:

def main(arg1, arg2, ..., *args, *kwargs):
    pass
```

Body:
Here is the current command:

`async def namemembers(self, ctx, members, name, *args):`

This works fine enough, but I would like to add more parameters after *args, or if there is another way to use the name parameter to allow spaces and multiple words. If I try to do something like:

`async def namemembers(self, ctx, members, name, *args, worlds):`

To define the world, it always says that world is a required argument that is missing. "Worlds" are split by a / but it still considers the / as part of the *args. Ideally I would have a command like this:

`async def nameM(self, ctx, name, *, worlds):`

Which would allow me to use the name parameter with many words. Since currently using it this way "allows" me to input multiple words, but the bot sends back only the first word anyway.

Hopefully my question makes sense.


问:
Two times form submitted, when I click the hide and show button
```<code>    **Component.ts**
     hide = true;
  constructor(private userService: UserService,
    private fb: FormBuilder,
    private alertService: AlertService
  ) { }

  signUpForm = this.fb.group({
    _id: ['s'],
    fullName: ['', [Validators.required, Validators.minLength(4)]],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirmPassword: ['', Validators.required]
  }, { validator: passwordMatchValidator })

  /* Shorthands for form controls (used from within template) */
  get fullName() { return this.signUpForm.get('fullName'); }
  get email() { return this.signUpForm.get('email'); }
  get password() { return this.signUpForm.get('password'); }
  get confirmPassword() { return this.signUpForm.get('confirmPassword'); }

  register() {
    if (this.signUpForm.invalid) {
      return;
    }
    this.userService.register(this.signUpForm.value).subscribe(data => {
      console.log(this.alertService.sucess('Registration Sucessful'));
    }, error => {
      this.alertService.error(error);
    })
  }

    **Component.html**

    <form
      class="example-form"
      [formGroup]="signUpForm"
      (ngSubmit)="register()"
      validate
    >
      <mat-form-field class="example-full-width">
        <mat-label>User Name</mat-label>
        <input matInput formControlName="fullName" />
        <mat-error *ngIf="fullName.hasError('required')">
          User Name is <strong>required</strong>
        </mat-error>
        <mat-error *ngIf="fullName.hasError('minlength')">
          User Name must have at least 4 characters
        </mat-error>
      </mat-form-field>
      <mat-form-field class="example-full-width">
        <mat-label>Email</mat-label>
        <input
          matInput
          formControlName="email"
          placeholder="Ex. pat@example.com"
        />
        <mat-error
          *ngIf="email.hasError('email') && !email.hasError('required')"
        >
          Please enter a valid email address
        </mat-error>
        <mat-error *ngIf="email.hasError('required')">
          Email is <strong>required</strong>
        </mat-error>
      </mat-form-field>
      <div class="example-container">
        <mat-form-field class="example-full-width">
          <mat-label>Password</mat-label>
          <input
            matInput
            (input)="onPasswordInput()"
            [type]="hide ? 'password' : 'text'"
            formControlName="password"
          />
          <mat-error *ngIf="password.hasError('required')"
            >Password is <strong>required</strong></mat-error
          >
          <mat-error *ngIf="password.hasError('minlength')"
            >Password must have at least 8 characters</mat-error
          >
          <button
            mat-icon-button
            matSuffix
            (click)="hide = !hide"
            [attr.aria-label]="'Hide password'"
            [attr.aria-pressed]="hide"
          >
            <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon>
          </button>
        </mat-form-field>
      </div>
      <div class="example-container">
        <mat-form-field class="example-full-width">
          <mat-label>Confirm Password</mat-label>
          <input
            matInput
            type="password"
            placeholder="Confirm password"
            formControlName="confirmPassword"
            (input)="onPasswordInput()"
          />
          <mat-error *ngIf="confirmPassword.hasError('required')"
            >Please confirm your password</mat-error
          >
          <mat-error
            *ngIf="
              confirmPassword.invalid && !confirmPassword.hasError('required')
            "
            >Passwords don't match</mat-error
          >
        </mat-form-field>
        <div class="example-button-row">
          <button
            mat-raised-button
            color="primary"
            type="submit"
            [disabled]="!signUpForm.valid"
          >
            Submit
          </button>
          <a mat-raised-button routerLink="/login" color="accent">Cancel</a>
        </div>
      </div>
    </form>
</code>```

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this.

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this

答:
It is because your button hide, is inside the form, so it's considered as submit button, you should add:

```<code>type="button"
</code>```

to all your button inside the form, that are not submit buttons.

```<code><button
        mat-icon-button
        matSuffix
        type="button"
        (click)="hide = !hide"
        [attr.aria-label]="'Hide password'"
        [attr.aria-pressed]="hide"
      >
        <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon>
      </button>
</code>```

Body:
    **Component.ts**
     hide = true;
  constructor(private userService: UserService,
    private fb: FormBuilder,
    private alertService: AlertService
  ) { }

  signUpForm = this.fb.group({
    _id: ['s'],
    fullName: ['', [Validators.required, Validators.minLength(4)]],
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirmPassword: ['', Validators.required]
  }, { validator: passwordMatchValidator })

  /* Shorthands for form controls (used from within template) */
  get fullName() { return this.signUpForm.get('fullName'); }
  get email() { return this.signUpForm.get('email'); }
  get password() { return this.signUpForm.get('password'); }
  get confirmPassword() { return this.signUpForm.get('confirmPassword'); }

  register() {
    if (this.signUpForm.invalid) {
      return;
    }
    this.userService.register(this.signUpForm.value).subscribe(data => {
      console.log(this.alertService.sucess('Registration Sucessful'));
    }, error => {
      this.alertService.error(error);
    })
  }

    **Component.html**

    <form
      class="example-form"
      [formGroup]="signUpForm"
      (ngSubmit)="register()"
      validate
    >
      <mat-form-field class="example-full-width">
        <mat-label>User Name</mat-label>
        <input matInput formControlName="fullName" />
        <mat-error *ngIf="fullName.hasError('required')">
          User Name is required
        </mat-error>
        <mat-error *ngIf="fullName.hasError('minlength')">
          User Name must have at least 4 characters
        </mat-error>
      </mat-form-field>
      <mat-form-field class="example-full-width">
        <mat-label>Email</mat-label>
        <input
          matInput
          formControlName="email"
          placeholder="Ex. pat@example.com"
        />
        <mat-error
          *ngIf="email.hasError('email') && !email.hasError('required')"
        >
          Please enter a valid email address
        </mat-error>
        <mat-error *ngIf="email.hasError('required')">
          Email is required
        </mat-error>
      </mat-form-field>

        <mat-form-field class="example-full-width">
          <mat-label>Password</mat-label>
          <input
            matInput
            (input)="onPasswordInput()"
            [type]="hide ? 'password' : 'text'"
            formControlName="password"
          />
          <mat-error *ngIf="password.hasError('required')"
            >Password is required</mat-error
          >
          <mat-error *ngIf="password.hasError('minlength')"
            >Password must have at least 8 characters</mat-error
          >
          <button
            mat-icon-button
            matSuffix
            (click)="hide = !hide"
            [attr.aria-label]="'Hide password'"
            [attr.aria-pressed]="hide"
          >
            <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon>
          </button>
        </mat-form-field>

        <mat-form-field class="example-full-width">
          <mat-label>Confirm Password</mat-label>
          <input
            matInput
            type="password"
            placeholder="Confirm password"
            formControlName="confirmPassword"
            (input)="onPasswordInput()"
          />
          <mat-error *ngIf="confirmPassword.hasError('required')"
            >Please confirm your password</mat-error
          >
          <mat-error
            *ngIf="
              confirmPassword.invalid && !confirmPassword.hasError('required')
            "
            >Passwords don't match</mat-error
          >
        </mat-form-field>

          <button
            mat-raised-button
            color="primary"
            type="submit"
            [disabled]="!signUpForm.valid"
          >
            Submit
          </button>
          Cancel

    </form>

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this.

When I try to show and hide the password button it working fine with hiding and show functionality, but when I click the same button two or more times continuously it behaves as form submit and showing all forms fields are showing errors how can we resolve it, can anyone help me on this

Body:
It is because your button hide, is inside the form, so it's considered as submit button, you should add:

type="button"

to all your button inside the form, that are not submit buttons.

<button
        mat-icon-button
        matSuffix
        type="button"
        (click)="hide = !hide"
        [attr.aria-label]="'Hide password'"
        [attr.aria-pressed]="hide"
      >
        <mat-icon>{{ hide ? "visibility_off" : "visibility" }}</mat-icon>
      </button>


问:
Programmatically navigate to new view in SwiftUI
Descriptive example:

login screen, user taps "Login" button, request is performed, UI shows waiting indicator, then after successful response I'd like to automatically navigate user to the next screen.

How can I achieve such automatic transition in SwiftUI?

答:
To expound what others have elaborated above based on changes on combine as of Swift Version 5.2 it could be simplified using publishers.

Create a class names UserAuth as shown below don't forget to import import Combine.

```<code>class UserAuth: ObservableObject {
        @Published var isLoggedin:Bool = false

        func login() {
            self.isLoggedin = true
        }
    }
</code>```

Update SceneDelegate.Swift with

let contentView =  ContentView().environmentObject(UserAuth())

Your authentication view

```<code> struct LoginView: View {
    @EnvironmentObject  var  userAuth: UserAuth
    var body: some View {
        ...
    if ... {
    self.userAuth.login()
    } else {
    ...
    }
 }
}

</code>```

Your dashboard after successful authentication, if the authentication userAuth.isLoggedin = true then it will be loaded.

```<code>   struct NextView: View {
     var body: some View {
     ...
     }
   }
</code>```

Lastly, the initial view to be loaded once the application is launched.

```<code>struct ContentView: View {
    @EnvironmentObject var userAuth: UserAuth
    var body: some View {
        if !userAuth.isLoggedin {
                LoginView()
            } else {
                NextView()
            }
    }
  }
</code>```

Body:
To expound what others have elaborated above based on changes on combine as of Swift Version 5.2 it could be simplified using publishers.

Create a class names UserAuth as shown below don't forget to import import Combine.

class UserAuth: ObservableObject {
        @Published var isLoggedin:Bool = false

        func login() {
            self.isLoggedin = true
        }
    }

Update SceneDelegate.Swift with

let contentView =  ContentView().environmentObject(UserAuth())

Your authentication view

 struct LoginView: View {
    @EnvironmentObject  var  userAuth: UserAuth
    var body: some View {
        ...
    if ... {
    self.userAuth.login()
    } else {
    ...
    }
 }
}

Your dashboard after successful authentication, if the authentication userAuth.isLoggedin = true then it will be loaded.

   struct NextView: View {
     var body: some View {
     ...
     }
   }

Lastly, the initial view to be loaded once the application is launched.

struct ContentView: View {
    @EnvironmentObject var userAuth: UserAuth
    var body: some View {
        if !userAuth.isLoggedin {
                LoginView()
            } else {
                NextView()
            }
    }
  }


问:
How to group elements inside select element inside React JS?
Here is a codesandbox url for the working demo of the grouping of elements with react.

So my requirement is that once the user clicks on the drop down, the user can see the list of items which are grouped.

In this list is only one Group 1, so the list Group 1 is
coming but also one group is coming as undefined How can I
remove the undefined as group inside the drop down list and
whatever items are inside the undefined should be give some
padding-right.

I have already given the style mycustomselect inside
style.css but it still takes the default style. I want to remove the color green which is coming as the default.

Thanks and Regards.

答:
The problem is that your startDatePurchaseBehavior contains items missing the propery optgroup. Your for each loop over that object then uses undefined when it can't find the property as the object key. This is where it happens:

```<code> if (!groupedOptions[option.optgroup]) groupedOptions[option.optgroup] = [];
</code>```

In order to fix it, make sure that every object in the array has the prop optgroup, like optgroup: "Group 1" for all items in one array or another key for the items in two.

I could not find mycustomselect inside style.css, but you can fix your problem using this id selector:

```<code>#cars {
  color: unset;
  border: 1px solid black;
}
</code>```

Body:
The problem is that your startDatePurchaseBehavior contains items missing the propery optgroup. Your for each loop over that object then uses undefined when it can't find the property as the object key. This is where it happens:

 if (!groupedOptions[option.optgroup]) groupedOptions[option.optgroup] = [];

In order to fix it, make sure that every object in the array has the prop optgroup, like optgroup: "Group 1" for all items in one array or another key for the items in two.

I could not find mycustomselect inside style.css, but you can fix your problem using this id selector:

#cars {
  color: unset;
  border: 1px solid black;
}


问:
filtering a dataframe, present rows depending on the value of certain columns
I have the following type of dataframe and I want to leave only rows where columns that are named 'Model' are equal to 'BUY' or 'SELL'

Input:

```<code>          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4
0   2020-05-28   AAPL       gold       None  ...   STAND   STAND    STAND    STAND
1   2020-05-28   ABBV       gold  reiterate  ...   STAND   STAND    STAND    STAND
2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
4   2020-05-28   ADSK   standard       None  ...   STAND   STAND    STAND    STAND
..         ...    ...        ...        ...  ...     ...     ...      ...      ...
130 2020-05-28    WEX       gold       None  ...   STAND   STAND    STAND    STAND
131 2020-05-28   WYNN       gold       None  ...   STAND   STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND
133 2020-05-28    ZEN       gold  reiterate  ...   STAND   STAND    STAND    STAND
134 2020-05-28    ZEN     silver       None  ...   STAND   STAND    STAND    STAND

[135 rows x 58 columns]
</code>```

Output:

```<code>          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4

2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND
</code>```

I tried using the following masks but I've gotten NaNs on all my dataframe for some reason:

```<code>mask1 = signals.loc[:, 'ModelA1':] == 'BUY'
mask2 = signals.loc[:, 'ModelA1':] == 'SELL'
signals = signals[mask1 & mask2]
</code>```

The model columns go from A1, A2, A3, A4... to G1, G2, G3, G4.

Thanks for the help!

答:
```<code>model_cols = (cols for cols in signals.columns if cols.startswith("Model"))
mask = signals[model_cols].apply(lambda s: "BUY" in s.values or "SELL" in s.values, axis=1)
signals = signals[mask]
</code>```

We first get the "model" columns, then generate mask with your condition and use it.

Body:
I have the following type of dataframe and I want to leave only rows where columns that are named 'Model' are equal to 'BUY' or 'SELL'

Input:

          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4
0   2020-05-28   AAPL       gold       None  ...   STAND   STAND    STAND    STAND
1   2020-05-28   ABBV       gold  reiterate  ...   STAND   STAND    STAND    STAND
2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
4   2020-05-28   ADSK   standard       None  ...   STAND   STAND    STAND    STAND
..         ...    ...        ...        ...  ...     ...     ...      ...      ...
130 2020-05-28    WEX       gold       None  ...   STAND   STAND    STAND    STAND
131 2020-05-28   WYNN       gold       None  ...   STAND   STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND
133 2020-05-28    ZEN       gold  reiterate  ...   STAND   STAND    STAND    STAND
134 2020-05-28    ZEN     silver       None  ...   STAND   STAND    STAND    STAND

[135 rows x 58 columns]

Output:

          Date Ticker IssuerTier     Action  ... ModelG1 ModelG2  ModelG3  ModelG4

2   2020-05-28   ABMD   standard       None  ...   STAND   STAND    SELL     STAND
3   2020-05-28   ACAD       gold       None  ...   BUY     STAND    STAND    STAND
132 2020-05-28    ZEN       gold       None  ...   BUY     STAND    STAND    STAND

I tried using the following masks but I've gotten NaNs on all my dataframe for some reason:

mask1 = signals.loc[:, 'ModelA1':] == 'BUY'
mask2 = signals.loc[:, 'ModelA1':] == 'SELL'
signals = signals[mask1 & mask2]

The model columns go from A1, A2, A3, A4... to G1, G2, G3, G4.

Thanks for the help!

Body:
model_cols = (cols for cols in signals.columns if cols.startswith("Model"))
mask = signals[model_cols].apply(lambda s: "BUY" in s.values or "SELL" in s.values, axis=1)
signals = signals[mask]

We first get the "model" columns, then generate mask with your condition and use it.


问:
When calling a Lotusscript agent from a button on the web, how can I add a spinner so that until the agent is done the user knows it is processing?
I have a Lotusscript agent behind a submit button that takes a while to do everything....the user needs to know it is processing so that they do not click the button multiple times.

Am using @Command([RunAgent];"agentname") to kick the agent off.

How in Lotusscript could I add some kind of 'processing' indication, either a progress bar or a spinner or something?   I suppose I could embed some javascript inside the lotusscript, but hoping someone has a clean example or some tips to do this.

Maybe hiding the submit button at the same time if I use javascript via a display property on a  surrounding the button would help too.

答:
You can't do this with LotusScript coding, and while hiding the Submit button is a good idea, you're going to have to know when to unhide it. A simple @Command([RunAgent]...) call won't give you a way to do that.

You're going to have to redesign your form to include a significant amount of JavaScript and make an AJAX-style call to invoke your agent asynchronously via a ?OpenAgent URL sent in a POST request via XMLHttpRequest. Your main JavaScript code will continue after the call and launch the spinner, and the callback that you set up to handle the asynch return from the XMLHttpRequest can then either transition to a new page or stop the spinner by setting a variable that the spinner is checking once every second or two.


问:
How to save data offline using coredata, and if network comes(online) send the saved data to the API?
How to save data in offline using coredata, and if network comes(online) send the saved data to the API?

This is the code to save data:

```<code>func savePSaveInfo(cId: String, pId:String, createdBy:String, agep:String, languageId:String, emailId:String, mobileNumber:String,backendUpdate: Bool)
{
    let nameObj = NSEntityDescription.insertNewObject(forEntityName: "SaveInfo", into: context!) as! SaveInfo

    nameObj.cId = cId
    nameObj.pId = pId
    nameObj.createdBy = createdBy
    nameObj.agep = agep
    nameObj.languageId = languageId
    nameObj.emailId = emailId
    nameObj.mobileNumber = mobileNumber
    nameObj.backendUpdate = backendUpdate

    do{
        try context!.save()
    }catch{
        print("not saved")
    }
}
</code>```

答:
For inserting value in core data, I am sharing a example , you can set according to you data.

Step 1 :- Set the entity like this

Step 2:-

```<code>//MARK:- FOR CREATING NEW DATA
    func createData(){

        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext

        //Now let’s create an entity and new user records.
        let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!

        //final, we need to add some data to our newly created record for each keys using

        let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
        user.setValue(txtFldUsername.text!, forKeyPath: "username")
        user.setValue(txtFldEmail.text!, forKey: "email")
        user.setValue(txtFldPassword.text!, forKey: "password")

        retrieveData()
        //Now we have set all the values. The next step is to save them inside the Core Data

        do {
            try managedContext.save()

        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
</code>```

Stop 3:- For fetching data

```<code> //MARK:- FOR RETRIEVING OR FETCHING THE DATA
    func retrieveData() {

        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext

        //Prepare the request of type NSFetchRequest  for the entity
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")

        do {
            let result = try managedContext.fetch(fetchRequest)
            arrUserDetails.removeAll()
            for data in result as! [NSManagedObject] {
                print(data.value(forKey: "username") as! String)
                arrUserDetails.append(userData(username: (data.value(forKey: "username") as! String), email: (data.value(forKey: "email") as! String), password: (data.value(forKey: "password") as! String)))
            }
            tblView.reloadData()

        } catch {

            print("Failed")
        }
    }
</code>```

Still there is any issue , let me know about the query

Body:
How to save data in offline using coredata, and if network comes(online) send the saved data to the API?

This is the code to save data:

func savePSaveInfo(cId: String, pId:String, createdBy:String, agep:String, languageId:String, emailId:String, mobileNumber:String,backendUpdate: Bool)
{
    let nameObj = NSEntityDescription.insertNewObject(forEntityName: "SaveInfo", into: context!) as! SaveInfo

    nameObj.cId = cId
    nameObj.pId = pId
    nameObj.createdBy = createdBy
    nameObj.agep = agep
    nameObj.languageId = languageId
    nameObj.emailId = emailId
    nameObj.mobileNumber = mobileNumber
    nameObj.backendUpdate = backendUpdate

    do{
        try context!.save()
    }catch{
        print("not saved")
    }
}

Body:
For inserting value in core data, I am sharing a example , you can set according to you data.

Step 1 :- Set the entity like this

Step 2:-

//MARK:- FOR CREATING NEW DATA
    func createData(){

        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext

        //Now let’s create an entity and new user records.
        let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!

        //final, we need to add some data to our newly created record for each keys using

        let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
        user.setValue(txtFldUsername.text!, forKeyPath: "username")
        user.setValue(txtFldEmail.text!, forKey: "email")
        user.setValue(txtFldPassword.text!, forKey: "password")

        retrieveData()
        //Now we have set all the values. The next step is to save them inside the Core Data

        do {
            try managedContext.save()

        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }

Stop 3:- For fetching data

 //MARK:- FOR RETRIEVING OR FETCHING THE DATA
    func retrieveData() {

        //As we know that container is set up in the AppDelegates so we need to refer that container.
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

        //We need to create a context from this container
        let managedContext = appDelegate.persistentContainer.viewContext

        //Prepare the request of type NSFetchRequest  for the entity
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")

        do {
            let result = try managedContext.fetch(fetchRequest)
            arrUserDetails.removeAll()
            for data in result as! [NSManagedObject] {
                print(data.value(forKey: "username") as! String)
                arrUserDetails.append(userData(username: (data.value(forKey: "username") as! String), email: (data.value(forKey: "email") as! String), password: (data.value(forKey: "password") as! String)))
            }
            tblView.reloadData()

        } catch {

            print("Failed")
        }
    }

Still there is any issue , let me know about the query


问:
How to access the ISA configuration space and what does it look like?
How do you access the ISA configuration space programmatically and what does it look like -- how do you set base addresses for ISA PnP Option ROMs?</p>

答:
A card is selected using the ISA Isolation procedure as follows:

On power up, all Plug and Play cards detect the ISA bus reset signal, RESET_DRV, set their CSN to 0, and enter the Wait for Key state. The software must delay 2 msec after RESET_DRV before accessing the auto-configuration ports (address, read, write), this is so that the device can perform initial configuration, load initial configuration register values from non-volatile memory, set CSN to 0 and enter the wait for key state in time. Cards in the Wait for Key state do not respond to any access to their auto-configuration ports until the initiation key is detected and will ignore all ISA accesses to their Plug and Play interface.

The initiation key is sent by software by writing the sequence 6A,B5,DA,ED,F6,FB,7D,BE, DF,6F,37,1B,0D,86,C3,61 B0,58,2C,16,8B,45,A2,D1, E8,74,3A,9D,CE,E7,73,39 to the address port. When the ISA cards detect this sequence, they enter the sleep state. In this state, the cards listen for a Wake[CSN] command with the write data set to 0x00 by software. This Wake[CSN] command will send all cards to the Isolation state and entering this state it  resets the serial identifier/resource data pointer to the beginning.

The first time the cards enter the Isolation state it is necessary to set the READ_DATA port address using the Set RD_DATA port command (which is sent when you send an offset of 00h to the address port). Next, 72 pairs of reads are performed by software to the Serial Isolation register to isolate a card (offset 01h).

A read causes each card to place 55h on SDL[7:0] if the next bit of their serial identification number is 1. If it isn't 1 then it asserts nothing and checks SDL[1:0] which will be 01 if 55h has been asserted by another card. If it's 01b then it will assert AAh next read, if not 01b it will check for 10b next read. The next read from the isolation register by software causes the cards that asserted 55h or that did not detect 01b to assert AAh. The other cards check the lower 2 SDL bits for 01b. If 01b is present, they enter a sleep state. All other cards check if they've sent the final bit of the serial identifier, if not, they move to the next round. If they have, it will be the only card remaining.

The isolated card remains in the Isolation state while all other cards have failed the isolation protocol and have returned to the Sleep state.

Writes to the card control registers are intercepted by all devices in a sleep/isolation/config state and are interpreted as certain commands based on the data and what state they are in. A write to the wake register will be accepted by the card in the isolation state as the new CSN. The CSN on this card is set to a unique number. Writing this value causes this card to transition to the Config state. You then select a logical device number by writing to the LDN register, which only the device in Config state responds to by mapping the registers of that logical device below offset 0x30.

The configuration space looks like this:

In order to select a base address for a MMIO space (including Option ROM), you put a base address in a memory descptor at offset 0x40–0x5F. Presumably the upper limit register is written by the card to tell you how much memory it requires. On PCI, you write all 1s to the BAR to get the size. Not sure about ISA. There are 4 memory descriptors and 8 I/O descriptors. You configure a 24 bit address that resides somewhere in the 1MiB ISA hole below 16MiB that is programmed to be forwarded to the ISA Bridge.

In order to continue the isolation procedure to isolate the next card, A Wake[CSN] command with a parameter of zero (write to the Wake register offset 0x03) will force all cards without a CSN to enter the  Isolation state (a Wake[CSN] command with a parameter other than zero will force a card with a matching CSN to enter the config  state. Any card that is in an isolation or Config state that receives a CSN that is not it's own transitions to the Sleep state).

Don't forget that the ISA-XT bus appeared on 8086–80186 as an 8 bit bus with 20 bit addressing. 80286 chipsets and onwards it was 16 bit with 24 bit addressing. The 80486 SIO(.A) and IB southbridges were just single function PCI devices on the PCI bus that functioned as an ISA bridge. So was the PCEB southbridge (where the ESC subsouthbridge registers were accessed through IO ports). The PIIX–PIIX4E southbridges were multifunction PCI devices. The ICH0 southbridge was a multidevice and multifunction PCI device and the ISA bridge was an optional separate device on the PCI bus, separate to the southbridge.


问:
Choosing the Right Solution for Search and Indexing
We are working on headless application design and development. Currently, we are facing a **architectural question** which we need to find the answer to proceed with designing the system, we are not experts in the **search engine**, but we are doing research on this area.

Our tech stack is .net Core/SQL Server and in future we may plan to use Raven DB.

Instead of using content delivery API, we plan to use Query based content delivery to make it more flexible and reduce the overheads of API development for each front end framework. and We decided to use indexing and index for majority of the data management, i.e. to reduce the DB load. So basically most content operations will be handled using the indexes.

The problem we observed with Search Engine:
On the first cut, we planned to use Elastic Search, but again we understood the following issues.

The system will have a dynamic field management and field data management, i.e. user will be editing the fields, and field values while the system is running. for each time we may need to rebuild the index to update the field in elastic search (We are not experts in search engine), this will increase the network load which may not be feasible for us to operate in a large multitenant environment.

So we decided to go with Lucene.net, but before proceeding with lucene.net we want to make sure the following things can be solved.

Updating field dynamically without rebuilding indexing each time, does lucene support this or can we customize to manage this?

The second Issue is managing separate indexes for each tenant with a distributed architecture.

We plan to have a partition for each tenant in production so that data will not be in a single index. This is because we don't need to put high load on web server for managing permission-based query results, instead, Lucene will do this. so for any query results will be returned based on permission of the users who queried it, so it is better to have separate index for each tenant to reduce the operations.

Is it possible to have distributed Lucene implementation by having a partition for each tenant exclusively?

So kindly help in finding a solution for above two problems that we facing right now.

答:
Elasticsearch internally uses Lucene only, every elasticsearch index(made up of one or more shards) is internally a Lucene index. You can even think of Elasticsearch as a distributed Lucene which can be easily scaled to thousands of physical servers easily.

Now, this should clear you any doubt as all the low-level operation like updating a document and deleting the document is done by internally Lucene in case of Elasticsearch which is part 1 of your question.

Your first question

Q: Updating field dynamically without rebuilding indexing each time, does Lucene support this or can we customize to manage this?

You are just updating a single document, it would not cause the entire index to rebuild and you will get the updated document within 1 sec(default refresh interval) or you if want updated document immediately you can do an explicit refresh(Not recommended).

Coming to your second question:

Q: Is it possible to have distributed Lucene implementation by having a partition for each tenant exclusively?

Answer: As explained you can think of Elasticsearch as a distributed Lucence only and can create a separate index for each of tenant easily and they won't interface with each other data(although if you are storing multiple indices on the same Elasticsearch cluster there will not an infra resource isolation(CPU, memory)) etc and you can get the noisy neighbors issue.


问:
How to convert class component table to functional component
I am pretty new at React Hooks and Functional Components. If anyone would be so kind as to help I would so appreciate it. I have been working at this for hours now. </p>

<p>How do I turn the following table that uses class components into a table that uses functional components </p>

```<code>
class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      status: [
        { title: "Clients", view: 1, total: 20 },
        { title: "Returning Players", view: 3, total: 18 },
        { title: "New Players", view: 3, total: 20 },
        { title: "Pending Players", view: 4, total: 10 },
        { title: "Players who left", view: 3, total: 11 },
        { title: "Total Players", view: 15, total: 79 }
      ]
    };
  }

  PlayersTableHeader() {
    let header = Object.keys(this.state.status[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  }

  PlayersTableData() {
    return this.state.status.map((status, index) => {
      const { title, view, total } = status;
      return (
        <tr key={index}>
          <td>{title}</td>
          <td>{view}</td>
          <td>{total}</td>
        </tr>
      );
    });
  }

  render() {
    return (
      <div>
        <table id="status">
          <tbody>
            <tr>{this.PlayersTableHeader()}</tr>
            {this.PlayersTableData()}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Table;
</code>```

答:
```<code>import React, { Component, useState } from "react";

const Table = () => {
  const [state, setState] = useState({
    status: [
      { title: "Clients", view: 1, total: 20 },
      { title: "Returning Players", view: 3, total: 18 },
      { title: "New Players", view: 3, total: 20 },
      { title: "Pending Players", view: 4, total: 10 },
      { title: "Players who left", view: 3, total: 11 },
      { title: "Total Players", view: 15, total: 79 }
    ]
  });

  const PlayersTableHeader = () => {
    let header = Object.keys(state.status[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  };

  const PlayersTableData = () => {
    return state.status.map((status, index) => {
      const { title, view, total } = status;
      return (
        <tr key={index}>
          <td>{title}</td>
          <td>{view}</td>
          <td>{total}</td>
        </tr>
      );
    });
  };

  return (
    <div>
      <table id="status">
        <tbody>
          <tr>{PlayersTableHeader()}</tr>
          {PlayersTableData()}
        </tbody>
      </table>
    </div>
  );
};

export default Table;
</code>```

React Hooks is a powerful tool. Check this for reference

To set state in your Table Function now:

```<code>setState({ status: customStatus })
</code>```

Body:
I am pretty new at React Hooks and Functional Components. If anyone would be so kind as to help I would so appreciate it. I have been working at this for hours now.

How do I turn the following table that uses class components into a table that uses functional components

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      status: [
        { title: "Clients", view: 1, total: 20 },
        { title: "Returning Players", view: 3, total: 18 },
        { title: "New Players", view: 3, total: 20 },
        { title: "Pending Players", view: 4, total: 10 },
        { title: "Players who left", view: 3, total: 11 },
        { title: "Total Players", view: 15, total: 79 }
      ]
    };
  }

  PlayersTableHeader() {
    let header = Object.keys(this.state.status[0]);
    return header.map((key, index) => {
      return {key.toUpperCase()}	;
    });
  }

  PlayersTableData() {
    return this.state.status.map((status, index) => {
      const { title, view, total } = status;
      return (

          {title}
          {view}
          {total}

      );
    });
  }

  render() {
    return (

{this.PlayersTableHeader()}

            {this.PlayersTableData()}

    );
  }
}

export default Table;

Body:
import React, { Component, useState } from "react";

const Table = () => {
  const [state, setState] = useState({
    status: [
      { title: "Clients", view: 1, total: 20 },
      { title: "Returning Players", view: 3, total: 18 },
      { title: "New Players", view: 3, total: 20 },
      { title: "Pending Players", view: 4, total: 10 },
      { title: "Players who left", view: 3, total: 11 },
      { title: "Total Players", view: 15, total: 79 }
    ]
  });

  const PlayersTableHeader = () => {
    let header = Object.keys(state.status[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  };

  const PlayersTableData = () => {
    return state.status.map((status, index) => {
      const { title, view, total } = status;
      return (
        <tr key={index}>
          <td>{title}</td>
          <td>{view}</td>
          <td>{total}</td>
        </tr>
      );
    });
  };

  return (
    <div>
      <table id="status">
        <tbody>
          <tr>{PlayersTableHeader()}</tr>
          {PlayersTableData()}
        </tbody>
      </table>
    </div>
  );
};

export default Table;

React Hooks is a powerful tool. Check this for reference

To set state in your Table Function now:

setState({ status: customStatus })


问:
Why does TKinter open 2 windows when I add a background
I'm trying to add a background to my Tkinter window, but when I use this code, then It opens the background as a different Tkinter window and the main window as a seperate one. How can I make them into one?</p>

```<code>from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox

top = Tk()

C = Canvas(top, bg ="blue", height=250, width=300)
filename = PhotoImage(file = "C:/Users/plapl/Desktop/ching.pgm")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop()

def newfile():
    print("New File!")

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=newfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)

mainloop()
</code>```

答:
I have simplified your code and now it works for me in 1 window and also i imported a module you might have missed (PIL)

Code:

```<code>from tkinter import *
from PIL import ImageTk
from tkinter.filedialog import askopenfilename
from tkinter import messagebox

top = Tk()

C = Canvas(top, bg ="blue", height=250, width=300)
filename = ImageTk.PhotoImage(file = "C:/Users/plapl/Desktop/ching.pgm")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

def newfile():
    print("New File!")

menu = Menu(top)
top.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=newfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=top.quit)

top.mainloop()
</code>```

Body:
I'm trying to add a background to my Tkinter window, but when I use this code, then It opens the background as a different Tkinter window and the main window as a seperate one. How can I make them into one?

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter import messagebox

top = Tk()

C = Canvas(top, bg ="blue", height=250, width=300)
filename = PhotoImage(file = "C:/Users/plapl/Desktop/ching.pgm")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop()

def newfile():
    print("New File!")

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=newfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)

mainloop()

Body:
I have simplified your code and now it works for me in 1 window and also i imported a module you might have missed (PIL)

Code:

from tkinter import *
from PIL import ImageTk
from tkinter.filedialog import askopenfilename
from tkinter import messagebox

top = Tk()

C = Canvas(top, bg ="blue", height=250, width=300)
filename = ImageTk.PhotoImage(file = "C:/Users/plapl/Desktop/ching.pgm")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

def newfile():
    print("New File!")

menu = Menu(top)
top.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=newfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=top.quit)

top.mainloop()


问:
fork with Ruby 1.8 and Windows
I'm using ruby 1.8.7 patchlevel 302 and I'm working on a Windows xp system.
I have to start an external process that needs to react on user input. The process doesn't react if I use threads, so I tried using fork. With fork the external process reacts on the user input but it executes more than just the fork block. For example

```<code>fork do
  puts 'child'
end
puts 'parent'
Process.wait
puts 'done'</code>```

produces the following output on my machine:

```<code>parent
child
parent
done
done
</code>```

As you can see 'done' and 'parent' is printed twice. What can I do to make the child execute only its block and not more? (I can't switch to Ruby 1.9 because of some gems)

答:
Like that:</p>

```<code>if child = fork
  puts 'parent'
  Process.wait
  puts 'done'
else
  puts 'child'
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: fork with Ruby 1.8 and Windows

Body:
I'm using ruby 1.8.7 patchlevel 302 and I'm working on a Windows xp system.
I have to start an external process that needs to react on user input. The process doesn't react if I use threads, so I tried using fork. With fork the external process reacts on the user input but it executes more than just the fork block. For example

fork do
  puts 'child'
end
puts 'parent'
Process.wait
puts 'done'

produces the following output on my machine:

parent
child
parent
done
done

As you can see 'done' and 'parent' is printed twice. What can I do to make the child execute only its block and not more? (I can't switch to Ruby 1.9 because of some gems)

Body:
Like that:

if child = fork
  puts 'parent'
  Process.wait
  puts 'done'
else
  puts 'child'
end


问:
Is it possible to list endorsing peers of a chaincode in the application?
In Hyperledger ledger, how could I list endorsing peers of a specific chaincode?
I have a channel with 5 peers but I need that only three of them endorse a transaction while the other two need only to access to same ledger. </p>

答:
With the latest Fabric Client SDKs (personally using GO client), you don't need to deal with endorsement policies. Client SDK already does this dirty work for you. It extracts:

Which organizations' endorsements are required for this chaincode, key (key level endorsement policy can be defined as well), etc.

Which peers currently exist in the system and what are their MSPs (from discovery service).

According to these information, client SDK builds a set of necessary peers then sends your transaction request to all. It waits response from requested endorsers. Once it collects all responses, it sends to orderer and so on.

If you have a special case which you need to manually set endorsing peers of your choice (I had one use case about private collections so I had to use this approach) check out discovery service API of your client SDK.


问:
How to fix java.lang.UnsupportedOperationException ? ( Kotlin - Android Studio )
I'm trying to add an intem to my arrayList when there new values added on my firebase database using this peace of code THIS IS A SAMPLE CODE ( the error happens when you click on send button ):

```<code>ref.addChildEventListener(object : ChildEventListener {

        override fun onCancelled(p0: DatabaseError) {
        }

        override fun onChildMoved(p0: DataSnapshot, p1: String?) {
        }

        override fun onChildChanged(dataSnapshot: DataSnapshot, p1: String?) {
        }

        @SuppressLint("LongLogTag")
        override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {

            val newMSG: Messages? = dataSnapshot.getValue(Messages::class.java)

            val myrv = findViewById<RecyclerView>(R.id.msgRV)
            name = dataSnapshot.child("name").value.toString()
            muid = dataSnapshot.child("muid").value.toString()
            time = dataSnapshot.child("time").value.toString()
            message = dataSnapshot.child("message").value.toString()
            var contained = false
                messagesArrayList.forEach{ contained =  it.time !=time}
            if (messagesArrayList.isNotEmpty() && contained){
                messagesArrayList.add(Messages(newMSG?.name, newMSG?.mUID, newMSG?.time, newMSG?.message)) // The error is pointing here
                messagesArrayList = messagesArrayList.sortedWith(compareBy { it.time }) as MutableList<Messages>
                val myModulesAdapter = MessageRV(this@MessageActivity, messagesArrayList)
                myrv.layoutManager = GridLayoutManager(this@MessageActivity, 1)
                myrv.adapter = myModulesAdapter
                myrv.scrollToPosition(myModulesAdapter.itemCount - 1)

            }

        }

        override fun onChildRemoved(p0: DataSnapshot) {
        }
    })
</code>```

But i got this error :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.medanis.medmax, PID: 3533
    java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:153)
        at java.util.AbstractList.add(AbstractList.java:111)
        at com.medanis.medmax.messages.MessageActivity$onCreate$3.onChildAdded(MessageActivity.kt:148)
        at com.google.firebase.database.core.ChildEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.3.0:79)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.3.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.3.0:55)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
</code>```

Can anyone tell me what went wrong? How can I fix it?

NOTE : your database must be structred like this:
  Messages/MoIfH0sbt2UjJj7yozXRQF72RgK2/w691O35sZ2hvDpkTbAnm6aaTjZj1/
  then a value of time in this format yyyyMMddHHmmss the Message Model content

SOLLUTION:
Thanks to @Slaw and @AlexMamo, i solved the problem by changing {  as MutableList } to { .toMutableList() }

(name, muid, time, message)

Body:
I'm trying to add an intem to my arrayList when there new values added on my firebase database using this peace of code THIS IS A SAMPLE CODE ( the error happens when you click on send button ):

ref.addChildEventListener(object : ChildEventListener {

        override fun onCancelled(p0: DatabaseError) {
        }

        override fun onChildMoved(p0: DataSnapshot, p1: String?) {
        }

        override fun onChildChanged(dataSnapshot: DataSnapshot, p1: String?) {
        }

        @SuppressLint("LongLogTag")
        override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {

            val newMSG: Messages? = dataSnapshot.getValue(Messages::class.java)

            val myrv = findViewById<RecyclerView>(R.id.msgRV)
            name = dataSnapshot.child("name").value.toString()
            muid = dataSnapshot.child("muid").value.toString()
            time = dataSnapshot.child("time").value.toString()
            message = dataSnapshot.child("message").value.toString()
            var contained = false
                messagesArrayList.forEach{ contained =  it.time !=time}
            if (messagesArrayList.isNotEmpty() && contained){
                messagesArrayList.add(Messages(newMSG?.name, newMSG?.mUID, newMSG?.time, newMSG?.message)) // The error is pointing here
                messagesArrayList = messagesArrayList.sortedWith(compareBy { it.time }) as MutableList<Messages>
                val myModulesAdapter = MessageRV(this@MessageActivity, messagesArrayList)
                myrv.layoutManager = GridLayoutManager(this@MessageActivity, 1)
                myrv.adapter = myModulesAdapter
                myrv.scrollToPosition(myModulesAdapter.itemCount - 1)

            }

        }

        override fun onChildRemoved(p0: DataSnapshot) {
        }
    })

But i got this error :

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.medanis.medmax, PID: 3533
    java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:153)
        at java.util.AbstractList.add(AbstractList.java:111)
        at com.medanis.medmax.messages.MessageActivity$onCreate$3.onChildAdded(MessageActivity.kt:148)
        at com.google.firebase.database.core.ChildEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.3.0:79)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.3.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.3.0:55)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7478)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)

Can anyone tell me what went wrong? How can I fix it?

NOTE : your database must be structred like this:
  Messages/MoIfH0sbt2UjJj7yozXRQF72RgK2/w691O35sZ2hvDpkTbAnm6aaTjZj1/
  then a value of time in this format yyyyMMddHHmmss the Message Model content

SOLLUTION:
Thanks to @Slaw and @AlexMamo, i solved the problem by changing {  as MutableList } to { .toMutableList() }

(name, muid, time, message)


问:
Nested loops in Go templates
coders.
I need to render the nested struct data in go template. I wonder if it possible to do with nested loops in .gohtml template file.
Here is my .gohtml code:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charser="utf-8" />
        <title>Go templates</title>
    </head>
    <body>
        <ul>
            {{range $city := .}}
                <li>
                    name: {{$city.name}}
                    hotels:
                        <ul>
                            {{range $hotel := $city.hotels}}
                                <li>
                                    name: {{$hotel.name}}
                                    address: {{$hotel.address}}
                                    zip: {{$hotel.zip}}
                                </li>
                            {{end}}
                        </ul>
                </li>
            {{end}}
        </ul>
    </body>
</html>
</code>```

Here is main.go code:

```<code>package main

import (
    "os"
    "text/template"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.New("").ParseGlob("./*.gohtml"))
}

func main() {
    type hotel struct {
        name    string
        address string
        city    string
        zip     int
    }
    type city struct {
        name   string
        hotels []hotel
    }
    type region struct {
        cities []city
    }

    hotel1 := hotel{
        "Lambda",
        "Street 19",
        "Some city",
        65530,
    }
    hotel2 := hotel{
        "Black Sea",
        "Street 21",
        "Some city",
        65543,
    }
    hotel3 := hotel{
        "Blue Sea",
        "Street 15",
        "Some city",
        54400,
    }
    hotel4 := hotel{
        "Yellow Submarine",
        "The Beatles Square",
        "Some city",
        54401,
    }
    hotel5 := hotel{
        "LolKek",
        "Cheburek",
        "Some city",
        14213,
    }

    city1 := city{
        "Some city",
        []hotel{hotel1, hotel2},
    }
    city2 := city{
        "Some city",
        []hotel{hotel3, hotel4},
    }
    city3 := city{
        "Some city",
        []hotel{hotel5},
    }

    someRegion := region{
        []city{city1, city2, city3},
    }

    tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion)
}

</code>```

There is no error in the terminal when go run main.go, but I don't understand why the output looks like this:

```<code><!DOCTYPE html>
<html>
        <head>
                <meta charser="utf-8" />
                <title>Go templates</title>
        </head>
        <body>
                <ul>
</code>```

Why is it cutted?

答:
You don't see any errors because you're not checking errors, you're omitting them.

Template.ExecuteTemplate() returns an error, do check it:

```<code>if err := tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion); err != nil {
    fmt.Println(err)
}
</code>```

This will output:

```<code>template: :9:29: executing "" at <.>: range can't iterate over {[{Some city [{Lambda Street 19 Some city 65530} {Black Sea Street 21 Some city 65543}]} {Some city [{Blue Sea Street 15 Some city 54400} {Yellow Submarine The Beatles Square Some city 54401}]} {Some city [{LolKek Cheburek Some city 14213}]}]}
</code>```

The error is clear: you pass a struct for execution, and then you try to range over it. You can't. Range over the slice:

```<code>{{range $city := .cities}}
</code>```

This of course won't work: you have to export the struct field to be able to access it inside the template.

```<code>type region struct {
    Cities []city
}
</code>```

And in template:

```<code>{{range $city := .Cities}}
</code>```

You also have to export other struct fields:

```<code>type hotel struct {
    Name    string
    Address string
    City    string
    Zip     int
}
type city struct {
    Name   string
    Hotels []hotel
}
</code>```

After these changes it will work and output (try it on the Go Playground):

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charser="utf-8" />
        <title>Go templates</title>
    </head>
    <body>
        <ul>

                <li>
                    name: Some city
                    hotels:
                        <ul>

                                <li>
                                    name: Lambda
                                    address: Street 19
                                    zip: 65530
                                </li>

                                <li>
                                    name: Black Sea
                                    address: Street 21
                                    zip: 65543
                                </li>

                        </ul>
                </li>

                <li>
                    name: Some city
                    hotels:
                        <ul>

                                <li>
                                    name: Blue Sea
                                    address: Street 15
                                    zip: 54400
                                </li>

                                <li>
                                    name: Yellow Submarine
                                    address: The Beatles Square
                                    zip: 54401
                                </li>

                        </ul>
                </li>

                <li>
                    name: Some city
                    hotels:
                        <ul>

                                <li>
                                    name: LolKek
                                    address: Cheburek
                                    zip: 14213
                                </li>

                        </ul>
                </li>

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

Title: Nested loops in Go templates

Body:
coders.
I need to render the nested struct data in go template. I wonder if it possible to do with nested loops in .gohtml template file.
Here is my .gohtml code:

<!DOCTYPE html>

        <meta charser="utf-8" />
        <title>Go templates</title>

            {{range $city := .}}

                    name: {{$city.name}}
                    hotels:

                            {{range $hotel := $city.hotels}}

                                    name: {{$hotel.name}}
                                    address: {{$hotel.address}}
                                    zip: {{$hotel.zip}}

                            {{end}}

            {{end}}

Here is main.go code:

package main

import (
    "os"
    "text/template"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.New("").ParseGlob("./*.gohtml"))
}

func main() {
    type hotel struct {
        name    string
        address string
        city    string
        zip     int
    }
    type city struct {
        name   string
        hotels []hotel
    }
    type region struct {
        cities []city
    }

    hotel1 := hotel{
        "Lambda",
        "Street 19",
        "Some city",
        65530,
    }
    hotel2 := hotel{
        "Black Sea",
        "Street 21",
        "Some city",
        65543,
    }
    hotel3 := hotel{
        "Blue Sea",
        "Street 15",
        "Some city",
        54400,
    }
    hotel4 := hotel{
        "Yellow Submarine",
        "The Beatles Square",
        "Some city",
        54401,
    }
    hotel5 := hotel{
        "LolKek",
        "Cheburek",
        "Some city",
        14213,
    }

    city1 := city{
        "Some city",
        []hotel{hotel1, hotel2},
    }
    city2 := city{
        "Some city",
        []hotel{hotel3, hotel4},
    }
    city3 := city{
        "Some city",
        []hotel{hotel5},
    }

    someRegion := region{
        []city{city1, city2, city3},
    }

    tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion)
}

There is no error in the terminal when go run main.go, but I don't understand why the output looks like this:

<!DOCTYPE html>

                <meta charser="utf-8" />
                <title>Go templates</title>

Why is it cutted?

Body:
You don't see any errors because you're not checking errors, you're omitting them.

Template.ExecuteTemplate() returns an error, do check it:

if err := tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", someRegion); err != nil {
    fmt.Println(err)
}

This will output:

template: :9:29: executing "" at <.>: range can't iterate over {[{Some city [{Lambda Street 19 Some city 65530} {Black Sea Street 21 Some city 65543}]} {Some city [{Blue Sea Street 15 Some city 54400} {Yellow Submarine The Beatles Square Some city 54401}]} {Some city [{LolKek Cheburek Some city 14213}]}]}

The error is clear: you pass a struct for execution, and then you try to range over it. You can't. Range over the slice:

{{range $city := .cities}}

This of course won't work: you have to export the struct field to be able to access it inside the template.

type region struct {
    Cities []city
}

And in template:

{{range $city := .Cities}}

You also have to export other struct fields:

type hotel struct {
    Name    string
    Address string
    City    string
    Zip     int
}
type city struct {
    Name   string
    Hotels []hotel
}

After these changes it will work and output (try it on the Go Playground):

<!DOCTYPE html>
<html>
    <head>
        <meta charser="utf-8" />
        <title>Go templates</title>
    </head>
    <body>
        <ul>

                <li>
                    name: Some city
                    hotels:
                        <ul>

                                <li>
                                    name: Lambda
                                    address: Street 19
                                    zip: 65530
                                </li>

                                <li>
                                    name: Black Sea
                                    address: Street 21
                                    zip: 65543
                                </li>

                        </ul>
                </li>

                <li>
                    name: Some city
                    hotels:
                        <ul>

                                <li>
                                    name: Blue Sea
                                    address: Street 15
                                    zip: 54400
                                </li>

                                <li>
                                    name: Yellow Submarine
                                    address: The Beatles Square
                                    zip: 54401
                                </li>

                        </ul>
                </li>

                <li>
                    name: Some city
                    hotels:
                        <ul>

                                <li>
                                    name: LolKek
                                    address: Cheburek
                                    zip: 14213
                                </li>

                        </ul>
                </li>

        </ul>
    </body>
</html>