问:
docker-compose build: value 'devices' does not match any of the regexes: '^x-'
I´m trying to enable GPU access in a docker container, but when I run the command docker-compose build I get the next error:
ERROR: The Compose file './docker-compose.yml' is invalid because:
services.notebook.deploy.resources.reservations value 'devices' does not match any of the regexes: '^x-'
My docker-compose.yml file looks like this:

```<code>services:
  notebook:
    build: .
    ports:
      - 8887:8887
    volumes:
      - ./:/home/pae/
      - ./models:/home/pae/models
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
      - /mnt/zdisk:/home/pae/data/zdisk
    stdin_open: true
    tty: true
    command: " jupyter-notebook --allow-root --no-browser --ip=0.0.0.0 --port=8887"
    restart: always
    image: pae_notebook:latest
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              capabilities:
                - gpu

</code>```

Something curious, is that if I build the image without the deploy key in the .yml file and then add it to the file, it is possible to run docker-compose up and it uses the GPU, as I´ve checked with the nvidia-smi tool.
Another thing I notice is that the error message says "value 'devices'" and 'devices' is a key.

Version information:
Docker version 20.10.14, build a224086
docker-compose version 1.29.2, build unknown

I hope someone can help me, I´m a beginner in docker. Thanks in advance

Body:
I´m trying to enable GPU access in a docker container, but when I run the command docker-compose build I get the next error:
ERROR: The Compose file './docker-compose.yml' is invalid because:
services.notebook.deploy.resources.reservations value 'devices' does not match any of the regexes: '^x-'
My docker-compose.yml file looks like this:

services:
  notebook:
    build: .
    ports:
      - 8887:8887
    volumes:
      - ./:/home/pae/
      - ./models:/home/pae/models
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
      - /mnt/zdisk:/home/pae/data/zdisk
    stdin_open: true
    tty: true
    command: " jupyter-notebook --allow-root --no-browser --ip=0.0.0.0 --port=8887"
    restart: always
    image: pae_notebook:latest
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              capabilities:
                - gpu

Something curious, is that if I build the image without the deploy key in the .yml file and then add it to the file, it is possible to run docker-compose up and it uses the GPU, as I´ve checked with the nvidia-smi tool.
Another thing I notice is that the error message says "value 'devices'" and 'devices' is a key.

Version information:
Docker version 20.10.14, build a224086
docker-compose version 1.29.2, build unknown

I hope someone can help me, I´m a beginner in docker. Thanks in advance


来源: stackexchange

问:
Firebase Storage + Realtime Database too slow
for a small application I decided to use Firebase. I store user's profile photo on Firebase Storage, and take download URL and keep it on Firebase Realtime Database with the name of user's Auth ID. The problem is this process is too slow, I put print statements to understand where exactly process getting slower, both getting URL from Realtime db and downloading image from Storage is slow. Normally it take 3-5 seconds to download but for some reason it can go up to even 15 seconds. First I thought maybe internet connection on simulator is too slow but I also tested with my own iPhone, still slow. Therefore users first sees a placeholder image and after 5 seconds they can see their own profile photo, which is very bad user experience. Here is how I download, this function is in MainViewModel.

```<code>   func getProfileImage(uid: String, completion: @escaping (Data? , Error?) -> (Void)) {
        print("now inside get profile func")

        Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value) { snapshot  in
        guard let dictionary = snapshot.value as? [String:Any] else { return }
        guard let profileImageUrl = dictionary["image_url"] as? String else { return }
        guard let url  = URL(string: profileImageUrl) else { return }
        print("url returned, about to get in urlsession.")

        URLSession.shared.dataTask(with: url) { data, response, error in
            completion(nil, error)
            guard let data = data else { return }

        print("url session end, now dispatchque completion.")

            DispatchQueue.main.async {
            completion(data, nil)
            }

            }.resume()
    }
}
</code>```

and from viewController I use this viewmodel's function like that:

```<code>fileprivate func setProfilePicture() {
    guard let uid = Auth.auth().currentUser?.uid else { return }

    mainViewModel.getProfileImage(uid: uid) { imageData, err in
        if err != nil {
            print("err")
            return
        }
    guard let imageData = imageData else { return }
    let image  = UIImage(data: imageData)
    self.profilePhoto.image = image
    }
}
</code>```

Am I doing anything wrong or is Free plan of Firebase is really that slow?

ContentLicense: CC BY-SA 4.0

Body:
for a small application I decided to use Firebase. I store user's profile photo on Firebase Storage, and take download URL and keep it on Firebase Realtime Database with the name of user's Auth ID. The problem is this process is too slow, I put print statements to understand where exactly process getting slower, both getting URL from Realtime db and downloading image from Storage is slow. Normally it take 3-5 seconds to download but for some reason it can go up to even 15 seconds. First I thought maybe internet connection on simulator is too slow but I also tested with my own iPhone, still slow. Therefore users first sees a placeholder image and after 5 seconds they can see their own profile photo, which is very bad user experience. Here is how I download, this function is in MainViewModel.

   func getProfileImage(uid: String, completion: @escaping (Data? , Error?) -> (Void)) {
        print("now inside get profile func")

        Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value) { snapshot  in
        guard let dictionary = snapshot.value as? [String:Any] else { return }
        guard let profileImageUrl = dictionary["image_url"] as? String else { return }
        guard let url  = URL(string: profileImageUrl) else { return }
        print("url returned, about to get in urlsession.")

        URLSession.shared.dataTask(with: url) { data, response, error in
            completion(nil, error)
            guard let data = data else { return }

        print("url session end, now dispatchque completion.")

            DispatchQueue.main.async {
            completion(data, nil)
            }

            }.resume()
    }
}

and from viewController I use this viewmodel's function like that:

fileprivate func setProfilePicture() {
    guard let uid = Auth.auth().currentUser?.uid else { return }

    mainViewModel.getProfileImage(uid: uid) { imageData, err in
        if err != nil {
            print("err")
            return
        }
    guard let imageData = imageData else { return }
    let image  = UIImage(data: imageData)
    self.profilePhoto.image = image
    }
}

Am I doing anything wrong or is Free plan of Firebase is really that slow?


问:
Border is disappearing when converting HTML document to PDF
I have a JS file to generate HTML document.
When users right-click, click print and save as PDF, the border of the document is disappearing before the document ends.

Code:

```<code>div {
        margin: 10px 0px 0px 0px;
        border: 1px solid black;
        min-height: 100vh;
    }
</code>```

HTML document image:

PDF document image:

Body:
I have a JS file to generate HTML document.
When users right-click, click print and save as PDF, the border of the document is disappearing before the document ends.

Code:

div {
        margin: 10px 0px 0px 0px;
        border: 1px solid black;
        min-height: 100vh;
    }

HTML document image:

PDF document image:


问:
Can't find / Missing Windows option in Visual Studio
enter image description here

Newbie VS user here, (not really but using after years) I can't find the windows option in Visual Studio Code. I want to use it to reset the windows layout bur=t struggling from past 2-3 days finding one option. The Internet doesn't seem to have a Idea on this either. Please Guide if you can & also another question in here (if you wish to answer) is How do I find Solution Explorer tab also.

Thank you for the time.
Have a Great Day!

I wanted to start a project but couldn't find Solution Explorer tab, hence now I am trying to Reset all window layout but can't find that option too.


问:
How to completely simplify terms by a theta expression
I have an expression that is a complex runtime of an algorithm. The expression is this:

```<code>n^2 + 55*sqrt(n) + 4n^4 + 19^19
</code>```

My task is to simplify this term as much as I can using a theta expression. My initial thought is that the answer is theta(n^4) as this is the largest growth rate in the term. However, I cannot verify if this is correct. Any help would be much appreciated, thanks in advance.
(This is for revision, not homework or coursework)

Body:
I have an expression that is a complex runtime of an algorithm. The expression is this:

n^2 + 55*sqrt(n) + 4n^4 + 19^19

My task is to simplify this term as much as I can using a theta expression. My initial thought is that the answer is theta(n^4) as this is the largest growth rate in the term. However, I cannot verify if this is correct. Any help would be much appreciated, thanks in advance.
(This is for revision, not homework or coursework)


问:
Does GORM support attibutes of many to many relationships?
Using the gorm.io library, how would I implement a many to many relationship, where the relationship itself has attributes?

Example:

Without the attribute I would do it something like this, but I can't find a solution to my Problem in the GORM docs.

type Recipe struct {
    gorm.Model
    Name string
    Ingredients []Ingredient `gorm:"many2many"`
}

type Ingredient struct {
    gorm.Model
    Name string
}
```


问:
Rails 7 - selecting database with multi-database when calling ActiveRecord::Base.connection.execute
The new multi-database feature is great, however it is unclear to me how you can still execute raw mysql calling ActiveRecord::Base.connection.execute and have it select a specific database in the database.yml file.

this

ActiveRecord::Base.connected_to(role: :reading) do

end
Doesnt accept a database

ActiveRecord::Base.connection.execute  always seems to USE the first database in the config file.
thanks

Tried: ActiveRecord::Base.connected_to do ...
doesn't expect a database


问:
controlling a particular task inside a playbook
Is there a way we can control particular task alone to run on all nodes in parallel and rest run based on strategy defined ?  data_dir size is in GBs and want this to run on all hosts to reduce the time for backup.

This is the last task in the play

```<code>- name: Data backup
  become: true
  shell: cp -R {{ fs_mount }}/{{ data_dir }} {{ fs_mount }}/{{ data_dir }}_3
</code>```

In ansible.cfg strategy defined is "free".

Body:
Is there a way we can control particular task alone to run on all nodes in parallel and rest run based on strategy defined ?  data_dir size is in GBs and want this to run on all hosts to reduce the time for backup.

This is the last task in the play

- name: Data backup
  become: true
  shell: cp -R {{ fs_mount }}/{{ data_dir }} {{ fs_mount }}/{{ data_dir }}_3

In ansible.cfg strategy defined is "free".


问:
Java.Lang.IllegalStateException: Make sure to call FirebaseApp.initializeApp(Context) first.' xamarin.android
i am trying to implement fcm in my xamarin.android app using xamarin.forms. i am using the Plugin.FirebasePushNotification version 3.3.10 depending on this youtube tutorial: https://www.youtube.com/watch?v=7w2q2D6mR7g

i added Application.cs to my xamarin.android app:

```<code>using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Plugin.FirebasePushNotification;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearningWithCassidy.Droid
{
    [Application]
    public class MainApplication : Application
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();

            //Set the default notification channel for your app when running Android Oreo
            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                //Change for your default notification channel id here
                FirebasePushNotificationManager.DefaultNotificationChannelId = "FirebasePushNotificationChannel";

                //Change for your default notification channel name here
                FirebasePushNotificationManager.DefaultNotificationChannelName = "General";

                FirebasePushNotificationManager.DefaultNotificationChannelImportance = NotificationImportance.Max;
            }

            //If debug you should reset the token each time.
#if DEBUG
            FirebasePushNotificationManager.Initialize(this, true);
#else
            FirebasePushNotificationManager.Initialize(this, false);
#endif

            //Handle notification when app is closed here
            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {

            };
        }
    }
}

</code>```

and added this line to my MainActivity as mentioned:

```<code>
protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            LoadApplication(new App());

            FirebasePushNotificationManager.ProcessIntent(this, Intent);
        }
</code>```

i also added the internet permission to my manifest file. but when i launch my app i get this exception:

```<code>**Java.Lang.IllegalStateException:** 'Default FirebaseApp is not initialized in this process com.companyname.learningwithcassidy. Make sure to call FirebaseApp.initializeApp(Context) first.'
</code>```

i searched a lot and tried many things. i tried adding  FirebaseApp.InitializeApp(this); to my mainactivity but nothing happened. what am i doing wrong? many answers correspond to android studio i really trie understanding the probelm but couldn't. thanks in advance

Body:
i am trying to implement fcm in my xamarin.android app using xamarin.forms. i am using the Plugin.FirebasePushNotification version 3.3.10 depending on this youtube tutorial: https://www.youtube.com/watch?v=7w2q2D6mR7g

i added Application.cs to my xamarin.android app:

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Plugin.FirebasePushNotification;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearningWithCassidy.Droid
{
    [Application]
    public class MainApplication : Application
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();

            //Set the default notification channel for your app when running Android Oreo
            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                //Change for your default notification channel id here
                FirebasePushNotificationManager.DefaultNotificationChannelId = "FirebasePushNotificationChannel";

                //Change for your default notification channel name here
                FirebasePushNotificationManager.DefaultNotificationChannelName = "General";

                FirebasePushNotificationManager.DefaultNotificationChannelImportance = NotificationImportance.Max;
            }

            //If debug you should reset the token each time.
#if DEBUG
            FirebasePushNotificationManager.Initialize(this, true);
#else
            FirebasePushNotificationManager.Initialize(this, false);
#endif

            //Handle notification when app is closed here
            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {

            };
        }
    }
}

and added this line to my MainActivity as mentioned:

protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            LoadApplication(new App());

            FirebasePushNotificationManager.ProcessIntent(this, Intent);
        }

i also added the internet permission to my manifest file. but when i launch my app i get this exception:

**Java.Lang.IllegalStateException:** 'Default FirebaseApp is not initialized in this process com.companyname.learningwithcassidy. Make sure to call FirebaseApp.initializeApp(Context) first.'

i searched a lot and tried many things. i tried adding  FirebaseApp.InitializeApp(this); to my mainactivity but nothing happened. what am i doing wrong? many answers correspond to android studio i really trie understanding the probelm but couldn't. thanks in advance


问:
I had an error in my html project and renaming the file fixes it or makes it reoccur
I am trying to get into web development and got started on a simple website with a top bar for three different tabs that you can click through. That top bar started to resize when changing tabs and then reloading the website and I didn't know why.

I commented out everything, literally every bit of html that wasn't the "a" components for the tabs or a container thereof and all of my css and javascript and it still resized. I then made a new file where I just had those parts and deleted the comments and it worked. I then tried to rename my original file and nothing weird happened either. Now, when I rename it back to "main.html" it breaks again, when it's called anything else it works. Here's the full code before I commented anything out:

// script.js

function showHome() {
  document.getElementById("home").style.display = "block";
  document.getElementById("timeline").style.display = "none";
  document.getElementById("about").style.display = "none";

  document.querySelector('a[href="#home"]').classList.add('active');
  document.querySelector('a[href="#timeline"]').classList.remove('active');
  document.querySelector('a[href="#about"]').classList.remove('active');

  const homeTab = document.querySelector('a[href="#home"]');
  const line = document.querySelector('.line');
  line.style.left = `${homeTab.offsetLeft + homeTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

function showTimeline() {
  document.getElementById("home").style.display = "none";
  document.getElementById("timeline").style.display = "block";
  document.getElementById("about").style.display = "none";

  document.querySelector('a[href="#home"]').classList.remove('active');
  document.querySelector('a[href="#timeline"]').classList.add('active');
  document.querySelector('a[href="#about"]').classList.remove('active');

  const timelineTab = document.querySelector('a[href="#timeline"]');
  const line = document.querySelector('.line');
  line.style.left = `${timelineTab.offsetLeft + timelineTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

function showAbout() {
  document.getElementById("home").style.display = "none";
  document.getElementById("timeline").style.display = "none";
  document.getElementById("about").style.display = "block";

  document.querySelector('a[href="#home"]').classList.remove('active');
  document.querySelector('a[href="#timeline"]').classList.remove('active');
  document.querySelector('a[href="#about"]').classList.add('active');

  const aboutTab = document.querySelector('a[href="#about"]');
  const line = document.querySelector('.line');
  line.style.left = `${aboutTab.offsetLeft + aboutTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

function updateTabInfo() {
  var hashtag = window.location.hash;

  for (let tab of ['home', 'timeline', 'about']) {
    if (hashtag == `#${tab}`) {
      document.getElementById(tab).style.display = "block";
      document.querySelector(`a[href="#${tab}"]`).classList.add('active');
    } else {
      document.getElementById(`${tab}`).style.display = "none";
      document.querySelector(`[href="#${tab}"]`).classList.remove('active');
    }
  }

  const currentTab = document.querySelector(`a[href="${hashtag}"]`);
  const line = document.querySelector('.line');
  line.style.left = `${currentTab.offsetLeft + currentTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

window.onload = function() {
  updateTabInfo()
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* style.css */

@font-face {
  font-family: 'Palanquin Dark Regular';
  src: url('fonts/palanquindark-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Palanquin Dark Medium';
  src: url('fonts/palanquindark-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Palanquin Dark Semibold';
  src: url('fonts/palanquindark-semibold-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Palanquin Dark Bold';
  src: url('fonts/palanquindark-bold-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

#top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100px;
}

nav {
  position: fixed;
  text-align: center;
  top: 0;
  left: 0;
  right: 0;
  height: 100px;
}

nav a {
  padding-top: 20px;
  display: inline-block;
  text-decoration: none;
  color: black;
  font-size: 20px;
  margin: 0 7%;
  font-family: 'Palanquin Dark Bold', Tahoma, Verdana, sans-serif;
}

h1 {
  text-align: center;
  font-family: 'Palanquin Dark Regular', Tahoma, Verdana, sans-serif;
  font-size: 50px;
}

#content h1 {
  padding-top: 45px;
  padding-bottom: 10px;
}

#content {
  margin-top: 100px;
}

p {
  text-align: center;
  font-family: 'Palanquin Dark Semibold', Tahoma, Verdana, sans-serif;
  font-size: 25px;
  line-height: 40px;
  max-width: 50%;
  margin: 0 auto;
}

img {
  border-radius: 10px;
  width: 200px;
  height: 200px;
  object-fit: cover;
  object-position: center;
}

.timeline-element {
  margin-top: 20px;
}

#timeline {
  margin: auto 0;
}

#timeline-elements {
  margin: auto 0;
}

.tab-container {
  position: relative;
}

.line {
  background-color: black;
  height: 4px;
  width: 30px;
  transition: left 0.3s ease;
  position: relative;
  bottom: 0;
  border-radius: 2px;
  padding-left: 0;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>My Web Page</title>

  <link rel="stylesheet" href="style.css">

      Home
      Timeline
      About

Welcome to my beautiful website

well not quite beautiful yet but believe me we're getting there chat gpt is helping me with the technical stuff and i'm doing all of the design decisions

```

To test and debug the file I just dragged and dropped it into chrome.

Please focus on the specific question although I am sure I could use a lot of input on general html/css/javascript structure as well.

Body:
I am trying to get into web development and got started on a simple website with a top bar for three different tabs that you can click through. That top bar started to resize when changing tabs and then reloading the website and I didn't know why.

I commented out everything, literally every bit of html that wasn't the "a" components for the tabs or a container thereof and all of my css and javascript and it still resized. I then made a new file where I just had those parts and deleted the comments and it worked. I then tried to rename my original file and nothing weird happened either. Now, when I rename it back to "main.html" it breaks again, when it's called anything else it works. Here's the full code before I commented anything out:

// script.js

function showHome() {
  document.getElementById("home").style.display = "block";
  document.getElementById("timeline").style.display = "none";
  document.getElementById("about").style.display = "none";

  document.querySelector('a[href="#home"]').classList.add('active');
  document.querySelector('a[href="#timeline"]').classList.remove('active');
  document.querySelector('a[href="#about"]').classList.remove('active');

  const homeTab = document.querySelector('a[href="#home"]');
  const line = document.querySelector('.line');
  line.style.left = `${homeTab.offsetLeft + homeTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

function showTimeline() {
  document.getElementById("home").style.display = "none";
  document.getElementById("timeline").style.display = "block";
  document.getElementById("about").style.display = "none";

  document.querySelector('a[href="#home"]').classList.remove('active');
  document.querySelector('a[href="#timeline"]').classList.add('active');
  document.querySelector('a[href="#about"]').classList.remove('active');

  const timelineTab = document.querySelector('a[href="#timeline"]');
  const line = document.querySelector('.line');
  line.style.left = `${timelineTab.offsetLeft + timelineTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

function showAbout() {
  document.getElementById("home").style.display = "none";
  document.getElementById("timeline").style.display = "none";
  document.getElementById("about").style.display = "block";

  document.querySelector('a[href="#home"]').classList.remove('active');
  document.querySelector('a[href="#timeline"]').classList.remove('active');
  document.querySelector('a[href="#about"]').classList.add('active');

  const aboutTab = document.querySelector('a[href="#about"]');
  const line = document.querySelector('.line');
  line.style.left = `${aboutTab.offsetLeft + aboutTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

function updateTabInfo() {
  var hashtag = window.location.hash;

  for (let tab of ['home', 'timeline', 'about']) {
    if (hashtag == `#${tab}`) {
      document.getElementById(tab).style.display = "block";
      document.querySelector(`a[href="#${tab}"]`).classList.add('active');
    } else {
      document.getElementById(`${tab}`).style.display = "none";
      document.querySelector(`[href="#${tab}"]`).classList.remove('active');
    }
  }

  const currentTab = document.querySelector(`a[href="${hashtag}"]`);
  const line = document.querySelector('.line');
  line.style.left = `${currentTab.offsetLeft + currentTab.offsetWidth / 2 - line.offsetWidth / 2}px`;
}

window.onload = function() {
  updateTabInfo()
};

/* style.css */

@font-face {
  font-family: 'Palanquin Dark Regular';
  src: url('fonts/palanquindark-regular-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Palanquin Dark Medium';
  src: url('fonts/palanquindark-medium-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Palanquin Dark Semibold';
  src: url('fonts/palanquindark-semibold-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: 'Palanquin Dark Bold';
  src: url('fonts/palanquindark-bold-webfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

#top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 100px;
}

nav {
  position: fixed;
  text-align: center;
  top: 0;
  left: 0;
  right: 0;
  height: 100px;
}

nav a {
  padding-top: 20px;
  display: inline-block;
  text-decoration: none;
  color: black;
  font-size: 20px;
  margin: 0 7%;
  font-family: 'Palanquin Dark Bold', Tahoma, Verdana, sans-serif;
}

h1 {
  text-align: center;
  font-family: 'Palanquin Dark Regular', Tahoma, Verdana, sans-serif;
  font-size: 50px;
}

#content h1 {
  padding-top: 45px;
  padding-bottom: 10px;
}

#content {
  margin-top: 100px;
}

p {
  text-align: center;
  font-family: 'Palanquin Dark Semibold', Tahoma, Verdana, sans-serif;
  font-size: 25px;
  line-height: 40px;
  max-width: 50%;
  margin: 0 auto;
}

img {
  border-radius: 10px;
  width: 200px;
  height: 200px;
  object-fit: cover;
  object-position: center;
}

.timeline-element {
  margin-top: 20px;
}

#timeline {
  margin: auto 0;
}

#timeline-elements {
  margin: auto 0;
}

.tab-container {
  position: relative;
}

.line {
  background-color: black;
  height: 4px;
  width: 30px;
  transition: left 0.3s ease;
  position: relative;
  bottom: 0;
  border-radius: 2px;
  padding-left: 0;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>My Web Page</title>

  <link rel="stylesheet" href="style.css">

      Home
      Timeline
      About

Welcome to my beautiful website

well not quite beautiful yet but believe me we're getting there chat gpt is helping me with the technical stuff and i'm doing all of the design decisions

To test and debug the file I just dragged and dropped it into chrome.

Please focus on the specific question although I am sure I could use a lot of input on general html/css/javascript structure as well.


问:
getting correct data from mettler teledo
I am reading data from a scale Mettler toledo using USB to RS232
I am successfully getting data with the following setting using C#.NET

```<code>Port.BaudRate = (int)baudRate;
Port.Handshake = Handshake.XOnXOff;Port.Parity = Parity.Even; //Even,None,Odd supported
Port.DataBits = 7;

Port.StopBits = StopBits.One;
Port.ReadTimeout = 2000;
Port.WriteTimeout = 500;
Port.ReadBufferSize = 2048;
Port.ReceivedBytesThreshold = 1;
Port.WriteBufferSize = 1024;
Port.DtrEnable = true; //enable Data Terminal Ready
Port.RtsEnable = false; //enable Request to send
</code>```

the setting on my display toledo is set to continuous output

I am able to get the weight in real-time, but it comes with a bunch of data as follows

A*0     15     00

or

A*0     15     0

or

The first set may vary but the middle one which is the weight changes according to what is on the scale

I did try to remove special characters using regex, reducing the white spaces and splitting the data, to get only the middle one but it wasn't successful

What I want to achieve is only to get the weight [middle value]

Body:
I am reading data from a scale Mettler toledo using USB to RS232
I am successfully getting data with the following setting using C#.NET

Port.BaudRate = (int)baudRate;
Port.Handshake = Handshake.XOnXOff;Port.Parity = Parity.Even; //Even,None,Odd supported
Port.DataBits = 7;

Port.StopBits = StopBits.One;
Port.ReadTimeout = 2000;
Port.WriteTimeout = 500;
Port.ReadBufferSize = 2048;
Port.ReceivedBytesThreshold = 1;
Port.WriteBufferSize = 1024;
Port.DtrEnable = true; //enable Data Terminal Ready
Port.RtsEnable = false; //enable Request to send

the setting on my display toledo is set to continuous output

I am able to get the weight in real-time, but it comes with a bunch of data as follows

A*0     15     00

or

A*0     15     0

or

The first set may vary but the middle one which is the weight changes according to what is on the scale

I did try to remove special characters using regex, reducing the white spaces and splitting the data, to get only the middle one but it wasn't successful

What I want to achieve is only to get the weight [middle value]


问:
Why no commandline/powershell command can copy a snapshot image of a open PST file, yet File explorer copy can?
I am trying to automate some backing up of important stuff in a computer, specifically I want to automate backing up local Outlook archives (.pst). The thing is that these computer's users might be using the computer (and thus, outlook and the pst files that Outlook reads/writes to) at the same time.
I figured that the "easy enough" fix was to automate a VSS copy, and then copy the file in the Shadow Copy. I tested it, but it didn't work! paradoxically, it seemed to work just fine if I copied the file BY HAND, in file explorer, but if I try to use xcopy, robocopy or copy-Item, it throws an error.

I can't manage to avoid the problem of "you can't copy a file that's being acessed"... Not even by using a VSS!

This is a code I managed to put together that creates a Volume Shadow copy, copies the file from the shadow copy and deletes the shadow copy afterwards:

```<code>#Data
$SourceDir=$env:USERPROFILE+'\Documents\Outlook Files' #Location of PST files
$TargetDir='\\NetworkLocation\Resource\Folder'
$logFile='"'+$SourceDir+'\Outlook-backup.log"'

if (-not (Test-Path -LiteralPath $SourceDir)){
    throw "Source: `"$SourceDir`" does not exist"
}
if (-not (Test-Path -LiteralPath $TargetDir)){
    throw "Target: `"$SourceDir`" does not exist"
}

$SourceDir = Get-Item -LiteralPath $SourceDir
$TargetDir = Get-Item -LiteralPath $TargetDir

#Create Volume Shadow Copy
$s1 = (Get-WmiObject -List Win32_ShadowCopy).Create("C:\\", "ClientAccessible")
try{
    $s2 = Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $s1.ShadowID }
    $d  = $s2.DeviceObject + "\\"

    #Create symlink to the snapshot for easy access
    cmd /c mklink /d C:\shadowcopy "$d"

    #Find file location inside snapshot
    $null=$SourceDir.FullName -match "(?<=^[a-z]:\\).*$"
    $ShadowSource = "C:\shadowcopy\"+$Matches[0]
    if (-not (Test-Path -LiteralPath $ShadowSource)){
        throw "Shadow source: `"$ShadowSource`" does not exist"
    }
    $ShadowSource = $ShadowSource | Get-Item

    #Copy file from snapshot
    robocopy.exe $ShadowSource.FullName $TargetDir.fullname /MIR /COPY:DAT /J /Z /COMPRESS /R:3 /W:5 /NP /UNILOG:$logFile #/L
    #ROBOCOPY FAILS TO COPY THE FILES
}
catch{
    Write-Host "Error occurred $($_.ScriptStackTrace)"
    Write-Host $_
}
finally{
    #Delete snapshot (In two different ways just in case)
    "vssadmin delete shadows /Shadow=""$($s1.ShadowID.ToLower())"" /Quiet" | iex
    "vssadmin delete shadows /Shadow=""$($s2.ID.ToLower())"" /Quiet" | iex
    #Delete Junction
    cmd.exe /c "rmdir C:\shadowcopy\ & exit"
}
</code>```

The error logged by robocopy for every PST file is:

```<code>ERROR 33 (0x00000021) [...]The process cannot access the file because another process has locked a portion of the file.
</code>```

How is this possible? Aren't Snapshots supposed to be read-only? Why does it work fine when doint it by hand in file explorer?

Body:
I am trying to automate some backing up of important stuff in a computer, specifically I want to automate backing up local Outlook archives (.pst). The thing is that these computer's users might be using the computer (and thus, outlook and the pst files that Outlook reads/writes to) at the same time.
I figured that the "easy enough" fix was to automate a VSS copy, and then copy the file in the Shadow Copy. I tested it, but it didn't work! paradoxically, it seemed to work just fine if I copied the file BY HAND, in file explorer, but if I try to use xcopy, robocopy or copy-Item, it throws an error.

I can't manage to avoid the problem of "you can't copy a file that's being acessed"... Not even by using a VSS!

This is a code I managed to put together that creates a Volume Shadow copy, copies the file from the shadow copy and deletes the shadow copy afterwards:

#Data
$SourceDir=$env:USERPROFILE+'\Documents\Outlook Files' #Location of PST files
$TargetDir='\\NetworkLocation\Resource\Folder'
$logFile='"'+$SourceDir+'\Outlook-backup.log"'

if (-not (Test-Path -LiteralPath $SourceDir)){
    throw "Source: `"$SourceDir`" does not exist"
}
if (-not (Test-Path -LiteralPath $TargetDir)){
    throw "Target: `"$SourceDir`" does not exist"
}

$SourceDir = Get-Item -LiteralPath $SourceDir
$TargetDir = Get-Item -LiteralPath $TargetDir

#Create Volume Shadow Copy
$s1 = (Get-WmiObject -List Win32_ShadowCopy).Create("C:\\", "ClientAccessible")
try{
    $s2 = Get-WmiObject Win32_ShadowCopy | Where-Object { $_.ID -eq $s1.ShadowID }
    $d  = $s2.DeviceObject + "\\"

    #Create symlink to the snapshot for easy access
    cmd /c mklink /d C:\shadowcopy "$d"

    #Find file location inside snapshot
    $null=$SourceDir.FullName -match "(?<=^[a-z]:\\).*$"
    $ShadowSource = "C:\shadowcopy\"+$Matches[0]
    if (-not (Test-Path -LiteralPath $ShadowSource)){
        throw "Shadow source: `"$ShadowSource`" does not exist"
    }
    $ShadowSource = $ShadowSource | Get-Item

    #Copy file from snapshot
    robocopy.exe $ShadowSource.FullName $TargetDir.fullname /MIR /COPY:DAT /J /Z /COMPRESS /R:3 /W:5 /NP /UNILOG:$logFile #/L
    #ROBOCOPY FAILS TO COPY THE FILES
}
catch{
    Write-Host "Error occurred $($_.ScriptStackTrace)"
    Write-Host $_
}
finally{
    #Delete snapshot (In two different ways just in case)
    "vssadmin delete shadows /Shadow=""$($s1.ShadowID.ToLower())"" /Quiet" | iex
    "vssadmin delete shadows /Shadow=""$($s2.ID.ToLower())"" /Quiet" | iex
    #Delete Junction
    cmd.exe /c "rmdir C:\shadowcopy\ & exit"
}

The error logged by robocopy for every PST file is:

ERROR 33 (0x00000021) [...]The process cannot access the file because another process has locked a portion of the file.

How is this possible? Aren't Snapshots supposed to be read-only? Why does it work fine when doint it by hand in file explorer?


问:
Javascript Object Finding Game
im currently having a big problem with a javascript little game im programming. Essentially the player finds specific objects, but to make it easier i want to make a menu to show which objects are there to find

```<code>for (let i = 0; i < figuresCount; i++) {
        var img = document.createElement("img");
        img.src = "figure" + randomNumber(1,10)+ ".svg";
        img.id = "figure"+i;
        var div = document.getElementById("main");
        div.appendChild(img);
        document.getElementById("figure"+i).style.top = randomNumber(10, 95) + "%";
        document.getElementById("figure"+i).style.left = randomNumber(1, 90) + "%";
        document.getElementById("figure"+i).style.width = randomNumber(30, 60) + "px";
        document.getElementById("figure"+i).style.transform = "rotate("+ randomNumber(0,360) +"deg)";
        document.getElementById("figure"+i).style.position = "fixed";
        document.getElementById("figure"+i).addEventListener("click", findFigure);
    }
</code>```

this is the loop where the objects are taken and shown on the playing field. The problem im having is saving the same randomized photos in the menu. Another thing that is difficult is that when a specific object is found, then the object in the menu should disappear too. Can someone help me with this?

I tried creating another variable and saving it there but it does not work.

```<code>var menu = document.getElementById("menu");
        menu.appendChild(img);
</code>```

Title: Javascript Object Finding Game

Body:
im currently having a big problem with a javascript little game im programming. Essentially the player finds specific objects, but to make it easier i want to make a menu to show which objects are there to find

for (let i = 0; i < figuresCount; i++) {
        var img = document.createElement("img");
        img.src = "figure" + randomNumber(1,10)+ ".svg";
        img.id = "figure"+i;
        var div = document.getElementById("main");
        div.appendChild(img);
        document.getElementById("figure"+i).style.top = randomNumber(10, 95) + "%";
        document.getElementById("figure"+i).style.left = randomNumber(1, 90) + "%";
        document.getElementById("figure"+i).style.width = randomNumber(30, 60) + "px";
        document.getElementById("figure"+i).style.transform = "rotate("+ randomNumber(0,360) +"deg)";
        document.getElementById("figure"+i).style.position = "fixed";
        document.getElementById("figure"+i).addEventListener("click", findFigure);
    }

this is the loop where the objects are taken and shown on the playing field. The problem im having is saving the same randomized photos in the menu. Another thing that is difficult is that when a specific object is found, then the object in the menu should disappear too. Can someone help me with this?

I tried creating another variable and saving it there but it does not work.

var menu = document.getElementById("menu");
        menu.appendChild(img);


问:
Flutter Plugin IOS Error - [Security] This method should not be called on the main thread as it may lead to UI unresponsiveness
I am trying to implement flutter version of this IOS Code - https://developer.mastercard.com/open-banking-us/documentation/connect/mobile-sdks/#ios

I am facing this issue when I am trying to connect the Connect SDK

```<code>2022-12-21 23:52:39.678730+0530 Runner[36839:1696429] [Security] This method should not be called on the main thread as it may lead to UI unresponsiveness.
</code>```

This is the Code I have written so far:

```<code>import Flutter
import UIKit
import Connect

public class SwiftFinicityPlugin: NSObject, FlutterPlugin {
  var flutterResult: FlutterResult!
  var connectViewController: ConnectViewController!
  var connectNavController: UINavigationController!
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "finicity", binaryMessenger: registrar.messenger())
    let instance = SwiftFinicityPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    flutterResult = result;
    guard let args = call.arguments as? [String : Any] else {return}
    let connectUrl = args["connectUrl"] as! String
    let config = ConnectViewConfig(connectUrl: connectUrl, loaded: self.connectLoaded, done: self.connectDone, cancel: self.connectCancelled, error: self.connectError, route: self.connectRoute, userEvent: self.connectUserEvent)
    flutterResult("iOS " + UIDevice.current.systemVersion)
    self.connectViewController = ConnectViewController()
    self.connectViewController.load(config: config)
  }

  func connectLoaded() {
    self.connectNavController = UINavigationController(rootViewController: self.connectViewController)
    self.connectNavController.modalPresentationStyle = .fullScreen
     self.present(self.connectNavController, animated: false)
}

func connectDone(_ data: NSDictionary?) {
  flutterResult("iOS " + UIDevice.current.systemVersion)
}

func connectCancelled() {
     // Connect flow exited prematurely
}

func connectError(_ data: NSDictionary?) {
     // Error encountered in Connect flow
}

func connectRoute(_data: NSDictionary?) {
 // Connect route changed
}

func connectUserEvent(_ data: NSDictionary?) {
 // Connect user event fired in response to user action
}
}
</code>```

Body:
I am trying to implement flutter version of this IOS Code - https://developer.mastercard.com/open-banking-us/documentation/connect/mobile-sdks/#ios

I am facing this issue when I am trying to connect the Connect SDK

2022-12-21 23:52:39.678730+0530 Runner[36839:1696429] [Security] This method should not be called on the main thread as it may lead to UI unresponsiveness.

This is the Code I have written so far:

import Flutter
import UIKit
import Connect

public class SwiftFinicityPlugin: NSObject, FlutterPlugin {
  var flutterResult: FlutterResult!
  var connectViewController: ConnectViewController!
  var connectNavController: UINavigationController!
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "finicity", binaryMessenger: registrar.messenger())
    let instance = SwiftFinicityPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    flutterResult = result;
    guard let args = call.arguments as? [String : Any] else {return}
    let connectUrl = args["connectUrl"] as! String
    let config = ConnectViewConfig(connectUrl: connectUrl, loaded: self.connectLoaded, done: self.connectDone, cancel: self.connectCancelled, error: self.connectError, route: self.connectRoute, userEvent: self.connectUserEvent)
    flutterResult("iOS " + UIDevice.current.systemVersion)
    self.connectViewController = ConnectViewController()
    self.connectViewController.load(config: config)
  }

  func connectLoaded() {
    self.connectNavController = UINavigationController(rootViewController: self.connectViewController)
    self.connectNavController.modalPresentationStyle = .fullScreen
     self.present(self.connectNavController, animated: false)
}

func connectDone(_ data: NSDictionary?) {
  flutterResult("iOS " + UIDevice.current.systemVersion)
}

func connectCancelled() {
     // Connect flow exited prematurely
}

func connectError(_ data: NSDictionary?) {
     // Error encountered in Connect flow
}

func connectRoute(_data: NSDictionary?) {
 // Connect route changed
}

func connectUserEvent(_ data: NSDictionary?) {
 // Connect user event fired in response to user action
}
}


问:
GCP Workflow: serving is disabled for this workflow
I have error in GCP Workflow which says:

```<code>{
  "error": {
    "code": 400,
    "message": "serving is disabled for this workflow",
    "status": "FAILED_PRECONDITION"
  }
}
</code>```

Could someone please help to understand how to enable serving?

Body:
I have error in GCP Workflow which says:

{
  "error": {
    "code": 400,
    "message": "serving is disabled for this workflow",
    "status": "FAILED_PRECONDITION"
  }
}

Could someone please help to understand how to enable serving?


问:
Native Base Medium/Bold fonts show up the same as Regular font
I'm building a react native app, and I've linked my fonts to my projects. For iOS, i'm having trouble with the font variations. I am using the Roboto font family, and no matter what font weight variation I use, it shows up as "Roboto-Regular".

If I do:
fontFamily: 'Roboto-Medium' or
fontFamily: 'Roboto-Bold'

It displays the same as Roboto-Regular. I am not having this issue in Android. The fonts folder is added to the Bundle Resources, and to the info.plist.

Just to test things out further if i do:
fontFamily: 'Roboto-sMedium' it will show a warning message "Unrecognized fontFamily", and revert to a system default font.

There is no problem in xcode recognizing the font family, but I cannot get the Medium and Bold variations to show properly.

Any suggestions?

--edit--

I figured out this was an issue with the Native Base elements I am using, where the style attributes were not recognizing the font weight variations on any Native Base elements.

For example, the <Text> element from Native Base didn't recognize the font weight variation of style={{fontFamily: 'Roboto-Medium'}}

If I switched to the react native <Text> element it would work appropriately.

I realize that you need to customize the them in Native Base to use the font properties as noted here:
https://docs.nativebase.io/customizing-fonts

However, I did not expect that the font-family style attributes would not work.


问:
Which one should I use to render the main project in React.js
I created a React project with Yarn Vite and in the main.tsx the <App /> component was called inside a pair of <React.StrictMode></React.StrictMode>.

It is rendering the application normally and everything is working, only thing that bothers me is that all the console.log I use appears twice in the console. I have already changed to nameless tags for example: <></> and to <React.Fragment></React.Fragment>, both of which solve the problem of the console.log appearing duplicate.

I wanted to know which is the most appropriate way to use and what are the differences between these tags.

I read about the <React.StrictMode></React.StrictMode> at https://pt-br.reactjs.org/docs/strict-mode.html and understood that it is used for verifications, but I didn't quite understand which is the most proper one to use.


问:
DataGrid Event Handler has an error that prevents the live view from being updated
I am having an interesting issue. I am using Visual Studio 2022. In my XAML code, I have a DataGrid with EventSetter. The Handler is alerting on "Invalid value for property 'Handler'. This error prevents the live view from being updated. I have either to rebuild the project or remove the EventSetter and write it back every time for the live view to update.

Is it something that I have to resolve in the VS setup or the code behind?

I was trying to add an Event Handler for DataGrid. It is successfully working but the Handler has an error. This prevents the live view from refreshing, when I am making changes on the XAML code.


问:
Game tree for Othello(Reversi) in pyhton
I have to write this function that generates a game tree for Othello (or Reversi), without using any library, that at the end gives me as an output a tuple (a,b,c) with:

a: the number of situations that result in a black win

b: the number of situations that result in a white win

c: the number of situations that result in a draw.

I have to work with these boards given as a txt file, as such:

```<code>. . W W
. . B B
W W W B
W B B W
</code>```

The problem is I get a wrong output (different from the expected one). In the given exemple above, the output tuple should be (2, 16, 0), but I get (5, 7, 11). Below I will leave you the code, and I can't figure out what did I do wrong.

```<code>def generate_game_tree(filename: str):

    # Load the board from the file
    board = [line.split() for line in open(filename)]

    # Initialize the game tree with the root node representing the current board state
    game_tree = [(board, 0)]
    black_count = 0
    white_count = 0
    draw_count = 0
    # Generate the game tree by expanding the nodes in a breadth-first manner
    i = 0
    while i < len(game_tree):
        node = game_tree[i]
        board, _ = node
        valid_moves = get_valid_moves(board)
        for move in valid_moves:
            new_board = make_move(board, move)
            game_tree.append((new_board, i))
        i += 1
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j] == "W":
                white_count += 1
            if board[i][j] == "B":
                black_count += 1
            else:
                draw_count += 1

    return black_count, white_count, draw_count

def make_move(board, move):
    flips = []
    x, y = move
    curr_color = board[x][y]
    for dx, dy in [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]:
        x, y = move
        x += dx
        y += dy
        if not (0 <= x < len(board) and 0 <= y < len(board[0])):
            continue
        if board[x][y] != '.':
            continue
        while board[x][y] != curr_color:
            flips.append((x, y))
            x += dx
            y += dy
            if not (0 <= x < len(board) and 0 <= y < len(board[0])):
                break
    return flips

def get_valid_moves(board):
    valid_moves = []
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j] != '.':
                continue
            flips = make_move(board, (i, j))
            if flips:
                valid_moves.append((i, j))
    return valid_moves
</code>```

Body:
I have to write this function that generates a game tree for Othello (or Reversi), without using any library, that at the end gives me as an output a tuple (a,b,c) with:

a: the number of situations that result in a black win

b: the number of situations that result in a white win

c: the number of situations that result in a draw.

I have to work with these boards given as a txt file, as such:

. . W W
. . B B
W W W B
W B B W

The problem is I get a wrong output (different from the expected one). In the given exemple above, the output tuple should be (2, 16, 0), but I get (5, 7, 11). Below I will leave you the code, and I can't figure out what did I do wrong.

def generate_game_tree(filename: str):

    # Load the board from the file
    board = [line.split() for line in open(filename)]

    # Initialize the game tree with the root node representing the current board state
    game_tree = [(board, 0)]
    black_count = 0
    white_count = 0
    draw_count = 0
    # Generate the game tree by expanding the nodes in a breadth-first manner
    i = 0
    while i < len(game_tree):
        node = game_tree[i]
        board, _ = node
        valid_moves = get_valid_moves(board)
        for move in valid_moves:
            new_board = make_move(board, move)
            game_tree.append((new_board, i))
        i += 1
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j] == "W":
                white_count += 1
            if board[i][j] == "B":
                black_count += 1
            else:
                draw_count += 1

    return black_count, white_count, draw_count

def make_move(board, move):
    flips = []
    x, y = move
    curr_color = board[x][y]
    for dx, dy in [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]:
        x, y = move
        x += dx
        y += dy
        if not (0 <= x < len(board) and 0 <= y < len(board[0])):
            continue
        if board[x][y] != '.':
            continue
        while board[x][y] != curr_color:
            flips.append((x, y))
            x += dx
            y += dy
            if not (0 <= x < len(board) and 0 <= y < len(board[0])):
                break
    return flips

def get_valid_moves(board):
    valid_moves = []
    for i in range(len(board)):
        for j in range(len(board[0])):
            if board[i][j] != '.':
                continue
            flips = make_move(board, (i, j))
            if flips:
                valid_moves.append((i, j))
    return valid_moves


问:
label for captcha field in Drupal 9
How can I add a label for captcha field in Drupal 9 webform

I tried to edit the field as any normal field , but there is no way to enter a label for it through the UI

Title: label for captcha field in Drupal 9


问:
Useless queries after migrating to Hibernate 6
I tried to migrate a spring boot project to the newest version. Which included an upgrade to hibernate 6. I have done that before and never had an issue like this. I use spring-data-jpa Repositories with an MSSQL Database. After the Update close to all of my queries are broken. I debugged into it and found out, the JPQL looks fine. But somewhere on the way to TransactSQL something mysterious is happening.
I'd like to show you three of the problems I faced.

Problem Nr. 1

```<code>@Entity public class Gender {
    ...
}

@Entity public class Person {
    @ManyToOne public Gender gender;
    @Embedded public Details details;
}
</code>```

With something as simple as this. I expected to see select ... from Person or maybe even select ... from Person p left join Gender g on ... if Gender is fetched eagerly. But what i got was

```<code>select ... from Person p1 left join Person p2 on p1.id = p2.id left join Gender g on ...
</code>```

which works but it is rather useless to have that second join on Person.

Problem Nr. 2

resultPerson.details is null although the query actually returned values for the columns inside Person.details.

Problem Nr. 3

A more complex query I wrote myself now joins stuff in the wrong order:

```<code>select Person p1
left join Something s1 on s2.somethingId = s1.somethingId
left join SomethingElse s2 on ...
</code>```

Question

All these queries worked fine before the upgrade and haven't been touched during the upgrade. All the errors are so diverse, that I don't even know where to start looking. I don't expect you to solve my problems. I'm just asking for hints. Hope anybody has seen this before.

Body:
I tried to migrate a spring boot project to the newest version. Which included an upgrade to hibernate 6. I have done that before and never had an issue like this. I use spring-data-jpa Repositories with an MSSQL Database. After the Update close to all of my queries are broken. I debugged into it and found out, the JPQL looks fine. But somewhere on the way to TransactSQL something mysterious is happening.
I'd like to show you three of the problems I faced.

Problem Nr. 1

@Entity public class Gender {
    ...
}

@Entity public class Person {
    @ManyToOne public Gender gender;
    @Embedded public Details details;
}

With something as simple as this. I expected to see select ... from Person or maybe even select ... from Person p left join Gender g on ... if Gender is fetched eagerly. But what i got was

select ... from Person p1 left join Person p2 on p1.id = p2.id left join Gender g on ...

which works but it is rather useless to have that second join on Person.

Problem Nr. 2

resultPerson.details is null although the query actually returned values for the columns inside Person.details.

Problem Nr. 3

A more complex query I wrote myself now joins stuff in the wrong order:

select Person p1
left join Something s1 on s2.somethingId = s1.somethingId
left join SomethingElse s2 on ...

Question

All these queries worked fine before the upgrade and haven't been touched during the upgrade. All the errors are so diverse, that I don't even know where to start looking. I don't expect you to solve my problems. I'm just asking for hints. Hope anybody has seen this before.


问:
Python import files are overwritten in parallel run
I have a python module to be called from a shell script,

Script sample: test.ksh "a" "b"

```<code>#!/usr/bin/ksh
export A=$1
export B=$2
# The parameter are exported to the property file using "envsubst" command.
envsubst < /var/apps/test_1_properties.py.template > /var/apps/test_1_properties.py
python3 /var/apps/test_1.py

envsubst < /var/apps/test_2_properties.py.template > /var/apps/test_2_properties.py
python3 /var/apps/test_2.py
</code>```

But each python module uses a property file to read few dynamic variables and that will used in the main modules. The property files are called using import.

Now, the issue is, with the situation where we will run the test.ksh script in parallel with different parameter and during the execution of python modules the dynamic variables are getting overwritten in the property files.
Need to know a different way to avoid the overwriting issue in the property files called in the main modules during the parallel run??

Body:
I have a python module to be called from a shell script,

Script sample: test.ksh "a" "b"

#!/usr/bin/ksh
export A=$1
export B=$2
# The parameter are exported to the property file using "envsubst" command.
envsubst < /var/apps/test_1_properties.py.template > /var/apps/test_1_properties.py
python3 /var/apps/test_1.py

envsubst < /var/apps/test_2_properties.py.template > /var/apps/test_2_properties.py
python3 /var/apps/test_2.py

But each python module uses a property file to read few dynamic variables and that will used in the main modules. The property files are called using import.

Now, the issue is, with the situation where we will run the test.ksh script in parallel with different parameter and during the execution of python modules the dynamic variables are getting overwritten in the property files.
Need to know a different way to avoid the overwriting issue in the property files called in the main modules during the parallel run??


问:
How can I stop Kafka from retrying connections?
I have a structured streaming application that reads messages from Kafka and then shuts down. However, if the kafka broker is down or unreachable, my application will attempt to reconnect indefinitely. I would prefer that it shuts down after 2-3 retries and let my orchestration engine handle alerting and retrying.

It seems like Kafka does not expose any configuration options on the consumer side that would allow us to stop attempting reconnects after a certain time period or retry count.

https://github.com/apache/kafka/blob/6ab4d047d563e0fe42a7c0ed6f10ddecda135595/clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerConfig.java

The only configurations that I found in the ConsumerConfig that might assist us with this are the following:

```<code>kafka.reconnect.backoff.ms
kafka.reconnect.backoff.max.ms
kafka.socket.connection.setup.timeout.max.ms
</code>```

Here is my Structured Streaming code for reference:

```<code>val checkpointUrl = "s3://mybucket/experiment/checkpoint/"
val url = "s3://mybucket/experiment/triggerOnce/"

val df = spark
  .readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "X.X.X.X:9092")
  .option("kafka.reconnect.backoff.max.ms", 1000)
  .option("kafka.socket.connection.setup.timeout.max.ms", 10000)
  .option("subscribe", "experiment3")
  .load()
  .writeStream
  .format("csv")
  .option("checkpointLocation", checkpointUrl)
  .trigger(Trigger.Once())
  .start(url)
  .awaitTermination()
</code>```

I am currently looking into if there is a way to leverage SparkListeners to intervene within the reconnection logic.

Body:
I have a structured streaming application that reads messages from Kafka and then shuts down. However, if the kafka broker is down or unreachable, my application will attempt to reconnect indefinitely. I would prefer that it shuts down after 2-3 retries and let my orchestration engine handle alerting and retrying.

It seems like Kafka does not expose any configuration options on the consumer side that would allow us to stop attempting reconnects after a certain time period or retry count.

https://github.com/apache/kafka/blob/6ab4d047d563e0fe42a7c0ed6f10ddecda135595/clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerConfig.java

The only configurations that I found in the ConsumerConfig that might assist us with this are the following:

kafka.reconnect.backoff.ms
kafka.reconnect.backoff.max.ms
kafka.socket.connection.setup.timeout.max.ms

Here is my Structured Streaming code for reference:

val checkpointUrl = "s3://mybucket/experiment/checkpoint/"
val url = "s3://mybucket/experiment/triggerOnce/"

val df = spark
  .readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "X.X.X.X:9092")
  .option("kafka.reconnect.backoff.max.ms", 1000)
  .option("kafka.socket.connection.setup.timeout.max.ms", 10000)
  .option("subscribe", "experiment3")
  .load()
  .writeStream
  .format("csv")
  .option("checkpointLocation", checkpointUrl)
  .trigger(Trigger.Once())
  .start(url)
  .awaitTermination()

I am currently looking into if there is a way to leverage SparkListeners to intervene within the reconnection logic.


问:
Naming and calling a dynamically created checkbox
So I'm creating an online catalog for collectibles. I want the user to be able to wishlist items that they want to acquire via a checkbox. However, eventually, the database will contain thousands of items, so I've first implemented a few basic dropdown filters on the search page for dynamically narrowing the list down to the most relevant items. This means the checkboxes are dynamically generated too. (Eventually, I'll also implement a search function, but that's for later.)

Here's the abbreviated code for my dropdown filters:

```<code>//Dropdown menus for sorting through the db
<form method="post">
    //Dropdown menus here for filtering through db, not reproduced for brevity

    //Submit button for dropdowns
    <input type="submit" id="Filter" name="Filter"></input>
</form>
</code>```

And here's the code for the PHP functions:

```<code><?php
    //Establishes connection
    include_once "config.php";

    if($_SERVER["REQUEST_METHOD"] == "POST") {

        //Writes out filtered results
        if (isset($_POST['Filter'])){\
            //Sanitize inputs, search db, and store results in $limit (which has column ITEM), then:
            while ($row = mysqli_fetch_assoc($limit)) {
                //Echo lots of stuff, notably this line:
                echo '<div><form method="post"><p>Wishlist</p><input type="checkbox" name="wishlist[' . htmlspecialchars($row['ITEM']) . ']" value="' . htmlspecialchars($row['ITEM']) . '"></input></form></div>';
            }
        }

        //Test function by calling entire array of wishlist checkboxes
        if (isset($_POST['wishlist'])){
            echo 'Test';
        }
    }
?>
</code>```

Clicking submit after selecting whatever dropdown options currently works fine and populates the page with filtered results. Each checkbox is correctly displayed (and clickable) next to each entry on the page, but when I click one (or all), my test function doesn't write anything to the page. var_dump($_POST['wishlist']); confirms that clicking the checkboxes doesn't update the POST wishlist array at all (stays NULL).

I'm probably going about this all wrong. What's a better way to call a dynamically created form?

Body:
So I'm creating an online catalog for collectibles. I want the user to be able to wishlist items that they want to acquire via a checkbox. However, eventually, the database will contain thousands of items, so I've first implemented a few basic dropdown filters on the search page for dynamically narrowing the list down to the most relevant items. This means the checkboxes are dynamically generated too. (Eventually, I'll also implement a search function, but that's for later.)

Here's the abbreviated code for my dropdown filters:

//Dropdown menus for sorting through the db
<form method="post">
    //Dropdown menus here for filtering through db, not reproduced for brevity

    //Submit button for dropdowns
    <input type="submit" id="Filter" name="Filter"></input>
</form>

And here's the code for the PHP functions:

<?php
    //Establishes connection
    include_once "config.php";

    if($_SERVER["REQUEST_METHOD"] == "POST") {

        //Writes out filtered results
        if (isset($_POST['Filter'])){\
            //Sanitize inputs, search db, and store results in $limit (which has column ITEM), then:
            while ($row = mysqli_fetch_assoc($limit)) {
                //Echo lots of stuff, notably this line:
                echo '
<form method="post">
Wishlist
<input type="checkbox" name="wishlist[' . htmlspecialchars($row['ITEM']) . ']" value="' . htmlspecialchars($row['ITEM']) . '"></input></form>
';
            }
        }

        //Test function by calling entire array of wishlist checkboxes
        if (isset($_POST['wishlist'])){
            echo 'Test';
        }
    }
?>

Clicking submit after selecting whatever dropdown options currently works fine and populates the page with filtered results. Each checkbox is correctly displayed (and clickable) next to each entry on the page, but when I click one (or all), my test function doesn't write anything to the page. var_dump($_POST['wishlist']); confirms that clicking the checkboxes doesn't update the POST wishlist array at all (stays NULL).

I'm probably going about this all wrong. What's a better way to call a dynamically created form?


问:
Output Lines get out of bounds when I knit my Rmarkdown
when trying to knit my Rmd to output it as pdf document, some of the outputs get out of bounds
example of the output that gets out of bounds:

The YAML and settings are this:

.

Also when I "knit on save", the rstudio doesn't stop the process untill i give up waiting, idk if it's because it is trying to knit a big pdf(140 pages), but when i press stop in the Render it aborts and somehow the document shows up in my files.

Although I don't show it, i have the knitr packages installed. I've tried many forms of output, the only YAML format that i can generate a pdf with is the one from the picture. Idk if there is something that could prevent the outputs to go out of bounds. Help is appreciated


问:
How to parse_obj() in current class object from its method?
I have class:

```<code>class Rate(BaseMode):
  rate: int

  def load_from_db(self):
    # here getting data from db into el dict
    self = self.parse_obj(el) # it doesn't work. how do it correct?
</code>```

I try code above, but data doesn't add up to current object.

Body:
I have class:

class Rate(BaseMode):
  rate: int

  def load_from_db(self):
    # here getting data from db into el dict
    self = self.parse_obj(el) # it doesn't work. how do it correct?

I try code above, but data doesn't add up to current object.


问:
Solutions to group elements in different pairs
I am working on grouping of elements for large dataset in least amount of time.

Below is small dataset example of the same:

```<code>Input:
pairs = [[1,2],[8,10],[4,8],[3,4],[2,3],[5,6],[6,7],[9,4],[11,12],[13,10],[16,1],[78,79],[61,3],[93,94]]
</code>```

How to derive output:

If any of the element is present in another pair then both pair can be grouped. This way traverse all pairs and create different groups.

```<code>Output: -
[{1, 2, 3, 4, 8, 9, 10, 13, 16, 61}, {5, 6, 7}, {11, 12}, {78, 79}, {93, 94}]
</code>```

Question:

What is the best way to solve this problem?
e.g.: graph database(neo4j) or any specific readily available algorithm.

any other alternatives which is not listed in example solution(neo4j, algorithm) above?

Below output is expected and solution should consume less time with large dataset.

```<code>Expected Output: -
[{1, 2, 3, 4, 8, 9, 10, 13, 16, 61}, {5, 6, 7}, {11, 12}, {78, 79}, {93, 94}]
</code>```

Body:
I am working on grouping of elements for large dataset in least amount of time.

Below is small dataset example of the same:

Input:
pairs = [[1,2],[8,10],[4,8],[3,4],[2,3],[5,6],[6,7],[9,4],[11,12],[13,10],[16,1],[78,79],[61,3],[93,94]]

How to derive output:

If any of the element is present in another pair then both pair can be grouped. This way traverse all pairs and create different groups.

Output: -
[{1, 2, 3, 4, 8, 9, 10, 13, 16, 61}, {5, 6, 7}, {11, 12}, {78, 79}, {93, 94}]

Question:

What is the best way to solve this problem?
e.g.: graph database(neo4j) or any specific readily available algorithm.

any other alternatives which is not listed in example solution(neo4j, algorithm) above?

Below output is expected and solution should consume less time with large dataset.

Expected Output: -
[{1, 2, 3, 4, 8, 9, 10, 13, 16, 61}, {5, 6, 7}, {11, 12}, {78, 79}, {93, 94}]


问:
How do I fix the error "Cannot read properties of undefined (reading 'create')" in Node Js + open ai api
I am using node js to create a input for a user to call on the open ai api to create content on the page.
When the user inputs into the input field and sends it, I get the error "Cannot read properties of undefined (reading 'create')"

Below is my code:

HTML:

```<code><form id="prompt-form">
    <label for="prompt-input">Enter prompt:</label><br>
    <input type="text" id="prompt-input" name="prompt"><br>
    <button type="submit">Submit</button>
  </form>

  <script>
  document.getElementById('prompt-form').addEventListener('submit', (event) => {
  event.preventDefault();
  const formData = new FormData(event.target);
  const prompt = formData.get('prompt');
  console.log(prompt);
  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/generate-content');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onload = () => {
    if (xhr.status === 200) {
      // Display the generated content on the page
      document.getElementById('generated-content').innerHTML = xhr.responseText;
    }
  };
  xhr.send(`prompt=${prompt}`);
});
  </script>
</code>```

node js server.js:

```<code>import express from 'express';

// test of the open ai api in console log
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
  apiKey: "secretkey",
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "write a cover letter for web dev",
  max_tokens: 5,
  temperature: 0,
});
console.log(response.data.choices[0].text)

const app = express();
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

app.post('/generate-content', (req, res) => {
    const prompt = req.body.prompt;
    openai.completions.create({
      model: 'text-davinci-002',
      prompt: prompt,
      max_tokens: 256
    }, (error, response) => {
      if (error) {
        res.send(error);
      } else {
        res.send(response.choices[0].text);
      }
    });
  });

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

</code>```

I have tried putting in user input and I was expecting the submitted data to generate content using open ai.

Body:
I am using node js to create a input for a user to call on the open ai api to create content on the page.
When the user inputs into the input field and sends it, I get the error "Cannot read properties of undefined (reading 'create')"

Below is my code:

HTML:

<form id="prompt-form">
    Enter prompt:

    <input type="text" id="prompt-input" name="prompt">

    <button type="submit">Submit</button>
  </form>

node js server.js:

import express from 'express';

// test of the open ai api in console log
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
  apiKey: "secretkey",
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "write a cover letter for web dev",
  max_tokens: 5,
  temperature: 0,
});
console.log(response.data.choices[0].text)

const app = express();
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

app.post('/generate-content', (req, res) => {
    const prompt = req.body.prompt;
    openai.completions.create({
      model: 'text-davinci-002',
      prompt: prompt,
      max_tokens: 256
    }, (error, response) => {
      if (error) {
        res.send(error);
      } else {
        res.send(response.choices[0].text);
      }
    });
  });

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

I have tried putting in user input and I was expecting the submitted data to generate content using open ai.


问:
Multiple website from one apache server: http to https not routing
I want to run multiple websites from one server. Each website has subdomains. Here is the scenarios:

Domain 1: domain1.com
Subdomain 1: sub1.domain1.com
Subdomain 2: sub2.domain1.com
Subdomain 3: sub3.domain1.com
and goes on!

Domain 2: domain2.com
Subdomain 1: sub1.domain2.com
Subdomain 2: sub2.domain2.com
Subdomain 3: sub3.domain2.com
and goes on!

Domain 3: domain3.com
Subdomain 1: sub1.domain3.com
Subdomain 2: sub2.domain3.com
Subdomain 3: sub3.domain3.com
and goes on!

For each domain, I already have SSL certificates. I want to redirect all of them on to https.

I have virtual hosts conf file for each domain as:

```<code><VirtualHost *:80>
ServerName domain1.com
ServerAlias www.domain1.com

RewriteEngine on
RewriteCond %{SERVER_NAME} =*.domain1.com [OR]
RewriteCond %{SERVER_NAME} =domain1.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
<VirtualHost *:80>

<IfModule mod_ssl.c>
<VirtualHost *:443>

ServerName domain1.com
ServerAlias www.domain1.com

#SSL Certificate Information and Website location

</VirtualHost>
</IfModule>
</code>```

Similarly for other domains too.

My two domains (domain1 and all subdomains on domain1 & domain3 and all subdomains on domain3) are routing perfectly fine but one of them (domain2 and all subdomains on domain2) is not routing to https traffic. I really appreciate any help. When I check the certificate validity for domain2, it points to domain1 certificate.

Any help is really appreciated. Thanks

Body:
I want to run multiple websites from one server. Each website has subdomains. Here is the scenarios:

Domain 1: domain1.com
Subdomain 1: sub1.domain1.com
Subdomain 2: sub2.domain1.com
Subdomain 3: sub3.domain1.com
and goes on!

Domain 2: domain2.com
Subdomain 1: sub1.domain2.com
Subdomain 2: sub2.domain2.com
Subdomain 3: sub3.domain2.com
and goes on!

Domain 3: domain3.com
Subdomain 1: sub1.domain3.com
Subdomain 2: sub2.domain3.com
Subdomain 3: sub3.domain3.com
and goes on!

For each domain, I already have SSL certificates. I want to redirect all of them on to https.

I have virtual hosts conf file for each domain as:

<VirtualHost *:80>
ServerName domain1.com
ServerAlias www.domain1.com

RewriteEngine on
RewriteCond %{SERVER_NAME} =*.domain1.com [OR]
RewriteCond %{SERVER_NAME} =domain1.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
<VirtualHost *:80>

<IfModule mod_ssl.c>
<VirtualHost *:443>

ServerName domain1.com
ServerAlias www.domain1.com

#SSL Certificate Information and Website location

</VirtualHost>
</IfModule>

Similarly for other domains too.

My two domains (domain1 and all subdomains on domain1 & domain3 and all subdomains on domain3) are routing perfectly fine but one of them (domain2 and all subdomains on domain2) is not routing to https traffic. I really appreciate any help. When I check the certificate validity for domain2, it points to domain1 certificate.

Any help is really appreciated. Thanks


问:
BotBase.__init__() missing 1 required keyword-only argument: 'intents'
I was trying to make a music bot for discord and I used this code:

```<code>import discord
import Config
from discord.ext import commands
from youtube_dl import YoutubeDL

YDL_OPTIONS = {'format': 'worstaudio/best', 'noplaylist': 'False', 'simulate': 'True',
               'preferredquality': '192', 'preferredcodec': 'mp3', 'key': 'FFmpegExtractAudio'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

client = commands.Bot(command_prefix='-')

@client.command()
async def play(ctx, *, arg):
    vc = await ctx.message.author.voice.channel.connect()

    with YoutubeDL(YDL_OPTIONS) as ydl:
        if 'https://' in arg:
            info = ydl.extract_info(arg, download=False)
        else:
            info = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]

    url = info['formats'][0]['url']

    vc.play(discord.FFmpegPCMAudio(executable="ffmpeg\\ffmpeg.exe", source=url, **FFMPEG_OPTIONS))
</code>```

But this error pops up:

```<code>BotBase.__init__() missing 1 required keyword-only argument: 'intents'
</code>```

I was trying to fix this problem and i google it. I wrote instead

```<code>client = commands.Bot(command_prefix='-')
</code>```

this:

```<code>client = discord.Client(intents=discord.Intents.default())
</code>```

But instead I get this error:

```<code>AttributeError: 'Client' object has no attribute 'command'
</code>```

Body:
I was trying to make a music bot for discord and I used this code:

import discord
import Config
from discord.ext import commands
from youtube_dl import YoutubeDL

YDL_OPTIONS = {'format': 'worstaudio/best', 'noplaylist': 'False', 'simulate': 'True',
               'preferredquality': '192', 'preferredcodec': 'mp3', 'key': 'FFmpegExtractAudio'}
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

client = commands.Bot(command_prefix='-')

@client.command()
async def play(ctx, *, arg):
    vc = await ctx.message.author.voice.channel.connect()

    with YoutubeDL(YDL_OPTIONS) as ydl:
        if 'https://' in arg:
            info = ydl.extract_info(arg, download=False)
        else:
            info = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]

    url = info['formats'][0]['url']

    vc.play(discord.FFmpegPCMAudio(executable="ffmpeg\\ffmpeg.exe", source=url, **FFMPEG_OPTIONS))

But this error pops up:

BotBase.__init__() missing 1 required keyword-only argument: 'intents'

I was trying to fix this problem and i google it. I wrote instead

client = commands.Bot(command_prefix='-')

this:

client = discord.Client(intents=discord.Intents.default())

But instead I get this error:

AttributeError: 'Client' object has no attribute 'command'


问:
NextJs 13 - Edge causing pages to return 500 (Internal Error)
I am currently following the NextJs guide for setting up the runtime to use Edge, to try and take advantage or the performance benefits. However, I do not seem to be having any luck. I am getting a 500 response. I have tried to add this globally and per page, but all I get is the same error, with

```<code>"[TypeError: Cannot read properties of null (reading 'registered')]"
</code>```

in the terminal.

My current setup : NextJs 13.0.7 (latest as of today)

Those are some images of the setup using edge.

Body:
I am currently following the NextJs guide for setting up the runtime to use Edge, to try and take advantage or the performance benefits. However, I do not seem to be having any luck. I am getting a 500 response. I have tried to add this globally and per page, but all I get is the same error, with

"[TypeError: Cannot read properties of null (reading 'registered')]"

in the terminal.

My current setup : NextJs 13.0.7 (latest as of today)

Those are some images of the setup using edge.


问:
Node with axios - pipe gets stuck
I am facing an unexpected behavior when piping a response from axios. I am making a HTTP request that gives me a stream to download a tar file. I use node-tar to extract it.

I am running this code for a lot of different endpoints, applying the same logic to each one and 99% of them work just fine, and the rest just gets stuck the pipe never ends, letting the process up and running, doing nothing. (each time I run, a different endpoint gets stuck, seems random which one).
To get to this conclusion, I see that the log "start pipe" shows up, but none of the events are reached. Also, if I uncomment the setTimeout line, the code runs just fine.

See below a code example:

```<code>const response = await axios.get(...);
await new Promise((resolve, reject) => {
    console.log('start pipe');
    response.data.pipe(
        tar.extract({cwd: mydir})
    )
      .on('finish', () => {
          console.log('finish');
          resolve();
      })
      .on('aborted', () => {
          console.log('aborted');
          resolve();
      })
      .on('end', () => {
          console.log('end');
          resolve();
      })
      .on('error', () => {
          console.log('error');
          resolve();
      })
      .on('close', () => {
          console.log('close');
          resolve();
      })

     //setTimeout(() => {
     //  reject(new Error('20 seconds passed and pipe not finished'));
     //}, 20000);
}).then(() => {
   // do something with the extracted files
}).catch((err) => {
   console.log(err);
   throw err;
});
</code>```

What am I missing?

Ubuntu 20.04 / Node - v14.20 /Axios - 1.1.3 / Tar - 6.1.12

Title: Node with axios - pipe gets stuck

Body:
I am facing an unexpected behavior when piping a response from axios. I am making a HTTP request that gives me a stream to download a tar file. I use node-tar to extract it.

I am running this code for a lot of different endpoints, applying the same logic to each one and 99% of them work just fine, and the rest just gets stuck the pipe never ends, letting the process up and running, doing nothing. (each time I run, a different endpoint gets stuck, seems random which one).
To get to this conclusion, I see that the log "start pipe" shows up, but none of the events are reached. Also, if I uncomment the setTimeout line, the code runs just fine.

See below a code example:

const response = await axios.get(...);
await new Promise((resolve, reject) => {
    console.log('start pipe');
    response.data.pipe(
        tar.extract({cwd: mydir})
    )
      .on('finish', () => {
          console.log('finish');
          resolve();
      })
      .on('aborted', () => {
          console.log('aborted');
          resolve();
      })
      .on('end', () => {
          console.log('end');
          resolve();
      })
      .on('error', () => {
          console.log('error');
          resolve();
      })
      .on('close', () => {
          console.log('close');
          resolve();
      })

     //setTimeout(() => {
     //  reject(new Error('20 seconds passed and pipe not finished'));
     //}, 20000);
}).then(() => {
   // do something with the extracted files
}).catch((err) => {
   console.log(err);
   throw err;
});

What am I missing?

Ubuntu 20.04 / Node - v14.20 /Axios - 1.1.3 / Tar - 6.1.12


问:
Can't create venv in docker jupyter image (permissions)
When trying to docker build from this Dockerfile:

```<code>FROM jupyter/datascience-notebook:latest
ENV VIRTUAL_ENV=/opt/venv
RUN python -m venv $VIRTUAL_ENV
</code>```

... I receive the following error:

```<code>Error: [Errno 13] Permission denied: '/opt/venv'
The command '/bin/bash -o pipefail -c python -m venv $VIRTUAL_ENV' returned a non-zero code: 1
</code>```

It works fine with other parent images.

I don't understand why it doesn't work. Since my Dockerfile doesn't contain a USER ... line, the RUN line which tries to create the venv is operating as root user isn't it?

I've tried the usual things like including a RUN chown appuser /opt higher up in the Dockerfile without success.

Body:
When trying to docker build from this Dockerfile:

FROM jupyter/datascience-notebook:latest
ENV VIRTUAL_ENV=/opt/venv
RUN python -m venv $VIRTUAL_ENV

... I receive the following error:

Error: [Errno 13] Permission denied: '/opt/venv'
The command '/bin/bash -o pipefail -c python -m venv $VIRTUAL_ENV' returned a non-zero code: 1

It works fine with other parent images.

I don't understand why it doesn't work. Since my Dockerfile doesn't contain a USER ... line, the RUN line which tries to create the venv is operating as root user isn't it?

I've tried the usual things like including a RUN chown appuser /opt higher up in the Dockerfile without success.


问:
How to show TypeScript enum member names in Storybook controls?
I’m using Storybook with React and TypeScript.

When my components have parameters whose type are TypeScript enums, they are rendered in the “Controls” panel using their index:

I would like them to render using their names, like on this mockup:

How can I achieve that? Here is my code:

```<code>// components/Card.tsx
import React from 'react';

enum Suit { Clubs, Diamonds, Hearts, Spades }
interface CardProps {
  suit?: Suit;
}
export default function Card({ suit = Suit.Clubs }: CardProps) {
  return <div />;
}
</code>```
```<code>// stories/Card.stories.tsx
import React from 'react';
import { ComponentMeta } from '@storybook/react';
import Card from '../components/Card';

export default {
  component: Card,
  args: {},
} as ComponentMeta<typeof Card>;

const Template = (args: React.ComponentProps<typeof Card>) => <Card {...args} />;
export const DefaultState = Template.bind({});
</code>```

Body:
I’m using Storybook with React and TypeScript.

When my components have parameters whose type are TypeScript enums, they are rendered in the “Controls” panel using their index:

I would like them to render using their names, like on this mockup:

How can I achieve that? Here is my code:

// components/Card.tsx
import React from 'react';

enum Suit { Clubs, Diamonds, Hearts, Spades }
interface CardProps {
  suit?: Suit;
}
export default function Card({ suit = Suit.Clubs }: CardProps) {
  return
;
}

// stories/Card.stories.tsx
import React from 'react';
import { ComponentMeta } from '@storybook/react';
import Card from '../components/Card';

export default {
  component: Card,
  args: {},
} as ComponentMeta<typeof Card>;

const Template = (args: React.ComponentProps<typeof Card>) => <Card {...args} />;
export const DefaultState = Template.bind({});


问:
Target child on parent hover using @emotion/react css
This doesn't seem to be an issue with styled in Emotion, but I can't do it with css...

Just like the title says, I have a child component that is display: none, I want to change it to display: block when the parent is hovered.

You can see it not working in this code sandbox with the following code:

```<code>const child = css`
  background: yellow;
  display: none;
`;

const parent = css`
  background: red;
  width: 200px;
  height: 200px;
  &:hover {
    background: green;
  }
  &:hover ${child} {
    display: block;
  }
`;
</code>```

Is it just not an option with Emotion's css?

Body:
This doesn't seem to be an issue with styled in Emotion, but I can't do it with css...

Just like the title says, I have a child component that is display: none, I want to change it to display: block when the parent is hovered.

You can see it not working in this code sandbox with the following code:

const child = css`
  background: yellow;
  display: none;
`;

const parent = css`
  background: red;
  width: 200px;
  height: 200px;
  &:hover {
    background: green;
  }
  &:hover ${child} {
    display: block;
  }
`;

Is it just not an option with Emotion's css?


问:
Android studio compiles code but highlights error imported library class
I try to add google cloud dependency "com.google.cloud:libraries-bom".

```<code>implementation platform ("com.google.cloud:libraries-bom:$googleCloudVer")
implementation ('com.google.cloud:google-cloud-vision') {
    exclude group: 'com.google.protobuf', module: 'protobuf-java'
    exclude group: 'com.google.api.grpc', module: 'proto-google-common-protos'
}
</code>```

but when I exclude protobuf module, the code imported will error highlighted.
This is the error message:
Cannot access 'com.google.protobuf.GeneratedMessageV3' which is a supertype of 'com.google.cloud.vision.v1.Image'. Check your module classpath for missing or conflicting dependencies

The code compiles but ide complains. When I remove the exclude in dependency, there's no error highlight. But I need to exclude them for duplicated classes with protobuf dependency. Is there any workaround for it?

Body:
I try to add google cloud dependency "com.google.cloud:libraries-bom".

implementation platform ("com.google.cloud:libraries-bom:$googleCloudVer")
implementation ('com.google.cloud:google-cloud-vision') {
    exclude group: 'com.google.protobuf', module: 'protobuf-java'
    exclude group: 'com.google.api.grpc', module: 'proto-google-common-protos'
}

but when I exclude protobuf module, the code imported will error highlighted.
This is the error message:
Cannot access 'com.google.protobuf.GeneratedMessageV3' which is a supertype of 'com.google.cloud.vision.v1.Image'. Check your module classpath for missing or conflicting dependencies

The code compiles but ide complains. When I remove the exclude in dependency, there's no error highlight. But I need to exclude them for duplicated classes with protobuf dependency. Is there any workaround for it?


问:
Accessing Internal NeoLoad Variables in a JS
I am new to NeoLoad, and I am using 9.1. After recording a script with necessary transaction names, I see Neoload creates some internal variables like NL-HttpRequestId, NL-HttpRequestPageName, etc. I want to access these variables from JavaScript. How can I do so?

I tried the below js code and placed both outside a transaction and inside, but the value is blank.

```<code>logger.debug("TXN NAME="+context.variableManager.parseString("${NL-HttpRequestTransactionName}"));
</code>```

Body:
I am new to NeoLoad, and I am using 9.1. After recording a script with necessary transaction names, I see Neoload creates some internal variables like NL-HttpRequestId, NL-HttpRequestPageName, etc. I want to access these variables from JavaScript. How can I do so?

I tried the below js code and placed both outside a transaction and inside, but the value is blank.

logger.debug("TXN NAME="+context.variableManager.parseString("${NL-HttpRequestTransactionName}"));