问:
Getting UnhandledPromiseRejection while trying to return a caught error from multiple levels deep
I am implementing an API on the app that takes the input and performs an action. The happy path works well. However, when I catch an error in a try-catch block I can't properly return it back to the API level to respond with a custom error message to the API caller. I pass it 3 levels back and can't pass it further getting an error message:

```<code>node:internal/process/promises:288
                   triggerUncaughtException(err, true /* fromPromise */);
                   ^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Credential Definition ID Invalid".] {
   code: 'ERR_UNHANDLED_REJECTION'
 }

 Node.js v18.12.1
 [nodemon] app crashed - waiting for file changes before starting...
</code>```

Here is what my schematic flow looks like

```<code>// index.js
app.post('/api/v1/myRoute', async (req, res) => {
  try {
    // validation here
    // do something here
    // start the flow here

     // I see this log before the rest of the logs from the catch block below... It is undefined
    const result = await File1.function1(id1,id2)
    console.log('__________________________')
    console.log(result)
    console.log('__________________________')

  if (result && result.error) {
    throw result.error
  }

  } catch (error) {
    if (error === 'MISSING_ID') { // custom validation
      res.json({error: "missing id"})
    } else if (error) {
      res.json(error) // This is where I should handle custom message
    } else {
      res.json({
        error:
          'Generic error message',
      })
    }
  }
}

// file 1 - funciton 1
const function1 = async function (id1, id2) {
  try {
    // do something here
    //and here
    //call more async functions here
    // continue with the flow here
    const response = await function2(id3, object)

    if (response.error) {
    // there is a response.error, but I can't throw it further
      throw response.error // ------ it breaks here -------
    }

  } catch (error){
    console.log('this is the function1 catch block') // I never get here
    console.log(error)
    return {error: error}
  }
}

// file 1 - funciton 2
const function1 = async function (id3, object) {
  try {
    // validation
    // continue with the flow here
    const response = await File2.function1(data)

    if (response.error) {
      throw response.error.reason // I successfully catch the error here
    }

  } catch (error){
    console.log('this is the function2 catch block')
    console.log(error)
    return {error: error} // I successfully return error here
  }
}

// file 2 - funciton 1
const function1 = async function (data) {
  try {
    // verifications based on API requests to the cloud agent
    const response = await Cloud.APIcall(data)

    if (!response) {
      throw new ControllerError(5, 'Credential Definition ID Invalid') // this throws an error
    }
  } catch (error){
    return {
      error: {
        code: error.code,
        reason: error.reason,
      }, // I successfully return error here
    }
  }
}

// Controller error file - Custom error file
class ControllerError extends Error {
  constructor(code = 0, reason = 'Internal Server Error', ...params) {
    super(...params)

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ControllerError)
    }

    this.name = 'ControllerError'
    // Custom debugging information
    this.code = code
    this.reason = reason
  }
}

module.exports = ControllerError
</code>```

What am I doing wrong and how can I pass the catch an error from an async function through all layers of my flow using try-catch block?

Body:
I am implementing an API on the app that takes the input and performs an action. The happy path works well. However, when I catch an error in a try-catch block I can't properly return it back to the API level to respond with a custom error message to the API caller. I pass it 3 levels back and can't pass it further getting an error message:

node:internal/process/promises:288
                   triggerUncaughtException(err, true /* fromPromise */);
                   ^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Credential Definition ID Invalid".] {
   code: 'ERR_UNHANDLED_REJECTION'
 }

 Node.js v18.12.1
 [nodemon] app crashed - waiting for file changes before starting...

Here is what my schematic flow looks like

// index.js
app.post('/api/v1/myRoute', async (req, res) => {
  try {
    // validation here
    // do something here
    // start the flow here

     // I see this log before the rest of the logs from the catch block below... It is undefined
    const result = await File1.function1(id1,id2)
    console.log('__________________________')
    console.log(result)
    console.log('__________________________')

  if (result && result.error) {
    throw result.error
  }

  } catch (error) {
    if (error === 'MISSING_ID') { // custom validation
      res.json({error: "missing id"})
    } else if (error) {
      res.json(error) // This is where I should handle custom message
    } else {
      res.json({
        error:
          'Generic error message',
      })
    }
  }
}

// file 1 - funciton 1
const function1 = async function (id1, id2) {
  try {
    // do something here
    //and here
    //call more async functions here
    // continue with the flow here
    const response = await function2(id3, object)

    if (response.error) {
    // there is a response.error, but I can't throw it further
      throw response.error // ------ it breaks here -------
    }

  } catch (error){
    console.log('this is the function1 catch block') // I never get here
    console.log(error)
    return {error: error}
  }
}

// file 1 - funciton 2
const function1 = async function (id3, object) {
  try {
    // validation
    // continue with the flow here
    const response = await File2.function1(data)

    if (response.error) {
      throw response.error.reason // I successfully catch the error here
    }

  } catch (error){
    console.log('this is the function2 catch block')
    console.log(error)
    return {error: error} // I successfully return error here
  }
}

// file 2 - funciton 1
const function1 = async function (data) {
  try {
    // verifications based on API requests to the cloud agent
    const response = await Cloud.APIcall(data)

    if (!response) {
      throw new ControllerError(5, 'Credential Definition ID Invalid') // this throws an error
    }
  } catch (error){
    return {
      error: {
        code: error.code,
        reason: error.reason,
      }, // I successfully return error here
    }
  }
}

// Controller error file - Custom error file
class ControllerError extends Error {
  constructor(code = 0, reason = 'Internal Server Error', ...params) {
    super(...params)

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, ControllerError)
    }

    this.name = 'ControllerError'
    // Custom debugging information
    this.code = code
    this.reason = reason
  }
}

module.exports = ControllerError

What am I doing wrong and how can I pass the catch an error from an async function through all layers of my flow using try-catch block?


来源: stackexchange

问:
How to solve net::ERR_SSL_PROTOCOL_ERROR?
The error shown in this image

I just made a simple landing page with Nestjs (backend), Reactjs (frontend) and using graphql for API and deployed on AWS EC2.  (The error says, "POST https://[our public address]:[end point port number]/graphql net::ERR_SSL_PROTOCOL_ERROR")

And I set up a proxy server with Nginx and put SSL with Let's encrypt.

It was fine submitting a form (just simple email info) and got them in our database (PostgreSQL) and as soon as I got the SSL implemented in NginX.

We are getting that error.

Can anyone help us to solve this error please?

tried making https protocol for backend following this official doc https://docs.nestjs.com/faq/multiple-servers#https does not seem to work and I am not sure if this is necessary to do to be honest.

The current NginX set up
Not sure if I have to do somethings on this Nginx setup.

ContentLicense: CC BY-SA 4.0


问:
How do I make it so that using CustomTkinter I can accept an input by pressing 'Enter'?
I was able so successfully place the input module earlier but now when I try to implement code to use 'Enter' to accept the input I'm not even able to get it to pack. If anyone can help me it would be thoroughly appreciated. Eventually I am trying to make it so that whatever typed ends up being incrementally placed as a title in a column centered to the left of the entry widget but I will work on that later. (this is the UI for a text adventure game)

Below is the code I have so far

```<code>#imports
import time, os, sys, logging
from pynput import *
from tkinter import Button
from tkinter import *
import customtkinter
import tkinter.font as font
from tkinter import simpledialog
import tkinter
import time
import tkinter as tk

userin = ''

#graphics
the_path_text = '''
┏┓┏┓╋╋╋╋╋╋╋╋┏┓┏┓
   ┃┗┫┗┳━┓┏━┳━┓┃┗┫┗┓
   ┃┏┫┃┃┻┫┃╋┃╋┗┫┏┫┃┃
   ┗━┻┻┻━┛┃┏┻━━┻━┻┻┛
   ╋╋╋╋╋╋╋┗┛'''

#window
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

root = customtkinter.CTk()
root.geometry("800x520")
root.resizable(width = False, height = False)
root.title('The Path')

photo = PhotoImage(file = "D:\\pathpic.png")
root.iconphoto(False, photo)

myfont = ("Roboto Mono",30)

frame = customtkinter.CTkFrame(master = root)
frame.pack(pady = 20, padx = 60, fill = 'both', expand = True)

#splash/start screen

#loading
label = customtkinter.CTkLabel(root, text="Loading", font= ('Roboto', 20))
label.pack()

# Incrementally add dots
for i in range(3):
    label.configure(text="Loading" + "." * (i + 1))
    time.sleep(.5)
    root.update()

# Clear the label text
label.configure(text="")

# Incrementally add dots again
for i in range(3):
    label.configure(text="Loading" + "." * (i + 1))
    time.sleep(.5)
    root.update()

label.configure(text="  ")

#splash logo
label_path_logo = customtkinter.CTkLabel(master=frame, text= the_path_text, font = ('Roboto', 20))
label_path_logo.pack(pady =12, padx = 10)

#clearing splash/ main game loop
start = 0
def clear_start():
    time.sleep(.2)
    global frame, root
    frame.destroy()
    frame = Frame(root)
    frame.pack()
    start_button.destroy()
    start = 1

#main game
start_button = customtkinter.CTkButton(master=root, text="Enter the path", command = clear_start)
start_button.pack(padx = 6, pady=20)
while start == 1:
    #main text console
    main_entry = root.entry = customtkinter.CTkEntry(root, textvariable=userin, placeholder_text="Enter Command")
    main_entry.pack(side = BOTTOM,fill = BOTH, pady = 5, padx = 200 )

def process(event=None):
    content = main_entry.get() # get the contents of the entry widget
    print(content) # for example
    main_entry.bind('<Return>', process)

root.mainloop()
</code>```

Body:
I was able so successfully place the input module earlier but now when I try to implement code to use 'Enter' to accept the input I'm not even able to get it to pack. If anyone can help me it would be thoroughly appreciated. Eventually I am trying to make it so that whatever typed ends up being incrementally placed as a title in a column centered to the left of the entry widget but I will work on that later. (this is the UI for a text adventure game)

Below is the code I have so far

#imports
import time, os, sys, logging
from pynput import *
from tkinter import Button
from tkinter import *
import customtkinter
import tkinter.font as font
from tkinter import simpledialog
import tkinter
import time
import tkinter as tk

userin = ''

#graphics
the_path_text = '''
┏┓┏┓╋╋╋╋╋╋╋╋┏┓┏┓
   ┃┗┫┗┳━┓┏━┳━┓┃┗┫┗┓
   ┃┏┫┃┃┻┫┃╋┃╋┗┫┏┫┃┃
   ┗━┻┻┻━┛┃┏┻━━┻━┻┻┛
   ╋╋╋╋╋╋╋┗┛'''

#window
customtkinter.set_appearance_mode("dark")
customtkinter.set_default_color_theme("dark-blue")

root = customtkinter.CTk()
root.geometry("800x520")
root.resizable(width = False, height = False)
root.title('The Path')

photo = PhotoImage(file = "D:\\pathpic.png")
root.iconphoto(False, photo)

myfont = ("Roboto Mono",30)

frame = customtkinter.CTkFrame(master = root)
frame.pack(pady = 20, padx = 60, fill = 'both', expand = True)

#splash/start screen

#loading
label = customtkinter.CTkLabel(root, text="Loading", font= ('Roboto', 20))
label.pack()

# Incrementally add dots
for i in range(3):
    label.configure(text="Loading" + "." * (i + 1))
    time.sleep(.5)
    root.update()

# Clear the label text
label.configure(text="")

# Incrementally add dots again
for i in range(3):
    label.configure(text="Loading" + "." * (i + 1))
    time.sleep(.5)
    root.update()

label.configure(text="  ")

#splash logo
label_path_logo = customtkinter.CTkLabel(master=frame, text= the_path_text, font = ('Roboto', 20))
label_path_logo.pack(pady =12, padx = 10)

#clearing splash/ main game loop
start = 0
def clear_start():
    time.sleep(.2)
    global frame, root
    frame.destroy()
    frame = Frame(root)
    frame.pack()
    start_button.destroy()
    start = 1

#main game
start_button = customtkinter.CTkButton(master=root, text="Enter the path", command = clear_start)
start_button.pack(padx = 6, pady=20)
while start == 1:
    #main text console
    main_entry = root.entry = customtkinter.CTkEntry(root, textvariable=userin, placeholder_text="Enter Command")
    main_entry.pack(side = BOTTOM,fill = BOTH, pady = 5, padx = 200 )

def process(event=None):
    content = main_entry.get() # get the contents of the entry widget
    print(content) # for example
    main_entry.bind('<Return>', process)

root.mainloop()


问:
Populate within object only work in some function
I'm having trouble dealing with populate within object, so I have a SosmedPost schema. I want to populate the Comments field, which is an array. Likewise, I have 2 function create comment and getPost, the populate working in create comment but in getPost it's not working

```<code>const SosmedPostSchema = new mongoose.Schema({
   Username : {
       type : String
   },
   Content : {
       type : String
   },
   Documents : {
       type : String
   },
   Author : {
       type : mongoose.Schema.Types.ObjectId,
       ref : 'sosmedprofiles'
   },
   Comments : [{
       PostedBy : {
              type : mongoose.Schema.Types.ObjectId,
              ref : "sosmedprofiles"
       },
       Text : {
              type : String
       }
   }],
   Likes : [{
          type : mongoose.Schema.Types.ObjectId,
          ref : "sosmedprofiles"
   }]
}, {timestamps : true});
</code>```

I have a function to create comment, and it's working perfectly fine

```<code>const createComment = (req, res) => {
  const Id = req.params.id;

  const comment = {
    Text : req.body.Text,
    PostedBy : req.body.PostedBy
  }

  SosmedPostModel.findByIdAndUpdate({_id : Id}, {
    $push : {Comments : comment}
  }, {
    new : true
  }).populate("Comments.PostedBy")
  .exec((err, result) => {
    if (err) {
      return res.status(422).json({error : err})
    } else {
      res.json(result)
    }
  })
}
</code>```

But in another function getPostById the Comments.PostedBy populate its not working. Is there something wrong with how I populate the array ?

```<code>const getPostById = (req, res) => {
    const Id = req.params.id;

    SosmedPostModel.findById({_id : Id})
    .populate("Author")
    .populate("Comments.PostedBy")
    .populate("Likes")
    .exec(function (err, posts) {
       if (err) return handleError(err);
       res.send(posts)
    })
}
</code>```

This is the result in create comment function :

```<code>"Comments": [
    {
      "Text": "Cool Post",
      "PostedBy": {
        "_id": "63a116dc3c759e4437fabacb",
        "Username": "rahmandhika5@gmail.com",
        "FullName": "Rahmandhika",
        "ProfilePicture": "https://example.jpg",
        "Bio": "Live in Tangerang",
        "Post": [],
        "createdAt": "2022-12-20T01:58:52.179Z",
        "updatedAt": "2022-12-20T01:58:52.179Z",
        "__v": 0
      },
      "_id": "63a1172f3c759e4437fabaf9"
    },
</code>```

But in getPostById function, the result is :

```<code> "Comments": [
      {
        "Text": "Cool Post",
        "PostedBy": "63a116dc3c759e4437fabacb",
        "_id": "63a1172f3c759e4437fabaf9"
      },
      {
        "Text": "Yo",
        "PostedBy": "63a116dc3c759e4437fabacb",
        "_id": "63a11bab4aad531ee8ad8273"
      },
      {
        "PostedBy": "63a116dc3c759e4437fabacb",
        "Text": "YAAY",
        "_id": "63a11fcdf5384ab89174ad7e"
      }
    ],
</code>```

Body:
I'm having trouble dealing with populate within object, so I have a SosmedPost schema. I want to populate the Comments field, which is an array. Likewise, I have 2 function create comment and getPost, the populate working in create comment but in getPost it's not working

const SosmedPostSchema = new mongoose.Schema({
   Username : {
       type : String
   },
   Content : {
       type : String
   },
   Documents : {
       type : String
   },
   Author : {
       type : mongoose.Schema.Types.ObjectId,
       ref : 'sosmedprofiles'
   },
   Comments : [{
       PostedBy : {
              type : mongoose.Schema.Types.ObjectId,
              ref : "sosmedprofiles"
       },
       Text : {
              type : String
       }
   }],
   Likes : [{
          type : mongoose.Schema.Types.ObjectId,
          ref : "sosmedprofiles"
   }]
}, {timestamps : true});

I have a function to create comment, and it's working perfectly fine

const createComment = (req, res) => {
  const Id = req.params.id;

  const comment = {
    Text : req.body.Text,
    PostedBy : req.body.PostedBy
  }

  SosmedPostModel.findByIdAndUpdate({_id : Id}, {
    $push : {Comments : comment}
  }, {
    new : true
  }).populate("Comments.PostedBy")
  .exec((err, result) => {
    if (err) {
      return res.status(422).json({error : err})
    } else {
      res.json(result)
    }
  })
}

But in another function getPostById the Comments.PostedBy populate its not working. Is there something wrong with how I populate the array ?

const getPostById = (req, res) => {
    const Id = req.params.id;

    SosmedPostModel.findById({_id : Id})
    .populate("Author")
    .populate("Comments.PostedBy")
    .populate("Likes")
    .exec(function (err, posts) {
       if (err) return handleError(err);
       res.send(posts)
    })
}

This is the result in create comment function :

"Comments": [
    {
      "Text": "Cool Post",
      "PostedBy": {
        "_id": "63a116dc3c759e4437fabacb",
        "Username": "rahmandhika5@gmail.com",
        "FullName": "Rahmandhika",
        "ProfilePicture": "https://example.jpg",
        "Bio": "Live in Tangerang",
        "Post": [],
        "createdAt": "2022-12-20T01:58:52.179Z",
        "updatedAt": "2022-12-20T01:58:52.179Z",
        "__v": 0
      },
      "_id": "63a1172f3c759e4437fabaf9"
    },

But in getPostById function, the result is :

 "Comments": [
      {
        "Text": "Cool Post",
        "PostedBy": "63a116dc3c759e4437fabacb",
        "_id": "63a1172f3c759e4437fabaf9"
      },
      {
        "Text": "Yo",
        "PostedBy": "63a116dc3c759e4437fabacb",
        "_id": "63a11bab4aad531ee8ad8273"
      },
      {
        "PostedBy": "63a116dc3c759e4437fabacb",
        "Text": "YAAY",
        "_id": "63a11fcdf5384ab89174ad7e"
      }
    ],


问:
How can I run my next.js app on my live web server? Getting 300 Access denied error
Trying to build my first next.js app with little experience beyond the php/mysql world and running into a gap in my understanding. I have access to a remote VPS that runs my many websites that I can access through the web. Let's say I installed the app in /www/my-app

All tutorials on next.js speak of running typing 'npm run dev' and deploying my app through localhost:3000 on a local development server. No search engine seems to understand my problem that I want to run this on a remote server and not locally.

I've created an app through create-next-app. Calling the folder by URL (url.com/my-app) gives me a 300 Access denied. Not sure what should have happened or how I should access my app.


问:
Function to populate created table using trigger on another table is not inserting any data
I am working on a project for school. They gave us a sample database in postgresql and we have to have a detailed table (which is a combination of multiple fields from joining two tables) and a summary table (which is populated using fields of your choice from the detailed table). I am using a trigger on the detail table to insert values from the detailed table into the summary table, and in this function I have it so that it concatenates two of the data fields from the detail table and concatenates them in the summary table. however whenever viewing the table after the function, it concatenated the fields but didn't include the new field name. It just moved over the fields into one column and kept the same column name, and deleted a column from my table.

-- Code for my function

```<code>Create or Replace Function refresh_summary_table ()
Returns Trigger
language plpgsql
As
$$
Begin
    Delete From summary_data_table;
    Insert Into summary_data_table (
        SELECT customer_id, CONCAT(first_name, ' ', last_name) as full_name, email, active
        FROM detailed_data_table
        WHERE active = '0'
        GROUP BY customer_id, full_name, email, active
        ORDER BY customer_id DESC
        LIMIT 100
    );
    RETURN NEW;
End;
$$

</code>```

-- Creating the Trigger

```<code>Create or Replace Trigger summary_refresh
After Insert ON detailed_data_table
For Each STATEMENT
Execute Procedure refresh_summary_table();
</code>```

-- After viewing the table after running these. This is the output I get

```<code>"customer_id"   "first_name"          "last_name"                   "email"         "active"
592 "Terrance Roush"    "terrance.roush@sakilacustomer.org"   "0"            [null]
558 "Jimmie Eggleston"  "jimmie.eggleston@sakilacustomer.org"     "0"            [null]
534 "Christian Jung"    "christian.jung@sakilacustomer.org"   "0"            [null]
510 "Ben Easter"            "ben.easter@sakilacustomer.org"           "0"            [null]
482 "Maurice Crawley"   "maurice.crawley@sakilacustomer.org"      "0"            [null]
446 "Theodore Culp"         "theodore.culp@sakilacustomer.org"    "0"            [null]
406 "Nathan Runyon"         "nathan.runyon@sakilacustomer.org"    "0"            [null]
368 "Harry Arce"            "harry.arce@sakilacustomer.org"       "0"            [null]
</code>```

I was expecting the first_name and last_name columns to merge the data into a column called full_name. If i highlight and only run the part of the insert statement in my function where i do the concatenation. The output is as expected.

Body:
I am working on a project for school. They gave us a sample database in postgresql and we have to have a detailed table (which is a combination of multiple fields from joining two tables) and a summary table (which is populated using fields of your choice from the detailed table). I am using a trigger on the detail table to insert values from the detailed table into the summary table, and in this function I have it so that it concatenates two of the data fields from the detail table and concatenates them in the summary table. however whenever viewing the table after the function, it concatenated the fields but didn't include the new field name. It just moved over the fields into one column and kept the same column name, and deleted a column from my table.

-- Code for my function

Create or Replace Function refresh_summary_table ()
Returns Trigger
language plpgsql
As
$$
Begin
    Delete From summary_data_table;
    Insert Into summary_data_table (
        SELECT customer_id, CONCAT(first_name, ' ', last_name) as full_name, email, active
        FROM detailed_data_table
        WHERE active = '0'
        GROUP BY customer_id, full_name, email, active
        ORDER BY customer_id DESC
        LIMIT 100
    );
    RETURN NEW;
End;
$$

-- Creating the Trigger

Create or Replace Trigger summary_refresh
After Insert ON detailed_data_table
For Each STATEMENT
Execute Procedure refresh_summary_table();

-- After viewing the table after running these. This is the output I get

"customer_id"   "first_name"          "last_name"                   "email"         "active"
592 "Terrance Roush"    "terrance.roush@sakilacustomer.org"   "0"            [null]
558 "Jimmie Eggleston"  "jimmie.eggleston@sakilacustomer.org"     "0"            [null]
534 "Christian Jung"    "christian.jung@sakilacustomer.org"   "0"            [null]
510 "Ben Easter"            "ben.easter@sakilacustomer.org"           "0"            [null]
482 "Maurice Crawley"   "maurice.crawley@sakilacustomer.org"      "0"            [null]
446 "Theodore Culp"         "theodore.culp@sakilacustomer.org"    "0"            [null]
406 "Nathan Runyon"         "nathan.runyon@sakilacustomer.org"    "0"            [null]
368 "Harry Arce"            "harry.arce@sakilacustomer.org"       "0"            [null]

I was expecting the first_name and last_name columns to merge the data into a column called full_name. If i highlight and only run the part of the insert statement in my function where i do the concatenation. The output is as expected.


问:
When predicting unseen data with my model with sklearn, am I meant to bring the original sc.transform method?
I'm using sklearn and have a model based on network intrusion detection which has over 50 columns.

I want to make the model transferable and used elsewhere for other data that isn't just X_test. As far as I know, I calculate the mean and standard deviation of the training data, and then use that to transform the testing data.

If I were to use this model elsewhere, JUST the prediction part of my code, how would I transfer it elsewhere and make it usable? Am I saving the wrong part here: fit_new_input, or should I be saving the x = sc.fit_transform part because that is ultimately what the new test data later on will be using?

from joblib import dump
from joblib import load
df1 = pd.read_csv('trainingdata.csv', sep=r'\s*,\s*', engine='python')
df2 = pd.read_csv('testdata.csv', sep=r'\s*,\s*', engine='python')

saved_model = keras.models.load_model("Model.h5")

sc = MinMaxScaler()
x = pd.get_dummies(trainingdata.drop(['Label', ], axis = 1))
x = sc.fit_transform(x) # <<< SHOULD I BE SAVING THIS INSTEAD AND REUSING IT ELSEWHERE?
testdata = testdata.drop(['Label', ], axis = 1)
fit_new_input = sc.transform(testdata) # <<<< I'M SAVING THIS, IS THIS CORRECT?
dump(fit_new_input, 'scaler_transform.joblib')
scaler_transform = load('scaler_transform.joblib')

#pred = saved_model.predict(scaler.reshape(-1,77))
```


问:
How to import a table containing arrays into PostgreSQL with pgAdmin 4?
I have a table which has data type "array". I've imported the data into pgAdmin4, but it always fails because I'm confused about how to import data that has an array data type. Below is the code that I have tried

```<code>CREATE TABLE dvdrentals.film (
film_id smallint,
title varchar,
description text,
release_year int,
language_id smallint,
original_language_id smallint,
rental_duration smallint,
rental_rate numeric,
length smallint,
replacement_cost numeric,
rating varchar,
last_update timestamp,
special_features varchar[]);
</code>```

how to import special_features column with array data type?

Contents of the data type array:

special_features
["Deleted Scenes","Behind the Scenes"]
["Trailers","Deleted Scenes","Behind the Scenes"]
...
```

Body:
I have a table which has data type "array". I've imported the data into pgAdmin4, but it always fails because I'm confused about how to import data that has an array data type. Below is the code that I have tried

CREATE TABLE dvdrentals.film (
film_id smallint,
title varchar,
description text,
release_year int,
language_id smallint,
original_language_id smallint,
rental_duration smallint,
rental_rate numeric,
length smallint,
replacement_cost numeric,
rating varchar,
last_update timestamp,
special_features varchar[]);

how to import special_features column with array data type?

Contents of the data type array:

special_features
["Deleted Scenes","Behind the Scenes"]
["Trailers","Deleted Scenes","Behind the Scenes"]
...


问:
Python: ModuleNotFoundError: No module named 'foo' even with __init__.py file
I have a flask project and is basically setup like so:

```<code>...
├-- nba_elo_system
│   ├-- __init__.py
│   ├-- db.py
│   ├-- elo_calculator.py
│   ├-- models.py
│   ├-- routes.py
│   └-- nba.db
└-- run.py
</code>```

There's a Elo_Calculator class in elo_calculator.py that I'm trying to import to db.py with the following, the same way I import in my other files

```<code>from nba_elo_system.elo_calculator import Elo_Calculator
</code>```

But I get the following error when I run db.py

```<code>Traceback (most recent call last):
  File "...\nba_elo_system\db.py", line 10, in <module>
    from nba.calculator import Elo
ModuleNotFoundError: No module named 'nba'
</code>```

Also I did try a relative import with

```<code>from . import elo_calculator
</code>```

But I got another error

```<code>Traceback (most recent call last):
  File "...\nba_elo_system\db.py", line 10, in <module>
    from . import elo_calculator
ImportError: attempted relative import with no known parent package
</code>```

Whereas when I use this

```<code>from elo_calculator import Elo_Calculator
</code>```

db.py runs fine.

Why doesn't the first method of importing work even though I use it in other files like routes.py? Is it because I'm not directly running routes.py but instead run.py?
What's the difference between the second and third methods?

Any help would be greatly appreciated! Thanks.

Body:
I have a flask project and is basically setup like so:

...
├-- nba_elo_system
│   ├-- __init__.py
│   ├-- db.py
│   ├-- elo_calculator.py
│   ├-- models.py
│   ├-- routes.py
│   └-- nba.db
└-- run.py

There's a Elo_Calculator class in elo_calculator.py that I'm trying to import to db.py with the following, the same way I import in my other files

from nba_elo_system.elo_calculator import Elo_Calculator

But I get the following error when I run db.py

Traceback (most recent call last):
  File "...\nba_elo_system\db.py", line 10, in <module>
    from nba.calculator import Elo
ModuleNotFoundError: No module named 'nba'

Also I did try a relative import with

from . import elo_calculator

But I got another error

Traceback (most recent call last):
  File "...\nba_elo_system\db.py", line 10, in <module>
    from . import elo_calculator
ImportError: attempted relative import with no known parent package

Whereas when I use this

from elo_calculator import Elo_Calculator

db.py runs fine.

Why doesn't the first method of importing work even though I use it in other files like routes.py? Is it because I'm not directly running routes.py but instead run.py?
What's the difference between the second and third methods?

Any help would be greatly appreciated! Thanks.


问:
how to get bandwith consumption in yii2 per request
How can I get the bandwidth consumption of user per request in yii2?

I tried afteraction and beforeaction in \yii\web\Controller but I don't get it.


问:
Flink SQL using python udf error: org.apache.beam.sdk.options.PipelineOptionsFactory
```<code># start flink sql client
bin/sql-client.sh \
-pyarch file:///opt/flink_data/requirements/py_env/pyflink_jm_1.16.0_env.zip \
-pyexec pyflink_jm_1.16.0_env.zip/bin/python3.7 \
-pyclientexec pyflink_jm_1.16.0_env.zip/bin/python3.7 \
-pyfs file:///opt/flink_data/requirements/udfs

# my python udf func
from pyflink.table import DataTypes
from pyflink.table.udf import udf

@udf(input_types=[DataTypes.STRING()],result_type=DataTypes.STRING())
def func1(line):
    return "udf_{}".format(line)

# call python udf in sql client
Flink SQL> CREATE TEMPORARY FUNCTION func1 AS 'to_fahr.func1' LANGUAGE PYTHON;
Flink SQL> select func1('Chicago');
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.flink.api.java.ClosureCleaner (file:/opt/flink/lib/flink-dist-1.16.0.jar) to field java.lang.Class.ANNOTATION
WARNING: Please consider reporting this to the maintainers of org.apache.flink.api.java.ClosureCleaner
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
+----+--------------------------------+
| op |                         EXPR$0 |
+----+--------------------------------+
[ERROR] Could not execute SQL statement. Reason:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.beam.sdk.options.PipelineOptionsFactory

#error log in log file
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.beam.sdk.options.PipelineOptionsFactory
        at org.apache.flink.streaming.api.runners.python.beam.BeamPythonFunctionRunner.open(BeamPythonFunctionRunner.java:238) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.api.operators.python.process.AbstractExternalPythonFunctionOperator.open(AbstractExternalPythonFunctionOperator.java:57) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.table.runtime.operators.python.AbstractStatelessFunctionOperator.open(AbstractStatelessFunctionOperator.java:92) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.table.runtime.operators.python.scalar.AbstractPythonScalarFunctionOperator.open(AbstractPythonScalarFunctionOperator.java:101) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.table.runtime.operators.python.scalar.PythonScalarFunctionOperator.open(PythonScalarFunctionOperator.java:71) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.RegularOperatorChain.initializeStateAndOpenOperators(RegularOperatorChain.java:107) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTask.restoreGates(StreamTask.java:726) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTaskActionExecutor$SynchronizedStreamTaskActionExecutor.call(StreamTaskActionExecutor.java:100) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTask.restoreInternal(StreamTask.java:702) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTask.restore(StreamTask.java:669) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.runWithSystemExitMonitoring(Task.java:935) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.restoreAndInvoke(Task.java:904) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:728) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.run(Task.java:550) ~[flink-dist-1.16.0.jar:1.16.0]
        at java.lang.Thread.run(Unknown Source) ~[?:?]
</code>```

Does anyone know what to do next? I guess it maybe some situation

python interpreter in the cluster needs requirments

some configuration wrong with the flink sql client

How can i use python udf correctly in flink sql client?

Body:
# start flink sql client
bin/sql-client.sh \
-pyarch file:///opt/flink_data/requirements/py_env/pyflink_jm_1.16.0_env.zip \
-pyexec pyflink_jm_1.16.0_env.zip/bin/python3.7 \
-pyclientexec pyflink_jm_1.16.0_env.zip/bin/python3.7 \
-pyfs file:///opt/flink_data/requirements/udfs

# my python udf func
from pyflink.table import DataTypes
from pyflink.table.udf import udf

@udf(input_types=[DataTypes.STRING()],result_type=DataTypes.STRING())
def func1(line):
    return "udf_{}".format(line)

# call python udf in sql client
Flink SQL> CREATE TEMPORARY FUNCTION func1 AS 'to_fahr.func1' LANGUAGE PYTHON;
Flink SQL> select func1('Chicago');
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.flink.api.java.ClosureCleaner (file:/opt/flink/lib/flink-dist-1.16.0.jar) to field java.lang.Class.ANNOTATION
WARNING: Please consider reporting this to the maintainers of org.apache.flink.api.java.ClosureCleaner
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
+----+--------------------------------+
| op |                         EXPR$0 |
+----+--------------------------------+
[ERROR] Could not execute SQL statement. Reason:
java.lang.NoClassDefFoundError: Could not initialize class org.apache.beam.sdk.options.PipelineOptionsFactory

#error log in log file
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.apache.beam.sdk.options.PipelineOptionsFactory
        at org.apache.flink.streaming.api.runners.python.beam.BeamPythonFunctionRunner.open(BeamPythonFunctionRunner.java:238) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.api.operators.python.process.AbstractExternalPythonFunctionOperator.open(AbstractExternalPythonFunctionOperator.java:57) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.table.runtime.operators.python.AbstractStatelessFunctionOperator.open(AbstractStatelessFunctionOperator.java:92) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.table.runtime.operators.python.scalar.AbstractPythonScalarFunctionOperator.open(AbstractPythonScalarFunctionOperator.java:101) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.table.runtime.operators.python.scalar.PythonScalarFunctionOperator.open(PythonScalarFunctionOperator.java:71) ~[flink-python-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.RegularOperatorChain.initializeStateAndOpenOperators(RegularOperatorChain.java:107) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTask.restoreGates(StreamTask.java:726) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTaskActionExecutor$SynchronizedStreamTaskActionExecutor.call(StreamTaskActionExecutor.java:100) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTask.restoreInternal(StreamTask.java:702) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.streaming.runtime.tasks.StreamTask.restore(StreamTask.java:669) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.runWithSystemExitMonitoring(Task.java:935) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.restoreAndInvoke(Task.java:904) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:728) ~[flink-dist-1.16.0.jar:1.16.0]
        at org.apache.flink.runtime.taskmanager.Task.run(Task.java:550) ~[flink-dist-1.16.0.jar:1.16.0]
        at java.lang.Thread.run(Unknown Source) ~[?:?]

Does anyone know what to do next? I guess it maybe some situation

python interpreter in the cluster needs requirments

some configuration wrong with the flink sql client

How can i use python udf correctly in flink sql client?


问:
Populate id of subdocument with mongoose
I'm trying to build an API with Express and Mongoose. The way that this API works is that I have a Schema for Customers, Devices and Orders. When a service Order is created, it will contain information regarding the Devices being serviced and the Customer they belong to.

So far the only issue I'm experiencing is when I'm querying an Order and when using .populate. All of my .populate work with id's except for one making reference to a subdocument.

Here's my Orders Schema:

```<code>
   var Device = new Schema({
              deviceId: { type: Schema.ObjectId, ref: 'Device', required: true},
              diagnosis: { type: String },
              resolution: { type: String },
              notes: { type: String },
              serviceCompleted: { type: Boolean, default: false},
              servicedBy: { type: Schema.ObjectId, ref: 'User'}
               })

              var Order = new Schema({
              customerId: { type: Schema.ObjectId, ref: 'Customer', required: true },
              servDevices: [Device],
              isOpen: { type: Boolean, default: true},
              servAddressId: {type: Schema.ObjectId, ref: 'Customer.contactInfo.address',      required: true},
              notes: { type: String },
              createdOn: { type: Date, default: Date.now },
              createdBy: { type: Schema.ObjectId, ref: 'User', required: true},
              closedBy: { type: Schema.ObjectId, ref: 'User'}

               })

</code>```

Here's my Customers Schema:

```<code> var CustomerAddresses = new Schema({
           id: ObjectId,
           description: { type: String },
           isBusiness: { type: Boolean, default: false},
           street1: { type: String, required: true },
           street2: { type: String },
           city: { type: String, required: true },
           state: { type: String, required: true },
           zip: { type: String, required: true }
           })

           var CustomerAltEmails = new Schema({
           id: ObjectId,
           email: { type: String, trim: true}
           })

           var CustomerPhones = new Schema({
           id: ObjectId,
           description: { type: String },
           number: { type: String, required: true },
           ext: { type: String }
           })

           var Customer = new Schema({
           id: ObjectId,
           firstName: { type: String, required: true },
           lastName: { type: String },
           contactInfo: {
             email: { type: String, required: true, unique: true, trim: true },
             altEmail: [CustomerAltEmails],
             phone: [CustomerPhones],
             address: [CustomerAddresses],
           },
           company: { type: Schema.Types.ObjectId, ref: 'Company'},
           notes: { type: String },
           createdBy: { type: Schema.Types.ObjectId, ref: 'User', required: true },
           lastModifiedBy: { type: Schema.Types.ObjectId, ref: 'User' },
           },

        {
        timestamps: { createdAt: 'customerSince', updatedAt: 'lastModified' }
        })

</code>```

And here are all my .populates (The very last one is the one I'm having a hard time making it to work)

```<code>                     Order.findById({_id: req.query._id})
                    .populate('createdBy', 'firstName lastName')
                    .populate('customerId', 'firstName lastName')
                    .populate('servDevices.deviceId', 'brand model serial description notes')
                    .populate('servAddressId', 'description') //HERE'S MY PROBLEM
                    .exec(function (err, order) {
                        if (err) {
                            console.log(err)
                            res.send(err)
                        }
                        else {
                            console.log(order)
                            res.json(order);
                        }
                    })

</code>```

I don't exactly know what to do. I've read some documentation from Mongoose and even tried a different syntax for the .populate({path: populate:...}) with no success. What I get on my terminal is an error saying "Schema hasn't been registered for model "Customer.contactInfo.address".

Can someone please share some knowledge into this issue? Thank you so much!

Not understanding exactly how this worked, but I tried many similar things like this:

```<code>                    // .populate({
                    //     path: 'servAddressId.description',
                    //     populate: {
                    //         path: 'Customer',
                    //     }})
</code>```

Body:
I'm trying to build an API with Express and Mongoose. The way that this API works is that I have a Schema for Customers, Devices and Orders. When a service Order is created, it will contain information regarding the Devices being serviced and the Customer they belong to.

So far the only issue I'm experiencing is when I'm querying an Order and when using .populate. All of my .populate work with id's except for one making reference to a subdocument.

Here's my Orders Schema:

   var Device = new Schema({
              deviceId: { type: Schema.ObjectId, ref: 'Device', required: true},
              diagnosis: { type: String },
              resolution: { type: String },
              notes: { type: String },
              serviceCompleted: { type: Boolean, default: false},
              servicedBy: { type: Schema.ObjectId, ref: 'User'}
               })

              var Order = new Schema({
              customerId: { type: Schema.ObjectId, ref: 'Customer', required: true },
              servDevices: [Device],
              isOpen: { type: Boolean, default: true},
              servAddressId: {type: Schema.ObjectId, ref: 'Customer.contactInfo.address',      required: true},
              notes: { type: String },
              createdOn: { type: Date, default: Date.now },
              createdBy: { type: Schema.ObjectId, ref: 'User', required: true},
              closedBy: { type: Schema.ObjectId, ref: 'User'}

               })

Here's my Customers Schema:

 var CustomerAddresses = new Schema({
           id: ObjectId,
           description: { type: String },
           isBusiness: { type: Boolean, default: false},
           street1: { type: String, required: true },
           street2: { type: String },
           city: { type: String, required: true },
           state: { type: String, required: true },
           zip: { type: String, required: true }
           })

           var CustomerAltEmails = new Schema({
           id: ObjectId,
           email: { type: String, trim: true}
           })

           var CustomerPhones = new Schema({
           id: ObjectId,
           description: { type: String },
           number: { type: String, required: true },
           ext: { type: String }
           })

           var Customer = new Schema({
           id: ObjectId,
           firstName: { type: String, required: true },
           lastName: { type: String },
           contactInfo: {
             email: { type: String, required: true, unique: true, trim: true },
             altEmail: [CustomerAltEmails],
             phone: [CustomerPhones],
             address: [CustomerAddresses],
           },
           company: { type: Schema.Types.ObjectId, ref: 'Company'},
           notes: { type: String },
           createdBy: { type: Schema.Types.ObjectId, ref: 'User', required: true },
           lastModifiedBy: { type: Schema.Types.ObjectId, ref: 'User' },
           },

        {
        timestamps: { createdAt: 'customerSince', updatedAt: 'lastModified' }
        })

And here are all my .populates (The very last one is the one I'm having a hard time making it to work)

                     Order.findById({_id: req.query._id})
                    .populate('createdBy', 'firstName lastName')
                    .populate('customerId', 'firstName lastName')
                    .populate('servDevices.deviceId', 'brand model serial description notes')
                    .populate('servAddressId', 'description') //HERE'S MY PROBLEM
                    .exec(function (err, order) {
                        if (err) {
                            console.log(err)
                            res.send(err)
                        }
                        else {
                            console.log(order)
                            res.json(order);
                        }
                    })

I don't exactly know what to do. I've read some documentation from Mongoose and even tried a different syntax for the .populate({path: populate:...}) with no success. What I get on my terminal is an error saying "Schema hasn't been registered for model "Customer.contactInfo.address".

Can someone please share some knowledge into this issue? Thank you so much!

Not understanding exactly how this worked, but I tried many similar things like this:

                    // .populate({
                    //     path: 'servAddressId.description',
                    //     populate: {
                    //         path: 'Customer',
                    //     }})


问:
ApiCast deployed on AWS as docker unable to access the echoAPI on SaaS 3scale API trial version
I am trying to call an api deployed on the 3scale API SaaS platform(provided by redhat as trial).I wanted to check with the APICAST deployed outside the hosted 3scale envirnment provided by redhat which would connect to the SaaS platform I currently have(hosted by redhat trial).

However to do this i have deployed the docker on my AWS using the following command

```<code>docker run --name apicast --rm -p 443:8080 -e THREESCALE_PORTAL_ENDPOINT=https://<ACCESS_TOKEN>@<3SCALE_MNGMT_ROUTE> registry.redhat.io/3scale-amp2/apicast-gateway-rhel8:3scale2.9
</code>```

where access token=token I generated on 3scale.I have then published the changes in my 3scale api and hence get a curl to call the api

However when i make the call using postman I get the following error

I have been stuck with this for quite some time.Could anyone please point me in the right direction?

Body:
I am trying to call an api deployed on the 3scale API SaaS platform(provided by redhat as trial).I wanted to check with the APICAST deployed outside the hosted 3scale envirnment provided by redhat which would connect to the SaaS platform I currently have(hosted by redhat trial).

However to do this i have deployed the docker on my AWS using the following command

docker run --name apicast --rm -p 443:8080 -e THREESCALE_PORTAL_ENDPOINT=https://<ACCESS_TOKEN>@<3SCALE_MNGMT_ROUTE> registry.redhat.io/3scale-amp2/apicast-gateway-rhel8:3scale2.9

where access token=token I generated on 3scale.I have then published the changes in my 3scale api and hence get a curl to call the api

However when i make the call using postman I get the following error

I have been stuck with this for quite some time.Could anyone please point me in the right direction?


问:
Issue with importing SCVI package into an jupyter environment [partially initialized module 'jax' has no attribute 'version']
I am analyzing single cell RNA-seq data in jupyter utilizing python3. In order to delineate differential expression between cells/samples/etc. scanpy and SCVI is needed to perform the task i need. I am able to install SCVI and I installed scvi-tools into jupyter:

[!pip3 install SCVI]
[!pip install "scvi-tools[tutorials]"]

-This was successful.

Proceeded to import SCVI and this error occured

[ import scvi ]

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[264], line 1
----> 1 import scvi

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/__init__.py:10
      7 from ._settings import settings
      9 # this import needs to come after prior imports to prevent circular import
---> 10 from . import data, model, external, utils
     12 # https://github.com/python-poetry/poetry/pull/2366#issuecomment-652418094
     13 # https://github.com/python-poetry/poetry/issues/144#issuecomment-623927302
     14 try:

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/__init__.py:3
      1 from anndata import read_csv, read_h5ad, read_loom, read_text
----> 3 from ._datasets import (
      4     annotation_simulation,
      5     brainlarge_dataset,
      6     breast_cancer_dataset,
      7     cortex,
      8     dataset_10x,
      9     frontalcortex_dropseq,
     10     heart_cell_atlas_subsampled,
     11     mouse_ob_dataset,
     12     pbmc_dataset,
     13     pbmc_seurat_v4_cite_seq,
     14     pbmcs_10x_cite_seq,
     15     prefrontalcortex_starmap,
     16     purified_pbmc_dataset,
     17     retina,
     18     seqfish,
     19     seqfishplus,
     20     smfish,
     21     spleen_lymph_cite_seq,
     22     synthetic_iid,
     23 )
     24 from ._manager import AnnDataManager, AnnDataManagerValidationCheck
     25 from ._preprocessing import (
     26     organize_cite_seq_10x,
     27     organize_multiome_anndatas,
     28     poisson_gene_selection,
     29 )

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/_datasets.py:5
      1 from typing import List, Optional
      3 import anndata
----> 5 from ._built_in_data._brain_large import _load_brainlarge_dataset
      6 from ._built_in_data._cite_seq import (
      7     _load_pbmc_seurat_v4_cite_seq,
      8     _load_pbmcs_10x_cite_seq,
      9     _load_spleen_lymph_cite_seq,
     10 )
     11 from ._built_in_data._cortex import _load_cortex

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/_built_in_data/_brain_large.py:9
      6 import numpy as np
      7 import scipy.sparse as sp_sparse
----> 9 from scvi.data._download import _download
     11 logger = logging.getLogger(__name__)
     14 def _load_brainlarge_dataset(
     15     save_path: str = "data/",
     16     sample_size_gene_var: int = 10000,
   (...)
     19     loading_batch_size: int = 100000,
     20 ) -> anndata.AnnData:

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/_download.py:8
      4 from typing import Optional
      6 import numpy as np
----> 8 from scvi.utils import track
     10 logger = logging.getLogger(__name__)
     13 def _download(url: Optional[str], save_path: str, filename: str):

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/utils/__init__.py:4
      2 from ._decorators import unsupported_in_latent_mode
      3 from ._docstrings import setup_anndata_dsp
----> 4 from ._jax import device_selecting_PRNGKey
      5 from ._track import track
      7 __all__ = [
      8     "track",
      9     "setup_anndata_dsp",
   (...)
     12     "unsupported_in_latent_mode",
     13 ]

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/utils/_jax.py:3
      1 from typing import Callable
----> 3 import jax
      4 from jax import random
      7 def device_selecting_PRNGKey(use_cpu: bool = True) -> Callable:

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/__init__.py:35
     30 del _cloud_tpu_init
     32 # Confusingly there are two things named "config": the module and the class.
     33 # We want the exported object to be the class, so we first import the module
     34 # to make sure a later import doesn't overwrite the class.
---> 35 from jax import config as _config_module
     36 del _config_module
     38 from jax._src.basearray import Array as Array

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/config.py:17
      1 # Copyright 2018 The JAX Authors.
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License");
   (...)
     14
     15 # TODO(phawkins): fix users of this alias and delete this file.
---> 17 from jax._src.config import config

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/_src/config.py:28
     25 import warnings
     26 from typing import Any, List, Callable, Hashable, NamedTuple, Iterator, Optional
---> 28 from jax._src import lib
     29 from jax._src.lib import jax_jit
     30 from jax._src.lib import transfer_guard_lib

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/_src/lib/__init__.py:75
     71   return _jaxlib_version
     73 version_str = jaxlib.version.__version__
     74 version = check_jaxlib_version(
---> 75   jax_version=jax.version.__version__,
     76   jaxlib_version=jaxlib.version.__version__,
     77   minimum_jaxlib_version=jax.version._minimum_jaxlib_version)
     81 # Before importing any C compiled modules from jaxlib, first import the CPU
     82 # feature guard module to verify that jaxlib was compiled in a way that only
     83 # uses instructions that are present on this machine.
     84 import jaxlib.cpu_feature_guard as cpu_feature_guard

AttributeError: partially initialized module 'jax' has no attribute 'version' (most likely due to a circular import)
</code>```

I am using a mac - M1 - 13.0.1
Python --version 3.9.15

What am I missing?

I have tried installing SCVI using brew forge in conda environment

[ brew install --cask mambaforge ]

This was in my zsh terminal.

I'm assuming there is an issue with my GPU prerequisites

Thanks for any help.

Body:
I am analyzing single cell RNA-seq data in jupyter utilizing python3. In order to delineate differential expression between cells/samples/etc. scanpy and SCVI is needed to perform the task i need. I am able to install SCVI and I installed scvi-tools into jupyter:

[!pip3 install SCVI]
[!pip install "scvi-tools[tutorials]"]

-This was successful.

Proceeded to import SCVI and this error occured

[ import scvi ]

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[264], line 1
----> 1 import scvi

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/__init__.py:10
      7 from ._settings import settings
      9 # this import needs to come after prior imports to prevent circular import
---> 10 from . import data, model, external, utils
     12 # https://github.com/python-poetry/poetry/pull/2366#issuecomment-652418094
     13 # https://github.com/python-poetry/poetry/issues/144#issuecomment-623927302
     14 try:

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/__init__.py:3
      1 from anndata import read_csv, read_h5ad, read_loom, read_text
----> 3 from ._datasets import (
      4     annotation_simulation,
      5     brainlarge_dataset,
      6     breast_cancer_dataset,
      7     cortex,
      8     dataset_10x,
      9     frontalcortex_dropseq,
     10     heart_cell_atlas_subsampled,
     11     mouse_ob_dataset,
     12     pbmc_dataset,
     13     pbmc_seurat_v4_cite_seq,
     14     pbmcs_10x_cite_seq,
     15     prefrontalcortex_starmap,
     16     purified_pbmc_dataset,
     17     retina,
     18     seqfish,
     19     seqfishplus,
     20     smfish,
     21     spleen_lymph_cite_seq,
     22     synthetic_iid,
     23 )
     24 from ._manager import AnnDataManager, AnnDataManagerValidationCheck
     25 from ._preprocessing import (
     26     organize_cite_seq_10x,
     27     organize_multiome_anndatas,
     28     poisson_gene_selection,
     29 )

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/_datasets.py:5
      1 from typing import List, Optional
      3 import anndata
----> 5 from ._built_in_data._brain_large import _load_brainlarge_dataset
      6 from ._built_in_data._cite_seq import (
      7     _load_pbmc_seurat_v4_cite_seq,
      8     _load_pbmcs_10x_cite_seq,
      9     _load_spleen_lymph_cite_seq,
     10 )
     11 from ._built_in_data._cortex import _load_cortex

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/_built_in_data/_brain_large.py:9
      6 import numpy as np
      7 import scipy.sparse as sp_sparse
----> 9 from scvi.data._download import _download
     11 logger = logging.getLogger(__name__)
     14 def _load_brainlarge_dataset(
     15     save_path: str = "data/",
     16     sample_size_gene_var: int = 10000,
   (...)
     19     loading_batch_size: int = 100000,
     20 ) -> anndata.AnnData:

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/data/_download.py:8
      4 from typing import Optional
      6 import numpy as np
----> 8 from scvi.utils import track
     10 logger = logging.getLogger(__name__)
     13 def _download(url: Optional[str], save_path: str, filename: str):

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/utils/__init__.py:4
      2 from ._decorators import unsupported_in_latent_mode
      3 from ._docstrings import setup_anndata_dsp
----> 4 from ._jax import device_selecting_PRNGKey
      5 from ._track import track
      7 __all__ = [
      8     "track",
      9     "setup_anndata_dsp",
   (...)
     12     "unsupported_in_latent_mode",
     13 ]

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/scvi/utils/_jax.py:3
      1 from typing import Callable
----> 3 import jax
      4 from jax import random
      7 def device_selecting_PRNGKey(use_cpu: bool = True) -> Callable:

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/__init__.py:35
     30 del _cloud_tpu_init
     32 # Confusingly there are two things named "config": the module and the class.
     33 # We want the exported object to be the class, so we first import the module
     34 # to make sure a later import doesn't overwrite the class.
---> 35 from jax import config as _config_module
     36 del _config_module
     38 from jax._src.basearray import Array as Array

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/config.py:17
      1 # Copyright 2018 The JAX Authors.
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License");
   (...)
     14
     15 # TODO(phawkins): fix users of this alias and delete this file.
---> 17 from jax._src.config import config

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/_src/config.py:28
     25 import warnings
     26 from typing import Any, List, Callable, Hashable, NamedTuple, Iterator, Optional
---> 28 from jax._src import lib
     29 from jax._src.lib import jax_jit
     30 from jax._src.lib import transfer_guard_lib

File ~/opt/miniconda3/envs/env_x86/lib/python3.9/site-packages/jax/_src/lib/__init__.py:75
     71   return _jaxlib_version
     73 version_str = jaxlib.version.__version__
     74 version = check_jaxlib_version(
---> 75   jax_version=jax.version.__version__,
     76   jaxlib_version=jaxlib.version.__version__,
     77   minimum_jaxlib_version=jax.version._minimum_jaxlib_version)
     81 # Before importing any C compiled modules from jaxlib, first import the CPU
     82 # feature guard module to verify that jaxlib was compiled in a way that only
     83 # uses instructions that are present on this machine.
     84 import jaxlib.cpu_feature_guard as cpu_feature_guard

AttributeError: partially initialized module 'jax' has no attribute 'version' (most likely due to a circular import)

I am using a mac - M1 - 13.0.1
Python --version 3.9.15

What am I missing?

I have tried installing SCVI using brew forge in conda environment

[ brew install --cask mambaforge ]

This was in my zsh terminal.

I'm assuming there is an issue with my GPU prerequisites

Thanks for any help.


问:
NextJS get SyntaxError Unexpected token '=' with chart.js
I am using nextJS 14 with chart.js ^4.1.1 and  react-chartjs-2 ^5.1.0

```<code>import {
    BarElement,
    CategoryScale,
    Chart as ChartJS,
    Legend,
    LinearScale,
    Title,
    Tooltip,
} from 'chart.js'

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)

</code>```

In dev mode, it work fine in many browsers, until i test in iPhone WKWebview (IOS 14.2 sumilator).
It show SyntaxError Unexpected token '=' . Excepted an opening '(' before a method's parameter list

Show the Bar Chart without any error.

Body:
I am using nextJS 14 with chart.js ^4.1.1 and  react-chartjs-2 ^5.1.0

import {
    BarElement,
    CategoryScale,
    Chart as ChartJS,
    Legend,
    LinearScale,
    Title,
    Tooltip,
} from 'chart.js'

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)

In dev mode, it work fine in many browsers, until i test in iPhone WKWebview (IOS 14.2 sumilator).
It show SyntaxError Unexpected token '=' . Excepted an opening '(' before a method's parameter list

Show the Bar Chart without any error.


问:
How to let GCC for MIPS restore the stack pointer just before returning?
When GCC for MIPS compiles a leaf function, it generates assembly code like the following:

```<code>   addiu $sp, $sp, 72
   sb    $v1, 0($v0)
   lbu   $a0, 5($t2)
   lw    $v0, 0($t1)
   sb    $a0,1($v0)
   lbu   $v1,6($t2)
   lw    $v0,0($t1)
   sb    $v1,2($v0)
   lw    $a0,0($t1)
   lbu   $v0,7($t2)
   jr    $ra
   sb    $v0,3($a0)
</code>```

where  "addiu  $sp, $sp, 72" is the instruction that
pops the stack pointer,  there're many instructions between this instruction and the return
instruction "jr      $ra".

This could cause problem in a pre-emptive OS: when the current thread is interrupted just between the "addiu $sp, $sp, 72" instruction and "jr $ra" by an hardware interrupt, after the interrupt service routine finishes, a thread of higher priority will be scheduled to run,  it will ruin the original thread's stack.

This only happens when the function is a leaf function,  does GCC for MIPS have any compiling options not to generate code like above?

Body:
When GCC for MIPS compiles a leaf function, it generates assembly code like the following:

   addiu $sp, $sp, 72
   sb    $v1, 0($v0)
   lbu   $a0, 5($t2)
   lw    $v0, 0($t1)
   sb    $a0,1($v0)
   lbu   $v1,6($t2)
   lw    $v0,0($t1)
   sb    $v1,2($v0)
   lw    $a0,0($t1)
   lbu   $v0,7($t2)
   jr    $ra
   sb    $v0,3($a0)

where  "addiu  $sp, $sp, 72" is the instruction that
pops the stack pointer,  there're many instructions between this instruction and the return
instruction "jr      $ra".

This could cause problem in a pre-emptive OS: when the current thread is interrupted just between the "addiu $sp, $sp, 72" instruction and "jr $ra" by an hardware interrupt, after the interrupt service routine finishes, a thread of higher priority will be scheduled to run,  it will ruin the original thread's stack.

This only happens when the function is a leaf function,  does GCC for MIPS have any compiling options not to generate code like above?


问:
try to load js dynamically in vue.js but having error to call function
i'm trying to load local script and external script in vue.js. Initially, I loaded external script in 'mounted' and loaded local script in top of export default.
However, i had an error saying somes values or functions inside the local script is not defined.
I believe it's because the local script which is using some functions in external script is loaded first before the external script is fully loaded.
So, i remove the import local script, and put it in 'mounted' when the external script is fully loaded. Then, it worked successfully.
However, when i try to use the functions from the local script, now it says the functions updateNode()  and updateEdge() are not defined.
I tried to change them to this.updateNode() or window(s).updateNode() or m.updateNode(), but none of them worked.
How can i call the functions?
i tried to copy the functions from script in method, but not quite successful.

<template>

add node

      node id (int)<input type="text" id="newID">

      label text (text)<input type="text" id="newLabel">

      <input type="button" value="Update" @click="updateNode()">

add edge

      from id (int)<input type="text" id="newEdgeFromID">

      to id (int)<input type="text" id="newEdgeToID">

      edge text (text)<input type="text" id="newEdgeLabel">

      <input type="button" value="Update" @click="updateEdge()">

</template>


问:
AsyncResource.runInAsync argument passing RxJS
I'm having trouble figuring out how AsyncResource supports passing of arguments to the bound function.

Details

NodeJS now includes AsyncLocalStorage as an analog to a ThreadLocal in a threaded environment. That is, it provides a storage (usually a key/value map) that can be accessed throughout a call-chain, such as an HTTP request.

This provides a useful pattern for a "request scoped cache" or similar, that would otherwise result in an unwieldy API of passing params around. The cache can just be obtained globally, and nodeJS takes care of providing the unique storage bucket for a given request or call-chain, taking care of managing the set of them behind-the-scenes.

That is until it doesn't. Very occasionally, the async id gets lost along the way. A common case of this is when using EventEmitter extended classes.

Fortunately, for this, there is AsyncResource, which can capture the asyncId in a running callchain, and bind another callback function to that ID, so that the callback function gets the same instance of the cache.

Usage With RxJS

I had a case where an RxJS subscribe method was losing access to the AsyncLocalStorage, even though it had been set up.

I rebound the callback using an AsyncResource. Here's the puzzling part:

```<code>subject.subscribe(asyncResource.runInAsyncScope.bind(asyncResource, async (v) => {
    console.log(`observerA: ${v}, with cache value: ${cacheValue}`);
}, null));
</code>```

When I write the callback as above, arguments are passed into the callback function correctly.

When I write as below, the callback function receives no arguments.

```<code>subject.subscribe(asyncResource.runInAsyncScope.bind(asyncResource, async (v) => {
    console.log(`observerA: ${v}`);
}));
</code>```

Question

What is the difference? In the first version we have an additional argument of null after the callback function. Why does the first version have arguments passed correctly and the latter does not?

Appendix

Here is a test program I used to figure out how to get arguments passed correctly via the AsyncResource. (The test doesn't reproduce the Async context getting lost, so the RxJS callback would work just as well without the AsyncResource, but in the real-life project, it saves the day).

```<code>const server = createServer((req, res) => {
    const localStorage = new AsyncLocalStorage<Map<string, any>>();
    localStorage.run(localStorage.getStore(), () => {

        const store = localStorage.getStore();
        store.set("foo", "bar")
        const asyncResource = new AsyncResource('request');
        subject.subscribe(asyncResource.runInAsyncScope.bind(asyncResource, async (v) => {
            const contextHolder = ContextHolder.getInstance()
            const cacheValue = contextHolder.localStorage.get<string>("foo")
            console.log(`observerA: ${v}, with cache value: ${cacheValue}`);
        }, null));

        setTimeout(() => {
            const store = localStorage.getStore();
            store.set("foo", "zzzaaappa")
        }, 1500)

        subject.next(1);
        subject.next(2);
        setTimeout(() => {
            subject.next(3)
        }, 1000)

        setTimeout(() => {
            subject.next(4)
        }, 2000)

        setTimeout(() => {
            subject.next(5)
        }, 3000)

        setTimeout(() => {
            console.log("$$$$$$$ LONG ONE !!!!!!!!!")
            res.writeHead(200)
            res.end("Hello there!");
        }, 4000)

    })

}).listen(3000);
console.log("Running")
</code>```

Body:
I'm having trouble figuring out how AsyncResource supports passing of arguments to the bound function.

Details

NodeJS now includes AsyncLocalStorage as an analog to a ThreadLocal in a threaded environment. That is, it provides a storage (usually a key/value map) that can be accessed throughout a call-chain, such as an HTTP request.

This provides a useful pattern for a "request scoped cache" or similar, that would otherwise result in an unwieldy API of passing params around. The cache can just be obtained globally, and nodeJS takes care of providing the unique storage bucket for a given request or call-chain, taking care of managing the set of them behind-the-scenes.

That is until it doesn't. Very occasionally, the async id gets lost along the way. A common case of this is when using EventEmitter extended classes.

Fortunately, for this, there is AsyncResource, which can capture the asyncId in a running callchain, and bind another callback function to that ID, so that the callback function gets the same instance of the cache.

Usage With RxJS

I had a case where an RxJS subscribe method was losing access to the AsyncLocalStorage, even though it had been set up.

I rebound the callback using an AsyncResource. Here's the puzzling part:

subject.subscribe(asyncResource.runInAsyncScope.bind(asyncResource, async (v) => {
    console.log(`observerA: ${v}, with cache value: ${cacheValue}`);
}, null));

When I write the callback as above, arguments are passed into the callback function correctly.

When I write as below, the callback function receives no arguments.

subject.subscribe(asyncResource.runInAsyncScope.bind(asyncResource, async (v) => {
    console.log(`observerA: ${v}`);
}));

Question

What is the difference? In the first version we have an additional argument of null after the callback function. Why does the first version have arguments passed correctly and the latter does not?

Appendix

Here is a test program I used to figure out how to get arguments passed correctly via the AsyncResource. (The test doesn't reproduce the Async context getting lost, so the RxJS callback would work just as well without the AsyncResource, but in the real-life project, it saves the day).

const server = createServer((req, res) => {
    const localStorage = new AsyncLocalStorage<Map<string, any>>();
    localStorage.run(localStorage.getStore(), () => {

        const store = localStorage.getStore();
        store.set("foo", "bar")
        const asyncResource = new AsyncResource('request');
        subject.subscribe(asyncResource.runInAsyncScope.bind(asyncResource, async (v) => {
            const contextHolder = ContextHolder.getInstance()
            const cacheValue = contextHolder.localStorage.get<string>("foo")
            console.log(`observerA: ${v}, with cache value: ${cacheValue}`);
        }, null));

        setTimeout(() => {
            const store = localStorage.getStore();
            store.set("foo", "zzzaaappa")
        }, 1500)

        subject.next(1);
        subject.next(2);
        setTimeout(() => {
            subject.next(3)
        }, 1000)

        setTimeout(() => {
            subject.next(4)
        }, 2000)

        setTimeout(() => {
            subject.next(5)
        }, 3000)

        setTimeout(() => {
            console.log("$$$$$$$ LONG ONE !!!!!!!!!")
            res.writeHead(200)
            res.end("Hello there!");
        }, 4000)

    })

}).listen(3000);
console.log("Running")


问:
How to merge a dataframe and plot from 3 excels documents
I need your help,
I want to create a dataframe and to plot a graph showing the evolution of the real estate, the price of renting and the evolution of the interest rate.  I don’t succeed to create a code for that, do you have any ideal ?
Which code can show me, and also give me a graph of the evolution of the 3 indicators merged together, to know how the real estate evolve with the interest rate.knowing that i want the same period quarterly for all.

Thanks in advance, I am also a beginner.


问:
Add a product when Order Again in woocommerce
My product has variable description and price so I am using meta data to make the pre-orders for the customers, after that the customer selects reorder and pays for the product.

As the product is variable when reordering there is no real stock or price so I had to send the total ammount to a fee. That works ok but I can not use coupons. I have tried instead of adding the fee, to add a product with the price being $credit value but had no luck, $product->set_price( $credit );.

```<code>  // ----------------
// 3. Detect Edit Order Action and Store in Session

add_action( 'woocommerce_cart_loaded_from_session', 'bbloomer_detect_edit_order' );

function bbloomer_detect_edit_order( $cart ) {
    if ( isset( $_GET['edit_order'], $_GET['_wpnonce'] ) && is_user_logged_in() && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-order_again' ) ) WC()->session->set( 'edit_order', absint( $_GET['edit_order'] ) );
}

// ----------------
// 4. Display Cart Notice re: Edited Order

add_action( 'woocommerce_before_cart', 'bbloomer_show_me_session' );

function bbloomer_show_me_session() {
    if ( ! is_cart() ) return;
    $edited = WC()->session->get('edit_order');
    if ( ! empty( $edited ) ) {
        $order = new WC_Order( $edited );
        $credit = $order->get_total();

    }
}

// ----------------
// 5. Calculate New Total if Edited Order

add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_use_edit_order_total', 20, 1 );

function bbloomer_use_edit_order_total( $cart ) {

  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

  $edited = WC()->session->get('edit_order');
  if ( ! empty( $edited ) ) {
      $order = new WC_Order( $edited );
      $credit = 1 * $order->get_total();

      $cart->add_fee( 'FLETE', $credit );

  }

}

// 6. Save Order Action if New Order is Placed

add_action( 'woocommerce_checkout_update_order_meta', 'bbloomer_save_edit_order' );

function bbloomer_save_edit_order( $order_id ) {
    $edited = WC()->session->get( 'edit_order' );
    if ( ! empty( $edited ) ) {
        // update this new order
        update_post_meta( $order_id, '_edit_order', $edited );
        $neworder = new WC_Order( $order_id );
        $oldorder_edit = get_edit_post_link( $edited );
        $neworder->add_order_note( 'Order placed after editing. Old order number: <a href="' . $oldorder_edit . '">' . $edited . '</a>' );
        // cancel previous order
        $oldorder = new WC_Order( $edited );
        $neworder_edit = get_edit_post_link( $order_id );
        $oldorder->update_status( 'cancelled', 'Order cancelled after editing. New order number: <a href="' . $neworder_edit . '">' . $order_id . '</a> -' );
        WC()->session->set( 'edit_order', null );
</code>```

Body:
My product has variable description and price so I am using meta data to make the pre-orders for the customers, after that the customer selects reorder and pays for the product.

As the product is variable when reordering there is no real stock or price so I had to send the total ammount to a fee. That works ok but I can not use coupons. I have tried instead of adding the fee, to add a product with the price being $credit value but had no luck, $product->set_price( $credit );.

  // ----------------
// 3. Detect Edit Order Action and Store in Session

add_action( 'woocommerce_cart_loaded_from_session', 'bbloomer_detect_edit_order' );

function bbloomer_detect_edit_order( $cart ) {
    if ( isset( $_GET['edit_order'], $_GET['_wpnonce'] ) && is_user_logged_in() && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), 'woocommerce-order_again' ) ) WC()->session->set( 'edit_order', absint( $_GET['edit_order'] ) );
}

// ----------------
// 4. Display Cart Notice re: Edited Order

add_action( 'woocommerce_before_cart', 'bbloomer_show_me_session' );

function bbloomer_show_me_session() {
    if ( ! is_cart() ) return;
    $edited = WC()->session->get('edit_order');
    if ( ! empty( $edited ) ) {
        $order = new WC_Order( $edited );
        $credit = $order->get_total();

    }
}

// ----------------
// 5. Calculate New Total if Edited Order

add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_use_edit_order_total', 20, 1 );

function bbloomer_use_edit_order_total( $cart ) {

  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

  $edited = WC()->session->get('edit_order');
  if ( ! empty( $edited ) ) {
      $order = new WC_Order( $edited );
      $credit = 1 * $order->get_total();

      $cart->add_fee( 'FLETE', $credit );

  }

}

// 6. Save Order Action if New Order is Placed

add_action( 'woocommerce_checkout_update_order_meta', 'bbloomer_save_edit_order' );

function bbloomer_save_edit_order( $order_id ) {
    $edited = WC()->session->get( 'edit_order' );
    if ( ! empty( $edited ) ) {
        // update this new order
        update_post_meta( $order_id, '_edit_order', $edited );
        $neworder = new WC_Order( $order_id );
        $oldorder_edit = get_edit_post_link( $edited );
        $neworder->add_order_note( 'Order placed after editing. Old order number: ' . $edited . '' );
        // cancel previous order
        $oldorder = new WC_Order( $edited );
        $neworder_edit = get_edit_post_link( $order_id );
        $oldorder->update_status( 'cancelled', 'Order cancelled after editing. New order number: ' . $order_id . ' -' );
        WC()->session->set( 'edit_order', null );


问:
Wrong code generation while using "-march=armv7-a -mfloat-abi=softfp -mfpu=neon" on gcc 4.3.3
I am maintaining an project which build with gcc-4.3.3 and I find something strange. The compiler will generate wrong code when I use specified compile option.
Here is my test code which on a file named test.cpp, var1.m_mask will be set correctly but the var2.m_mask is not set correctly, still keeping default value.
`

```<code>struct TestStruct
{
public:
    TestStruct(void);
    ~TestStruct(void);
    inline void SetFloatValue(float value)
    {
        m_fValue = value;
        m_mask |= 1;
    }
private:
    unsigned long long  m_mask;     //8 bytes
    float               m_fValue;   //4 byts
    char reserved[128 - 8 - 4 + 1]; //If sizeof(reserved) <= 116, it is ok
};
extern void OtherFunc(  const TestStruct &st );
void Test()
{
    //First variable
    TestStruct var1;
    //set var1.m_mask and var1.m_fValue
    var1.SetFloatValue( 100.0f );
    //call some function in case that var1 would be optimized
    OtherFunc( var1 );

    //Second variable
    TestStruct var2;
    //Set var2.m_fValue and var2.m_mask !!!
    var2.SetFloatValue( 100.0f );
    //call some function in case that var2 would be optimized
    OtherFunc( var2 );
}
</code>```

`
And then compile it with this: arm-none-linux-gnueabi-g++ -c -march=armv7-a -mfloat-abi=softfp -mfpu=neon -O2 -g -o Test.obj Test.cpp

And I check the disassembly: arm-none-linux-gnueabi-objdump -d -C Test.obj > Test.asm

I have added some note on disassembly code, the wrong codes are generated on address 58 and 5c.
`

```<code>
Test.obj:     file format elf32-littlearm

Disassembly of section .text:

00000000 <Test()>:
   0:   e92d41f0    push    {r4, r5, r6, r7, r8, lr}
   4:   e24dde11    sub sp, sp, #272    ; sp = &var2
   8:   e28d8088    add r8, sp, #136    ; r8 = &var1
   c:   e3a06001    mov r6, #1  ; 0x1
  10:   e3a07000    mov r7, #0  ; 0x0
  14:   e1a00008    mov r0, r8  ; r0 = &var1
  18:   ebfffffe    bl  0 <TestStruct::TestStruct()>    ; construct var1
  1c:   e1cd28d8    ldrd    r2, [sp, #136]  ; load m_mask to r2, r3
  20:   e1a00008    mov r0, r8              ; r0 = &var1
  24:   e1835007    orr r5, r3, r7          ; calc m_mask high 4bytes in r5
  28:   e1824006    orr r4, r2, r6          ; calc m_mask low 4bytes in r4
  2c:   e3003000    movw    r3, #0          ; low 2bytes for 100.0f
  30:   e1cd48f8    strd    r4, [sp, #136]  ; r4,r5 store to var1.m_mask ()
  34:   e34432c8    movt    r3, #17096      ; 0x42c8 , high 2bytes for 100.0f
  38:   e58d3090    str r3, [sp, #144]      ; store 100.0f to var1.m_fValue
  3c:   ebfffffe    bl  0 <OtherFunc(TestStruct const&)>
  40:   e1a0000d    mov r0, sp              ; r0 = &var2, sp = &var2
  44:   ebfffffe    bl  0 <TestStruct::TestStruct()>    ; construct var2
  48:   e1cd20d0    ldrd    r2, [sp]        ; load m_mask to r2, r3
  4c:   e28d0e11    add r0, sp, #272        ; r0 = &var2 + 272
  50:   e1835007    orr r5, r3, r7          ; calc m_mask high 4bytes in r5
  54:   e1824006    orr r4, r2, r6          ; calc m_mask low 4bytes in r4
  58:   e5304110    ldr r4, [r0, #-272]!    ; !!! error : ldr should be str , r4 store to var2.m_mask low 4bytes
  5c:   e5905004    ldr r5, [r0, #4]        ; !!! error : ldr should be str , r5 store to var2.m_mask high 4bytes
  60:   e1a0000d    mov r0, sp              ; r0 = &var2
  64:   e3003000    movw    r3, #0          ; low 2bytes for 100.0f
  68:   e34432c8    movt    r3, #17096      ; 0x42c8 , high 2bytes for 100.0f
  6c:   e58d3008    str r3, [sp, #8]        ; store 100.0f to var2.m_fValue
  70:   ebfffffe    bl  0 <OtherFunc(TestStruct const&)>
  74:   e1a0000d    mov r0, sp
  78:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  7c:   e1a00008    mov r0, r8
  80:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  84:   e28dde11    add sp, sp, #272    ; 0x110
  88:   e8bd81f0    pop {r4, r5, r6, r7, r8, pc}
  8c:   e1a04000    mov r4, r0
  90:   e1a00008    mov r0, r8
  94:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  98:   e1a00004    mov r0, r4
  9c:   ebfffffe    bl  0 <__cxa_end_cleanup>
  a0:   e1a04000    mov r4, r0
  a4:   e1a0000d    mov r0, sp
  a8:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  ac:   eafffff7    b   90 <TestStruct::~TestStruct()+0x90>
</code>```

`
But when I change -O2 to -O1, the issue is gone.
When I remove one of "-march=armv7-a -mfloat-abi=softfp -mfpu=neon", and still compile with -O2, the issue is gone too.
I have on idea why this would happen, could someone help me out? Thanks so much!

Body:
I am maintaining an project which build with gcc-4.3.3 and I find something strange. The compiler will generate wrong code when I use specified compile option.
Here is my test code which on a file named test.cpp, var1.m_mask will be set correctly but the var2.m_mask is not set correctly, still keeping default value.
`

struct TestStruct
{
public:
    TestStruct(void);
    ~TestStruct(void);
    inline void SetFloatValue(float value)
    {
        m_fValue = value;
        m_mask |= 1;
    }
private:
    unsigned long long  m_mask;     //8 bytes
    float               m_fValue;   //4 byts
    char reserved[128 - 8 - 4 + 1]; //If sizeof(reserved) <= 116, it is ok
};
extern void OtherFunc(  const TestStruct &st );
void Test()
{
    //First variable
    TestStruct var1;
    //set var1.m_mask and var1.m_fValue
    var1.SetFloatValue( 100.0f );
    //call some function in case that var1 would be optimized
    OtherFunc( var1 );

    //Second variable
    TestStruct var2;
    //Set var2.m_fValue and var2.m_mask !!!
    var2.SetFloatValue( 100.0f );
    //call some function in case that var2 would be optimized
    OtherFunc( var2 );
}

`
And then compile it with this: arm-none-linux-gnueabi-g++ -c -march=armv7-a -mfloat-abi=softfp -mfpu=neon -O2 -g -o Test.obj Test.cpp

And I check the disassembly: arm-none-linux-gnueabi-objdump -d -C Test.obj > Test.asm

I have added some note on disassembly code, the wrong codes are generated on address 58 and 5c.
`

Test.obj:     file format elf32-littlearm

Disassembly of section .text:

00000000 <Test()>:
   0:   e92d41f0    push    {r4, r5, r6, r7, r8, lr}
   4:   e24dde11    sub sp, sp, #272    ; sp = &var2
   8:   e28d8088    add r8, sp, #136    ; r8 = &var1
   c:   e3a06001    mov r6, #1  ; 0x1
  10:   e3a07000    mov r7, #0  ; 0x0
  14:   e1a00008    mov r0, r8  ; r0 = &var1
  18:   ebfffffe    bl  0 <TestStruct::TestStruct()>    ; construct var1
  1c:   e1cd28d8    ldrd    r2, [sp, #136]  ; load m_mask to r2, r3
  20:   e1a00008    mov r0, r8              ; r0 = &var1
  24:   e1835007    orr r5, r3, r7          ; calc m_mask high 4bytes in r5
  28:   e1824006    orr r4, r2, r6          ; calc m_mask low 4bytes in r4
  2c:   e3003000    movw    r3, #0          ; low 2bytes for 100.0f
  30:   e1cd48f8    strd    r4, [sp, #136]  ; r4,r5 store to var1.m_mask ()
  34:   e34432c8    movt    r3, #17096      ; 0x42c8 , high 2bytes for 100.0f
  38:   e58d3090    str r3, [sp, #144]      ; store 100.0f to var1.m_fValue
  3c:   ebfffffe    bl  0 <OtherFunc(TestStruct const&)>
  40:   e1a0000d    mov r0, sp              ; r0 = &var2, sp = &var2
  44:   ebfffffe    bl  0 <TestStruct::TestStruct()>    ; construct var2
  48:   e1cd20d0    ldrd    r2, [sp]        ; load m_mask to r2, r3
  4c:   e28d0e11    add r0, sp, #272        ; r0 = &var2 + 272
  50:   e1835007    orr r5, r3, r7          ; calc m_mask high 4bytes in r5
  54:   e1824006    orr r4, r2, r6          ; calc m_mask low 4bytes in r4
  58:   e5304110    ldr r4, [r0, #-272]!    ; !!! error : ldr should be str , r4 store to var2.m_mask low 4bytes
  5c:   e5905004    ldr r5, [r0, #4]        ; !!! error : ldr should be str , r5 store to var2.m_mask high 4bytes
  60:   e1a0000d    mov r0, sp              ; r0 = &var2
  64:   e3003000    movw    r3, #0          ; low 2bytes for 100.0f
  68:   e34432c8    movt    r3, #17096      ; 0x42c8 , high 2bytes for 100.0f
  6c:   e58d3008    str r3, [sp, #8]        ; store 100.0f to var2.m_fValue
  70:   ebfffffe    bl  0 <OtherFunc(TestStruct const&)>
  74:   e1a0000d    mov r0, sp
  78:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  7c:   e1a00008    mov r0, r8
  80:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  84:   e28dde11    add sp, sp, #272    ; 0x110
  88:   e8bd81f0    pop {r4, r5, r6, r7, r8, pc}
  8c:   e1a04000    mov r4, r0
  90:   e1a00008    mov r0, r8
  94:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  98:   e1a00004    mov r0, r4
  9c:   ebfffffe    bl  0 <__cxa_end_cleanup>
  a0:   e1a04000    mov r4, r0
  a4:   e1a0000d    mov r0, sp
  a8:   ebfffffe    bl  0 <TestStruct::~TestStruct()>
  ac:   eafffff7    b   90 <TestStruct::~TestStruct()+0x90>

`
But when I change -O2 to -O1, the issue is gone.
When I remove one of "-march=armv7-a -mfloat-abi=softfp -mfpu=neon", and still compile with -O2, the issue is gone too.
I have on idea why this would happen, could someone help me out? Thanks so much!


问:
CSS Not Linking Up To Pug File
I'm creating a website using NodeJS, Express, and Pug, but when attempting to link a CSS file to a Pug File it returns this error in the developer tools console:

```<code>The resource from “https://you-gotta-know-these-attempt-at-a-flash-card-generator.emiiy.repl.co/style.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).you-gotta-know-these-attempt-at-a-flash-card-generator.emiiy.repl.co.
</code>```

Along with this error, the CSS file formats have nothing specified in the pug file.

I tried to link the before-mentioned Pug file to a CSS file (style.css), using link(rel='stylesheet', href='style.css', type='text/css')`. This is correct formatting from what I know, let me know if it isn't. As previously mentioned, the CSS code will not format any of the elements inside of the Pug file, and from what I've gotten from the error the 2 files don't even get linked up.

Pug File

```<code>doctype html
html
  head
    title :(
    link(rel='stylesheet', href='style.css', type='text/css')
  body
    div.center
      h1 This should be centered but it isn't, why?
</code>```

CSS File

```<code>.center {
  margin: 0 auto;
  text-align: center;
  font-family: "Lucida Console", monospace;
}
</code>```

For further info, here's the online repl - https://replit.com/@EmiIy/You-Gotta-Know-These-Attempt-At-A-Flash-Card-Generator

Title: CSS Not Linking Up To Pug File

Body:
I'm creating a website using NodeJS, Express, and Pug, but when attempting to link a CSS file to a Pug File it returns this error in the developer tools console:

The resource from “https://you-gotta-know-these-attempt-at-a-flash-card-generator.emiiy.repl.co/style.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).you-gotta-know-these-attempt-at-a-flash-card-generator.emiiy.repl.co.

Along with this error, the CSS file formats have nothing specified in the pug file.

I tried to link the before-mentioned Pug file to a CSS file (style.css), using link(rel='stylesheet', href='style.css', type='text/css')`. This is correct formatting from what I know, let me know if it isn't. As previously mentioned, the CSS code will not format any of the elements inside of the Pug file, and from what I've gotten from the error the 2 files don't even get linked up.

Pug File

doctype html
html
  head
    title :(
    link(rel='stylesheet', href='style.css', type='text/css')
  body
    div.center
      h1 This should be centered but it isn't, why?

CSS File

.center {
  margin: 0 auto;
  text-align: center;
  font-family: "Lucida Console", monospace;
}

For further info, here's the online repl - https://replit.com/@EmiIy/You-Gotta-Know-These-Attempt-At-A-Flash-Card-Generator


问:
What GeckoView build should you use on Android?
I am currently browsing the Mozilla maven GeckoView directory for Android.

I have to admit, I am quite overwhelmed by the sheer variety of what I can choose from.

```<code>geckoview-exoplayer2-beta/
geckoview-exoplayer2-nightly/
geckoview-exoplayer2/
geckoview-nightly-arm64-v8a/
geckoview-nightly-armeabi-v7a/
geckoview-nightly-omni-arm64-v8a/
geckoview-nightly-omni-armeabi-v7a/
geckoview-nightly-omni-x86/
geckoview-nightly-omni-x86_64/
geckoview-nightly-omni/
geckoview-nightly-x86/
geckoview-nightly-x86_64/
geckoview-nightly/
geckoview-omni-arm64-v8a/
geckoview-omni-armeabi-v7a/
geckoview-omni-x86/
geckoview-omni-x86_64/
geckoview-omni/
geckoview-x86/
geckoview-x86_64/
geckoview/
...
</code>```

Does anyone have any insight into what the differences are between all these builds?

Without any documentation, I am unsure which one an Android app should be using?

Body:
I am currently browsing the Mozilla maven GeckoView directory for Android.

I have to admit, I am quite overwhelmed by the sheer variety of what I can choose from.

geckoview-exoplayer2-beta/
geckoview-exoplayer2-nightly/
geckoview-exoplayer2/
geckoview-nightly-arm64-v8a/
geckoview-nightly-armeabi-v7a/
geckoview-nightly-omni-arm64-v8a/
geckoview-nightly-omni-armeabi-v7a/
geckoview-nightly-omni-x86/
geckoview-nightly-omni-x86_64/
geckoview-nightly-omni/
geckoview-nightly-x86/
geckoview-nightly-x86_64/
geckoview-nightly/
geckoview-omni-arm64-v8a/
geckoview-omni-armeabi-v7a/
geckoview-omni-x86/
geckoview-omni-x86_64/
geckoview-omni/
geckoview-x86/
geckoview-x86_64/
geckoview/
...

Does anyone have any insight into what the differences are between all these builds?

Without any documentation, I am unsure which one an Android app should be using?


问:
Why does not isinstance() accept a set of types?
It really bugs me why wouldn't isinstance(value, type_or_types) accept a set() of types if it accepts tuple.

Basically why:

```<code>isinstance(1.23, (int, float, complex))
</code>```

is valid, but:

isinstance(1.23, {int, float, complex})

is not?.

I've noticed that for the latter case, up to Python 3.9 it throws the error:

```<code>TypeError: isinstance() arg 2 must be a type or tuple of types
</code>```

while from 3.10 the error has changed to:

```<code>TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
</code>```

After I saw union I felt something might have changed in the newer versions, but I don't get what. What is a union? I only know the method set.union() which in turn returns another set, so I'm basically stuck without being able to use it.

EDIT:
I suspect the reason is the mutability?

Body:
It really bugs me why wouldn't isinstance(value, type_or_types) accept a set() of types if it accepts tuple.

Basically why:

isinstance(1.23, (int, float, complex))

is valid, but:

isinstance(1.23, {int, float, complex})

is not?.

I've noticed that for the latter case, up to Python 3.9 it throws the error:

TypeError: isinstance() arg 2 must be a type or tuple of types

while from 3.10 the error has changed to:

TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union

After I saw union I felt something might have changed in the newer versions, but I don't get what. What is a union? I only know the method set.union() which in turn returns another set, so I'm basically stuck without being able to use it.

EDIT:
I suspect the reason is the mutability?


问:
Error on Stat command with condition statements << directory not found
I am trying to use the stat command to check if a permission is correct on a directory and if not then change that permission on that file. I have done this multiple times but I keep getting "stat:cannot statx '/usr/share/nginx': No such file or directory found. But the directory is there I checked multiple times</p>
```<code>#!/bin/bash

test_host=(host)

path=/usr/share/nginx

for my_hosts in "${test_host}"
do

    ssh -q -o "StrictHostKeyChecking no" root@${my_hosts} <<EOF
        if [ ! $(stat -c "%a" "$path") == "664" ]
        then

            chmod -R 664 ${path}

        else

            echo "permissions were already changed"

        fi

EOF
done
</code>```

Body:
I am trying to use the stat command to check if a permission is correct on a directory and if not then change that permission on that file. I have done this multiple times but I keep getting "stat:cannot statx '/usr/share/nginx': No such file or directory found. But the directory is there I checked multiple times

#!/bin/bash

test_host=(host)

path=/usr/share/nginx

for my_hosts in "${test_host}"
do

    ssh -q -o "StrictHostKeyChecking no" root@${my_hosts} <<EOF
        if [ ! $(stat -c "%a" "$path") == "664" ]
        then

            chmod -R 664 ${path}

        else

            echo "permissions were already changed"

        fi

EOF
done


问:
GTM: Custom HTML tag not fired when all trigger filters are met and trigger fires the Google Analytics tag
I've got 2 tags in Google Tag Manager using the same trigger - page view.

Google Analytics tag and it fires when triggered.

Custom HTML tag which does not fire with the same trigger

Has anyone seen this issue before?

I've attached images showing the same trigger is set for both tags and that the trigger fires the Google Analytics tag but not the Custom HTML tag

I'm trying to get a HubSpot Tracking Code to run in a SPA for tracking page views

Shows 1 tag firing but not the
other

Shows the trigger
filters being met but confirming tag not
firing

Confirming the trigger
filters being met and tag firing

There are no error codes that I can see - if there is a way to find some, please let me know

I was expecting the custom html tag to fire as well