问:
How to bind checkboxes with Angular in reactive forms
Actually, I made a dummy project on health care so in that I made a component having Test Services in that I made a Radio Button, on the click of the radio Specific data goes to dropdown which is Services, and on the click on specific service I need sub-services in checkboxes and then on the click of submit I need that goes to JSON server.

I tried I made every thing radio dependent dropdown n checkboxes too but, when I check with the debugger it fetches the target value in the check box only true no value, so I need value in the checkboxes.

In this image, I bind the data from .ts to HTML and apply the for loop [In this ts file I call the change event with the event.target.value here in change service I get the value but when I see with debugger its an empty string only.

The test service with the subservice data:
the HTML file here I made custom checkboxes and bind them with subServiices

Code:

```<code><!-- For SubServices checkboxes -->
<div class="d-flex flex-row align-items-center mb-4">
  <i class="fa fa-lock fa-lg me-3 fa-fw"></i>
  <div class="form-outline flex-fill mb-0">
    <div class="form-check form-check-inline">
      <!-- <label for="testService" class="form-label">Sub Services</label><br> -->
      <!-- (change)="onCheckboxChange ($event)" -->
      <div class="check" *ngFor="let sub of subServiceList"> --> <input class="form-check-input" type="checkbox"
          formControlName="subService" | id="flexCheckChecked" [value]="sub.subService_id"
          (change)="onCheckChange($event)"> <label class="form-check-label" for="flexCheckChecked">
          {{sub.subService_name}}
          <!-- [checked]="{{sub.select}}" -->
        </label>
      </div>
    </div>
  </div>
</div>
</code>```

The ts file here I create the change event with the help of that I get my target id

Code:

```<code>  //to change the service calling change event and shows the dependent subservice in dropdown
  changeService(event: any) {
    debugger;
    let serviceId = event.target.value;
    this.subServiceList = this.testService.
      getSubService().
      filter((u) => u.service_id == serviceId);
    console.log(this.subServicelist);
  }

  onCheckChange(event: any) {
    const checkid = event.target.value;
    console.log(checkid);
    this.subServiceList = this.subServicelist.filter(
      (e) => e.subService_id == checkid
    );
  }
</code>```

The test service here I made the JSON data so that I can fetch that

Code:

```<code>getSubService(): ISubService[] {
  return [
    {
      subService_id: 1501,
      service_id: 115,
      select: false,
      subService_name: 'X-RAY both Kneen',
    },
    {
      subService_id: 1502,
      service_id: 115,
      select: false,
      subService_name: 'X-RAY chest',
    },
    {
      subService_id: 1503,
      service_id: 115,
      select: false,
      subService_name: 'X-RAY spine',
    },
  ]
}
</code>```

The issue which I facing that I don't get the value of subservice in the request of post

Body:
Actually, I made a dummy project on health care so in that I made a component having Test Services in that I made a Radio Button, on the click of the radio Specific data goes to dropdown which is Services, and on the click on specific service I need sub-services in checkboxes and then on the click of submit I need that goes to JSON server.

I tried I made every thing radio dependent dropdown n checkboxes too but, when I check with the debugger it fetches the target value in the check box only true no value, so I need value in the checkboxes.

In this image, I bind the data from .ts to HTML and apply the for loop [In this ts file I call the change event with the event.target.value here in change service I get the value but when I see with debugger its an empty string only.

The test service with the subservice data:
the HTML file here I made custom checkboxes and bind them with subServiices

Code:

 --> <input class="form-check-input" type="checkbox"
          formControlName="subService" | id="flexCheckChecked" [value]="sub.subService_id"
          (change)="onCheckChange($event)">
          {{sub.subService_name}}

The ts file here I create the change event with the help of that I get my target id

Code:

  //to change the service calling change event and shows the dependent subservice in dropdown
  changeService(event: any) {
    debugger;
    let serviceId = event.target.value;
    this.subServiceList = this.testService.
      getSubService().
      filter((u) => u.service_id == serviceId);
    console.log(this.subServicelist);
  }

  onCheckChange(event: any) {
    const checkid = event.target.value;
    console.log(checkid);
    this.subServiceList = this.subServicelist.filter(
      (e) => e.subService_id == checkid
    );
  }

The test service here I made the JSON data so that I can fetch that

Code:

getSubService(): ISubService[] {
  return [
    {
      subService_id: 1501,
      service_id: 115,
      select: false,
      subService_name: 'X-RAY both Kneen',
    },
    {
      subService_id: 1502,
      service_id: 115,
      select: false,
      subService_name: 'X-RAY chest',
    },
    {
      subService_id: 1503,
      service_id: 115,
      select: false,
      subService_name: 'X-RAY spine',
    },
  ]
}

The issue which I facing that I don't get the value of subservice in the request of post


来源: stackexchange

问:
Dynamic Provisioning of CephFS with Kubernetes
We are using the latest versions of CephFS (v17.2.5) & Kubernetes (v1.24.2).

With the above versions of both, we are able to MANUALLY provision CephFS storage to be used with Kubernetes.

However, we get the following error when we try to DYNAMICALLY provision CephFS storage to be used with Kubernetes:

"Normal ExternalProvisioning 10s (x2 over 23s) persistentvolume-controller waiting for a volume to be created, either by external provisioner "cephfs.csi.ceph.com" or manually created by system administrator"

Has anyone experienced the same & solved it?

ContentLicense: CC BY-SA 4.0


问:
why does AAssetManager_openDir or AAsset_read take so long to execute?
I got a problem here, I use these api(AAssetManager_openDir, AAsset_read, AAsset_seek) to get file list on Android devices.

It works fine when use grade plugin version 2.1.0 and gradle version 2.14.1, but when I upgrade Gradle plugin version to 2.2.0 or higer, and just modify ONLY this place.

Furthermore, I tested in Android Studio with some versions, the same problem happened.

```<code>Bumblebee | 2021.1.1 Patch 2
Build #AI-211.7628.21.2111.8193401, built on February 17, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
</code>```

It would run in a very low speed, but the code is all the same!

I guess it maybe call by a reflection? I don't have a clue.

this is the log that I print for compare :

```<code>D/ZipFile:  (good)
  get_file_list begin>>> at 8.889095
  get_central_dir begin>>> 8.889117
  get_central_dir end>>> 8.889126 cost >> 0.000010
  get_file_header begin>>> 8.889134
  get_file_header end>>> 8.889142 cost >> 0.000009

D/ZipFile:  (bad)
  get_file_list begin>>> at 8.659172
  get_central_dir begin>>> 8.911783
  get_central_dir end>>> 9.150952 cost >> 0.239181
  get_file_header begin>>> 9.151023
  get_file_header end>>> 9.151134 cost >> 0.000112

</code>```

additionally, I got this message came out with the bad one:

```<code>Accessing hidden method Ldalvik/system/VMRuntime;->getRuntime()Ldalvik/system/VMRuntime; (unsupported,core-platform-api, reflection, allowed)
Accessing hidden method Ldalvik/system/VMRuntime;->vmInstructionSet()Ljava/lang/String; (unsupported,core-platform-api, reflection, allowed)
</code>```

This is my code in the below for check.

```<code>bool assetsFile::open(std::string filepath)
{
#ifdef OS_ANDROID
    if (!s_mgr)
    {
        LOGE("mgr is null");
        return false;
    }
    _assFile = AAssetManager_open(s_mgr, filepath.c_str(), 0);
#endif
    return true;
}

int assetsFile::length()
{
    int fileLength = 0;
#ifdef OS_ANDROID
    fileLength = AAsset_getLength(_assFile);
#endif
    return fileLength;
}

int assetsFile::read(void* buffer, int size)
{
    int readSize = 0;
#ifdef OS_ANDROID
    readSize = AAsset_read(_assFile, buffer, size);
    if (size != readSize)
        LOGE("asset read warning");
#endif
    return readSize;
}

void assetsFile::seek(int offset, int where)
{
#ifdef OS_ANDROID
    if (AAsset_seek(_assFile, offset, where) == -1)
        LOGE("asset seek error");
#endif
}
</code>```

I compared different gradle version to check the result, older version is ok, and if i use Gradle plugin version to 2.2.0 or higer, this will happen.

Body:
I got a problem here, I use these api(AAssetManager_openDir, AAsset_read, AAsset_seek) to get file list on Android devices.

It works fine when use grade plugin version 2.1.0 and gradle version 2.14.1, but when I upgrade Gradle plugin version to 2.2.0 or higer, and just modify ONLY this place.

Furthermore, I tested in Android Studio with some versions, the same problem happened.

Bumblebee | 2021.1.1 Patch 2
Build #AI-211.7628.21.2111.8193401, built on February 17, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0

It would run in a very low speed, but the code is all the same!

I guess it maybe call by a reflection? I don't have a clue.

this is the log that I print for compare :

D/ZipFile:  (good)
  get_file_list begin>>> at 8.889095
  get_central_dir begin>>> 8.889117
  get_central_dir end>>> 8.889126 cost >> 0.000010
  get_file_header begin>>> 8.889134
  get_file_header end>>> 8.889142 cost >> 0.000009

D/ZipFile:  (bad)
  get_file_list begin>>> at 8.659172
  get_central_dir begin>>> 8.911783
  get_central_dir end>>> 9.150952 cost >> 0.239181
  get_file_header begin>>> 9.151023
  get_file_header end>>> 9.151134 cost >> 0.000112

additionally, I got this message came out with the bad one:

Accessing hidden method Ldalvik/system/VMRuntime;->getRuntime()Ldalvik/system/VMRuntime; (unsupported,core-platform-api, reflection, allowed)
Accessing hidden method Ldalvik/system/VMRuntime;->vmInstructionSet()Ljava/lang/String; (unsupported,core-platform-api, reflection, allowed)

This is my code in the below for check.

bool assetsFile::open(std::string filepath)
{
#ifdef OS_ANDROID
    if (!s_mgr)
    {
        LOGE("mgr is null");
        return false;
    }
    _assFile = AAssetManager_open(s_mgr, filepath.c_str(), 0);
#endif
    return true;
}

int assetsFile::length()
{
    int fileLength = 0;
#ifdef OS_ANDROID
    fileLength = AAsset_getLength(_assFile);
#endif
    return fileLength;
}

int assetsFile::read(void* buffer, int size)
{
    int readSize = 0;
#ifdef OS_ANDROID
    readSize = AAsset_read(_assFile, buffer, size);
    if (size != readSize)
        LOGE("asset read warning");
#endif
    return readSize;
}

void assetsFile::seek(int offset, int where)
{
#ifdef OS_ANDROID
    if (AAsset_seek(_assFile, offset, where) == -1)
        LOGE("asset seek error");
#endif
}

I compared different gradle version to check the result, older version is ok, and if i use Gradle plugin version to 2.2.0 or higer, this will happen.


问:
How to wait for many storyboards to complete in WPF
I have the following code which loops through a list of storyboards, which have not been begun yet:

```<code>void ActivateEffects()
    {
        if (Effects != null)
        {
            foreach (var effect in Effects)
            {
                Storyboard sb = effect.GetAnimation();
                sb.Begin();
            }
        }
    }
</code>```

It does not matter what Effect class is. GetAnimation returns Storyboard, which has to be started.
How do I wait for all of them to complete before continuing?
Effects list:

```<code>List<Effect>? Effects { get; }
</code>```

Body:
I have the following code which loops through a list of storyboards, which have not been begun yet:

void ActivateEffects()
    {
        if (Effects != null)
        {
            foreach (var effect in Effects)
            {
                Storyboard sb = effect.GetAnimation();
                sb.Begin();
            }
        }
    }

It does not matter what Effect class is. GetAnimation returns Storyboard, which has to be started.
How do I wait for all of them to complete before continuing?
Effects list:

List<Effect>? Effects { get; }


问:
Why does the order of a nonterminal's "or" clauses are in effect the behavior of the postprocessor in nearly?
In the Nearley Parser Playground, if I type:

```<code>excludebrackets-> null | [^\\[\]]:+ {%(d) => { return "myReturn"}%}
</code>```

The parser returns "MyReturn" as expected.  However, if

```<code>excludebrackets-> [^\\[\]]:+ | null {%(d) => { return "myReturn"}%}
</code>```

Nearley seems to totally ignore the postprocessor, returning [Array[n]] as it would by default.  (However, some legitimate attempts at accessing the array in the postprocessor throw errors.)

Man, this caused some weird bugs.

Can anyone explain why it would behave this way?

Body:
In the Nearley Parser Playground, if I type:

excludebrackets-> null | [^\\[\]]:+ {%(d) => { return "myReturn"}%}

The parser returns "MyReturn" as expected.  However, if

excludebrackets-> [^\\[\]]:+ | null {%(d) => { return "myReturn"}%}

Nearley seems to totally ignore the postprocessor, returning [Array[n]] as it would by default.  (However, some legitimate attempts at accessing the array in the postprocessor throw errors.)

Man, this caused some weird bugs.

Can anyone explain why it would behave this way?


问:
Node redis retry is blocking the main thread , is there any way in nodejs to make the retry on different thread?
I have a nodejs server, when redis connection goes down it will fire an error event which is blocking the main thread and no further task can be done apart from retrying.

I want both redis retry and when redis connection is down my main thread should proceed with next task.

Here is my redisManager class

```<code>'use strict';

const redis = require("redis");
const { commandOptions } = require("redis");
const config = require('config');
const {formatStack, getMessageUUID, createCustomLogger, createCustomGlobalErrorLogger} = require('./logging')
//logging options
const loggerOptions = config.get("logging.email_service");
const logger = createCustomLogger(loggerOptions);
const errorLogger = createCustomGlobalErrorLogger(loggerOptions.logger_label);
class RedisManager {
    /**
     * Constructor
     * @param redisOptions
     * @param logger
     */
    constructor(redisOptions) {
        // create redis client with retry strategy
        // redisOptions.retry_strategy = this.getRetryStrategy;
        this.isConnected = false;
        this.client = redis.createClient(redisOptions);

        // listen for redis client events
        this.client.on("error", function (error) {
            console.log("[ Redis ] unable to connect");
            this.isConnected =false;
        });

        this.client.on("ready", function () {
            console.log(`Redis connection: READY!`);
            this.isConnected = true;
        });
        /*

        this.client.on("connect", function () {
            console.log(`Redis connection: CONNECT!`);
        });

        this.client.on("reconnecting", function () {
            console.log(`Redis connection: RECONNECTING`);
        });

        this.client.on("end", function () {
            console.log(`Redis connection: END!`);
        });
        */
    }

    /**
     *
     * @returns {RedisClient}
     */
    getRedisClient() {
        return this.client;
    }

    closeConnection() {
        this.client.end(true);
    }

    getRetryStrategy(options){
        if (options.error && options.error.code === "ECONNREFUSED") {
            // If redis refuses the connection or is not able to connect
            logger.warn("Redis connection refused .. unable to connect");
         }
         if (options.total_retry_time > 1000*60*60) {
            // End reconnection after the specified time limit
            logger.warn("Redis retry time exhausted");
            return new Error("Retry time exhausted");
         }
        //  if (options.attempt > 1) {
        //     // End reconnecting with built in error
        //     logger.warn("Redis max retry exhausted");
        //     return undefined;
        //  }
         // reconnect after
        //  return Math.min(options.attempt * 100, 10000);
        return 2000;
    }
    /**
     *
     * @param key
     * @returns {Promise<unknown>}
     */
    async getDataFromRedis(key) {
        return new Promise((resolve, reject) => {
            this.client.get(key, function (error, res) {
                if (error) {
                    reject(new Error(`Cannot read from REDIS:\n ${JSON.stringify(error.stack, null, 4)}`));
                } else {
                    if (res) {
                        resolve(JSON.parse(res));
                    } else {
                        reject(new Error(`No value found for key: "${key}" on REDIS!`));
                    }
                }
            });
        });
    }

}

module.exports = RedisManager;

</code>```

I tried throwing and error from error event handler but it is stoping the server.
I tried to set a custom retry_strategy but still it is blocking main thread.

Body:
I have a nodejs server, when redis connection goes down it will fire an error event which is blocking the main thread and no further task can be done apart from retrying.

I want both redis retry and when redis connection is down my main thread should proceed with next task.

Here is my redisManager class

'use strict';

const redis = require("redis");
const { commandOptions } = require("redis");
const config = require('config');
const {formatStack, getMessageUUID, createCustomLogger, createCustomGlobalErrorLogger} = require('./logging')
//logging options
const loggerOptions = config.get("logging.email_service");
const logger = createCustomLogger(loggerOptions);
const errorLogger = createCustomGlobalErrorLogger(loggerOptions.logger_label);
class RedisManager {
    /**
     * Constructor
     * @param redisOptions
     * @param logger
     */
    constructor(redisOptions) {
        // create redis client with retry strategy
        // redisOptions.retry_strategy = this.getRetryStrategy;
        this.isConnected = false;
        this.client = redis.createClient(redisOptions);

        // listen for redis client events
        this.client.on("error", function (error) {
            console.log("[ Redis ] unable to connect");
            this.isConnected =false;
        });

        this.client.on("ready", function () {
            console.log(`Redis connection: READY!`);
            this.isConnected = true;
        });
        /*

        this.client.on("connect", function () {
            console.log(`Redis connection: CONNECT!`);
        });

        this.client.on("reconnecting", function () {
            console.log(`Redis connection: RECONNECTING`);
        });

        this.client.on("end", function () {
            console.log(`Redis connection: END!`);
        });
        */
    }

    /**
     *
     * @returns {RedisClient}
     */
    getRedisClient() {
        return this.client;
    }

    closeConnection() {
        this.client.end(true);
    }

    getRetryStrategy(options){
        if (options.error && options.error.code === "ECONNREFUSED") {
            // If redis refuses the connection or is not able to connect
            logger.warn("Redis connection refused .. unable to connect");
         }
         if (options.total_retry_time > 1000*60*60) {
            // End reconnection after the specified time limit
            logger.warn("Redis retry time exhausted");
            return new Error("Retry time exhausted");
         }
        //  if (options.attempt > 1) {
        //     // End reconnecting with built in error
        //     logger.warn("Redis max retry exhausted");
        //     return undefined;
        //  }
         // reconnect after
        //  return Math.min(options.attempt * 100, 10000);
        return 2000;
    }
    /**
     *
     * @param key
     * @returns {Promise<unknown>}
     */
    async getDataFromRedis(key) {
        return new Promise((resolve, reject) => {
            this.client.get(key, function (error, res) {
                if (error) {
                    reject(new Error(`Cannot read from REDIS:\n ${JSON.stringify(error.stack, null, 4)}`));
                } else {
                    if (res) {
                        resolve(JSON.parse(res));
                    } else {
                        reject(new Error(`No value found for key: "${key}" on REDIS!`));
                    }
                }
            });
        });
    }

}

module.exports = RedisManager;

I tried throwing and error from error event handler but it is stoping the server.
I tried to set a custom retry_strategy but still it is blocking main thread.


问:
get original dst failed in container
I am designing an http service and need to get the real destination IP. The network on the host looks like this（just like k8s kubeproxy doing）：

```<code>traffic arrived host -> host ipvs -> docker bridge -> container
</code>```

My service(golang) runs in container, but there is an IPVS load balancer that do dnat in front, so I need to get original dst in some way, I know I can use syscall.GetsockoptIPv6Mreq to get real dst, but it just work when service run in host,if run in container,the code failed with err：syscall.GetsockoptIPv6Mreq: no such file or directory

container use docker, run in bridge mod, this is my service code：

package main

import (
   "context"
   "fmt"
   "net"
   "net/http"
   "syscall"
)

const SO_ORIGINAL_DST = 80

type contextKey struct {
   key string
}

var ConnContextKey = &contextKey{"http-conn"}

func SaveConnInContext(ctx context.Context, c net.Conn) context.Context {
   return context.WithValue(ctx, ConnContextKey, c)
}
func GetConn(r *http.Request) net.Conn {
   return r.Context().Value(ConnContextKey).(net.Conn)
}

func getOriginalDst(conn net.Conn) (string, int, error) {
   tc, ok := conn.(*net.TCPConn)
   if !ok {
      return "", 0, fmt.Errorf("redirect proxy only support tcp")
   }

   f, err := tc.File()
   if err != nil {
      return "", 0, fmt.Errorf("get conn file error, err: %s", err)
   }
   defer f.Close()

   addr, err := syscall.GetsockoptIPv6Mreq(int(f.Fd()), syscall.IPPROTO_IP, SO_ORIGINAL_DST)
   if err != nil {
      return "", 0, fmt.Errorf("syscall.GetsockoptIPv6Mreq: %s", err)
   }

   p0 := int(addr.Multiaddr[2])
   p1 := int(addr.Multiaddr[3])

   port := p0*256 + p1

   ips := addr.Multiaddr[4:8]
   ip := fmt.Sprintf("%d.%d.%d.%d", ips[0], ips[1], ips[2], ips[3])

   return ip, port, nil
}

func hello(w http.ResponseWriter, req *http.Request) {
   conn := GetConn(req)

   ip, port, err := getOriginalDst(conn)
   if err != nil {
      fmt.Fprintf(w, fmt.Sprintf("get original dst failed: %s", err))
      return
   }
   msg := fmt.Sprintf("source addr: %s, server addr: %s, original dst: %s:%d \n",
      req.RemoteAddr, req.Context().Value(http.LocalAddrContextKey), ip, port)
   fmt.Fprintf(w, msg)
}

func version(w http.ResponseWriter, req *http.Request) {
   fmt.Fprintf(w, "v4")
}

func main() {
   http.HandleFunc("/", version)
   http.HandleFunc("/test", hello)

   addr := "0.0.0.0:9090"
   srv := http.Server{
      ConnContext: SaveConnInContext,
   }
   //server.ListenAndServe()
   ln, err := net.Listen("tcp4", addr)
   if err != nil {
      panic(err)
   }
   srv.Serve(ln)
}
```
<p>if service run on the host it works ok：</p>
<ol>
<li><code>sudo iptables -t nat -A OUTPUT -p tcp -m tcp --dport 8080 -j REDIRECT --to-ports 9090</code></li>
<li><code>curl localhost:8080/test</code></li>
<li>get expected answer</li>
</ol>
```source addr: 127.0.0.1:21918, server addr: 127.0.0.1:9090, original dst: 127.0.0.1:9090
```
<p>If the service run in container then the request will fail</p>
```➜  ~ curl 172.17.0.2:9090/test
get original dst failed: syscall.GetsockoptIPv6Mreq: no such file or directory
```

I have tried many ways. At first I thought it was a permission problem. Adding --privileged=true -u=root is still useless.

I expect the code can work and get original dst in container.

Title: get original dst failed in container

Body:
I am designing an http service and need to get the real destination IP. The network on the host looks like this（just like k8s kubeproxy doing）：

traffic arrived host -> host ipvs -> docker bridge -> container

My service(golang) runs in container, but there is an IPVS load balancer that do dnat in front, so I need to get original dst in some way, I know I can use syscall.GetsockoptIPv6Mreq to get real dst, but it just work when service run in host,if run in container,the code failed with err：syscall.GetsockoptIPv6Mreq: no such file or directory

container use docker, run in bridge mod, this is my service code：

package main

import (
   "context"
   "fmt"
   "net"
   "net/http"
   "syscall"
)

const SO_ORIGINAL_DST = 80

type contextKey struct {
   key string
}

var ConnContextKey = &contextKey{"http-conn"}

func SaveConnInContext(ctx context.Context, c net.Conn) context.Context {
   return context.WithValue(ctx, ConnContextKey, c)
}
func GetConn(r *http.Request) net.Conn {
   return r.Context().Value(ConnContextKey).(net.Conn)
}

func getOriginalDst(conn net.Conn) (string, int, error) {
   tc, ok := conn.(*net.TCPConn)
   if !ok {
      return "", 0, fmt.Errorf("redirect proxy only support tcp")
   }

   f, err := tc.File()
   if err != nil {
      return "", 0, fmt.Errorf("get conn file error, err: %s", err)
   }
   defer f.Close()

   addr, err := syscall.GetsockoptIPv6Mreq(int(f.Fd()), syscall.IPPROTO_IP, SO_ORIGINAL_DST)
   if err != nil {
      return "", 0, fmt.Errorf("syscall.GetsockoptIPv6Mreq: %s", err)
   }

   p0 := int(addr.Multiaddr[2])
   p1 := int(addr.Multiaddr[3])

   port := p0*256 + p1

   ips := addr.Multiaddr[4:8]
   ip := fmt.Sprintf("%d.%d.%d.%d", ips[0], ips[1], ips[2], ips[3])

   return ip, port, nil
}

func hello(w http.ResponseWriter, req *http.Request) {
   conn := GetConn(req)

   ip, port, err := getOriginalDst(conn)
   if err != nil {
      fmt.Fprintf(w, fmt.Sprintf("get original dst failed: %s", err))
      return
   }
   msg := fmt.Sprintf("source addr: %s, server addr: %s, original dst: %s:%d \n",
      req.RemoteAddr, req.Context().Value(http.LocalAddrContextKey), ip, port)
   fmt.Fprintf(w, msg)
}

func version(w http.ResponseWriter, req *http.Request) {
   fmt.Fprintf(w, "v4")
}

func main() {
   http.HandleFunc("/", version)
   http.HandleFunc("/test", hello)

   addr := "0.0.0.0:9090"
   srv := http.Server{
      ConnContext: SaveConnInContext,
   }
   //server.ListenAndServe()
   ln, err := net.Listen("tcp4", addr)
   if err != nil {
      panic(err)
   }
   srv.Serve(ln)
}

if service run on the host it works ok：

sudo iptables -t nat -A OUTPUT -p tcp -m tcp --dport 8080 -j REDIRECT --to-ports 9090

curl localhost:8080/test

get expected answer

source addr: 127.0.0.1:21918, server addr: 127.0.0.1:9090, original dst: 127.0.0.1:9090

If the service run in container then the request will fail

➜  ~ curl 172.17.0.2:9090/test
get original dst failed: syscall.GetsockoptIPv6Mreq: no such file or directory

I have tried many ways. At first I thought it was a permission problem. Adding --privileged=true -u=root is still useless.

I expect the code can work and get original dst in container.


问:
Restore original interrupt handler in Linux
I removed the existing interrupt handler for the keyboard and registered my interrupt handler and after removing my interrupt handler, I want to restore the original interrupt handler for the keyboard.

int init_module()
{
    free_irq(1, NULL); // removing the existing interrupt handler
    return request_irq(1, irq_handler, IRQF_SHARED, "test_keyboard_irq_handler", (void *)(irq_handler)); // registering my interrupt handler
}

void cleanup_module()
{
    free_irq(1, NULL); // removing my interrupt handler
}
```

In the cleanup_module(), after removing my interrupt handler, I want to restore the original one.

Body:
I removed the existing interrupt handler for the keyboard and registered my interrupt handler and after removing my interrupt handler, I want to restore the original interrupt handler for the keyboard.

int init_module()
{
    free_irq(1, NULL); // removing the existing interrupt handler
    return request_irq(1, irq_handler, IRQF_SHARED, "test_keyboard_irq_handler", (void *)(irq_handler)); // registering my interrupt handler
}

void cleanup_module()
{
    free_irq(1, NULL); // removing my interrupt handler
}

In the cleanup_module(), after removing my interrupt handler, I want to restore the original one.


问:
Postman: How to run multiple GET requests from a list?
I have spreadsheet with around 900 GET requests that look like this "http://www.omdbapi.com/?apikey=XXXXXXX&t=Alien"

I can pull one at the time and get the right data, but is there a way I can just dump a batch of them in postman?

I tired pasting mutiple url in the field but I get the issue that request url size is too big.


问:
ValueError: X has 41 features, but RandomForestClassifier is expecting 42 features as input
I am trying to code a machine learning model that predicts the outcome of college basketball games (Code shown below)

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
</code>```
```<code>folder = '../input/mens-march-mania-2022/MDataFiles_Stage1/'

Seeds = pd.read_csv(folder+'MNCAATourneySeeds.csv')
Conferences = pd.read_csv(folder+'MTeamConferences.csv')
team_ids = pd.read_csv(folder + 'MTeams.csv')

reg_season_data = pd.read_csv(folder+'MRegularSeasonDetailedResults.csv')
TourneyCompact = pd.read_csv(folder+'MNCAATourneyCompactResults.csv')
tournament_data = pd.read_csv(folder + 'MNCAATourneyDetailedResults.csv')

display(reg_season_data.columns.values)
</code>```
```<code>WinTeams = pd.DataFrame()
LoseTeams = pd.DataFrame()

columns = ['Season', 'TeamID', 'Points', 'LTeamID', 'OppPoints',
       'Loc', 'NumOT', 'FGM', 'FGA', 'FGM3', 'FGA3', 'FTM', 'FTA',
       'OR', 'DR', 'Ast', 'TO', 'Stl', 'Blk', 'PF', 'LFGM', 'LFGA',
       'LFGM3', 'LFGA3', 'LFTM', 'LFTA', 'LOR', 'LDR', 'LAst', 'LTO',
       'LStl', 'LBlk', 'LPF']

WinTeams[columns] = reg_season_data[['Season', 'WTeamID', 'WScore', 'LTeamID', 'LScore',
       'WLoc', 'NumOT', 'WFGM', 'WFGA', 'WFGM3', 'WFGA3', 'WFTM', 'WFTA',
       'WOR', 'WDR', 'WAst', 'WTO', 'WStl', 'WBlk', 'WPF', 'LFGM', 'LFGA',
       'LFGM3', 'LFGA3', 'LFTM', 'LFTA', 'LOR', 'LDR', 'LAst', 'LTO',
       'LStl', 'LBlk', 'LPF']]

WinTeams['Wins'] = 1
WinTeams['Loses'] = 0

LoseTeams[columns] = reg_season_data[['Season', 'LTeamID', 'LScore', 'WTeamID', 'WScore',
       'WLoc', 'NumOT', 'LFGM', 'LFGA', 'LFGM3', 'LFGA3', 'LFTM', 'LFTA',
       'LOR', 'LDR', 'LAst', 'LTO', 'LStl', 'LBlk', 'LPF', 'WFGM', 'WFGA',
       'WFGM3', 'WFGA3', 'WFTM', 'WFTA', 'WOR', 'WDR', 'WAst', 'WTO',
       'WStl', 'WBlk', 'WPF']]

def change_loc(loc):
    if loc == 'H':
        return 'A'
    elif loc == 'A':
        return 'H'
    else:
        return 'N'

LoseTeams['Loc'] = LoseTeams['Loc'].apply(change_loc)

LoseTeams['Wins'] = 0
LoseTeams['Loses'] = 1

WinLoseTeams = pd.concat([WinTeams, LoseTeams])
combinedTeams = WinLoseTeams.groupby(['Season', 'TeamID']).sum()
combinedTeams['NumGames'] = combinedTeams['Wins'] + combinedTeams['Loses']
display(combinedTeams.columns.values)
</code>```
```<code>RegularSeasonInput = pd.DataFrame()

RegularSeasonInput['WinRatio'] = combinedTeams['Wins']/combinedTeams['NumGames']
RegularSeasonInput['PointsPerGame'] = combinedTeams['Points']/combinedTeams['NumGames']
RegularSeasonInput['PointsAllowedPerGame'] = combinedTeams['OppPoints']/combinedTeams['NumGames']
RegularSeasonInput['PointsRatio'] = combinedTeams['Points']/combinedTeams['OppPoints']
RegularSeasonInput['OTsPerGame'] = combinedTeams['NumOT']/combinedTeams['NumGames']

RegularSeasonInput['FGperGame'] = combinedTeams['FGM']/combinedTeams['NumGames']
RegularSeasonInput['FGRatio'] = combinedTeams['FGM']/combinedTeams['FGA']
RegularSeasonInput['FGallowedPerGame'] = combinedTeams['LFGM']/combinedTeams['NumGames']
RegularSeasonInput['OppFGRatio'] = combinedTeams['LFGM']/combinedTeams['LFGA']

RegularSeasonInput['Opp3FGRatio'] = combinedTeams['LFGM3']/combinedTeams['LFGA3']

RegularSeasonInput['FTallowedPerGame'] = combinedTeams['LFTM']/combinedTeams['NumGames']

RegularSeasonInput['OffensiveReboundRatio'] = combinedTeams['OR'] / (combinedTeams['OR'] + combinedTeams['LDR'])
RegularSeasonInput['AstPerGame'] = combinedTeams['Ast']/combinedTeams['NumGames']

RegularSeasonInput['LDefensiveReboundRatio'] = combinedTeams['LDR'] / (combinedTeams['LDR'] + combinedTeams['OR'])
RegularSeasonInput['TOPerGame'] = combinedTeams['TO']/combinedTeams['NumGames']
RegularSeasonInput['StlPerGame'] = combinedTeams['Stl']/combinedTeams['NumGames']
RegularSeasonInput['BlkPerGame'] = combinedTeams['Blk']/combinedTeams['NumGames']
RegularSeasonInput['PFPerGame'] = combinedTeams['PF']/combinedTeams['NumGames']

RegularSeasonInput['LTOPerGame'] = combinedTeams['LTO']/combinedTeams['NumGames']
RegularSeasonInput['LStlPerGame'] = combinedTeams['LStl']/combinedTeams['NumGames']
RegularSeasonInput['LBlkPerGame'] = combinedTeams['LBlk']/combinedTeams['NumGames']
RegularSeasonInput['LPFPerGame'] = combinedTeams['LPF']/combinedTeams['NumGames']

RegularSeasonInput['PossesionsPerGame'] = (combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA']))/ combinedTeams['NumGames']
RegularSeasonInput['OppPossesionsPerGame'] = (combinedTeams['LFGA'] - combinedTeams['LOR'] + combinedTeams['LTO'] + (0.475*combinedTeams['LFTA']))/ combinedTeams['NumGames']
RegularSeasonInput['PointsPerPossesion'] = (combinedTeams['Points']/combinedTeams['NumGames'])/((combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA']))/ combinedTeams['NumGames'])

RegularSeasonInput['TrueShooting%'] = combinedTeams['Points']/(2*(combinedTeams['FGA'] + 0.44 * combinedTeams['FTA']))
RegularSeasonInput['OppTrueShooting%'] = combinedTeams['OppPoints']/(2*(combinedTeams['LFGA'] + 0.44 * combinedTeams['LFTA']))
RegularSeasonInput['EffectiveFG%'] = (combinedTeams['FGM'] + 0.5 * combinedTeams['FGM3'])/combinedTeams['FGA']
RegularSeasonInput['OppEffectiveFG%'] = (combinedTeams['LFGM'] + 0.5 * combinedTeams['LFGM3'])/combinedTeams['LFGA']

RegularSeasonInput['AstToTORatio'] = combinedTeams['Ast']/ combinedTeams['TO']
RegularSeasonInput['OppAstToTORatio'] = combinedTeams['LAst']/ combinedTeams['LTO']

RegularSeasonInput['Efficiency'] = (combinedTeams['Points'] + combinedTeams['OR'] + combinedTeams['DR'] + combinedTeams['Ast'] + combinedTeams['Stl'] + combinedTeams['Blk'] - (combinedTeams['FGA'] - combinedTeams['FGM']) - (combinedTeams['FTA'] - combinedTeams['FTM']) - combinedTeams['TO'])/combinedTeams['NumGames']
RegularSeasonInput['OppEfficiency'] = (combinedTeams['OppPoints'] + combinedTeams['LOR'] + combinedTeams['LDR'] + combinedTeams['LAst'] + combinedTeams['LStl'] + combinedTeams['LBlk'] - (combinedTeams['LFGA'] - combinedTeams['LFGM']) - (combinedTeams['LFTA'] - combinedTeams['LFTM']) - combinedTeams['LTO'])/combinedTeams['NumGames']
RegularSeasonInput['OppFTRate'] = combinedTeams['LFTA']/combinedTeams['LFGA']

RegularSeasonInput['OffensiveEfficiencyPer100'] = (combinedTeams['Points']/(combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA'])))*100
RegularSeasonInput['DefensiveEfficiencyPer100'] = (combinedTeams['OppPoints']/(combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA'])))*100

RegularSeasonInput['OppOffensiveEfficiencyPer100'] = (combinedTeams['OppPoints']/(combinedTeams['LFGA'] - combinedTeams['LOR'] + combinedTeams['LTO'] + (0.475*combinedTeams['LFTA'])))*100
RegularSeasonInput['OppDefensiveEfficiencyPer100'] = (combinedTeams['Points']/(combinedTeams['LFGA'] - combinedTeams['LOR'] + combinedTeams['LTO'] + (0.475*combinedTeams['LFTA'])))*100

RegularSeasonInput['Opp2P%'] = (combinedTeams['LFGM'] - combinedTeams['LFGM3'])/(combinedTeams['LFGA'] - combinedTeams['LFGA3'])
RegularSeasonInput['2P%'] = (combinedTeams['FGM'] - combinedTeams['FGM3'])/(combinedTeams['FGA'] - combinedTeams['FGA3'])

RegularSeasonInput['Ew%'] = combinedTeams['Points']**11.5/(combinedTeams['Points']**11.5 + combinedTeams['OppPoints']**11.5)

display(RegularSeasonInput)
</code>```
```<code>seed_dict = Seeds.set_index(['Season', 'TeamID'])
display(seed_dict.index.values)

TourneyInput = pd.DataFrame()

winIDs = TourneyCompact['WTeamID']
loseIDs = TourneyCompact['LTeamID']
season = TourneyCompact['Season']

winners = pd.DataFrame()
winners[['Season', 'Team1', 'Team2']] = TourneyCompact[['Season', 'WTeamID', 'LTeamID']]
winners['Result'] = 1

losers = pd.DataFrame()
losers[['Season', 'Team1', 'Team2']] = TourneyCompact[['Season', 'LTeamID', 'WTeamID']]
losers['Result'] = 0

TourneyInput = pd.concat([winners, losers])
TourneyInput = TourneyInput[TourneyInput['Season']>=2003].reset_index(drop=True)

team1seeds = []
team2seeds = []

for x in range(len(TourneyInput)):
    idx = (TourneyInput['Season'][x], TourneyInput['Team1'][x])
    seed = seed_dict.loc[idx].values[0]
    if len(seed) == 4:
        seed = int(seed[1:-1])
    else:
        seed = int(seed[1:])
    team1seeds.append(seed)

    idx = (TourneyInput['Season'][x], TourneyInput['Team2'][x])
    seed = seed_dict.loc[idx].values[0]
    if len(seed) == 4:
        seed = int(seed[1:-1])
    else:
        seed = int(seed[1:])
    team2seeds.append(seed)

TourneyInput['Team1Seed'] = team1seeds
TourneyInput['Team2Seed'] = team2seeds

display(TourneyInput)
</code>```
```<code>outscores = []

for x in range (len(TourneyInput)):
    idx = (TourneyInput['Season'][x], TourneyInput['Team1'][x])
    team1score = RegularSeasonInput.loc[idx]
    team1score['Seed'] = TourneyInput['Team1Seed'][x]

    idx = (TourneyInput['Season'][x], TourneyInput['Team2'][x])
    team2score = RegularSeasonInput.loc[idx]
    team2score['Seed'] = TourneyInput['Team2Seed'][x]

    outscore = team1score - team2score
    outscore['Result'] = TourneyInput['Result'][x]
    outscores.append(outscore)

outscores = pd.DataFrame(outscores)
display(outscores)
</code>```
```<code>corrs = round(outscores.corr(), 2)
display(np.abs(corrs['Result']))

import seaborn as sns

plt.figure(figsize=(15,10))
sns.heatmap(corrs)
plt.show()
</code>```
```<code>X = outscores[outscores.columns[:-1]].values
Y = outscores['Result'].values

np.random.seed(1)
idx = np.random.permutation(len(X))
train_idx = idx[:int(-0.2*len(X))]
test_idx = idx[int(-0.2*len(X)):]

X_train = X[train_idx]
X_test = X[test_idx]
Y_train = Y[train_idx]
Y_test = Y[test_idx]

mins = X_train.min(axis=0)
maxs = X_train.max(axis=0)

X_train = (X_train - mins)/(maxs - mins)
X_test = (X_test - mins)/(maxs - mins)

print(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)
</code>```

Whenever I run the cell below it comes up with the error. X has 41 features, but RandomForestClassifier is expecting 42 features as input.

```<code>def predict_matchup(team1, team2, season, team1_seed, team2_seed):
    team1_name = list(team_ids[team_ids['TeamID'] == team1]['TeamName'])[0]
    team2_name = list(team_ids[team_ids['TeamID'] == team2]['TeamName'])[0]
    print(f'{team1_seed} {team1_name} vs {team2_seed} {team2_name}')
    season_data = RegularSeasonInput.query(f'Season == {season}').reset_index()
    team1_data = season_data.query(f'TeamID == {team1}')
    team2_data = season_data.query(f'TeamID == {team2}')

    match_data = team1_data.merge(team2_data, on='Season', suffixes=['', '_Opponent'])
    match_data['Seed_Diff'] = team2_seed - team1_seed
    match_data = match_data[['WinRatio', 'PointsPerGame', 'PointsAllowedPerGame', 'PointsRatio',
                             'OTsPerGame','FGperGame', 'FGRatio', 'FGallowedPerGame',
                             'OppFGRatio', 'Opp3FGRatio', 'FTallowedPerGame',
'OffensiveReboundRatio', 'AstPerGame',
                             'LDefensiveReboundRatio', 'TOPerGame', 'StlPerGame', 'BlkPerGame',
                             'PFPerGame', 'LTOPerGame', 'LStlPerGame', 'LPFPerGame', 'PossesionsPerGame',
                             'OppPossesionsPerGame','PointsPerPossesion', 'TrueShooting%', 'OppTrueShooting%',
                             'EffectiveFG%', 'OppEffectiveFG%', 'AstToTORatio', 'OppAstToTORatio',
                             'Efficiency', 'OppEfficiency', 'OppFTRate', 'OffensiveEfficiencyPer100',
                             'DefensiveEfficiencyPer100', 'OppOffensiveEfficiencyPer100',
                             'OppDefensiveEfficiencyPer100', 'Opp2P%', '2P%', 'Ew%', 'LBlkPerGame']]

    model.predict(match_data)

predict_matchup(1333, 1393, 2003, 1, 3)

</code>```
```<code>from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(random_state=3)
model = model.fit(X_train, Y_train)
model.score(X_test, Y_test)
</code>```

I don't know what I am doing please help. You do not understand the frustration that this project has caused me

When running the code above I expected it to output the models predictions based on all of the inputs.

Body:
I am trying to code a machine learning model that predicts the outcome of college basketball games (Code shown below)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

folder = '../input/mens-march-mania-2022/MDataFiles_Stage1/'

Seeds = pd.read_csv(folder+'MNCAATourneySeeds.csv')
Conferences = pd.read_csv(folder+'MTeamConferences.csv')
team_ids = pd.read_csv(folder + 'MTeams.csv')

reg_season_data = pd.read_csv(folder+'MRegularSeasonDetailedResults.csv')
TourneyCompact = pd.read_csv(folder+'MNCAATourneyCompactResults.csv')
tournament_data = pd.read_csv(folder + 'MNCAATourneyDetailedResults.csv')

display(reg_season_data.columns.values)

WinTeams = pd.DataFrame()
LoseTeams = pd.DataFrame()

columns = ['Season', 'TeamID', 'Points', 'LTeamID', 'OppPoints',
       'Loc', 'NumOT', 'FGM', 'FGA', 'FGM3', 'FGA3', 'FTM', 'FTA',
       'OR', 'DR', 'Ast', 'TO', 'Stl', 'Blk', 'PF', 'LFGM', 'LFGA',
       'LFGM3', 'LFGA3', 'LFTM', 'LFTA', 'LOR', 'LDR', 'LAst', 'LTO',
       'LStl', 'LBlk', 'LPF']

WinTeams[columns] = reg_season_data[['Season', 'WTeamID', 'WScore', 'LTeamID', 'LScore',
       'WLoc', 'NumOT', 'WFGM', 'WFGA', 'WFGM3', 'WFGA3', 'WFTM', 'WFTA',
       'WOR', 'WDR', 'WAst', 'WTO', 'WStl', 'WBlk', 'WPF', 'LFGM', 'LFGA',
       'LFGM3', 'LFGA3', 'LFTM', 'LFTA', 'LOR', 'LDR', 'LAst', 'LTO',
       'LStl', 'LBlk', 'LPF']]

WinTeams['Wins'] = 1
WinTeams['Loses'] = 0

LoseTeams[columns] = reg_season_data[['Season', 'LTeamID', 'LScore', 'WTeamID', 'WScore',
       'WLoc', 'NumOT', 'LFGM', 'LFGA', 'LFGM3', 'LFGA3', 'LFTM', 'LFTA',
       'LOR', 'LDR', 'LAst', 'LTO', 'LStl', 'LBlk', 'LPF', 'WFGM', 'WFGA',
       'WFGM3', 'WFGA3', 'WFTM', 'WFTA', 'WOR', 'WDR', 'WAst', 'WTO',
       'WStl', 'WBlk', 'WPF']]

def change_loc(loc):
    if loc == 'H':
        return 'A'
    elif loc == 'A':
        return 'H'
    else:
        return 'N'

LoseTeams['Loc'] = LoseTeams['Loc'].apply(change_loc)

LoseTeams['Wins'] = 0
LoseTeams['Loses'] = 1

WinLoseTeams = pd.concat([WinTeams, LoseTeams])
combinedTeams = WinLoseTeams.groupby(['Season', 'TeamID']).sum()
combinedTeams['NumGames'] = combinedTeams['Wins'] + combinedTeams['Loses']
display(combinedTeams.columns.values)

RegularSeasonInput = pd.DataFrame()

RegularSeasonInput['WinRatio'] = combinedTeams['Wins']/combinedTeams['NumGames']
RegularSeasonInput['PointsPerGame'] = combinedTeams['Points']/combinedTeams['NumGames']
RegularSeasonInput['PointsAllowedPerGame'] = combinedTeams['OppPoints']/combinedTeams['NumGames']
RegularSeasonInput['PointsRatio'] = combinedTeams['Points']/combinedTeams['OppPoints']
RegularSeasonInput['OTsPerGame'] = combinedTeams['NumOT']/combinedTeams['NumGames']

RegularSeasonInput['FGperGame'] = combinedTeams['FGM']/combinedTeams['NumGames']
RegularSeasonInput['FGRatio'] = combinedTeams['FGM']/combinedTeams['FGA']
RegularSeasonInput['FGallowedPerGame'] = combinedTeams['LFGM']/combinedTeams['NumGames']
RegularSeasonInput['OppFGRatio'] = combinedTeams['LFGM']/combinedTeams['LFGA']

RegularSeasonInput['Opp3FGRatio'] = combinedTeams['LFGM3']/combinedTeams['LFGA3']

RegularSeasonInput['FTallowedPerGame'] = combinedTeams['LFTM']/combinedTeams['NumGames']

RegularSeasonInput['OffensiveReboundRatio'] = combinedTeams['OR'] / (combinedTeams['OR'] + combinedTeams['LDR'])
RegularSeasonInput['AstPerGame'] = combinedTeams['Ast']/combinedTeams['NumGames']

RegularSeasonInput['LDefensiveReboundRatio'] = combinedTeams['LDR'] / (combinedTeams['LDR'] + combinedTeams['OR'])
RegularSeasonInput['TOPerGame'] = combinedTeams['TO']/combinedTeams['NumGames']
RegularSeasonInput['StlPerGame'] = combinedTeams['Stl']/combinedTeams['NumGames']
RegularSeasonInput['BlkPerGame'] = combinedTeams['Blk']/combinedTeams['NumGames']
RegularSeasonInput['PFPerGame'] = combinedTeams['PF']/combinedTeams['NumGames']

RegularSeasonInput['LTOPerGame'] = combinedTeams['LTO']/combinedTeams['NumGames']
RegularSeasonInput['LStlPerGame'] = combinedTeams['LStl']/combinedTeams['NumGames']
RegularSeasonInput['LBlkPerGame'] = combinedTeams['LBlk']/combinedTeams['NumGames']
RegularSeasonInput['LPFPerGame'] = combinedTeams['LPF']/combinedTeams['NumGames']

RegularSeasonInput['PossesionsPerGame'] = (combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA']))/ combinedTeams['NumGames']
RegularSeasonInput['OppPossesionsPerGame'] = (combinedTeams['LFGA'] - combinedTeams['LOR'] + combinedTeams['LTO'] + (0.475*combinedTeams['LFTA']))/ combinedTeams['NumGames']
RegularSeasonInput['PointsPerPossesion'] = (combinedTeams['Points']/combinedTeams['NumGames'])/((combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA']))/ combinedTeams['NumGames'])

RegularSeasonInput['TrueShooting%'] = combinedTeams['Points']/(2*(combinedTeams['FGA'] + 0.44 * combinedTeams['FTA']))
RegularSeasonInput['OppTrueShooting%'] = combinedTeams['OppPoints']/(2*(combinedTeams['LFGA'] + 0.44 * combinedTeams['LFTA']))
RegularSeasonInput['EffectiveFG%'] = (combinedTeams['FGM'] + 0.5 * combinedTeams['FGM3'])/combinedTeams['FGA']
RegularSeasonInput['OppEffectiveFG%'] = (combinedTeams['LFGM'] + 0.5 * combinedTeams['LFGM3'])/combinedTeams['LFGA']

RegularSeasonInput['AstToTORatio'] = combinedTeams['Ast']/ combinedTeams['TO']
RegularSeasonInput['OppAstToTORatio'] = combinedTeams['LAst']/ combinedTeams['LTO']

RegularSeasonInput['Efficiency'] = (combinedTeams['Points'] + combinedTeams['OR'] + combinedTeams['DR'] + combinedTeams['Ast'] + combinedTeams['Stl'] + combinedTeams['Blk'] - (combinedTeams['FGA'] - combinedTeams['FGM']) - (combinedTeams['FTA'] - combinedTeams['FTM']) - combinedTeams['TO'])/combinedTeams['NumGames']
RegularSeasonInput['OppEfficiency'] = (combinedTeams['OppPoints'] + combinedTeams['LOR'] + combinedTeams['LDR'] + combinedTeams['LAst'] + combinedTeams['LStl'] + combinedTeams['LBlk'] - (combinedTeams['LFGA'] - combinedTeams['LFGM']) - (combinedTeams['LFTA'] - combinedTeams['LFTM']) - combinedTeams['LTO'])/combinedTeams['NumGames']
RegularSeasonInput['OppFTRate'] = combinedTeams['LFTA']/combinedTeams['LFGA']

RegularSeasonInput['OffensiveEfficiencyPer100'] = (combinedTeams['Points']/(combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA'])))*100
RegularSeasonInput['DefensiveEfficiencyPer100'] = (combinedTeams['OppPoints']/(combinedTeams['FGA'] - combinedTeams['OR'] + combinedTeams['TO'] + (0.475*combinedTeams['FTA'])))*100

RegularSeasonInput['OppOffensiveEfficiencyPer100'] = (combinedTeams['OppPoints']/(combinedTeams['LFGA'] - combinedTeams['LOR'] + combinedTeams['LTO'] + (0.475*combinedTeams['LFTA'])))*100
RegularSeasonInput['OppDefensiveEfficiencyPer100'] = (combinedTeams['Points']/(combinedTeams['LFGA'] - combinedTeams['LOR'] + combinedTeams['LTO'] + (0.475*combinedTeams['LFTA'])))*100

RegularSeasonInput['Opp2P%'] = (combinedTeams['LFGM'] - combinedTeams['LFGM3'])/(combinedTeams['LFGA'] - combinedTeams['LFGA3'])
RegularSeasonInput['2P%'] = (combinedTeams['FGM'] - combinedTeams['FGM3'])/(combinedTeams['FGA'] - combinedTeams['FGA3'])

RegularSeasonInput['Ew%'] = combinedTeams['Points']**11.5/(combinedTeams['Points']**11.5 + combinedTeams['OppPoints']**11.5)

display(RegularSeasonInput)

seed_dict = Seeds.set_index(['Season', 'TeamID'])
display(seed_dict.index.values)

TourneyInput = pd.DataFrame()

winIDs = TourneyCompact['WTeamID']
loseIDs = TourneyCompact['LTeamID']
season = TourneyCompact['Season']

winners = pd.DataFrame()
winners[['Season', 'Team1', 'Team2']] = TourneyCompact[['Season', 'WTeamID', 'LTeamID']]
winners['Result'] = 1

losers = pd.DataFrame()
losers[['Season', 'Team1', 'Team2']] = TourneyCompact[['Season', 'LTeamID', 'WTeamID']]
losers['Result'] = 0

TourneyInput = pd.concat([winners, losers])
TourneyInput = TourneyInput[TourneyInput['Season']>=2003].reset_index(drop=True)

team1seeds = []
team2seeds = []

for x in range(len(TourneyInput)):
    idx = (TourneyInput['Season'][x], TourneyInput['Team1'][x])
    seed = seed_dict.loc[idx].values[0]
    if len(seed) == 4:
        seed = int(seed[1:-1])
    else:
        seed = int(seed[1:])
    team1seeds.append(seed)

    idx = (TourneyInput['Season'][x], TourneyInput['Team2'][x])
    seed = seed_dict.loc[idx].values[0]
    if len(seed) == 4:
        seed = int(seed[1:-1])
    else:
        seed = int(seed[1:])
    team2seeds.append(seed)

TourneyInput['Team1Seed'] = team1seeds
TourneyInput['Team2Seed'] = team2seeds

display(TourneyInput)

outscores = []

for x in range (len(TourneyInput)):
    idx = (TourneyInput['Season'][x], TourneyInput['Team1'][x])
    team1score = RegularSeasonInput.loc[idx]
    team1score['Seed'] = TourneyInput['Team1Seed'][x]

    idx = (TourneyInput['Season'][x], TourneyInput['Team2'][x])
    team2score = RegularSeasonInput.loc[idx]
    team2score['Seed'] = TourneyInput['Team2Seed'][x]

    outscore = team1score - team2score
    outscore['Result'] = TourneyInput['Result'][x]
    outscores.append(outscore)

outscores = pd.DataFrame(outscores)
display(outscores)

corrs = round(outscores.corr(), 2)
display(np.abs(corrs['Result']))

import seaborn as sns

plt.figure(figsize=(15,10))
sns.heatmap(corrs)
plt.show()

X = outscores[outscores.columns[:-1]].values
Y = outscores['Result'].values

np.random.seed(1)
idx = np.random.permutation(len(X))
train_idx = idx[:int(-0.2*len(X))]
test_idx = idx[int(-0.2*len(X)):]

X_train = X[train_idx]
X_test = X[test_idx]
Y_train = Y[train_idx]
Y_test = Y[test_idx]

mins = X_train.min(axis=0)
maxs = X_train.max(axis=0)

X_train = (X_train - mins)/(maxs - mins)
X_test = (X_test - mins)/(maxs - mins)

print(X_train.shape, X_test.shape, Y_train.shape, Y_test.shape)

Whenever I run the cell below it comes up with the error. X has 41 features, but RandomForestClassifier is expecting 42 features as input.

def predict_matchup(team1, team2, season, team1_seed, team2_seed):
    team1_name = list(team_ids[team_ids['TeamID'] == team1]['TeamName'])[0]
    team2_name = list(team_ids[team_ids['TeamID'] == team2]['TeamName'])[0]
    print(f'{team1_seed} {team1_name} vs {team2_seed} {team2_name}')
    season_data = RegularSeasonInput.query(f'Season == {season}').reset_index()
    team1_data = season_data.query(f'TeamID == {team1}')
    team2_data = season_data.query(f'TeamID == {team2}')

    match_data = team1_data.merge(team2_data, on='Season', suffixes=['', '_Opponent'])
    match_data['Seed_Diff'] = team2_seed - team1_seed
    match_data = match_data[['WinRatio', 'PointsPerGame', 'PointsAllowedPerGame', 'PointsRatio',
                             'OTsPerGame','FGperGame', 'FGRatio', 'FGallowedPerGame',
                             'OppFGRatio', 'Opp3FGRatio', 'FTallowedPerGame',
'OffensiveReboundRatio', 'AstPerGame',
                             'LDefensiveReboundRatio', 'TOPerGame', 'StlPerGame', 'BlkPerGame',
                             'PFPerGame', 'LTOPerGame', 'LStlPerGame', 'LPFPerGame', 'PossesionsPerGame',
                             'OppPossesionsPerGame','PointsPerPossesion', 'TrueShooting%', 'OppTrueShooting%',
                             'EffectiveFG%', 'OppEffectiveFG%', 'AstToTORatio', 'OppAstToTORatio',
                             'Efficiency', 'OppEfficiency', 'OppFTRate', 'OffensiveEfficiencyPer100',
                             'DefensiveEfficiencyPer100', 'OppOffensiveEfficiencyPer100',
                             'OppDefensiveEfficiencyPer100', 'Opp2P%', '2P%', 'Ew%', 'LBlkPerGame']]

    model.predict(match_data)

predict_matchup(1333, 1393, 2003, 1, 3)

from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(random_state=3)
model = model.fit(X_train, Y_train)
model.score(X_test, Y_test)

I don't know what I am doing please help. You do not understand the frustration that this project has caused me

When running the code above I expected it to output the models predictions based on all of the inputs.


问:
Twilio Whatsapp Sandbox Configuration for deploying application via AWS elastic beanstalk
enter image description here

Currently I am developing a chatbot for my application with django, using a twilio trial account.
The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script.

However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp.

In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues?

Great thanks in advance.

(Please forgive me if my use of language is not accurate as I am not with computer science background.)

Below is part of the code that I applied.

```<code>
@csrf_exempt
def message(request):

    account_sid = 'xxx'
    auth_token = 'xxx'
    client = Client(account_sid, auth_token)

    client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852")
    client_phone_number.removeprefix("+852")
    incoming_message = request.POST.get('Body')
    conversation_sid = request.POST.get('conversation_sid')

    incoming_message = incoming_message.lower()
    response = MessagingResponse()

#processing the incoming message to produce the text

    resp = "text"

    response.message(resp)

    return HttpResponse(str(response))
</code>```

I have tried pasting https://xxxxx-env.yyyyyyy.us-east-1.elasticbeanstalk.com/whatsapp/ to the sandbox configuration cell as shown in the image and it resulted to what I mentioned above. The whatsapp url is set just like typically done for other urls for django, followed by message(request) to process the request sent out from the whatsapp. Any other proper way I can do it?

Body:
enter image description here

Currently I am developing a chatbot for my application with django, using a twilio trial account.
The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script.

However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp.

In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues?

Great thanks in advance.

(Please forgive me if my use of language is not accurate as I am not with computer science background.)

Below is part of the code that I applied.

@csrf_exempt
def message(request):

    account_sid = 'xxx'
    auth_token = 'xxx'
    client = Client(account_sid, auth_token)

    client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852")
    client_phone_number.removeprefix("+852")
    incoming_message = request.POST.get('Body')
    conversation_sid = request.POST.get('conversation_sid')

    incoming_message = incoming_message.lower()
    response = MessagingResponse()

#processing the incoming message to produce the text

    resp = "text"

    response.message(resp)

    return HttpResponse(str(response))

I have tried pasting https://xxxxx-env.yyyyyyy.us-east-1.elasticbeanstalk.com/whatsapp/ to the sandbox configuration cell as shown in the image and it resulted to what I mentioned above. The whatsapp url is set just like typically done for other urls for django, followed by message(request) to process the request sent out from the whatsapp. Any other proper way I can do it?


问:
Need to specify WarmType for ES-Domain creation
Why do i need to specify "WarmType" even if it is an optional parameter while creating AWS ES-Domain through CLI using JSON file ?

Using this command, rest of the AWS resources are working fine, like DDB,S3 but what's the matter with ES?

```<code>awslocal es create-elasticsearch-domain --cli-input-json file://filename.json
</code>```

and this is the error i'm getting

```<code>botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter ClusterConfig.WarmType, value: None,
type: <class 'NoneType'>, valid types: <class 'str'>
</code>```

and this is my json file

```<code>{
            "DomainName":"mydomain",
            "ElasticsearchVersion": "6.8",
            "ElasticsearchClusterConfig": {
              "DedicatedMasterEnabled": true,
              "DedicatedMasterCount": 3,
              "ZoneAwarenessEnabled": false,
              "InstanceCount": 3,
              "InstanceType":"m3.medium.elasticsearch",
              "DedicatedMasterType": "m3.medium.elasticsearch",
              "WarmEnabled":false
            },
            "EBSOptions" : {
                "EBSEnabled" : true,
                "VolumeSize" : 1,
                "VolumeType" : "gp2"
            }
 }

</code>```

Why I'm getting this exception? Even by disabling "WarmEnabled" option.

Body:
Why do i need to specify "WarmType" even if it is an optional parameter while creating AWS ES-Domain through CLI using JSON file ?

Using this command, rest of the AWS resources are working fine, like DDB,S3 but what's the matter with ES?

awslocal es create-elasticsearch-domain --cli-input-json file://filename.json

and this is the error i'm getting

botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter ClusterConfig.WarmType, value: None,
type: <class 'NoneType'>, valid types: <class 'str'>

and this is my json file

{
            "DomainName":"mydomain",
            "ElasticsearchVersion": "6.8",
            "ElasticsearchClusterConfig": {
              "DedicatedMasterEnabled": true,
              "DedicatedMasterCount": 3,
              "ZoneAwarenessEnabled": false,
              "InstanceCount": 3,
              "InstanceType":"m3.medium.elasticsearch",
              "DedicatedMasterType": "m3.medium.elasticsearch",
              "WarmEnabled":false
            },
            "EBSOptions" : {
                "EBSEnabled" : true,
                "VolumeSize" : 1,
                "VolumeType" : "gp2"
            }
 }

Why I'm getting this exception? Even by disabling "WarmEnabled" option.


问:
How to duplicate table from table existing in excel
I have an excel template and I need create new table based on existing tables following condition(s) for example month, year, etc.

I'm using ClosedXML.Excel. How I can do it?

Thank you.


问:
How to render page after force downloading (Node.js)?
I am working on a project Where I want to force/Download my data and then after downloading I want to render some specific details on frontend. It's working separately but not together. Maybe the reason is the resource is being ended and it's not able to render the next one.

Here is code snippet

```<code>user = await UserModel.create({ username: useridname });
    res.cookie(`username`,useridname);
    let greet = "Hello " + useridname;
    var pageinfo = getpage(greet, "");
    var hashuserid = await bcrypt.hash(useridname,12);
    res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=key.txt'});
    res.end( hashuserid );
    res.render('home', {root:pageinfo['greet'], info: pageinfo['lblinfo'], showchat: pageinfo['frmshwbtn']});
</code>```

Here force downloading is working but last res.render is not working.

I was trying this

```<code>user = await UserModel.create({ username: useridname });
    res.cookie(`username`,useridname);
    let greet = "Hello " + useridname;
    var pageinfo = getpage(greet, "");
    var hashuserid = await bcrypt.hash(useridname,12);
    res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=key.txt'});
res.render('home', {root:pageinfo['greet'], info: pageinfo['lblinfo'], showchat: pageinfo['frmshwbtn']});
  res.end( hashuserid );

</code>```

but I know it won't help.

Body:
I am working on a project Where I want to force/Download my data and then after downloading I want to render some specific details on frontend. It's working separately but not together. Maybe the reason is the resource is being ended and it's not able to render the next one.

Here is code snippet

user = await UserModel.create({ username: useridname });
    res.cookie(`username`,useridname);
    let greet = "Hello " + useridname;
    var pageinfo = getpage(greet, "");
    var hashuserid = await bcrypt.hash(useridname,12);
    res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=key.txt'});
    res.end( hashuserid );
    res.render('home', {root:pageinfo['greet'], info: pageinfo['lblinfo'], showchat: pageinfo['frmshwbtn']});

Here force downloading is working but last res.render is not working.

I was trying this

user = await UserModel.create({ username: useridname });
    res.cookie(`username`,useridname);
    let greet = "Hello " + useridname;
    var pageinfo = getpage(greet, "");
    var hashuserid = await bcrypt.hash(useridname,12);
    res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=key.txt'});
res.render('home', {root:pageinfo['greet'], info: pageinfo['lblinfo'], showchat: pageinfo['frmshwbtn']});
  res.end( hashuserid );

but I know it won't help.


问:
Dependencies are placed under web-inf/lib properly, but cannot access the api's of dependencies when deployed the .war file on tomcat
I have few spring boot projects, the structure is as follows:

```<code>parent: war

    ---child1: jar

    ---child2: jar

    ---child3: jar

    ---child4: jar
</code>```

child1,child2,child3,child4 are dependencies of parent.

when I build the parent project as a war, child projects are added as dependencies in web-inf/lib. But when I run the .war file(parent), the child projects are not triggered.

And, when I run the parent project in an IDE, it works fine...(I can access the child projects).

Is there any way to trigger the child projects and access the api's of child projects when we run the war file of parent.

Note:
Here the issue is not placing the dependency jars in web-inf/lib folder, but to access the those jars during runtime.

Body:
I have few spring boot projects, the structure is as follows:

parent: war

    ---child1: jar

    ---child2: jar

    ---child3: jar

    ---child4: jar

child1,child2,child3,child4 are dependencies of parent.

when I build the parent project as a war, child projects are added as dependencies in web-inf/lib. But when I run the .war file(parent), the child projects are not triggered.

And, when I run the parent project in an IDE, it works fine...(I can access the child projects).

Is there any way to trigger the child projects and access the api's of child projects when we run the war file of parent.

Note:
Here the issue is not placing the dependency jars in web-inf/lib folder, but to access the those jars during runtime.


问:
Persisting BloomFilterRedis
We use BloomFilter in a pretty busy flow computing environment with about 50K operations per second. Earlier, the filters were implemented on a per node basis and would periodically be cleared, to prevent saturation.

With the current implementation based on BloomFilterRedis, it's been a bit of a challenge to keep the filter from saturation by persisting existing values and copying the BitSet over to a new instance, there is no provision to set the older BitSet into the new instance with a setter or a constructor.
Looking to hear from somebody with experience in this library

Title: Persisting BloomFilterRedis


问:
How to validate a table with arrays using SimpleReactValidator
I have a table that can add and delete rows. However, am not able to validate the table. if the table cells are empty or filled am not able to post the values to the backend. The error message still shows.What is the best way to validate the table. I would like to have the error message show if the fields are empty on submit.</p>
```<code>payment.js

import React, {Component } from "react";
              import "bootstrap/dist/css/bootstrap.min.css"
              import axios from "axios"
              import SimpleReactValidator from "simple-react-validator"
              import Box from '@mui/material/Box';
              import Button from "@mui/material/Button";
              import BillTable from "./billTable"
              import $ from 'jquery'

              class Payment extends Component {
                  constructor(){
                      super()
                      this.state = {
                      Bill:"",
                      billTable: [{
                          index: Math.random(),
                          serialNumber: "",
                          item:"",
                          cost:""}],
                              errorMessage: '',
                      }
                      this.validator = new SimpleReactValidator({autoForceUpdate: this,messages: {
                          default: 'Please enter this field!'
                      },element: message => <div style={{color: "red"}}>{message}</div>})
                      this.handleSubmit = this.handleSubmit.bind(this)
                      this.handleChange = this.handleChange.bind(this)
                  }
                  handleChange = (e) => {
                    if (["serialNumber", "item", "cost"].includes(e.target.name)) {
                      let billTable = [...this.state.billTable]
                      billTable[e.target.dataset.id][e.target.name] = e.target.value;
                    }
                    else {
                      this.setState({ [e.target.name]: e.target.value })
                    }
                  };
              addNewRowPlan = () => {
                this.setState((prevState) => ({
                    billTable: [...prevState.billTable, { index: Math.random(), serialNumber: "", item: "", cost:""}],
                  }));
              }
              deleteRow = (index) => {
                  this.setState({
                      billTable: this.state.billTable.filter((s, sindex) => index !== sindex),
                  });
              }
              clickOnDelete(record) {
                  this.setState({
                      billTable: this.state.billTable.filter(r => r !== record),

                  });
              }

                  handleSubmit(event){
                      event.preventDefault()

              if(this.validator.allValid()){
                  this.validator.hideMessages()
                      const billed = {
                          Bill:this.state.billTable
              };
              axios.post(`http://localhost:4000/bill`, billed,{

              })
              .then(response => {
                  console.log(response.data)
                  return $('.alert-success').show();

                })

                  this.setState({
                      Bill:"",
                  })
              }
                  else{
                      this.validator.showMessages()
                      this.forceUpdate()
                      return $('.alert-danger').show();
                  }

              }

                  render() {

                      let {billTable} = this.state
                      return (
                          <div>
                              <div className="container">
                                  <div className="form-div">
                                      <h1>Billing</h1>
                                      <Box component="form" onSubmit={this.handleSubmit} noValidate       sx={{ mt: 1}} onChange={this.handleChange}>

                                  <div className="row" style={{ marginTop: 20 }}>
                                      <div className="col-sm-3"></div>
                                      <div className="col-sm-12">
                                          <div className="card">
                                              <div className="card-header text-center">Bill</div>
                                              <div className="card-body">
                                                  <div className="row">
                                                      <div className="col-sm-4">
                                                      </div>
                                                  </div>
                                                  <table>
                                                      <thead>
                                                          <tr>
                                                              <th>Serial #</th>
                                                              <th>Item</th>
                                                              <th>Cost</th>
                                                          </tr>
                                                      </thead>
                                                      <tbody>
                                                          <BillTable id="bill" add={this.addNewRowPlan.bind(this)} delete={this.clickOnDelete.bind(this)} billTable={billTable} />
                                                          {this.validator.message('bill',this.state.Bill,'required')}
                                                      </tbody>
                                                  </table>
                                              </div>

                                          </div>
                                      </div>
                                      <div className="col-sm-1"></div>
                                  </div>
                          <Button
                            type="submit"
                            fullWidth
                            sx={{ mt: 3, mb: 2}}
                          >

                            <span>Submit</span>
                                              </Button>
                                          </Box>
                                      </div>
                                    </div>
                                  </div>
                      );
                  }
              }

              export default Payment;

billTable.js

import React from "react"

const billTable = (props) => {
  return (props.billTable.map((val, idx) => {
      let serialNumber = `serialNumber-$${idx}`, item = `item-$${idx}`, cost = `cost-$${idx}`
      return (
        <tr key={val.index}>
          <td>
            <input type="text"  name="serialNumber" data-id={idx} id={serialNumber} className="form-control" />
          </td>
          <td>
            <input type="text"  name="item" data-id={idx} id={item}  className="form-control " />
          </td>
          <td>
            <input type="text"  name="cost" data-id={idx} id={cost}  className="form-control"/>
          </td>
          <td>
            {
            idx===0?<button onClick={()=>props.add(idx)} type="button" className="btn btn-primary">Add Row</button>
            : <button className="btn btn-danger" onClick={(() => props.delete(val))} >Delete Row</button>
            }
          </td>
        </tr>
      )
    })
  )
}
export default billTable

`````````````````````

How can i correct this code. Thank you in advance
</code>```

Body:
I have a table that can add and delete rows. However, am not able to validate the table. if the table cells are empty or filled am not able to post the values to the backend. The error message still shows.What is the best way to validate the table. I would like to have the error message show if the fields are empty on submit.

payment.js

import React, {Component } from "react";
              import "bootstrap/dist/css/bootstrap.min.css"
              import axios from "axios"
              import SimpleReactValidator from "simple-react-validator"
              import Box from '@mui/material/Box';
              import Button from "@mui/material/Button";
              import BillTable from "./billTable"
              import $ from 'jquery'

              class Payment extends Component {
                  constructor(){
                      super()
                      this.state = {
                      Bill:"",
                      billTable: [{
                          index: Math.random(),
                          serialNumber: "",
                          item:"",
                          cost:""}],
                              errorMessage: '',
                      }
                      this.validator = new SimpleReactValidator({autoForceUpdate: this,messages: {
                          default: 'Please enter this field!'
                      },element: message =>
{message}
})
                      this.handleSubmit = this.handleSubmit.bind(this)
                      this.handleChange = this.handleChange.bind(this)
                  }
                  handleChange = (e) => {
                    if (["serialNumber", "item", "cost"].includes(e.target.name)) {
                      let billTable = [...this.state.billTable]
                      billTable[e.target.dataset.id][e.target.name] = e.target.value;
                    }
                    else {
                      this.setState({ [e.target.name]: e.target.value })
                    }
                  };
              addNewRowPlan = () => {
                this.setState((prevState) => ({
                    billTable: [...prevState.billTable, { index: Math.random(), serialNumber: "", item: "", cost:""}],
                  }));
              }
              deleteRow = (index) => {
                  this.setState({
                      billTable: this.state.billTable.filter((s, sindex) => index !== sindex),
                  });
              }
              clickOnDelete(record) {
                  this.setState({
                      billTable: this.state.billTable.filter(r => r !== record),

                  });
              }

                  handleSubmit(event){
                      event.preventDefault()

              if(this.validator.allValid()){
                  this.validator.hideMessages()
                      const billed = {
                          Bill:this.state.billTable
              };
              axios.post(`http://localhost:4000/bill`, billed,{

              })
              .then(response => {
                  console.log(response.data)
                  return $('.alert-success').show();

                })

                  this.setState({
                      Bill:"",
                  })
              }
                  else{
                      this.validator.showMessages()
                      this.forceUpdate()
                      return $('.alert-danger').show();
                  }

              }

                  render() {

                      let {billTable} = this.state
                      return (

Billing

                                      <Box component="form" onSubmit={this.handleSubmit} noValidate       sx={{ mt: 1}} onChange={this.handleChange}>

Bill

                                                              Serial #
                                                              Item
                                                              Cost

                                                          <BillTable id="bill" add={this.addNewRowPlan.bind(this)} delete={this.clickOnDelete.bind(this)} billTable={billTable} />
                                                          {this.validator.message('bill',this.state.Bill,'required')}

                          <Button
                            type="submit"
                            fullWidth
                            sx={{ mt: 3, mb: 2}}
                          >

                            Submit
                                              </Button>
                                          </Box>

                      );
                  }
              }

              export default Payment;

billTable.js

import React from "react"

const billTable = (props) => {
  return (props.billTable.map((val, idx) => {
      let serialNumber = `serialNumber-$${idx}`, item = `item-$${idx}`, cost = `cost-$${idx}`
      return (

            <input type="text"  name="serialNumber" data-id={idx} id={serialNumber} className="form-control" />

            <input type="text"  name="item" data-id={idx} id={item}  className="form-control " />

            <input type="text"  name="cost" data-id={idx} id={cost}  className="form-control"/>

            {
            idx===0?<button onClick={()=>props.add(idx)} type="button" className="btn btn-primary">Add Row</button>
            : <button className="btn btn-danger" onClick={(() => props.delete(val))} >Delete Row</button>
            }

      )
    })
  )
}
export default billTable

`````````````````````

How can i correct this code. Thank you in advance


问:
I am having a problem with props returning an error of undefined
I am trying to render props from the Room to the single room page. but when I try to access the props I get an empty object.

The below code snippet is the room component.

```<code>import React, { Component} from 'react';
import defaultImg from '../images/room-1.jpeg';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
export default function Room({ room }) {
    const { name, slug, images, price } = room;
    // console.log(slug);
    return (

        <article className='room'>
            <div className='img-container'>
                <img src={images[0] || { defaultImg }} alt='single room' />
                <div className='price-top'>
                    <h6>${price}</h6>
                    <p>per night</p>
                </div>
                <Link to={`/rooms/${slug}`} className='btn-primary room-link'>
                    Features
                </Link>
            </div>
            <p className='room-info'>{name}</p>
        </article>
    )
}

Room.propTypes = {
    room: PropTypes.shape({
        name: PropTypes.string.isRequired,
        slug: PropTypes.string.isRequired,
        images: PropTypes.arrayOf(PropTypes.string).isRequired,
        price: PropTypes.number.isRequired,
    })
}
</code>```
```<code>Above is the parent element that is passing down the slug(prop) property
</code>```

Now this is the single room that is trying to access the props passed from room.js

```<code>import React, { Component } from 'react'
import defaultBcg from '../images/room-1.jpeg'
import Hero from '../Components/Hero'
import Banner from '../Components/Banner'
import { Link } from 'react-router-dom'
import { RoomContext } from '../Context'

export default class SingleRooms extends Component {
  constructor(props) {
    super(props)
    console.log(this.props);
    this.state = {
      slug: this.props.match.params.slug,
      defaultBcg
    };

  }
  static contextType = RoomContext;

  render() {
    const { getRoom } = this.context;
    const room = getRoom(this.state.slug);
    console.log(room);
    return (
      <div>SingleRooms</div>
    )
  }
}
</code>```

But when I try to log the props I get an empty object, I get this error

```<code>"SingleRooms.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'params')" error
</code>```

Here is My app Js using routes

```<code>import Home from "./Pages/Home";
import Error from "./Pages/Error";
import Rooms from "./Pages/Rooms";
import SingleRooms from "./Pages/SingleRooms";
import { Route, Routes } from "react-router-dom";
import Navbar from "./Components/Navbar";
import './App.css';
function App() {
  return (
    <>
    <Navbar/>
        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/rooms' element={<Rooms />} />
          <Route path="/rooms/:slug" element={<SingleRooms />} />
          <Route path="*"element={<Error/>}/>
        </Routes>
    </>
  );
}

export default App;
</code>```
```<code></code>```

Body:
I am trying to render props from the Room to the single room page. but when I try to access the props I get an empty object.

The below code snippet is the room component.

import React, { Component} from 'react';
import defaultImg from '../images/room-1.jpeg';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
export default function Room({ room }) {
    const { name, slug, images, price } = room;
    // console.log(slug);
    return (

${price}

per night

                <Link to={`/rooms/${slug}`} className='btn-primary room-link'>
                    Features
                </Link>

{name}

    )
}

Room.propTypes = {
    room: PropTypes.shape({
        name: PropTypes.string.isRequired,
        slug: PropTypes.string.isRequired,
        images: PropTypes.arrayOf(PropTypes.string).isRequired,
        price: PropTypes.number.isRequired,
    })
}

Above is the parent element that is passing down the slug(prop) property

Now this is the single room that is trying to access the props passed from room.js

import React, { Component } from 'react'
import defaultBcg from '../images/room-1.jpeg'
import Hero from '../Components/Hero'
import Banner from '../Components/Banner'
import { Link } from 'react-router-dom'
import { RoomContext } from '../Context'

export default class SingleRooms extends Component {
  constructor(props) {
    super(props)
    console.log(this.props);
    this.state = {
      slug: this.props.match.params.slug,
      defaultBcg
    };

  }
  static contextType = RoomContext;

  render() {
    const { getRoom } = this.context;
    const room = getRoom(this.state.slug);
    console.log(room);
    return (

SingleRooms

    )
  }
}

But when I try to log the props I get an empty object, I get this error

"SingleRooms.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'params')" error

Here is My app Js using routes

import Home from "./Pages/Home";
import Error from "./Pages/Error";
import Rooms from "./Pages/Rooms";
import SingleRooms from "./Pages/SingleRooms";
import { Route, Routes } from "react-router-dom";
import Navbar from "./Components/Navbar";
import './App.css';
function App() {
  return (
    <>
    <Navbar/>
        <Routes>
          <Route path='/' element={<Home />} />
          <Route path='/rooms' element={<Rooms />} />
          <Route path="/rooms/:slug" element={<SingleRooms />} />
          <Route path="*"element={<Error/>}/>
        </Routes>
    </>
  );
}

export default App;


问:
The game object does not have a script attached to it
 - error message

After completing the bullet script operation, I tried to insert the script into Bullet Sprite in 2D Object format, but an error was displayed and the insertion was not possible. I tried turning off and on the editor because I thought it was a bug because I had the same file name and class name, but it didn't work. Do you happen to know about this problem? The editor version is 2021.3.11f1.

Bullet Script

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;

public class Bullet : MonoBehaviour
{
    [SerializeField]
    private float speed = 10f;

    private IObjectPool<Bullet> pool;

    void Update()
    {
        transform.Translate(Vector2.up);
    }

    public void SetPool(IObjectPool<Bullet> bulletPool)
    {
        Launcher.Instance.bulletPool = pool;
    }

    private void OnBecameInvisible()
    {
        Launcher.Instance.bulletPool.Release(this);
    }

}
```

I turned off and on the editor and changed the class name because I thought it was different.

Body:
 - error message

After completing the bullet script operation, I tried to insert the script into Bullet Sprite in 2D Object format, but an error was displayed and the insertion was not possible. I tried turning off and on the editor because I thought it was a bug because I had the same file name and class name, but it didn't work. Do you happen to know about this problem? The editor version is 2021.3.11f1.

Bullet Script

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;

public class Bullet : MonoBehaviour
{
    [SerializeField]
    private float speed = 10f;

    private IObjectPool<Bullet> pool;

    void Update()
    {
        transform.Translate(Vector2.up);
    }

    public void SetPool(IObjectPool<Bullet> bulletPool)
    {
        Launcher.Instance.bulletPool = pool;
    }

    private void OnBecameInvisible()
    {
        Launcher.Instance.bulletPool.Release(this);
    }

}

I turned off and on the editor and changed the class name because I thought it was different.


问:
How to close the child window which is opened by the parent window using form submit with target="_blank"?
I am creating a javascript form for opening a new browser tab when I do form submit while clicking the button/link.

```<code>var form = document.createElement('form');
document.body.appendChild(form);
form.target = '_blank';
form.method = 'post';
form.action = 'sample.html';
form.submit();
document.body.removeChild(form);
</code>```

Now, I need to close the new tab (child window) which is opened by form submit based on some condition at the Parent window.

Any help would be great!

Body:
I am creating a javascript form for opening a new browser tab when I do form submit while clicking the button/link.

var form = document.createElement('form');
document.body.appendChild(form);
form.target = '_blank';
form.method = 'post';
form.action = 'sample.html';
form.submit();
document.body.removeChild(form);

Now, I need to close the new tab (child window) which is opened by form submit based on some condition at the Parent window.

Any help would be great!


问:
Command failed with exit code 1
enter image description here

How do I go about this,
I have updated my yarn,
lowed the eas-cli version but still gets errors

Title: Command failed with exit code 1


问:
Add New Column In Each Object Inside An Array in MongoDB
Please refer to the attached image.

Questions -
I have to add one column(column name will be Temp) with value "Hello" inside each object (0,1,2) inside "Products" Array.
No of object will not be 3 for each record.
Please help me out with this.


问:
Extract GeoLocation using C# winform application
I am trying to extract GeoLocation (address) of user with the help of C# winform application.
I have checked that with the help of System.Device.Location dll, we can do it.

I tried below code but always I am getting watcher.Position.Location.IsUnknown =true due to which not able to find the address.

Can any one help on same? Do I have to give any specific permission for this?

```<code>using System;
using System.Device.Location;
namespace ResolveAddressSync
{
    class Program
    {
        static void Main(string[] args)
        {
            ResolveAddressSync();
        }
        static void ResolveAddressSync()
        {
            GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            watcher.MovementThreshold = 1.0; // set to one meter
            watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));

            CivicAddressResolver resolver = new CivicAddressResolver();

            if (watcher.Position.Location.IsUnknown == false)
            {
                CivicAddress address = resolver.ResolveAddress(watcher.Position.Location);

                if (!address.IsUnknown)
                {
                    Console.WriteLine("Country: {0}, Zip: {1}",
                            address.CountryRegion,
                            address.PostalCode);
                }
                else
                {
                    Console.WriteLine("Address unknown.");
                }
            }
        }
    }
}
</code>```

Thanks.

Body:
I am trying to extract GeoLocation (address) of user with the help of C# winform application.
I have checked that with the help of System.Device.Location dll, we can do it.

I tried below code but always I am getting watcher.Position.Location.IsUnknown =true due to which not able to find the address.

Can any one help on same? Do I have to give any specific permission for this?

using System;
using System.Device.Location;
namespace ResolveAddressSync
{
    class Program
    {
        static void Main(string[] args)
        {
            ResolveAddressSync();
        }
        static void ResolveAddressSync()
        {
            GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            watcher.MovementThreshold = 1.0; // set to one meter
            watcher.TryStart(false, TimeSpan.FromMilliseconds(1000));

            CivicAddressResolver resolver = new CivicAddressResolver();

            if (watcher.Position.Location.IsUnknown == false)
            {
                CivicAddress address = resolver.ResolveAddress(watcher.Position.Location);

                if (!address.IsUnknown)
                {
                    Console.WriteLine("Country: {0}, Zip: {1}",
                            address.CountryRegion,
                            address.PostalCode);
                }
                else
                {
                    Console.WriteLine("Address unknown.");
                }
            }
        }
    }
}

Thanks.


问:
Amplify AWS Graphql filter is not working with limit
For example, if there are ten students in the class and you want to find three who scored 80, as of now, it works as follows: they retrieve the first three students and filter the scores as 80, then it does not check from the fourth to the tenth student. It should eventually filter out students who have a score of 80, and then it should select three.

Here is the code what I'm trying to do: I want to filter out those that contain "featured" in "tags" and I want 3 results. tags is a string array.

```<code>const filter = {
      tags: { contains: 'FEATURED' },
    };

await API.graphql({
        query: listTestsByStatus,
        variables: { status: 'APPROVED', filter: filter, limit: 3 },
      });
</code>```

Body:
For example, if there are ten students in the class and you want to find three who scored 80, as of now, it works as follows: they retrieve the first three students and filter the scores as 80, then it does not check from the fourth to the tenth student. It should eventually filter out students who have a score of 80, and then it should select three.

Here is the code what I'm trying to do: I want to filter out those that contain "featured" in "tags" and I want 3 results. tags is a string array.

const filter = {
      tags: { contains: 'FEATURED' },
    };

await API.graphql({
        query: listTestsByStatus,
        variables: { status: 'APPROVED', filter: filter, limit: 3 },
      });


问:
Write bash script to output results of commands on remote device in text file on local device
I'm looking at writing a bash script to run a bunch of commands to multiple devices and I want to output the results of each command into a text file on the local device.

So far this is about all I have:

```<code>#!bin/bash

devices={host1 host2}

commands={command1;command2;command3}

if i in ${devices}; do
echo "Working on host: ${i}"
ssh ${i} ${commands} > ${i}_output.txt
echo "====================================================================="
done
</code>```

Body:
I'm looking at writing a bash script to run a bunch of commands to multiple devices and I want to output the results of each command into a text file on the local device.

So far this is about all I have:

#!bin/bash

devices={host1 host2}

commands={command1;command2;command3}

if i in ${devices}; do
echo "Working on host: ${i}"
ssh ${i} ${commands} > ${i}_output.txt
echo "====================================================================="
done


问:
libgpg-error.so.0, needed by ../src/.libs/libgcrypt.so, not found (try using -rpath or -rpath-link)
I am trying to cross compile the libgcrypt-1.10.1 package but I am getting error messages. Actually libgcrypt depends on libgpg-error, I have cross compiled it and added path to LD_LIBRARY_PATH. After doing all these still I am getting errors. Can anyone please help me to find a mistake. Can anyone please help me to solve the below error.

I am getting following error.

Error:

libtool: link: riscv64-unknown-linux-gnu-gcc -g -O2 -fvisibility=hidden -fno-delete-null-pointer-checks -Wall -o version version.o -Wl,--disable-new-dtags  ../src/.libs/libgcrypt.so ../compat/.libs/libcompat.a /root/MDP/RV64G_Fedora_Distro/rpm_stuff/gpg-error_install/lib/libgpg-error.so -Wl,-rpath -Wl,/root/MDP/RV64G_Fedora_Distro/rpm_stuff/libgcrypt-1.10.1/src/.libs -Wl,-rpath -Wl,/root/MDP/RV64G_Fedora_Distro/rpm_stuff/gpg-error_install/lib -Wl,-rpath -Wl,/root/MDP/RV64G_Fedora_Distro/rpm_stuff/libgcrypt_install/lib -Wl,-rpath -Wl,/root/MDP/RV64G_Fedora_Distro/rpm_stuff/gpg-error_install/lib
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: warning: libgpg-error.so.0, needed by ../src/.libs/libgcrypt.so, not found (try using -rpath or -rpath-link)
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_fprintf@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpg_err_code_from_syserror@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_get_syscall_clamp@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_lock_init@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_fwrite@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpg_err_code_from_errno@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_lock_unlock@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_b64dec_start@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_rewind@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_b64dec_finish@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_lock_lock@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpg_err_set_errno@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpg_strsource@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_fclose@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_b64dec_proc@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_fopenmem@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpg_strerror@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_fclose_snatch@GPG_ERROR_1.0'
/root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_ferror@GPG_ERROR_1.0' /root/MDP/RV64G_Fedora_Distro/rv64g-os/cross-tools/lib/gcc/riscv64-unknown-linux-gnu/12.2.0/../../../../riscv64-unknown-linux-gnu/bin/ld: ../src/.libs/libgcrypt.so: undefined reference to gpgrt_lock_destroy@GPG_ERROR_1.0'
collect2: error: ld returned 1 exit status