问:
Angular angular2-draggable ngDraggable drop event not firing
I am using the angular2-draggable library in an Angular 14 project:

```<code>"angular2-draggable": "^2.3.2"
</code>```

When I have a normal draggable element, like this:

```<code><span draggable="true"> Normal Draggable</span>
</code>```

I can drag it over another element that listens for dragover and drop events, like this:

```<code><div (drop)="drop($event)" (dragover)="allowDrop($event)">Drop Area</div>
</code>```

When I drop the normal draggable on the Drop Area, the dragover and drop events fire as expected.

However, when I have an element marked with "ngDraggable", like this:

```<code><span ngDraggable >ngDraggable</span>
</code>```

and I try to do the same thing, neither the dragover nor the drop events fire.

The angular2-draggable library is working great for multiple things I'm doing, but I need to know when an element is dropped on another.

Does anyone know whether/how this can be done?

Thanks much in advance.

Body:
I am using the angular2-draggable library in an Angular 14 project:

"angular2-draggable": "^2.3.2"

When I have a normal draggable element, like this:

 Normal Draggable

I can drag it over another element that listens for dragover and drop events, like this:

Drop Area

When I drop the normal draggable on the Drop Area, the dragover and drop events fire as expected.

However, when I have an element marked with "ngDraggable", like this:

ngDraggable

and I try to do the same thing, neither the dragover nor the drop events fire.

The angular2-draggable library is working great for multiple things I'm doing, but I need to know when an element is dropped on another.

Does anyone know whether/how this can be done?

Thanks much in advance.


来源: stackexchange

问:
How to add new column with conditional values?
I tried to add a new column with values which is conditional also. And Getting below error -

Subqueries are not allowed in this context. Only scalar expressions are allowed.

Add Column SQL:

```<code>IF NOT EXISTS(SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'Dbo'
        AND TABLE_NAME = 'User'
        AND COLUMN_NAME = 'CanEdit')
    BEGIN
        ALTER TABLE [User]
        ADD CanEdit
        AS
        (CASE WHEN IdUser IN (SELECT u.IdUser
                            FROM [User] u INNER JOIN UserRole Usrl
                            ON u.IdUser = Usrl.IdUser INNER JOIN [Role] Rl
                            ON Usrl.IdRole = Rl.IdRole AND Rl.[Name] = 'Admin') THEN 1

                                                                                ELSE 0
         END)
    END
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to add a new column with values which is conditional also. And Getting below error -

Subqueries are not allowed in this context. Only scalar expressions are allowed.

Add Column SQL:

IF NOT EXISTS(SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'Dbo'
        AND TABLE_NAME = 'User'
        AND COLUMN_NAME = 'CanEdit')
    BEGIN
        ALTER TABLE [User]
        ADD CanEdit
        AS
        (CASE WHEN IdUser IN (SELECT u.IdUser
                            FROM [User] u INNER JOIN UserRole Usrl
                            ON u.IdUser = Usrl.IdUser INNER JOIN [Role] Rl
                            ON Usrl.IdRole = Rl.IdRole AND Rl.[Name] = 'Admin') THEN 1

                                                                                ELSE 0
         END)
    END


问:
Transform Matrix4 TransformHelper
tell me what's wrong with the code? I don't know how to change it to make it work,what to do to make this class work, I have already broken my head

```<code>import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';

class TransformHelper {
  static Transform rotate({var? a, var? b, var? c, var? d, Widget? child}) {
    return Transform(
      transform: Matrix4(a ?? 1, c ?? 0, 0, 0, b ?? 0, d ?? 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }

  static Transform scale({var? x, var? y, var? z, Widget? child}) {
    return Transform(
      transform: Matrix4(x ?? 1, 0, 0, 0, 0, y ?? 1, 0, 0, 0, 0, z ?? 1, 0, 0, 0, 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }

  static Transform translate({var? , required Container childx, var? y, var? z, Widget? child}) {
    return Transform(
      transform: Matrix4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x ?? 0, y ?? 0, z ?? 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }

  static Transform translateAndScale({
    var? translateX,
    var? translateY,
    var? translateZ,
    var? scaleX,
    var? scaleY,
    var? scaleZ,
    Widget? child,
  }) {
    return Transform(
      transform: Matrix4(scaleX ?? 1, 0, 0, 0, 0, scaleY ?? 1, 0, 0, 0, 0, scaleZ ?? 1, 0, translateX ?? 0, translateY ?? 0, translateZ ?? 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }
}

</code>```

I've been overreacting but it doesn't help

Title: Transform Matrix4 TransformHelper

Body:
tell me what's wrong with the code? I don't know how to change it to make it work,what to do to make this class work, I have already broken my head

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';

class TransformHelper {
  static Transform rotate({var? a, var? b, var? c, var? d, Widget? child}) {
    return Transform(
      transform: Matrix4(a ?? 1, c ?? 0, 0, 0, b ?? 0, d ?? 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }

  static Transform scale({var? x, var? y, var? z, Widget? child}) {
    return Transform(
      transform: Matrix4(x ?? 1, 0, 0, 0, 0, y ?? 1, 0, 0, 0, 0, z ?? 1, 0, 0, 0, 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }

  static Transform translate({var? , required Container childx, var? y, var? z, Widget? child}) {
    return Transform(
      transform: Matrix4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x ?? 0, y ?? 0, z ?? 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }

  static Transform translateAndScale({
    var? translateX,
    var? translateY,
    var? translateZ,
    var? scaleX,
    var? scaleY,
    var? scaleZ,
    Widget? child,
  }) {
    return Transform(
      transform: Matrix4(scaleX ?? 1, 0, 0, 0, 0, scaleY ?? 1, 0, 0, 0, 0, scaleZ ?? 1, 0, translateX ?? 0, translateY ?? 0, translateZ ?? 0, 1),
      alignment: Alignment.topLeft,
      child: child,
    );
  }
}

I've been overreacting but it doesn't help


问:
safari axios then use window.location.href or location.href not work,but other explorer work
```<code>getSites = async (e, param) => {

      axios.get(`${Config.siteInfo}`).then(res => {
        if (res.status === 200 && res.data?.data) {
          if (param === 'baidu') {
            var url = res.data.data[0].site
            window.location.href = url  //**not work in safari, but work in android or chrome (url value correct)**
          }
        }
      }).catch(error => {
        console.log('getSites error:', error);
      });
  }

<div className="list">
  <div
    className="list-item"
    onClick={e => {
      this.getSites(e, 'baidu')

    }}
  >
    <span>
      <img src={logo} className="test" alt="" />
    </span>
    <span>{'测试'}</span>
  </div>
</div>
</code>```

i don't know why using the 'window.location.href' or 'location.href' not working in safari, but work in android and other explorer, anyone knows? thanks

Body:
getSites = async (e, param) => {

      axios.get(`${Config.siteInfo}`).then(res => {
        if (res.status === 200 && res.data?.data) {
          if (param === 'baidu') {
            var url = res.data.data[0].site
            window.location.href = url  //**not work in safari, but work in android or chrome (url value correct)**
          }
        }
      }).catch(error => {
        console.log('getSites error:', error);
      });
  }

 {
      this.getSites(e, 'baidu')

    }}
  >

    {'测试'}

i don't know why using the 'window.location.href' or 'location.href' not working in safari, but work in android and other explorer, anyone knows? thanks


问:
Java QueryDSL Building a Path through a Map dynamically
I'm looking to form a QueryDSL Path where there is a Map somewhere in the object hierarchy. If I just have simple object hierarchies, I can do the following, which works:

```<code>        BooleanBuilder builder = new BooleanBuilder();
        Path path = Expressions.path(Outer.class, "root");
        path = Expressions.path(Inner.class, path, "inner");
        builder.and(Expressions.path(String.class, path, "field").eq("test"));
</code>```

However, I'm a bit confused when coming to a Map. There doesn't seem to be method parameter to pass in the root path, so I'm just at a loss on what to do. Passing the Path metadata doesn't seem to work, but I really didn't expect it to. And there is also no place to pass in the property name that is the map.

```<code>        BooleanBuilder builder = new BooleanBuilder();
        Path path = Expressions.path(Outer.class, "root");
        path = Expressions.mapPath(String.class, String.class, StringPath.class, path.getMetadata()); // What would be the proper way to dive down into the map?
        builder.and(Expressions.path(String.class, path, "field").eq("test"));
</code>```

Clearly I do not understand the proper use of this method, but I am unable to glean what the proper use would be.

Also of note, I'm trying to do this dynamically, so even though I could use Q-generated classes in these examples, that isn't my final goal.

So if I had an object structure of Outer.map[key].field, how could I build a Path to select field?

The closest question I found was QueryDsl web query on the key of a Map field, but that assumes directly accessing a dictionary, not having a dictionary somewhere in the path.

Body:
I'm looking to form a QueryDSL Path where there is a Map somewhere in the object hierarchy. If I just have simple object hierarchies, I can do the following, which works:

        BooleanBuilder builder = new BooleanBuilder();
        Path path = Expressions.path(Outer.class, "root");
        path = Expressions.path(Inner.class, path, "inner");
        builder.and(Expressions.path(String.class, path, "field").eq("test"));

However, I'm a bit confused when coming to a Map. There doesn't seem to be method parameter to pass in the root path, so I'm just at a loss on what to do. Passing the Path metadata doesn't seem to work, but I really didn't expect it to. And there is also no place to pass in the property name that is the map.

        BooleanBuilder builder = new BooleanBuilder();
        Path path = Expressions.path(Outer.class, "root");
        path = Expressions.mapPath(String.class, String.class, StringPath.class, path.getMetadata()); // What would be the proper way to dive down into the map?
        builder.and(Expressions.path(String.class, path, "field").eq("test"));

Clearly I do not understand the proper use of this method, but I am unable to glean what the proper use would be.

Also of note, I'm trying to do this dynamically, so even though I could use Q-generated classes in these examples, that isn't my final goal.

So if I had an object structure of Outer.map[key].field, how could I build a Path to select field?

The closest question I found was QueryDsl web query on the key of a Map field, but that assumes directly accessing a dictionary, not having a dictionary somewhere in the path.


问:
How can I auto-populate an ACF field on a standard Wordpress post with the date of the post (year only)?
I am not a coding person at all (very basic HTML and CSS) but I have been asked by a client to have a field in each post they make (just standard WP posts, not custom post types or anything) which holds the year that the post was created. This was easy enough using ACF and the field now shows up  underneath the main content area when editing the post. What I am having no luck figuring out is how to automatically fill that field with the year when the post is saved (initially saved...not updated).

I got some info from ACF about using the acf-save_post action and the "applied before save" version...and they also directed me to the Wordpress Developer Resources site for using get_the_date. The trouble is, I have NO idea what I am doing with PHP! What I tried piecing together is below with (I presume) the function name being "acf_post_year" and the ACF field name being "post_year":

```<code>add_action('acf/save_post', 'acf_post_year', 5);
function acf_post_year( $post_id ) {

    // Get previous values.
    $prev_values = get_fields( $post_id );

    // Get submitted values.
    $values = $_POST['acf'];

    // Check if a specific value was updated.
    if( isset($_POST['acf']['post_year']) ) {
        function get_the_date( $format = 'Y', $post = null ) {
        $post = get_post( $post );

        if ( ! $post ) {
            return false;
        }

        $_format = ! empty( $format ) ? $format : get_option( 'date_format' );

        $the_date = get_post_time( $_format, false, $post, true );

        /**
        * Filters the date a post was published.
        *
        * @since 3.0.0
        *
        * @param string|int  $the_date Formatted date string or Unix timestamp if `$format` is 'U' or 'G'.
        * @param string      $format   PHP date format.
        * @param WP_Post     $post     The post object.
        */
        return apply_filters( 'get_the_date', $the_date, $format, $post );
    }
    }
}
</code>```

Obviously it didn't work and I don't even know where to start! So if anybody can give me a solution that I can just drop in to functions.php (using Code Snippets as I currently am) that would be amazing!! In return for you time and knowledge, you are more than welcome to mock me for taking on something I clearly have no ability to finish!!!

Body:
I am not a coding person at all (very basic HTML and CSS) but I have been asked by a client to have a field in each post they make (just standard WP posts, not custom post types or anything) which holds the year that the post was created. This was easy enough using ACF and the field now shows up  underneath the main content area when editing the post. What I am having no luck figuring out is how to automatically fill that field with the year when the post is saved (initially saved...not updated).

I got some info from ACF about using the acf-save_post action and the "applied before save" version...and they also directed me to the Wordpress Developer Resources site for using get_the_date. The trouble is, I have NO idea what I am doing with PHP! What I tried piecing together is below with (I presume) the function name being "acf_post_year" and the ACF field name being "post_year":

add_action('acf/save_post', 'acf_post_year', 5);
function acf_post_year( $post_id ) {

    // Get previous values.
    $prev_values = get_fields( $post_id );

    // Get submitted values.
    $values = $_POST['acf'];

    // Check if a specific value was updated.
    if( isset($_POST['acf']['post_year']) ) {
        function get_the_date( $format = 'Y', $post = null ) {
        $post = get_post( $post );

        if ( ! $post ) {
            return false;
        }

        $_format = ! empty( $format ) ? $format : get_option( 'date_format' );

        $the_date = get_post_time( $_format, false, $post, true );

        /**
        * Filters the date a post was published.
        *
        * @since 3.0.0
        *
        * @param string|int  $the_date Formatted date string or Unix timestamp if `$format` is 'U' or 'G'.
        * @param string      $format   PHP date format.
        * @param WP_Post     $post     The post object.
        */
        return apply_filters( 'get_the_date', $the_date, $format, $post );
    }
    }
}

Obviously it didn't work and I don't even know where to start! So if anybody can give me a solution that I can just drop in to functions.php (using Code Snippets as I currently am) that would be amazing!! In return for you time and knowledge, you are more than welcome to mock me for taking on something I clearly have no ability to finish!!!


问:
ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets
I did a ML model of handwritten digit recognition, and I'm trying to use the accuracy_score to know the % of the predcition if the model is accurated enough.

This is the model:

```<code>model = Sequential(
    [
        tf.keras.Input(shape=(64,)),
        Dense(25, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01), name = "L1"),
        Dense(15, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01), name = "L2"),
        Dense(10, activation='linear', name = "L3"),
    ], name = "my_model"
)
#Compiling the model
model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer=tf.keras.optimizers.Adam(0.01),
)
#Fitting the model
model.fit(
    x_train, y_train,
    epochs=1000

</code>```

Here is some of the data:

```<code>(1797, 64)
X_train.shape (1078, 64) y_train.shape (1078,)
X_cv.shape (359, 64) y_cv.shape (359,)
X_test.shape (360, 64) y_test.shape (360,)
[[ 0.  0.  5. ...  0.  0.  0.]
 [ 0.  0.  0. ... 10.  0.  0.]
 [ 0.  0.  0. ... 16.  9.  0.]
 ...
 [ 0.  0.  0. ...  7.  0.  0.]
 [ 0.  2. 15. ...  5.  0.  0.]
 [ 0.  0.  1. ...  3.  0.  0.]]

</code>```

Everytime I run the code and use the accuracy_score I get the error message:

ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets

Does anyone know how I can fix this?
Thanks in advance.

I tried a way to fix, but I'm not sure if it's correct.
I used this code:

```<code>predictions = model.predict(x_test)
print(accuracy_score(y_test, np.argmax(predictions, axis=1)))
I get a number like '0.90', but I'm not sure if it's correct.
</code>```

Body:
I did a ML model of handwritten digit recognition, and I'm trying to use the accuracy_score to know the % of the predcition if the model is accurated enough.

This is the model:

model = Sequential(
    [
        tf.keras.Input(shape=(64,)),
        Dense(25, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01), name = "L1"),
        Dense(15, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.01), name = "L2"),
        Dense(10, activation='linear', name = "L3"),
    ], name = "my_model"
)
#Compiling the model
model.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    optimizer=tf.keras.optimizers.Adam(0.01),
)
#Fitting the model
model.fit(
    x_train, y_train,
    epochs=1000

Here is some of the data:

(1797, 64)
X_train.shape (1078, 64) y_train.shape (1078,)
X_cv.shape (359, 64) y_cv.shape (359,)
X_test.shape (360, 64) y_test.shape (360,)
[[ 0.  0.  5. ...  0.  0.  0.]
 [ 0.  0.  0. ... 10.  0.  0.]
 [ 0.  0.  0. ... 16.  9.  0.]
 ...
 [ 0.  0.  0. ...  7.  0.  0.]
 [ 0.  2. 15. ...  5.  0.  0.]
 [ 0.  0.  1. ...  3.  0.  0.]]

Everytime I run the code and use the accuracy_score I get the error message:

ValueError: Classification metrics can't handle a mix of multiclass and multiclass-multioutput targets

Does anyone know how I can fix this?
Thanks in advance.

I tried a way to fix, but I'm not sure if it's correct.
I used this code:

predictions = model.predict(x_test)
print(accuracy_score(y_test, np.argmax(predictions, axis=1)))
I get a number like '0.90', but I'm not sure if it's correct.


问:
azure-event-hubs-for-kafka: EOF during handshake, handshake status is NEED_UNWRAP
i'm trying the azure-event-hubs-for-kafka quickstart java samples, and cannot get producer working, error message:

```<code>[Producer clientId=KafkaExampleProducer] Connection with <my_EH_namespace>.servicebus.windows.net/191.1.129.16 disconnected
java.io.EOFException: EOF during handshake, handshake status is NEED_UNWRAP
    at org.apache.kafka.common.network.SslTransportLayer.handshakeUnwrap(SslTransportLayer.java:525)
    at org.apache.kafka.common.network.SslTransportLayer.doHandshake(SslTransportLayer.java:368)
    at org.apache.kafka.common.network.SslTransportLayer.handshake(SslTransportLayer.java:291)
    at org.apache.kafka.common.network.KafkaChannel.prepare(KafkaChannel.java:178)
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:543)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:481)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:551)
    at org.apache.kafka.clients.NetworkClientUtils.awaitReady(NetworkClientUtils.java:74)
    at org.apache.kafka.clients.producer.internals.Sender.awaitNodeReady(Sender.java:526)
    at org.apache.kafka.clients.producer.internals.Sender.maybeSendAndPollTransactionalRequest(Sender.java:447)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:316)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:243)
    at java.base/java.lang.Thread.run(Thread.java:833)
2023-01-11 09:06:34 DEBUG SslTransportLayer:198 - [SslTransportLayer channelId=-1 key=channel=java.nio.channels.SocketChannel[connection-pending remote=<my_EH_namespace>.servicebus.windows.net/191.1.129.16:9093], selector=sun.nio.ch.KQueueSelectorImpl@5603a6ad, interestOps=8, readyOps=0] Failed to send SSL Close message
</code>```

here is my producer.config:

```<code>bootstrap.servers=<my_EH_namespace_here>.servicebus.windows.net:9093
security.protocol=SASL_SSL
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="$ConnectionString" password="Endpoint=sb://<my_EH_namespace_here>.servicebus.windows.net/;SharedAccessKeyName=xxxxxx;SharedAccessKey=xxxxxx";
</code>```

apache kafka-clients: 3.0.1

here is the log from the run:

```<code>2023-01-11 09:05:49 INFO  KafkaProducer:532 - [Producer clientId=KafkaExampleProducer] Instantiated an idempotent producer.
2023-01-11 09:05:49 INFO  AbstractLogin:61 - Successfully logged in.
2023-01-11 09:05:49 DEBUG DefaultSslEngineFactory:264 - Created SSL context with keystore null, truststore null, provider SunJSSE.
2023-01-11 09:05:49 DEBUG Sender:238 - [Producer clientId=KafkaExampleProducer] Starting Kafka producer I/O thread.
2023-01-11 09:05:49 DEBUG TransactionManager:1091 - [Producer clientId=KafkaExampleProducer] Transition from state UNINITIALIZED to INITIALIZING
2023-01-11 09:05:49 INFO  AppInfoParser:119 - Kafka version: 3.0.1
2023-01-11 09:05:49 INFO  AppInfoParser:120 - Kafka commitId: 8e30984f43e64d8b
2023-01-11 09:05:49 INFO  AppInfoParser:121 - Kafka startTimeMs: 1673456749806
2023-01-11 09:05:49 DEBUG KafkaProducer:434 - [Producer clientId=KafkaExampleProducer] Kafka producer started
2023-01-11 09:05:49 DEBUG TransactionManager:1129 - [Producer clientId=KafkaExampleProducer] Enqueuing transactional request InitProducerIdRequestData(transactionalId=null, transactionTimeoutMs=2147483647, producerId=-1, producerEpoch=-1)
2023-01-11 09:05:49 DEBUG NetworkClient:1151 - [Producer clientId=KafkaExampleProducer] Initialize connection to node <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) for sending metadata request
2023-01-11 09:05:49 DEBUG ClientUtils:113 - Resolved host <my_EH_namespace>.servicebus.windows.net as 191.1.129.16
2023-01-11 09:05:49 DEBUG NetworkClient:980 - [Producer clientId=KafkaExampleProducer] Initiating connection to node <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) using address <my_EH_namespace>.servicebus.windows.net/191.1.129.16
2023-01-11 09:05:49 DEBUG SaslClientAuthenticator:411 - [Producer clientId=KafkaExampleProducer] Set SASL client state to SEND_APIVERSIONS_REQUEST
2023-01-11 09:05:49 DEBUG SaslClientAuthenticator:217 - [Producer clientId=KafkaExampleProducer] Creating SaslClient: client=null;service=kafka;serviceHostname=<my_EH_namespace>.servicebus.windows.net;mechs=[PLAIN]
2023-01-11 09:05:49 DEBUG Selector:531 - [Producer clientId=KafkaExampleProducer] Created socket with SO_RCVBUF = 32768, SO_SNDBUF = 131072, SO_TIMEOUT = 0 to node -1
2023-01-11 09:05:49 DEBUG NetworkClient:942 - [Producer clientId=KafkaExampleProducer] Completed connection to node -1. Fetching API versions.
Test Data #0 from thread #20
2023-01-11 09:05:59 DEBUG SslTransportLayer:198 - [SslTransportLayer channelId=-1 key=channel=java.nio.channels.SocketChannel[connection-pending remote=<my_EH_namespace>.servicebus.windows.net/191.1.129.16:9093], selector=sun.nio.ch.KQueueSelectorImpl@5603a6ad, interestOps=8, readyOps=0] Failed to send SSL Close message
java.io.IOException: Unexpected status returned by SSLEngine.wrap, expected CLOSED, received OK. Will not send close message to peer.
    at org.apache.kafka.common.network.SslTransportLayer.close(SslTransportLayer.java:192)
    at org.apache.kafka.common.utils.Utils.closeAll(Utils.java:972)
    at org.apache.kafka.common.network.KafkaChannel.close(KafkaChannel.java:155)
    at org.apache.kafka.common.network.Selector.doClose(Selector.java:955)
    at org.apache.kafka.common.network.Selector.close(Selector.java:939)
    at org.apache.kafka.common.network.Selector.close(Selector.java:885)
    at org.apache.kafka.clients.NetworkClient.handleTimedOutConnections(NetworkClient.java:809)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:564)
    at org.apache.kafka.clients.NetworkClientUtils.awaitReady(NetworkClientUtils.java:74)
    at org.apache.kafka.clients.producer.internals.Sender.awaitNodeReady(Sender.java:526)
    at org.apache.kafka.clients.producer.internals.Sender.maybeSendAndPollTransactionalRequest(Sender.java:447)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:316)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:243)
    at java.base/java.lang.Thread.run(Thread.java:833)
2023-01-11 09:05:59 DEBUG NetworkClient:810 - [Producer clientId=KafkaExampleProducer] Disconnecting from node -1 due to socket connection setup timeout. The timeout value is 9404 ms.
2023-01-11 09:05:59 WARN  NetworkClient:1054 - [Producer clientId=KafkaExampleProducer] Bootstrap broker <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) disconnected
2023-01-11 09:05:59 DEBUG Sender:475 - [Producer clientId=KafkaExampleProducer] Disconnect from <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) while trying to send request InitProducerIdRequestData(transactionalId=null, transactionTimeoutMs=2147483647, producerId=-1, producerEpoch=-1). Going to back off and retry.
java.io.IOException: Connection to <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) failed.
    at org.apache.kafka.clients.NetworkClientUtils.awaitReady(NetworkClientUtils.java:71)
    at org.apache.kafka.clients.producer.internals.Sender.awaitNodeReady(Sender.java:526)
    at org.apache.kafka.clients.producer.internals.Sender.maybeSendAndPollTransactionalRequest(Sender.java:447)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:316)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:243)
    at java.base/java.lang.Thread.run(Thread.java:833)

</code>```

Body:
i'm trying the azure-event-hubs-for-kafka quickstart java samples, and cannot get producer working, error message:

[Producer clientId=KafkaExampleProducer] Connection with <my_EH_namespace>.servicebus.windows.net/191.1.129.16 disconnected
java.io.EOFException: EOF during handshake, handshake status is NEED_UNWRAP
    at org.apache.kafka.common.network.SslTransportLayer.handshakeUnwrap(SslTransportLayer.java:525)
    at org.apache.kafka.common.network.SslTransportLayer.doHandshake(SslTransportLayer.java:368)
    at org.apache.kafka.common.network.SslTransportLayer.handshake(SslTransportLayer.java:291)
    at org.apache.kafka.common.network.KafkaChannel.prepare(KafkaChannel.java:178)
    at org.apache.kafka.common.network.Selector.pollSelectionKeys(Selector.java:543)
    at org.apache.kafka.common.network.Selector.poll(Selector.java:481)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:551)
    at org.apache.kafka.clients.NetworkClientUtils.awaitReady(NetworkClientUtils.java:74)
    at org.apache.kafka.clients.producer.internals.Sender.awaitNodeReady(Sender.java:526)
    at org.apache.kafka.clients.producer.internals.Sender.maybeSendAndPollTransactionalRequest(Sender.java:447)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:316)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:243)
    at java.base/java.lang.Thread.run(Thread.java:833)
2023-01-11 09:06:34 DEBUG SslTransportLayer:198 - [SslTransportLayer channelId=-1 key=channel=java.nio.channels.SocketChannel[connection-pending remote=<my_EH_namespace>.servicebus.windows.net/191.1.129.16:9093], selector=sun.nio.ch.KQueueSelectorImpl@5603a6ad, interestOps=8, readyOps=0] Failed to send SSL Close message

here is my producer.config:

bootstrap.servers=<my_EH_namespace_here>.servicebus.windows.net:9093
security.protocol=SASL_SSL
sasl.mechanism=PLAIN
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required username="$ConnectionString" password="Endpoint=sb://<my_EH_namespace_here>.servicebus.windows.net/;SharedAccessKeyName=xxxxxx;SharedAccessKey=xxxxxx";

apache kafka-clients: 3.0.1

here is the log from the run:

2023-01-11 09:05:49 INFO  KafkaProducer:532 - [Producer clientId=KafkaExampleProducer] Instantiated an idempotent producer.
2023-01-11 09:05:49 INFO  AbstractLogin:61 - Successfully logged in.
2023-01-11 09:05:49 DEBUG DefaultSslEngineFactory:264 - Created SSL context with keystore null, truststore null, provider SunJSSE.
2023-01-11 09:05:49 DEBUG Sender:238 - [Producer clientId=KafkaExampleProducer] Starting Kafka producer I/O thread.
2023-01-11 09:05:49 DEBUG TransactionManager:1091 - [Producer clientId=KafkaExampleProducer] Transition from state UNINITIALIZED to INITIALIZING
2023-01-11 09:05:49 INFO  AppInfoParser:119 - Kafka version: 3.0.1
2023-01-11 09:05:49 INFO  AppInfoParser:120 - Kafka commitId: 8e30984f43e64d8b
2023-01-11 09:05:49 INFO  AppInfoParser:121 - Kafka startTimeMs: 1673456749806
2023-01-11 09:05:49 DEBUG KafkaProducer:434 - [Producer clientId=KafkaExampleProducer] Kafka producer started
2023-01-11 09:05:49 DEBUG TransactionManager:1129 - [Producer clientId=KafkaExampleProducer] Enqueuing transactional request InitProducerIdRequestData(transactionalId=null, transactionTimeoutMs=2147483647, producerId=-1, producerEpoch=-1)
2023-01-11 09:05:49 DEBUG NetworkClient:1151 - [Producer clientId=KafkaExampleProducer] Initialize connection to node <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) for sending metadata request
2023-01-11 09:05:49 DEBUG ClientUtils:113 - Resolved host <my_EH_namespace>.servicebus.windows.net as 191.1.129.16
2023-01-11 09:05:49 DEBUG NetworkClient:980 - [Producer clientId=KafkaExampleProducer] Initiating connection to node <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) using address <my_EH_namespace>.servicebus.windows.net/191.1.129.16
2023-01-11 09:05:49 DEBUG SaslClientAuthenticator:411 - [Producer clientId=KafkaExampleProducer] Set SASL client state to SEND_APIVERSIONS_REQUEST
2023-01-11 09:05:49 DEBUG SaslClientAuthenticator:217 - [Producer clientId=KafkaExampleProducer] Creating SaslClient: client=null;service=kafka;serviceHostname=<my_EH_namespace>.servicebus.windows.net;mechs=[PLAIN]
2023-01-11 09:05:49 DEBUG Selector:531 - [Producer clientId=KafkaExampleProducer] Created socket with SO_RCVBUF = 32768, SO_SNDBUF = 131072, SO_TIMEOUT = 0 to node -1
2023-01-11 09:05:49 DEBUG NetworkClient:942 - [Producer clientId=KafkaExampleProducer] Completed connection to node -1. Fetching API versions.
Test Data #0 from thread #20
2023-01-11 09:05:59 DEBUG SslTransportLayer:198 - [SslTransportLayer channelId=-1 key=channel=java.nio.channels.SocketChannel[connection-pending remote=<my_EH_namespace>.servicebus.windows.net/191.1.129.16:9093], selector=sun.nio.ch.KQueueSelectorImpl@5603a6ad, interestOps=8, readyOps=0] Failed to send SSL Close message
java.io.IOException: Unexpected status returned by SSLEngine.wrap, expected CLOSED, received OK. Will not send close message to peer.
    at org.apache.kafka.common.network.SslTransportLayer.close(SslTransportLayer.java:192)
    at org.apache.kafka.common.utils.Utils.closeAll(Utils.java:972)
    at org.apache.kafka.common.network.KafkaChannel.close(KafkaChannel.java:155)
    at org.apache.kafka.common.network.Selector.doClose(Selector.java:955)
    at org.apache.kafka.common.network.Selector.close(Selector.java:939)
    at org.apache.kafka.common.network.Selector.close(Selector.java:885)
    at org.apache.kafka.clients.NetworkClient.handleTimedOutConnections(NetworkClient.java:809)
    at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:564)
    at org.apache.kafka.clients.NetworkClientUtils.awaitReady(NetworkClientUtils.java:74)
    at org.apache.kafka.clients.producer.internals.Sender.awaitNodeReady(Sender.java:526)
    at org.apache.kafka.clients.producer.internals.Sender.maybeSendAndPollTransactionalRequest(Sender.java:447)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:316)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:243)
    at java.base/java.lang.Thread.run(Thread.java:833)
2023-01-11 09:05:59 DEBUG NetworkClient:810 - [Producer clientId=KafkaExampleProducer] Disconnecting from node -1 due to socket connection setup timeout. The timeout value is 9404 ms.
2023-01-11 09:05:59 WARN  NetworkClient:1054 - [Producer clientId=KafkaExampleProducer] Bootstrap broker <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) disconnected
2023-01-11 09:05:59 DEBUG Sender:475 - [Producer clientId=KafkaExampleProducer] Disconnect from <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) while trying to send request InitProducerIdRequestData(transactionalId=null, transactionTimeoutMs=2147483647, producerId=-1, producerEpoch=-1). Going to back off and retry.
java.io.IOException: Connection to <my_EH_namespace>.servicebus.windows.net:9093 (id: -1 rack: null) failed.
    at org.apache.kafka.clients.NetworkClientUtils.awaitReady(NetworkClientUtils.java:71)
    at org.apache.kafka.clients.producer.internals.Sender.awaitNodeReady(Sender.java:526)
    at org.apache.kafka.clients.producer.internals.Sender.maybeSendAndPollTransactionalRequest(Sender.java:447)
    at org.apache.kafka.clients.producer.internals.Sender.runOnce(Sender.java:316)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:243)
    at java.base/java.lang.Thread.run(Thread.java:833)


问:
Cant get JSON file in postman response in GET and POST requests
I am trying to make a MERN application project and I have make a server with node and express, I made API and i am testing it in postman. The api is working fine with mongodb when i post something but when i request GET it is not showing me or returning the response in JSON file, the status code is also getting success but its getting timed out and says ABORTED in response tab of postman.
Please help how to solve this and get JSON in response of postman.

This is my GET request controller:

const getAllExecise = async (req, res) => { const allExercises = await Workout.find({}).sort({createdAt: -1}) res.status(101).json(allExercises) }

and also it shows warning on VScode that refactor redundunt await on a non promise.
Please help how to solve this and get JSON in response of postman.


问:
Multithreadning in GNU Octave with GNU Octave code
I'm looking for a way to run a function over and over and over again by using multithreadning. Is there any way to do that in GNU Octave?</p>


问:
Loaded ML model in Flask always returns the same output
I'm trying to deploy an XGBoost ML Model on a bank customer churn dataset using Flask. The code runs without any errors but it always returns the same output ("This Customer is likely to Continue! Confidence level is [0.80315804]", yes even the same probability score) no matter what values I fill in the request forms.

The code I'm trying to run:

```<code>import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import pickle
from flask import Flask, request, render_template

app = Flask(__name__,template_folder='templates')

df_1=pd.read_csv("Churn_Modelling.csv")

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

@app.route("/", methods=['POST'])
def predict():

    CreditScore = float(request.form['CreditScore'])
    Geography = (request.form['Geography'])
    Gender = request.form['Gender']
    Age = float(request.form['Age'])
    Tenure = float(request.form['Tenure'])
    Balance = float(request.form['Balance'])
    NumOfProducts = request.form['NumOfProducts']
    HasCrCard = request.form['HasCrCard']
    IsActiveMember = request.form['IsActiveMember']
    EstimatedSalary = float(request.form['EstimatedSalary'])

    model = pickle.load(open('churn_model.pkl', 'rb'))
    data = [[CreditScore, Geography, Gender, Age, Tenure, Balance, NumOfProducts, HasCrCard, IsActiveMember, EstimatedSalary]]
    new_df = pd.DataFrame(data, columns=['CreditScore', 'Geography', 'Gender',
        'Age', 'Tenure', 'Balance', 'NumOfProducts',
        'HasCrCard', 'IsActiveMember', 'EstimatedSalary'])

    df_1.drop(columns= ['RowNumber','CustomerId','Surname','Exited'], axis=1, inplace=True)

    new_df__dummies = pd.get_dummies(df_1[['CreditScore', 'Geography',
       'Gender', 'Age','Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
       'IsActiveMember', 'EstimatedSalary']])

    single = model.predict(new_df__dummies.tail(1))
    probability = model.predict_proba(new_df__dummies.tail(1))[:, 1]

    print(single)

    if single == 1:
        op1 = "This Customer is likely to be Churned!"
        op2 = "Confidence level is {}".format(probability*100)
    else:
        op1 = "This Customer is likely to Continue!"
        op2 = "Confidence level is {}".format(probability*100)

    return render_template("index.html", op1=op1, op2=op2,
                           CreditScore=request.form['CreditScore'],
                           Geography=request.form['Geography'],
                           Gender=request.form['Gender'],
                           Age=request.form['Age'],
                           Tenure=request.form['Tenure'],
                           Balance=request.form['Balance'],
                           NumOfProducts=request.form['NumOfProducts'],
                           HasCrCard=request.form['HasCrCard'],
                           IsActiveMember=request.form['IsActiveMember'],
                           EstimatedSalary=request.form['EstimatedSalary'])

if __name__ == '__main__':
    app.run(debug=True)
</code>```

I'm sure the problem isn't with the ML model which I built in a separate ipynb file since I have tested some sample row predictions and the results were just about expected. So I believe the problem is within the posted code, but I can't figure out where I made a mistake.

Thanks in advance!

Body:
I'm trying to deploy an XGBoost ML Model on a bank customer churn dataset using Flask. The code runs without any errors but it always returns the same output ("This Customer is likely to Continue! Confidence level is [0.80315804]", yes even the same probability score) no matter what values I fill in the request forms.

The code I'm trying to run:

import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import pickle
from flask import Flask, request, render_template

app = Flask(__name__,template_folder='templates')

df_1=pd.read_csv("Churn_Modelling.csv")

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

@app.route("/", methods=['POST'])
def predict():

    CreditScore = float(request.form['CreditScore'])
    Geography = (request.form['Geography'])
    Gender = request.form['Gender']
    Age = float(request.form['Age'])
    Tenure = float(request.form['Tenure'])
    Balance = float(request.form['Balance'])
    NumOfProducts = request.form['NumOfProducts']
    HasCrCard = request.form['HasCrCard']
    IsActiveMember = request.form['IsActiveMember']
    EstimatedSalary = float(request.form['EstimatedSalary'])

    model = pickle.load(open('churn_model.pkl', 'rb'))
    data = [[CreditScore, Geography, Gender, Age, Tenure, Balance, NumOfProducts, HasCrCard, IsActiveMember, EstimatedSalary]]
    new_df = pd.DataFrame(data, columns=['CreditScore', 'Geography', 'Gender',
        'Age', 'Tenure', 'Balance', 'NumOfProducts',
        'HasCrCard', 'IsActiveMember', 'EstimatedSalary'])

    df_1.drop(columns= ['RowNumber','CustomerId','Surname','Exited'], axis=1, inplace=True)

    new_df__dummies = pd.get_dummies(df_1[['CreditScore', 'Geography',
       'Gender', 'Age','Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
       'IsActiveMember', 'EstimatedSalary']])

    single = model.predict(new_df__dummies.tail(1))
    probability = model.predict_proba(new_df__dummies.tail(1))[:, 1]

    print(single)

    if single == 1:
        op1 = "This Customer is likely to be Churned!"
        op2 = "Confidence level is {}".format(probability*100)
    else:
        op1 = "This Customer is likely to Continue!"
        op2 = "Confidence level is {}".format(probability*100)

    return render_template("index.html", op1=op1, op2=op2,
                           CreditScore=request.form['CreditScore'],
                           Geography=request.form['Geography'],
                           Gender=request.form['Gender'],
                           Age=request.form['Age'],
                           Tenure=request.form['Tenure'],
                           Balance=request.form['Balance'],
                           NumOfProducts=request.form['NumOfProducts'],
                           HasCrCard=request.form['HasCrCard'],
                           IsActiveMember=request.form['IsActiveMember'],
                           EstimatedSalary=request.form['EstimatedSalary'])

if __name__ == '__main__':
    app.run(debug=True)

I'm sure the problem isn't with the ML model which I built in a separate ipynb file since I have tested some sample row predictions and the results were just about expected. So I believe the problem is within the posted code, but I can't figure out where I made a mistake.

Thanks in advance!


问:
pd.read_csv with varying header row
I am writing a program to vertically concatenate user input .csv files. It's assumed that they all have the same header, but there may or may not be metadata/comments and blank rows above the header row.

EX:

```<code>Client Name
Report Name
Date Data Pulled: Date
(blank)
(blank)
(blank)
col1   col2   col3   ...
data  data   data   ...
...
</code>```

I am having trouble writing that portion of this program that effectively detects the location of the header so that I have the right header or skiprows argument for pd.read_csv.

This was the closest I got, from another thread (which I'd link if I could find):

```<code>def file_len(file):
    with open(file) as f:
        for i, l in enumerate(f):
            pass
        return i+1

def unknown_header_read(file):
    rows = file_len(file)
    for i in range(rows):
        try:
            df = pd.read_csv(file, skiprows=range(i))
            return df
        except Exception:
            pass
</code>```

The issue I ran into--when testing on a .csv structured exactly like the example above--was that the returned df had 1 column whose header was the last piece of metadata, first row of that column was the last actual header column, followed by all of that column's corresponding data.
The remaining actual headers and data were in a multi-index--no idea why.
FWIW I'm using Spyder.
Note that the test file I'm working with does have a comma in the client name, which made the first row of metadata inadvertently have two columns.

Title: pd.read_csv with varying header row

Body:
I am writing a program to vertically concatenate user input .csv files. It's assumed that they all have the same header, but there may or may not be metadata/comments and blank rows above the header row.

EX:

Client Name
Report Name
Date Data Pulled: Date
(blank)
(blank)
(blank)
col1   col2   col3   ...
data  data   data   ...
...

I am having trouble writing that portion of this program that effectively detects the location of the header so that I have the right header or skiprows argument for pd.read_csv.

This was the closest I got, from another thread (which I'd link if I could find):

def file_len(file):
    with open(file) as f:
        for i, l in enumerate(f):
            pass
        return i+1

def unknown_header_read(file):
    rows = file_len(file)
    for i in range(rows):
        try:
            df = pd.read_csv(file, skiprows=range(i))
            return df
        except Exception:
            pass

The issue I ran into--when testing on a .csv structured exactly like the example above--was that the returned df had 1 column whose header was the last piece of metadata, first row of that column was the last actual header column, followed by all of that column's corresponding data.
The remaining actual headers and data were in a multi-index--no idea why.
FWIW I'm using Spyder.
Note that the test file I'm working with does have a comma in the client name, which made the first row of metadata inadvertently have two columns.


问:
bzlmod: dealing with external dependencies with no MODULE.bazel
I would like to use bzlmod as I am in the process of splitting a project into different modules and thought it would be a great way to solve the transitive dependencies.

However, not all project have yet a MODULE.bazel file (e.g. grpc), so the question is: is it possible to add an external dependency that doesn't have a MODULE.bazel to the module system so that everything works fine if I reuse the new module?


问:
Lwt error sending messages with capnproto
I am using capnproto to send messages between several nodes. Each node can both send and receive messages from all others. The relevant code looks like this:

main.ml:

```<code>let start_node id nodes =
    Lwt_main.run begin
        let listen_address = `TCP ("127.0.0.1", 9000 + id) in
        let config = Capnp_rpc_unix.Vat_config.create ~serve_tls:false ~secret_key listen_address in
        let service_id = Capnp_rpc_net.Restorer.Id.public "" in
        let restore = Capnp_rpc_net.Restorer.single service_id (Hs.local id nodes) in
        let* vat = Capnp_rpc_unix.serve config ~restore in
        let uri = Capnp_rpc_unix.Vat.sturdy_uri vat service_id in
        Fmt.pr "Server ID=%s running. Connect to URI %S.@." (Int.to_string id) (Uri.to_string uri);
        Lwt.wait () |> fst
    end
</code>```

hs.ml:

```<code>(*client*)
let open_conn id =
    let uri = Uri.of_string ("capnp://insecure@127.0.0.1:" ^ Int.to_string (id + 9000)) in
    let client_vat = Capnp_rpc_unix.client_only_vat () in
    Capnp_rpc_unix.Vat.import_exn client_vat uri

let open_conns nodes =
    let ids = List.init nodes Fun.id in
    List.map (fun x -> open_conn x) ids

let send msg service =
    let open Api.Client.Hs.SendMsg in
    let request, params = Capability.Request.create Params.init_pointer in
    let _ = Params.msg_set_reader params msg in
    let* _ = Capability.call_for_value_exn service method_id request in
    Lwt.return ()

let send_msg service msg =
    Sturdy_ref.with_cap_exn service (send msg)

(*server*)
let local id nodes =
    (*...*)
    let conns = open_conns nodes in
    let module Hs = Api.Service.Hs in
    Hs.local @@ object
        inherit Hs.service

        method send_msg_impl params release_param_caps =
            let open Hs.SendMsg in
            let msg = Params.msg_get params in
            release_param_caps ();
                        (* do stuff like sending messages *)
            Service.return_empty ()
    end
</code>```

After sending several messages the nodes crash with LWT errors:

```<code>hs: internal error, uncaught exception:
    Unix.Unix_error(Unix.EINVAL, "select", "")
    Raised by primitive operation at Lwt_engine.select#select in file "src/unix/lwt_engine.ml", line 405, characters 26-60
    Called from Lwt_engine.select_based#iter in file "src/unix/lwt_engine.ml", line 346, characters 8-39
    Called from Lwt_main.run.run_loop in file "src/unix/lwt_main.ml", line 41, characters 6-49
    Called from Lwt_main.run in file "src/unix/lwt_main.ml", line 118, characters 8-13
    Re-raised at Lwt_main.run in file "src/unix/lwt_main.ml", line 124, characters 4-13
    Called from Cmdliner_term.app.(fun) in file "cmdliner_term.ml", line 24, characters 19-24
    Called from Cmdliner_eval.run_parser in file "cmdliner_eval.ml", line 34, characters 37-44
</code>```
```<code>Fatal error: exception Lwt_switch.Off
Raised by primitive operation at Lwt_unix.read_bigarray.(fun) in file "src/unix/lwt_unix.cppo.ml", line 688, characters 8-59
Called from Lwt_unix.wrap_syscall.(fun) in file "src/unix/lwt_unix.cppo.ml", line 571, characters 17-28
</code>```
```<code>main.exe: [WARNING] Uncaught exception handling CapTP connection: Failure("recv: Unix.Unix_error(Unix.ECONNRESET, \"read\", \"\")") (dropping connection)
main.exe: [DEBUG] Error calling field(6110)(rc=1+1) -> #[] -> remote-promise(6109, rc=1) -> q0(Hs.sendMsg): Disconnected: Switch turned off
Fatal error: exception Failure("Hs.sendMsg: Disconnected: Switch turned off")
Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
Called from Lwt.Sequential_composition.bind.create_result_promise_and_callback_if_deferred.c in file "src/core/lwt.ml", line 1849, characters 23-26
</code>```

How can I fix this?

Body:
I am using capnproto to send messages between several nodes. Each node can both send and receive messages from all others. The relevant code looks like this:

main.ml:

let start_node id nodes =
    Lwt_main.run begin
        let listen_address = `TCP ("127.0.0.1", 9000 + id) in
        let config = Capnp_rpc_unix.Vat_config.create ~serve_tls:false ~secret_key listen_address in
        let service_id = Capnp_rpc_net.Restorer.Id.public "" in
        let restore = Capnp_rpc_net.Restorer.single service_id (Hs.local id nodes) in
        let* vat = Capnp_rpc_unix.serve config ~restore in
        let uri = Capnp_rpc_unix.Vat.sturdy_uri vat service_id in
        Fmt.pr "Server ID=%s running. Connect to URI %S.@." (Int.to_string id) (Uri.to_string uri);
        Lwt.wait () |> fst
    end

hs.ml:

(*client*)
let open_conn id =
    let uri = Uri.of_string ("capnp://insecure@127.0.0.1:" ^ Int.to_string (id + 9000)) in
    let client_vat = Capnp_rpc_unix.client_only_vat () in
    Capnp_rpc_unix.Vat.import_exn client_vat uri

let open_conns nodes =
    let ids = List.init nodes Fun.id in
    List.map (fun x -> open_conn x) ids

let send msg service =
    let open Api.Client.Hs.SendMsg in
    let request, params = Capability.Request.create Params.init_pointer in
    let _ = Params.msg_set_reader params msg in
    let* _ = Capability.call_for_value_exn service method_id request in
    Lwt.return ()

let send_msg service msg =
    Sturdy_ref.with_cap_exn service (send msg)

(*server*)
let local id nodes =
    (*...*)
    let conns = open_conns nodes in
    let module Hs = Api.Service.Hs in
    Hs.local @@ object
        inherit Hs.service

        method send_msg_impl params release_param_caps =
            let open Hs.SendMsg in
            let msg = Params.msg_get params in
            release_param_caps ();
                        (* do stuff like sending messages *)
            Service.return_empty ()
    end

After sending several messages the nodes crash with LWT errors:

hs: internal error, uncaught exception:
    Unix.Unix_error(Unix.EINVAL, "select", "")
    Raised by primitive operation at Lwt_engine.select#select in file "src/unix/lwt_engine.ml", line 405, characters 26-60
    Called from Lwt_engine.select_based#iter in file "src/unix/lwt_engine.ml", line 346, characters 8-39
    Called from Lwt_main.run.run_loop in file "src/unix/lwt_main.ml", line 41, characters 6-49
    Called from Lwt_main.run in file "src/unix/lwt_main.ml", line 118, characters 8-13
    Re-raised at Lwt_main.run in file "src/unix/lwt_main.ml", line 124, characters 4-13
    Called from Cmdliner_term.app.(fun) in file "cmdliner_term.ml", line 24, characters 19-24
    Called from Cmdliner_eval.run_parser in file "cmdliner_eval.ml", line 34, characters 37-44

Fatal error: exception Lwt_switch.Off
Raised by primitive operation at Lwt_unix.read_bigarray.(fun) in file "src/unix/lwt_unix.cppo.ml", line 688, characters 8-59
Called from Lwt_unix.wrap_syscall.(fun) in file "src/unix/lwt_unix.cppo.ml", line 571, characters 17-28

main.exe: [WARNING] Uncaught exception handling CapTP connection: Failure("recv: Unix.Unix_error(Unix.ECONNRESET, \"read\", \"\")") (dropping connection)
main.exe: [DEBUG] Error calling field(6110)(rc=1+1) -> #[] -> remote-promise(6109, rc=1) -> q0(Hs.sendMsg): Disconnected: Switch turned off
Fatal error: exception Failure("Hs.sendMsg: Disconnected: Switch turned off")
Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
Called from Lwt.Sequential_composition.bind.create_result_promise_and_callback_if_deferred.c in file "src/core/lwt.ml", line 1849, characters 23-26

How can I fix this?


问:
OpenSearch knn index similarity search not returning any hits
I am trying to set up a proof of concept showing how the OpenSearch knn index similarity search works with text I copied from Wikipedia. I am using Python and opensearchpy to send and retrieve data from the OpenSearch instance. I am not getting any errors so I think I am setting things up the correct way but when I try to query the index with a simple one word search term I get a successful response with no hits back. I am pretty new to OpenSearch in general so the problem may be super obvious and I am just missing it.

setting up index

```<code>index_name = 'knn-test'
index_body = {
  "settings": {
    "index": {
      "knn": "true",
      "knn.algo_param.ef_search": 100
    }
  },
  "mappings": {
    "properties": {
        "encoded_text": {
          "type": "knn_vector",
          "dimension": 768,
          "method": {
            "name": "hnsw",
            "space_type": "innerproduct",
            "engine": "faiss",
            "parameters": {
              "ef_construction": 512,
              "m": 16
            }
          }
        }
    }
  }
}

response = opensearch_py_connection.indices.create(index_name, body=index_body)
print('\nCreating index:')
print(response)
</code>```

Encoding the text and loading it into the index

```<code>word_embedding_model = sentence_models.Transformer("sentence-transformers/paraphrase-distilroberta-base-v1", max_seq_length=256)
pooling_model = sentence_models.Pooling(word_embedding_model.get_word_embedding_dimension())
model = SentenceTransformer(modules=[word_embedding_model, pooling_model])

id = 1
for text in text_list:

    encoded_text = model.encode(text, convert_to_tensor=False)

    document = {
        'encoded-text': encoded_text
    }

    response = opensearch_py_connection.index(
        index = "knn-test",
        body = document,
        id = id,
        refresh = True
    )

    print('\nAdding document:')
    print(response)
    id = id+1
</code>```

Encode and ask basic query

```<code>query = "ship"

encoded_query = model.encode(query, convert_to_tensor=False)

query_body = {
  "size": 2,
  "query": {
    "knn": {
      "encoded_text": {
        "vector": encoded_query,
        "k": 2
      }
    }
  }
}

response = opensearch_py_connection.search(
    body = query_body,
    index = "knn-test"
)
print('\nSearch results:')
print(response)
</code>```

print out of the query is as follows:

```<code>Search results:
{'took': 7, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 0, 'relation': 'eq'}, 'max_score': None, 'hits': []}}
</code>```

My guess is that I am formatting the body of one of the opensearchpy calls the wrong way but I have not been able to find out why exactly. Any help is appreciated.

Body:
I am trying to set up a proof of concept showing how the OpenSearch knn index similarity search works with text I copied from Wikipedia. I am using Python and opensearchpy to send and retrieve data from the OpenSearch instance. I am not getting any errors so I think I am setting things up the correct way but when I try to query the index with a simple one word search term I get a successful response with no hits back. I am pretty new to OpenSearch in general so the problem may be super obvious and I am just missing it.

setting up index

index_name = 'knn-test'
index_body = {
  "settings": {
    "index": {
      "knn": "true",
      "knn.algo_param.ef_search": 100
    }
  },
  "mappings": {
    "properties": {
        "encoded_text": {
          "type": "knn_vector",
          "dimension": 768,
          "method": {
            "name": "hnsw",
            "space_type": "innerproduct",
            "engine": "faiss",
            "parameters": {
              "ef_construction": 512,
              "m": 16
            }
          }
        }
    }
  }
}

response = opensearch_py_connection.indices.create(index_name, body=index_body)
print('\nCreating index:')
print(response)

Encoding the text and loading it into the index

word_embedding_model = sentence_models.Transformer("sentence-transformers/paraphrase-distilroberta-base-v1", max_seq_length=256)
pooling_model = sentence_models.Pooling(word_embedding_model.get_word_embedding_dimension())
model = SentenceTransformer(modules=[word_embedding_model, pooling_model])

id = 1
for text in text_list:

    encoded_text = model.encode(text, convert_to_tensor=False)

    document = {
        'encoded-text': encoded_text
    }

    response = opensearch_py_connection.index(
        index = "knn-test",
        body = document,
        id = id,
        refresh = True
    )

    print('\nAdding document:')
    print(response)
    id = id+1

Encode and ask basic query

query = "ship"

encoded_query = model.encode(query, convert_to_tensor=False)

query_body = {
  "size": 2,
  "query": {
    "knn": {
      "encoded_text": {
        "vector": encoded_query,
        "k": 2
      }
    }
  }
}

response = opensearch_py_connection.search(
    body = query_body,
    index = "knn-test"
)
print('\nSearch results:')
print(response)

print out of the query is as follows:

Search results:
{'took': 7, 'timed_out': False, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}, 'hits': {'total': {'value': 0, 'relation': 'eq'}, 'max_score': None, 'hits': []}}

My guess is that I am formatting the body of one of the opensearchpy calls the wrong way but I have not been able to find out why exactly. Any help is appreciated.


问:
How To Map Nodejs Api in reactjs data fields..?
I have created an Nodejs API and a React App in which i have datafields.. how do i map them alongside my node api's .??

I have tried using the useState feature but didn't understand it.


问:
Is this security issue in appimage-builder? Can I address this by changing default configuration?

Background

I have some mutiplatform C++ application. On Linux installation package is created using appimge-builder.

$ appimagetool --version
appimagetool, continuous build (commit 76bf860), build <local dev build> built on 2022-02-13 18:52:16 UTC
$ uname -a
Linux d1bc106a5f0f 5.4.0-125-generic #141-Ubuntu SMP Wed Aug 10 13:42:03 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
```
<p>Now in my continuous integration builds (Jenkins) are failing. In logs I see</p>
```[2023-01-11T17:36:58.520Z] INFO:main:Running main script
[2023-01-11T17:36:58.520Z] INFO:main:Running apt deploy
[2023-01-11T17:36:58.520Z] INFO:apt:Download key file: http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3b4fe6acc0b21f32
[2023-01-11T17:36:58.520Z] Traceback (most recent call last):
[2023-01-11T17:36:58.520Z]   File "/home/jenkins/.local/bin/appimage-builder", line 8, in <module>
[2023-01-11T17:36:58.520Z]     sys.exit(__main__())
[2023-01-11T17:36:58.520Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/__main__.py", line 58, in __main__
[2023-01-11T17:36:58.520Z]     invoker.execute(commands)
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/invoker.py", line 41, in execute
[2023-01-11T17:36:58.521Z]     command()
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/commands/apt_deploy.py", line 42, in __call__
[2023-01-11T17:36:58.521Z]     apt_venv = self._setup_apt_venv()
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/commands/apt_deploy.py", line 60, in _setup_apt_venv
[2023-01-11T17:36:58.521Z]     apt_venv = Venv(
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/modules/deploy/apt/venv.py", line 48, in __init__
[2023-01-11T17:36:58.521Z]     self._write_keys(keys)
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/modules/deploy/apt/venv.py", line 121, in _write_keys
[2023-01-11T17:36:58.521Z]     request.urlretrieve(key_url, key_path)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 247, in urlretrieve
[2023-01-11T17:36:58.521Z]     with contextlib.closing(urlopen(url, data)) as fp:
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 222, in urlopen
[2023-01-11T17:36:58.521Z]     return opener.open(url, data, timeout)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 531, in open
[2023-01-11T17:36:58.521Z]     response = meth(req, response)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 640, in http_response
[2023-01-11T17:36:58.521Z]     response = self.parent.error(
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 569, in error
[2023-01-11T17:36:58.521Z]     return self._call_chain(*args)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 502, in _call_chain
[2023-01-11T17:36:58.521Z]     result = func(*args)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 649, in http_error_default
[2023-01-11T17:36:58.521Z]     raise HTTPError(req.full_url, code, msg, hdrs, fp)
[2023-01-11T17:36:58.521Z] urllib.error.HTTPError: HTTP Error 503: Service Unavailable
```

Problem

This logs show clearly some network issue, for some reason server responds with 503: Service Unavailable. I do not know why this error is reported only on Jenkins and I can't reproduce it only local machine. If someone has clues this is bonus question.

A real interesting issue is details of this logs: Download key file: http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3b4fe6acc0b21f32.

Note http protocol not https

Content of this url is "PGP PUBLIC KEY"!

This look like a security hole. Dynamically fetching public key using insecure channel.

Questions

Am I right to suspect security hole here? (I was not able to quickly inspect consequences for appimage-builder). Is this appimage-builder problem or only version distributed for Ubuntu has it?

can I change system configuration, so I will manually upload this public key somewhere (once) and configure appimage-builder to use this key and disable downloading of this key.

bonus question: is there other way to address this build failure?

Body:
Background

I have some mutiplatform C++ application. On Linux installation package is created using appimge-builder.

$ appimagetool --version
appimagetool, continuous build (commit 76bf860), build <local dev build> built on 2022-02-13 18:52:16 UTC
$ uname -a
Linux d1bc106a5f0f 5.4.0-125-generic #141-Ubuntu SMP Wed Aug 10 13:42:03 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Now in my continuous integration builds (Jenkins) are failing. In logs I see

[2023-01-11T17:36:58.520Z] INFO:main:Running main script
[2023-01-11T17:36:58.520Z] INFO:main:Running apt deploy
[2023-01-11T17:36:58.520Z] INFO:apt:Download key file: http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3b4fe6acc0b21f32
[2023-01-11T17:36:58.520Z] Traceback (most recent call last):
[2023-01-11T17:36:58.520Z]   File "/home/jenkins/.local/bin/appimage-builder", line 8, in <module>
[2023-01-11T17:36:58.520Z]     sys.exit(__main__())
[2023-01-11T17:36:58.520Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/__main__.py", line 58, in __main__
[2023-01-11T17:36:58.520Z]     invoker.execute(commands)
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/invoker.py", line 41, in execute
[2023-01-11T17:36:58.521Z]     command()
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/commands/apt_deploy.py", line 42, in __call__
[2023-01-11T17:36:58.521Z]     apt_venv = self._setup_apt_venv()
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/commands/apt_deploy.py", line 60, in _setup_apt_venv
[2023-01-11T17:36:58.521Z]     apt_venv = Venv(
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/modules/deploy/apt/venv.py", line 48, in __init__
[2023-01-11T17:36:58.521Z]     self._write_keys(keys)
[2023-01-11T17:36:58.521Z]   File "/home/jenkins/.local/lib/python3.8/site-packages/appimagebuilder/modules/deploy/apt/venv.py", line 121, in _write_keys
[2023-01-11T17:36:58.521Z]     request.urlretrieve(key_url, key_path)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 247, in urlretrieve
[2023-01-11T17:36:58.521Z]     with contextlib.closing(urlopen(url, data)) as fp:
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 222, in urlopen
[2023-01-11T17:36:58.521Z]     return opener.open(url, data, timeout)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 531, in open
[2023-01-11T17:36:58.521Z]     response = meth(req, response)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 640, in http_response
[2023-01-11T17:36:58.521Z]     response = self.parent.error(
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 569, in error
[2023-01-11T17:36:58.521Z]     return self._call_chain(*args)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 502, in _call_chain
[2023-01-11T17:36:58.521Z]     result = func(*args)
[2023-01-11T17:36:58.521Z]   File "/usr/lib/python3.8/urllib/request.py", line 649, in http_error_default
[2023-01-11T17:36:58.521Z]     raise HTTPError(req.full_url, code, msg, hdrs, fp)
[2023-01-11T17:36:58.521Z] urllib.error.HTTPError: HTTP Error 503: Service Unavailable

Problem

This logs show clearly some network issue, for some reason server responds with 503: Service Unavailable. I do not know why this error is reported only on Jenkins and I can't reproduce it only local machine. If someone has clues this is bonus question.

A real interesting issue is details of this logs: Download key file: http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3b4fe6acc0b21f32.

Note http protocol not https

Content of this url is "PGP PUBLIC KEY"!

This look like a security hole. Dynamically fetching public key using insecure channel.

Questions

Am I right to suspect security hole here? (I was not able to quickly inspect consequences for appimage-builder). Is this appimage-builder problem or only version distributed for Ubuntu has it?

can I change system configuration, so I will manually upload this public key somewhere (once) and configure appimage-builder to use this key and disable downloading of this key.

bonus question: is there other way to address this build failure?


问:
Ng2-charts in Angular 13 : Can't bind to 'data' since it isn't a known property of 'canvas'
I'm trying to add ng2-charts to angular application, but it gives me weird errors.

I installed ng2-charts version 3.0.9 with:
 npm i ng2-charts@3.0.9

npm i chart.js

Then added NgChartsModule to app.module.ts.

Here is my typescript file:

```<code>salesData: ChartData<'line'> = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [
      { label: 'Mobiles', data: [1000, 1200, 1050, 2000, 500], tension: 0.5 },
      { label: 'Laptop', data: [200, 100, 400, 50, 90], tension: 0.5 },
      { label: 'AC', data: [500, 400, 350, 450, 650], tension: 0.5 },
      { label: 'Headset', data: [1200, 1500, 1020, 1600, 900], tension: 0.5 },
    ],
  };

  chartOptions: ChartOptions = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Monthly Sales Data',
      },
    },
  };
</code>```

Here is HTML:

```<code><canvas
          baseChart
          [data]="salesData"
          [type]="'bar'"
          [options]="chartOptions"
        >
        </canvas>
</code>```

For each property I get error:

```<code>
Can't bind to 'data' since it isn't a known property of 'canvas'.
</code>```

What am I doing wrong ?

Thank you so much.

Installing different versions of packages but it didn't work.

Body:
I'm trying to add ng2-charts to angular application, but it gives me weird errors.

I installed ng2-charts version 3.0.9 with:
 npm i ng2-charts@3.0.9

npm i chart.js

Then added NgChartsModule to app.module.ts.

Here is my typescript file:

salesData: ChartData<'line'> = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    datasets: [
      { label: 'Mobiles', data: [1000, 1200, 1050, 2000, 500], tension: 0.5 },
      { label: 'Laptop', data: [200, 100, 400, 50, 90], tension: 0.5 },
      { label: 'AC', data: [500, 400, 350, 450, 650], tension: 0.5 },
      { label: 'Headset', data: [1200, 1500, 1020, 1600, 900], tension: 0.5 },
    ],
  };

  chartOptions: ChartOptions = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Monthly Sales Data',
      },
    },
  };

Here is HTML:

<canvas
          baseChart
          [data]="salesData"
          [type]="'bar'"
          [options]="chartOptions"
        >
        </canvas>

For each property I get error:

Can't bind to 'data' since it isn't a known property of 'canvas'.

What am I doing wrong ?

Thank you so much.

Installing different versions of packages but it didn't work.


问:
Get 2 meta values from key column (Single table)
How can I select the Display_Name and Play_Time on MySQL query?

This is my current query but nothing displays:

```<code>SELECT * FROM `myTable` WHERE submission_id = '47' AND `key` = 'Display_Name' AND `key` = 'Play_Time'
</code>```

display the value of display_name and play_time by calling those red highlighted keys on a screenshot.

Body:
How can I select the Display_Name and Play_Time on MySQL query?

This is my current query but nothing displays:

SELECT * FROM `myTable` WHERE submission_id = '47' AND `key` = 'Display_Name' AND `key` = 'Play_Time'

display the value of display_name and play_time by calling those red highlighted keys on a screenshot.


问:
Where can i find a documentation about the xml used in intellij .iml files?
I want to learn about the xml used in Intellijs build system .iml file.
But I am too stupid to google.

F.E. I want to know how to use the  Tag.
Can somebody show me material about the xml elements used in the .iml file?

Thanks in advance.

I looked up here, but it did not help.
https://www.jetbrains.com/help/idea/working-with-xml.html#import-xml-namespace


问:
Calling different service Implementations from controller based on payload
I have to write a microservice which is responsible for making data transfer across cloud .i.e S3 to S3, S3 to Google cloud storage. Etc I was thinking to have separate controller for each of the implementation. Is it good practice to do that or shall I create a single controller which can call to different service implementations based on the payload request</p>


问:
This file handling program to add, modify, delete and display data is not working as it should
There is no error raised but when I use the functions to add or modify data, the records remains unchanged. I've edited the file path for privacy reasons.

```<code>import pickle
def addfrnd():
    name = input("Enter a name: ")
    phone = int(input("Enter phone number: "))
    with open(r"practical6\phonebook.dat","ab") as myfile:
        data = (name, phone)
        pickle.dump(data, myfile)
def modifyfrnd():
    status = True
    with open(r"practice programs\practical6\phonebook.dat","rb") as myfile:
        data = pickle.load(myfile)
    name = input("Enter the name whose number is to be modified: ")
    phone = int(input("Enter new no.: "))
    print(data)
    for rec in data:
        if rec[0] == name:
            data.remove(rec)
            data.append((name,phone))
            with open(r"practice programs\practical6\phonebook.dat","ab") as myfile:
                pickle.dump(data,myfile)
            break
        else:
            status = False
            return status
def deletefrnd():
    status = True
    name = input("Enter name: ")
    with open(r"practice programs\practical6\phonebook.dat","rb") as myfile:
        data = pickle.load(myfile)
    for rec in data:
        if rec[0] == name:
            data.remove(rec)
        with open(r"practice programs\practical6\phonebook.dat","wb") as myfile:
            pickle.dump(data,myfile)
            break
    else:
        status = False
        return status

def display():
    with open(r"practice programs\practical6\phonebook.dat", "rb") as myfile:
        data = pickle.load(myfile)
        for i in data:
            print(i)

while True:
    print("-----PHONEBOOK-----")
    print("1. add contact")
    print("2. modify")
    print("3. delete")
    print("4. display")
    print("5. exit")
    ch = int(input("Enter your choice (1-5): "))
    if ch==1:
        addfrnd()
    elif ch==2:
        modifyfrnd()
    elif ch==3:
        deletefrnd()
    elif ch==4:
        display()
    elif ch==5:
        break
    else:
        print("Wrong Input")

</code>```

When I select to add contact, the record should get added to the data present in the file. Or when I modify, the data should get modified. However it is not the case when tried.

Body:
There is no error raised but when I use the functions to add or modify data, the records remains unchanged. I've edited the file path for privacy reasons.

import pickle
def addfrnd():
    name = input("Enter a name: ")
    phone = int(input("Enter phone number: "))
    with open(r"practical6\phonebook.dat","ab") as myfile:
        data = (name, phone)
        pickle.dump(data, myfile)
def modifyfrnd():
    status = True
    with open(r"practice programs\practical6\phonebook.dat","rb") as myfile:
        data = pickle.load(myfile)
    name = input("Enter the name whose number is to be modified: ")
    phone = int(input("Enter new no.: "))
    print(data)
    for rec in data:
        if rec[0] == name:
            data.remove(rec)
            data.append((name,phone))
            with open(r"practice programs\practical6\phonebook.dat","ab") as myfile:
                pickle.dump(data,myfile)
            break
        else:
            status = False
            return status
def deletefrnd():
    status = True
    name = input("Enter name: ")
    with open(r"practice programs\practical6\phonebook.dat","rb") as myfile:
        data = pickle.load(myfile)
    for rec in data:
        if rec[0] == name:
            data.remove(rec)
        with open(r"practice programs\practical6\phonebook.dat","wb") as myfile:
            pickle.dump(data,myfile)
            break
    else:
        status = False
        return status

def display():
    with open(r"practice programs\practical6\phonebook.dat", "rb") as myfile:
        data = pickle.load(myfile)
        for i in data:
            print(i)

while True:
    print("-----PHONEBOOK-----")
    print("1. add contact")
    print("2. modify")
    print("3. delete")
    print("4. display")
    print("5. exit")
    ch = int(input("Enter your choice (1-5): "))
    if ch==1:
        addfrnd()
    elif ch==2:
        modifyfrnd()
    elif ch==3:
        deletefrnd()
    elif ch==4:
        display()
    elif ch==5:
        break
    else:
        print("Wrong Input")

When I select to add contact, the record should get added to the data present in the file. Or when I modify, the data should get modified. However it is not the case when tried.


问:
Http API gateway error "too much redirect" and ALB health check move from 200 to 302 after deploying code
i have backend server in elastic beanstalk with rds in private subnet, so to access backend i have created http api gateway but problem is when i click on http api gateway endpoint i got error too many redirect.i am facing this problem for last 2 week, applied many solution but no progress,
onething more i oberseved ,when i deployed code on EB then Load balancer health ceck move fromm 200 to 302, and i got  error "health check failed with these code 302",but when i set 302 as health check status code instance become health,but still same error in api  gateway

curl localhost

also tried to redirect http to https from ALB
and also tried without https 443

```<code>Connected to localhost (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> Host: localhost
> User-Agent: curl/7.79.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Server: nginx/1.22.0
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Cache-Control: no-cache, private
< Date: Thu, 12 Jan 2023 11:48:54 GMT
< Location: https://localhost
<
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='https://localhost'" />

        <title>Redirecting to https://localhost</title>
    </head>
    <body>
        Redirecting to <a href="https://localhost">https://localhost</a>.
    </body>
* Connection #0 to host localhost left intact
</code>```

Body:
i have backend server in elastic beanstalk with rds in private subnet, so to access backend i have created http api gateway but problem is when i click on http api gateway endpoint i got error too many redirect.i am facing this problem for last 2 week, applied many solution but no progress,
onething more i oberseved ,when i deployed code on EB then Load balancer health ceck move fromm 200 to 302, and i got  error "health check failed with these code 302",but when i set 302 as health check status code instance become health,but still same error in api  gateway

curl localhost

also tried to redirect http to https from ALB
and also tried without https 443

Connected to localhost (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> Host: localhost
> User-Agent: curl/7.79.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Server: nginx/1.22.0
< Content-Type: text/html; charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Cache-Control: no-cache, private
< Date: Thu, 12 Jan 2023 11:48:54 GMT
< Location: https://localhost
<
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="0;url='https://localhost'" />

        <title>Redirecting to https://localhost</title>

        Redirecting to https://localhost.

* Connection #0 to host localhost left intact


问:
SwiftUI: Display live map coordinates while moving
I am making app where I need to get live coordinates of user and upload the newest coordinates every x minutes. I've been struggling with it for last few hours, and tried almost everything and checked all threads available and still don't have the answer.
Here is my code:

```<code>class LocationService: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var location: CLLocation?

    @Published var locationManager = CLLocationManager()

    init(searchCompleter: MKLocalSearchCompleter = MKLocalSearchCompleter()) {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = CLLocationDistanceMax
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
}

extension LocationService {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }
        self.location = location
        print(location.coordinate)
    }
}

extension MKCoordinateRegion {
    static func goldenGateRegion() -> MKCoordinateRegion {
        MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 37.819527098978355, longitude:  -122.47854602016669), latitudinalMeters: 10, longitudinalMeters: 10)
    }
    func getBinding() -> Binding<MKCoordinateRegion>? {
        return Binding<MKCoordinateRegion>.constant(self)
    }
}
</code>```

I am calling this function on main view:

```<code>.onChange(of: locationService.location) { newValue in
                print(newValue?.coordinate ?? "error")
            }
</code>```

And I am getting same coordinates for the whole time, (I picked driveway location option in simulator).

Body:
I am making app where I need to get live coordinates of user and upload the newest coordinates every x minutes. I've been struggling with it for last few hours, and tried almost everything and checked all threads available and still don't have the answer.
Here is my code:

class LocationService: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var location: CLLocation?

    @Published var locationManager = CLLocationManager()

    init(searchCompleter: MKLocalSearchCompleter = MKLocalSearchCompleter()) {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = CLLocationDistanceMax
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }
}

extension LocationService {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }
        self.location = location
        print(location.coordinate)
    }
}

extension MKCoordinateRegion {
    static func goldenGateRegion() -> MKCoordinateRegion {
        MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 37.819527098978355, longitude:  -122.47854602016669), latitudinalMeters: 10, longitudinalMeters: 10)
    }
    func getBinding() -> Binding<MKCoordinateRegion>? {
        return Binding<MKCoordinateRegion>.constant(self)
    }
}

I am calling this function on main view:

.onChange(of: locationService.location) { newValue in
                print(newValue?.coordinate ?? "error")
            }

And I am getting same coordinates for the whole time, (I picked driveway location option in simulator).


问:
Are Autoencoder lighter than MLPs?
I want to know if Autoencoders are computationally lighter than other neural networks such as MLP with the same number of neurons. I have read in some papers that Autoencoders train the network faster, and I could check it in python, the training part is faster than a MLP. However, all these papers mention it briefly. I would like to know if there are some papers that explain it in more detail, because I could not find them.

Thank you in advance.

Title: Are Autoencoder lighter than MLPs?


问:
NuxtJS 2 Routing and Template / Components challenge
Hei guys,

I'm having some trouble with my current project. I wish to achieve the following project that must answer this needs :

Have a config JSON with information about the project/projects, static pages, and other general information about the client

Have a main landing page. This page is optional. If this is not set/wanted and if in the config there is only 1 project, then on the base domain the page should be the project

Each static page is built using sections that are found in the config file

Some examples:

Case 1:
In the config, we have a client with 2 projects and no landing page. The routing should be:

domain.ex/project1 -> project template with dynamic sections

domain.ex/project2 -> project template with dynamic sections

Case 2:
We have a client with 1 project and no landing page in the config. The routing should be:

domain.ex -> project template with dynamic sections

Case 3:
We have a client with 1 project and a landing page in the config. The routing should be:

domain.ex -> static page with dynamic sections

domain.ex/project1 -> project template with dynamic sections

What is the best way of doing this in NujtJS? I was thinking either by using a router middleware and changing the page base component based on the config, or by creating manual routes in the nuxt config and redirecting in the route middleware from one to another (but losing Case 2)
Also, I would like to have a decent code splitting


问:
SQL query for sales pipeline
I need to build a sales pipeline with one query in SQL (Big Query).
The table has columns:
-timestamp (event time)
-id (user id)
-event

Each event is a number from 1 to 8. And I need to calculate how many unique users there were at each step.

Each step is counted only if the previous steps have been completed.

It is not necessary to go through them straight one after the other, but the main thing is that before each step, n-1 step was taken earlier.

If you sort the table by 'timestamp', you often get such sequences for one 'id' at one day:
4, 4, 1, 1, 3, 6, 5, 5, 6, 5, 6, 7, 8, 1, 2, 5, 3, 4.
In this example, the longest sequence is 1, 2, 3, 4.

The sequence is counted in one day!

I failed to solve the problem through the max/min/lag/lead window functions. I even did a 'case' with a sequential comparison with lag+n values.

I wasted 2 days for this task(

Title: SQL query for sales pipeline


问:
GTKSourceView Syntax Highlighting different colours for layers of brackets (like VSCode)
VSCode

In VSCode (and probably other editors too) when you have brackets within brackets, the colour will change, this doesn't happen in GTK editors like Mousepad and Gedit. I know how to add syntax rules to GTKSourceView programs by editing the *language*.lang files, and I have got it working like this:

What I have so far

I have the text different colours depending if it is in brackets, however, it's highlighting all the text, instead of just the brackets. How can you get it to highlight only the brackets, but still highlight other brackets within those differently?

Code I have to do what the image shows:

```<code>    <context id="testing1" end-at-line-end="true" style-ref="testing1">
          <start>\(</start>
          <end>\)</end>
          <include>
            <context id="testing2" style-ref="testing2">
              <start>\(</start>
              <end>\)</end>
            </context>
          </include>
        </context>

</code>```

Body:
VSCode

In VSCode (and probably other editors too) when you have brackets within brackets, the colour will change, this doesn't happen in GTK editors like Mousepad and Gedit. I know how to add syntax rules to GTKSourceView programs by editing the *language*.lang files, and I have got it working like this:

What I have so far

I have the text different colours depending if it is in brackets, however, it's highlighting all the text, instead of just the brackets. How can you get it to highlight only the brackets, but still highlight other brackets within those differently?

Code I have to do what the image shows:

    <context id="testing1" end-at-line-end="true" style-ref="testing1">
          <start>\(</start>
          <end>\)</end>
          <include>
            <context id="testing2" style-ref="testing2">
              <start>\(</start>
              <end>\)</end>
            </context>
          </include>
        </context>


问:
NEXTAUTH_URL not being recognized by NextAuth
I am having an issue with NextAuth in production. Every time I try to sign-in with Discord, after clicking the login button, it redirects me to localhost:3000/api/auth/signin/discord, while it should use the production URL instead.
I have NEXTAUTH_URL defined in the .env file, and I've attempted to pass the env value in the next.config.js file as well, but no luck.
Here is my current NextAuth handler;

import { NextAuthOptions } from "next-auth"
import NextAuth from "next-auth/next"
import DiscordProvider from "next-auth/providers/discord"
import { NextApiRequest, NextApiResponse } from "next/types"

function validateUser(userID: string | undefined) {
    const allowedUsers = (process.env.ALLOWED_AUTH_IDS as string).split(",")
    return userID && allowedUsers.includes(userID)
}

export const authOptions: NextAuthOptions = {
    providers: [
        DiscordProvider({
            clientId: "<id>",
            clientSecret: "<secret>",
        }),
    ],

    jwt: {
        secret: process.env.SECRET_KEY,
        maxAge: 30 * 24 * 60 * 60,

    },

    session: {
        strategy: "jwt"
    },

    secret: process.env.SECRET_KEY,

    callbacks: {
        async jwt(props) {

            return props.token
        },

        async session(props) {
            if(props.token && props.session) {
                props.session.user.authorized = validateUser(props.token.sub) as boolean
            }

            return props.session
        },

        async signIn(props) {
            if(props.user) {
                if(validateUser(props.user.id)) return true
            }

            return "/error/auth-not-allowed"
        },
    },
}

export default async function Auth(req: NextApiRequest, res: NextApiResponse) {

    return await NextAuth(req, res, authOptions)
}
```

I have also attempted to use a custom redirect callback, but there was no luck there either. The baseUrl and url props of it were still http://localhost:3000 though.

So, to be clear, my goal is to make NextAuth use the production url instead of localhost. I deployed the application in my servers, and on Vercel, so NextAuth cannot fetch the URL automatically.

Body:
I am having an issue with NextAuth in production. Every time I try to sign-in with Discord, after clicking the login button, it redirects me to localhost:3000/api/auth/signin/discord, while it should use the production URL instead.
I have NEXTAUTH_URL defined in the .env file, and I've attempted to pass the env value in the next.config.js file as well, but no luck.
Here is my current NextAuth handler;

import { NextAuthOptions } from "next-auth"
import NextAuth from "next-auth/next"
import DiscordProvider from "next-auth/providers/discord"
import { NextApiRequest, NextApiResponse } from "next/types"

function validateUser(userID: string | undefined) {
    const allowedUsers = (process.env.ALLOWED_AUTH_IDS as string).split(",")
    return userID && allowedUsers.includes(userID)
}

export const authOptions: NextAuthOptions = {
    providers: [
        DiscordProvider({
            clientId: "<id>",
            clientSecret: "<secret>",
        }),
    ],

    jwt: {
        secret: process.env.SECRET_KEY,
        maxAge: 30 * 24 * 60 * 60,

    },

    session: {
        strategy: "jwt"
    },

    secret: process.env.SECRET_KEY,

    callbacks: {
        async jwt(props) {

            return props.token
        },

        async session(props) {
            if(props.token && props.session) {
                props.session.user.authorized = validateUser(props.token.sub) as boolean
            }

            return props.session
        },

        async signIn(props) {
            if(props.user) {
                if(validateUser(props.user.id)) return true
            }

            return "/error/auth-not-allowed"
        },
    },
}

export default async function Auth(req: NextApiRequest, res: NextApiResponse) {

    return await NextAuth(req, res, authOptions)
}

I have also attempted to use a custom redirect callback, but there was no luck there either. The baseUrl and url props of it were still http://localhost:3000 though.

So, to be clear, my goal is to make NextAuth use the production url instead of localhost. I deployed the application in my servers, and on Vercel, so NextAuth cannot fetch the URL automatically.


问:
VS 2022 Error List lines don't show the code in error when clicked
I am using the Visual Studio 2022 V17.4.4 IDE.  In previous versions the error list, after a build, contained links to the code in error.  In other words, in the error list, you could double click the error and VS 2022 would open the code file, if not already open, and position the cursor on the line in error.  But that seems to have stopped working.  Double clicking the error no longer opens the appropriate file and does not position the cursor on the line in error.  Anyone know why?</p>


问:
Using a default parameter that is a subtype of the generic type passed in?
I have this kind of code:

type MapOf<V> = { [key: string]: V };

type ThingWithConfigCallback<ThingType, ConfigType extends MapOf<any>> = (
  Thing: ThingType,
  config?: ConfigType,
) => void;

type ThingWithConfig<ThingType, ConfigType extends MapOf<any>> = {
  Thing: ThingType,
  config?: ConfigType,
};

const createThingsWithConfig <T, C>() => {
  const registerThingsWithConfig: ThingWithConfigCallback<T, C> = (Thing: T, config: C) => {
  // do stuff to register things
  }
  // other functions
  return {
    registerThingsWithConfig,
    // other functions
  }
};
```

However I want to provide a default parameter for config for registerThingsWithConfig, instead of leaving it undefined. However I can't create a default that's of the correct type/subtype.

If I do (Thing: T, config: C = {}) => { I get Type '{}' is not assignable to C and how Type '{}' is assignable to the constraint of 'C', but 'C' could be instantiated with a different subtype of constraint 'MapOf<any>'

If I declare const defaultConfig: MapOf<any> = {}; and use that as the default param in registerThingsWithConfig I get the same error but with Type MapOf<any> is assignable to the constraint of 'C' ...

But I do not follow how/why that is the case, even after reading How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"? .

Body:
I have this kind of code:

type MapOf<V> = { [key: string]: V };

type ThingWithConfigCallback<ThingType, ConfigType extends MapOf<any>> = (
  Thing: ThingType,
  config?: ConfigType,
) => void;

type ThingWithConfig<ThingType, ConfigType extends MapOf<any>> = {
  Thing: ThingType,
  config?: ConfigType,
};

const createThingsWithConfig <T, C>() => {
  const registerThingsWithConfig: ThingWithConfigCallback<T, C> = (Thing: T, config: C) => {
  // do stuff to register things
  }
  // other functions
  return {
    registerThingsWithConfig,
    // other functions
  }
};

However I want to provide a default parameter for config for registerThingsWithConfig, instead of leaving it undefined. However I can't create a default that's of the correct type/subtype.

If I do (Thing: T, config: C = {}) => { I get Type '{}' is not assignable to C and how Type '{}' is assignable to the constraint of 'C', but 'C' could be instantiated with a different subtype of constraint 'MapOf<any>'

If I declare const defaultConfig: MapOf<any> = {}; and use that as the default param in registerThingsWithConfig I get the same error but with Type MapOf<any> is assignable to the constraint of 'C' ...

But I do not follow how/why that is the case, even after reading How to fix TS2322: "could be instantiated with a different subtype of constraint 'object'"? .


问:
CSS file gives 200 code in network tab but changes don't display in browser
Probably a dumb question. I'm working on an HTML/CSS project and when I try to link to the CSS file with a relative path, the network tab in developer tools gives me a 200 code meaning that it's finding the file. However, the changes don't display properly.

Here's an overview of my general code structure:

```<code>src
|
-index.html
|
-style.css
</code>```

And here are my exact statements:

```<code><link href="./style.css" rel="stylesheet" type="text/css">
</code>```

And inside of style.css:

```<code>p {
  background-color: red;
}
</code>```

I've tried putting the CSS code inside of a  tag in index.html and the changes display fine in the browser. What could be the reason that the CSS file is found but the code contained inside of it isn't being applied?

Body:
Probably a dumb question. I'm working on an HTML/CSS project and when I try to link to the CSS file with a relative path, the network tab in developer tools gives me a 200 code meaning that it's finding the file. However, the changes don't display properly.

Here's an overview of my general code structure:

src
|
-index.html
|
-style.css

And here are my exact statements:

<link href="./style.css" rel="stylesheet" type="text/css">

And inside of style.css:

p {
  background-color: red;
}

I've tried putting the CSS code inside of a  tag in index.html and the changes display fine in the browser. What could be the reason that the CSS file is found but the code contained inside of it isn't being applied?