问:
How to adjust fill color in ggplot bubble graph
I am plotting a bubble graph in ggplot and looking to change the fill color of the bubbles. How can I do this. I will add the code for the two ways in which I am plotting the same bubble chart. If anyone knows how to change the fill color for either of the ways, that would be appreciated.

```<code>options(repr.plot.width=15, repr.plot.height=15)
ggplot(final_melted, aes(x=PC, y=trunc_path, size=pval, color=enrichment)) +
geom_point(alpha=0.5)

ggplot(final_melted, aes(x=PC, y=trunc_path))+
geom_point(aes(size=pval, fill = enrichment), shape=21)
</code>```

I am trying to change the enrichment fill color to 'Spectral'

see above code please

Body:
I am plotting a bubble graph in ggplot and looking to change the fill color of the bubbles. How can I do this. I will add the code for the two ways in which I am plotting the same bubble chart. If anyone knows how to change the fill color for either of the ways, that would be appreciated.

options(repr.plot.width=15, repr.plot.height=15)
ggplot(final_melted, aes(x=PC, y=trunc_path, size=pval, color=enrichment)) +
geom_point(alpha=0.5)

ggplot(final_melted, aes(x=PC, y=trunc_path))+
geom_point(aes(size=pval, fill = enrichment), shape=21)

I am trying to change the enrichment fill color to 'Spectral'

see above code please


来源: stackexchange

问:
Why can't put from stdin in memory assembler
I'm trying to edit some code.

I found a code in YT video, that printing "Hello World!" and it worked fine.

Then I decided to change it to modify the string from console, first fifth chars of it.
I found that "read" is 0x3 (eax) and stdin is 0 (ebx).
I added ;from ;to

```<code>global _start

section .text:

_start:

    ; from
    mov eax, 0x3
    mov ebx, 0
    mov ecx, message
    mov edx, 5
    int 0x80
    ; to

    mov eax, 0x4
    mov ebx, 1
    mov ecx, message
    mov edx, message_length
    int 0x80

    mov eax, 0x1
    mov ebx, 0
    int 0x80

section .data:
    message: db "Hello World!", 0xA
    message_length equ $-message
</code>```

nasm -f elf32 -o app.o app.asm
ld -m elf_i386 -o app app.o
./app

There is reading from console, but the string isn't modifying, why?
And moreover than it, if I write more than 5 chars "qwertyui" - "yui" somehow... put in next command of console, after my app is closed!

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to edit some code.

I found a code in YT video, that printing "Hello World!" and it worked fine.

Then I decided to change it to modify the string from console, first fifth chars of it.
I found that "read" is 0x3 (eax) and stdin is 0 (ebx).
I added ;from ;to

global _start

section .text:

_start:

    ; from
    mov eax, 0x3
    mov ebx, 0
    mov ecx, message
    mov edx, 5
    int 0x80
    ; to

    mov eax, 0x4
    mov ebx, 1
    mov ecx, message
    mov edx, message_length
    int 0x80

    mov eax, 0x1
    mov ebx, 0
    int 0x80

section .data:
    message: db "Hello World!", 0xA
    message_length equ $-message

nasm -f elf32 -o app.o app.asm
ld -m elf_i386 -o app app.o
./app

There is reading from console, but the string isn't modifying, why?
And moreover than it, if I write more than 5 chars "qwertyui" - "yui" somehow... put in next command of console, after my app is closed!


问:
After importing opencv-python , the corresponding functions don't work
I'm new to learning on opencv-python.
So I started by creating a new python project named OpenCV and then imported opencv-python package and then started typing in my code in a new Python file. But once I try running the file I keep getting error.

Code And Error img

It seems as if imread() and imshow() - none are accepted.
I tried importing imread() separately by using cmd and my terminal but nothing seems to works.
It further shows legacy error.

```<code>import cv2
img = cv2.imread('lena.jpg', 1)
print(img)
cv2.imshow('image', img)
cv2.waitKey(10000)

cv2.destroyAllWindows()
</code>```

My error:
Traceback (most recent call last):
File "/Users/mac/myprojects/opencv/read_and_display_image.py", line 1, in
import cv2

File "/Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/init.py", line 181, in
bootstrap()

File "/Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/init.py", line 153, in bootstrap
native_module = importlib.import_module("cv2")

File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)

ImportError: dlopen(/Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/cv2.abi3.so, 2): Symbol not found: _VTRegisterSupplementalVideoDecoderIfAvailable

Referenced from: /Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/.dylibs/libavcodec.59.37.100.dylib

Expected in: /System/Library/Frameworks/VideoToolbox.framework/Versions/A/VideoToolbox
in /Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/.dylibs/libavcodec.59.37.100.dylib

Body:
I'm new to learning on opencv-python.
So I started by creating a new python project named OpenCV and then imported opencv-python package and then started typing in my code in a new Python file. But once I try running the file I keep getting error.

Code And Error img

It seems as if imread() and imshow() - none are accepted.
I tried importing imread() separately by using cmd and my terminal but nothing seems to works.
It further shows legacy error.

import cv2
img = cv2.imread('lena.jpg', 1)
print(img)
cv2.imshow('image', img)
cv2.waitKey(10000)

cv2.destroyAllWindows()

My error:
Traceback (most recent call last):
File "/Users/mac/myprojects/opencv/read_and_display_image.py", line 1, in
import cv2

File "/Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/init.py", line 181, in
bootstrap()

File "/Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/init.py", line 153, in bootstrap
native_module = importlib.import_module("cv2")

File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)

ImportError: dlopen(/Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/cv2.abi3.so, 2): Symbol not found: _VTRegisterSupplementalVideoDecoderIfAvailable

Referenced from: /Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/.dylibs/libavcodec.59.37.100.dylib

Expected in: /System/Library/Frameworks/VideoToolbox.framework/Versions/A/VideoToolbox
in /Users/mac/myprojects/opencv/openenv/lib/python3.9/site-packages/cv2/.dylibs/libavcodec.59.37.100.dylib


问:
Linker does not recognize format of compiled Rust file
I am writing an OS kernel in Rust, and have reached the stage of linking said kernel to a bootloader written in Assembly. The kernel (kernel.rs) compiles fine to kernel.o using rustc with the x86_64-unknown-none target.

The problem arises when I try to link this kernel to my bootloader. I attempt to link kernel.o to kernel_enter.o (compiled from a .asm file) with the ld linker:

```<code>ld -o "full_kernel.bin" -Ttext 0x1000 "kernel_enter.o" "kernel.o" --oformat binary
</code>```

and received the the following error:

```<code>ld: kernel.o: error adding symbols: file in wrong format
</code>```

I have tried to build with x86_64-unknown-uefi, and with i686-unknown-uefi and the i386-elf-ld linker.

I have also read of the possibility of writing custom targets with JSON. Knowing how to do that would probably solve my problem.

Thanks.

Body:
I am writing an OS kernel in Rust, and have reached the stage of linking said kernel to a bootloader written in Assembly. The kernel (kernel.rs) compiles fine to kernel.o using rustc with the x86_64-unknown-none target.

The problem arises when I try to link this kernel to my bootloader. I attempt to link kernel.o to kernel_enter.o (compiled from a .asm file) with the ld linker:

ld -o "full_kernel.bin" -Ttext 0x1000 "kernel_enter.o" "kernel.o" --oformat binary

and received the the following error:

ld: kernel.o: error adding symbols: file in wrong format

I have tried to build with x86_64-unknown-uefi, and with i686-unknown-uefi and the i386-elf-ld linker.

I have also read of the possibility of writing custom targets with JSON. Knowing how to do that would probably solve my problem.

Thanks.


问:
Update editable DataTable Output in RShiny
I am new to the world of RShiny and i think reactivity is bit complex to understand. I am trying to make a datatable output based on row and column condition given as per user selectinput dropdown buttons. My DataTable is editable and i want to store the updated table after user edited the cells of the datatable in a new variable but i am stuck.

I tried couple of chunks suggested on stackoverflow but none of them worked for me mostly using proxytable or reactivity. I want to store the datatable after i hit proceed button. Any help would be much appreciated.

Here is my code:

```<code>library(shiny)
library(shinyWidgets)
library(shinythemes)
library(DT)
library(data.table)

#ui
shinyApp(
  ui = fluidPage(
    theme = shinythemes::shinytheme("flatly"),
    titlePanel("Trial"),
    sidebarLayout(
      shiny::sidebarPanel(
        #to take multiple user input
        shiny::textAreaInput(
          "text_input",
          label = "Write input"
        ),
        #to slect the columns to be added
        shinyWidgets::pickerInput(
          inputId = "somevalue",
          label = "Columns to add",
          choices = colnames(df),
          options = list(`actions-box` = TRUE),
          multiple = TRUE
        ),
        #action button tot show the table
        shinyWidgets::actionBttn(
          "show_table",
          label = "Show",
          size =  "sm",
          color = "default",
          block = TRUE
        ), width = 2
      ),
      mainPanel(
        shiny::tabsetPanel(type = "tabs",
                           shiny::tabPanel("Table", DT::dataTableOutput("table")),
                                    actionBttn("proceed","proceed")

        ),width = 10
      )
    )
  ),
  server = function(input, output,session) {
    #to add reactivity to the show button

    df_filter <- reactive({
      text_input <- trimws(strsplit(input$text_input, ",")[[1]])
      df_filter <- df[df$make %chin% text_input, input$somevalue]

    })%>% shiny::bindEvent(input$show_table)

    #to output hte dt table with the filters
    output$table <- DT::renderDT({
      DT::datatable(df_filter(),
                    editable = 'cell',
                    options = list(scrollX = TRUE , lengthChange = FALSE, autoWidth = TRUE)
                    # editable = list(target = "row", disable = list(columns = c(2, 4, 5))))
      )
    })%>% shiny::bindEvent(df_filter())
  }
)
</code>```

Body:
I am new to the world of RShiny and i think reactivity is bit complex to understand. I am trying to make a datatable output based on row and column condition given as per user selectinput dropdown buttons. My DataTable is editable and i want to store the updated table after user edited the cells of the datatable in a new variable but i am stuck.

I tried couple of chunks suggested on stackoverflow but none of them worked for me mostly using proxytable or reactivity. I want to store the datatable after i hit proceed button. Any help would be much appreciated.

Here is my code:

library(shiny)
library(shinyWidgets)
library(shinythemes)
library(DT)
library(data.table)

#ui
shinyApp(
  ui = fluidPage(
    theme = shinythemes::shinytheme("flatly"),
    titlePanel("Trial"),
    sidebarLayout(
      shiny::sidebarPanel(
        #to take multiple user input
        shiny::textAreaInput(
          "text_input",
          label = "Write input"
        ),
        #to slect the columns to be added
        shinyWidgets::pickerInput(
          inputId = "somevalue",
          label = "Columns to add",
          choices = colnames(df),
          options = list(`actions-box` = TRUE),
          multiple = TRUE
        ),
        #action button tot show the table
        shinyWidgets::actionBttn(
          "show_table",
          label = "Show",
          size =  "sm",
          color = "default",
          block = TRUE
        ), width = 2
      ),
      mainPanel(
        shiny::tabsetPanel(type = "tabs",
                           shiny::tabPanel("Table", DT::dataTableOutput("table")),
                                    actionBttn("proceed","proceed")

        ),width = 10
      )
    )
  ),
  server = function(input, output,session) {
    #to add reactivity to the show button

    df_filter <- reactive({
      text_input <- trimws(strsplit(input$text_input, ",")[[1]])
      df_filter <- df[df$make %chin% text_input, input$somevalue]

    })%>% shiny::bindEvent(input$show_table)

    #to output hte dt table with the filters
    output$table <- DT::renderDT({
      DT::datatable(df_filter(),
                    editable = 'cell',
                    options = list(scrollX = TRUE , lengthChange = FALSE, autoWidth = TRUE)
                    # editable = list(target = "row", disable = list(columns = c(2, 4, 5))))
      )
    })%>% shiny::bindEvent(df_filter())
  }
)


问:
Swagger and Redoc static Documentation For Django Rest API
I am looking to use Swagger and Redoc documentation in my RestApi Pet Project. I don't want it to be dynamic. I know, that I can use Swagger Editor to create my OpenApi Schema. But how to implement that schema to my project?

For example I have a full completed .yml OpenApi Schema. What should I do to implement it to my endpoint 'docs' or 'redoc'?

I am using SPA with drf and react in my project.

Example of project structure:

```<code>Project_name
|api
||serializers.py
||views.py
||urls.py
|project_name
||asgi.py
||settings.py
||urls.py
|manage.py
|openapi-schema.yml
</code>```

Body:
I am looking to use Swagger and Redoc documentation in my RestApi Pet Project. I don't want it to be dynamic. I know, that I can use Swagger Editor to create my OpenApi Schema. But how to implement that schema to my project?

For example I have a full completed .yml OpenApi Schema. What should I do to implement it to my endpoint 'docs' or 'redoc'?

I am using SPA with drf and react in my project.

Example of project structure:

Project_name
|api
||serializers.py
||views.py
||urls.py
|project_name
||asgi.py
||settings.py
||urls.py
|manage.py
|openapi-schema.yml


问:
How to use winston to send logs to my frontend using socket.io
Cannot figure out how to get the winston logs and send that data to my frontend using socket.io

I looks like someone was able to send logs using winston.transport.WebHook but Winston 2.0 removed the Webhook method: Nodejs Winston Emit to socket

Someone recommended to http transport but cant figure out how to use it


问:
Reactive user base data in the shinyauthr package
I have developed a shiny app. Once subscribed to the website, you must authenticate yourself to access the information. When the subscription is made, the username and password are stored in a data frame called user_base that has two columns: user and password. The user makes the subscription and authentication, but cannot access the information without reloading the web page, since when the app is executed the user_base file is loaded and then it is not updated. One way to get this file updated automatically would be to use the reactiveFileReader function, but I don't know how I could use this function in the authentication module.

My code is the following:

```<code>ui <- fluidPage(
 div(class = "login-ui",
         shinyauthr::loginUI(id = "login",
            title = tags$div(HTML("<p style='color:#B2BABB; font-size: 14px';>   Log in </p>")),
            user_title = "User",
            pass_title = "Password",
            login_title = "Log in"
                                                                            )),

div(class = "pull-right",
shinyauthr::logoutUI(id = "logout",
                     label = "Log out",
                     icon = NULL))
 )

server <- function(input, output, session) {

  user_baseR=reactiveFileReader(1000, NULL, filePath="~/data/user_base.RData", readFunc = load, envir = .GlobalEnv)
  user_baseR()

 credentials <- shinyauthr::loginServer(
    id = "login",
    data = user_base,
    user_col = user,
    pwd_col = password,
    log_out = reactive(logout_init())
  )

  logout_init <- shinyauthr::logoutServer(
    id = "logout",
    active = reactive(credentials()$user_auth)
  )
}
</code>```

The code works and the user can log in if the app is reloaded, but when I add the first two lines on the server an error is thrown as this is not the correct use of the reactiveFileReader function. I would appreciate a solution to the problem raised above

Body:
I have developed a shiny app. Once subscribed to the website, you must authenticate yourself to access the information. When the subscription is made, the username and password are stored in a data frame called user_base that has two columns: user and password. The user makes the subscription and authentication, but cannot access the information without reloading the web page, since when the app is executed the user_base file is loaded and then it is not updated. One way to get this file updated automatically would be to use the reactiveFileReader function, but I don't know how I could use this function in the authentication module.

My code is the following:

ui <- fluidPage(
 div(class = "login-ui",
         shinyauthr::loginUI(id = "login",
            title = tags$div(HTML("
   Log in
")),
            user_title = "User",
            pass_title = "Password",
            login_title = "Log in"
                                                                            )),

div(class = "pull-right",
shinyauthr::logoutUI(id = "logout",
                     label = "Log out",
                     icon = NULL))
 )

server <- function(input, output, session) {

  user_baseR=reactiveFileReader(1000, NULL, filePath="~/data/user_base.RData", readFunc = load, envir = .GlobalEnv)
  user_baseR()

 credentials <- shinyauthr::loginServer(
    id = "login",
    data = user_base,
    user_col = user,
    pwd_col = password,
    log_out = reactive(logout_init())
  )

  logout_init <- shinyauthr::logoutServer(
    id = "logout",
    active = reactive(credentials()$user_auth)
  )
}

The code works and the user can log in if the app is reloaded, but when I add the first two lines on the server an error is thrown as this is not the correct use of the reactiveFileReader function. I would appreciate a solution to the problem raised above


问:
Android TelecomFramework createConnectionFailed TC@47: (TSI.aNIC)->CS.crCoF->H.CS.crCoF@E-AZs
I'm debugging a voip call application for Android. It users Android Telecom framework & self-managed phone accounts. The incoming calls fail sometimes with a cryptic message:

TelecomFramework createConnectionFailed TC@47: (TSI.aNIC)->CS.crCoF->H.CS.crCoF@E-AZs

I deciphered some of it, but still having trouble with parts of the message.

TSI.aNIC is TelecomServiceImpl.addNewIncomingCall

CS.crCof is ConnectionService.createConnectionFailed

H. is Handler.

So it looks like a poor man's stacktrace. I still can't figure out TC@47 and E-AZs (E- is EXTERNAL_INDICATOR, but that does not tell much).

But what I really need is the actual reason why the connection is failing. Any suggestions?

P.S. I figured out TC@47: TeleCom, @47 is just a sequence number to identify an interaction. And instead of AZs it's sometimes ARs.

P.P.S: It seems like ARs etc, is also some sort of transient identifier, it changes all the time. Thus the cryptic message contains no explanation for the failure.


问:
Replacement for Microsoft.Practices.EnterpriseLibrary.Validation in .Net 6
I'm converting an old application from .Net 4x to .Net 6, and I can't seem to find a replacement for Microsoft.Practices.EnterpriseLibrary.Validation.  In newer code we've used System.ComponentModel.DataAnnotations for similar functionality, but it looks like a lot of the attributes have different names.  Has anyone come across a fix?</p>


问:
The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant
I get this error: The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.
Previous: []
Incoming: [iCWh9p5f36aKGfwzjbplzXtLvFC2]

To prevent it, I first check if userUID not equal to [] and only then I output useEffect, but I still get the same error

```<code> if(auth.currentUser != null){

    let userUID = (auth.currentUser.uid)

        if(userUID.length > 0){
          console.log(userUID.length)

          useEffect(() => {

                  const q = query(collection(db, "customers", userUID, "subscriptions"));

                  onSnapshot(q, (querySnapshot) => {
                      querySnapshot.forEach(async (subscription) => {
                            setSubscription({
                                role: subscription.data().role,
                                current_period_start:
                          subscription.data().current_period_start.seconds,
                        current_period_end: subscription.data().current_period_end.seconds,
                      });
                    });
                  });
                }, [userUID]) //if I'll put logic inside then this userUID will crash the site because it is equal to null first few secs

        }
    }
</code>```

If I need to put if statement inside useEffect => is it possible to export "let" from an if statement?

Something like this:

```<code> if(auth.currentUser != null){

    let userUID = (auth.currentUser.uid);

    export default userUID;
}

useEffect(() => {
                  const q = query(collection(db, "customers", userUID, "subscriptions"))
                  ...
}, [userUID]);
</code>```

Body:
I get this error: The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.
Previous: []
Incoming: [iCWh9p5f36aKGfwzjbplzXtLvFC2]

To prevent it, I first check if userUID not equal to [] and only then I output useEffect, but I still get the same error

 if(auth.currentUser != null){

    let userUID = (auth.currentUser.uid)

        if(userUID.length > 0){
          console.log(userUID.length)

          useEffect(() => {

                  const q = query(collection(db, "customers", userUID, "subscriptions"));

                  onSnapshot(q, (querySnapshot) => {
                      querySnapshot.forEach(async (subscription) => {
                            setSubscription({
                                role: subscription.data().role,
                                current_period_start:
                          subscription.data().current_period_start.seconds,
                        current_period_end: subscription.data().current_period_end.seconds,
                      });
                    });
                  });
                }, [userUID]) //if I'll put logic inside then this userUID will crash the site because it is equal to null first few secs

        }
    }

If I need to put if statement inside useEffect => is it possible to export "let" from an if statement?

Something like this:

 if(auth.currentUser != null){

    let userUID = (auth.currentUser.uid);

    export default userUID;
}

useEffect(() => {
                  const q = query(collection(db, "customers", userUID, "subscriptions"))
                  ...
}, [userUID]);


问:
How to approximate low-res 3D density map to smooth models?
3D Density maps of course can be plotted as heatmap, but when data itself is homogeneous (near 0) except for a small part (2D cross section for example):

This should give a letter 'E' shape as 2D "model". The original data is not saved as point-cloud however.

A naive approach would be to use the pixels that are more than a certain value, and then smooth the border. However this does not take into account of the border pixels being small.

Another would be to use some point-cloud based algorithms that come with modeling softwares, but then the point-cloud's probability function would still be discontinuous on pixel border, and not taking into account that only one side have signal.

Is there any tested solution to this (the example is 2D, the actual case is many 2D slices that compose a low-res 3D density map)? I was thinking of making border pixels have area proportional to signal data, and border should be defined from gradient? Any suggestions?

I was thinking of model visualization results similar to this (seems to be based on established point-cloud algorithm):


问:
How to combine a single rjags model object of 6 elements into a LargeList of rjags model objects from MixSIAR
Ive been running MixSIAR package which has a loop command that you define multiple models before running a for loop over which calls rjags to run on each model.

```<code>   n.mod <- 8
 mix <- vector("list", n.mod)
    mix[[1]] <- load_mix_data(filename=mix.filename, iso_names=c("d13C","d15N"),
                         factors=NULL, fac_random=NULL, fac_nested=NULL,  cont_effects=NULL)
    mix[[2]] <- load_mix_data(filename=mix.filename, iso_names=c("d13C","d15N"),
                        factors="habitat", fac_random=FALSE, fac_nested=FALSE, cont_effects=NULL)
# Run the models
source <- vector("list", n.mod)
discr <- vector("list", n.mod)
jags.mod <- vector("list", n.mod)
#Loop through models in rjags
for(mod in 1:n.mod){
  # create sub-directory and move into it
  mainDir <- getwd()
  subDir <- paste0("model_", mod)
  dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
  setwd(file.path(mainDir, subDir))

  source[[mod]] <- load_source_data(filename=source.filename, source_factors=NULL,
                             conc_dep=FALSE, data_type="means",  mix[[mod]])
  discr[[mod]] <- load_discr_data(filename=discr.filename, mix[[mod]])

  # Define model structure and write JAGS model file
  model_filename <- paste0("MixSIAR_model_", mod, ".txt")
  resid_err <- TRUE
  process_err <- TRUE
  write_JAGS_model(model_filename, resid_err, process_err, mix[[mod]], source[[mod]])

  # Run the JAGS model
  jags.mod[[mod]] <- run_model(run="long", mix[[mod]], source[[mod]], discr[[mod]], model_filename, alpha.prior=1, resid_err, process_err)

  # Move back up to root directory
  setwd(mainDir)
}
</code>```

This code is problematic and inefficient in many ways because it has to process through all models before it creates the final list and if the computer crashes while running, I have to start all over again. The final output object is a LargeList. In this example setting n.mod = 8 means  a list of 8 elements, but any 1 model object has 6 elements within it.  If I am fortunate enough to make it through all 8 models, and I want to add additional models I don't know how to combine the information.  I have tried c() and append().  If I run 1 additional model, it will be an rjags object of a list of 6 elements.
When I used c(jags.mod, jags.mod1) it generates a LargeList of 14 elements. It should be a LargeList of 9 elements.

I would rather have it generate and save outside the LargeList each individual rjags model object, AND have it generate this LargeList, or somehow save whatever has been accomplished so if I have to run it again, I can do so without starting all over. It would pick up where it left off, or allow additional models to be added.  I am also wondering if a ForEach would be faster (cleaner in how it uses CPU and RAM) instead of a for loop? But that might be too much to think about at this time.

Body:
Ive been running MixSIAR package which has a loop command that you define multiple models before running a for loop over which calls rjags to run on each model.

   n.mod <- 8
 mix <- vector("list", n.mod)
    mix[[1]] <- load_mix_data(filename=mix.filename, iso_names=c("d13C","d15N"),
                         factors=NULL, fac_random=NULL, fac_nested=NULL,  cont_effects=NULL)
    mix[[2]] <- load_mix_data(filename=mix.filename, iso_names=c("d13C","d15N"),
                        factors="habitat", fac_random=FALSE, fac_nested=FALSE, cont_effects=NULL)
# Run the models
source <- vector("list", n.mod)
discr <- vector("list", n.mod)
jags.mod <- vector("list", n.mod)
#Loop through models in rjags
for(mod in 1:n.mod){
  # create sub-directory and move into it
  mainDir <- getwd()
  subDir <- paste0("model_", mod)
  dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
  setwd(file.path(mainDir, subDir))

  source[[mod]] <- load_source_data(filename=source.filename, source_factors=NULL,
                             conc_dep=FALSE, data_type="means",  mix[[mod]])
  discr[[mod]] <- load_discr_data(filename=discr.filename, mix[[mod]])

  # Define model structure and write JAGS model file
  model_filename <- paste0("MixSIAR_model_", mod, ".txt")
  resid_err <- TRUE
  process_err <- TRUE
  write_JAGS_model(model_filename, resid_err, process_err, mix[[mod]], source[[mod]])

  # Run the JAGS model
  jags.mod[[mod]] <- run_model(run="long", mix[[mod]], source[[mod]], discr[[mod]], model_filename, alpha.prior=1, resid_err, process_err)

  # Move back up to root directory
  setwd(mainDir)
}

This code is problematic and inefficient in many ways because it has to process through all models before it creates the final list and if the computer crashes while running, I have to start all over again. The final output object is a LargeList. In this example setting n.mod = 8 means  a list of 8 elements, but any 1 model object has 6 elements within it.  If I am fortunate enough to make it through all 8 models, and I want to add additional models I don't know how to combine the information.  I have tried c() and append().  If I run 1 additional model, it will be an rjags object of a list of 6 elements.
When I used c(jags.mod, jags.mod1) it generates a LargeList of 14 elements. It should be a LargeList of 9 elements.

I would rather have it generate and save outside the LargeList each individual rjags model object, AND have it generate this LargeList, or somehow save whatever has been accomplished so if I have to run it again, I can do so without starting all over. It would pick up where it left off, or allow additional models to be added.  I am also wondering if a ForEach would be faster (cleaner in how it uses CPU and RAM) instead of a for loop? But that might be too much to think about at this time.


问:
Use jar file inside zip dependency in dependencies block in Gradle script
I have a Gradle build script written in Kotlin where I declare some dependencies (Jars) that I need for some Kotlin classes in my custom Gradle plugin:

```<code>dependencies {
    compileOnly("group:prefix-dependency1:version")
    compileOnly("group:prefix-dependency2:version")
}
</code>```

One jar that I need is not published itself in the Nexus repository that I use but there is a published zip file that contains all jars including the jar that I needed:

```<code>compileOnly("group:prefix:version")
</code>```

The structure of the zip file (group_prefix_version.zip) looks like this:

```<code>...
plugins
...
    needed_plugin.jar
    ...
...
</code>```

Is there a way to extract needed_plugin.jar from the zip dependency so that I can use it as a normal dependency?
Pseudo code:

```<code>compileOnly("group:prefix:version").extract("plugins/needed_plugin.jar")
</code>```

Body:
I have a Gradle build script written in Kotlin where I declare some dependencies (Jars) that I need for some Kotlin classes in my custom Gradle plugin:

dependencies {
    compileOnly("group:prefix-dependency1:version")
    compileOnly("group:prefix-dependency2:version")
}

One jar that I need is not published itself in the Nexus repository that I use but there is a published zip file that contains all jars including the jar that I needed:

compileOnly("group:prefix:version")

The structure of the zip file (group_prefix_version.zip) looks like this:

...
plugins
...
    needed_plugin.jar
    ...
...

Is there a way to extract needed_plugin.jar from the zip dependency so that I can use it as a normal dependency?
Pseudo code:

compileOnly("group:prefix:version").extract("plugins/needed_plugin.jar")


问:
Is the undetected_chromedriver package safe to use?
Is the undetected_chromedriver package safe to use?
Is this a widely used and trusted package that you would happily pip install and run?

Thanks a lot


问:
resources.getIdentifier() in kotlin fragment
A very simple operation fails to build for reasons that I can't understand:

resources.getIdentifier(tokens[1],"drawable", requireContext().toString()) produces an incomprehensible (to me) error message: "Type mismatch: inferred type is New1Fragment
but Context! was expected"

New1Fragment is the fragment name.  'tokens' is an array of String vars that contains in index [1] the filename: String of the image resource in drawable whose integer identifier I need.

The code works as expected in an Activity (with "packageName" in place of "requireContext().toString()".

As a work-around, I could write a post processor to iterate through the drawables folder and grab the IDs of each item but that is clumsy and error prone.

What on earth does Context! mean?  How may people of ordinary skill in the art know that?

Tried every possibility the IDE offered.

The compiler always gives the same incomprehensible error message.


问:
Why is it calling destructor at vec.push_back(v)?
Why is it calling destructor at vec.push_back(v)?
I tried multiple things like reference...
Can anyone help me understand what is happening exactly?

This I have implemented the class Vector to mimic the vectors in STL but when I create Vector<Vector> obj and do push_back, it deletes the element being pushed. Why?

```<code>#include <iostream>
using namespace std;

template <typename T, int cap=1>
class Vector {
    private:
        T* arr{};
        int capacity=cap;
        int size = -1;

    public:
        Vector() {
            arr = new T[capacity]{};
        }

        bool isEmpty() {
            if(capacity && size) {
                return false;
            }
            return true;
        }

        void deletePoint(T* temp) {
            delete[] temp;
        }

        void Realloc() {
            cout << "Realloc" << '\n';
            T* temp = arr;
            capacity = 2*capacity;
            arr = new T[capacity]{};

            for(int i=0; i!=size; ++i) {
                arr[i] = temp[i];
            }

            deletePoint(temp);

        }

        int sizeOf() {
            return size + 1;
        }

        void push_back(T& val) {
            cout << size << " ";
            ++size;
            cout << size << " ";
            if(size < capacity) {
                // ++size;
                cout << "pushBack\n";
                arr[size] = val;
                return;
            }
            Realloc();
            // ++size;

            arr[size] = val;
            return;
        }

        void push_back(Vector val) {
            cout << size << " ";
            ++size;
            cout << size << " ";
            if(size < capacity) {
                // ++size;
                cout << "pushBack\n";
                arr[size] = val;
                return;
            }
            Realloc();
            // ++size;

            arr[size] = val;
            return;

        }

        void erase(int pointer) {
            arr[pointer] = 0;
            if (pointer > size) {
                return;
            }

            for(; pointer < size; ++pointer) {
                arr[pointer] = arr[pointer + 1];
                arr[pointer + 1] = 0;
            }
            --size;

        }

        int capacityOf() {
            return capacity;
        }

        T at(int val) {
            if(val <= size) {
                return arr[val];
            }
            return 0;
        }

        T& operator[] (int val) {
            return arr[val];
        }

        ~Vector() {
            cout << "Deleting with size:" << capacity << '\n';
            deletePoint(arr);
        }

};
</code>```

this is the main function

```<code>int main()
{

    Vector<int> v;
    Vector<Vector<int>> vec;

    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    v.push_back(6);
    cout << v.sizeOf() << "\n";
    vec.push_back(v);
}
</code>```

Body:
Why is it calling destructor at vec.push_back(v)?
I tried multiple things like reference...
Can anyone help me understand what is happening exactly?

This I have implemented the class Vector to mimic the vectors in STL but when I create Vector<Vector> obj and do push_back, it deletes the element being pushed. Why?

#include <iostream>
using namespace std;

template <typename T, int cap=1>
class Vector {
    private:
        T* arr{};
        int capacity=cap;
        int size = -1;

    public:
        Vector() {
            arr = new T[capacity]{};
        }

        bool isEmpty() {
            if(capacity && size) {
                return false;
            }
            return true;
        }

        void deletePoint(T* temp) {
            delete[] temp;
        }

        void Realloc() {
            cout << "Realloc" << '\n';
            T* temp = arr;
            capacity = 2*capacity;
            arr = new T[capacity]{};

            for(int i=0; i!=size; ++i) {
                arr[i] = temp[i];
            }

            deletePoint(temp);

        }

        int sizeOf() {
            return size + 1;
        }

        void push_back(T& val) {
            cout << size << " ";
            ++size;
            cout << size << " ";
            if(size < capacity) {
                // ++size;
                cout << "pushBack\n";
                arr[size] = val;
                return;
            }
            Realloc();
            // ++size;

            arr[size] = val;
            return;
        }

        void push_back(Vector val) {
            cout << size << " ";
            ++size;
            cout << size << " ";
            if(size < capacity) {
                // ++size;
                cout << "pushBack\n";
                arr[size] = val;
                return;
            }
            Realloc();
            // ++size;

            arr[size] = val;
            return;

        }

        void erase(int pointer) {
            arr[pointer] = 0;
            if (pointer > size) {
                return;
            }

            for(; pointer < size; ++pointer) {
                arr[pointer] = arr[pointer + 1];
                arr[pointer + 1] = 0;
            }
            --size;

        }

        int capacityOf() {
            return capacity;
        }

        T at(int val) {
            if(val <= size) {
                return arr[val];
            }
            return 0;
        }

        T& operator[] (int val) {
            return arr[val];
        }

        ~Vector() {
            cout << "Deleting with size:" << capacity << '\n';
            deletePoint(arr);
        }

};

this is the main function

int main()
{

    Vector<int> v;
    Vector<Vector<int>> vec;

    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    v.push_back(6);
    cout << v.sizeOf() << "\n";
    vec.push_back(v);
}


问:
Bubble Sort in never ending loop
I have the following data:

I basically want the 5,6,7 records to be at the very top of the list ordered by eta. The rest I am OK with as they stand. since they do not realy have an eta.

My JS function :

```<code>bubbleSortETA : function(array) {
        var swapped;
        do {
            swapped = false;
            for(var i = 0; i < array.length; i++) {
                console.log('array[i]');
                console.log(array[i]);
                console.log('array[i+1]');
                console.log(array[i+1]);

                var thisRowEta;
                var nextRowEta;

                if (array[i] && typeof(array[i].eta) != "undefined"){
                    thisRowEta = array[i].eta;
                }else{
                    thisRowEta = 1000; //so it appears at the bottom???
                }

                if (array[i+1] && typeof(array[i+1].eta) != "undefined"){
                    nextRowEta = array[i+1].eta;
                }else{
                    nextRowEta = 1000;
                }

                if(array[i] && array[i + 1] && typeof(array[i].walkInDetails) != "undefined" && typeof(array[i+1].walkInDetails) != "undefined" && (thisRowEta != nextRowEta)){
                    this.swap(array, i, i + 1);
                    console.log('we swapped...');
                    swapped = true;
                }
            }
        } while(swapped);
        console.log(array);
        return array;
    }
</code>```

It goes into this never ending loop. I have tried looking at output statements but am unable to understand why it is going into infinite loop.

Any tips?

Title: Bubble Sort in never ending loop

Body:
I have the following data:

I basically want the 5,6,7 records to be at the very top of the list ordered by eta. The rest I am OK with as they stand. since they do not realy have an eta.

My JS function :

bubbleSortETA : function(array) {
        var swapped;
        do {
            swapped = false;
            for(var i = 0; i < array.length; i++) {
                console.log('array[i]');
                console.log(array[i]);
                console.log('array[i+1]');
                console.log(array[i+1]);

                var thisRowEta;
                var nextRowEta;

                if (array[i] && typeof(array[i].eta) != "undefined"){
                    thisRowEta = array[i].eta;
                }else{
                    thisRowEta = 1000; //so it appears at the bottom???
                }

                if (array[i+1] && typeof(array[i+1].eta) != "undefined"){
                    nextRowEta = array[i+1].eta;
                }else{
                    nextRowEta = 1000;
                }

                if(array[i] && array[i + 1] && typeof(array[i].walkInDetails) != "undefined" && typeof(array[i+1].walkInDetails) != "undefined" && (thisRowEta != nextRowEta)){
                    this.swap(array, i, i + 1);
                    console.log('we swapped...');
                    swapped = true;
                }
            }
        } while(swapped);
        console.log(array);
        return array;
    }

It goes into this never ending loop. I have tried looking at output statements but am unable to understand why it is going into infinite loop.

Any tips?


问:
Dynamic QR-Code Generator Web Service with API to Wifi Controller
I'm looking for an open source solution allowing an easy way to grant access to a WiFi guest network for an enterprise.

The code should run on a webserver and generate new pre shared keys (PSK), calling an wireless controller via API to generate the new PSK, then display the PSK (and the SSID) as a QR code on the website. The WiFi controller should be able to handle mutliple PSK on one SSID of course.

The process should look like this:
Process QR-Code generator and create new PSK

Does someone maybe know an open source project which already developing something like this?


问:
How do I get server.js to do the equivalent of "yarn start" in nodejs to docker conversion?
I am trying to get a nodejs app to run in a container. I have followed the tutorial here: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/ and it works for the example. But, I do not know how to convert my start up command "yarn start" to be triggered by server.js.

All of the examples of dockerizing a nodejs app that I have found online use this server.js approach. In the tutorial linked above the container ends up running a simple "Hello World!" example app. I have tried putting

```<code>CMD [ "yarn", "start" ]

</code>```

in my Dockerfile but it does not launch the app.

This is my package.json file:

```<code>{
  "name": "my-server",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "concurrently \"cd api && yarn startd\" \"cd admin && yarn startd\"",
    "dev": "concurrently \"cd api && yarn dev\" \"cd admin && yarn dev\"",
    "logs": "heroku logs -t",
    "heroku-postbuild": "cd src/client && npm install && npm run build"
  },
  "devDependencies": {
    "concurrently": "^4.1.0",
    "nodemon": "^1.19.4",
    "prettier": "2.7.1",
    "prettier-plugin-apex": "1.10.0"
  }
}
</code>```

Question is: How do I get server.js to do the equivalent of "yarn start"?

server.js (modified to open two ports):

```<code>'use strict';

const express = require('express');

// Constants
const PORT1 = 3000;
const PORT2 = 4000;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
  res.send('Hello World from my-server');
});

app.listen(PORT1, PORT2, HOST, () => {
  console.log(`Running on http://${HOST}:${PORT1}`);
});
</code>```

Thank you!

Body:
I am trying to get a nodejs app to run in a container. I have followed the tutorial here: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/ and it works for the example. But, I do not know how to convert my start up command "yarn start" to be triggered by server.js.

All of the examples of dockerizing a nodejs app that I have found online use this server.js approach. In the tutorial linked above the container ends up running a simple "Hello World!" example app. I have tried putting

CMD [ "yarn", "start" ]

in my Dockerfile but it does not launch the app.

This is my package.json file:

{
  "name": "my-server",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "start": "concurrently \"cd api && yarn startd\" \"cd admin && yarn startd\"",
    "dev": "concurrently \"cd api && yarn dev\" \"cd admin && yarn dev\"",
    "logs": "heroku logs -t",
    "heroku-postbuild": "cd src/client && npm install && npm run build"
  },
  "devDependencies": {
    "concurrently": "^4.1.0",
    "nodemon": "^1.19.4",
    "prettier": "2.7.1",
    "prettier-plugin-apex": "1.10.0"
  }
}

Question is: How do I get server.js to do the equivalent of "yarn start"?

server.js (modified to open two ports):

'use strict';

const express = require('express');

// Constants
const PORT1 = 3000;
const PORT2 = 4000;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
  res.send('Hello World from my-server');
});

app.listen(PORT1, PORT2, HOST, () => {
  console.log(`Running on http://${HOST}:${PORT1}`);
});

Thank you!


问:
Django websocket cannot connect through https request blocked in railway app
My websocket works fine on localhost. But fails to run when I deploy my project on railway app

(which uses https)

It shows this error in the console log:

first error -

```<code>    (index):382 Mixed Content: The page at 'https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://supreme-key-production.up.railway.app/ws/bangladesh_ott/'. This request has been blocked; this endpoint must be available over WSS.
</code>```

second error -

```<code>    (index):382 Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.
        at window.onload (https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/:382:24)
</code>```

This is in my script :

    window.onload = function() {
        const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
        const userName = JSON.parse(document.getElementById('json-username').textContent);
        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/'
            + roomName
            + '/'
        );
        chatSocket.onmessage = function(e) {
            console.log('onmessage')

            const data = JSON.parse(e.data);

            if (data.message) {
                let html = '
';
                    html += '
' + data.username + '
';
                    html += '
' + data.message + '

';

                document.querySelector('#chat-messages').innerHTML += html;
            } else {
                alert('The message was empty!');
            }
        }

        chatSocket.onclose = function(e) {
            console.log('onclose')
        }

        //

        document.querySelector('#chat-message-submit').onclick = function(e) {
            e.preventDefault();

            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;

            chatSocket.send(JSON.stringify({
                'message': message,
                'username': userName,
                'room': roomName
            }));

            messageInputDom.value = '';

            return false;
        }
    }
```

Any solution for this?

Body:
My websocket works fine on localhost. But fails to run when I deploy my project on railway app

(which uses https)

It shows this error in the console log:

first error -

    (index):382 Mixed Content: The page at 'https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://supreme-key-production.up.railway.app/ws/bangladesh_ott/'. This request has been blocked; this endpoint must be available over WSS.

second error -

    (index):382 Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.
        at window.onload (https://supreme-key-production.up.railway.app/rooms/bangladesh_ott/:382:24)

This is in my script :

    window.onload = function() {
        const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
        const userName = JSON.parse(document.getElementById('json-username').textContent);
        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/'
            + roomName
            + '/'
        );
        chatSocket.onmessage = function(e) {
            console.log('onmessage')

            const data = JSON.parse(e.data);

            if (data.message) {
                let html = '
';
                    html += '
' + data.username + '
';
                    html += '
' + data.message + '

';

                document.querySelector('#chat-messages').innerHTML += html;
            } else {
                alert('The message was empty!');
            }
        }

        chatSocket.onclose = function(e) {
            console.log('onclose')
        }

        //

        document.querySelector('#chat-message-submit').onclick = function(e) {
            e.preventDefault();

            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;

            chatSocket.send(JSON.stringify({
                'message': message,
                'username': userName,
                'room': roomName
            }));

            messageInputDom.value = '';

            return false;
        }
    }

Any solution for this?


问:
How to check the amount of memory a single/set of lines in python is using?
I added several lines to a python codebase and now the memory is exceeding the limits. Is there a way to see how much memory a particular line or set of lines is using in Python?

Here's the set of lines that I added

```<code>    df["value_weighted_average"] = (
      df.reset_index().merge(df2merge, on='vid', suffixes=['','_x'])
      .assign(proportions=lambda x: (x[['first','first_x']].min(axis=1) - x[['second','second_x']].max(axis=1)))
      .query('proportions >= 0')
      .groupby('index')['proportions'].sum()
    )
</code>```

df1.shape is ttypically about O(10^5) x O(10^1).
df2.shape is typically about O(10^7) x O(10^1).

I'm not well versed with Python, but I think the merge operation is what's introducing a lot of memory usage

Body:
I added several lines to a python codebase and now the memory is exceeding the limits. Is there a way to see how much memory a particular line or set of lines is using in Python?

Here's the set of lines that I added

    df["value_weighted_average"] = (
      df.reset_index().merge(df2merge, on='vid', suffixes=['','_x'])
      .assign(proportions=lambda x: (x[['first','first_x']].min(axis=1) - x[['second','second_x']].max(axis=1)))
      .query('proportions >= 0')
      .groupby('index')['proportions'].sum()
    )

df1.shape is ttypically about O(10^5) x O(10^1).
df2.shape is typically about O(10^7) x O(10^1).

I'm not well versed with Python, but I think the merge operation is what's introducing a lot of memory usage


问:
Write an assembly program that capitalizes each word of an input char array

Write an emu8086 assembly program that capitalizes the first letter of each word of an input char array, with the following requirements:

The maximum length of the input array is 40 chars.

The input array will be typed using the keyboard.

The input array will be stored in pre-allocated memory locations

The result will be displayed in the next row.

So, after I enter the input array, it gives this error message:

unknown opcode skipped: 46

not 8086 instruction - not supported yet.

```<code>org 100h

jmp start
array_char db 40 dup(?)

;init video mode
start:
    mov AX, 0h
    int 10h

main:
    call readInputArray
    call capitalizeArray
    call printNextRow
    int 20h

getKey:
    mov AH, 00h; read key press
    int 16h ; keyboard services interrupt
    ret

printKey:
    mov AH, 0Eh ; 0Eh = Teletype output; AL = Character
    int 10h ; video services interrupt
    ret

readInputArray:
    cld
    lea DI, array_char
    mov CX, 40

read1Char:
    call getKey ;returns in AL the ASCII code of the key printed
    stosb
    call printKey
    cmp AL, 0x0D
    loopne read1Char
    ret

capitalizeArray:
    lea SI, array_char
    mov AL, [SI]
    cmp AL, 'a'
    jb end_cap
    cmp AL, 'z'
    ja end_cap
    sub AL, 20h
    mov [SI], AL
    inc SI
    jmp check_word

check_word:
    cmp [SI], ' '
    jne check_next
    inc SI
    mov AL, [SI]
    cmp AL, 'a'
    jb check_next
    cmp AL, 'z'
    ja check_next
    sub AL, 20h
    mov [SI], AL

check_next:
    inc SI
    cmp SI, 40
    jz end_cap
    jmp check_word

end_cap:
    ret

printNextRow:
    mov AH, 02h
    mov DL, 10
    int 21h
    mov DL, 13
    int 21h
    mov AH, 09h
    lea DX, array_char
    int 21h
    ret
</code>```

Body:
Write an emu8086 assembly program that capitalizes the first letter of each word of an input char array, with the following requirements:

The maximum length of the input array is 40 chars.

The input array will be typed using the keyboard.

The input array will be stored in pre-allocated memory locations

The result will be displayed in the next row.

So, after I enter the input array, it gives this error message:

unknown opcode skipped: 46

not 8086 instruction - not supported yet.

org 100h

jmp start
array_char db 40 dup(?)

;init video mode
start:
    mov AX, 0h
    int 10h

main:
    call readInputArray
    call capitalizeArray
    call printNextRow
    int 20h

getKey:
    mov AH, 00h; read key press
    int 16h ; keyboard services interrupt
    ret

printKey:
    mov AH, 0Eh ; 0Eh = Teletype output; AL = Character
    int 10h ; video services interrupt
    ret

readInputArray:
    cld
    lea DI, array_char
    mov CX, 40

read1Char:
    call getKey ;returns in AL the ASCII code of the key printed
    stosb
    call printKey
    cmp AL, 0x0D
    loopne read1Char
    ret

capitalizeArray:
    lea SI, array_char
    mov AL, [SI]
    cmp AL, 'a'
    jb end_cap
    cmp AL, 'z'
    ja end_cap
    sub AL, 20h
    mov [SI], AL
    inc SI
    jmp check_word

check_word:
    cmp [SI], ' '
    jne check_next
    inc SI
    mov AL, [SI]
    cmp AL, 'a'
    jb check_next
    cmp AL, 'z'
    ja check_next
    sub AL, 20h
    mov [SI], AL

check_next:
    inc SI
    cmp SI, 40
    jz end_cap
    jmp check_word

end_cap:
    ret

printNextRow:
    mov AH, 02h
    mov DL, 10
    int 21h
    mov DL, 13
    int 21h
    mov AH, 09h
    lea DX, array_char
    int 21h
    ret


问:
Does sys.path.append() not work on a Mac?
I have used this code on my PC and it works no problem and gives me access to all the source code inside the ibapi library: import sys --
sys.path.append("C:\TWS API\This PC\Downloads\source\pythonclient\ibapi")

from ibapi.client import EClient

But when I run the mirror image on a Mac,
sys.path.append('/Users/paulbeasley/Downloads/twsapi_macunix/IBJts/source/pythonclient/ibapi')

it throws me an error saying -- ModuleNotFoundError: No module named 'ibapi'.

I am now pretty sure that sys.path.append is a PC only function. How can I translate it so it works on a Mac?

Instead of using sys, I opted to try to use the os library to append the path name instead using this code :

```<code>import os

pathname = '/Users/paulbeasley/Downloads/twsapi_macunix/IBJts/source/pythonclient/ibapi'

# Get the current PATH environment variable
current_path = os.environ.get('PATH')

# Append the new pathname to the current PATH
new_path = current_path + ':' + pathname

# Set the new PATH environment variable
os.environ['PATH'] = new_path

print(new_path)
</code>```

It does print my pathname in the list of pathnames, but still throws me the same error when I try to run the script. How can I resolve my issue so I can access all the source code in the ibapi library that I downloaded to my computer? Thanks

Body:
I have used this code on my PC and it works no problem and gives me access to all the source code inside the ibapi library: import sys --
sys.path.append("C:\TWS API\This PC\Downloads\source\pythonclient\ibapi")

from ibapi.client import EClient

But when I run the mirror image on a Mac,
sys.path.append('/Users/paulbeasley/Downloads/twsapi_macunix/IBJts/source/pythonclient/ibapi')

it throws me an error saying -- ModuleNotFoundError: No module named 'ibapi'.

I am now pretty sure that sys.path.append is a PC only function. How can I translate it so it works on a Mac?

Instead of using sys, I opted to try to use the os library to append the path name instead using this code :

import os

pathname = '/Users/paulbeasley/Downloads/twsapi_macunix/IBJts/source/pythonclient/ibapi'

# Get the current PATH environment variable
current_path = os.environ.get('PATH')

# Append the new pathname to the current PATH
new_path = current_path + ':' + pathname

# Set the new PATH environment variable
os.environ['PATH'] = new_path

print(new_path)

It does print my pathname in the list of pathnames, but still throws me the same error when I try to run the script. How can I resolve my issue so I can access all the source code in the ibapi library that I downloaded to my computer? Thanks


问:
Django Rosetta autoreload new translations bad gateway error
I have a problem with django-rosetta, it works fine but when changing translations it is not applied to the site until restarting the docker. I tried adding these codes:

```<code>ROSETTA_WSGI_AUTO_RELOAD = True
ROSETTA_UWSGI_AUTO_RELOAD = True
</code>```

But after adding this codes when saving rosetta it gives 502 bad gateway error despite saving new translations but it is still not applying new translations to the site until I restart.

Body:
I have a problem with django-rosetta, it works fine but when changing translations it is not applied to the site until restarting the docker. I tried adding these codes:

ROSETTA_WSGI_AUTO_RELOAD = True
ROSETTA_UWSGI_AUTO_RELOAD = True

But after adding this codes when saving rosetta it gives 502 bad gateway error despite saving new translations but it is still not applying new translations to the site until I restart.


问:
Meta OPT-66B - How to generate answers to prompts
I recently downloaded OPT-66B from the following link :
https://github.com/facebookresearch/metaseq/tree/main/projects/OPT

To my knowledge, this model is designed for extended text in the following way :

The user provides starter text

The model outputs an extension of that text

Is it possible to do the following with this model? :

The user provides a prompt (e.g. "Write a story about a dog in the park")

The model outputs the requested answer (e.g. "Buddy the dog was ...")

If so, is there any documentation/code to have it function in this way?


问:
Insert into multiple tables on one transaction using GORM
I'm trying to store information in 3 tables in a single transaction using GORM. I need to create just one row on Table1 and Table2 and multiple records on Table3

```<code>type Table1 struct {
    Id          uuid.UUID   `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
}

type Table2 struct {
    Id          uuid.UUID   `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Table2ID    uuid.UUID   `gorm:"type:uuid;default:uuid_generate_v4()"`
    Table2      Table2
}

type Table3 struct {
    Id          uuid.UUID   `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Table3ID    uuid.UUID   `gorm:"type:uuid;default:uuid_generate_v4()"`
    Table3      Table3
}

type Table3List []Table3
</code>```

When I use just Table2 including all Table1 attributes, that works. One transaction creates one row in each table., but if I use Table3List, GORM creates multiple records on Table 1, table 2, and didn't assign Table3ID on Table3. I tried to create an aditional logical struct (is not a DB table) like this, but doesn't work

```<code>type MyCompoundedTx struct {
    Table2
    Table3List
}
</code>```

Any ideas?

Body:
I'm trying to store information in 3 tables in a single transaction using GORM. I need to create just one row on Table1 and Table2 and multiple records on Table3

type Table1 struct {
    Id          uuid.UUID   `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
}

type Table2 struct {
    Id          uuid.UUID   `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Table2ID    uuid.UUID   `gorm:"type:uuid;default:uuid_generate_v4()"`
    Table2      Table2
}

type Table3 struct {
    Id          uuid.UUID   `gorm:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Table3ID    uuid.UUID   `gorm:"type:uuid;default:uuid_generate_v4()"`
    Table3      Table3
}

type Table3List []Table3

When I use just Table2 including all Table1 attributes, that works. One transaction creates one row in each table., but if I use Table3List, GORM creates multiple records on Table 1, table 2, and didn't assign Table3ID on Table3. I tried to create an aditional logical struct (is not a DB table) like this, but doesn't work

type MyCompoundedTx struct {
    Table2
    Table3List
}

Any ideas?


问:
How to measure time of training for one node with tensorflow federated?
i want to benchmark different federated learning tools, does anyone know how to measure the training time with tensorflow federated? In all the tutorials the trainer only does the next function to perform training on all nodes and aggregating and i can not find the function which calls the training process on a invidual node. Can someone help me where to find this or has another idea which could work? Below is my training loop, its based on the example of the kubernetes simulation of tff https://www.tensorflow.org/federated/tutorials/high_performance_simulation_with_kubernetes

```<code>def train_loop(num_rounds=10, num_clients=10):
    state = trainer.initialize()
    for round in range(1, num_rounds + 1):
        train_data = train_data_iterator.select(num_clients)
        result = trainer.next(state, train_data)
        state = result.state
        train_metrics = result.metrics['client_work']['train']
        with open('readme.txt', 'a+') as f:
            f.writelines('round {:2d}, metrics={}'.format(round, train_metrics))
        print('round {:2d}, metrics={}'.format(round, train_metrics))
</code>```

Searching trough the source code to find the function that gets called when a invidual nodes trains on there local data but i found nothing so far.

Body:
i want to benchmark different federated learning tools, does anyone know how to measure the training time with tensorflow federated? In all the tutorials the trainer only does the next function to perform training on all nodes and aggregating and i can not find the function which calls the training process on a invidual node. Can someone help me where to find this or has another idea which could work? Below is my training loop, its based on the example of the kubernetes simulation of tff https://www.tensorflow.org/federated/tutorials/high_performance_simulation_with_kubernetes

def train_loop(num_rounds=10, num_clients=10):
    state = trainer.initialize()
    for round in range(1, num_rounds + 1):
        train_data = train_data_iterator.select(num_clients)
        result = trainer.next(state, train_data)
        state = result.state
        train_metrics = result.metrics['client_work']['train']
        with open('readme.txt', 'a+') as f:
            f.writelines('round {:2d}, metrics={}'.format(round, train_metrics))
        print('round {:2d}, metrics={}'.format(round, train_metrics))

Searching trough the source code to find the function that gets called when a invidual nodes trains on there local data but i found nothing so far.


问:
pandas fast mapping and replacing column value
I have a DataFrame, you can have it by running:

```<code>import pandas as pd
from io import StringIO

df = """

               case_id    scheduled_date        status_code
               1213       2021-08               1
               3444       2021-06               0
               4566       2021-07               2
               12213      2021-08               2
               34344      2021-06               0
               44566      2021-07               2
               1213       2021-08               0

        """
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')
</code>```

This outputs:

```<code>  case_id   scheduled_date  status_code
0   1213    2021-08         1
1   3444    2021-06         0
2   4566    2021-07         2
3   12213   2021-08         2
4   34344   2021-06         0
5   44566   2021-07         2
6   1213    2021-08         0
</code>```

How can I replace the status_code value with {1:'success',0:'fail',2:'unknown'},the output should be:

```<code>  case_id   scheduled_date  status_code
0   1213    2021-08         success
1   3444    2021-06         fail
2   4566    2021-07         unknown
3   12213   2021-08         unknown
4   34344   2021-06         fail
5   44566   2021-07         unknown
6   1213    2021-08         fail
</code>```

Body:
I have a DataFrame, you can have it by running:

import pandas as pd
from io import StringIO

df = """

               case_id    scheduled_date        status_code
               1213       2021-08               1
               3444       2021-06               0
               4566       2021-07               2
               12213      2021-08               2
               34344      2021-06               0
               44566      2021-07               2
               1213       2021-08               0

        """
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')

This outputs:

  case_id   scheduled_date  status_code
0   1213    2021-08         1
1   3444    2021-06         0
2   4566    2021-07         2
3   12213   2021-08         2
4   34344   2021-06         0
5   44566   2021-07         2
6   1213    2021-08         0

How can I replace the status_code value with {1:'success',0:'fail',2:'unknown'},the output should be:

  case_id   scheduled_date  status_code
0   1213    2021-08         success
1   3444    2021-06         fail
2   4566    2021-07         unknown
3   12213   2021-08         unknown
4   34344   2021-06         fail
5   44566   2021-07         unknown
6   1213    2021-08         fail


问:
Unable to install library in jupyter notebook getting [WinError 2]
I am unable to use pip install to install a library in jupyter notebook.

I tried running pip install ffprobe and I received the error below

```<code>---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19512\1427077936.py in <module>
----> 1 get_ipython().run_line_magic('conda', 'install -c travis ffprobe')

~\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2362                 kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2363             with self.builtin_trap:
-> 2364                 result = fn(*args, **kwargs)
   2365             return result
   2366

~\anaconda3\lib\site-packages\decorator.py in fun(*args, **kw)
    230             if not kwsyntax:
    231                 args, kw = fix(args, kw, sig)
--> 232             return caller(func, *(extras + args), **kw)
    233     fun.__name__ = func.__name__
    234     fun.__doc__ = func.__doc__

~\anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

~\anaconda3\lib\site-packages\IPython\core\magics\packaging.py in conda(self, line)
    107             extra_args.extend(["--prefix", sys.prefix])
    108
--> 109         self.shell.system(' '.join([conda, command] + extra_args + args))
    110         print("\nNote: you may need to restart the kernel to use updated packages.")

~\anaconda3\lib\site-packages\ipykernel\zmqshell.py in system_piped(self, cmd)
    629                 if path is not None:
    630                     cmd = "pushd %s &&%s" % (path, cmd)
--> 631                 self.user_ns["_exit_code"] = system(cmd)
    632         else:
    633             self.user_ns["_exit_code"] = system(self.var_expand(cmd, depth=1))

~\anaconda3\lib\site-packages\IPython\utils\_process_win32.py in system(cmd)
    143         if path is not None:
    144             cmd = '"pushd %s &&"%s' % (path, cmd)
--> 145         return process_handler(cmd, _system_body)
    146
    147 def getoutput(cmd):

~\anaconda3\lib\site-packages\IPython\utils\_process_common.py in process_handler(cmd, callback, stderr)
     77     if shell and os.name == 'posix' and 'SHELL' in os.environ:
     78         executable = os.environ['SHELL']
---> 79     p = subprocess.Popen(cmd, shell=shell,
     80                          executable=executable,
     81                          stdin=subprocess.PIPE,

~\anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask)
    949                             encoding=encoding, errors=errors)
    950
--> 951             self._execute_child(args, executable, preexec_fn, close_fds,
    952                                 pass_fds, cwd, env,
    953                                 startupinfo, creationflags, shell,

~\anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_gid, unused_gids, unused_uid, unused_umask, unused_start_new_session)
   1418             # Start the process
   1419             try:
-> 1420                 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
   1421                                          # no special security
   1422                                          None, None,

FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

The first thing I tried to do was add --user at the end of my command so it is pip install ffprobe-python --user but I still received the same error. After that I tried upgrading pip using pip install --upgrade pip but it didn't work.

I tried entering anaconda3/share/jupyter/python3 and checking if the kernel.json file has any issue but there was no problem

Lastly I tried going into subprocesses.py and changing the shell from this function to true but it didnt solve anything

```<code>def __init__(self, args, bufsize=-1, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=True,
                 shell=False, cwd=None, env=None, universal_newlines=None,
                 startupinfo=None, creationflags=0,
                 restore_signals=True, start_new_session=False,
                 pass_fds=(), *, user=None, group=None, extra_groups=None,
                 encoding=None, errors=None, text=None, umask=-1):
</code>```

Please do let me know if any more information needs to be provided as I am quite new to this and any help would be greatly appreciated.

I just tried %conda install -c travis ffprobe and installing the package that was mentioned however I still received the same error as the one above.

Body:
I am unable to use pip install to install a library in jupyter notebook.

I tried running pip install ffprobe and I received the error below

---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19512\1427077936.py in <module>
----> 1 get_ipython().run_line_magic('conda', 'install -c travis ffprobe')

~\anaconda3\lib\site-packages\IPython\core\interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2362                 kwargs['local_ns'] = self.get_local_scope(stack_depth)
   2363             with self.builtin_trap:
-> 2364                 result = fn(*args, **kwargs)
   2365             return result
   2366

~\anaconda3\lib\site-packages\decorator.py in fun(*args, **kw)
    230             if not kwsyntax:
    231                 args, kw = fix(args, kw, sig)
--> 232             return caller(func, *(extras + args), **kw)
    233     fun.__name__ = func.__name__
    234     fun.__doc__ = func.__doc__

~\anaconda3\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188
    189         if callable(arg):

~\anaconda3\lib\site-packages\IPython\core\magics\packaging.py in conda(self, line)
    107             extra_args.extend(["--prefix", sys.prefix])
    108
--> 109         self.shell.system(' '.join([conda, command] + extra_args + args))
    110         print("\nNote: you may need to restart the kernel to use updated packages.")

~\anaconda3\lib\site-packages\ipykernel\zmqshell.py in system_piped(self, cmd)
    629                 if path is not None:
    630                     cmd = "pushd %s &&%s" % (path, cmd)
--> 631                 self.user_ns["_exit_code"] = system(cmd)
    632         else:
    633             self.user_ns["_exit_code"] = system(self.var_expand(cmd, depth=1))

~\anaconda3\lib\site-packages\IPython\utils\_process_win32.py in system(cmd)
    143         if path is not None:
    144             cmd = '"pushd %s &&"%s' % (path, cmd)
--> 145         return process_handler(cmd, _system_body)
    146
    147 def getoutput(cmd):

~\anaconda3\lib\site-packages\IPython\utils\_process_common.py in process_handler(cmd, callback, stderr)
     77     if shell and os.name == 'posix' and 'SHELL' in os.environ:
     78         executable = os.environ['SHELL']
---> 79     p = subprocess.Popen(cmd, shell=shell,
     80                          executable=executable,
     81                          stdin=subprocess.PIPE,

~\anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, user, group, extra_groups, encoding, errors, text, umask)
    949                             encoding=encoding, errors=errors)
    950
--> 951             self._execute_child(args, executable, preexec_fn, close_fds,
    952                                 pass_fds, cwd, env,
    953                                 startupinfo, creationflags, shell,

~\anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_gid, unused_gids, unused_uid, unused_umask, unused_start_new_session)
   1418             # Start the process
   1419             try:
-> 1420                 hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
   1421                                          # no special security
   1422                                          None, None,

FileNotFoundError: [WinError 2] The system cannot find the file specified

The first thing I tried to do was add --user at the end of my command so it is pip install ffprobe-python --user but I still received the same error. After that I tried upgrading pip using pip install --upgrade pip but it didn't work.

I tried entering anaconda3/share/jupyter/python3 and checking if the kernel.json file has any issue but there was no problem

Lastly I tried going into subprocesses.py and changing the shell from this function to true but it didnt solve anything

def __init__(self, args, bufsize=-1, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=True,
                 shell=False, cwd=None, env=None, universal_newlines=None,
                 startupinfo=None, creationflags=0,
                 restore_signals=True, start_new_session=False,
                 pass_fds=(), *, user=None, group=None, extra_groups=None,
                 encoding=None, errors=None, text=None, umask=-1):

Please do let me know if any more information needs to be provided as I am quite new to this and any help would be greatly appreciated.

I just tried %conda install -c travis ffprobe and installing the package that was mentioned however I still received the same error as the one above.


问:
Class inheritance - can it be done backwards?
In Python there is the possibility of using inheritance to obtain different classes after one parent. But is it possible that I have various "child" classes that have the same methods that strictly depends on the parent class, and that each one inherits a different parent, like the following example

```<code>class Parent_1():
    methods for parent 1

class Parent_2():
    methods for parent 2

class Parent_3():
    methods for parent 3

GENERAL_CHILD_METHODS -> is an object that includes all the methods that all the childs will share

class Child_1(inherits Parent_1 and uses GENERAL CHILD METHODS)

class Child_2(inherits Parent_2 and uses GENERAL CHILD METHODS)

class Child_3(inherits Parent_3 and uses GENERAL CHILD METHODS)

</code>```

is it possible to create something like the GENERAL_CHILD_METHOD object that I mention in the example? so that I do not have to copy all the same methods for each child, because in the end they are the same. So I suppose there is a way to wrap this methods so that I only have to use one line to call all of them in each Child class and not to have to copy everything all the time.

Body:
In Python there is the possibility of using inheritance to obtain different classes after one parent. But is it possible that I have various "child" classes that have the same methods that strictly depends on the parent class, and that each one inherits a different parent, like the following example

class Parent_1():
    methods for parent 1

class Parent_2():
    methods for parent 2

class Parent_3():
    methods for parent 3

GENERAL_CHILD_METHODS -> is an object that includes all the methods that all the childs will share

class Child_1(inherits Parent_1 and uses GENERAL CHILD METHODS)

class Child_2(inherits Parent_2 and uses GENERAL CHILD METHODS)

class Child_3(inherits Parent_3 and uses GENERAL CHILD METHODS)

is it possible to create something like the GENERAL_CHILD_METHOD object that I mention in the example? so that I do not have to copy all the same methods for each child, because in the end they are the same. So I suppose there is a way to wrap this methods so that I only have to use one line to call all of them in each Child class and not to have to copy everything all the time.


问:
For a given y how to print x? Stata
Is there any command in Stata, that prints the value of x according to an input y value? I have 10 y values which form a descending curve. So, is there any way to predict x from a given y? I am trying somehow to find the linear equation y=ax+b and then calculate the x according to y. I would like to listen your solutions.</p>

Title: For a given y how to print x? Stata


问:
In Flutter, how can I make sure that ChangNotifier is not being used before running the state dispose?
I'm getting the following error with ChangeNotifier.dispose.

```<code>A ShakeWidgetState was used after being disposed.
Once you have called dispose() on a ShakeWidgetState, it can no longer be used.

When the exception was thrown, this was the stack:
#2      ChangeNotifier.dispose (package:flutter/src/foundation/change_notifier.dart:302:27)
</code>```

I did some research but none of the possible solutions works for me. I even comment out the notifyListeners but the error is still thrown. Here is the snippet of my code.

```<code>class ShakeWidgetState extends State<ShakeWidget>
    with SingleTickerProviderStateMixin, ChangeNotifier {
bool disposed=false;
@override
  void notifyListeners() {
    if (!disposed) {
      super.notifyListeners();
    }
  }
void dispose() {
     // assert(ChangeNotifier.debugAssertNotDisposed(this));
    _disposed = true;
       super. Dispose();
    //});
  }
}
</code>```

Appreciate any feedback.

Body:
I'm getting the following error with ChangeNotifier.dispose.

A ShakeWidgetState was used after being disposed.
Once you have called dispose() on a ShakeWidgetState, it can no longer be used.

When the exception was thrown, this was the stack:
#2      ChangeNotifier.dispose (package:flutter/src/foundation/change_notifier.dart:302:27)

I did some research but none of the possible solutions works for me. I even comment out the notifyListeners but the error is still thrown. Here is the snippet of my code.

class ShakeWidgetState extends State<ShakeWidget>
    with SingleTickerProviderStateMixin, ChangeNotifier {
bool disposed=false;
@override
  void notifyListeners() {
    if (!disposed) {
      super.notifyListeners();
    }
  }
void dispose() {
     // assert(ChangeNotifier.debugAssertNotDisposed(this));
    _disposed = true;
       super. Dispose();
    //});
  }
}

Appreciate any feedback.


问:
Problem with submitting ENUM from dropdown menu into table
I have a form where user insert amount, note, date, and he also have a dropdown menu to select one option, that select menu is populated from ENUM.

That looks like this:

```<code> <form action="#"
                  th:action="@{/api/transaction/saveIncome/{walletId} (walletId=${walletId})}"
                  th:object="${transaction}" method="post">
                <div class="row">
                    <div class="form-group col-md-6">
                        <label for="amount" class="col-form-label">Amount</label> <input
                            type="text" th:field="*{amount}" class="form-control" id="amount"
                            placeholder="amount"> <span
                            th:if="${#fields.hasErrors('amount')}" th:errors="*{amount}"
                            class="text-danger"></span>
                    </div>
                    <div class="form-group col-md-8">
                        <label for="note" class="col-form-label">Note</label> <input
                            type="text" th:field="*{note}" class="form-control" id="note"
                            placeholder="note"> <span
                            th:if="${#fields.hasErrors('note')}" th:errors="*{note}"
                            class="text-danger"></span>
                    </div>
                    <div class="form-group col-md-8">
                        <label for="theDate" class="col-form-label">Date</label> <input
                            type="date" th:field="*{date}" class="form-control"
                            id="theDate" placeholder="date"> <span
                            th:if="${#fields.hasErrors('date')}" th:errors="date"
                            class="text-danger"></span>
                    </div>
                    <div class="form-group col-md-8">
                        <select th:field="${transaction.incomeCategories}">
                            <option value="0">Select income category</option>
                            <option
                                    th:each="incomeCategories : ${incomeCategories}"
                                    th:value="${incomeCategories}"
                                    th:text="${incomeCategories.displayName}"
                            ></option>
                        </select>
                    </div>

                    <div class="form-group col-md-8">
                        <input type="submit" class="btn btn-primary"
                               value="Create transaction">
                    </div>
                </div>
            </form>
</code>```

This is how I populated dropdown menu:

```<code> <select th:field="${transaction.incomeCategories}">
                            <option value="0">Select income category</option>
                            <option
                                    th:each="incomeCategories : ${incomeCategories}"
                                    th:value="${incomeCategories}"
                                    th:text="${incomeCategories.displayName}"
                            ></option>
 </select>
</code>```

Then, I have controller to submit this form into database:

```<code>  @PostMapping("/saveIncome/{walletId}")
public String saveIncome(@PathVariable(value = "walletId") long walletId, @Valid Transaction transaction, BindingResult result, Model model) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();

    Wallet wallet = walletService.getWalletById(walletId);

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        model.addAttribute("incomeCategories", IncomeCategories.values());
        return "income_transaction";
    }

    transaction.setWallet(wallet);
    transactionService.saveIncome(transaction, walletId, userId);
    return "redirect:/api/wallet/userWallet/balance/" + userId;
}
</code>```

When I insert data in all fields and try to submit I get:

Column 'expense_categories' cannot be null

That is table:

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "transaction_id")
private Long id;

@Min(value = 0, message = "Please, insert a positive amount")
private double amount;

private String note;

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "date")
private Date date;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "wallet_id", nullable = false)
private Wallet wallet;

@Enumerated(EnumType.STRING)
@Column(name = "transaction_type", columnDefinition = "ENUM('EXPENSE', 'INCOME')")
private TransactionType transactionType;

@Enumerated(EnumType.STRING)
@Column(name = "expense_categories", columnDefinition = "ENUM('FOOD_AND_DRINK', 'SHOPPING', 'TRANSPORT', 'HOME'," +
        " 'BILLS_AND_FEES', 'ENTERTAINMENT', 'CAR', 'TRAVEL', 'FAMILY_AND_PERSONAL', 'HEALTHCARE'," +
        " 'EDUCATION', 'GROCERIES', 'GIFTS', 'BEAUTY', 'WORK', 'SPORTS_AND_HOBBIES', 'OTHER')")
private ExpenseCategories expenseCategories;

@Enumerated(EnumType.STRING)
@Column(name = "income_categories", columnDefinition = "ENUM('SALARY', 'BUSINESS', 'GIFTS', 'EXTRA_INCOME', 'LOAN', 'PARENTAL_LEAVE', 'INSURANCE_PAYOUT', 'OTHER')")
private IncomeCategories incomeCategories;
</code>```

Just to say, user first have a two buttons to choose between income transaction and expense transaction, that is reason why I have IncomeCategories and Expense and as you can see when I try to insert income into database I get that error, but I thought column can be null

Body:
I have a form where user insert amount, note, date, and he also have a dropdown menu to select one option, that select menu is populated from ENUM.

That looks like this:

 <form action="#"
                  th:action="@{/api/transaction/saveIncome/{walletId} (walletId=${walletId})}"
                  th:object="${transaction}" method="post">

                        Amount <input
                            type="text" th:field="*{amount}" class="form-control" id="amount"
                            placeholder="amount">

                        Note <input
                            type="text" th:field="*{note}" class="form-control" id="note"
                            placeholder="note">

                        Date <input
                            type="date" th:field="*{date}" class="form-control"
                            id="theDate" placeholder="date">

                        <select th:field="${transaction.incomeCategories}">
                            <option value="0">Select income category</option>
                            <option
                                    th:each="incomeCategories : ${incomeCategories}"
                                    th:value="${incomeCategories}"
                                    th:text="${incomeCategories.displayName}"
                            ></option>
                        </select>

                        <input type="submit" class="btn btn-primary"
                               value="Create transaction">

            </form>

This is how I populated dropdown menu:

 <select th:field="${transaction.incomeCategories}">
                            <option value="0">Select income category</option>
                            <option
                                    th:each="incomeCategories : ${incomeCategories}"
                                    th:value="${incomeCategories}"
                                    th:text="${incomeCategories.displayName}"
                            ></option>
 </select>

Then, I have controller to submit this form into database:

  @PostMapping("/saveIncome/{walletId}")
public String saveIncome(@PathVariable(value = "walletId") long walletId, @Valid Transaction transaction, BindingResult result, Model model) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
    long userId = user.getId();

    Wallet wallet = walletService.getWalletById(walletId);

    boolean thereAreErrors = result.hasErrors();
    if (thereAreErrors) {
        model.addAttribute("incomeCategories", IncomeCategories.values());
        return "income_transaction";
    }

    transaction.setWallet(wallet);
    transactionService.saveIncome(transaction, walletId, userId);
    return "redirect:/api/wallet/userWallet/balance/" + userId;
}

When I insert data in all fields and try to submit I get:

Column 'expense_categories' cannot be null

That is table:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "transaction_id")
private Long id;

@Min(value = 0, message = "Please, insert a positive amount")
private double amount;

private String note;

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "date")
private Date date;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "wallet_id", nullable = false)
private Wallet wallet;

@Enumerated(EnumType.STRING)
@Column(name = "transaction_type", columnDefinition = "ENUM('EXPENSE', 'INCOME')")
private TransactionType transactionType;

@Enumerated(EnumType.STRING)
@Column(name = "expense_categories", columnDefinition = "ENUM('FOOD_AND_DRINK', 'SHOPPING', 'TRANSPORT', 'HOME'," +
        " 'BILLS_AND_FEES', 'ENTERTAINMENT', 'CAR', 'TRAVEL', 'FAMILY_AND_PERSONAL', 'HEALTHCARE'," +
        " 'EDUCATION', 'GROCERIES', 'GIFTS', 'BEAUTY', 'WORK', 'SPORTS_AND_HOBBIES', 'OTHER')")
private ExpenseCategories expenseCategories;

@Enumerated(EnumType.STRING)
@Column(name = "income_categories", columnDefinition = "ENUM('SALARY', 'BUSINESS', 'GIFTS', 'EXTRA_INCOME', 'LOAN', 'PARENTAL_LEAVE', 'INSURANCE_PAYOUT', 'OTHER')")
private IncomeCategories incomeCategories;

Just to say, user first have a two buttons to choose between income transaction and expense transaction, that is reason why I have IncomeCategories and Expense and as you can see when I try to insert income into database I get that error, but I thought column can be null


问:
Rows are getting still opened when we inject the new data from API and showing expand icon in expanded form in react table when we click sortingbutton
I have used React-table 7 datagrid with few customizations , where I have hidden all headers and just using a single column as a narrow hierarchy component.
I have implemented server side sorting on this datagrid(narrow hierarchy component) by clicking on a button (This button is in a component from where I am calling react-table datagrid) .
On initial render, I can see all icons in a collapsed format, when i click on any icon, children level API call is getting made and children data got appended post api call response.
When I click on sort button, sorting order changes (eg:- "ASC","DESC") , then I see rows position which I have opened in previous sort order , those positions are showing expandable icon as expanded rather then collapsed.
Can somebody help me here???

enter image description here

I want when I click sort button, new data comes, then all rows should have the expandable icon in a collapsed form.