问:
debugging the server part of the shiny
I've tried to run this app several times, but the server part of the code doesn't work at all, even though it should be complete. The UI part works perfectly; however, when I attempt to run the server part, it just stops. I can't really see the issue
I would be grateful if you could look at the code.

```<code>ui<-pageWithSidebar(
  headerPanel("Statistical analysis"),
  sidebarPanel(
    fileInput('file1', 'Select your file',
              accept = c(
                'text/csv',
                'text/comma-separated-values','.csv',
                '.sas7bdat'
              )
    ),
    splitLayout(
      textInput("subvar","Subset Variable:"),

      textInput("subval","Subset Value:")),
    splitLayout(
      textInput("dep","Dependent variable:"),
      textInput("indep","Independent variable:")),
    selectInput("varlist","Pick Treatment
variable:",choices=c(colnames(data()))),
    selectInput("Model","Model:",
                list("Linear regression" = "lm",
                     "Logistic regression" = "logistic",
                     "Survival analysis" = "surv",
                     "Anova test" = "anova",
                     "Chisquare test" = "chisq",
                     "Correlation" = "corr",
                     "Bootstrap CI" = "BCa")),
    radioButtons("type", "Select the plot file
type",choices=list("png","pdf"))),
  # Show the output and plot
  mainPanel(
    h3(textOutput("caption")),
    plotOutput("myPlot"),
    downloadButton("save1", "Save the plot"),
    verbatimTextOutput("regSum")))
</code>```

Server

```<code>server<-function(input, output, session) {
 # Import data
 data1 <- reactive({
 inFile <- input$file1
 if(is.null(file)){return()} [1]
 read_sas(inFile$datapath)
 })
 observeEvent(input$file1,{
 updateSelectInput(session,"varlist",choices=c(colnames(data1())))
 })
 # Compute the forumla text
 formulaText <- reactive({
 paste(input$dep,"~", input$indep)
 })
 output$caption <- renderText({
 formulaText()
 })
# Data
 new_data<-reactive({
raw_data <- data1()
 if (input$Model == 'surv') {
 df<-data.frame(
 Time = raw_data[[input$dep]],
 trt = raw_data[[input$varlist]],
 cen = raw_data[[input$indep]],
 sub = raw_data[[input$subvar]]
 )
 if (input$subval == "") { df2<-df }
 else { df2<-subset(df,sub==input$subval) }
 return(df2)
 }
 if (input$Model == 'logistic') {
 df<-data.frame(
 y = raw_data[[input$dep]],
 trt = raw_data[[input$indep]],
 sub = raw_data[[input$subvar]]
 )
 if (input$subval == "") { df2<-df }
 else { df2<-subset(df,sub==input$subval) }
 return(df2)
 }
# Statistics
 new_fit<-reactive({
 if (input$Model == 'surv') {
 fit<-survfit(Surv(Time , cen) ~ trt , data = new_data())
 return(fit)
 }
 if (input$Model == 'logistic') {
 fit<-glm(y ~ factor(trt), data = new_data(), family = "binomial")
 print(paste('Odds ratio:',exp(coef(fit))))
 return(fit)
 }
# Graph
 new_plot<-reactive({
 if (input$Model == 'surv') {
 graph<-ggsurvplot(new_fit(), risk.table = TRUE, pval = TRUE, data =
new_data())
 return(graph)
 }
 if (input$Model == 'logistic') {
 graph<-ggplot(new_data(),aes(y))+geom_bar()+facet_wrap('trt')
+labs(x=input$dep)
 return(graph)
 }
# Generate the plot
 output$myPlot <- renderPlot({
 new_plot()
 })
# Generate the summary of analysis
 output$regSum <- renderPrint({
 summary(new_fit())
 })
# Save the plot
 output$save1 <- downloadHandler(
 filename = function() {
 paste("myplot",input$type,sep=".")
 },
 content = function(file){
 if(input$type=="png") png(file)
 else pdf(file)
 print(new_plot())
 dev.off()
 })
}
</code>```

答:
I have no idea if this will suffice: your code is missing close }) in just about all reactive(. blocks. Additionally, you are not covering most of your input$Model possibilities, which means most of your reactive blocks return nothing, perhaps by-design, perhaps something else.

Try this code. Notice that indentation, while subjective, provides a clearer context of what "close" }) is tied to which reactive({. In the end, if you ever see any nesting of reactive, observe, or render*, you're doing something wrong.

server<-function(input, output, session) {
  # Import data
  data1 <- reactive({
    inFile <- input$file1
    if(is.null(file)){return()} [1]
    read_sas(inFile$datapath)
  })
  observeEvent(input$file1,{
    updateSelectInput(session,"varlist",choices=c(colnames(data1())))
  })
  # Compute the forumla text
  formulaText <- reactive({
    paste(input$dep,"~", input$indep)
  })
  output$caption <- renderText({
    formulaText()
  })
  # Data
  new_data<-reactive({
    raw_data <- data1()
    if (input$Model == 'surv') {
      df<-data.frame(
        Time = raw_data[[input$dep]],
        trt = raw_data[[input$varlist]],
        cen = raw_data[[input$indep]],
        sub = raw_data[[input$subvar]]
      )
      if (input$subval == "") { df2<-df }
      else { df2<-subset(df,sub==input$subval) }
      return(df2)
    }
    if (input$Model == 'logistic') {
      df<-data.frame(
        y = raw_data[[input$dep]],
        trt = raw_data[[input$indep]],
        sub = raw_data[[input$subvar]]
      )
      if (input$subval == "") { df2<-df }
      else { df2<-subset(df,sub==input$subval) }
      return(df2)
    }
  })
  # Statistics
  new_fit<-reactive({
    if (input$Model == 'surv') {
      fit<-survfit(Surv(Time , cen) ~ trt , data = new_data())
      return(fit)
    }
    if (input$Model == 'logistic') {
      fit<-glm(y ~ factor(trt), data = new_data(), family = "binomial")
      print(paste('Odds ratio:',exp(coef(fit))))
      return(fit)
    }
  })
  # Graph
  new_plot<-reactive({
    if (input$Model == 'surv') {
      graph<-ggsurvplot(new_fit(), risk.table = TRUE, pval = TRUE, data = new_data())
      return(graph)
    }
    if (input$Model == 'logistic') {
      graph<-ggplot(new_data(),aes(y))+geom_bar()+facet_wrap('trt') +
        labs(x=input$dep)
      return(graph)
    }
  })
  # Generate the plot
  output$myPlot <- renderPlot({
    new_plot()
  })
  # Generate the summary of analysis
  output$regSum <- renderPrint({
    summary(new_fit())
  })
  # Save the plot
  output$save1 <- downloadHandler(
    filename = function() {
      paste("myplot",input$type,sep=".")
    },
    content = function(file) {
      if(input$type=="png") png(file)
      else pdf(file)
      print(new_plot())
      dev.off()
    }
  )
}
```

Title: debugging the server part of the shiny

Body:
I've tried to run this app several times, but the server part of the code doesn't work at all, even though it should be complete. The UI part works perfectly; however, when I attempt to run the server part, it just stops. I can't really see the issue
I would be grateful if you could look at the code.

ui<-pageWithSidebar(
  headerPanel("Statistical analysis"),
  sidebarPanel(
    fileInput('file1', 'Select your file',
              accept = c(
                'text/csv',
                'text/comma-separated-values','.csv',
                '.sas7bdat'
              )
    ),
    splitLayout(
      textInput("subvar","Subset Variable:"),

      textInput("subval","Subset Value:")),
    splitLayout(
      textInput("dep","Dependent variable:"),
      textInput("indep","Independent variable:")),
    selectInput("varlist","Pick Treatment
variable:",choices=c(colnames(data()))),
    selectInput("Model","Model:",
                list("Linear regression" = "lm",
                     "Logistic regression" = "logistic",
                     "Survival analysis" = "surv",
                     "Anova test" = "anova",
                     "Chisquare test" = "chisq",
                     "Correlation" = "corr",
                     "Bootstrap CI" = "BCa")),
    radioButtons("type", "Select the plot file
type",choices=list("png","pdf"))),
  # Show the output and plot
  mainPanel(
    h3(textOutput("caption")),
    plotOutput("myPlot"),
    downloadButton("save1", "Save the plot"),
    verbatimTextOutput("regSum")))

Server

server<-function(input, output, session) {
 # Import data
 data1 <- reactive({
 inFile <- input$file1
 if(is.null(file)){return()} [1]
 read_sas(inFile$datapath)
 })
 observeEvent(input$file1,{
 updateSelectInput(session,"varlist",choices=c(colnames(data1())))
 })
 # Compute the forumla text
 formulaText <- reactive({
 paste(input$dep,"~", input$indep)
 })
 output$caption <- renderText({
 formulaText()
 })
# Data
 new_data<-reactive({
raw_data <- data1()
 if (input$Model == 'surv') {
 df<-data.frame(
 Time = raw_data[[input$dep]],
 trt = raw_data[[input$varlist]],
 cen = raw_data[[input$indep]],
 sub = raw_data[[input$subvar]]
 )
 if (input$subval == "") { df2<-df }
 else { df2<-subset(df,sub==input$subval) }
 return(df2)
 }
 if (input$Model == 'logistic') {
 df<-data.frame(
 y = raw_data[[input$dep]],
 trt = raw_data[[input$indep]],
 sub = raw_data[[input$subvar]]
 )
 if (input$subval == "") { df2<-df }
 else { df2<-subset(df,sub==input$subval) }
 return(df2)
 }
# Statistics
 new_fit<-reactive({
 if (input$Model == 'surv') {
 fit<-survfit(Surv(Time , cen) ~ trt , data = new_data())
 return(fit)
 }
 if (input$Model == 'logistic') {
 fit<-glm(y ~ factor(trt), data = new_data(), family = "binomial")
 print(paste('Odds ratio:',exp(coef(fit))))
 return(fit)
 }
# Graph
 new_plot<-reactive({
 if (input$Model == 'surv') {
 graph<-ggsurvplot(new_fit(), risk.table = TRUE, pval = TRUE, data =
new_data())
 return(graph)
 }
 if (input$Model == 'logistic') {
 graph<-ggplot(new_data(),aes(y))+geom_bar()+facet_wrap('trt')
+labs(x=input$dep)
 return(graph)
 }
# Generate the plot
 output$myPlot <- renderPlot({
 new_plot()
 })
# Generate the summary of analysis
 output$regSum <- renderPrint({
 summary(new_fit())
 })
# Save the plot
 output$save1 <- downloadHandler(
 filename = function() {
 paste("myplot",input$type,sep=".")
 },
 content = function(file){
 if(input$type=="png") png(file)
 else pdf(file)
 print(new_plot())
 dev.off()
 })
}


来源: stackexchange

问:
How to Create Tweet with OAuth 2.0 (Twitter API v2) using tweepy
I try to create a tweet using tweepy under OAuth 2.0 instead of OAuth 1.0a. In other words, I am looking for an OAuth 2.0 equivalent of the following code.

```<code>import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
client = tweepy.Client(
    consumer_key=consumer_key, consumer_secret=consumer_secret,
    access_token=access_token, access_token_secret=access_token_secret
)
response = client.create_tweet(
    text="This Tweet was Tweeted using Tweepy and Twitter API v2!"
)
print(f"https://twitter.com/user/status/{response.data['id']}")
</code>```

Following Twitter's guide on OAuth 2.0 Making requests on behalf of users and tweepy's guide on OAuth 2.0 Authorization Code Flow with PKCE (User Context), I am able to obtain an access token, which is passed instead of the Bearer Token.

```<code>import tweepy

client_id = ""
redirect_uri = ""
client_secret = ""

oauth2_user_handler = tweepy.OAuth2UserHandler(
    client_id=client_id,
    redirect_uri=redirect_uri,
    scope=["tweet.read", "tweet.write", "users.read"],
    client_secret=client_secret
)

print(oauth2_user_handler.get_authorization_url())

authorization_response = input("--> ")

access_token = oauth2_user_handler.fetch_token(
    authorization_response
)

client = tweepy.Client(access_token)
</code>```

It seems that Twitter's implementation of OAuth 2.0 is in unfinished as of Dec '21. However, in Feb '21, the steps to post Tweets on behalf of users under OAuth 2.0 was described in another forum.

答:
A solution is found.</p>
```<code>client = tweepy.Client(access_token["access_token"])

response = client.create_tweet(
    text="This Tweet was Tweeted using Tweepy and Twitter API v2!",
    user_auth=False
)
print(f"https://twitter.com/user/status/{response.data['id']}")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to create a tweet using tweepy under OAuth 2.0 instead of OAuth 1.0a. In other words, I am looking for an OAuth 2.0 equivalent of the following code.

import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
client = tweepy.Client(
    consumer_key=consumer_key, consumer_secret=consumer_secret,
    access_token=access_token, access_token_secret=access_token_secret
)
response = client.create_tweet(
    text="This Tweet was Tweeted using Tweepy and Twitter API v2!"
)
print(f"https://twitter.com/user/status/{response.data['id']}")

Following Twitter's guide on OAuth 2.0 Making requests on behalf of users and tweepy's guide on OAuth 2.0 Authorization Code Flow with PKCE (User Context), I am able to obtain an access token, which is passed instead of the Bearer Token.

import tweepy

client_id = ""
redirect_uri = ""
client_secret = ""

oauth2_user_handler = tweepy.OAuth2UserHandler(
    client_id=client_id,
    redirect_uri=redirect_uri,
    scope=["tweet.read", "tweet.write", "users.read"],
    client_secret=client_secret
)

print(oauth2_user_handler.get_authorization_url())

authorization_response = input("--> ")

access_token = oauth2_user_handler.fetch_token(
    authorization_response
)

client = tweepy.Client(access_token)

It seems that Twitter's implementation of OAuth 2.0 is in unfinished as of Dec '21. However, in Feb '21, the steps to post Tweets on behalf of users under OAuth 2.0 was described in another forum.

Body:
A solution is found.

client = tweepy.Client(access_token["access_token"])

response = client.create_tweet(
    text="This Tweet was Tweeted using Tweepy and Twitter API v2!",
    user_auth=False
)
print(f"https://twitter.com/user/status/{response.data['id']}")


问:
How can I use Python requests to paginate api calls with offset parameter
I need to make repeated api calls as there is a limit on each call of 1000 records. There are about 20,000 total records of which I test them , keep a sample, then need request the next 1000. The offset parameter is available.

```<code>p = getpass.getpass()
url = ("https://example.api.com/api/1.0/devices/all/?offset={}&include_cols=asset_no,name,service_level,building&type=physical"
r = requests.get(url, auth=HTTPBasicAuth('admin', p))
data = json.loads(r.text)
payload = data["Devices"]
</code>```

offset value should increment by 1000 each api call, (ex. offset = 1000, offset = 2000, offset = 3000, etc) until all pages retrieved.

How could I create a function that makes paginated api calls using this offset parameter? I believe a generator is what is needed, but I'm unable to understand the examples I've found, with the offset parameter I need to use.

答:
In a general sense, pagination with limit and offset is a little formula :

```<code>number_of_offsets = total_items / limit_per_page
</code>```

The offset parameter controls the starting point within the collection of resource results.

If you have a collection of 15 items to be retrieved from a resource and you specify limit=5, you can retrieve the entire set of results in 3 successive requests by varying the offset value: offset=0, offset=5, and offset=10.

The number offsets become the number of pages. So in our example above it would be :

```<code>offset = 0 : page 1 - 5/15
offset = 5 : page 2 - 10/15
offset = 10: page 3 - 15/15
</code>```

Body:
I need to make repeated api calls as there is a limit on each call of 1000 records. There are about 20,000 total records of which I test them , keep a sample, then need request the next 1000. The offset parameter is available.

p = getpass.getpass()
url = ("https://example.api.com/api/1.0/devices/all/?offset={}&include_cols=asset_no,name,service_level,building&type=physical"
r = requests.get(url, auth=HTTPBasicAuth('admin', p))
data = json.loads(r.text)
payload = data["Devices"]

offset value should increment by 1000 each api call, (ex. offset = 1000, offset = 2000, offset = 3000, etc) until all pages retrieved.

How could I create a function that makes paginated api calls using this offset parameter? I believe a generator is what is needed, but I'm unable to understand the examples I've found, with the offset parameter I need to use.

Body:
In a general sense, pagination with limit and offset is a little formula :

number_of_offsets = total_items / limit_per_page

The offset parameter controls the starting point within the collection of resource results.

If you have a collection of 15 items to be retrieved from a resource and you specify limit=5, you can retrieve the entire set of results in 3 successive requests by varying the offset value: offset=0, offset=5, and offset=10.

The number offsets become the number of pages. So in our example above it would be :

offset = 0 : page 1 - 5/15
offset = 5 : page 2 - 10/15
offset = 10: page 3 - 15/15


问:
Styling <input type="file">, cropped box-shadow and outline
I want my <input type="file" /> button to look like all my other buttons.

Now, it's easy with all browsers thanks to :

::file-selector-button (Firefox)

::-webkit-file-upload-button

::-ms-browse

This is what this input looks like in ShadowDOM :

```<code><input type="file">
  <button tabindex="-1">
  <label>No file selected</label>
</input>
</code>```

So, the button is within the input box so everything that's outsize this box is cropped (box-shadow and outline).

Do you have an idea to avoid this crop ?

I mean, I can add padding to the input but I have to calculate the border-radius spread, outline offset, correct padding with negative margins, etc.

I'm looking for something more flexible.

EDIT : overflow:visible on the input is not working. I don't know why

EDIT 2 : This is the default styling from resource://gre-ressource/forms.css (Firefox)

```<code>input[type=file] {
  white-space: nowrap !important;
  overflow: hidden !important;
  overflow-clip-box: padding-box;
  color: unset;

  /* Revert rules which apply on all inputs. */
  appearance: none;
  -moz-default-appearance: none;
  cursor: default;

  border: none;
  background-color: transparent;
  padding: unset;
}
</code>```

This explains why overflow:visible doesn't work. Also, playing with overflow-clip-box doesn't changes anything. It is set in forms.css however specifications say this property is not implemented in Firefox. Plus, there is a bug associated

EDIT 3 : Defining overflow: visible !important seems to override user agent styling, and it cancels overflow-clip-box: padding-box; as well but the overflowing content is still not visible.

Any workaround idea ?

:root {
  --base-color: purple;
  --file-border: 2px solid var(--base-color);
  --file-border-radius: 5px;
  --file-background: gold;
  --file-box-shadow: 2px 2px 3px 0 #888;
  --file-outline: 2px dadshed blue;
}

::file-selector-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-webkit-file-upload-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-ms-browse {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

[type=file]:focus::file-selector-button{
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-webkit-file-upload-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-ms-browse {
  outline: var(--file-outline);
  outline-offset: 2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Cropped box-shadow and outline (on focus) :
<p>
  <input type="file" />
</p>
With padding :
<p>
  <input type="file" style="padding: 5px"/>
</p>
With padding + correction :
<p>
  <input type="file" style="padding: 5px;margin-left:-5px;margin-top:-5px"/>
</p></code>```

答:
I mean, I can add padding to the input but I have to calculate the border-radius spread, outline offset, correct padding with negative margins, etc.

You don't have to do the calculations, just use padding-bottom directly instead of setting padding on all sides.

Edit: You can also make another custom variable to control the padding in one place. Since you have no issue setting the shadow as custom property as well. See the snippet below:

:root {
  --base-color: purple;
  --file-border: 2px solid var(--base-color);
  --file-border-radius: 5px;
  --file-background: gold;
  --file-box-shadow: 2px 2px 3px 0 #888;
  --file-outline: 2px dashed blue;
  --file-padding: 0 0 5px 0;
}

::file-selector-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

::-webkit-file-upload-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

::-ms-browse {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

[type=file]:focus::file-selector-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}

[type=file]:focus::-webkit-file-upload-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}

[type=file]:focus::-ms-browse {
  outline: var(--file-outline);
  outline-offset: 2px;
}

input{
  padding: var(--file-padding);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  <input type="file" />
</p></code>```

Body:
I want my <input type="file" /> button to look like all my other buttons.

Now, it's easy with all browsers thanks to :

::file-selector-button (Firefox)

::-webkit-file-upload-button

::-ms-browse

This is what this input looks like in ShadowDOM :

<input type="file">
  <button tabindex="-1">
  No file selected
</input>

So, the button is within the input box so everything that's outsize this box is cropped (box-shadow and outline).

Do you have an idea to avoid this crop ?

I mean, I can add padding to the input but I have to calculate the border-radius spread, outline offset, correct padding with negative margins, etc.

I'm looking for something more flexible.

EDIT : overflow:visible on the input is not working. I don't know why

EDIT 2 : This is the default styling from resource://gre-ressource/forms.css (Firefox)

input[type=file] {
  white-space: nowrap !important;
  overflow: hidden !important;
  overflow-clip-box: padding-box;
  color: unset;

  /* Revert rules which apply on all inputs. */
  appearance: none;
  -moz-default-appearance: none;
  cursor: default;

  border: none;
  background-color: transparent;
  padding: unset;
}

This explains why overflow:visible doesn't work. Also, playing with overflow-clip-box doesn't changes anything. It is set in forms.css however specifications say this property is not implemented in Firefox. Plus, there is a bug associated

EDIT 3 : Defining overflow: visible !important seems to override user agent styling, and it cancels overflow-clip-box: padding-box; as well but the overflowing content is still not visible.

Any workaround idea ?

:root {
  --base-color: purple;
  --file-border: 2px solid var(--base-color);
  --file-border-radius: 5px;
  --file-background: gold;
  --file-box-shadow: 2px 2px 3px 0 #888;
  --file-outline: 2px dadshed blue;
}

::file-selector-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-webkit-file-upload-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}
::-ms-browse {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

[type=file]:focus::file-selector-button{
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-webkit-file-upload-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}
[type=file]:focus::-ms-browse {
  outline: var(--file-outline);
  outline-offset: 2px;
}

Cropped box-shadow and outline (on focus) :

  <input type="file" />

With padding :

  <input type="file" style="padding: 5px"/>

With padding + correction :

  <input type="file" style="padding: 5px;margin-left:-5px;margin-top:-5px"/>

Body:
I mean, I can add padding to the input but I have to calculate the border-radius spread, outline offset, correct padding with negative margins, etc.

You don't have to do the calculations, just use padding-bottom directly instead of setting padding on all sides.

Edit: You can also make another custom variable to control the padding in one place. Since you have no issue setting the shadow as custom property as well. See the snippet below:

:root {
  --base-color: purple;
  --file-border: 2px solid var(--base-color);
  --file-border-radius: 5px;
  --file-background: gold;
  --file-box-shadow: 2px 2px 3px 0 #888;
  --file-outline: 2px dashed blue;
  --file-padding: 0 0 5px 0;
}

::file-selector-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

::-webkit-file-upload-button {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

::-ms-browse {
  color: var(--base-color);
  border-radius: var(--file-border-radius);
  background-color: var(--file-background);
  border: var(--file-border);
  box-shadow: var(--file-box-shadow);
}

[type=file]:focus::file-selector-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}

[type=file]:focus::-webkit-file-upload-button {
  outline: var(--file-outline);
  outline-offset: 2px;
}

[type=file]:focus::-ms-browse {
  outline: var(--file-outline);
  outline-offset: 2px;
}

input{
  padding: var(--file-padding);
}

<p>
  <input type="file" />
</p>


问:
How to use Jquery to print each value from an XML file?
Anyone know how to go through an XML file using Jquery and print the tag names and text values from only the tags that have a text value in them?

Example, html that outputs like:

```<code>id: 00130000004EQCpAAO
updated: 2011-08-16 19:40:51
account_type: Vendor Other
active: 1
someprop_d: 0
</code>```

that comes from XML like:

```<code><accounts>
    <id>00130000004EQCpAAO</id>
    <updated>2011-08-16 19:40:51</updated>
    <account_type>Vendor Other</account_type>
    <someprop_a/>
    <active_c>1</active_c>
    <someprob_b/>
    <someprop_c/>
    <someprop_d>0</someprop_d>
</accounts>
</code>```

The Jquery:

```<code>var mystr = $.ajax({
    type: 'GET',
    url: '/js/data_account.xml',
    async: false,
    data: {
        key: "value"
    },
    dataType: "xml",
    success: function(data) {
        var xml = $(data)
        //var $accountid = xml.find("id").text();
        // do something relevant here
        //return something;
    },
    error: function() {
        alert("error: call failed");
    }
});
$('parentElement').append(mystr);
</code>```

答:
```<code>$(xml).find('accounts').each(function(){
  var $accountid =  $(this).find('id').text();
  alert($accountid);
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Anyone know how to go through an XML file using Jquery and print the tag names and text values from only the tags that have a text value in them?

Example, html that outputs like:

id: 00130000004EQCpAAO
updated: 2011-08-16 19:40:51
account_type: Vendor Other
active: 1
someprop_d: 0

that comes from XML like:

<accounts>
    <id>00130000004EQCpAAO</id>
    <updated>2011-08-16 19:40:51</updated>
    <account_type>Vendor Other</account_type>
    <someprop_a/>
    <active_c>1</active_c>
    <someprob_b/>
    <someprop_c/>
    <someprop_d>0</someprop_d>
</accounts>

The Jquery:

var mystr = $.ajax({
    type: 'GET',
    url: '/js/data_account.xml',
    async: false,
    data: {
        key: "value"
    },
    dataType: "xml",
    success: function(data) {
        var xml = $(data)
        //var $accountid = xml.find("id").text();
        // do something relevant here
        //return something;
    },
    error: function() {
        alert("error: call failed");
    }
});
$('parentElement').append(mystr);


问:
How do instructions from a program get sent to different memory levels? Are they pre-loaded when the chips are manufactured for the first time?
I had asked a question earlier on how data gets pushed to registers in the CPU

My question now is, do instructions required for program execution get moved to memory by the compiler the same way data gets pushed?

If the answer to the first question is yes, then what do CPU designers load into the cache/main memory when it comes fresh out of the foundry? Since no program has ever been run before on the chip, are any instructions preloaded into memory at the time of designing and manufacturing of the chip so that it executes a pre-defined set of sequences when it is powered up for the first time?

答:
How do instructions from a program get sent to different memory levels?

The processor pulls them into caches using the program counter aka instruction pointer that refers to the next instruction to execute.

Are they pre-loaded when the chips are manufactured for the first time?

Not for general purpose programs.  Only special environments burn programs into permanent storage, like ROM, which may happen for booting a computer or for an embedded system.  General purpose programs rely on an operating system to associate their code & data with memory.

My question now is, do instructions required for program execution get moved to memory by the compiler the same way data gets pushed?

Recap: The compiler follows the statements & expressions of the (source) code program, translating them into machine code instructions & data; these machine code instructions instruct the processor what to do to carry out the high level language program.  This includes machine code instructions to load data into CPU registers, sometimes so that the data is closer to the CPU so quicker to work with, other times because that is the only way that the CPU can operate on the data (by the machine code instruction set of the processor).

There is a difference between having machine code instructions in memory and having them in the processor.

The compiler does not, per se, command instructions to be moved into the processor.  The processor is an interpreter of machine code instructions, and all on its own it will pull instructions into itself for execution.  The compiler lays out sequences of instructions and the CPU automatically brings them in for execution — that is is the CPU's purpose.

Program code (modulo modern caches) is too large to directly load into the CPU.  Thus, programs are stored in main memory, like data that is too large to fit directly in the CPU.  Program code is sequences of machine code instructions.  Since these instructions are stored in memory, each individual instruction has a unique memory address!  The processor refers to instructions by their memory address, and by their memory address has a concept of what instruction is executing now and what will/should execute next.

The mechanism for this goes to the instruction pointer register (in intel-speak) or the program counter register (in virtually all other machine code languages), but the concept is the same: there is a fundamental register inside the processor whose job is to hold the address of machine code instruction that is executing now, and whose job is also to change to indicate what instruction to execute next.

As mentioned, the processor is an interpreter of machine code instructions.  It uses its internal program counter in what is called a fetch-execute pattern, where it demands of the memory system the value of the machine code instruction to execute next.  That demand, a request to read an some particular memory address, may cause cache misses, or page fault (or both), which ultimately, through conspiracy of both the processor and the operating system, will cause machine code instructions to load into memory, to load in to caches, to load into the processor itself.

Each machine code instruction of the program informs the processor what machine code instruction to execute next.  The program can move the program counter backwards to re-execute instructions that have already executed (forming loops) or move it forward to exit a loop or skip a then or else statement.  There is a cooperation between the processor and the machine code, where the processor is told, at every step, what machine code to execute next.  So, the machine code program is directing the execution of sequences of the machine code program, but it is the processor that is doing the actual execution (though under the direction of the program).

Would we say that the compiler tells the processor to load instruction to execute into the CPU?  Sort of, but not quite as explicitly as commands to load data into the CPU.

The compiler creates a sequences in the machine code program used to control execution, so I would say it implicitly tells the processor what instructions to bring into the caches.  Otherwise (modulo memory mapping and page faulting) the machine code instructions are already in memory (by the operating system associating the memory with the program code & data), and the processor will manage caches to keep frequently executing instructions in the higher levels of the cache.

what do CPU designers load into the cache/main memory when it comes fresh out of the foundry?

Nothing, the memory is considered blank and can be repurposed.  On some systems we cannot even guarantee the value of each memory cell when the processor boots.  Where the program (as a file on disc) specifies the proper initial values for memory, then the original values that were in memory, from boot or from another program's execution, are replaced with those specified values.  Other memory used by the program is zeroed out before use.

are any instructions preloaded into memory at the time of designing and manufacturing of the chip so that it executes a pre-defined set of sequences when it is powered up for the first time?

Yes, sometime some memories are hard-coded with code and data that helps the computer boot.  This is not a general purpose way that programs run.


问:
What am I doing wrong here to get the ratio summed up?
So I've got this issue where for some reason my ratio isn't being added up, I'm still new to C and I don't understand what's going on. Here's the code in question. TotalRatio isn't working at all for me.

All of the code should be working fine and here's what I should be getting instead of it ending abruptly

What is the total length of the track, in feet?
1000
What is the maximum length of a train, in feet?
42
Your ride can have at most 112 people on it at one time.
This can be achieved with trains of 4 cars.
AVG Ratio: 0.451

```<code>#include <stdio.h>

#define FIRST_CAR_LENGTH 10
#define NORMAL_CAR_LENGTH 8
#define CAR_CAPACITY 4

int main(){

    int totalLength, trainLength, quarter, totalPeople, surplus, totalCar, i, currentLength, currentTrains, currentCars, currentPeople, cumulCarLength,number;
    printf("What is the total length of the track, in feet?\n");
    scanf("%d", &totalLength);
    printf("What is the maximum length of a train, in feet?\n");
    scanf("%d", &trainLength);
    quarter=totalLength/4;
    totalCar=(trainLength-FIRST_CAR_LENGTH)/NORMAL_CAR_LENGTH+1;
    int numberA=totalCar;
    float ratio[number], totalRatio, average, currentRatio;
    int variables[totalCar];
    int max_People=0;
    int max_Cars=0;
    for (i=0; i<totalCar;i++){
        if(i==0){
            currentLength=FIRST_CAR_LENGTH+(NORMAL_CAR_LENGTH*i);
            max_People=quarter/currentLength*CAR_CAPACITY;
            max_Cars=1;
            currentCars=1;
            currentTrains=quarter/currentLength;
            currentPeople=currentTrains*CAR_CAPACITY;
            cumulCarLength=currentTrains*currentLength;
            ratio[i]=(float)currentPeople/cumulCarLength;
        } else {
            currentLength=FIRST_CAR_LENGTH+(NORMAL_CAR_LENGTH*i);
            currentCars=(currentLength-FIRST_CAR_LENGTH)/NORMAL_CAR_LENGTH+1;
            currentTrains=quarter/currentLength;
            currentPeople=currentTrains*currentCars*CAR_CAPACITY;
            if(max_People<currentPeople){
                max_People=currentPeople;
                max_Cars=currentCars;
            }
            cumulCarLength=currentTrains*currentLength;
            ratio[i]=(float)currentPeople/cumulCarLength;
        }
    }
    printf("Your ride can have at most %d people on it at one time.\n",max_People);
    printf("This can be achieved with trains of %d cars.\n",max_Cars);

    totalRatio=0;
    for (i=0; i<totalCar;i++){
        //something is wrong with this line of code
        totalRatio += ratio[i];
    }
    printf("AVG Ratio: %f",totalRatio);

    return 0;
}
</code>```

答:
well for a start this is wrong

```<code>float ratio[number]
</code>```

because you haven't initialized number so it has a random value. Fix that first

Body:
So I've got this issue where for some reason my ratio isn't being added up, I'm still new to C and I don't understand what's going on. Here's the code in question. TotalRatio isn't working at all for me.

All of the code should be working fine and here's what I should be getting instead of it ending abruptly

What is the total length of the track, in feet?
1000
What is the maximum length of a train, in feet?
42
Your ride can have at most 112 people on it at one time.
This can be achieved with trains of 4 cars.
AVG Ratio: 0.451

#include <stdio.h>

#define FIRST_CAR_LENGTH 10
#define NORMAL_CAR_LENGTH 8
#define CAR_CAPACITY 4

int main(){

    int totalLength, trainLength, quarter, totalPeople, surplus, totalCar, i, currentLength, currentTrains, currentCars, currentPeople, cumulCarLength,number;
    printf("What is the total length of the track, in feet?\n");
    scanf("%d", &totalLength);
    printf("What is the maximum length of a train, in feet?\n");
    scanf("%d", &trainLength);
    quarter=totalLength/4;
    totalCar=(trainLength-FIRST_CAR_LENGTH)/NORMAL_CAR_LENGTH+1;
    int numberA=totalCar;
    float ratio[number], totalRatio, average, currentRatio;
    int variables[totalCar];
    int max_People=0;
    int max_Cars=0;
    for (i=0; i<totalCar;i++){
        if(i==0){
            currentLength=FIRST_CAR_LENGTH+(NORMAL_CAR_LENGTH*i);
            max_People=quarter/currentLength*CAR_CAPACITY;
            max_Cars=1;
            currentCars=1;
            currentTrains=quarter/currentLength;
            currentPeople=currentTrains*CAR_CAPACITY;
            cumulCarLength=currentTrains*currentLength;
            ratio[i]=(float)currentPeople/cumulCarLength;
        } else {
            currentLength=FIRST_CAR_LENGTH+(NORMAL_CAR_LENGTH*i);
            currentCars=(currentLength-FIRST_CAR_LENGTH)/NORMAL_CAR_LENGTH+1;
            currentTrains=quarter/currentLength;
            currentPeople=currentTrains*currentCars*CAR_CAPACITY;
            if(max_People<currentPeople){
                max_People=currentPeople;
                max_Cars=currentCars;
            }
            cumulCarLength=currentTrains*currentLength;
            ratio[i]=(float)currentPeople/cumulCarLength;
        }
    }
    printf("Your ride can have at most %d people on it at one time.\n",max_People);
    printf("This can be achieved with trains of %d cars.\n",max_Cars);

    totalRatio=0;
    for (i=0; i<totalCar;i++){
        //something is wrong with this line of code
        totalRatio += ratio[i];
    }
    printf("AVG Ratio: %f",totalRatio);

    return 0;
}

Body:
well for a start this is wrong

float ratio[number]

because you haven't initialized number so it has a random value. Fix that first


问:
Count occurrences of a given integer in an array using recursion
Without using a loop, I'm trying to count the number of times a given integer is in an array using recursion. I keep getting a StackOverflow error and I can't figure out why.

```<code>public static int countOccurrences(int[] arr, int n) {
    if (arr.length == 0) {
        return 0;
    }
    if (arr[0] == n) {
        return 1 + countOccurrences(arr, n - 1);
    }
    return countOccurrences(arr, n - 1);
}
</code>```

}

答:
the problem with above code is that the base condition will never be satisfied as you are never trying to reduce the length of the array. To keep track of length traversed, you can use a variable that starts from end to start ( or from start to end your choice ) . And let's say , num is the value that you want to count. Then you can change your code to like this :

```<code>public class CountFrequency {

                public static void main(String[] args) {
                    int A[] = { 1, 2, 3, 4, 5, 5 };
                    int count = countOccurences(A, 5);
                    System.out.println(count);
                }

                private static int countOccurences(int[] arr, int num) {
                    return helper(arr, num, arr.length - 1);

                }

                private static int helper(int[] arr, int num, int i) {
                    if (i == -1) {
                        return 0;
                    }
                    if (arr[i] == num)
                        return 1 + helper(arr, num, i - 1);
                    else
                        return helper(arr, num, i - 1);
                }
      }
</code>```

and the output is

```<code>2
</code>```

Body:
Without using a loop, I'm trying to count the number of times a given integer is in an array using recursion. I keep getting a StackOverflow error and I can't figure out why.

public static int countOccurrences(int[] arr, int n) {
    if (arr.length == 0) {
        return 0;
    }
    if (arr[0] == n) {
        return 1 + countOccurrences(arr, n - 1);
    }
    return countOccurrences(arr, n - 1);
}

}

Body:
the problem with above code is that the base condition will never be satisfied as you are never trying to reduce the length of the array. To keep track of length traversed, you can use a variable that starts from end to start ( or from start to end your choice ) . And let's say , num is the value that you want to count. Then you can change your code to like this :

public class CountFrequency {

                public static void main(String[] args) {
                    int A[] = { 1, 2, 3, 4, 5, 5 };
                    int count = countOccurences(A, 5);
                    System.out.println(count);
                }

                private static int countOccurences(int[] arr, int num) {
                    return helper(arr, num, arr.length - 1);

                }

                private static int helper(int[] arr, int num, int i) {
                    if (i == -1) {
                        return 0;
                    }
                    if (arr[i] == num)
                        return 1 + helper(arr, num, i - 1);
                    else
                        return helper(arr, num, i - 1);
                }
      }

and the output is

2


问:
LinkedIn-API r_emailaddress not retruning email
I am useing the linkedin Oauth API(my app is fully working and setup correctly with the scopes r_emailaddress) and I can't seem to return email, I can return it with curl but not with my code,

```<code>const userEmail = await fetch("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))", {
            method: "GET",
            headers: {
                "Authorization": "Bearer " + accessToken,
                "Accept": "application/json"
            }
        });
        const userMail = await userEmail.json();
        console.log(userMail)
</code>```

this code returns elements: [ { 'handle~': [Object], handle: 'urn:li:emailAddress:8238802378' } ]

should "elements": [{"handle~": {"emailAddress": "example.dev@gmail.com"},"handle": "urn:li:emailAddress:8238802378"}]

答: LOL, this fixed it userMail.elements[0]["handle~"].emailAddress, thanks to Xrysh✅

Body:
I am useing the linkedin Oauth API(my app is fully working and setup correctly with the scopes r_emailaddress) and I can't seem to return email, I can return it with curl but not with my code,

const userEmail = await fetch("https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))", {
            method: "GET",
            headers: {
                "Authorization": "Bearer " + accessToken,
                "Accept": "application/json"
            }
        });
        const userMail = await userEmail.json();
        console.log(userMail)

this code returns elements: [ { 'handle~': [Object], handle: 'urn:li:emailAddress:8238802378' } ]

should "elements": [{"handle~": {"emailAddress": "example.dev@gmail.com"},"handle": "urn:li:emailAddress:8238802378"}]


问:
Discord.js isnt sending the embed due to non-empty string error
```<code>const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}
</code>```

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

答:
```<code>        let new1 = new discord.MessageEmbed()
        new1.setTitle(city + `'s Weather`)
        new1.setDescription('bruh pls work')
        new1.setColor('#0099ff')
        new1.addFields('**Location**', `Latitude:`+ lat,true)
        new1.addFields('**Temperature**', `${temp}℃`,true)
        new1.setTimestamp()
        new1.setFooter({ text: 'Information by Open-Weather' })

        interaction.reply({embeds:[new1]})
</code>```

replace with:

```<code>        let new1 = new discord.MessageEmbed()
        new1.setTitle(city + `'s Weather`)
        new1.setDescription('bruh pls work')
        new1.setColor('#0099ff')
        new1.addFields(
            {name:'**Location**', value: `Latitude:+ lat`, inline: true },
            {name:'**Temperature**', value: `${temp}℃`, inline: true },
        )
        new1.setTimestamp()
        new1.setFooter({ text: 'Information by Open-Weather' })

        interaction.reply({embeds:[new1]})
</code>```

Body:
const { SlashCommandBuilder } = require('@discordjs/builders')
const discord = require('discord.js')
const open = require('openweather-api-node');
module.exports = {
    data: new SlashCommandBuilder()
        .setName('weather')
        .setDescription('Shows the Weather condition of a place')
        .addStringOption(option =>
            option.setName('city')
                .setDescription('Name of the city')
                .setRequired(true)),

    async execute(Discord, client, interaction) {

        let city = interaction.options.getString('city');

        let weather = new open({
            key: process.env.WEATHER,

            units: 'metric'
        })

        weather.setLanguage('en')
     let info = await   weather.getCurrent({ locationName: city })

      if(!info) return interaction.reply({content:"Oops "})
            //location
            var lon = info.lon.toString()
            var lat = info.lat.toString()
            let Timezone = info.timezone

            //Temperature
            var temp =  info.weather.temp.cur.toString()
            let feel_like = info.weather.feels_like.cur
            let min = info.weather.temp.min
            let max =info.weather.temp.max

            //air condition
            let pressure = info.weather.pressure
            let humidity = info.weather.humidity + '%'
            let wind = info.weather.wind.speed + 'km/h'

            //description

            let sky = info.weather.description
            let status = info.weather.main

        console.log(temp)
        console.log(lon)
        console.log(lat)

            let new1 = new discord.MessageEmbed()
            new1.setTitle(city + `'s Weather`)
            new1.setDescription('bruh pls work')
            new1.setColor('#0099ff')
            new1.addFields('**Location**', `Latitude:`+ lat,true)
            new1.addFields('**Temperature**', `${temp}℃`,true)
            new1.setTimestamp()
            new1.setFooter({ text: 'Information by Open-Weather' })

            interaction.reply({embeds:[new1]})

    }
}

So this is my code
the temp,lan,lat variables were number but i changed them into string
and even checked with the typeof method
It gave me a string

But still i'm facing out this error called RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty string

Please help me if you know whats the solution

Body:
        let new1 = new discord.MessageEmbed()
        new1.setTitle(city + `'s Weather`)
        new1.setDescription('bruh pls work')
        new1.setColor('#0099ff')
        new1.addFields('**Location**', `Latitude:`+ lat,true)
        new1.addFields('**Temperature**', `${temp}℃`,true)
        new1.setTimestamp()
        new1.setFooter({ text: 'Information by Open-Weather' })

        interaction.reply({embeds:[new1]})

replace with:

        let new1 = new discord.MessageEmbed()
        new1.setTitle(city + `'s Weather`)
        new1.setDescription('bruh pls work')
        new1.setColor('#0099ff')
        new1.addFields(
            {name:'**Location**', value: `Latitude:+ lat`, inline: true },
            {name:'**Temperature**', value: `${temp}℃`, inline: true },
        )
        new1.setTimestamp()
        new1.setFooter({ text: 'Information by Open-Weather' })

        interaction.reply({embeds:[new1]})


问:
SwiftUI: Animating border width animates also the height
I am trying to create a "glowing" animation to certain view in my app but the animation behaves a bit weird. The correct animation can be seen to the time widget and the wrong behaviour to the exercise widget.

You can find the code bellow:

```<code>    struct InformationPanel:View {

    @Environment(\.fontSize) private var fontSize
    @State var isAnimating = false
    let glows:Bool
    let title:String
    let value:String?
    let icon:String

    var body: some View {
        ZStack {
            Color(Asset.Colors.semiTransparentBackground.color)
                .opacity(0.43)
                .cornerRadius(20)
                .overlay(
                    RoundedRectangle(cornerRadius: 20, style: .circular)
                        .stroke(Color.white, lineWidth: glows && isAnimating ? 4 : 0)
                        .animation(.linear(duration: 1).repeatForever(),value: isAnimating)
                        .scaleEffect(1)

                        .opacity(0.65)
                        .onAppear {
                            isAnimating = true
                        }

                )

            VStack(alignment: .leading,spacing: 8) {
                HStack(spacing:8) {
                    CircularImage(image: icon)

                    Text(title)
                        .font(.system(size: 20, weight: .bold))
                        .frame(maxWidth: .infinity,alignment: .leading)
                        .foregroundColor(.black)
                }
                .padding(.top,2)
                .padding(.leading,6)

                Text(value ?? " ")
                    .font(.system(size: fontSize ?? 30, weight: .bold))
                    .frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .center)
                    .foregroundColor(.black)
                    .multilineTextAlignment(.center)
                    .lineLimit(3)
                    .minimumScaleFactor(0.5)
            }
            .padding(.vertical,4)
            .animation(nil,value: isAnimating)
        }
    }
}

struct WorkoutView:View {

    @StateObject private var viewModel:WorkoutViewModel

    @State private var exercisingState:WorkoutState = .startingUp
    @State private var timeRemaining:Int? = nil
    @State private var duration:TimeInterval = 0
    @State private var isPaused:Bool = false
    @State private var exersice:String? = nil
    @State private var nextExersice:String? = nil
    @State private var round = 0

    private let timer = Timer.TimerPublisher(interval: 1,tolerance: 0.1, runLoop: .main, mode: .common).autoconnect()

    init(routine:Routine) {
        self.init(viewModel: WorkoutViewModel(routine: routine))
    }

    init(viewModel:WorkoutViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    @ViewBuilder
    private func backgroundView() -> some View {
        switch exercisingState {
        case .startingUp, .roundReset:
            Color.yellow
        case .rest:
            Color.red
        case .work:
            Color.green
        }
    }

    private func control(image:String,action:() -> Void) -> some View {

        Button(action: {
            self.isPaused.toggle()
        }) {
            Image(image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 20)

        }
        .frame(width: 50, height: 50)
        .background(.white)
        .clipShape(Circle())
    }

    private func titleBarView() -> some View {
        HStack(spacing:16) {

            control(image: isPaused ? "play" : "pause",action: {
                isPaused.toggle()

            })

            Spacer()

            Text(exercisingState.title)
                .lineLimit(1)
                .font(.system(size: 24, weight: .bold))
                .foregroundColor(.black)

            Spacer()

            control(image: "stop",action: {
                isPaused.toggle()

            })

        }
    }

    private func countdownBar() -> some View{

        AnimationView(duration: duration ,paused: $isPaused) { progress in

            CountDownProgressView(progress: progress)
                .frame(width: 30)
        }
        .id(duration)
        .id(exercisingState)
    }

    private func timeWidget() -> some View {
        InformationPanel(
            glows: true,
            title: Strings.time,
            value: timeRemaining?.description,
            icon:  Asset.Images.timeWidget.name
        )
            .fontSize(85)
    }

    private func roundWidget() -> some View {
        InformationPanel(
            glows: false, title: Strings.round,
            value: round.description,
            icon: Asset.Images.roundWidget.name
        )
            .fontSize(45)
    }

    private func exerciseWidget() -> some View {
        InformationPanel(
            glows: true,
            title:Strings.exercise,
            value: exersice,
            icon: Asset.Images.exerciseWidget.name
        )
            .fontSize(25)
    }

    private func nextExerciseWidget() -> some View {
        InformationPanel(
            glows: false,
            title: Strings.next,
            value: nextExersice,
            icon: Asset.Images.nextWidget.name
        )
            .fontSize(25)

    }

    private func main() -> some View {
        VStack(spacing:16) {

            titleBarView()

            HStack(spacing:16) {
                GeometryReader { reader in
                    VStack(spacing:16) {

                        timeWidget()
                            .frame(height:150)

                        roundWidget()
                            .frame(height:100)

                        exerciseWidget()
                        nextExerciseWidget()
                    }

                }
                countdownBar()
            }

        }

        .padding(.horizontal,16)

    }

    var body: some View {
        ZStack {

            self.backgroundView()
                .transition(.opacity.animation(.linear(duration: 0.24)))
                .ignoresSafeArea()

            main()
                .padding(.vertical,8)

        }
        .navigationBarHidden(true)
        .onAppear(perform: viewModel.start)
        .model(viewModel: viewModel)
        .onReceive(viewModel.$currentPhase) { currentPhase in
            guard let currentPhase = currentPhase else { return }
            exercisingState = currentPhase.state
            duration = currentPhase.durationTimeInterval
            timeRemaining = currentPhase.duration
            exersice = currentPhase.state.excercise?.name
            nextExersice = currentPhase.state.nextExcercise?.name
            round = currentPhase.round
        }
        .onReceive(timer) { tick in
            guard !viewModel.isFinished else { return }
            guard !isPaused else { return }
            guard let timeRemaining = timeRemaining else { return }
            if timeRemaining <= 1 {
                viewModel.next()
            }
            self.timeRemaining = timeRemaining - 1

        }

    }
}
</code>```

答:
It appears each of the RoundedRectangles is doing the same thing, which would make sense as you are using .stroke() on them. When you change the .stroke() width on a built in shape like this, one half of that border is added on to the size of the shape. However, changing that to .strokeBorder() will keep in inside the bounds of the shape. Paul Hudson has a good explanation. You can see it very clearly in the following code:

```<code>struct GlowingRect: View {
    @State var isAnimating: Bool = false

    var body: some View {
        VStack {
            Color.blue
                .opacity(0.43)
                .cornerRadius(20)
                .frame(width: 300, height: 100)
                .overlay(
                    RoundedRectangle(cornerRadius: 20, style: .circular)
                        .strokeBorder(Color.orange, lineWidth: isAnimating ? 20:0)
                        .animation(.linear(duration: 2).repeatForever(), value: isAnimating)
                        .scaleEffect(1)

                        .opacity(0.65)
                        .onAppear {
                            isAnimating = true
                        }
                )
            Color.green
                .opacity(0.43)
                .cornerRadius(20)
                .frame(width: 300, height: 100)
                .overlay(
                    RoundedRectangle(cornerRadius: 20, style: .circular)
                        .stroke(Color.orange, lineWidth: isAnimating ? 20:0)
                        .animation(.linear(duration: 2).repeatForever(), value: isAnimating)
                        .scaleEffect(1)

                        .opacity(0.65)
                        .onAppear {
                            isAnimating = true
                        }
                )
        }
    }
}
</code>```

Body:
I am trying to create a "glowing" animation to certain view in my app but the animation behaves a bit weird. The correct animation can be seen to the time widget and the wrong behaviour to the exercise widget.

You can find the code bellow:

    struct InformationPanel:View {

    @Environment(\.fontSize) private var fontSize
    @State var isAnimating = false
    let glows:Bool
    let title:String
    let value:String?
    let icon:String

    var body: some View {
        ZStack {
            Color(Asset.Colors.semiTransparentBackground.color)
                .opacity(0.43)
                .cornerRadius(20)
                .overlay(
                    RoundedRectangle(cornerRadius: 20, style: .circular)
                        .stroke(Color.white, lineWidth: glows && isAnimating ? 4 : 0)
                        .animation(.linear(duration: 1).repeatForever(),value: isAnimating)
                        .scaleEffect(1)

                        .opacity(0.65)
                        .onAppear {
                            isAnimating = true
                        }

                )

            VStack(alignment: .leading,spacing: 8) {
                HStack(spacing:8) {
                    CircularImage(image: icon)

                    Text(title)
                        .font(.system(size: 20, weight: .bold))
                        .frame(maxWidth: .infinity,alignment: .leading)
                        .foregroundColor(.black)
                }
                .padding(.top,2)
                .padding(.leading,6)

                Text(value ?? " ")
                    .font(.system(size: fontSize ?? 30, weight: .bold))
                    .frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .center)
                    .foregroundColor(.black)
                    .multilineTextAlignment(.center)
                    .lineLimit(3)
                    .minimumScaleFactor(0.5)
            }
            .padding(.vertical,4)
            .animation(nil,value: isAnimating)
        }
    }
}

struct WorkoutView:View {

    @StateObject private var viewModel:WorkoutViewModel

    @State private var exercisingState:WorkoutState = .startingUp
    @State private var timeRemaining:Int? = nil
    @State private var duration:TimeInterval = 0
    @State private var isPaused:Bool = false
    @State private var exersice:String? = nil
    @State private var nextExersice:String? = nil
    @State private var round = 0

    private let timer = Timer.TimerPublisher(interval: 1,tolerance: 0.1, runLoop: .main, mode: .common).autoconnect()

    init(routine:Routine) {
        self.init(viewModel: WorkoutViewModel(routine: routine))
    }

    init(viewModel:WorkoutViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }

    @ViewBuilder
    private func backgroundView() -> some View {
        switch exercisingState {
        case .startingUp, .roundReset:
            Color.yellow
        case .rest:
            Color.red
        case .work:
            Color.green
        }
    }

    private func control(image:String,action:() -> Void) -> some View {

        Button(action: {
            self.isPaused.toggle()
        }) {
            Image(image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 20)

        }
        .frame(width: 50, height: 50)
        .background(.white)
        .clipShape(Circle())
    }

    private func titleBarView() -> some View {
        HStack(spacing:16) {

            control(image: isPaused ? "play" : "pause",action: {
                isPaused.toggle()

            })

            Spacer()

            Text(exercisingState.title)
                .lineLimit(1)
                .font(.system(size: 24, weight: .bold))
                .foregroundColor(.black)

            Spacer()

            control(image: "stop",action: {
                isPaused.toggle()

            })

        }
    }

    private func countdownBar() -> some View{

        AnimationView(duration: duration ,paused: $isPaused) { progress in

            CountDownProgressView(progress: progress)
                .frame(width: 30)
        }
        .id(duration)
        .id(exercisingState)
    }

    private func timeWidget() -> some View {
        InformationPanel(
            glows: true,
            title: Strings.time,
            value: timeRemaining?.description,
            icon:  Asset.Images.timeWidget.name
        )
            .fontSize(85)
    }

    private func roundWidget() -> some View {
        InformationPanel(
            glows: false, title: Strings.round,
            value: round.description,
            icon: Asset.Images.roundWidget.name
        )
            .fontSize(45)
    }

    private func exerciseWidget() -> some View {
        InformationPanel(
            glows: true,
            title:Strings.exercise,
            value: exersice,
            icon: Asset.Images.exerciseWidget.name
        )
            .fontSize(25)
    }

    private func nextExerciseWidget() -> some View {
        InformationPanel(
            glows: false,
            title: Strings.next,
            value: nextExersice,
            icon: Asset.Images.nextWidget.name
        )
            .fontSize(25)

    }

    private func main() -> some View {
        VStack(spacing:16) {

            titleBarView()

            HStack(spacing:16) {
                GeometryReader { reader in
                    VStack(spacing:16) {

                        timeWidget()
                            .frame(height:150)

                        roundWidget()
                            .frame(height:100)

                        exerciseWidget()
                        nextExerciseWidget()
                    }

                }
                countdownBar()
            }

        }

        .padding(.horizontal,16)

    }

    var body: some View {
        ZStack {

            self.backgroundView()
                .transition(.opacity.animation(.linear(duration: 0.24)))
                .ignoresSafeArea()

            main()
                .padding(.vertical,8)

        }
        .navigationBarHidden(true)
        .onAppear(perform: viewModel.start)
        .model(viewModel: viewModel)
        .onReceive(viewModel.$currentPhase) { currentPhase in
            guard let currentPhase = currentPhase else { return }
            exercisingState = currentPhase.state
            duration = currentPhase.durationTimeInterval
            timeRemaining = currentPhase.duration
            exersice = currentPhase.state.excercise?.name
            nextExersice = currentPhase.state.nextExcercise?.name
            round = currentPhase.round
        }
        .onReceive(timer) { tick in
            guard !viewModel.isFinished else { return }
            guard !isPaused else { return }
            guard let timeRemaining = timeRemaining else { return }
            if timeRemaining <= 1 {
                viewModel.next()
            }
            self.timeRemaining = timeRemaining - 1

        }

    }
}

Body:
It appears each of the RoundedRectangles is doing the same thing, which would make sense as you are using .stroke() on them. When you change the .stroke() width on a built in shape like this, one half of that border is added on to the size of the shape. However, changing that to .strokeBorder() will keep in inside the bounds of the shape. Paul Hudson has a good explanation. You can see it very clearly in the following code:

struct GlowingRect: View {
    @State var isAnimating: Bool = false

    var body: some View {
        VStack {
            Color.blue
                .opacity(0.43)
                .cornerRadius(20)
                .frame(width: 300, height: 100)
                .overlay(
                    RoundedRectangle(cornerRadius: 20, style: .circular)
                        .strokeBorder(Color.orange, lineWidth: isAnimating ? 20:0)
                        .animation(.linear(duration: 2).repeatForever(), value: isAnimating)
                        .scaleEffect(1)

                        .opacity(0.65)
                        .onAppear {
                            isAnimating = true
                        }
                )
            Color.green
                .opacity(0.43)
                .cornerRadius(20)
                .frame(width: 300, height: 100)
                .overlay(
                    RoundedRectangle(cornerRadius: 20, style: .circular)
                        .stroke(Color.orange, lineWidth: isAnimating ? 20:0)
                        .animation(.linear(duration: 2).repeatForever(), value: isAnimating)
                        .scaleEffect(1)

                        .opacity(0.65)
                        .onAppear {
                            isAnimating = true
                        }
                )
        }
    }
}


问:
struggling to install python package via amazon sagemaker
I am using Amazon Sagemaker and trying to install gaapi4py package via anaconda python3 notebook.

So far I've tried the following commands:

```<code>%conda install gaapi4py
</code>```

and

```<code>conda install gaapi4py

Got same error:

Collecting package metadata (current_repodata.json): failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/conda-forge/linux-64/current_repodata.json>
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
'https://conda.anaconda.org/conda-forge/linux-64'

Note: you may need to restart the kernel to use updated packages.
</code>```

Alternatively I've tried the below but it failed as well:

```<code>pip install gaapi4py
</code>```

Error text:

```<code>WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803c50>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c8035f8>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803550>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803400>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803358>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
ERROR: Could not find a version that satisfies the requirement gaapi4py (from versions: none)
ERROR: No matching distribution found for gaapi4py
WARNING: You are using pip version 20.0.2; however, version 20.3 is available.
You should consider upgrading via the '/home/ec2-user/anaconda3/envs/python3/bin/python -m pip install --upgrade pip' command.
Note: you may need to restart the kernel to use updated packages.
</code>```

What am I doing wrong? All previous packages worked well.

UPD:

Tried also as recommended in amazon book:

```<code>import sys
!{sys.executable} -m pip install gaapi4py
</code>```

and

```<code>import sys
!conda install -y --prefix {sys.prefix} gaapi4py
</code>```

Both didn't work neither, getting same errors as above.

答: After talking back-in-forth with our IT department I figured out that custom libraries installation was blocked for security reasons.</p>

Body:
I am using Amazon Sagemaker and trying to install gaapi4py package via anaconda python3 notebook.

So far I've tried the following commands:

%conda install gaapi4py

and

conda install gaapi4py

Got same error:

Collecting package metadata (current_repodata.json): failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/conda-forge/linux-64/current_repodata.json>
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
'https://conda.anaconda.org/conda-forge/linux-64'

Note: you may need to restart the kernel to use updated packages.

Alternatively I've tried the below but it failed as well:

pip install gaapi4py

Error text:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803c50>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c8035f8>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803550>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803400>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f657c803358>: Failed to establish a new connection: [Errno 101] Network is unreachable',)': /simple/gaapi4py/
ERROR: Could not find a version that satisfies the requirement gaapi4py (from versions: none)
ERROR: No matching distribution found for gaapi4py
WARNING: You are using pip version 20.0.2; however, version 20.3 is available.
You should consider upgrading via the '/home/ec2-user/anaconda3/envs/python3/bin/python -m pip install --upgrade pip' command.
Note: you may need to restart the kernel to use updated packages.

What am I doing wrong? All previous packages worked well.

UPD:

Tried also as recommended in amazon book:

import sys
!{sys.executable} -m pip install gaapi4py

and

import sys
!conda install -y --prefix {sys.prefix} gaapi4py

Both didn't work neither, getting same errors as above.


问:
PHP formula needed to calculate a simple format
I am trying to take an amount and convert it to a units type format...

For example:

( note: don't worry about the dollar sign )

Total is $400

I need to display it as 4 * 100

Another Example

Total is $450

I need to display it as 4 * 100 |  50 * 1

So another words there are only 100 and 1 units.

I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?

答:
Use the modulus operator to break down the number (this kind of thing is good to learn how to do because you'll need it for many other units conversion tasks like seconds -> minutes & seconds conversion):</p>

```<code>$value=450;
$ones = $value % 100;
$hundreds = floor($value / 100);
echo "$hundreds * 100 | $ones * 1\n";
</code>```

Body:
Use the modulus operator to break down the number (this kind of thing is good to learn how to do because you'll need it for many other units conversion tasks like seconds -> minutes & seconds conversion):

$value=450;
$ones = $value % 100;
$hundreds = floor($value / 100);
echo "$hundreds * 100 | $ones * 1\n";


问:
Why do the persist() and cache() methods shorten DataFrame plan in Spark?
I am working with spark version 3.0.1. I am generating a large dataframe. At the end calculations, I save dataframe plan in json format. I need him.
But there is one problem. If I persist a DataFrame, then its plan in json format is completely truncated. That is, all data lineage disappears.

For example, I do this:

```<code>val myDf: DataFrame = ???
val myPersistDf = myDf.persist
  //toJSON method cuts down my plan
val jsonPlan = myPersistDf.queryExecution.optimizedPlan.toJSON
</code>```

As a result, only information about the current columns remains.
But for example, if you use spark version 3.1.2, then there is no such problem. That is, the plan is not cut.
It is also worth saying that if you do not call the toJSON method, then the plan is not cut:

```<code>// Plan is not being cut.
val textPlan = myPersistDf.queryExecution.optimizedPlan.toString
</code>```

I made a small test project to make sure of this:
https://github.com/MinorityMeaning/CutPlanDataFrame

Please help me figure it out.
I need to get the full plan in json format.

UPD(1):

Now I'm trying to convert each node to json separately. Now it doesn't work perfectly, but I think we need to go in this direction.

```<code>val jsonPlan = s"[${getJson(result_df.queryExecution.optimizedPlan).mkString(",")}]"

  def getJson(lp: TreeNode[_]): Seq[String] = {
    val children = (lp.innerChildren ++ lp.children.map(c => c.asInstanceOf[TreeNode[_]])).distinct
    JsonMethods.compact(JsonMethods.render(JsonMethods.parse(lp.toJSON)(0))) +:
      getJson(t.asInstanceOf[TreeNode[_]])))
      children.flatMap(t => getJson(t))
  }
</code>```

UPD(2):

OK, here's how I finally solved this problem.
I downloaded spark 3.0.1 from github. Then replaced the TreeNode class in this project with a file from spark 3.1.2. Recompiled the project.
As a result, I received a package spark-catalyst_2.12-3.0.1.jar
Which replaced the existing original packaging.

There is no option to switch to another version of spark. I have not found any other solutions to the problem.
Thank you guys for prompting. Your advice helped.

答:
You can cherry pick below 2 commits into spark 3.0.1 to fix this issue.</p>
```<code>* 1603775934 - [SPARK-35411][SQL][FOLLOWUP] Handle Currying Product while serializing TreeNode to JSON (8 months ago) <Tengfei Huang>
* 9804f07c17 - [SPARK-35411][SQL] Add essential information while serializing TreeNode to json (9 months ago) <Tengfei Huang>
</code>```

Body:
I am working with spark version 3.0.1. I am generating a large dataframe. At the end calculations, I save dataframe plan in json format. I need him.
But there is one problem. If I persist a DataFrame, then its plan in json format is completely truncated. That is, all data lineage disappears.

For example, I do this:

val myDf: DataFrame = ???
val myPersistDf = myDf.persist
  //toJSON method cuts down my plan
val jsonPlan = myPersistDf.queryExecution.optimizedPlan.toJSON

As a result, only information about the current columns remains.
But for example, if you use spark version 3.1.2, then there is no such problem. That is, the plan is not cut.
It is also worth saying that if you do not call the toJSON method, then the plan is not cut:

// Plan is not being cut.
val textPlan = myPersistDf.queryExecution.optimizedPlan.toString

I made a small test project to make sure of this:
https://github.com/MinorityMeaning/CutPlanDataFrame

Please help me figure it out.
I need to get the full plan in json format.

UPD(1):

Now I'm trying to convert each node to json separately. Now it doesn't work perfectly, but I think we need to go in this direction.

val jsonPlan = s"[${getJson(result_df.queryExecution.optimizedPlan).mkString(",")}]"

  def getJson(lp: TreeNode[_]): Seq[String] = {
    val children = (lp.innerChildren ++ lp.children.map(c => c.asInstanceOf[TreeNode[_]])).distinct
    JsonMethods.compact(JsonMethods.render(JsonMethods.parse(lp.toJSON)(0))) +:
      getJson(t.asInstanceOf[TreeNode[_]])))
      children.flatMap(t => getJson(t))
  }

UPD(2):

OK, here's how I finally solved this problem.
I downloaded spark 3.0.1 from github. Then replaced the TreeNode class in this project with a file from spark 3.1.2. Recompiled the project.
As a result, I received a package spark-catalyst_2.12-3.0.1.jar
Which replaced the existing original packaging.

There is no option to switch to another version of spark. I have not found any other solutions to the problem.
Thank you guys for prompting. Your advice helped.

Body:
You can cherry pick below 2 commits into spark 3.0.1 to fix this issue.

* 1603775934 - [SPARK-35411][SQL][FOLLOWUP] Handle Currying Product while serializing TreeNode to JSON (8 months ago) <Tengfei Huang>
* 9804f07c17 - [SPARK-35411][SQL] Add essential information while serializing TreeNode to json (9 months ago) <Tengfei Huang>


问:
Phaser 3 extend create function
How do I extend phaser 3 create function in an extended scene without overwriting the original create function?

```<code>class Level2 extends GameScene {
constructor() {
  super('Level2')
  this.heights = [5, 4, null, 4, 6, 4, 6, 5, 5];
  // Add Level2 weather here
  this.weather = 'twilight';
  this.skyColor = 'sunset';
  this.music = 'bass';
  this.platform = 'platform2'
  this.large = 'bg31';
  this.medium = 'bg21';
}

create() {
  console.log("HELLO CRETE FROM LEVLE 2")

  gameState.bat = this.physics.add.group({
    allowGravity: false
  });
  this.time.addEvent({
    callback: this.batGenLoop,
    delay: 5000,
    callbackScope: this,
    loop: true,
  });

  gameState.bat.move = this.tweens.add({
    targets: gameState.bat.getChildren(),
    //.map(function (c) { return c.body.velocity })
    x: 0,
    ease: 'Linear',
    duration: 7000,
    repeat: 0,
    yoyo: false,
  });

}//create

batGenLoop() {
  console.log('batman')

  const yCoord = Math.random() * 600;
  gameState.bat.create(1890, yCoord, 'bat');
  //.setScale(3).body.setSize(140, 320, true).setOffset(100, 20)

}
</code>```

}

this is my attempt but it overwrites the original create function in gameScene.
Level 2 is extended from gameScene.

答:
If you don't want to override the create function, I see two easy options:

don't write a create in the new Scene, than when you call the function, the function of the base class is used.

or call the function of the base class, in the new function, like this:

```<code>class Level2 extends GameScene {
    ...
    create(){
         super.create(); // calling the function of the base class
         ...
    }
}
</code>```

With the second option, you can  write some code after calling super.create(), to adapt the functionality.

Title: Phaser 3 extend create function

Body:
How do I extend phaser 3 create function in an extended scene without overwriting the original create function?

class Level2 extends GameScene {
constructor() {
  super('Level2')
  this.heights = [5, 4, null, 4, 6, 4, 6, 5, 5];
  // Add Level2 weather here
  this.weather = 'twilight';
  this.skyColor = 'sunset';
  this.music = 'bass';
  this.platform = 'platform2'
  this.large = 'bg31';
  this.medium = 'bg21';
}

create() {
  console.log("HELLO CRETE FROM LEVLE 2")

  gameState.bat = this.physics.add.group({
    allowGravity: false
  });
  this.time.addEvent({
    callback: this.batGenLoop,
    delay: 5000,
    callbackScope: this,
    loop: true,
  });

  gameState.bat.move = this.tweens.add({
    targets: gameState.bat.getChildren(),
    //.map(function (c) { return c.body.velocity })
    x: 0,
    ease: 'Linear',
    duration: 7000,
    repeat: 0,
    yoyo: false,
  });

}//create

batGenLoop() {
  console.log('batman')

  const yCoord = Math.random() * 600;
  gameState.bat.create(1890, yCoord, 'bat');
  //.setScale(3).body.setSize(140, 320, true).setOffset(100, 20)

}

}

this is my attempt but it overwrites the original create function in gameScene.
Level 2 is extended from gameScene.

Body:
If you don't want to override the create function, I see two easy options:

don't write a create in the new Scene, than when you call the function, the function of the base class is used.

or call the function of the base class, in the new function, like this:

class Level2 extends GameScene {
    ...
    create(){
         super.create(); // calling the function of the base class
         ...
    }
}

With the second option, you can  write some code after calling super.create(), to adapt the functionality.


问:
Algorithm that reduces an array of integers to a single value
Given an array of integers.

Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.

That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.

At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.

The process continues until there's only one element left in the array.

Here is the code I have:

```<code>        int[] arr= {1,2,3,4,5}; // orignal array

        int[] newArr = new int[arr.length];
        int[] result = new int[newArr.length];
        for(int i = 1;i<n;i++)
        {

            newArr = Arrays.copyOf(arr, arr.length - i);
            System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.

            //System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
            //result[0] = newArr[newArr.length - 1];
            //result = Arrays.copyOf(result,result.length-1);
            //System.out.println(Arrays.toString(result));
        }
</code>```

output should come like this

```<code>[1, 2, 3, 4, 5] // original array

[1, 2, 3, 4] // array after deletion

[4, 1, 2, 3] // array after rotaion

[4, 1, 2]// again after deletion from previous array

[2, 4, 1]// array after rotaion

[2, 4]// again after deletion from previous array

[4, 2]// array after rotation

[4]

final answer is 4
</code>```

答:
Your code will perform much better if you get rid of these intermediate arrays. If you have a few million elements in the array, your algorithm will require to allocate in memory a few million arrays which doesn't sound very performance-wise. From the clean-coding point of view, only one defensive copy is needed to preserve the source array intact. And the required operations will be done in place.

The core of this algorithm is the variable len defined inside the method rotateAndDelete(), which denotes the boundary of the "current array".

```<code>    public static void main(String[] args) {
        System.out.println(rotateAndDelete(new int[]{1, 2, 3, 4, 5}));
    }
</code>```
```<code>    public static int rotateAndDelete(int[] source) {
        int len = source.length;
        int[] copy = Arrays.copyOf(source, len);
        while (len > 1) {
            len--; // deletion in-place - the last valid index becomes less by one
            rotate(copy, len);
        }
        return copy[0];
    }
</code>```
```<code>    private static void rotate(int[] arr, int len) {
        int first = arr[len - 1];
        // shift all elements to the right
        for (int i = len - 1; i >= 1; i--) {
            arr[i] = arr[i - 1];
        }
        arr[0] = first;
    }
</code>```

output

```<code>4
</code>```

Body:
Given an array of integers.

Inside the for loop, firstly, I'm making a copy of the initial array to a new array. Then the last element is being removed and the rest elements are being rotated by one to the right.

That means the element at index 0 will go to index 1, and so on, and the element will go to index 0.

At this point, I am facing the issue. The previous result has to be a source for the subsequent iteration.

The process continues until there's only one element left in the array.

Here is the code I have:

        int[] arr= {1,2,3,4,5}; // orignal array

        int[] newArr = new int[arr.length];
        int[] result = new int[newArr.length];
        for(int i = 1;i<n;i++)
        {

            newArr = Arrays.copyOf(arr, arr.length - i);
            System.out.println(Arrays.toString(newArr));// here i am deleting one array at last,
// code works fine upto here. but i want the next step as below commented code to perform in loop. which i am really unable to do.

            //System.arraycopy(newArr, 0, result, 1, newArr.length - 1);
            //result[0] = newArr[newArr.length - 1];
            //result = Arrays.copyOf(result,result.length-1);
            //System.out.println(Arrays.toString(result));
        }

output should come like this

[1, 2, 3, 4, 5] // original array

[1, 2, 3, 4] // array after deletion

[4, 1, 2, 3] // array after rotaion

[4, 1, 2]// again after deletion from previous array

[2, 4, 1]// array after rotaion

[2, 4]// again after deletion from previous array

[4, 2]// array after rotation

[4]

final answer is 4

Body:
Your code will perform much better if you get rid of these intermediate arrays. If you have a few million elements in the array, your algorithm will require to allocate in memory a few million arrays which doesn't sound very performance-wise. From the clean-coding point of view, only one defensive copy is needed to preserve the source array intact. And the required operations will be done in place.

The core of this algorithm is the variable len defined inside the method rotateAndDelete(), which denotes the boundary of the "current array".

    public static void main(String[] args) {
        System.out.println(rotateAndDelete(new int[]{1, 2, 3, 4, 5}));
    }

    public static int rotateAndDelete(int[] source) {
        int len = source.length;
        int[] copy = Arrays.copyOf(source, len);
        while (len > 1) {
            len--; // deletion in-place - the last valid index becomes less by one
            rotate(copy, len);
        }
        return copy[0];
    }

    private static void rotate(int[] arr, int len) {
        int first = arr[len - 1];
        // shift all elements to the right
        for (int i = len - 1; i >= 1; i--) {
            arr[i] = arr[i - 1];
        }
        arr[0] = first;
    }

output

4


问:
Splitting csv file based on a particular column using Python
I'm a Python beginner, and have made a few basic scripts. My latest challenge is to take a very large csv file (10gb+) and split it into a number of smaller files, based on the value of a particular variable in each row.

For example, the file may look like this:

```<code>Category,Title,Sales
"Books","Harry Potter",1441556
"Books","Lord of the Rings",14251154
"Series", "Breaking Bad",6246234
"Books","The Alchemist",12562166
"Movie","Inception",1573437
</code>```

And I would want to split the file into separate files:
Books.csv, Series.csv, Movie.csv

In reality there will be hundreds of categories, and they will not be sorted. In this case they are in the first column but in future they may not be.

I've found a few solutions online but nothing in Python. There is a really simple AWK command that can do this in one line, but I cannot get access to AWK in work.

I've written the following code which works, but I think it is probably very inefficient. Can anybody suggest how to speed it up?

```<code>import csv

#Creates empty set - this will be used to store the values that have already been used
filelist = set()

#Opens the large csv file in "read" mode
with open('//directory/largefile', 'r') as csvfile:

    #Read the first row of the large file and store the whole row as a string (headerstring)
    read_rows = csv.reader(csvfile)
    headerrow = next(read_rows)
    headerstring=','.join(headerrow)

    for row in read_rows:

        #Store the whole row as a string (rowstring)
        rowstring=','.join(row)

        #Defines filename as the first entry in the row - This could be made dynamic so that the user inputs a column name to use
        filename = (row[0])

        #This basically makes sure it is not looking at the header row.
        if filename != "Category":

            #If the filename is not in the filelist set, add it to the list and create new csv file with header row.
            if filename not in filelist:
                filelist.add(filename)
                with open('//directory/subfiles/' +str(filename)+'.csv','a') as f:
                    f.write(headerstring)
                    f.write("\n")
                    f.write(rowstring)
                    f.write("\n")
                    f.close()
            #If the filename is in the filelist set, append the current row to the existing csv file.
            else:
                with open('//directory/subfiles/' +str(filename)+'.csv','a') as f:
                    f.write(rowstring)
                    f.write("\n")
                    f.close()
</code>```

Thanks!

答:
Another option is to use the groupby function provided by Pandas for DataFrames.

```<code>for (n), group in df.groupby(['category']):
    group.to_csv(f'../desired/dir/split/{n}.csv')
</code>```

here it is as a full script ready to go:

```<code>import pandas as pd

def split_csv(csvFilePath, newDirPath, splitKey):
    df = pd.read_csv(csvFilePath)
    for (n), group in df.groupby([splitKey]):
        group.to_csv(f'{newDirPath}{n}.csv')

# https://stackoverflow.com/questions/419163/what-does-if-name-main-do
if __name__ == "__main__":
    split_csv(
        csvFilePath='../desired/dir/myfile.csv', # CHANGE ME
        newDirPath='../desired/dir/myfile/', # CHANGE ME
        splitKey='category'  # CHANGE ME
    )
</code>```

Body:
I'm a Python beginner, and have made a few basic scripts. My latest challenge is to take a very large csv file (10gb+) and split it into a number of smaller files, based on the value of a particular variable in each row.

For example, the file may look like this:

Category,Title,Sales
"Books","Harry Potter",1441556
"Books","Lord of the Rings",14251154
"Series", "Breaking Bad",6246234
"Books","The Alchemist",12562166
"Movie","Inception",1573437

And I would want to split the file into separate files:
Books.csv, Series.csv, Movie.csv

In reality there will be hundreds of categories, and they will not be sorted. In this case they are in the first column but in future they may not be.

I've found a few solutions online but nothing in Python. There is a really simple AWK command that can do this in one line, but I cannot get access to AWK in work.

I've written the following code which works, but I think it is probably very inefficient. Can anybody suggest how to speed it up?

import csv

#Creates empty set - this will be used to store the values that have already been used
filelist = set()

#Opens the large csv file in "read" mode
with open('//directory/largefile', 'r') as csvfile:

    #Read the first row of the large file and store the whole row as a string (headerstring)
    read_rows = csv.reader(csvfile)
    headerrow = next(read_rows)
    headerstring=','.join(headerrow)

    for row in read_rows:

        #Store the whole row as a string (rowstring)
        rowstring=','.join(row)

        #Defines filename as the first entry in the row - This could be made dynamic so that the user inputs a column name to use
        filename = (row[0])

        #This basically makes sure it is not looking at the header row.
        if filename != "Category":

            #If the filename is not in the filelist set, add it to the list and create new csv file with header row.
            if filename not in filelist:
                filelist.add(filename)
                with open('//directory/subfiles/' +str(filename)+'.csv','a') as f:
                    f.write(headerstring)
                    f.write("\n")
                    f.write(rowstring)
                    f.write("\n")
                    f.close()
            #If the filename is in the filelist set, append the current row to the existing csv file.
            else:
                with open('//directory/subfiles/' +str(filename)+'.csv','a') as f:
                    f.write(rowstring)
                    f.write("\n")
                    f.close()

Thanks!

Body:
Another option is to use the groupby function provided by Pandas for DataFrames.

for (n), group in df.groupby(['category']):
    group.to_csv(f'../desired/dir/split/{n}.csv')

here it is as a full script ready to go:

import pandas as pd

def split_csv(csvFilePath, newDirPath, splitKey):
    df = pd.read_csv(csvFilePath)
    for (n), group in df.groupby([splitKey]):
        group.to_csv(f'{newDirPath}{n}.csv')

# https://stackoverflow.com/questions/419163/what-does-if-name-main-do
if __name__ == "__main__":
    split_csv(
        csvFilePath='../desired/dir/myfile.csv', # CHANGE ME
        newDirPath='../desired/dir/myfile/', # CHANGE ME
        splitKey='category'  # CHANGE ME
    )