问:
Emulator Unit Test Fails Saying "Unable to establish connection on channel"
I use get_it for simple dependency injection. I have a function that I made sure is called when the app initializes as below:

void initDI() {
  // ... the other providers and repositories ...

  //--------- //
  // Firebase //
  //--------- //
  // i reference these instances everywhere when i wanna access them
  // such as providers, repositories, etc.
  GetIt.I.registerLazySingleton<FirebaseAuth>(() => FirebaseAuth.instance);
  GetIt.I.registerLazySingleton<FirebaseFirestore>(
    () => FirebaseFirestore.instance,
  );
  GetIt.I.registerLazySingleton<FirebaseFunctions>(
    () => FirebaseFunctions.instance,
  );
}
```
<p>In my <code>test</code> directory, I have a file named <code>initializers.dart</code>, which has setup functions for tests for convenience. One that concerns us is as follows:</p>
<pre class="lang-dart prettyprint-override"><code>// test/initializers.dart

Future<void> initFirebaseEmulatorUse() async {
  // ensure widget bindings get initialized because firebase requires this for some reason
  WidgetsFlutterBinding.ensureInitialized();
  // initialize firebase app
  await Firebase.initializeApp();
  // use functions emulator because there is no mock or fake package for functions, which is reasonable
  FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);

  // unregister default references
  GetIt.I.unregister<FirebaseAuth>();
  GetIt.I.unregister<FirebaseFirestore>();

  // register with mocks and fakes
  GetIt.I.registerLazySingleton<FirebaseAuth>(() => MockFirebaseAuth());
  GetIt.I.registerLazySingleton<FirebaseFirestore>(
    () => FakeFirebaseFirestore(),
  );
}
</code>```

And, an example test is as follows:

// import initializers, we'll need them
import '../initializers.dart';

void main() {
  // use in setUpAll, once and for all
  late FirebaseFirestore firebaseFirestore;

  setUpAll(() {
    // returning future here because i've seen setUpAll must return
    // an instance of Future when it has to do something in the future
    // so, marking it as async is not enough it seems
    return Future(() async {
      WidgetsFlutterBinding.ensureInitialized(); // just to be double sure
      initDI();
      await initFirebaseEmulatorUse();
      firebaseFirestore = GetIt.I.get(); // get an instance of firestore
    });
  });

  tearDownAll(() {
    return Future(() async {
      // ... do something to clear all documents in firestore? ...
      // ... so it won't affect other tests? ...
      // i need to access `firebaseFirestore` instance here to do it
    });
  });

  test('do tests', () async {
    // ... test stuff ...
  });
}
```
<p>However, this fails saying:</p>
```PlatformException(channel-error, Unable to establish connection on channel., null, null)
FirebaseCoreHostApi.initializeCore
✖ (setUpAll)
LateInitializationError: Local 'firebaseFirestore' has not been initialized.
dart:_internal                                        LateError._throwLocalNotInitialized
main.<fn>.<fn>
===== asynchronous gap ===========================
dart:async                                            new Future
main.<fn>

✖ (tearDownAll)
Exited (1)
```
<p>When I go to the line where it throws this error, it actually throws <em>in the <code>tearDownAll</code></em>.</p>
<p>Troubleshooting for a while, I think we've got two problems:</p>
<ul>
<li><code>firebaseFirestore</code> is not initialized while in <code>tearDownAll</code>. While I have it initialized in <code>setUpAll</code>, that probably means the <code>Future</code> I return from <code>setUpAll</code> does not finish fast enough until I reach <code>tearDownAll</code>. That's my guess.</li>
<li>That "Unable to establish connection on channel" message is, I believe, because somehow the Firebase cannot connect to my local emulator.</li>
</ul>
<p>I've been trying to solve these with different methods for hours but couldn't find a way to solve it. Any blog post about setting up Firebase Emulator + Unit Testing is also appreciated. The posts that I've found so far couldn't get me figure out how I can connect to my local Firebase emulator. Thanks in advance.</p>
<hr />
<h1>Environment</h1>
<ul>
<li>Firebase Tools 11.19.0</li>
<li>get_it: ^7.2.0</li>
<li>firebase_core: ^2.3.0</li>
<li>firebase_auth: ^4.1.3</li>
<li>cloud_firestore: ^4.1.0</li>
<li>firebase_crashlytics: ^3.0.6</li>
<li>cloud_functions: ^4.0.5</li>
<li>firebase_analytics: ^10.0.6</li>
<li>fake_cloud_firestore: ^2.1.0 as dev</li>
<li>firebase_auth_mocks: ^0.9.2 as dev</li>
</ul>
<h2>Flutter Doctor</h2>
```[✓] Flutter (Channel stable, 3.3.9, on Fedora Linux 36 (KDE Plasma) 6.0.14-200.fc36.x86_64, locale en_US.UTF-8)
    • Flutter version 3.3.9 on channel stable at /home/erayerdin/.local/lib/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (4 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /home/erayerdin/.sdks/android/
    • Platform android-33, build-tools 33.0.0
    • ANDROID_SDK_ROOT = /home/erayerdin/.sdks/android
    • Java binary at: /var/lib/snapd/snap/android-studio/125/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 14.0.5 (Fedora 14.0.5-2.fc36)
    • cmake version 3.25.1
    • ninja version 1.10.2
    • pkg-config version 1.8.0

[✓] Android Studio (version 2021.3)
    • Android Studio at /var/lib/snapd/snap/android-studio/125/android-studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] VS Code
    • VS Code at /snap/code/current
    • Flutter extension version 3.56.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Fedora Linux 36 (KDE Plasma) 6.0.14-200.fc36.x86_64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
```

Body:
I use get_it for simple dependency injection. I have a function that I made sure is called when the app initializes as below:

void initDI() {
  // ... the other providers and repositories ...

  //--------- //
  // Firebase //
  //--------- //
  // i reference these instances everywhere when i wanna access them
  // such as providers, repositories, etc.
  GetIt.I.registerLazySingleton<FirebaseAuth>(() => FirebaseAuth.instance);
  GetIt.I.registerLazySingleton<FirebaseFirestore>(
    () => FirebaseFirestore.instance,
  );
  GetIt.I.registerLazySingleton<FirebaseFunctions>(
    () => FirebaseFunctions.instance,
  );
}

In my test directory, I have a file named initializers.dart, which has setup functions for tests for convenience. One that concerns us is as follows:

// test/initializers.dart

Future<void> initFirebaseEmulatorUse() async {
  // ensure widget bindings get initialized because firebase requires this for some reason
  WidgetsFlutterBinding.ensureInitialized();
  // initialize firebase app
  await Firebase.initializeApp();
  // use functions emulator because there is no mock or fake package for functions, which is reasonable
  FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);

  // unregister default references
  GetIt.I.unregister<FirebaseAuth>();
  GetIt.I.unregister<FirebaseFirestore>();

  // register with mocks and fakes
  GetIt.I.registerLazySingleton<FirebaseAuth>(() => MockFirebaseAuth());
  GetIt.I.registerLazySingleton<FirebaseFirestore>(
    () => FakeFirebaseFirestore(),
  );
}

And, an example test is as follows:

// import initializers, we'll need them
import '../initializers.dart';

void main() {
  // use in setUpAll, once and for all
  late FirebaseFirestore firebaseFirestore;

  setUpAll(() {
    // returning future here because i've seen setUpAll must return
    // an instance of Future when it has to do something in the future
    // so, marking it as async is not enough it seems
    return Future(() async {
      WidgetsFlutterBinding.ensureInitialized(); // just to be double sure
      initDI();
      await initFirebaseEmulatorUse();
      firebaseFirestore = GetIt.I.get(); // get an instance of firestore
    });
  });

  tearDownAll(() {
    return Future(() async {
      // ... do something to clear all documents in firestore? ...
      // ... so it won't affect other tests? ...
      // i need to access `firebaseFirestore` instance here to do it
    });
  });

  test('do tests', () async {
    // ... test stuff ...
  });
}

However, this fails saying:

PlatformException(channel-error, Unable to establish connection on channel., null, null)
FirebaseCoreHostApi.initializeCore
✖ (setUpAll)
LateInitializationError: Local 'firebaseFirestore' has not been initialized.
dart:_internal                                        LateError._throwLocalNotInitialized
main.<fn>.<fn>
===== asynchronous gap ===========================
dart:async                                            new Future
main.<fn>

✖ (tearDownAll)
Exited (1)

When I go to the line where it throws this error, it actually throws in the tearDownAll.

Troubleshooting for a while, I think we've got two problems:

firebaseFirestore is not initialized while in tearDownAll. While I have it initialized in setUpAll, that probably means the Future I return from setUpAll does not finish fast enough until I reach tearDownAll. That's my guess.

That "Unable to establish connection on channel" message is, I believe, because somehow the Firebase cannot connect to my local emulator.

I've been trying to solve these with different methods for hours but couldn't find a way to solve it. Any blog post about setting up Firebase Emulator + Unit Testing is also appreciated. The posts that I've found so far couldn't get me figure out how I can connect to my local Firebase emulator. Thanks in advance.

Environment

Firebase Tools 11.19.0

get_it: ^7.2.0

firebase_core: ^2.3.0

firebase_auth: ^4.1.3

cloud_firestore: ^4.1.0

firebase_crashlytics: ^3.0.6

cloud_functions: ^4.0.5

firebase_analytics: ^10.0.6

fake_cloud_firestore: ^2.1.0 as dev

firebase_auth_mocks: ^0.9.2 as dev

Flutter Doctor

[✓] Flutter (Channel stable, 3.3.9, on Fedora Linux 36 (KDE Plasma) 6.0.14-200.fc36.x86_64, locale en_US.UTF-8)
    • Flutter version 3.3.9 on channel stable at /home/erayerdin/.local/lib/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (4 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /home/erayerdin/.sdks/android/
    • Platform android-33, build-tools 33.0.0
    • ANDROID_SDK_ROOT = /home/erayerdin/.sdks/android
    • Java binary at: /var/lib/snapd/snap/android-studio/125/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 14.0.5 (Fedora 14.0.5-2.fc36)
    • cmake version 3.25.1
    • ninja version 1.10.2
    • pkg-config version 1.8.0

[✓] Android Studio (version 2021.3)
    • Android Studio at /var/lib/snapd/snap/android-studio/125/android-studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] VS Code
    • VS Code at /snap/code/current
    • Flutter extension version 3.56.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Fedora Linux 36 (KDE Plasma) 6.0.14-200.fc36.x86_64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!


来源: stackexchange

问:
How to return Error Response to a user from a middleware
I am new to Rust and the Actix web framework. I have been trying to create a simple server in actix web. I have implemented the auth system but I am trying to create a middleware for verifying the JWT token and extract the claims from the jwt to be used in an handler.

impl<S, B> Service<ServiceRequest> for JwtVerifierMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let authorization = req.headers().get("Authorization");

        let mut extensions = req.extensions_mut();

        let fut = self.service.call(req);

        let token = if let Some(authorization) = authorization {
            authorization.to_str().unwrap()
        } else {
            return Box::pin(async {
                let res = fut.await?;
                Ok(res)
            });
        };

        let claims = verify(token).unwrap();

        extensions.insert(claims);

        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }

}

```

I have the code above where I am trying to extract the token from the request and return an error response if the token is a None variant.The issue I have currently is that self.service.call() wants to move the req but it has already been borrowed here req.headers().get("Authorization"). I am not sure how to approach this.

I have tried to clone the req but it seems ServiceRequest does not implement the clone trait. I have also tried to pass a reference to the ServiceRequest as argument to the call function but I get an error that method call has an incompatible type for trait Service

ContentLicense: CC BY-SA 4.0

Body:
I am new to Rust and the Actix web framework. I have been trying to create a simple server in actix web. I have implemented the auth system but I am trying to create a middleware for verifying the JWT token and extract the claims from the jwt to be used in an handler.

impl<S, B> Service<ServiceRequest> for JwtVerifierMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let authorization = req.headers().get("Authorization");

        let mut extensions = req.extensions_mut();

        let fut = self.service.call(req);

        let token = if let Some(authorization) = authorization {
            authorization.to_str().unwrap()
        } else {
            return Box::pin(async {
                let res = fut.await?;
                Ok(res)
            });
        };

        let claims = verify(token).unwrap();

        extensions.insert(claims);

        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }

}

I have the code above where I am trying to extract the token from the request and return an error response if the token is a None variant.The issue I have currently is that self.service.call() wants to move the req but it has already been borrowed here req.headers().get("Authorization"). I am not sure how to approach this.

I have tried to clone the req but it seems ServiceRequest does not implement the clone trait. I have also tried to pass a reference to the ServiceRequest as argument to the call function but I get an error that method call has an incompatible type for trait Service


问:
Return the max cosine similarity and target text from list which is most similar using FIASS
How can I use FAISS ( Facebook AI Similarity Search ) to compare cosine similarity with texts with list of target texts, and return the max cosine similarity and target text from list which is most similar:

I have done this sofar:

```<code> import faiss

    # Preprocess data as needed
    documents = [
        "This is the first document"
    ]

    documents2 = [
      "first doc",
        "This is the first document"

    ]

    # Use TF-IDF to convert the text documents into numerical vectors
    vectorizer = TfidfVectorizer()
    data = vectorizer.fit_transform(documents)
    data = data.toarray()

    # Normalize the vectors
    data = data / np.linalg.norm(data, axis=1, keepdims=True)

    # Create an index using FAISS
    index = faiss.IndexFlatIP(data.shape[1])  # Create an index with the same number of dimensions as your data
    index.add(data)  # Add your data to the index

# Search for the nearest neighbors of a given text document
query = vectorizer.transform(documents2).toarray()  # The text document you want to find the nearest neighbors of
k = 2  # The number of nearest neighbors to return
distances, indices = index.search(query, k)

# Calculate the similarity score between the text documents
similarity_score = distances[0][0]  # The inner product is equal to the cosine of the angle between the normalized vectors
</code>```

However, this is not giving result which I am looking for. Can someone guide me please?

Body:
How can I use FAISS ( Facebook AI Similarity Search ) to compare cosine similarity with texts with list of target texts, and return the max cosine similarity and target text from list which is most similar:

I have done this sofar:

 import faiss

    # Preprocess data as needed
    documents = [
        "This is the first document"
    ]

    documents2 = [
      "first doc",
        "This is the first document"

    ]

    # Use TF-IDF to convert the text documents into numerical vectors
    vectorizer = TfidfVectorizer()
    data = vectorizer.fit_transform(documents)
    data = data.toarray()

    # Normalize the vectors
    data = data / np.linalg.norm(data, axis=1, keepdims=True)

    # Create an index using FAISS
    index = faiss.IndexFlatIP(data.shape[1])  # Create an index with the same number of dimensions as your data
    index.add(data)  # Add your data to the index

# Search for the nearest neighbors of a given text document
query = vectorizer.transform(documents2).toarray()  # The text document you want to find the nearest neighbors of
k = 2  # The number of nearest neighbors to return
distances, indices = index.search(query, k)

# Calculate the similarity score between the text documents
similarity_score = distances[0][0]  # The inner product is equal to the cosine of the angle between the normalized vectors

However, this is not giving result which I am looking for. Can someone guide me please?


问:
Uncaught Error: [$injector:nomod] Module is not available
Even though I am not new to Angular programming and testing, the situation that I came across is a bit unique and I need some help to resolve that.

I am writing test cases for a service that gets the data from the backend. To write a test case I mocked the target module. This module is internally dependent on other modules and I am getting an error like,

Uncaught Error: [$injector:nomod] Module 'moduleName' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Now, my test case is very basic

```<code>    import {moduleName} from "../config/constants";

    describe('test ModalService', () => {

        let modalService;

        beforeAll(angular.mock.module(moduleName));

        beforeEach(inject((tgtmodalService)=>{
        modalService = tgtmodalService;
     }));

        it("test service defined", () => {
        expect(modalService).toBeDefined();
       });

    });
</code>```

and my module.js looks as follows. This module then depends on other modules as shown below.

```<code>    import { moduleName } from "./config/constants";

    if (typeof window.$m === 'undefined' || !window.$m) {
    window.$m = {};
    }

    if (window.$m.isTest1) {
        angular.module(moduleName, ['module2', 'module3']);
    } else if (window.$m.isTest2) {
        angular.module(moduleName, ['module2', 'module4', 'module5']);
     } else {
        angular.module(moduleName, ['module2', 'module5']);
     }

      export { moduleName };
</code>```

When I execute the above test case I get the error mentioned above. I don't know what to do to avoid errors related to dependencies. Also, I am not sure if my method of mocking the module is wrong. Any help would be appreciated.

Body:
Even though I am not new to Angular programming and testing, the situation that I came across is a bit unique and I need some help to resolve that.

I am writing test cases for a service that gets the data from the backend. To write a test case I mocked the target module. This module is internally dependent on other modules and I am getting an error like,

Uncaught Error: [$injector:nomod] Module 'moduleName' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Now, my test case is very basic

    import {moduleName} from "../config/constants";

    describe('test ModalService', () => {

        let modalService;

        beforeAll(angular.mock.module(moduleName));

        beforeEach(inject((tgtmodalService)=>{
        modalService = tgtmodalService;
     }));

        it("test service defined", () => {
        expect(modalService).toBeDefined();
       });

    });

and my module.js looks as follows. This module then depends on other modules as shown below.

    import { moduleName } from "./config/constants";

    if (typeof window.$m === 'undefined' || !window.$m) {
    window.$m = {};
    }

    if (window.$m.isTest1) {
        angular.module(moduleName, ['module2', 'module3']);
    } else if (window.$m.isTest2) {
        angular.module(moduleName, ['module2', 'module4', 'module5']);
     } else {
        angular.module(moduleName, ['module2', 'module5']);
     }

      export { moduleName };

When I execute the above test case I get the error mentioned above. I don't know what to do to avoid errors related to dependencies. Also, I am not sure if my method of mocking the module is wrong. Any help would be appreciated.


问:
in swiftUI ForEach loop displays words separated in different lines and not keeping words in original text form
1ForEach loop displays words separated in different lines and not keeping words in original text form. whether in  HStack or VStack still there is same issue.

HStack words
VStack words

```<code>import SwiftUI

struct ContentView: View {

    let mainText = "In the midst of a wartime evacuation, a British aeroplane crashes on or near an isolated island in a remote region of the Pacific Ocean."

    let wordsToMakeTapable = ["evacuation,", "crashes", "isolated"]
    let definitions = ["evacuation,": "make empty", "crashes": "hit", "isolated": "far away"]

    var body: some View {

        let words = mainText.components(separatedBy: " ")

        HStack {
            ForEach(words, id: \.self) { word in
                if wordsToMakeTapable.contains(word) {
                    Text(word)
                        .foregroundColor(.blue)
                        .bold()
                        .onTapGesture {
                            switch word {
                            case "evacuation":
                                print(definitions["evacuation"]!)
                            case "crashes":
                                print(definitions["crashes"]!)
                            case "isolated":
                                print(definitions["isolated"]!)
                            default:
                                break
                            }
                        }
                } else {
                    Text(word)
                }
                Spacer()

            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

please let me know how to fix it.

Body:
1ForEach loop displays words separated in different lines and not keeping words in original text form. whether in  HStack or VStack still there is same issue.

HStack words
VStack words

import SwiftUI

struct ContentView: View {

    let mainText = "In the midst of a wartime evacuation, a British aeroplane crashes on or near an isolated island in a remote region of the Pacific Ocean."

    let wordsToMakeTapable = ["evacuation,", "crashes", "isolated"]
    let definitions = ["evacuation,": "make empty", "crashes": "hit", "isolated": "far away"]

    var body: some View {

        let words = mainText.components(separatedBy: " ")

        HStack {
            ForEach(words, id: \.self) { word in
                if wordsToMakeTapable.contains(word) {
                    Text(word)
                        .foregroundColor(.blue)
                        .bold()
                        .onTapGesture {
                            switch word {
                            case "evacuation":
                                print(definitions["evacuation"]!)
                            case "crashes":
                                print(definitions["crashes"]!)
                            case "isolated":
                                print(definitions["isolated"]!)
                            default:
                                break
                            }
                        }
                } else {
                    Text(word)
                }
                Spacer()

            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

please let me know how to fix it.


问:
How to loop through values in a data frame with the PrepText() command?
I have a data frame that stores names of saved data frame objects in my R session:

```<code>col1 <- c("what is this", "how are you", "hello im good")
df <- data.frame(col1)
</code>```

The what is this object looks like this:

```<code>title <- c("this is a cat", "this is a dog", "this is a dog")
body <- c("the cat is very cute", "who cares", "here is a bone")
`what is this` <- data.frame(title, body)
</code>```

I want to be able to loop through all three object names in the df data frame using the textnets package and stack the text_centrality results on top of each other. I wrote the following code:

```<code>for (row in 1:nrow(df)) {
  prepped_header <- PrepText(df[row, "col1"], groupvar = "title", textvar = "body", node_type = "groups", tokenizer = "words", pos = "nouns", remove_stop_words = TRUE, compound_nouns = TRUE)

  header_text_network <- CreateTextnet(prepped_header)
  text_centrality <- TextCentrality(header_text_network)
}
</code>```

I am getting the following error message:

```<code>Error in PrepText(df[row, "col1"], groupvar = "title", textvar = "body",  :
  unused arguments (groupvar = "title", textvar = "body", node_type = "groups", tokenizer = "words", pos = "nouns", remove_stop_words = TRUE, compound_nouns = TRUE)
</code>```

Any guidance would be appreciated!

Body:
I have a data frame that stores names of saved data frame objects in my R session:

col1 <- c("what is this", "how are you", "hello im good")
df <- data.frame(col1)

The what is this object looks like this:

title <- c("this is a cat", "this is a dog", "this is a dog")
body <- c("the cat is very cute", "who cares", "here is a bone")
`what is this` <- data.frame(title, body)

I want to be able to loop through all three object names in the df data frame using the textnets package and stack the text_centrality results on top of each other. I wrote the following code:

for (row in 1:nrow(df)) {
  prepped_header <- PrepText(df[row, "col1"], groupvar = "title", textvar = "body", node_type = "groups", tokenizer = "words", pos = "nouns", remove_stop_words = TRUE, compound_nouns = TRUE)

  header_text_network <- CreateTextnet(prepped_header)
  text_centrality <- TextCentrality(header_text_network)
}

I am getting the following error message:

Error in PrepText(df[row, "col1"], groupvar = "title", textvar = "body",  :
  unused arguments (groupvar = "title", textvar = "body", node_type = "groups", tokenizer = "words", pos = "nouns", remove_stop_words = TRUE, compound_nouns = TRUE)

Any guidance would be appreciated!


问:
Cabinet : Not Found
I am trying to login on IBPS3 and getting error:- Cabinet : Not Found.Omni docs is working fine and we are able to login alos. Earlier it was working fine and suddenly we got error.

Refer Image

I have tried below things.

checked all the config and properties files.

checked ofservices.

checked server logs and got :-

Input xml:-

```<code><?xml version="1.0"?>
<OA_Connect_Input>
<Option>OA_Connect</Option>
<CabinetName>GIB_DEV2</CabinetName><ApplicationInfo>172.16.20.250</ApplicationInfo><ApplicationName>OAP</ApplicationName>
<UserName>******</UserName>
<Scope>USER</Scope>
<UserExist>Y</UserExist>
<Locale>en_US</Locale>
<UserImageFlag>Y</UserImageFlag>
</OA_Connect_Input>
</code>```

Output xml:-

```<code><?xml version="1.0"?>
<OA_Connect_Output>
<Option>OA_Connect</Option>
<Status>-1011</Status><Error>Cabinet :  Not Found</Error></OA_Connect_Output>
</code>```

Title: Cabinet : Not Found

Body:
I am trying to login on IBPS3 and getting error:- Cabinet : Not Found.Omni docs is working fine and we are able to login alos. Earlier it was working fine and suddenly we got error.

Refer Image

I have tried below things.

checked all the config and properties files.

checked ofservices.

checked server logs and got :-

Input xml:-

<?xml version="1.0"?>
<OA_Connect_Input>
<Option>OA_Connect</Option>
<CabinetName>GIB_DEV2</CabinetName><ApplicationInfo>172.16.20.250</ApplicationInfo><ApplicationName>OAP</ApplicationName>
<UserName>******</UserName>
<Scope>USER</Scope>
<UserExist>Y</UserExist>
<Locale>en_US</Locale>
<UserImageFlag>Y</UserImageFlag>
</OA_Connect_Input>

Output xml:-

<?xml version="1.0"?>
<OA_Connect_Output>
<Option>OA_Connect</Option>
<Status>-1011</Status><Error>Cabinet :  Not Found</Error></OA_Connect_Output>


问:
splitChunks optimization resulting in a larger bundle size?
I'm trying to optimize the build for my application, here is what it looks like with the default config,

Now, I've made a few changes to my node_mdoules, removed about 5-6 unused packages, replaced sanitize-html with isomorphic-dompurify which should ideally result in a smaller bundle size, but this is what it looks like now,

Even though the size of the vendor and app chunks are down significantly - 62kb and 28kb respective, the "All" size is up from 1.64mb to 1.79mb (~150kb), the only change in the nuxt config is adding the splitChunks config to build,

build: {
  ..
  splitChunks: {
    layouts: true
  }
}
```

Why does this happen? and is it okay if the overall bundle size is larger when layouts is split?

Will it affect performance negatively?

Body:
I'm trying to optimize the build for my application, here is what it looks like with the default config,

Now, I've made a few changes to my node_mdoules, removed about 5-6 unused packages, replaced sanitize-html with isomorphic-dompurify which should ideally result in a smaller bundle size, but this is what it looks like now,

Even though the size of the vendor and app chunks are down significantly - 62kb and 28kb respective, the "All" size is up from 1.64mb to 1.79mb (~150kb), the only change in the nuxt config is adding the splitChunks config to build,

build: {
  ..
  splitChunks: {
    layouts: true
  }
}

Why does this happen? and is it okay if the overall bundle size is larger when layouts is split?

Will it affect performance negatively?


问:
trying to install via conda throws glibc version error
I am trying to install a conda package on a virtual machine on my mac and I keep getting this error that I dont understand.</p>
```<code>conda install -c "formicidae-tracker/label/test" py-fort-myrmidon

ERROR
UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - py-fort-myrmidon -> python[version='>=3.8,<3.9.0a0']

Your python: python=3.9.0

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your system:

  - feature:/linux-64::__glibc==2.31=0
  - feature:|@/linux-64::__glibc==2.31=0

Your installed version is: 2.31
</code>```

Body:
I am trying to install a conda package on a virtual machine on my mac and I keep getting this error that I dont understand.

conda install -c "formicidae-tracker/label/test" py-fort-myrmidon

ERROR
UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - py-fort-myrmidon -> python[version='>=3.8,<3.9.0a0']

Your python: python=3.9.0

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your system:

  - feature:/linux-64::__glibc==2.31=0
  - feature:|@/linux-64::__glibc==2.31=0

Your installed version is: 2.31


问:
IIS URL Rewrite with Abort action is not aborting the request
I am trying to abort some URL patterns when it comes to my server/application. I have the below URL Rewrite in place. But I am seeing those request are not aborted under the worker process.

If the URL is something like www.example.com/search/?q=abc\&page=abc\&contenttype=all I want to abort that request immediately.

<rule name="Abort Request" stopProcessing="true">
  <match url="(.*)" />
  <conditions>
    <add input="{URL}" pattern="\/search\/\?q=" />
  </conditions>
  <action type="AbortRequest" />
</rule>
```


问:
Cannot execute file in android "No such file or directory" even though I can read the file
I sideloaded a binary that I built using the NDK for android and I used to be able to push it to /data and then I could run it by just calling it in adb shell with /data/program.
Now suddenly, without changing anything I am unable to do so with the error message being: /system/bin/sh: /data/program: No such file or directory.

But the file exists, when I read it with cat /data/program it outputs me the entire binary.

I tried looking into it, I don't think there is a sepolicy violation and it also doesn't seem to be an issue with permissions. I tried using root and I added the execution permission using chmod +x /data/program and chmod 777 /data/program. None of this worked.

Has anybody had a similar issue? I am running on LineageOS 19.1 on my Pixel 3


问:
Flutter Onesignal push notification, navigate to page when tapping on notification
I am using Onesignal system for push notification. How can I navigate user to specific app screen when user tap to notification. On web system I am using url properties but I don't know how to do this on mobile (android and ios) applications. Thanks for help.</p>


问:
Updating templates in django app without re-rendering the pages
I'm making a Django web application in python, similar to language learning quiz. It consists of three different parts. One is showing the set of sentences to a user (one element per page) and the second is asking questions about sentences that was just shown. The third one is showing results and asking for redo the wrong q/a. Each part has next/prev buttons for iteration and the content of the sentence.
I also need to store info to DB when the user answers the question right to not to show it again. The set of questions is provided by a view function through filtering the models objects.

I need to have these 3 stages without page rendering. I face the following problem:

The list of questions is passed to the template to iterate over it once to present sentences, then I need to start the loop again with the only difference of adding a field of textarea for answer and a few buttons. What is the best way to do it? I was thinking about some ajax function that'll be triggered after the first loop is finished. This js function can refill the certain tags with textarea and buttons. But then need to identify the end of the second loop to show the results. I'm not a JS developer and this sounds quite messy so I suppose there is smarter way to do it.

PS. Just FYI the pagination is done also without re-rendering the templates.


问:
Show previous fragment after entering Picture-In-Picture
I have the following navigation structure in my app:

```<code> MainActivity    ->    VideoListFragment     ->      VideoShowingFragment
(only activity,     (shows a list of Video      (gets the URL of the video to
 container for       items via a Recycler-        show and plays the video via
 all the other       View, the URL of the         ExoPlayer. From here, the user
 fragments)          Video is passed to           can enter PiP mode)
                     next Fragment)
</code>```

So, when the app starts, a list of Video items is shown to the user. When the user clicks on an item, the URL is passed to the VideoShowingFragment which displays the Video content to the user via the PlayerView of the ExoPlayer library. On top of the PlayerView, there is an icon so the user can enter PiP mode when he clicks on it.

Entering PiP works and is all fine, but how can I show the list of Videos after going to PiP mode? What I mean: When the user is in the VideoShowingFragment stage and decides to minimize the Video content by entering the PiP mode, how can I show him the list of Videos (VideoListFragment) so that he can browse through the list while still watching the content in PiP mode?

The situation right now is the following: The user enters PiP mode but the user sees the Start Screen of his device while the video content is minimized in the bottom right corner.

Body:
I have the following navigation structure in my app:

 MainActivity    ->    VideoListFragment     ->      VideoShowingFragment
(only activity,     (shows a list of Video      (gets the URL of the video to
 container for       items via a Recycler-        show and plays the video via
 all the other       View, the URL of the         ExoPlayer. From here, the user
 fragments)          Video is passed to           can enter PiP mode)
                     next Fragment)

So, when the app starts, a list of Video items is shown to the user. When the user clicks on an item, the URL is passed to the VideoShowingFragment which displays the Video content to the user via the PlayerView of the ExoPlayer library. On top of the PlayerView, there is an icon so the user can enter PiP mode when he clicks on it.

Entering PiP works and is all fine, but how can I show the list of Videos after going to PiP mode? What I mean: When the user is in the VideoShowingFragment stage and decides to minimize the Video content by entering the PiP mode, how can I show him the list of Videos (VideoListFragment) so that he can browse through the list while still watching the content in PiP mode?

The situation right now is the following: The user enters PiP mode but the user sees the Start Screen of his device while the video content is minimized in the bottom right corner.


问:
Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported
I have installed Opal Theme and i have this error:

```<code>Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)`
   in /home/mhd-01/www.triumphclubroma.it/htdocs/wp-content/themes/lexrider/inc/admin/screens/welcome.php on line 96
</code>```

This is the line 96

```<code><span class="<?php echo esc_attr( $status['time_limit'] ? 'pass' : ( $data['time_limit'] >= 60 ) ? 'warning' : 'fail' ); ?>"></span>
</code>```

How can I resolve this error?

Body:
I have installed Opal Theme and i have this error:

Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)`
   in /home/mhd-01/www.triumphclubroma.it/htdocs/wp-content/themes/lexrider/inc/admin/screens/welcome.php on line 96

This is the line 96

<span class="<?php echo esc_attr( $status['time_limit'] ? 'pass' : ( $data['time_limit'] >= 60 ) ? 'warning' : 'fail' ); ?>">

How can I resolve this error?


问:
Silverlight sockets: mimic framework Bind, Listen and Accept methods?
I have this .NET Framework C# class that practically acts as a wrapper for TCP connections around the Socket class in the System.Net.Sockets namespace.

Recently I have migrated the API of this wrapper class to Silverlight, but because of the limitations of the Socket class in Silverlight, as well as the normal trust restrictions with respect to avaiable ports, client access policy etc., I have only implemented network client support in my Silverlight version.

Now, with Silverlight 5 (RC), it has become possible to apply elevated trust even for in-browser SL applications, which removes all the port and client access policy restrictions that I had to adhere to in SL 4.

My question is, if there is also a way to implement some kind of network server support in my SL wrapper class? More specifically, is there a way in Silverlight to mimic the Bind, Listen and Accept methods of the .NET Framework Socket class?

To mimic Socket.Connect, I have used the ConnectAsync method in the Silverlight Socket class. Could something similar be done for the Bind/Listen/Accept methods using e.g. Receive(From)Async?

Thanks in advance.

ContentLicense: CC BY-SA 3.0


问:
Python: ValueError Data cardinality is ambiguous
I'm trying to make an AI that can convert handwriting to plain text. But I'm encountering the following error:

```<code>ValueError: Data cardinality is ambiguous:
  x sizes: 8
  y sizes: 1
Make sure all arrays contain the same number of samples.
</code>```

I have 8 images as testing dataset, each image has its own label file which looks something like this: 87 70 66 75 0 66 67 0 63 79 66 75 68 81.

Then I combine those into 1 file (combined_labels.csv):

```<code>39 46 70 0 51 66 70 71 66 13,42 66 0 73 62 62 81 0 80 81 66 66 65 80,74 66 66 79 0 83 62 75 0 71 66 69 82 74 76 79,87 70 66 75 0 66 67 0 63 79 66 75 68 81,68 66 87 66 73 73 70 68 69 66 70 65 0 70 75,65 66 0 72 73 62 80 2,38 66 75 70 66 81 0 83 62 75 0 65 66,83 62 72 62 75 81 70 66 2
</code>```

Relevant code:

```<code>image_paths = []
for i in range(8):
    image_paths.append("Dataset/Images/000000/000000_{}.png".format(str(i).zfill(2)))

images = []
for image_path in image_paths:
    image = Image.open(image_path)
    # Resize and grayscale the image
    image = image.resize((28, 28))
    image = image.convert("L")
    images.append(np.array(image))

images = np.array(images)
images = images / 255.0
images = images.reshape(-1, 28, 28, 1)

...

combined_labels = pd.read_csv("combined_labels.csv", names=["labels"])

combined_labels = combined_labels["labels"].str.split(",", expand=True)

labels = combined_labels.values

labels = labels.flatten()

model.fit(images, labels, epochs=10) # Error line
</code>```

Body:
I'm trying to make an AI that can convert handwriting to plain text. But I'm encountering the following error:

ValueError: Data cardinality is ambiguous:
  x sizes: 8
  y sizes: 1
Make sure all arrays contain the same number of samples.

I have 8 images as testing dataset, each image has its own label file which looks something like this: 87 70 66 75 0 66 67 0 63 79 66 75 68 81.

Then I combine those into 1 file (combined_labels.csv):

39 46 70 0 51 66 70 71 66 13,42 66 0 73 62 62 81 0 80 81 66 66 65 80,74 66 66 79 0 83 62 75 0 71 66 69 82 74 76 79,87 70 66 75 0 66 67 0 63 79 66 75 68 81,68 66 87 66 73 73 70 68 69 66 70 65 0 70 75,65 66 0 72 73 62 80 2,38 66 75 70 66 81 0 83 62 75 0 65 66,83 62 72 62 75 81 70 66 2

Relevant code:

image_paths = []
for i in range(8):
    image_paths.append("Dataset/Images/000000/000000_{}.png".format(str(i).zfill(2)))

images = []
for image_path in image_paths:
    image = Image.open(image_path)
    # Resize and grayscale the image
    image = image.resize((28, 28))
    image = image.convert("L")
    images.append(np.array(image))

images = np.array(images)
images = images / 255.0
images = images.reshape(-1, 28, 28, 1)

...

combined_labels = pd.read_csv("combined_labels.csv", names=["labels"])

combined_labels = combined_labels["labels"].str.split(",", expand=True)

labels = combined_labels.values

labels = labels.flatten()

model.fit(images, labels, epochs=10) # Error line


问:
Retrieving Data from REST API into Tableau
I'm trying to get data into Tableau from a RESTful API in which a certain endpoint is accepting a set of parameters and returning tabular data. A more correct representation of our request and response is as below:

Request:

```<code>http://api-baseurl:8080/query_data/Soap?access_token=123456789
</code>```

Reponse:

```<code>[{
    "Item": "Soap",
    "Market": "Domestic",
    "Price": 120
  },
  {
    "Item": "Soap",
    "Market": "Global",
    "Price": 190
  }]
</code>```

I also have a csv file with columns, Item and Owner(some irrelevant column name). I want to load this csv file to Tableau and upon selection of filters on Item column, I want to call the API as in the above example.

What I did so far:

I tried to use the TabPy, however it returns only measure columns. I tried to use a SCRIPT_STR function as in the below example:

```<code>SCRIPT_STR("
import requests
response = requests.get(f'http://api-baseurl:8080/query_data/{_arg1}?access_token=123456789')
dict_list = response.json()
response=str(dict_list)
return response
",ATTR([Item]))
</code>```

Unfortunately it is returning a single string and during SPLIT, I have below error:

```<code>The SPLIT function cannot be applied to table calculations and fields from multiple data sources
</code>```

Apparently since a single string is returned, it is not a wise way to query data.

Also tried to use the Web Data Connector, but it is only accepting hardcoded API URLs.

Now my questions:

Is something like this be applicable in Tableau? If so what property should I use? Is TabPy the correct path? Is the WDC has this capacity?

Looking forward to any kind of help.

Thanks for you interest.

Body:
I'm trying to get data into Tableau from a RESTful API in which a certain endpoint is accepting a set of parameters and returning tabular data. A more correct representation of our request and response is as below:

Request:

http://api-baseurl:8080/query_data/Soap?access_token=123456789

Reponse:

[{
    "Item": "Soap",
    "Market": "Domestic",
    "Price": 120
  },
  {
    "Item": "Soap",
    "Market": "Global",
    "Price": 190
  }]

I also have a csv file with columns, Item and Owner(some irrelevant column name). I want to load this csv file to Tableau and upon selection of filters on Item column, I want to call the API as in the above example.

What I did so far:

I tried to use the TabPy, however it returns only measure columns. I tried to use a SCRIPT_STR function as in the below example:

SCRIPT_STR("
import requests
response = requests.get(f'http://api-baseurl:8080/query_data/{_arg1}?access_token=123456789')
dict_list = response.json()
response=str(dict_list)
return response
",ATTR([Item]))

Unfortunately it is returning a single string and during SPLIT, I have below error:

The SPLIT function cannot be applied to table calculations and fields from multiple data sources

Apparently since a single string is returned, it is not a wise way to query data.

Also tried to use the Web Data Connector, but it is only accepting hardcoded API URLs.

Now my questions:

Is something like this be applicable in Tableau? If so what property should I use? Is TabPy the correct path? Is the WDC has this capacity?

Looking forward to any kind of help.

Thanks for you interest.


问:
nodejs yamux stream not ending
I'm trying to get multiple streams through a single tcp connection using stream multiplexing.

The idea is to have a "tunnel hub" accept tcp connections from clients, and pass http requests to the clients that match the host header.

I'm using yamux-js to handle the muxing/demuxing workload.

const http = require("http");
const net = require("net");
const yamux = require("yamux-js");
const fs = require("fs");
const {pipeline} = require("stream");

const muxerMap = new Map();

// https server receives http request, pipes it to yamux client stream
const webserver = http.createServer(function(req, res) {
    const muxer = muxerMap.get("any"); // TODO: Find muxer associated req.header.host
    if (!muxer) {
        res.writeHead(404);
        return res.end("muxer could not be found\n");
    }
    const muxStream = muxer.open();
    pipeline(req, muxStream, res, (err) => {
        if (err) console.error(err);
    });
});
webserver.listen(3128);

// tcp server receives socket from client and stores it "somewhere"
const tunnelServer = net.createServer();
tunnelServer.on("connection", function(socket) {
    const muxer = new yamux.Client();
    muxer.on("error", err => console.error(err));
    pipeline(muxer, socket, muxer, (err) => {
        if (err) console.error(err);
    });
    muxerMap.set("any", muxer);
});
tunnelServer.listen(3500);

// tcp client connect to tcp server
const socket = net.createConnection(3500);
socket.on("connect", () => {
    const muxer = new yamux.Server(function(muxStream) {
        const fileReadable = fs.createReadStream("hello-world.txt");
        pipeline(fileReadable, muxStream, (err) => {
            if (err) console.error(err);
        });
    });
    pipeline(muxer, socket, muxer, (err) => {
        if (err) console.error(err);
    });
});
```
<p>My problem is that the http response doesn't get ended, leaving my curl request stuck.</p>
<p>I can verify that the <code>hello-world.txt</code> file read stream, is emitting <code>end</code> events, so somewhere along the wire, that <code>end</code> event isn't "piped" correctly.</p>
<pre class="lang-bash prettyprint-override"><code>user@user-pc:~$ curl http://localhost:3128
Hello sweet world
</code>```

Is there a better way to solve this scenario or have I just made a silly mistake?

Title: nodejs yamux stream not ending

Body:
I'm trying to get multiple streams through a single tcp connection using stream multiplexing.

The idea is to have a "tunnel hub" accept tcp connections from clients, and pass http requests to the clients that match the host header.

I'm using yamux-js to handle the muxing/demuxing workload.

const http = require("http");
const net = require("net");
const yamux = require("yamux-js");
const fs = require("fs");
const {pipeline} = require("stream");

const muxerMap = new Map();

// https server receives http request, pipes it to yamux client stream
const webserver = http.createServer(function(req, res) {
    const muxer = muxerMap.get("any"); // TODO: Find muxer associated req.header.host
    if (!muxer) {
        res.writeHead(404);
        return res.end("muxer could not be found\n");
    }
    const muxStream = muxer.open();
    pipeline(req, muxStream, res, (err) => {
        if (err) console.error(err);
    });
});
webserver.listen(3128);

// tcp server receives socket from client and stores it "somewhere"
const tunnelServer = net.createServer();
tunnelServer.on("connection", function(socket) {
    const muxer = new yamux.Client();
    muxer.on("error", err => console.error(err));
    pipeline(muxer, socket, muxer, (err) => {
        if (err) console.error(err);
    });
    muxerMap.set("any", muxer);
});
tunnelServer.listen(3500);

// tcp client connect to tcp server
const socket = net.createConnection(3500);
socket.on("connect", () => {
    const muxer = new yamux.Server(function(muxStream) {
        const fileReadable = fs.createReadStream("hello-world.txt");
        pipeline(fileReadable, muxStream, (err) => {
            if (err) console.error(err);
        });
    });
    pipeline(muxer, socket, muxer, (err) => {
        if (err) console.error(err);
    });
});

My problem is that the http response doesn't get ended, leaving my curl request stuck.

I can verify that the hello-world.txt file read stream, is emitting end events, so somewhere along the wire, that end event isn't "piped" correctly.

user@user-pc:~$ curl http://localhost:3128
Hello sweet world

Is there a better way to solve this scenario or have I just made a silly mistake?


问:
SharePoint list how to show max Revision of same Document in another column
I have a SharePoint list with below columns and values:

```<code>     **Doc**             **Rev**
    Doc-0001               00
    Doc-0001               01
    Doc-0001               02
    Doc-0002               00
    Doc-0002               01
    Doc-0003               00
</code>```

Now I like to have another query results or view or list that shows me below result:

```<code>      **Doc**       **Rev**    **Max Rev**
       Doc-0001       00          02
       Doc-0001       01          02
       Doc-0001       02          02
       Doc-0002       00          01
       Doc-0002       01          01
       Doc-0003       00          00
</code>```

I am not experienced in SharePoint am using SharePoint on promises 2013, I read something about CAML query "https://stackoverflow.com/questions/516073/max-query-using-caml"
But I do not know how to use that in my sample.

Body:
I have a SharePoint list with below columns and values:

     **Doc**             **Rev**
    Doc-0001               00
    Doc-0001               01
    Doc-0001               02
    Doc-0002               00
    Doc-0002               01
    Doc-0003               00

Now I like to have another query results or view or list that shows me below result:

      **Doc**       **Rev**    **Max Rev**
       Doc-0001       00          02
       Doc-0001       01          02
       Doc-0001       02          02
       Doc-0002       00          01
       Doc-0002       01          01
       Doc-0003       00          00

I am not experienced in SharePoint am using SharePoint on promises 2013, I read something about CAML query "https://stackoverflow.com/questions/516073/max-query-using-caml"
But I do not know how to use that in my sample.


问:
Why useMutation onSuccess callback prints stale value?
Can someone explain why the output of following code is 0 and not 666?
I'm assuming onSuccess callback is somehow using stale data, but I don't think that is desirable.

```<code>import "./styles.css";
import { useQuery, useMutation } from "react-query";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const { mutate } = useMutation(
    [count],
    () => {
      return new Promise((resolve) => {
        setTimeout(() => resolve("data"), 5000);
      });
    },
    {
      onSuccess: (data) => {
        console.log(count);
      }
    }
  );

  return (
    <div className="App">
      <button
        onClick={() => {
          mutate();
          setTimeout(() => {
            setCount(666);
          }, 2000);
        }}
      >
        Button
      </button>
    </div>
  );
}

</code>```

I expect onSuccess to use latest value for count state variable

Body:
Can someone explain why the output of following code is 0 and not 666?
I'm assuming onSuccess callback is somehow using stale data, but I don't think that is desirable.

import "./styles.css";
import { useQuery, useMutation } from "react-query";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const { mutate } = useMutation(
    [count],
    () => {
      return new Promise((resolve) => {
        setTimeout(() => resolve("data"), 5000);
      });
    },
    {
      onSuccess: (data) => {
        console.log(count);
      }
    }
  );

  return (

      <button
        onClick={() => {
          mutate();
          setTimeout(() => {
            setCount(666);
          }, 2000);
        }}
      >
        Button
      </button>

  );
}

I expect onSuccess to use latest value for count state variable


问:
Single fetch-request and get multiple response from Server with express
Can someone help me with the easiest way to change my code to receive multiple replies? I want to be able to send multiple images at once.

I have this on the client side:

```<code>fetchUsers.addEventListener("click", function() {
  fetch("http://localhost:3000/users")
    .then(response => response.blob())
    .then(image => {
      var create_img = document.createElement("IMG");
      create_img.setAttribute("src", URL.createObjectURL(image));
      document.getElementById("imageDiv").appendChild(create_img);
      console.log(image);
    });
});
</code>```

And this on the server side:

```<code>app.get("/users", (req, res) => {
  res.set({
    'Content-Type': 'image/png'
  });
  res.sendFile("C:/Users/Pictures/Screenshots/Screenshot.png");
  //res.write("C:/Users/Pictures/Screenshots/Screenshot.png");
  //res.end();
  res.status(200);
});
</code>```

It works if I just send one picture. I would like to be able to send several pictures, but I don't know exactly how the client-server agreement should be, since I'm still a beginner.

Body:
Can someone help me with the easiest way to change my code to receive multiple replies? I want to be able to send multiple images at once.

I have this on the client side:

fetchUsers.addEventListener("click", function() {
  fetch("http://localhost:3000/users")
    .then(response => response.blob())
    .then(image => {
      var create_img = document.createElement("IMG");
      create_img.setAttribute("src", URL.createObjectURL(image));
      document.getElementById("imageDiv").appendChild(create_img);
      console.log(image);
    });
});

And this on the server side:

app.get("/users", (req, res) => {
  res.set({
    'Content-Type': 'image/png'
  });
  res.sendFile("C:/Users/Pictures/Screenshots/Screenshot.png");
  //res.write("C:/Users/Pictures/Screenshots/Screenshot.png");
  //res.end();
  res.status(200);
});

It works if I just send one picture. I would like to be able to send several pictures, but I don't know exactly how the client-server agreement should be, since I'm still a beginner.


问:
Next.js - getStaticProps() + Firestore onSnapshot() = unnecessary pairing?
I'm new to Next and I'm successfully using Firestore database's onSnapshot() like this:

```<code>async function getStaticProps() {
  const collectionRef = collection(db, "featured");
  const q = query(collectionRef, orderBy("timestamp", "desc"));
  const unsubscribe = onSnapshot(
    q,
    (snap) => {
      setData(
        snap.docs.map((doc) => ({
          ...(doc.data() as FeaturedType),
          id: doc.id,
          timestamp: doc.data().timestamp?.toDate().getTime(),
        }))
      );
    },
    (error) => {
      console.log(error.message);
    }
  );
  return unsubscribe;
}
</code>```

My concern is that they are mutually exclusive functions (onSnapshot and getStaticProps) or at least, an unnecessary pairing of functions(?)

I have several static list collections in a Firestore db and I'm doing the above pattern in each list component to pull the data each component needs to map the children ListItem components.

Body:
I'm new to Next and I'm successfully using Firestore database's onSnapshot() like this:

async function getStaticProps() {
  const collectionRef = collection(db, "featured");
  const q = query(collectionRef, orderBy("timestamp", "desc"));
  const unsubscribe = onSnapshot(
    q,
    (snap) => {
      setData(
        snap.docs.map((doc) => ({
          ...(doc.data() as FeaturedType),
          id: doc.id,
          timestamp: doc.data().timestamp?.toDate().getTime(),
        }))
      );
    },
    (error) => {
      console.log(error.message);
    }
  );
  return unsubscribe;
}

My concern is that they are mutually exclusive functions (onSnapshot and getStaticProps) or at least, an unnecessary pairing of functions(?)

I have several static list collections in a Firestore db and I'm doing the above pattern in each list component to pull the data each component needs to map the children ListItem components.


问:
possible reasons for UDP packet loss analysis
I have two servers, namely X and Y. Each has two network interfaces, say x1,x2 and y1,y2. X and Y are in the same LAN via x2 and y2.

X and Y also receives data as UDP packets on x1 and y1, respectively, as multicasts.

There are two copies a C++ application that does the following on both X and Y. Taking X as example, it does:

On thread #1, open a socket that receives the packets on interface x1 in non-blocking mode. In an infinite loop, recvfrom() is called, Then use sendto() on the same socket to forward the data to Y, using the IP address in y2 as target. Finally the data is enqueue to a concurrent queue.

On thread #2, open a socket that receives packets on interface x2 in non-blocking mode. Those packets are forwarded from Y as in 1). Then the data is enqueue to the same concurrent queue mentioned in 1)

On thread #3, the business logic will consume the data in the concurrent queue.

Each thread is bind to a CPU core, so 3 cores in total.

I know UDP is not reliable, but trying to figure out if anything is potentially done wrong in my application or server setting before blaming the hardware or randomness. In particular:

Is sending and receiving on the same socket in the same thread a bad practice? If so, what is a better way?

If the number of packets received in tcpdump and my application is the same, does that make sure that I am not missing packet because I wasted too much time between two recvfrom() calls?

If tcpdump on the sender server captured 100 outbound packets, while the one on the receiver server captured only 95 inbound ones, what can be said about the missing 5 packets? What layer(s) could have they arrived at?

Some attempts and numbers:

tcpdump on x2 and y2 shows that less number of packets are received on y2 than sent from x2, same for the other forwarding direction. In particular, packets from X to Y is more frequent (~10/sec) and larger (256 bytes) than those from Y to X (~5/sec, 192 bytes), and a higher percentage of packets are lost in that direction.

The buffer (from cat /proc/sys/net/core/rmem_default) are both 212992.

netstat -suna shows no increase in numbers of

```<code>packets to unknown port received
packet receive errors
receive buffer errors
send buffer errors
</code>```

under UDP.

Tests with sockperf between x2 and y2 show no packet drops with a setting of higher frequency of messages and throughput.

Body:
I have two servers, namely X and Y. Each has two network interfaces, say x1,x2 and y1,y2. X and Y are in the same LAN via x2 and y2.

X and Y also receives data as UDP packets on x1 and y1, respectively, as multicasts.

There are two copies a C++ application that does the following on both X and Y. Taking X as example, it does:

On thread #1, open a socket that receives the packets on interface x1 in non-blocking mode. In an infinite loop, recvfrom() is called, Then use sendto() on the same socket to forward the data to Y, using the IP address in y2 as target. Finally the data is enqueue to a concurrent queue.

On thread #2, open a socket that receives packets on interface x2 in non-blocking mode. Those packets are forwarded from Y as in 1). Then the data is enqueue to the same concurrent queue mentioned in 1)

On thread #3, the business logic will consume the data in the concurrent queue.

Each thread is bind to a CPU core, so 3 cores in total.

I know UDP is not reliable, but trying to figure out if anything is potentially done wrong in my application or server setting before blaming the hardware or randomness. In particular:

Is sending and receiving on the same socket in the same thread a bad practice? If so, what is a better way?

If the number of packets received in tcpdump and my application is the same, does that make sure that I am not missing packet because I wasted too much time between two recvfrom() calls?

If tcpdump on the sender server captured 100 outbound packets, while the one on the receiver server captured only 95 inbound ones, what can be said about the missing 5 packets? What layer(s) could have they arrived at?

Some attempts and numbers:

tcpdump on x2 and y2 shows that less number of packets are received on y2 than sent from x2, same for the other forwarding direction. In particular, packets from X to Y is more frequent (~10/sec) and larger (256 bytes) than those from Y to X (~5/sec, 192 bytes), and a higher percentage of packets are lost in that direction.

The buffer (from cat /proc/sys/net/core/rmem_default) are both 212992.

netstat -suna shows no increase in numbers of

packets to unknown port received
packet receive errors
receive buffer errors
send buffer errors

under UDP.

Tests with sockperf between x2 and y2 show no packet drops with a setting of higher frequency of messages and throughput.


问:
.htaccess Wildcard Subdomain
what kind of code did i need for a succesfull forward like

request: http://www.domain.com -> http://domain.com - url will stand http://domain.com

request: http://test.domain.com does forward to the same dir like "http://domain.com" but in the url will still stand http://test.domain.com

some code i have

```<code>#RewriteCond %{HTTP_HOST} !^domain.com$ [NC]
#RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://%1.domain.com/$ //<- doesnt work
</code>```

regards

Title: .htaccess Wildcard Subdomain

Body:
what kind of code did i need for a succesfull forward like

request: http://www.domain.com -> http://domain.com - url will stand http://domain.com

request: http://test.domain.com does forward to the same dir like "http://domain.com" but in the url will still stand http://test.domain.com

some code i have

#RewriteCond %{HTTP_HOST} !^domain.com$ [NC]
#RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://%1.domain.com/$ //<- doesnt work

regards


问:
Where is what I'm editing? (Jupyter notebook .ipynb within ArcGIS Pro)
Note: I also asked this at the Esri Community (formerly geonet), but haven't reached the right coders I guess. It relates to using a Jupyter Notebook that accesses arcpy that works both within ArcGIS Pro and within an external IDE (e.g. Jupyter or VS-code). So fair warning: this is not a FOSS-only question, as it assumes you're using arcpy with an ArcGIS license.

I'm trying to find a way to access the path of the notebook file (.ipynb) that I'm currently editing, in a way that would work either in ArcGIS Pro or in an external IDE like Jupyter or VS-code.  What I've done in the past, with ArcGIS Pro 2.8 (and possibly 2.9), is to use os.getcwd()to provide the folder that the current file being edited is in.  This works in an external IDE but doesn't work in ArcGIS Pro anymore.

In Pro, something like the following will work, at least with the default workspace location, to provide the project folder:

os.path.dirname(arcpy.env.workspace)

... and that os.path.dirname() method will of course also work if we know the path for the notebook file itself. However the same method will not work when editing the file with an external IDE like VS-code or Jupyter, since there's no knowledge of the default workspace for the project, and indeed there's no knowledge of the ArcGIS Pro project at all: our file is just sitting in a folder.

I purposefully standardize on editing these notebook files in the project folder (a slightly modified logic would work if I used a 'source' or 'notebooks' folder within the project folder just to keep things organized), to keep things simple for students; they can do things differently if they need to down the road as they get more comfortable. But currently, in ArcGIS Pro 3, os.getcwd() just returns

'C:\WINDOWS\system32'
which is clearly not the project folder, and not where the .ipynb file I'm editing is located.  There are what would seem to be obvious advantages in being able to edit a notebook either in ArcGIS Pro or an external IDE, and go back and forth, but I haven't figured out how to do this in ArcGIS Pro 3.

And here's a typical situation I want to work in both places, to set the workspace to a geodatabase "pen.gdb" in my project folder, thus providing code that is portable within the project folder, and an easy way to create other resources (e.g. geodatabases, folders) within that project folder.

import arcpy, os
projdir = os.getcwd()
arcpy.env.workspace = projdir + "\pen.gdb"

It all boils down to a simple question:  Where is what I'm editing?

As noted above os.getcwd() gets the containing folder of an .ipynb in an external IDE, but not in the Jupyter Notebook environment built into ArcGIS Pro 3. I'm looking for a solution that works the same within Pro as externally, and the above formerly worked in ArcGIS Pro 2.8.


问:
How do I make a choppable tree system with a meshpart instead of a normal part if nothing seems to work with a meshpart, but it does for a normal part
Script in the axe:

```<code>local mouse = game.Players.LocalPlayer:GetMouse()

local cooldown = false

script.Parent.Activated:Connect(function()

    if not cooldown then
        cooldown = true

        script.Parent.Parent.Humanoid:LoadAnimation(script.SwingAnimation):Play()

        game.ReplicatedStorage:WaitForChild("AxeRE"):FireServer(mouse.Target, mouse.Hit)

        wait(1)
        cooldown = false
    end
end)
</code>```

Script in serverscript service:

```<code>local re = game.ReplicatedStorage:WaitForChild("AxeRE")

local cooldown = {}

re.OnServerEvent:Connect(function(player, target, mouseHit)

    if not cooldown[player] and player.Character and target and target.Name == "Trunk" and target:FindFirstChild("Health") and mouseHit then

        local hrp = player.Character.HumanoidRootPart
        local distance = (hrp.Position - target.Position).Magnitude

        if distance <= 5 then
            cooldown[player] = true

            if not target:FindFirstChild("MaxHealth") then
                local maxHealth = Instance.new("IntValue")
                maxHealth.Name = "MaxHealth"
                maxHealth.Value = target.Health.Value
                maxHealth.Parent = target
            end
            local tool = player.Character.Axe
            local dmg = tool.Damage
            target.Health.Value -= dmg.Value

            if target.Health.Value < 1 then

                target.Parent:Destroy()

            end

            wait(1)
            cooldown[player] = false
        end
    end
end)
</code>```

It's for a survival game I'm working on and I have some experience in Lua, but I can't solve a problem I have. It doesn't look that good for now, but I'm working on it

I tried to use it on a tree that uses a meshpart for the trunk, but it won't seem to work. I replaced the meshpart with a normal part and THAT worked, but not the mesh part. The entire tree itself is a model with a meshpart called "Trunk" which has a health value (IntValue). The main issue (I think) is that the health won't lower after each hit

Example: https://youtu.be/woV76QpmxO8

Body:
Script in the axe:

local mouse = game.Players.LocalPlayer:GetMouse()

local cooldown = false

script.Parent.Activated:Connect(function()

    if not cooldown then
        cooldown = true

        script.Parent.Parent.Humanoid:LoadAnimation(script.SwingAnimation):Play()

        game.ReplicatedStorage:WaitForChild("AxeRE"):FireServer(mouse.Target, mouse.Hit)

        wait(1)
        cooldown = false
    end
end)

Script in serverscript service:

local re = game.ReplicatedStorage:WaitForChild("AxeRE")

local cooldown = {}

re.OnServerEvent:Connect(function(player, target, mouseHit)

    if not cooldown[player] and player.Character and target and target.Name == "Trunk" and target:FindFirstChild("Health") and mouseHit then

        local hrp = player.Character.HumanoidRootPart
        local distance = (hrp.Position - target.Position).Magnitude

        if distance <= 5 then
            cooldown[player] = true

            if not target:FindFirstChild("MaxHealth") then
                local maxHealth = Instance.new("IntValue")
                maxHealth.Name = "MaxHealth"
                maxHealth.Value = target.Health.Value
                maxHealth.Parent = target
            end
            local tool = player.Character.Axe
            local dmg = tool.Damage
            target.Health.Value -= dmg.Value

            if target.Health.Value < 1 then

                target.Parent:Destroy()

            end

            wait(1)
            cooldown[player] = false
        end
    end
end)

It's for a survival game I'm working on and I have some experience in Lua, but I can't solve a problem I have. It doesn't look that good for now, but I'm working on it

I tried to use it on a tree that uses a meshpart for the trunk, but it won't seem to work. I replaced the meshpart with a normal part and THAT worked, but not the mesh part. The entire tree itself is a model with a meshpart called "Trunk" which has a health value (IntValue). The main issue (I think) is that the health won't lower after each hit

Example: https://youtu.be/woV76QpmxO8


问:
discord.js bot not responding to command
I have this code everything works but when i write the command !classes nothing is happening
the bot has administrator and I gave him guilds in the scopes but still, nothing i searched here but didn't find anything useful or thing I haven't tried before.
i an using replit and discord.js version 14.7.1

this is the code:

```<code>const { Client, GatewayIntentBits, MessageEmbed } = require('discord.js')

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMessageReactions
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', message => {
  // Check if the message starts with the command prefix
  if (message.content.startsWith('!classes')) {
    // Create the embed
    const embed = new MessageEmbed()
      .setTitle('Classes')
      .addFields(
        { name: 'Class 1', value: 'Description of Class 1' },
        { name: 'Class 2', value: 'Description of Class 2' }
      );

    // Send the embed to the same channel
    message.channel.send(embed).then(async sentMessage => {
      // Wait for a reaction to be added
      const filter = (reaction, user) => ['', ''].includes(reaction.emoji.name) && user.id === message.author.id;
      const collected = await sentMessage.awaitReactions(filter, { max: 1 });
      const reaction = collected.first();

      try {
        // Check which class was selected
        if (reaction.emoji.name === '') {
          // Class 1 was selected
          // Send a message asking for homework and due date
          message.channel.send('Please enter your homework for Class 1:');

          // Wait for a response
          const homeworkFilter = m => m.author.id === message.author.id;
          const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
          const homework = homeworkMessage.first().content;

          message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

          // Wait for a response
          const dateFilter = m => m.author.id === message.author.id;
          const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
          const dueDate = dateMessage.first().content;

          // Send the homework and due date to a different channel
          const homeworkChannel = client.channels.cache.get('channel id');
          homeworkChannel.send(`Homework for Class 1: ${homework}\nDue date: ${dueDate}`);
        } else if (reaction.emoji.name === '') {
          // Class 2 was selected
          // Send a message asking for homework and due date
          message.channel.send('Please enter your homework for Class 2:');

          // Wait for a response
          const homeworkFilter = m => m.author.id === message.author.id;
          const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
          const homework = homeworkMessage.first().content;

          message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

          // Wait for a response
          const dateFilter = m => m.author.id === message.author.id;
          const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
          const dueDate = dateMessage.first().content;

          // Send the homework and due date to a different channel
          const homeworkChannel = client.channels.cache.get('channel id');
          homeworkChannel.send(`Homework for Class 2: ${homework}\nDue date: ${dueDate}`);
        } else {
          // Invalid reaction was added
          message.channel.send('Inv<sub>your text</sub>alid reaction added. Please try again.');
        }
      } catch (error) {
        console.error(error);
      }
    }
    )
  }
});

client.login('token');
</code>```

Body:
I have this code everything works but when i write the command !classes nothing is happening
the bot has administrator and I gave him guilds in the scopes but still, nothing i searched here but didn't find anything useful or thing I haven't tried before.
i an using replit and discord.js version 14.7.1

this is the code:

const { Client, GatewayIntentBits, MessageEmbed } = require('discord.js')

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMessageReactions
  ]
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('messageCreate', message => {
  // Check if the message starts with the command prefix
  if (message.content.startsWith('!classes')) {
    // Create the embed
    const embed = new MessageEmbed()
      .setTitle('Classes')
      .addFields(
        { name: 'Class 1', value: 'Description of Class 1' },
        { name: 'Class 2', value: 'Description of Class 2' }
      );

    // Send the embed to the same channel
    message.channel.send(embed).then(async sentMessage => {
      // Wait for a reaction to be added
      const filter = (reaction, user) => ['', ''].includes(reaction.emoji.name) && user.id === message.author.id;
      const collected = await sentMessage.awaitReactions(filter, { max: 1 });
      const reaction = collected.first();

      try {
        // Check which class was selected
        if (reaction.emoji.name === '') {
          // Class 1 was selected
          // Send a message asking for homework and due date
          message.channel.send('Please enter your homework for Class 1:');

          // Wait for a response
          const homeworkFilter = m => m.author.id === message.author.id;
          const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
          const homework = homeworkMessage.first().content;

          message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

          // Wait for a response
          const dateFilter = m => m.author.id === message.author.id;
          const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
          const dueDate = dateMessage.first().content;

          // Send the homework and due date to a different channel
          const homeworkChannel = client.channels.cache.get('channel id');
          homeworkChannel.send(`Homework for Class 1: ${homework}\nDue date: ${dueDate}`);
        } else if (reaction.emoji.name === '') {
          // Class 2 was selected
          // Send a message asking for homework and due date
          message.channel.send('Please enter your homework for Class 2:');

          // Wait for a response
          const homeworkFilter = m => m.author.id === message.author.id;
          const homeworkMessage = await message.channel.awaitMessages(homeworkFilter, { max: 1 });
          const homework = homeworkMessage.first().content;

          message.channel.send('Please enter the due date for your homework (e.g. "Tomorrow at 3pm"):');

          // Wait for a response
          const dateFilter = m => m.author.id === message.author.id;
          const dateMessage = await message.channel.awaitMessages(dateFilter, { max: 1 });
          const dueDate = dateMessage.first().content;

          // Send the homework and due date to a different channel
          const homeworkChannel = client.channels.cache.get('channel id');
          homeworkChannel.send(`Homework for Class 2: ${homework}\nDue date: ${dueDate}`);
        } else {
          // Invalid reaction was added
          message.channel.send('Invyour textalid reaction added. Please try again.');
        }
      } catch (error) {
        console.error(error);
      }
    }
    )
  }
});

client.login('token');


问:
Issue loading msnodesqlv8 via require
The documentation for msnodesqlv8 npm package uses this syntax for typescript.

```<code>import { SqlClient } from "msnodesqlv8";
const sql: SqlClient = require("msnodesqlv8");
</code>```

See: https://github.com/TimelordUK/node-sqlserver-v8#typescript

However this is the only place in my code where I'm using a require everything else is import ES style.

This works fine for my Azure function on my local machine. However when I upload to Azure it errors, but doesn't give me any reason in the streaming logs. I am using tsc to compile.

When I remove the require line, it works ok. I assume the issue is the require statement. I can't figure out the "ES way" of importing msnodesqlv8.

My preference is just to change this to an import - but not sure whether this is possible.

I guess my fallback is using babel - which seems a bit overkill for this situation.

Any ideas? Or do I have to get it working using Babel?

tsconfig.json

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "strict": false,
  },
  "include": ["**/*"],
  "exclude": ["**/*.test.ts"]
}
</code>```

package.json

```<code>{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "prestart": "npm run build",
    "start": "func start",
    "test": "jest",
    "prepare": "husky install"
  },
  "devDependencies": {
    "@babel/cli": "^7.20.7",
    "@babel/core": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-typescript": "^7.18.6",
    "@jest/globals": "^29.3.1",
    "@types/babel__core": "^7.1.20",
    "@types/jest": "^29.2.4",
    "@types/node": "16.x",
    "babel-jest": "^29.3.1",
    "husky": "^8.0.2",
    "jest": "^29.3.1",
    "ts-jest": "^29.0.3",
    "typescript": "^4.0.0"
  },
  "dependencies": {
    "@azure/functions": "^3.5.0",
    "@ringcentral/sdk": "^4.7.3",
    "date-fns": "^2.29.3",
    "msnodesqlv8": "^3.0.1"
  }
}

</code>```

Title: Issue loading msnodesqlv8 via require

Body:
The documentation for msnodesqlv8 npm package uses this syntax for typescript.

import { SqlClient } from "msnodesqlv8";
const sql: SqlClient = require("msnodesqlv8");

See: https://github.com/TimelordUK/node-sqlserver-v8#typescript

However this is the only place in my code where I'm using a require everything else is import ES style.

This works fine for my Azure function on my local machine. However when I upload to Azure it errors, but doesn't give me any reason in the streaming logs. I am using tsc to compile.

When I remove the require line, it works ok. I assume the issue is the require statement. I can't figure out the "ES way" of importing msnodesqlv8.

My preference is just to change this to an import - but not sure whether this is possible.

I guess my fallback is using babel - which seems a bit overkill for this situation.

Any ideas? Or do I have to get it working using Babel?

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "strict": false,
  },
  "include": ["**/*"],
  "exclude": ["**/*.test.ts"]
}

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "prestart": "npm run build",
    "start": "func start",
    "test": "jest",
    "prepare": "husky install"
  },
  "devDependencies": {
    "@babel/cli": "^7.20.7",
    "@babel/core": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-typescript": "^7.18.6",
    "@jest/globals": "^29.3.1",
    "@types/babel__core": "^7.1.20",
    "@types/jest": "^29.2.4",
    "@types/node": "16.x",
    "babel-jest": "^29.3.1",
    "husky": "^8.0.2",
    "jest": "^29.3.1",
    "ts-jest": "^29.0.3",
    "typescript": "^4.0.0"
  },
  "dependencies": {
    "@azure/functions": "^3.5.0",
    "@ringcentral/sdk": "^4.7.3",
    "date-fns": "^2.29.3",
    "msnodesqlv8": "^3.0.1"
  }
}


问:
Looking for an approach to break a B-spline/Cubic spline into multiple sections
I am self-learning a game developing. The current topic I am learning is about path design. I get some random points and need a good math model to design a smooth path through those points (not necessary to pass all points but in best fitting). I read a book about spline (B-spline and cubic spline) and seems it is a good tool to use them. However, those two splines will get the path throughs the points instead of the best fitting smooth curve. I go research and I found scipy do have a smooth spline interploation may help

```<code>from scipy.interpolate import BSpline, CubicSpline
from scipy.interpolate import splrep
from scipy.interpolate import BPoly
import numpy as np
# x, y are the given points
x = np.array([ 0. ,  1.2,  1.9,  3.2,  5, 6.5])
y = np.array([ 0. ,  2.3,  3. ,  4.3,  2.9, 3.1])
t, c, k = splrep(x, y, s=0.8, k=3) # make it smooth by setting s=0.8

spl = BSpline(t, c, k) # create B-spline

</code>```

The Bspline does help to generate a smooth path. For some reasons, I need to break the path into multiple section of curves. My goal is to change the Bspline into a multiple sections of Bezier curve. So I try the following two approaches found online

I found a question How to create Bezier curves from B-Splines in Sympy? in which someone ask about the same questions. I copy the code from there to below

```<code>import aggdraw
import numpy as np
import scipy.interpolate as si
from PIL import Image

# from https://stackoverflow.com/a/35007804/2849934
def scipy_bspline(cv, degree=3):
    """ cv:       Array of control vertices
        degree:   Curve degree
    """
    count = cv.shape[0]

    degree = np.clip(degree, 1, count-1)
    kv = np.clip(np.arange(count+degree+1)-degree, 0, count-degree)

    max_param = count - (degree * (1-periodic))
    spline = si.BSpline(kv, cv, degree)
    return spline, max_param

# based on https://math.stackexchange.com/a/421572/396192
def bspline_to_bezier(cv):
    cv_len = cv.shape[0]
    assert cv_len >= 4, "Provide at least 4 control vertices"
    spline, max_param = scipy_bspline(cv, degree=3)
    for i in range(1, max_param):
        spline = si.insert(i, spline, 2)
    return spline.c[:3 * max_param + 1]

def draw_bezier(d, bezier):
    path = aggdraw.Path()
    path.moveto(*bezier[0])
    for i in range(1, len(bezier) - 1, 3):
        v1, v2, v = bezier[i:i+3]
        path.curveto(*v1, *v2, *v)
    d.path(path, aggdraw.Pen("black", 2))

cv = np.array([[ 40., 148.], [ 40.,  48.],
               [244.,  24.], [160., 120.],
               [240., 144.], [210., 260.],
               [110., 250.]])

im = Image.fromarray(np.ones((400, 400, 3), dtype=np.uint8) * 255)
bezier = bspline_to_bezier(cv)
d = aggdraw.Draw(im)
draw_bezier(d, bezier)
d.flush()
# show/save im
</code>```

In the code, I don't quite understand what is v1, v2, v = bezier[i:i+3] v1, v2, v, is v1 the start point of the bezier curve, v2 the middle control point and v is the end point? so the bezier curve is always quadratic? I am trying to plot the v1, v2, v for each bezier extracted in the above code as follow, I get something very strange

```<code>    for i in range(1, len(bezier) - 1, 3):
        v1, v2, v = bezier[i:i+3]
        cc = np.array([(v1[0], v1[1]), (v2[0], v2[1]), (v[0], v[1])])
        curve = BPoly(cc[:, None, :], [0,1])
        X = np.linspace(0, 1, 20)
        p = curve(X)
        plt.gca().set_aspect('equal')
        plt.plot(*p.T)
</code>```

Could someone help to explain if anything wrong with the code above?

I have spent long time to figure out how to break the B spline into multiple Bezier curves but no good results, so I try to think of a different way. I use CubicSpline instead so the piecewise polynormial is avaialbe.

```<code>from scipy.interpolate import BSpline, CubicSpline
from scipy.interpolate import splrep
from scipy.interpolate import BPoly
import numpy as np
x = np.array([ 0. ,  1.2,  1.9,  3.2,  5, 6.5])
y = np.array([ 0. ,  2.3,  3. ,  4.3,  2.9, 3.1])
t, c, k = splrep(x, y, s=0.8, k=3)
spl = BSpline(t, c, k)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
xx = np.linspace(0, 6, 500)
ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
ax.plot(x, y, 'rs')

xx = x
yy = spl(xx)

cu = CubicSpline(xx, yy)
plt.plot(xx, yy, 'ko')
for i in range(len(cu.x)-1):
    xs = np.linspace(cu.x[i], cu.x[i+1], 100)
    plt.plot(xs, np.polyval(cu.c[:,i], xs - cu.x[i]))
</code>```

The code does give me a multiple segments but the number of segments depend on the xx I choose. If the xx is very dense, I may end up with so many segements. My goal is to use as less polynormial segments as possible to approach the spline. Could anyone give me some information for any way to do that? Thanks.

Looking for some advice how to apporach the problem

Body:
I am self-learning a game developing. The current topic I am learning is about path design. I get some random points and need a good math model to design a smooth path through those points (not necessary to pass all points but in best fitting). I read a book about spline (B-spline and cubic spline) and seems it is a good tool to use them. However, those two splines will get the path throughs the points instead of the best fitting smooth curve. I go research and I found scipy do have a smooth spline interploation may help

from scipy.interpolate import BSpline, CubicSpline
from scipy.interpolate import splrep
from scipy.interpolate import BPoly
import numpy as np
# x, y are the given points
x = np.array([ 0. ,  1.2,  1.9,  3.2,  5, 6.5])
y = np.array([ 0. ,  2.3,  3. ,  4.3,  2.9, 3.1])
t, c, k = splrep(x, y, s=0.8, k=3) # make it smooth by setting s=0.8

spl = BSpline(t, c, k) # create B-spline

The Bspline does help to generate a smooth path. For some reasons, I need to break the path into multiple section of curves. My goal is to change the Bspline into a multiple sections of Bezier curve. So I try the following two approaches found online

I found a question How to create Bezier curves from B-Splines in Sympy? in which someone ask about the same questions. I copy the code from there to below

import aggdraw
import numpy as np
import scipy.interpolate as si
from PIL import Image

# from https://stackoverflow.com/a/35007804/2849934
def scipy_bspline(cv, degree=3):
    """ cv:       Array of control vertices
        degree:   Curve degree
    """
    count = cv.shape[0]

    degree = np.clip(degree, 1, count-1)
    kv = np.clip(np.arange(count+degree+1)-degree, 0, count-degree)

    max_param = count - (degree * (1-periodic))
    spline = si.BSpline(kv, cv, degree)
    return spline, max_param

# based on https://math.stackexchange.com/a/421572/396192
def bspline_to_bezier(cv):
    cv_len = cv.shape[0]
    assert cv_len >= 4, "Provide at least 4 control vertices"
    spline, max_param = scipy_bspline(cv, degree=3)
    for i in range(1, max_param):
        spline = si.insert(i, spline, 2)
    return spline.c[:3 * max_param + 1]

def draw_bezier(d, bezier):
    path = aggdraw.Path()
    path.moveto(*bezier[0])
    for i in range(1, len(bezier) - 1, 3):
        v1, v2, v = bezier[i:i+3]
        path.curveto(*v1, *v2, *v)
    d.path(path, aggdraw.Pen("black", 2))

cv = np.array([[ 40., 148.], [ 40.,  48.],
               [244.,  24.], [160., 120.],
               [240., 144.], [210., 260.],
               [110., 250.]])

im = Image.fromarray(np.ones((400, 400, 3), dtype=np.uint8) * 255)
bezier = bspline_to_bezier(cv)
d = aggdraw.Draw(im)
draw_bezier(d, bezier)
d.flush()
# show/save im

In the code, I don't quite understand what is v1, v2, v = bezier[i:i+3] v1, v2, v, is v1 the start point of the bezier curve, v2 the middle control point and v is the end point? so the bezier curve is always quadratic? I am trying to plot the v1, v2, v for each bezier extracted in the above code as follow, I get something very strange

    for i in range(1, len(bezier) - 1, 3):
        v1, v2, v = bezier[i:i+3]
        cc = np.array([(v1[0], v1[1]), (v2[0], v2[1]), (v[0], v[1])])
        curve = BPoly(cc[:, None, :], [0,1])
        X = np.linspace(0, 1, 20)
        p = curve(X)
        plt.gca().set_aspect('equal')
        plt.plot(*p.T)

Could someone help to explain if anything wrong with the code above?

I have spent long time to figure out how to break the B spline into multiple Bezier curves but no good results, so I try to think of a different way. I use CubicSpline instead so the piecewise polynormial is avaialbe.

from scipy.interpolate import BSpline, CubicSpline
from scipy.interpolate import splrep
from scipy.interpolate import BPoly
import numpy as np
x = np.array([ 0. ,  1.2,  1.9,  3.2,  5, 6.5])
y = np.array([ 0. ,  2.3,  3. ,  4.3,  2.9, 3.1])
t, c, k = splrep(x, y, s=0.8, k=3)
spl = BSpline(t, c, k)

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
xx = np.linspace(0, 6, 500)
ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
ax.plot(x, y, 'rs')

xx = x
yy = spl(xx)

cu = CubicSpline(xx, yy)
plt.plot(xx, yy, 'ko')
for i in range(len(cu.x)-1):
    xs = np.linspace(cu.x[i], cu.x[i+1], 100)
    plt.plot(xs, np.polyval(cu.c[:,i], xs - cu.x[i]))

The code does give me a multiple segments but the number of segments depend on the xx I choose. If the xx is very dense, I may end up with so many segements. My goal is to use as less polynormial segments as possible to approach the spline. Could anyone give me some information for any way to do that? Thanks.

Looking for some advice how to apporach the problem