问:
Unable to fill PDF fields when FDF contains Kids sections FPDF/FPDM
I can successfully fill PDF forms,but it looks to be breaking when there are Kids sections in them.

E.g. this is the file I'm working with:

```<code>$ pdftk test.pdf dump_data_fields | grep FieldName
FieldName: Text36.0
FieldName: Text36.1
FieldName: Text37.1
FieldName: Text37.0.0
FieldName: Text37.0.1.0
FieldName: Text37.0.1.1
FieldName: Text38
FieldName: Text39.0
...
FieldName: Text41.5.23.1.19.5
FieldName: Text41.5.23.1.19.6
FieldName: Text41.5.23.1.19.7
FieldName: Text41

$ pdftk test.pdf dump_data_fields | grep FieldName | wc -l
402
</code>```

This works:

```<code><?php
require_once 'fpdm-2.9.2/fpdm.php';
$fields = [
    'Text38' => 'Joe'
];
$pdf = new FPDM('test.pdf', 'test.fdf', true);
$pdf->Load($fields);
$pdf->Merge();
$pdf->Output('F', 'test_out.pdf');
</code>```

Output:

```<code>PDF parse

Starting to parse 14336 entries

PDF parse retrieved 1094 refs

Merge info:

26 Field entry values found for 1 field values to fill

Output

Write file test_out.pdf
</code>```

This does not (same code as above, only different field name):

```<code>$fields = [
    'Text36.0' => 'Joe'
];

FPDF-Merge Error: field Text36.0 not found
</code>```

Snip from the FDF file:

```<code>/T (Text41)
>>
<<
/Kids [
<<
/V ()
/T (1)
>>
<<
/V ()
/T (0)
>>]
/T (Text36)
>>
<<
/Kids [
<<
/V ()
/T (1)
>>
<<
/Kids [
<<
/Kids [
<<
/V ()
/T (1)
>>
<<
/V ()
/T (0)
>>]
/T (1)
>>
<<
/V ()
/T (0)
>>]
/T (0)
>>]
/T (Text37)
>>
<<
/V ()
/T (Text38)
>>
<<
/Kids [
<<
/V ()
/T (19)
>>
<<
/V ()
/T (18)
>>
</code>```

So I'm trying to figure out if I'm sending the wrong data in, or if this is a limitation of the FPDM library.

Body:
I can successfully fill PDF forms,but it looks to be breaking when there are Kids sections in them.

E.g. this is the file I'm working with:

$ pdftk test.pdf dump_data_fields | grep FieldName
FieldName: Text36.0
FieldName: Text36.1
FieldName: Text37.1
FieldName: Text37.0.0
FieldName: Text37.0.1.0
FieldName: Text37.0.1.1
FieldName: Text38
FieldName: Text39.0
...
FieldName: Text41.5.23.1.19.5
FieldName: Text41.5.23.1.19.6
FieldName: Text41.5.23.1.19.7
FieldName: Text41

$ pdftk test.pdf dump_data_fields | grep FieldName | wc -l
402

This works:

<?php
require_once 'fpdm-2.9.2/fpdm.php';
$fields = [
    'Text38' => 'Joe'
];
$pdf = new FPDM('test.pdf', 'test.fdf', true);
$pdf->Load($fields);
$pdf->Merge();
$pdf->Output('F', 'test_out.pdf');

Output:

PDF parse

Starting to parse 14336 entries

PDF parse retrieved 1094 refs

Merge info:

26 Field entry values found for 1 field values to fill

Output

Write file test_out.pdf

This does not (same code as above, only different field name):

$fields = [
    'Text36.0' => 'Joe'
];

FPDF-Merge Error: field Text36.0 not found

Snip from the FDF file:

/T (Text41)
>>
<<
/Kids [
<<
/V ()
/T (1)
>>
<<
/V ()
/T (0)
>>]
/T (Text36)
>>
<<
/Kids [
<<
/V ()
/T (1)
>>
<<
/Kids [
<<
/Kids [
<<
/V ()
/T (1)
>>
<<
/V ()
/T (0)
>>]
/T (1)
>>
<<
/V ()
/T (0)
>>]
/T (0)
>>]
/T (Text37)
>>
<<
/V ()
/T (Text38)
>>
<<
/Kids [
<<
/V ()
/T (19)
>>
<<
/V ()
/T (18)
>>

So I'm trying to figure out if I'm sending the wrong data in, or if this is a limitation of the FPDM library.


来源: stackexchange

问:
How to use Excel Code Name in VBA Vlookup
I'm a newbie and create most of my macros by recording, however I have run into an issue.
In this macro I need it to run the exact same way every time - but the sheets it references will be differently named (but always in the same order - so same Code Name).
I have tried all manner of fixes but I can't seem to get this right and end up with a 424 error.

```<code>ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-18],'Sheet2'!C7:C13,7,FALSE)"
</code>```

Sheet2 will have a varied tab name

I have tried:

```<code>ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(B2,'" & Sheet2.Name & "'!H:N,7,FALSE)"
</code>```

and

```<code>ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-18],'" & Sheet2.Name & "'!C[-12]:C[-6],7,FALSE)"
</code>```

I need the formula visible in the cell when individuals are looking at the file.

ContentLicense: CC BY-SA 4.0

Body:
I'm a newbie and create most of my macros by recording, however I have run into an issue.
In this macro I need it to run the exact same way every time - but the sheets it references will be differently named (but always in the same order - so same Code Name).
I have tried all manner of fixes but I can't seem to get this right and end up with a 424 error.

ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-18],'Sheet2'!C7:C13,7,FALSE)"

Sheet2 will have a varied tab name

I have tried:

ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(B2,'" & Sheet2.Name & "'!H:N,7,FALSE)"

and

ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-18],'" & Sheet2.Name & "'!C[-12]:C[-6],7,FALSE)"

I need the formula visible in the cell when individuals are looking at the file.


问:
Opening a URL from a Firebase push notification
I have set up the ability to send and receive APNS through Firebase FCM. However, I would like to add the ability for the the notification to open a url once tapped. Where would I add the URL to the payload, and how will the client side handle said payload? I am really just looking for some syntax help here..

Here is where the payload is created and sent:

```<code>const payload = {
    notification: {
        title: chatRoomTitle,
        body: hostedByName + " is chatting right now.",
    }
};

await admin.messaging().sendToDevice(followerToken, payload);
</code>```

And the client handles the notification with this:

```<code>
@main
struct ChatterApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

    @StateObject var appManager = AppManager()

    var body: some Scene {
        WindowGroup {
            SplashScreen()
                .environmentObject(appManager)
                .onOpenURL(perform: appManager.handleDeepLink(_:))
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        UNUserNotificationCenter.current().delegate = self

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }

        FirebaseApp.configure()
        application.registerForRemoteNotifications()
        Messaging.messaging().delegate = self

        return true
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Firebase registration token: \(String(describing: fcmToken))")

        let dataDict: [String: String] = ["token": fcmToken ?? ""]
        NotificationCenter.default.post(
            name: Notification.Name("FCMToken"),
            object: nil,
            userInfo: dataDict
        )
    }
}

extension AppDelegate {
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)

        var readableToken: String = ""
        for i in 0..<deviceToken.count {
            readableToken += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
        }
        print("Received an APNs device token: \(readableToken)")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error)")
    }
}
</code>```

Body:
I have set up the ability to send and receive APNS through Firebase FCM. However, I would like to add the ability for the the notification to open a url once tapped. Where would I add the URL to the payload, and how will the client side handle said payload? I am really just looking for some syntax help here..

Here is where the payload is created and sent:

const payload = {
    notification: {
        title: chatRoomTitle,
        body: hostedByName + " is chatting right now.",
    }
};

await admin.messaging().sendToDevice(followerToken, payload);

And the client handles the notification with this:

@main
struct ChatterApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

    @StateObject var appManager = AppManager()

    var body: some Scene {
        WindowGroup {
            SplashScreen()
                .environmentObject(appManager)
                .onOpenURL(perform: appManager.handleDeepLink(_:))
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        UNUserNotificationCenter.current().delegate = self

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }

        FirebaseApp.configure()
        application.registerForRemoteNotifications()
        Messaging.messaging().delegate = self

        return true
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Firebase registration token: \(String(describing: fcmToken))")

        let dataDict: [String: String] = ["token": fcmToken ?? ""]
        NotificationCenter.default.post(
            name: Notification.Name("FCMToken"),
            object: nil,
            userInfo: dataDict
        )
    }
}

extension AppDelegate {
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)

        var readableToken: String = ""
        for i in 0..<deviceToken.count {
            readableToken += String(format: "%02.2hhx", deviceToken[i] as CVarArg)
        }
        print("Received an APNs device token: \(readableToken)")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error)")
    }
}


问:
Splash Screen API android apply change unpredictably
When I try to make changes to the splash screen and reinstall the application, the splash does not change.

It's strange that sometimes (the next day) changes are picked up on the first build. It`s really magic that splash stay the same when I change color and reinstall app.

I am debugging on ZTE Benefit M8 Android 7.1.2 (custom firmware).

app module->res folders:

values/splash_theme.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.App.Starting1" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">#069056</item>
        <item name="windowSplashScreenAnimationDuration">1000</item>
        <item name="postSplashScreenTheme">@style/Theme.NextTheme</item>
    </style>
</resources>
</code>```

values-night/splash_theme.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.App.Starting1" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">#ff1212</item>
        <item name="windowSplashScreenAnimationDuration">1000</item>
        <item name="postSplashScreenTheme">@style/Theme.NextTheme</item>
    </style>
</resources>
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="myApp.app.App"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        tools:targetApi="31">

        <activity
            android:name="myApp.presentation.MainActivity"
            android:exported="true"
            android:launchMode="singleTask"
            android:theme="@style/Theme.App.Starting1">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

build.gradle.kts

```<code>plugins {
    id(Dependencies.Plugins.application)
    id(Dependencies.Plugins.kotlin)
    id(Dependencies.Plugins.kapt)
    id(Dependencies.Plugins.serialization)
    id(Dependencies.Plugins.parcelize)
}

android {
    namespace = Config.Namespace.App
    compileSdk = Config.Sdk.compile

    defaultConfig {
        applicationId = Config.applicationId
        minSdk = Config.Sdk.min
        targetSdk = Config.Sdk.target
        versionCode = Config.Versions.code
        versionName = Config.Versions.name

        testInstrumentationRunner = Config.Test.instrumentationRunner
    }

    buildTypes {
        release {
            isMinifyEnabled = Config.Release.minifyEnabled // false
            proguardFiles(
                getDefaultProguardFile(Config.Release.Proguard.name),
                Config.Release.Proguard.rules
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = Config.Kotlin.Options.jvmTarget
    }

    buildFeatures {
        viewBinding = true
    }
}

dependencies {

    implementation(project(":core"))
    implementation(project(":core-ui"))

    implementation(Dependencies.Default.core)
    implementation(Dependencies.Default.appCompat)
    implementation(Dependencies.Default.material)

    //Activity
    implementation(Dependencies.Lifecycle.activity)

    //Fragment
    implementation(Dependencies.Lifecycle.fragment)

    // ViewModel
    implementation(Dependencies.Lifecycle.viewModel)

    // Lifecycle
    implementation(Dependencies.Lifecycle.lifecycle)
    kapt(Dependencies.Lifecycle.lifecycleCompiler)

    //Splash
    implementation(Dependencies.splash) // androidx.core:core-splashscreen:1.0.0
    ...
}

</code>```

MainActivity.kt

```<code> override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.onCreate(savedInstanceState)
        getAppComponent().inject(this)

        binding = ActivityMainBinding.inflate(layoutInflater)
            .apply { setContentView(root) }
</code>```

I try: invalid cache, restart, rebuild, clean, reinstalling dependencies by ./gradlew, reopen studio, delete app on device, rename splash theme, reconnect device with usb.

Body:
When I try to make changes to the splash screen and reinstall the application, the splash does not change.

It's strange that sometimes (the next day) changes are picked up on the first build. It`s really magic that splash stay the same when I change color and reinstall app.

I am debugging on ZTE Benefit M8 Android 7.1.2 (custom firmware).

app module->res folders:

values/splash_theme.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

values-night/splash_theme.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name="myApp.app.App"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        tools:targetApi="31">

        <activity
            android:name="myApp.presentation.MainActivity"
            android:exported="true"
            android:launchMode="singleTask"
            android:theme="@style/Theme.App.Starting1">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

build.gradle.kts

plugins {
    id(Dependencies.Plugins.application)
    id(Dependencies.Plugins.kotlin)
    id(Dependencies.Plugins.kapt)
    id(Dependencies.Plugins.serialization)
    id(Dependencies.Plugins.parcelize)
}

android {
    namespace = Config.Namespace.App
    compileSdk = Config.Sdk.compile

    defaultConfig {
        applicationId = Config.applicationId
        minSdk = Config.Sdk.min
        targetSdk = Config.Sdk.target
        versionCode = Config.Versions.code
        versionName = Config.Versions.name

        testInstrumentationRunner = Config.Test.instrumentationRunner
    }

    buildTypes {
        release {
            isMinifyEnabled = Config.Release.minifyEnabled // false
            proguardFiles(
                getDefaultProguardFile(Config.Release.Proguard.name),
                Config.Release.Proguard.rules
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = Config.Kotlin.Options.jvmTarget
    }

    buildFeatures {
        viewBinding = true
    }
}

dependencies {

    implementation(project(":core"))
    implementation(project(":core-ui"))

    implementation(Dependencies.Default.core)
    implementation(Dependencies.Default.appCompat)
    implementation(Dependencies.Default.material)

    //Activity
    implementation(Dependencies.Lifecycle.activity)

    //Fragment
    implementation(Dependencies.Lifecycle.fragment)

    // ViewModel
    implementation(Dependencies.Lifecycle.viewModel)

    // Lifecycle
    implementation(Dependencies.Lifecycle.lifecycle)
    kapt(Dependencies.Lifecycle.lifecycleCompiler)

    //Splash
    implementation(Dependencies.splash) // androidx.core:core-splashscreen:1.0.0
    ...
}

MainActivity.kt

 override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.onCreate(savedInstanceState)
        getAppComponent().inject(this)

        binding = ActivityMainBinding.inflate(layoutInflater)
            .apply { setContentView(root) }

I try: invalid cache, restart, rebuild, clean, reinstalling dependencies by ./gradlew, reopen studio, delete app on device, rename splash theme, reconnect device with usb.


问:
three.js create square with ellipse cut out from opposing corners
I want to create a path that I can extrude that would be the equivalent of the difference of a square and a circle with radius equal to the side of the square with its center at the upper right corner of the square.</p>


问:
How to handle likes with Firestore in flutter
My goal is to handle "likes" on items in my app like so: a given user can toggle his like on a given item.

So I created a collection "Likes" with two properties:

adId as a string

userId as a string

For a userId to like an adId consists in adding a document in the collection.

But because having multiple (adId, userId) document is nonsense, I'd like to handle the unicity of the document.

How to do this efficiently?

What I initially planned to do is write a toggle() function like so:

class Ad {

  /// The ad ID
  String id;

  /// Toggle like and returns the document [id].
  void toggle({required String userId}) async {
    // Don't let users like their own ads
    //if (ad.ownerUid == loggedUser?.uid) return null;

    // = Actually store the document
    final snapshots = await FirebaseFirestore.instance
        .collection(collectionName)
        .where("adId", isEqualTo: ad.id)
        .where("userId", isEqualTo: userId)
        .get();

    final docs = snapshots.docs;
    if (docs.isEmpty) {
      // = Actually store the document
      await FirebaseFirestore.instance
          .collection(collectionName)
          .add({"adId": ad.id, "userId": userId, "on": Timestamp.now()});
    } else {
      for (final doc in docs) {
        await FirebaseFirestore.instance
            .collection(collectionName)
            .doc(doc.id)
            .delete();
      }
    }
  }
}
```


问:
How to use laravel-jsvalidation with vite
I had been using laravel-jsvalidation with mix, but now am trying to upgrade to vite. The problem is that vite only packages modules, and laravel-jsvalidation is not one.

For example, in order for laravel-jsvalidation to work, you must include the following items in the blade.

```<code>  <script src="{{ asset('vendor/jsvalidation/js/jsvalidation.js') }}"></script>
  {!! JsValidator::formRequest('App\Http\Requests\NewPatientQuickRequest') !!}
</code>```

The first line (jsvalidation.js) depends on jQuery by using $.extend( $.fn, ...). The second line depends on the jsvalidation.js script and renders into something like .

So, the problem is that if jsvalidation.js is loaded as a module (i.e. with <scriot type="module"), the JsValidator is out of scope, and I get Uncaught TypeError: Cannot read properties of undefined (reading 'apply')

I even tried sidestepping the whole vite process by including the scripts directly. Doesn't work.

```<code>  <script src="/js/jquery-3.6.3.min.js"></script>
  <script src="/js/jquery-ui-1.13.2/jquery-ui.js"></script>
  <script type="module" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js') }}"></script>
  {!! JsValidator::formRequest('App\Http\Requests\NewPatientQuickRequest') !!}

</code>```

Has anyone got this working?

Body:
I had been using laravel-jsvalidation with mix, but now am trying to upgrade to vite. The problem is that vite only packages modules, and laravel-jsvalidation is not one.

For example, in order for laravel-jsvalidation to work, you must include the following items in the blade.

  {!! JsValidator::formRequest('App\Http\Requests\NewPatientQuickRequest') !!}

The first line (jsvalidation.js) depends on jQuery by using $.extend( $.fn, ...). The second line depends on the jsvalidation.js script and renders into something like .

So, the problem is that if jsvalidation.js is loaded as a module (i.e. with <scriot type="module"), the JsValidator is out of scope, and I get Uncaught TypeError: Cannot read properties of undefined (reading 'apply')

I even tried sidestepping the whole vite process by including the scripts directly. Doesn't work.

  {!! JsValidator::formRequest('App\Http\Requests\NewPatientQuickRequest') !!}

Has anyone got this working?


问:
Group by the same ID Datafrem PANDAS PYTHON
I'm just starting out in the world of python programming. I have this database:

```<code>INVOICE STOCK_CODE
0015    STIO1
0015    TUY02
0016    BVV01
0017    DFG04
0017    AAA03
0017    STI01
</code>```

and I would like to be able to transform the dataframe in this way:

```<code>INVOICE PROD_1 PROD_2 PROD_3
0015    STI01  TUY02  N/A
0016    BVV01  N/A    N/A
0017    DFG04  AAA03  STI01
</code>```

For your comments, thank you!

Body:
I'm just starting out in the world of python programming. I have this database:

INVOICE STOCK_CODE
0015    STIO1
0015    TUY02
0016    BVV01
0017    DFG04
0017    AAA03
0017    STI01

and I would like to be able to transform the dataframe in this way:

INVOICE PROD_1 PROD_2 PROD_3
0015    STI01  TUY02  N/A
0016    BVV01  N/A    N/A
0017    DFG04  AAA03  STI01

For your comments, thank you!


问:
Can I make an InputView in light mode transparent, like in dark mode?
I'm using a UIPickerView as InputView and in dark mode it has transparency (low alpha?), but in light mode it's just plain grey. Is it possible to make the background transparent in light mode as well?

Setting a backgroundColor for the inputView works fine, but setting the colors alpha just makes it show the grey area behind the color.


问:
Add a submenu to a distill rmarkdown website?
I am creating a distill website using rmarkdown and would like to add a submenu in the navigation bar. I found this feature request/issue on GitHub but have not been able to find a solution.

With the below _site.yml and index.Rmd the submenu text appears in the menu dropdown but is greyed-out and not clickable/selectable.

_site.yml:

```<code>name: "submenuTest"
title: "Submenu test"
description: |
  Submenu test
output_dir: "_site"
navbar:
  right:
    - text: "Home"
      href: index.html
    - text: 'Menu'
      menu:
      - text: 'Page'
        href: page.html
      - text: 'Submenu'
        menu:
        - text: 'Sub Page'
          href: subpage.html
output: distill::distill_article
</code>```

index.Rmd:

```<code>---
title: "Submenu test"
description: |
  Welcome to the website. I hope you enjoy it!
site: distill::distill_website
---

# here is my page content
</code>```

In a plain rmarkdown .html (can use the above .yml and .Rmd examples but without the output: distill::distill_article and site: distill::distill_website lines) renders with a workable submenu.

Body:
I am creating a distill website using rmarkdown and would like to add a submenu in the navigation bar. I found this feature request/issue on GitHub but have not been able to find a solution.

With the below _site.yml and index.Rmd the submenu text appears in the menu dropdown but is greyed-out and not clickable/selectable.

_site.yml:

name: "submenuTest"
title: "Submenu test"
description: |
  Submenu test
output_dir: "_site"
navbar:
  right:
    - text: "Home"
      href: index.html
    - text: 'Menu'
      menu:
      - text: 'Page'
        href: page.html
      - text: 'Submenu'
        menu:
        - text: 'Sub Page'
          href: subpage.html
output: distill::distill_article

index.Rmd:

---
title: "Submenu test"
description: |
  Welcome to the website. I hope you enjoy it!
site: distill::distill_website
---

# here is my page content

In a plain rmarkdown .html (can use the above .yml and .Rmd examples but without the output: distill::distill_article and site: distill::distill_website lines) renders with a workable submenu.


问:
I need some help to make the Videojs video player buttons navigable with the javascript Spatial Navigation plugin
I'm creating a website that can be navigable from the keyboard.
I use the great Spatial navigation here:
https://github.com/luke-chang/js-spatial-navigation

Everything work well with my keyboard navigation with this navigation plugin but after hours and days i still can't navigate these Video js buttons and i don't understand why.

I did a little example here one Codepen and it still not working.
https://codepen.io/onigetoc/pen/MWBowmg

I use the videojs seek to add forward and rewind buttons.
I will also use the videojs hotkeys plugin but for now, i try to make my player navigable with the arrow keyboard.

I absolutely want to use the Spatial Navigation plugin. (It's not a Videojs plugin at all).

```<code>var SN = SpatialNavigation;
SN.init();

// SN.set({
//   straightOnly: true
// });

SN.add("playerview", {
  selector: "#content_video"
  //        defaultElement: '#vplayer',
  //        defaultElement: '#mediaOptionsContainer .item:first-child',
  //        defaultElement: '#media-options-container .item:first-child',
  //        enterTo: '#media-options-container .item:first-child',
  //        straightOnly: false,
  //          rememberSource: true,
  //enterTo: 'last-focused'
});

SN.add("playcontrols", {
  //    selector: '.vjs-control-bar .vjs-control',
  //  selector: '.vjs-control-bar button',
  //  selector: ".video-js button",
  selector: ".vjs-control-bar .vjs-button",
  defaultElement: ".vjs-play-control"
  //        defaultElement: '.vjs-play-control',
  //        enterTo: 'button',
  //        straightOnly: true,
  //        leaveFor: {
  //            right: '',
  //            up: '',
  //            down: '@playerview',
  //            left: ''
  //        }
});

SN.makeFocusable();

var player = videojs("content_video", {
        plugins: {
//          hotkeys: {
//              volumeStep: 0.1,
//              seekStep: 30,
//              enableModifiersForNumbers: false
//          },
            seekButtons: {
       backIndex: 0,
       forward: 30,
       back: 10
     },
        },
});

player.on("ready", function () {
  player.vhs = null;

  setTimeout(() => {

    /*** ADD TABINDEX TO BUTTONS IF NEEDED ***/
    // $('.vjs-control .vjs-button').attr('tabindex', '-1');
    //  $("#player-view").find(".vjs-button").attr("tabindex", "-1");
    // $("#content_video").find(".vjs-button").attr("tabindex", "-1");

    SN.makeFocusable();
    // SN.focus('playerview'); // FOR OTHER PURPOSE I NEED THIS
    SN.focus("playcontrols"); // FOCUS ON THE PLAY BUTTON AT READY
  }, 700);
});
</code>```

Body:
I'm creating a website that can be navigable from the keyboard.
I use the great Spatial navigation here:
https://github.com/luke-chang/js-spatial-navigation

Everything work well with my keyboard navigation with this navigation plugin but after hours and days i still can't navigate these Video js buttons and i don't understand why.

I did a little example here one Codepen and it still not working.
https://codepen.io/onigetoc/pen/MWBowmg

I use the videojs seek to add forward and rewind buttons.
I will also use the videojs hotkeys plugin but for now, i try to make my player navigable with the arrow keyboard.

I absolutely want to use the Spatial Navigation plugin. (It's not a Videojs plugin at all).

var SN = SpatialNavigation;
SN.init();

// SN.set({
//   straightOnly: true
// });

SN.add("playerview", {
  selector: "#content_video"
  //        defaultElement: '#vplayer',
  //        defaultElement: '#mediaOptionsContainer .item:first-child',
  //        defaultElement: '#media-options-container .item:first-child',
  //        enterTo: '#media-options-container .item:first-child',
  //        straightOnly: false,
  //          rememberSource: true,
  //enterTo: 'last-focused'
});

SN.add("playcontrols", {
  //    selector: '.vjs-control-bar .vjs-control',
  //  selector: '.vjs-control-bar button',
  //  selector: ".video-js button",
  selector: ".vjs-control-bar .vjs-button",
  defaultElement: ".vjs-play-control"
  //        defaultElement: '.vjs-play-control',
  //        enterTo: 'button',
  //        straightOnly: true,
  //        leaveFor: {
  //            right: '',
  //            up: '',
  //            down: '@playerview',
  //            left: ''
  //        }
});

SN.makeFocusable();

var player = videojs("content_video", {
        plugins: {
//          hotkeys: {
//              volumeStep: 0.1,
//              seekStep: 30,
//              enableModifiersForNumbers: false
//          },
            seekButtons: {
       backIndex: 0,
       forward: 30,
       back: 10
     },
        },
});

player.on("ready", function () {
  player.vhs = null;

  setTimeout(() => {

    /*** ADD TABINDEX TO BUTTONS IF NEEDED ***/
    // $('.vjs-control .vjs-button').attr('tabindex', '-1');
    //  $("#player-view").find(".vjs-button").attr("tabindex", "-1");
    // $("#content_video").find(".vjs-button").attr("tabindex", "-1");

    SN.makeFocusable();
    // SN.focus('playerview'); // FOR OTHER PURPOSE I NEED THIS
    SN.focus("playcontrols"); // FOCUS ON THE PLAY BUTTON AT READY
  }, 700);
});


问:
Can not seem to add 2 different animations to Animated.Image in react native
I have a bit of code that displays an image and when the image is clicked, it spins round to the right and if clicked again it spins round to the left. All is working but I have added another animation. I am not getting any errors but it does not seem to be doing anything?

What I am aiming for is when it is clicked on it bounces in and out as well as spinning.

All the code is there that sort of works. I am not asking anyone to do this and say I have not tried anything but I have tried so many different things and this way is the only way I am not getting errors. The new animation is called animate and I have added it to the function.

Any help would be greatly appreciated.

All the code:

```<code>import React, { useRef, useState, useCallback } from 'react';
import {
  View,
  StyleSheet,
  Animated,
  Image,
  TouchableOpacity,
  Easing,
  TouchableWithoutFeedback,
} from 'react-native';
import Constants from 'expo-constants';

 const TabIcon = ({ onPress, menuToggled }) => {
    const logoStyles = [styles.logoStyle];

    const animation = useRef(new Animated.Value(menuToggled ? 0 : 1)).current;

    const startAnimation = () => {
      Animated.timing(animation, {
        toValue: menuToggled ? 1 :0,
        duration: 5500,
             friction:2,
      tension:10,
      easing: Easing.in(Easing.bounce),
        useNativeDriver: true,
      }).start();
    };

    const rotateInterpolate = animation.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg'],
    });
    const animatedStyles = { transform: [{ rotate: rotateInterpolate }] };
    logoStyles.push(animatedStyles);
    return (
      <TouchableWithoutFeedback
        onPress={() => {
          startAnimation();
          onPress?.();
        }}>
        <Animated.View style={animatedStyles}>
          <Animated.Image
            style={styles.tinyLogo}
            source={{
              uri: 'https://reactnative.dev/img/tiny_logo.png',
            }}
          />
        </Animated.View>
      </TouchableWithoutFeedback>
    );
  };

const App = () => {
  const spinValue = useRef(new Animated.Value(0)).current;
  const [menuToggled, setMenuToggled] = useState(null);

let opacity = new Animated.Value(0);

  const animate = () => {
    opacity.setValue(0);
    Animated.timing(opacity, {
      toValue: 1,
      duration: 1200,
      easing: Easing.bounce,
      useNativeDriver: true,
    }).start();
  };

  const size = opacity.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 80],
  });

  const animatedStyles = [
    {
      opacity,
      width: size,
      height: size,
    },
  ];

  return (
    <View style={styles.container}>
      <TabIcon
        onPress={() => setMenuToggled((prev) => !prev)}
        menuToggled={menuToggled}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  tinyLogo: {
    width: 150,
    height: 150,
    borderRadius: 100,
    margin: 28,
  },
});

export default App;
</code>```

Body:
I have a bit of code that displays an image and when the image is clicked, it spins round to the right and if clicked again it spins round to the left. All is working but I have added another animation. I am not getting any errors but it does not seem to be doing anything?

What I am aiming for is when it is clicked on it bounces in and out as well as spinning.

All the code is there that sort of works. I am not asking anyone to do this and say I have not tried anything but I have tried so many different things and this way is the only way I am not getting errors. The new animation is called animate and I have added it to the function.

Any help would be greatly appreciated.

All the code:

import React, { useRef, useState, useCallback } from 'react';
import {
  View,
  StyleSheet,
  Animated,
  Image,
  TouchableOpacity,
  Easing,
  TouchableWithoutFeedback,
} from 'react-native';
import Constants from 'expo-constants';

 const TabIcon = ({ onPress, menuToggled }) => {
    const logoStyles = [styles.logoStyle];

    const animation = useRef(new Animated.Value(menuToggled ? 0 : 1)).current;

    const startAnimation = () => {
      Animated.timing(animation, {
        toValue: menuToggled ? 1 :0,
        duration: 5500,
             friction:2,
      tension:10,
      easing: Easing.in(Easing.bounce),
        useNativeDriver: true,
      }).start();
    };

    const rotateInterpolate = animation.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '360deg'],
    });
    const animatedStyles = { transform: [{ rotate: rotateInterpolate }] };
    logoStyles.push(animatedStyles);
    return (
      <TouchableWithoutFeedback
        onPress={() => {
          startAnimation();
          onPress?.();
        }}>
        <Animated.View style={animatedStyles}>
          <Animated.Image
            style={styles.tinyLogo}
            source={{
              uri: 'https://reactnative.dev/img/tiny_logo.png',
            }}
          />
        </Animated.View>
      </TouchableWithoutFeedback>
    );
  };

const App = () => {
  const spinValue = useRef(new Animated.Value(0)).current;
  const [menuToggled, setMenuToggled] = useState(null);

let opacity = new Animated.Value(0);

  const animate = () => {
    opacity.setValue(0);
    Animated.timing(opacity, {
      toValue: 1,
      duration: 1200,
      easing: Easing.bounce,
      useNativeDriver: true,
    }).start();
  };

  const size = opacity.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 80],
  });

  const animatedStyles = [
    {
      opacity,
      width: size,
      height: size,
    },
  ];

  return (
    <View style={styles.container}>
      <TabIcon
        onPress={() => setMenuToggled((prev) => !prev)}
        menuToggled={menuToggled}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  tinyLogo: {
    width: 150,
    height: 150,
    borderRadius: 100,
    margin: 28,
  },
});

export default App;


问:
Dash Navbar component with image
I'm trying to add an image to a NavBarSimple with Dash and I want it to be aligned with the title of the brand attribute "Dashboard".
How can I align the image at the left of the brand while the other pages stay at the left?
Thanks in advance</p>
```<code>def Navbar():
 layout = dbc.NavbarSimple(
  children=\[
     dbc.NavItem(html.Img(src = "99.Imagenes/logo.png", height= "50px")),
     dbc.NavItem(dbc.NavLink("Inicio", href="/page1")),
     dbc.NavItem(dbc.NavLink("Resultados detallados", href = "/page2")),
     dbc.NavItem(dbc.NavLink("Subir archivos", href = "/page3")),
     dbc.NavItem(dbc.NavLink("Ejecutar cálculo", href="/page4"))
  \] ,
  brand= "Dashboard",
  brand_href="/page1",
  dark=True,
  className= "ml_auto")
 return layout
</code>```

Title: Dash Navbar component with image

Body:
I'm trying to add an image to a NavBarSimple with Dash and I want it to be aligned with the title of the brand attribute "Dashboard".
How can I align the image at the left of the brand while the other pages stay at the left?
Thanks in advance

def Navbar():
 layout = dbc.NavbarSimple(
  children=\[
     dbc.NavItem(html.Img(src = "99.Imagenes/logo.png", height= "50px")),
     dbc.NavItem(dbc.NavLink("Inicio", href="/page1")),
     dbc.NavItem(dbc.NavLink("Resultados detallados", href = "/page2")),
     dbc.NavItem(dbc.NavLink("Subir archivos", href = "/page3")),
     dbc.NavItem(dbc.NavLink("Ejecutar cálculo", href="/page4"))
  \] ,
  brand= "Dashboard",
  brand_href="/page1",
  dark=True,
  className= "ml_auto")
 return layout


问:
Peak Valley filter for signals
I'm trying to develop a peak valley filter function in python. The function is to receive a time history as input and a prescribe delta . The intermediate values between peaks and valleys need to eliminated based on delta. below an example signal that has been filtered (circled values are retained the rest is thrown out). enter image description here

The code i developed detects all peaks and valleys but not sure how to proceed with eliminating intermediate signals.

```<code>def peak_valley(time_series, delta):
peaks = []
valleys = []

# detecting peaks and valleys thru the time history
if time_series [0] > time_series[1] :

    peaks.append((time_series[0], 0))
elif time_series [0] < time_series[1]:
    valleys.append((time_series[0], 0))

if time_series [-1] > time_series[-2]:

    peaks.append((time_series[-1], len(time_series) - 1))
elif time_series [-1] < time_series[-2]:

    valleys.append((time_series[-1], len(time_series) - 1))

for i in range(1, len(time_series) - 1):
    print(time_series[i])
    if time_series[i] > time_series[i-1] and (time_series[i] > time_series[i+1] or time_series[i] == time_series[i+1]):
        peaks.append((time_series[i],i))
        print("found a peak")
    elif time_series[i] < time_series[i-1] and (time_series[i] < time_series[i+1] or time_series[i]== time_series[i+1]):
        valleys.append((time_series[i],i))
        print("found a valley")
return peaks,valleys
</code>```

please advice how i can proceed with the function so i can produce filtering like the pic provided above

Title: Peak Valley filter for signals

Body:
I'm trying to develop a peak valley filter function in python. The function is to receive a time history as input and a prescribe delta . The intermediate values between peaks and valleys need to eliminated based on delta. below an example signal that has been filtered (circled values are retained the rest is thrown out). enter image description here

The code i developed detects all peaks and valleys but not sure how to proceed with eliminating intermediate signals.

def peak_valley(time_series, delta):
peaks = []
valleys = []

# detecting peaks and valleys thru the time history
if time_series [0] > time_series[1] :

    peaks.append((time_series[0], 0))
elif time_series [0] < time_series[1]:
    valleys.append((time_series[0], 0))

if time_series [-1] > time_series[-2]:

    peaks.append((time_series[-1], len(time_series) - 1))
elif time_series [-1] < time_series[-2]:

    valleys.append((time_series[-1], len(time_series) - 1))

for i in range(1, len(time_series) - 1):
    print(time_series[i])
    if time_series[i] > time_series[i-1] and (time_series[i] > time_series[i+1] or time_series[i] == time_series[i+1]):
        peaks.append((time_series[i],i))
        print("found a peak")
    elif time_series[i] < time_series[i-1] and (time_series[i] < time_series[i+1] or time_series[i]== time_series[i+1]):
        valleys.append((time_series[i],i))
        print("found a valley")
return peaks,valleys

please advice how i can proceed with the function so i can produce filtering like the pic provided above


问:
Uncaught TypeError: Cannot read properties of null when trying to addEventListener to imported button
I'm trying to have a button update the HTML within my iframe when it's clicked but am having trouble. The way I've tried to go about it is to export my button from one JS file and then import it within another so that I can add an event listener that updates the iframe HTML when the button is clicked. However, when I try and add the event listener, I'm getting the following error:

```<code>Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at eval (userResume.js:5:55)
    at ./src/userResume.js (userResume.js:79:1)
    at __webpack_require__ (userResume.js:183:41)
    at userResume.js:235:37
    at userResume.js:237:12
eval @ userResume.js:5
./src/userResume.js @ userResume.js:79
__webpack_require__ @ userResume.js:183
(anonymous) @ userResume.js:235
(anonymous) @ userResume.js:237
</code>```

If it helps, I'm using webpack for this build.

Here is the button and iframe in question, within aboutYou.html:

```<code><button id="generateButton" class="bg-blue-500 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded inline-flex items-center">
                    <span>Generate Resume →</span>
</button>

<iframe class="w-full h-5/6" src="userResume.html"></iframe>
</code>```

and at the bottom of aboutYou.html:

```<code><script src="./aboutYou.js"></script>
</code>```

aboutYou.js:

```<code>let generateButton = document.querySelector('#generateButton')
export {generateButton};
</code>```

The HTML I'm trying to update, within userResume.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body contenteditable='true' class="content">
    <br />
    <h2 style="text-align: center">Resume Content Here </h2>
    <script src="./userResume.js"></script>
  </body>
</html>
</code>```

userResume.js:

```<code>import { generateButton } from "./aboutYou";

generateButton.addEventListener('click', function replaceBody(){
    let content = "test";
    document.getElementsByTagName('body')[0].innerHTML = content;
})
</code>```

Body:
I'm trying to have a button update the HTML within my iframe when it's clicked but am having trouble. The way I've tried to go about it is to export my button from one JS file and then import it within another so that I can add an event listener that updates the iframe HTML when the button is clicked. However, when I try and add the event listener, I'm getting the following error:

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at eval (userResume.js:5:55)
    at ./src/userResume.js (userResume.js:79:1)
    at __webpack_require__ (userResume.js:183:41)
    at userResume.js:235:37
    at userResume.js:237:12
eval @ userResume.js:5
./src/userResume.js @ userResume.js:79
__webpack_require__ @ userResume.js:183
(anonymous) @ userResume.js:235
(anonymous) @ userResume.js:237

If it helps, I'm using webpack for this build.

Here is the button and iframe in question, within aboutYou.html:

<button id="generateButton" class="bg-blue-500 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded inline-flex items-center">
                    Generate Resume →
</button>

and at the bottom of aboutYou.html:

aboutYou.js:

let generateButton = document.querySelector('#generateButton')
export {generateButton};

The HTML I'm trying to update, within userResume.html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Resume Content Here

userResume.js:

import { generateButton } from "./aboutYou";

generateButton.addEventListener('click', function replaceBody(){
    let content = "test";
    document.getElementsByTagName('body')[0].innerHTML = content;
})


问:
I would like to plot a pie chart from my pandas dataframe
I would like to plot a pie chart from my pandas data Frame of customer buying behaviours

PREMIUM_CUSTOMER
TOT_SALES

Mainstream
750744.50

Budget
676211.55

Premium
507458.95

This is my code so far

plt.style.use("fivethirtyeight")
labels = ['Mainstream','Budget','Premium']
df_customer.plt.pie("PREMIUM_CUSTOMER","TOT_SALES",labels=labels,wedgeprops={'edgecolor':'black'}, shadow = True,startangle =90, autopct='%1.11f%%')
plt.title("Percentage of sales to customer types ")
plt.tight_layout()
plt.show()
```


问:
TailwindCSS doesn't purge plugin classes
I was trying to reduce the size of my CSS file using Tailwind's in-house compiler. This is my config file:

module.exports = {

  content: ["./pages/*.html", "./components/**/*", "./src/*"],

  mode: "jit",

  plugins: [
    require("tailwindcss"),
    require("tw-elements/dist/plugin"),
    require('tailwind-scrollbar')({ nocompatible: true }),
    function ({ addVariant }) {
      addVariant("child", "& > *");
      addVariant("child-hover", "& > *:hover");
    },
  ],
  },
};

```

I have checked that the directories specified in content don't contain any hidden classes, however, it seems that Tailwind includes every class from the package tw-elements and doesn't purge them.

Is there any way how I can get a clean CSS file?

Many thanks for your help!

Body:
I was trying to reduce the size of my CSS file using Tailwind's in-house compiler. This is my config file:

module.exports = {

  content: ["./pages/*.html", "./components/**/*", "./src/*"],

  mode: "jit",

  plugins: [
    require("tailwindcss"),
    require("tw-elements/dist/plugin"),
    require('tailwind-scrollbar')({ nocompatible: true }),
    function ({ addVariant }) {
      addVariant("child", "& > *");
      addVariant("child-hover", "& > *:hover");
    },
  ],
  },
};

I have checked that the directories specified in content don't contain any hidden classes, however, it seems that Tailwind includes every class from the package tw-elements and doesn't purge them.

Is there any way how I can get a clean CSS file?

Many thanks for your help!


问:
What http codes are by default considered if we use @HystrixCommand
If we use the annotation @HystrixCommand with just 4 properties, namely, timeoutInMilliseconds, requestVolumeThreshold, errorThresholdPercentage and sleepWindowInMilliSeconds, then what HTTP response codes are considered by hystrix by default to trigger the timeout?

Is it possible to mention the HTTP response codes in any of the hystrix command properties on which you want to trigger the timeout?


问:
export imagepath from api mapping to use the right image when image is in fullscreen
I have a grid of images that get displayed by mapping the imagepath from an API (mongodb), I want to create a clickevent on each image which will open the image in fullscreen. When clicked it opens a new div that should contain the image with the correct path, so the path of the image that was clicked. I have this code at the moment.

```<code>const [showModal, setShowModal] = useState(false)
</code>```

function handleClick() {

```<code>setShowModal(true);

const previews = document.querySelectorAll(`.${styles.photo} img` );
const original = document.querySelector(`.${styles.fullimg}`)

console.log(original);
previews.forEach(preview => {
  preview.addEventListener('click', () => {
    data.map((date) => {
      const originalSrc = preview.getAttribute("data-original");
      //original.src = `./image/space/${originalSrc}`;
      console.log(originalSrc);
      //console.log(original.src);
    })
  });
});

console.log("clicked");
</code>```

}

```<code>        {data.map((datas) => {
      return (
      <li className={styles.li}key={datas._id}>
      <div className = {styles.photo} onClick={handleClick}>
        <img className = {styles.img} src={`/image/space/${datas.imagepath}`}  loading="lazy" data-original={datas.imagepath}/>
      </div>
      </li>
      );
      })}
    </div>
    </div>
    </ul>
  </section>
  {showModal ? (
        <div className={styles.modal} onClick={() => setShowModal(false)}>
          <img src='' className={styles.fullimg}/>
        </div>
  ) : null}

</code>```

I would like to be able to open the clicked image in fullscreen with the right path that is either take by the api or by the path of the image that is already loaded on the screen. I am able to access the correct attribute with getAttribute but I am not able to use it in the showModal function, I know that the problem is related with the fact that the div with the class fullimg is not yet in the scope so original.src will return null.

Body:
I have a grid of images that get displayed by mapping the imagepath from an API (mongodb), I want to create a clickevent on each image which will open the image in fullscreen. When clicked it opens a new div that should contain the image with the correct path, so the path of the image that was clicked. I have this code at the moment.

const [showModal, setShowModal] = useState(false)

function handleClick() {

setShowModal(true);

const previews = document.querySelectorAll(`.${styles.photo} img` );
const original = document.querySelector(`.${styles.fullimg}`)

console.log(original);
previews.forEach(preview => {
  preview.addEventListener('click', () => {
    data.map((date) => {
      const originalSrc = preview.getAttribute("data-original");
      //original.src = `./image/space/${originalSrc}`;
      console.log(originalSrc);
      //console.log(original.src);
    })
  });
});

console.log("clicked");

}

        {data.map((datas) => {
      return (

        <img className = {styles.img} src={`/image/space/${datas.imagepath}`}  loading="lazy" data-original={datas.imagepath}/>

      );
      })}

  {showModal ? (

 setShowModal(false)}>

  ) : null}

I would like to be able to open the clicked image in fullscreen with the right path that is either take by the api or by the path of the image that is already loaded on the screen. I am able to access the correct attribute with getAttribute but I am not able to use it in the showModal function, I know that the problem is related with the fact that the div with the class fullimg is not yet in the scope so original.src will return null.


问:
postgresql partitioned table primary key issue
I am working on a requirement to create partition for customer name table in Postgresql DB. Primary Key of this table is an auto generated sequence number.

Since regular table cannot be turned into a partitioned table, I am planning to create a new partitioned table with primary key as composite key (sequence number + first letter of the customer's name).

I am not sure if it is required to define different sequence number one for each partition of customer name or defining the sequence number for partitioned table once will work.


问:
Subprocess can't find module when not run with shell=True (Python)
When I use Popen to start a subprocess, if shell=True isn't set I get the following error message:

Traceback (most recent call last):
  File "C:\Users\Student01\PycharmProjects\yolov5-master\detect.py", line 37, in <module>
    import torch
ModuleNotFoundError: No module named 'torch'
```
<p>I don't get this error message if shell=True.</p>
<p>I don't want to need to set shell=True because it causes problems when I then try to call communicate or stdout on the subprocess (It just runs the subprocess into the shell without executing anything bellow the communicate call).</p>
<p>Here is the code (In case it can help):</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
import subprocess

detectPath = "C:\\Users\\Student01\\PycharmProjects\\yolov5-master\\detect.py"

print("First Print Passed")

process = subprocess.Popen("python {} --source 0".format(detectPath), stdout=subprocess.PIPE, shell=False)

# output = str(process.communicate())

while process.poll() is None:
    process.stdout.readline()
    print("Poll is None")
</code>```

I am using Pycharm

I tried adding the yolov5 project files into the included files of my pycharm project (since I'm working in a venv) but still get the error.

The only solution to the moduleNotFound error seems to be to set shell=True in the Popen but that creates other problems.

Body:
When I use Popen to start a subprocess, if shell=True isn't set I get the following error message:

Traceback (most recent call last):
  File "C:\Users\Student01\PycharmProjects\yolov5-master\detect.py", line 37, in <module>
    import torch
ModuleNotFoundError: No module named 'torch'

I don't get this error message if shell=True.

I don't want to need to set shell=True because it causes problems when I then try to call communicate or stdout on the subprocess (It just runs the subprocess into the shell without executing anything bellow the communicate call).

Here is the code (In case it can help):

#!/usr/bin/env python
import subprocess

detectPath = "C:\\Users\\Student01\\PycharmProjects\\yolov5-master\\detect.py"

print("First Print Passed")

process = subprocess.Popen("python {} --source 0".format(detectPath), stdout=subprocess.PIPE, shell=False)

# output = str(process.communicate())

while process.poll() is None:
    process.stdout.readline()
    print("Poll is None")

I am using Pycharm

I tried adding the yolov5 project files into the included files of my pycharm project (since I'm working in a venv) but still get the error.

The only solution to the moduleNotFound error seems to be to set shell=True in the Popen but that creates other problems.


问:
How to retrieve the response content from java HttpsURLConnection if there response code is an error
I have the following code snippet to call a web service with SSL:

```<code>HttpsURLConnection httpsURLCon = null;
String webServiceResponse = null;
String endPointURLwithToken = "https://some.end.point.com/path/to/token";
String client_id = "client-id-value";
String client_secret = "client-secret-value";
String grant_type = "client_credentials";
String scope = "scope-value";
URL url = new URL(endPointURLwithToken);
httpsURLCon = (HttpsURLConnection) url.openConnection();
String securedProtocol = "TLSv1.2";
SSLContext sc = SSLContext.getInstance(securedProtocol);
sc.init(null, null, new xxx.security.SecureRandom()); //replacee xxx with java
httpsURLCon.setSSLSocketFactory(sc.getSocketFactory());
httpsURLCon.setDoOutput(true);
httpsURLCon.setRequestMethod(requestMethod);
httpsURLCon.setRequestProperty("Content-Type", contentType);
String strClient_Key_Secret = client_id+":"+client_secret;
String strAuthBasic = "Basic "+new String(Base64Encoder.encode(strClient_Key_Secret.getBytes()));
httpsURLCon.setRequestProperty("Authorization", strAuthBasic);
String urlParameters = "grant_type=" + grant_type + "&scope=" + scope;
DataOutputStream wr = new DataOutputStream(httpsURLCon.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
if (httpsURLCon.getResponseCode() == HttpsURLConnection.HTTP_OK) {
    webServiceResponse = getWSResponse(httpsURLCon); //uses stream reader ...etc.
    System.out.println("Success - Web service reposne = " + webServiceResponse);
}
</code>```

I am trying to access the response content (json string) even if the response code is an error like 400, but I am unable to do so. In postman, I can see the response json even if there is an error.

I am trying to access the response using this function:

```<code>    private String getWSResponse(HttpsURLConnection httpsURLCon) throws Exception {
        InputStream responseInputStr = httpsURLCon.getInputStream();
        String tokenResponse = null;
        if (responseInputStr != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(responseInputStr));
            String output;
            StringBuffer responseStrBuf = new StringBuffer();
            while ((output = br.readLine()) != null) {
                // System.out.println(output);
                responseStrBuf.append(output);
            }
            br.close();
            tokenResponse= responseStrBuf.toString();
        }
        return tokenResponse;
    }
</code>```

When I tried accessing the response json and if the response code is not 200 it will throw an exception.

Is it possible to retrieve the web service response even if the response code is not 200?

Body:
I have the following code snippet to call a web service with SSL:

HttpsURLConnection httpsURLCon = null;
String webServiceResponse = null;
String endPointURLwithToken = "https://some.end.point.com/path/to/token";
String client_id = "client-id-value";
String client_secret = "client-secret-value";
String grant_type = "client_credentials";
String scope = "scope-value";
URL url = new URL(endPointURLwithToken);
httpsURLCon = (HttpsURLConnection) url.openConnection();
String securedProtocol = "TLSv1.2";
SSLContext sc = SSLContext.getInstance(securedProtocol);
sc.init(null, null, new xxx.security.SecureRandom()); //replacee xxx with java
httpsURLCon.setSSLSocketFactory(sc.getSocketFactory());
httpsURLCon.setDoOutput(true);
httpsURLCon.setRequestMethod(requestMethod);
httpsURLCon.setRequestProperty("Content-Type", contentType);
String strClient_Key_Secret = client_id+":"+client_secret;
String strAuthBasic = "Basic "+new String(Base64Encoder.encode(strClient_Key_Secret.getBytes()));
httpsURLCon.setRequestProperty("Authorization", strAuthBasic);
String urlParameters = "grant_type=" + grant_type + "&scope=" + scope;
DataOutputStream wr = new DataOutputStream(httpsURLCon.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
if (httpsURLCon.getResponseCode() == HttpsURLConnection.HTTP_OK) {
    webServiceResponse = getWSResponse(httpsURLCon); //uses stream reader ...etc.
    System.out.println("Success - Web service reposne = " + webServiceResponse);
}

I am trying to access the response content (json string) even if the response code is an error like 400, but I am unable to do so. In postman, I can see the response json even if there is an error.

I am trying to access the response using this function:

    private String getWSResponse(HttpsURLConnection httpsURLCon) throws Exception {
        InputStream responseInputStr = httpsURLCon.getInputStream();
        String tokenResponse = null;
        if (responseInputStr != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(responseInputStr));
            String output;
            StringBuffer responseStrBuf = new StringBuffer();
            while ((output = br.readLine()) != null) {
                // System.out.println(output);
                responseStrBuf.append(output);
            }
            br.close();
            tokenResponse= responseStrBuf.toString();
        }
        return tokenResponse;
    }

When I tried accessing the response json and if the response code is not 200 it will throw an exception.

Is it possible to retrieve the web service response even if the response code is not 200?


问:
Why isn't my backend correctly working when working with the deployed client side?
I am trying to deploy a booking system project. I have the frontend already deployed on Vercel. I have the backend deployed on Heroku. The frontend and the firestore database are working great but my backend is responsible for sending booking conformation emails. The thing I am confused about is that when I have the frontend running on localhost, the deployed backend is working and sending emails which means I don't even have to be running the server on localhost. The problem arises when I submit the form on the deployed frontend, because the emails stop sending. Here is my backend code:

In app.js: (main file)

```<code>require("dotenv").config();
const express = require("express");
const app = express();
const router = require("./routes/router");
const cors = require("cors");

app.use(express.json());
app.use(cors());
app.use(router);

app.listen(process.env.PORT || 8000, () => console.log("Server running"));
</code>```

In router/router.js:

```<code>const express = require("express");
const router = new express.Router();
const nodemailer = require("nodemailer");

router.post("/bookings", (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const date = req.body.readableDate;
  const time = req.body.time;
  const age = req.body.age;
  const number = req.body.number;
  const team = req.body.team;
  const service = req.body.service;

  try {
    const transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: process.env.EMAIL,
        pass: process.env.PASS,
      },
    });

    const customerMailOptions = {
      from: process.env.EMAIL,
      to: email,
      subject: "ShootToScore: Booking Conformation",
      html: `<div style="text-align: center;">
              <img style="width: 200px;" src="https://www.shoottoscore.ca/static/media/logo_blue.6582e64f919a39985d3e.png" alt="logo" />
              <h1 style="color: #333;">Booking Confirmation</h1>
              <p style="color: #666;">Hi ${name},</p>
              <p style="color: #666;">
                Thank you for booking with us on ${date} at ${time} for: ${service}. Your booking is confirmed and we look forward to
                seeing you!
              </p>
              <p style="color: #666;">
                If you need to make any changes to your booking, please don't
                hesitate to contact us at shoottoscorebookings@gmail.com or call
                (289)-387-4812. Cancelations and rebookings must be made 3 days prior to session.
              </p>
              <p style="color: #666;">
                Thank you for choosing ShootToScore for your hockey training
                needs.
              </p>
              <p style="color: #666;">
                <strong>ShootToScore</strong>
              </p>
            </div>`,
    };

    const businessMailOptions = {
      from: process.env.EMAIL,
      to: "shoottoscorebookings@gmail.com",
      subject: "New Booking",
      html: `<div style="text-align: center;">
        <img style="width: 200px;" src="https://www.shoottoscore.ca/static/media/logo_blue.6582e64f919a39985d3e.png" alt="logo" />
        <h1 style="color: #333;">New Booking</h1>
        <p style="color: #666;">A new booking has been made with the following details:</p>
        <p style="color: #666;"><strong>Name:</strong> ${name}</p>
        <p style="color: #666;"><strong>Email:</strong> ${email}</p>
        <p style="color: #666;"><strong>Service:</strong> ${service}</p>
        <p style="color: #666;"><strong>Date:</strong> ${date}</p>
        <p style="color: #666;"><strong>Time:</strong> ${time}</p>
        <p style="color: #666;"><strong>Age:</strong> ${age}</p>
        <p style="color: #666;"><strong>Phone Number:</strong> ${number}</p>
        <p style="color: #666;"><strong>Team:</strong> ${team}</p>
        <p style="color: #666;">
          Please make sure to add this booking to your schedule and contact the customer if necessary.
        </p>
        </div>`,
    };

    transporter.sendMail(businessMailOptions, (err, info) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Email sent to owner" + info.response);
        res.status(201).json({ status: 201, info });
      }
    });

    transporter.sendMail(customerMailOptions, (err, info) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Email sent to customer" + info.response);
        res.status(201).json({ status: 201, info });
      }
    });
  } catch (error) {
    res.status(201).json({ status: 401, error });
  }
});

module.exports = router;
</code>```

Here is my frontend function code that sends the data to the backend:

```<code>      const readableDate = date.toLocaleDateString("en-US", {
        month: "long",
        day: "numeric",
        year: "numeric",
      });

      const service = "30min goalie clinic - private";

      const res = await fetch("/bookings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name,
          email,
          number,
          team,
          age,
          readableDate,
          time,
          service,
        }),
      });

      console.log(res);

      setName("");
      setEmail("");
      setDate(null);
      setNumber("");
      setTeam("");
      setTime("");
      setAge("");
</code>```

I also have the proxy setup in my client side package.json which looks like this:

```<code>{
  "name": "jensen",
  "version": "0.1.0",
  "private": true,
  "proxy": "https://jensen-server.herokuapp.com/",
  "dependencies": {...}
}
</code>```

That is where the backend is currently deployed and is working because when I run the frontend in localhost, the deployed backend works. I also don't get any error logs in Heroku, the emails just aren't sending. Here is what the logs look like: Heroku Logs

Body:
I am trying to deploy a booking system project. I have the frontend already deployed on Vercel. I have the backend deployed on Heroku. The frontend and the firestore database are working great but my backend is responsible for sending booking conformation emails. The thing I am confused about is that when I have the frontend running on localhost, the deployed backend is working and sending emails which means I don't even have to be running the server on localhost. The problem arises when I submit the form on the deployed frontend, because the emails stop sending. Here is my backend code:

In app.js: (main file)

require("dotenv").config();
const express = require("express");
const app = express();
const router = require("./routes/router");
const cors = require("cors");

app.use(express.json());
app.use(cors());
app.use(router);

app.listen(process.env.PORT || 8000, () => console.log("Server running"));

In router/router.js:

const express = require("express");
const router = new express.Router();
const nodemailer = require("nodemailer");

router.post("/bookings", (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const date = req.body.readableDate;
  const time = req.body.time;
  const age = req.body.age;
  const number = req.body.number;
  const team = req.body.team;
  const service = req.body.service;

  try {
    const transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: process.env.EMAIL,
        pass: process.env.PASS,
      },
    });

    const customerMailOptions = {
      from: process.env.EMAIL,
      to: email,
      subject: "ShootToScore: Booking Conformation",
      html: `

Booking Confirmation

Hi ${name},

                Thank you for booking with us on ${date} at ${time} for: ${service}. Your booking is confirmed and we look forward to
                seeing you!

                If you need to make any changes to your booking, please don't
                hesitate to contact us at shoottoscorebookings@gmail.com or call
                (289)-387-4812. Cancelations and rebookings must be made 3 days prior to session.

                Thank you for choosing ShootToScore for your hockey training
                needs.

                ShootToScore

`,
    };

    const businessMailOptions = {
      from: process.env.EMAIL,
      to: "shoottoscorebookings@gmail.com",
      subject: "New Booking",
      html: `

New Booking

A new booking has been made with the following details:

Name: ${name}

Email: ${email}

Service: ${service}

Date: ${date}

Time: ${time}

Age: ${age}

Phone Number: ${number}

Team: ${team}

          Please make sure to add this booking to your schedule and contact the customer if necessary.

`,
    };

    transporter.sendMail(businessMailOptions, (err, info) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Email sent to owner" + info.response);
        res.status(201).json({ status: 201, info });
      }
    });

    transporter.sendMail(customerMailOptions, (err, info) => {
      if (err) {
        console.log(err);
      } else {
        console.log("Email sent to customer" + info.response);
        res.status(201).json({ status: 201, info });
      }
    });
  } catch (error) {
    res.status(201).json({ status: 401, error });
  }
});

module.exports = router;

Here is my frontend function code that sends the data to the backend:

      const readableDate = date.toLocaleDateString("en-US", {
        month: "long",
        day: "numeric",
        year: "numeric",
      });

      const service = "30min goalie clinic - private";

      const res = await fetch("/bookings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name,
          email,
          number,
          team,
          age,
          readableDate,
          time,
          service,
        }),
      });

      console.log(res);

      setName("");
      setEmail("");
      setDate(null);
      setNumber("");
      setTeam("");
      setTime("");
      setAge("");

I also have the proxy setup in my client side package.json which looks like this:

{
  "name": "jensen",
  "version": "0.1.0",
  "private": true,
  "proxy": "https://jensen-server.herokuapp.com/",
  "dependencies": {...}
}

That is where the backend is currently deployed and is working because when I run the frontend in localhost, the deployed backend works. I also don't get any error logs in Heroku, the emails just aren't sending. Here is what the logs look like: Heroku Logs


问:
Can't click on a button on booking.com with Selenium & Python
I am scraping a website booking.com to test Selenium. I got some code from this tutorial. I got stuck to click on a button to work (The currency button or language button on the top of the home page). I tried a couple of CSS selectors and could not make the button clicked. Any help is appreciated.
Omar

```<code># run.py

from booking.booking import Booking
with Booking() as bot:
    print('before land_first_page from run.py')
    bot.land_first_page(teardown=True)
    print('after land_first_page from run.py')
    bot.change_currency()

#########################
# booking.py

import os
import booking.constants as const
from selenium import webdriver

class Booking(webdriver.Chrome):
    def __init__(self, driver_path=const.chromePath, teardown=True):
        self.driver_path = driver_path
        self.teardown = teardown
        os.environ['PATH'] += self.driver_path
        super(Booking, self).__init__()
        self.implicitly_wait(15)
        self.maximize_window()

    def __exit__(self, exc_type, exc_val, exc_tb):
        while(self.teardown):
            pass  # i.e. do nothing until teardown is False
        if self.teardown:
            self.quit()

    def land_first_page(self, teardown):
        self.get(const.BASE_URL)

    def change_currency(self, currency=None):
        print('change_currency')
        # data-testid="header-currency-picker-trigger"
        currency_element = self.find_element_by_css_selector(
            'button[data-testid="header-currency-picker-trigger"]')
        print('currency_element: ', currency_element)
        currency_element.click()

    def change_language(self, language=None):
        language_element = self.find_element_by_css_selector(
            'button[data-tooltip-text="Choose your language"]')

        language_element.click()

</code>```

I tried several CSS selectors but could not click on the currency button.

Body:
I am scraping a website booking.com to test Selenium. I got some code from this tutorial. I got stuck to click on a button to work (The currency button or language button on the top of the home page). I tried a couple of CSS selectors and could not make the button clicked. Any help is appreciated.
Omar

# run.py

from booking.booking import Booking
with Booking() as bot:
    print('before land_first_page from run.py')
    bot.land_first_page(teardown=True)
    print('after land_first_page from run.py')
    bot.change_currency()

#########################
# booking.py

import os
import booking.constants as const
from selenium import webdriver

class Booking(webdriver.Chrome):
    def __init__(self, driver_path=const.chromePath, teardown=True):
        self.driver_path = driver_path
        self.teardown = teardown
        os.environ['PATH'] += self.driver_path
        super(Booking, self).__init__()
        self.implicitly_wait(15)
        self.maximize_window()

    def __exit__(self, exc_type, exc_val, exc_tb):
        while(self.teardown):
            pass  # i.e. do nothing until teardown is False
        if self.teardown:
            self.quit()

    def land_first_page(self, teardown):
        self.get(const.BASE_URL)

    def change_currency(self, currency=None):
        print('change_currency')
        # data-testid="header-currency-picker-trigger"
        currency_element = self.find_element_by_css_selector(
            'button[data-testid="header-currency-picker-trigger"]')
        print('currency_element: ', currency_element)
        currency_element.click()

    def change_language(self, language=None):
        language_element = self.find_element_by_css_selector(
            'button[data-tooltip-text="Choose your language"]')

        language_element.click()

I tried several CSS selectors but could not click on the currency button.


问:
How to add description to object properties
I have defined a new YSDK type using this syntax

/**
 * @typedef {{
 *     environment: {
 *          app: {
 *              id: string
 *          },
 *          browser: {
 *              lang: string,
 *          },
 *          i18n: {
 *              lang: string,
 *              tld: string
 *          },
 *          payload?: string
 *     }
 * }} YSDK
 */
```
<p>I know that I can add description if I use this syntax</p>
```/**
 * The complete Triforce, or one or more components of the Triforce.
 * @typedef {Object} WishGranter~Triforce
 * @property {boolean} hasCourage - Indicates whether the Courage component is present.
 * @property {boolean} hasPower - Indicates whether the Power component is present.
 * @property {boolean} hasWisdom - Indicates whether the Wisdom component is present.
 */
```

Is there a way to add a description to the properties of the object in the form in which I defined them?

Body:
I have defined a new YSDK type using this syntax

/**
 * @typedef {{
 *     environment: {
 *          app: {
 *              id: string
 *          },
 *          browser: {
 *              lang: string,
 *          },
 *          i18n: {
 *              lang: string,
 *              tld: string
 *          },
 *          payload?: string
 *     }
 * }} YSDK
 */

I know that I can add description if I use this syntax

/**
 * The complete Triforce, or one or more components of the Triforce.
 * @typedef {Object} WishGranter~Triforce
 * @property {boolean} hasCourage - Indicates whether the Courage component is present.
 * @property {boolean} hasPower - Indicates whether the Power component is present.
 * @property {boolean} hasWisdom - Indicates whether the Wisdom component is present.
 */

Is there a way to add a description to the properties of the object in the form in which I defined them?


问:
Node execPath references VSCode installation instead of path to Node installation
I have a NodeJS process that is used in a shared library that does the following:

```<code>async function execNpmInstall(currWorkingDirectory: string) {
  const exec = promisify(childProcess.exec);
  return await exec(`${process.execPath} npm install`, {
    cwd: currWorkingDirectory,
  });
}

</code>```

The problem is, when I call execNpmInstall, the process.execPath is replaced with the path of my VSCode extension, whereas I want it to be set to the location of where ndoe is installed. I found through the documentation (https://code.visualstudio.com/docs/editor/variables-reference):

${execPath} - the path to the running VS Code executable

When I execute the code, I get the following error:

```<code>Error: Command failed: /Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin) npm install
/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin) node_modules/npm/bin/npm-cli.js install --ignore-scripts'
</code>```

I tried to see if there was any way to find if there was any way to get the executable that started the Node.js process outside of process.execPath but I can't find any way to reference the node executable in any other way. Is there any way for me to resolve the process.execPath to be the "node" process.execPath and not the VS Code extension execPath variable?

Body:
I have a NodeJS process that is used in a shared library that does the following:

async function execNpmInstall(currWorkingDirectory: string) {
  const exec = promisify(childProcess.exec);
  return await exec(`${process.execPath} npm install`, {
    cwd: currWorkingDirectory,
  });
}

The problem is, when I call execNpmInstall, the process.execPath is replaced with the path of my VSCode extension, whereas I want it to be set to the location of where ndoe is installed. I found through the documentation (https://code.visualstudio.com/docs/editor/variables-reference):

${execPath} - the path to the running VS Code executable

When I execute the code, I get the following error:

Error: Command failed: /Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin) npm install
/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Plugin).app/Contents/MacOS/Code Helper (Plugin) node_modules/npm/bin/npm-cli.js install --ignore-scripts'

I tried to see if there was any way to find if there was any way to get the executable that started the Node.js process outside of process.execPath but I can't find any way to reference the node executable in any other way. Is there any way for me to resolve the process.execPath to be the "node" process.execPath and not the VS Code extension execPath variable?


问:
Error in React typecript : 'string' can't be used to index type
I have a DetailPage component
and I have JSON data called data.json
and data structure example like this:

data = {
  mobile: [...someData], speaker:[...someData],
  ... and ....
}
```
<p>My problem is about using <code>useParams</code> hook and I want to use params as key of object like this:</p>
<pre class="lang-js prettyprint-override"><code>import data from "../data/data.json";

const DetailPage = () => {
  const { category, id } = useParams();
  return <h1>{data[category][id].title}</h1>;
};
export default DetailPage;
</code>```

The first error is:

```<code>Type 'undefined' cannot be used as an index type.
</code>```

I solve that with typeguard condition in inline jsx:

```<code><h1>category !== undefined && data[category][id].title</h1>
</code>```

But the second error I can't handle:

```<code>Element implicitly has an 'any' type
  because expression of type 'string' can't be used to index type
</code>```

Body:
I have a DetailPage component
and I have JSON data called data.json
and data structure example like this:

data = {
  mobile: [...someData], speaker:[...someData],
  ... and ....
}

My problem is about using useParams hook and I want to use params as key of object like this:

import data from "../data/data.json";

const DetailPage = () => {
  const { category, id } = useParams();
  return
{data[category][id].title}
;
};
export default DetailPage;

The first error is:

Type 'undefined' cannot be used as an index type.

I solve that with typeguard condition in inline jsx:

category !== undefined && data[category][id].title

But the second error I can't handle:

Element implicitly has an 'any' type
  because expression of type 'string' can't be used to index type


问:
How can you configure gzip for CloudWatch PutMetricData
The documentation for PutMetricData calls out that POST requests are limited to 1MB in size.  It further states that large requests can be gzipped to fit into that limit.

However, as near as I can tell, there is no documentation on how to configure this.  I was able to find something for boto3, but there's not a 1:1 mapping of the Go and boto3 clients such that I can figure out how to transparently modify the request.

The docs do have some notes about how to modify settings via NewBuildableClient, but it would be helpful if there were additional examples that included transparently enabling GZip.


问:
Setting opacity on a vector layer
I'm trying to set the opacity of a specific layer and browsing the web gave me this result:

```<code>transp = iface.activeLayer()
root_rule_transp = transp.renderer().rootRule()

for rule in root_rule_transp.children():
    rule.symbol().setOpacity(0.5)
</code>```

It seems what I have been able to find may be for QGIS 2.

Anyone with any experience in this process for QGIS 3?

Title: Setting opacity on a vector layer

Body:
I'm trying to set the opacity of a specific layer and browsing the web gave me this result:

transp = iface.activeLayer()
root_rule_transp = transp.renderer().rootRule()

for rule in root_rule_transp.children():
    rule.symbol().setOpacity(0.5)

It seems what I have been able to find may be for QGIS 2.

Anyone with any experience in this process for QGIS 3?


问:
Add components to the dropdown of standard android's Spinner
Can I add components to the dropdown of standard android's Spinner without switching to another component and letting Spinner be the original Spinner?</p>


问:
Text not displayed in React using Routes
I am fairly new to using react and been following a couple of tutorials on YT, I have ran into a problem with one of them. I copied everything line by line, but my text on 'Home' and 'Login'  doesnt display! I get no errors, but the page remains blank.

here is App.js

```<code> import React from 'react'
  import { Routes, Route, useNavigate } from 'react-router-dom';

  import Login from './components/Login';
  import Home from './container/Home';

  const App = () => {
    return (
     <Routes>
       <Route path="login" element={<Login />} />
       <Route path="/*" element={<Home />} />
     </Routes>
    );
  };
</code>```

export default App;

Also the index.js file:

```<code> import React from 'react';
   import ReactDOM from 'react-dom';
   import { BrowserRouter as Router } from 'react-router-dom';

   import App from './App';
   import './index.css';

  ReactDOM.render(
     <Router>
         <App />
     </Router>,
      document.getElementById('root'),
 );

</code>```

**Then Login.jsx
**

```<code> import React from 'react';

const Login = () => {
  return (
    <div>
      Login
    </div>

  );
};

export default Login;
</code>```

Finally Home.jsx

```<code>import React from 'react';``your text``

  const Home = () => {
  return (
    <div>
   Home
      </div>
    );
  };

 export default Home;
</code>```

I know I am missing something, but I cant seem to find it! Any and all help is very much appreciated!

Tried to see if I am using on old version of the BroswerROuter/Routes in React, but I have very little knowledge to see the difference just yet!

Body:
I am fairly new to using react and been following a couple of tutorials on YT, I have ran into a problem with one of them. I copied everything line by line, but my text on 'Home' and 'Login'  doesnt display! I get no errors, but the page remains blank.

here is App.js

 import React from 'react'
  import { Routes, Route, useNavigate } from 'react-router-dom';

  import Login from './components/Login';
  import Home from './container/Home';

  const App = () => {
    return (
     <Routes>
       <Route path="login" element={<Login />} />
       <Route path="/*" element={<Home />} />
     </Routes>
    );
  };

export default App;

Also the index.js file:

 import React from 'react';
   import ReactDOM from 'react-dom';
   import { BrowserRouter as Router } from 'react-router-dom';

   import App from './App';
   import './index.css';

  ReactDOM.render(
     <Router>
         <App />
     </Router>,
      document.getElementById('root'),
 );

**Then Login.jsx
**

 import React from 'react';

const Login = () => {
  return (

      Login

  );
};

export default Login;

Finally Home.jsx

import React from 'react';``your text``

  const Home = () => {
  return (

   Home

    );
  };

 export default Home;

I know I am missing something, but I cant seem to find it! Any and all help is very much appreciated!

Tried to see if I am using on old version of the BroswerROuter/Routes in React, but I have very little knowledge to see the difference just yet!


问:
Bootstrap 5 Navbar columns stacking instead of staying on the same row
I want the navbar to stay on the same row, I believe the flex layout is stacking the columns and giving them 100% width. This means I end up with the icons and website name all stacked instead of on the left, center, and right. Is there a simple solution here I'm missing? Not really familiar with flex.

JSFiddle link because I had trouble getting the bootstreap css working in the Stack Overflow snippet

HTML:

```<code><!doctype html>
<html lang="en" class="h-100">
<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>

<body class="d-flex h-100 text-center text-white">

  <div class="cover-container d-flex w-100 h-100 mx-auto flex-column">
    <header class="mb-auto" id="nav">
      <div class="row justify-content-between">
        <div class="col-xs-4 col-sm-4 mt-4">
          <a class="nav-link first-icon ms-3" href="#">
              <i class="fa fa-car"></i>
            </a>
        </div>
        <div class="col-xs-4 col-sm-4 brand-logo">
          <h3 class="justify-content-center mt-3 fw-bold">Website Name</h3>
        </div>
        <div class="col-xs-4 col-sm-4">
          <nav class="nav nav-masthead float-end mt-4 me-3">
            <a class="nav-link">
              <i class="fa fa-car"></i>
            </a>
            <a class="nav-link" href="#">
              <i class="fa fa-car"></i>
            </a>
            <a class="nav-link" href="#">
              <i class="fa fa-car"></i>
            </a>
          </nav>
        </div>
      </div>
    </header>

    </div>

    <!-- JS -->
    <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js" integrity="sha256-xLD7nhI62fcsEZK2/v8LsBcb4lG7dgULkuXoXB/j91c=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>

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

CSS:

```<code>body {
  background-color: #000000;
}

#nav {
 height: 4rem;
 border-bottom: 1px solid #3a3a3c;
}

.icon {
  height: 30px;
  width: 30px;
  cursor: pointer;
}

.stats-icon {
  height: 27.5px !important;
  width: 27.5px !important;
}

.nav-masthead .nav-link {
  padding: .25rem 0;
  font-weight: 700;
  color: #fff;
  background-color: transparent;
  border-bottom: .10rem solid transparent;
  cursor: pointer;
}

.nav-masthead .nav-link:hover,
.nav-masthead .nav-link:focus {
  border-bottom-color: rgba(255, 255, 255, .25);
}

.nav-masthead .nav-link + .nav-link {
  margin-left: 1rem;
}

.nav-masthead .active {
  color: #fff;
  border-bottom-color: #fff;
}

.bd-placeholder-img {
  font-size: 1.125rem;
  text-anchor: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

@media (min-width: 768px) {
  .bd-placeholder-img-lg {
    font-size: 3.5rem;
  }
}

@media screen and (max-width: 768px) {
  .first-icon {
    float: left;
  }
}
</code>```

Body:
I want the navbar to stay on the same row, I believe the flex layout is stacking the columns and giving them 100% width. This means I end up with the icons and website name all stacked instead of on the left, center, and right. Is there a simple solution here I'm missing? Not really familiar with flex.

JSFiddle link because I had trouble getting the bootstreap css working in the Stack Overflow snippet

HTML:

<!doctype html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Website Name

CSS:

body {
  background-color: #000000;
}

#nav {
 height: 4rem;
 border-bottom: 1px solid #3a3a3c;
}

.icon {
  height: 30px;
  width: 30px;
  cursor: pointer;
}

.stats-icon {
  height: 27.5px !important;
  width: 27.5px !important;
}

.nav-masthead .nav-link {
  padding: .25rem 0;
  font-weight: 700;
  color: #fff;
  background-color: transparent;
  border-bottom: .10rem solid transparent;
  cursor: pointer;
}

.nav-masthead .nav-link:hover,
.nav-masthead .nav-link:focus {
  border-bottom-color: rgba(255, 255, 255, .25);
}

.nav-masthead .nav-link + .nav-link {
  margin-left: 1rem;
}

.nav-masthead .active {
  color: #fff;
  border-bottom-color: #fff;
}

.bd-placeholder-img {
  font-size: 1.125rem;
  text-anchor: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

@media (min-width: 768px) {
  .bd-placeholder-img-lg {
    font-size: 3.5rem;
  }
}

@media screen and (max-width: 768px) {
  .first-icon {
    float: left;
  }
}


问:
Django Policy cors
I have an api with several URLs, only one of the routes returns an error for cors when I call it from angular,

This is the configuration of the settings.py

```<code>CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
    "http://localhost:4200",
    "https://midominio.com"
]
</code>```

Try Creating a proxy.conf.json file with the following settings

```<code>{
    "/api": {
      "target": "https://www.midominio.com",
      "secure": true,
      "changeOrigin": true
    }
}
</code>```
```<code>Access to XMLHttpRequest at 'https://midominio/api/parchate/megusta/megusta' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Me sale el siguiente error
</code>```

Title: Django Policy cors

Body:
I have an api with several URLs, only one of the routes returns an error for cors when I call it from angular,

This is the configuration of the settings.py

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
    "http://localhost:4200",
    "https://midominio.com"
]

Try Creating a proxy.conf.json file with the following settings

{
    "/api": {
      "target": "https://www.midominio.com",
      "secure": true,
      "changeOrigin": true
    }
}

Access to XMLHttpRequest at 'https://midominio/api/parchate/megusta/megusta' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Me sale el siguiente error


问:
Struggling with the Restricted Boltzman Machine
I am triying to apply Restricted Boltzman Machine (RBM) to MNIST dataset, although I am getting small reconstructing errors, when reconstruct the test set to the same dimensions as the original, the reconstructed images differ considerably from their original.

class RBM:
def init(self, n_input_neurons, n_output_neurons):
self.W = np.random.normal(loc=0.0, scale=1.0, size=(n_input_neurons, n_output_neurons)).astype(np.float32)
self.visible_bias = np.random.rand(1, n_input_neurons) #visible layer bias
self.hidden_bias = np.random.rand(1, n_output_neurons) #hidden layer bias

```<code>def __sample(self, probability_distribution):
    random_dist = np.random.uniform(0, 1, probability_distribution.shape)
    example = probability_distribution - random_dist

    example[example > 0] = 1.0
    example[example <= 0] = 0.0
    return example

def __sigmoid(self, x):
    return 1 / (1 + np.e ** (-x))

def __encode(self, X):
    probability_distribution = self.__sigmoid(X @ self.W + self.hidden_bias) #probabilities of the hidden units
    return probability_distribution, self.__sample(probability_distribution)

def __decode(self, X):
    probability_distribution = self.__sigmoid(X @ self.W.T + self.visible_bias) #probabilities of the visible units
    return probability_distribution, self.__sample(probability_distribution)

def getReconstructedOutput(self, X):
    encode_probability, encode_sample = self.__encode(X)
    decode_probability, decode_sample = self.__decode(encode_sample)
    return decode_sample

def train(self, X, loss_function, lr=.01, epochs= 500, verbose = False):
    epoch = 0
    history = []
    while epoch < epochs:
        h0_prob, h0_state = self.__encode(X)
        positive_associations = X.T.dot(h0_prob)

        v1_prob, v1_state = self.__decode(h0_state)
        h1_prob, h1_state = self.__encode(v1_state)
        negative_associations = v1_state.T.dot(h1_prob)

        #Updating weights
        self.W+= lr * (positive_associations - negative_associations)
        self.hidden_bias+= (lr *  (h0_prob.sum(axis = 0) - h1_prob.sum(axis = 0)) )
        self.visible_bias+= (lr * (X.sum(axis=0) - v1_state.sum(axis=0)) )

        epoch+=1
        loss = loss_function(v1_state, X) #loss
        history.append(loss)
        if verbose:
            print(f'Epoch {epoch} ==> Loss: {loss}')
    return history
</code>```

What i am doing wrong?

Body:
I am triying to apply Restricted Boltzman Machine (RBM) to MNIST dataset, although I am getting small reconstructing errors, when reconstruct the test set to the same dimensions as the original, the reconstructed images differ considerably from their original.

class RBM:
def init(self, n_input_neurons, n_output_neurons):
self.W = np.random.normal(loc=0.0, scale=1.0, size=(n_input_neurons, n_output_neurons)).astype(np.float32)
self.visible_bias = np.random.rand(1, n_input_neurons) #visible layer bias
self.hidden_bias = np.random.rand(1, n_output_neurons) #hidden layer bias

def __sample(self, probability_distribution):
    random_dist = np.random.uniform(0, 1, probability_distribution.shape)
    example = probability_distribution - random_dist

    example[example > 0] = 1.0
    example[example <= 0] = 0.0
    return example

def __sigmoid(self, x):
    return 1 / (1 + np.e ** (-x))

def __encode(self, X):
    probability_distribution = self.__sigmoid(X @ self.W + self.hidden_bias) #probabilities of the hidden units
    return probability_distribution, self.__sample(probability_distribution)

def __decode(self, X):
    probability_distribution = self.__sigmoid(X @ self.W.T + self.visible_bias) #probabilities of the visible units
    return probability_distribution, self.__sample(probability_distribution)

def getReconstructedOutput(self, X):
    encode_probability, encode_sample = self.__encode(X)
    decode_probability, decode_sample = self.__decode(encode_sample)
    return decode_sample

def train(self, X, loss_function, lr=.01, epochs= 500, verbose = False):
    epoch = 0
    history = []
    while epoch < epochs:
        h0_prob, h0_state = self.__encode(X)
        positive_associations = X.T.dot(h0_prob)

        v1_prob, v1_state = self.__decode(h0_state)
        h1_prob, h1_state = self.__encode(v1_state)
        negative_associations = v1_state.T.dot(h1_prob)

        #Updating weights
        self.W+= lr * (positive_associations - negative_associations)
        self.hidden_bias+= (lr *  (h0_prob.sum(axis = 0) - h1_prob.sum(axis = 0)) )
        self.visible_bias+= (lr * (X.sum(axis=0) - v1_state.sum(axis=0)) )

        epoch+=1
        loss = loss_function(v1_state, X) #loss
        history.append(loss)
        if verbose:
            print(f'Epoch {epoch} ==> Loss: {loss}')
    return history

What i am doing wrong?