问:
Query on an indexed geometry column using CockroachDB on Windows
I'm getting the following error on cockroachDB when running a GIS query on an column with indexed GIS data:

```<code>[XXUUU] ERROR: geos: error during GEOS init: geos: cannot load GEOS from dir "/usr/local/lib/cockroach": geos error: failed to execute dlsym Hint: Ensure you have the spatial libraries installed as per the instructions in https://www.cockroachlabs.com/docs/v21.1/install-cockroachdb-windows
</code>```

It worked before indexing the column and after removing the index.

CockroachDB runs on on a remote server using windows, and my local computer is using windows and connecting to the DB through Datagrip. Changing the environment variables on the server and on my local computer, including adding a "\" to the end of the path, did not address the issue.

What is blocking me from using indexing on my queries?

答:
After getting an answer from the CockroachDB team, I'll post it here:

The issue was that when starting the cockroachDB server, I needed to add a flag that pointed to the spatial library, which included the files libgeos.dll and libgeos_c.dll. The flag looks like this:

--spatial-libs=[location of cockroach_server]/libs

Body:
I'm getting the following error on cockroachDB when running a GIS query on an column with indexed GIS data:

[XXUUU] ERROR: geos: error during GEOS init: geos: cannot load GEOS from dir "/usr/local/lib/cockroach": geos error: failed to execute dlsym Hint: Ensure you have the spatial libraries installed as per the instructions in https://www.cockroachlabs.com/docs/v21.1/install-cockroachdb-windows

It worked before indexing the column and after removing the index.

CockroachDB runs on on a remote server using windows, and my local computer is using windows and connecting to the DB through Datagrip. Changing the environment variables on the server and on my local computer, including adding a "\" to the end of the path, did not address the issue.

What is blocking me from using indexing on my queries?


来源: stackexchange

问:
How to get value of nested branch in firebase swift
I'm new to setting up firebase's realtime database, and I'm trying to access the content from a message to display in the app.

Here is how my database is structured:

I want to access "content" for each of the messages with the fewest value for "numberofresponses."

```<code>let ref: DatabaseReference! = Database.database().reference(withPath: "messagepool")

ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
        print("no snapshot exists")
        return }
    print(snapshot)
</code>```

The above code correctly prints the "messagepool," but I want the specific content value from each of the branches. I seem to be missing something. What is the correct way to do this? Thanks

答:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So in your closure/completion handler you will need to loop over snapshot.children to get at the individual result snapshot(s):

```<code>ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
        print("no snapshot exists")
        return
    }
    for childSnapshot in querySnapShot.children.allObjects as! [DataSnapshot] {
        print(childSnapshot.key)
        print(childSnapshot.value)
        guard let value = childSnapshot.value as? [String: Any] else { return }
        do {
          guard let content = value["content"] as? String,
          ...
        }
    }
}
</code>```

Also see:

Firebase queryOrderedByChild() method not giving sorted data

Retrieving Data using Firebase Swift

Getting nil in parsing Firebase values swift using Codable and CodableFirebase

ContentLicense: CC BY-SA 4.0

Body:
I'm new to setting up firebase's realtime database, and I'm trying to access the content from a message to display in the app.

Here is how my database is structured:

I want to access "content" for each of the messages with the fewest value for "numberofresponses."

let ref: DatabaseReference! = Database.database().reference(withPath: "messagepool")

ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
        print("no snapshot exists")
        return }
    print(snapshot)

The above code correctly prints the "messagepool," but I want the specific content value from each of the branches. I seem to be missing something. What is the correct way to do this? Thanks

Body:
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So in your closure/completion handler you will need to loop over snapshot.children to get at the individual result snapshot(s):

ref.queryOrdered(byChild: "numberofresponses").observeSingleEvent(of: .value, with: { snapshot in
    if !snapshot.exists() {
        print("no snapshot exists")
        return
    }
    for childSnapshot in querySnapShot.children.allObjects as! [DataSnapshot] {
        print(childSnapshot.key)
        print(childSnapshot.value)
        guard let value = childSnapshot.value as? [String: Any] else { return }
        do {
          guard let content = value["content"] as? String,
          ...
        }
    }
}

Also see:

Firebase queryOrderedByChild() method not giving sorted data

Retrieving Data using Firebase Swift

Getting nil in parsing Firebase values swift using Codable and CodableFirebase


问:
How to call UseBasePath() in Blazor with .NET Core 6?
There a tons of articles how to call UseBasePath() in a Blazor server side application - but unfortunately all describe how to do it in Startup() or Configure() up to .NET Core 5.
With .NET Core 6, a "new minimal hosting model" was introduced, so that Startup.cs and Program.cs no longer exist in the old way, nor the Configure() method.
Like mentioned e.g. in https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60?view=aspnetcore-6.0&tabs=visual-studio

```<code>var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpClient();
...
var app = builder.Build();
...
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

</code>```

How can I call UseBasePath() in the new, minimal Program.cs when there only are few lines of code left?
Not that I wouldn't appreciate this improvement, but for a ASP.NET newbie like me it is getting very difficult here...

答:
How about...

```<code>app.UsePathBase("/app");
</code>```

Or did I miss the question?

Body:
There a tons of articles how to call UseBasePath() in a Blazor server side application - but unfortunately all describe how to do it in Startup() or Configure() up to .NET Core 5.
With .NET Core 6, a "new minimal hosting model" was introduced, so that Startup.cs and Program.cs no longer exist in the old way, nor the Configure() method.
Like mentioned e.g. in https://learn.microsoft.com/en-us/aspnet/core/migration/50-to-60?view=aspnetcore-6.0&tabs=visual-studio

var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpClient();
...
var app = builder.Build();
...
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

How can I call UseBasePath() in the new, minimal Program.cs when there only are few lines of code left?
Not that I wouldn't appreciate this improvement, but for a ASP.NET newbie like me it is getting very difficult here...

Body:
How about...

app.UsePathBase("/app");

Or did I miss the question?


问:
FindFirst with Date value
I'm using a splitform to navigate information and I have a command button that selects a record based on today's date.

Private Sub FindDate_Click()
  TodayDate = DateTime.Date
     Me![Start Date].SetFocus
     DoCmd.FindRecord TodayDate
End Sub
```
<p>I discovered that wouldn't work if the date didn't exist in my recordset.</p>
<p>I modified the code but I get</p>
<blockquote>
<p>"Run-time error '3251': Operation is not supported for this type of
object."</p>
</blockquote>
<p>The new line of code is</p>
<pre class="lang-vb prettyprint-override"><code>Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date

StrSQl = "[Start Date] = #" & TodayDate & "#"

CurrRec.FindFirst (StrSQl)
</code>```

I'm trying to use that FindFirst function to tell me if there is a record that matches my criteria and if not I was going to -1 to TodayDate and check again until I get a record to lock onto.

答:
Get the SQL do the work:

```<code>Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset( _
   "select top 1 [Start Date] from AIM where [Start Date] <= #" & DateTime.Date & "# order by [Start Date] desc")

If CurrRec.EOF Then
   Debug.Print "Not Found"
Else
   Debug.Print CurrRec![Start Date]
End If

CurrRec.Close
Set CurrRec = Nothing
Set CurrDb = Nothing
</code>```

There is no looping/checking again, etc.
Also, when working with objects in VBA, it is good practice to close them (if there is a method for it), and set them to nothing.

Title: FindFirst with Date value

Body:
I'm using a splitform to navigate information and I have a command button that selects a record based on today's date.

Private Sub FindDate_Click()
  TodayDate = DateTime.Date
     Me![Start Date].SetFocus
     DoCmd.FindRecord TodayDate
End Sub

I discovered that wouldn't work if the date didn't exist in my recordset.

I modified the code but I get

"Run-time error '3251': Operation is not supported for this type of
object."

The new line of code is

Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date

StrSQl = "[Start Date] = #" & TodayDate & "#"

CurrRec.FindFirst (StrSQl)

I'm trying to use that FindFirst function to tell me if there is a record that matches my criteria and if not I was going to -1 to TodayDate and check again until I get a record to lock onto.

Body:
Get the SQL do the work:

Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset( _
   "select top 1 [Start Date] from AIM where [Start Date] <= #" & DateTime.Date & "# order by [Start Date] desc")

If CurrRec.EOF Then
   Debug.Print "Not Found"
Else
   Debug.Print CurrRec![Start Date]
End If

CurrRec.Close
Set CurrRec = Nothing
Set CurrDb = Nothing

There is no looping/checking again, etc.
Also, when working with objects in VBA, it is good practice to close them (if there is a method for it), and set them to nothing.


问:
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/
I'm using the Psychopy module in Python.  My code calls waitKeys(...) to get keypresses and reaction times.  90% of the time it works perfectly, but occasionally when I launch it I get this (exactly this, not an infinite repetition):

```<code>PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
</code>```

and not surprisingly it does not respond to any of my keystrokes, only to control-C.

I am only running Terminal (to launch the script), Xcode (to edit the python script), and Safari with only a couple of vanilla websites open (stackoverlow.com, discourse.psychopy.org, and google.com for searching).  The only way I can stop this behaviour is by logging out then logging back in.  Closing the Terminal window and opening a new one doesn't fix it.  Quitting from Terminal and relaunching it doesn't fix it.  Quitting from all running apps then relaunching Terminal doesn't fix it.

Sometimes when it happens, I had control-C'd out of the app just prior to this happening on the next launch.  So perhaps Psychopy is leaving some orphaned thread still running in the background, from that prior invocation of the script, and that thread hasn't relinquished its claim on the keyboard?  How could I find out?  And how can I address that in my code?

Here's the relevant code:

```<code>**from** psychopy **import** prefs
prefs.hardware['audioLib'] = ['PTB']  # Prepare to use the right audio backend before importing sound
latencyMode = 4    # For PTB. 0, 1, 2, 3, 4
prefs.hardware['audioLatencyMode'] = [str(latencyMode)]
from psychopy.sound.backend_ptb **import** SoundPTB
from psychopy.hardware **import** keyboard
kb = keyboard.Keyboard() # Set up a keyboard device
targetAudio = SoundPTB(listFiles[thisAudioIndex])
targetAudio.play()
 keys = kb.waitKeys(keyList = ["return", "space", "down", "right"],
                           waitRelease=False)
targetAudio.stop()
</code>```

2017 MacBook Pro, using the inbuilt keyboard.  macOS 11.4, Python 3.8.
I also posted this on discourse.psychopy.org

答:
Solved (kind of!).

For UI reasons, I stop keys typed during the experiment from being echoed to the screen (otherwise the screen gets full of random junk).  I do this by sending stty -echo to the parent shell.

But when exiting from the program (for any reason) I need to undo this by sending stty echo.  So I set up an exit handler:

```<code>def onExit():
    """Restore keystroke echo when we exit"""
    os.system('stty echo')
</code>```

However if the user types control-C then such an exit handler would not be executed, so I also have to trap control-C:

```<code>def captureControl_C(signum, frame):
    """If user types control-c, restore keystroke echo before quitting"""
    # Restore the original signal handler, otherwise evil things will happen
    # if CTRL+C is pressed while we are already here, e.g. "c" key bounced
    signal.signal(signal.SIGINT, originalSigintHandler)
    os.system('stty echo')
    raise KeyboardInterrupt # So we still see the stack trace on the screen
</code>```

See here for details.

And this brings us to the problem.  I connect up the above exit handler and trap with the following 3 lines in __main__:

```<code>os.system('stty -echo') # Stop any echo of keystrokes to the Terminal window.
atexit.register(onExit) # Restore keyboard echo when quitting
#
# BUT if user types control-c, then restore keyboard echo!
# Otherwise the Terminal window looks unresponsive.
#
originalSigintHandler = signal.signal(signal.SIGINT, captureControl_C)
</code>```

When those 3 lines are in __main__ then everything works perfectly.  But then I shifted them into a function initialSetup() which is called from main.  In doing that, of course I had to precede them with

```<code>global originalSigintHandler # So that captureControl_C() can see it
</code>```

Moving the crucial 3 lines into initialSetup() caused subsequent calls to waitKeys() to hang with all those warnings in my initial post.  Moving them back to __main__ fixed it.

I'd be delighted if anybody could explain why.

Body:
I'm using the Psychopy module in Python.  My code calls waitKeys(...) to get keypresses and reaction times.  90% of the time it works perfectly, but occasionally when I launch it I get this (exactly this, not an infinite repetition):

PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...
PTB-WARNING: During PsychHID invocation: Some other running application is preventing me from accessing the keyboard/keypad/mouse/...!
PTB-WARNING: This is likely a security measure, e.g., to protect some active password entry field.
PTB-WARNING: Please identify and quit the offending application. E.g., some versions of Firefox are known to cause such problems...

and not surprisingly it does not respond to any of my keystrokes, only to control-C.

I am only running Terminal (to launch the script), Xcode (to edit the python script), and Safari with only a couple of vanilla websites open (stackoverlow.com, discourse.psychopy.org, and google.com for searching).  The only way I can stop this behaviour is by logging out then logging back in.  Closing the Terminal window and opening a new one doesn't fix it.  Quitting from Terminal and relaunching it doesn't fix it.  Quitting from all running apps then relaunching Terminal doesn't fix it.

Sometimes when it happens, I had control-C'd out of the app just prior to this happening on the next launch.  So perhaps Psychopy is leaving some orphaned thread still running in the background, from that prior invocation of the script, and that thread hasn't relinquished its claim on the keyboard?  How could I find out?  And how can I address that in my code?

Here's the relevant code:

**from** psychopy **import** prefs
prefs.hardware['audioLib'] = ['PTB']  # Prepare to use the right audio backend before importing sound
latencyMode = 4    # For PTB. 0, 1, 2, 3, 4
prefs.hardware['audioLatencyMode'] = [str(latencyMode)]
from psychopy.sound.backend_ptb **import** SoundPTB
from psychopy.hardware **import** keyboard
kb = keyboard.Keyboard() # Set up a keyboard device
targetAudio = SoundPTB(listFiles[thisAudioIndex])
targetAudio.play()
 keys = kb.waitKeys(keyList = ["return", "space", "down", "right"],
                           waitRelease=False)
targetAudio.stop()

2017 MacBook Pro, using the inbuilt keyboard.  macOS 11.4, Python 3.8.
I also posted this on discourse.psychopy.org

Body:
Solved (kind of!).

For UI reasons, I stop keys typed during the experiment from being echoed to the screen (otherwise the screen gets full of random junk).  I do this by sending stty -echo to the parent shell.

But when exiting from the program (for any reason) I need to undo this by sending stty echo.  So I set up an exit handler:

def onExit():
    """Restore keystroke echo when we exit"""
    os.system('stty echo')

However if the user types control-C then such an exit handler would not be executed, so I also have to trap control-C:

def captureControl_C(signum, frame):
    """If user types control-c, restore keystroke echo before quitting"""
    # Restore the original signal handler, otherwise evil things will happen
    # if CTRL+C is pressed while we are already here, e.g. "c" key bounced
    signal.signal(signal.SIGINT, originalSigintHandler)
    os.system('stty echo')
    raise KeyboardInterrupt # So we still see the stack trace on the screen

See here for details.

And this brings us to the problem.  I connect up the above exit handler and trap with the following 3 lines in __main__:

os.system('stty -echo') # Stop any echo of keystrokes to the Terminal window.
atexit.register(onExit) # Restore keyboard echo when quitting
#
# BUT if user types control-c, then restore keyboard echo!
# Otherwise the Terminal window looks unresponsive.
#
originalSigintHandler = signal.signal(signal.SIGINT, captureControl_C)

When those 3 lines are in __main__ then everything works perfectly.  But then I shifted them into a function initialSetup() which is called from main.  In doing that, of course I had to precede them with

global originalSigintHandler # So that captureControl_C() can see it

Moving the crucial 3 lines into initialSetup() caused subsequent calls to waitKeys() to hang with all those warnings in my initial post.  Moving them back to __main__ fixed it.

I'd be delighted if anybody could explain why.


问:
#line keyword in C
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

```<code>char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"
</code>```

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

答:
The line directive:
http://msdn.microsoft.com/en-US/library/b5w2czay%28v=VS.80%29.aspx</p>

ContentLicense: CC BY-SA 3.0

Title: #line keyword in C

Body:
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.


问:
Azure DevOps not to trigger release automatically
I have a pipeline set up with continuous integration and two releases.  Both releases are triggered on commit. I only want to trigger one of them.  How do I stop the other one from triggering automatically?</p>

答:
I'm not sure if you mean you have 2 release pipelines, or 2 release stages.

Either way, you can use filters to achieve what you need. For release pipelines, you can add a branch filter on the build artifact. For release stages you can add an artifact filter on each stage.

The filters work by letting you specify branches and or tags. You could set it up that builds made from branch A will always trigger release pipeline A or release stage A.

You could also specify tags. These tags are build tags, not to be confused with git tags. When you manually run a build pipeline you can add a tag, or you can programmatically add it during the build pipeline in the yaml.

You could then set it up that certain tags need to be present on builds for certain release pipelines or stages to be triggered.


问:
Problem with GIT pull overriding previous code
I am new to GIT and face scenario as follow:

 push file below:

index.php

```<code>$name = "steve";

echo("good morning");
echo($name);
</code>```

 pull the file and then remove the $name variable by accidentally.

```<code>echo("good morning");
echo($name);
</code>```

Without realizing it,  pull and push the new code to server. Problem is the code is broke and no longer working, GIT won't prompt for removal of the line. Is there anyway to solve such scenario?

答:
The solution here is to be aware of what you're changing.  In git, this means using

```<code>git diff
</code>```

to check what code has changed before you add a file to the index.  You can also use gitk to look at your changes.  They'll show up as a red dot marked "Local uncommitted changes, not checked in to index."

If the problem comes from adding a whole file to the index, when you only want some of the changes to go in, here's a method you can use to add individual chunks of code:

```<code>git add -p
</code>```

This will go through the various changed bits of code and ask you, for each one, whether to add it to the index or not.  So if you have some changes in a file that need to be checked in, while others are just for experimentation or debugging, you can use git add -p to add only the ones that should really be checked in.

Body:
I am new to GIT and face scenario as follow:

 push file below:

index.php

$name = "steve";

echo("good morning");
echo($name);

 pull the file and then remove the $name variable by accidentally.

echo("good morning");
echo($name);

Without realizing it,  pull and push the new code to server. Problem is the code is broke and no longer working, GIT won't prompt for removal of the line. Is there anyway to solve such scenario?

Body:
The solution here is to be aware of what you're changing.  In git, this means using

git diff

to check what code has changed before you add a file to the index.  You can also use gitk to look at your changes.  They'll show up as a red dot marked "Local uncommitted changes, not checked in to index."

If the problem comes from adding a whole file to the index, when you only want some of the changes to go in, here's a method you can use to add individual chunks of code:

git add -p

This will go through the various changed bits of code and ask you, for each one, whether to add it to the index or not.  So if you have some changes in a file that need to be checked in, while others are just for experimentation or debugging, you can use git add -p to add only the ones that should really be checked in.


问:
Shiny app only renders first two tables from list of four
I'm putting together my first Shiny app and need some help. I'm trying to get the user to be able to choose different views on the same dataset via drop-down list selection.

In a separate R script, I have created my summary tables, I have sourced the script, and run it at the very beginning of my app.

These are the summary tables I would like to use in the app:

SummarybyAgency

SummarybyCallContext

SummarybyLicense

SummarybyLocation

I have also created a vector that contains the choices from the dropdown:

```<code>Views <- c("Agency", "Context", "License", "Location")
</code>```

This is the code in the UI portion of the app:

```<code>  box(
                    title = "Minute Consumption and Charges",
                    selectInput("View", "Select view", choices = Views)),
                    dataTableOutput("TableView")
      )
</code>```

And this is on the server side:

```<code>server <- function(input, output, session) {

  reactive_View <- reactive({
    if(input$View == "Agency") {return (SummarybyAgency)} else {
      if (input$View == "Context") {return(SummarybyCallContext)} else {
        if (input$view == "License") {return(SummarybyLicense)} else {
          if (input$View == "Location") {return(SummarybyLocation)}
        }
      }
    }

  })

  output$TableView <- renderDataTable(reactive_View(), options = list(pageLength = 5))

  }

shinyApp(ui, server)

}
</code>```

However, when I run the app I can select only the first two tables, the other two fail.

Example:

[

This is the error in the console:

```<code>Warning: Error in if: argument is of length zero
  114: <reactive:reactive_View> [app.R#116]
   98: reactive_View
   97: renderDataTable
   96: func
   83: renderFunc
   82: output$TableView
    1: runApp
</code>```

However, if I swap the order of the tables in the nested if statement, I will always see the first two tables (if I put "License" and "Location: in the first two ifs I'll be able to render them, but not Agency and Context.

Is there something wrong with my code?

答:
Perhaps something like this helps you?</p>
```<code>library(shiny)
library(shinydashboard)
Views <- c("Agency", "Context", "License", "Location")
ds <- list(
  Agency = data.frame("agency" = c(1,2,3), "b" = c(4,5,6)),
  Context = data.frame("context" = c(4,5,6), "b" = c(4,5,6)),
  License = data.frame("license" = c(7,8,9), "b" = c(4,5,6)),
  Location = data.frame("location" = c(10,11,12), "b" = c(4,5,6))
)

ui <- fluidPage(
  box(
    title = "Minute Consumption and Charges",
    selectInput("View", "Select view", choices = Views)),
  dataTableOutput("TableView")
)

server <- function(input, output, session) {
  output$TableView = renderDataTable(
    ds[[input$View]]
  )
}
</code>```

Body:
I'm putting together my first Shiny app and need some help. I'm trying to get the user to be able to choose different views on the same dataset via drop-down list selection.

In a separate R script, I have created my summary tables, I have sourced the script, and run it at the very beginning of my app.

These are the summary tables I would like to use in the app:

SummarybyAgency

SummarybyCallContext

SummarybyLicense

SummarybyLocation

I have also created a vector that contains the choices from the dropdown:

Views <- c("Agency", "Context", "License", "Location")

This is the code in the UI portion of the app:

  box(
                    title = "Minute Consumption and Charges",
                    selectInput("View", "Select view", choices = Views)),
                    dataTableOutput("TableView")
      )

And this is on the server side:

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

  reactive_View <- reactive({
    if(input$View == "Agency") {return (SummarybyAgency)} else {
      if (input$View == "Context") {return(SummarybyCallContext)} else {
        if (input$view == "License") {return(SummarybyLicense)} else {
          if (input$View == "Location") {return(SummarybyLocation)}
        }
      }
    }

  })

  output$TableView <- renderDataTable(reactive_View(), options = list(pageLength = 5))

  }

shinyApp(ui, server)

}

However, when I run the app I can select only the first two tables, the other two fail.

Example:

[

This is the error in the console:

Warning: Error in if: argument is of length zero
  114: <reactive:reactive_View> [app.R#116]
   98: reactive_View
   97: renderDataTable
   96: func
   83: renderFunc
   82: output$TableView
    1: runApp

However, if I swap the order of the tables in the nested if statement, I will always see the first two tables (if I put "License" and "Location: in the first two ifs I'll be able to render them, but not Agency and Context.

Is there something wrong with my code?

Body:
Perhaps something like this helps you?

library(shiny)
library(shinydashboard)
Views <- c("Agency", "Context", "License", "Location")
ds <- list(
  Agency = data.frame("agency" = c(1,2,3), "b" = c(4,5,6)),
  Context = data.frame("context" = c(4,5,6), "b" = c(4,5,6)),
  License = data.frame("license" = c(7,8,9), "b" = c(4,5,6)),
  Location = data.frame("location" = c(10,11,12), "b" = c(4,5,6))
)

ui <- fluidPage(
  box(
    title = "Minute Consumption and Charges",
    selectInput("View", "Select view", choices = Views)),
  dataTableOutput("TableView")
)

server <- function(input, output, session) {
  output$TableView = renderDataTable(
    ds[[input$View]]
  )
}


问:
How to convert uint to string in solidity?
In Solidity, is there a way I can convert my int  to string ?

Example:

```<code>pragma solidity ^0.4.4;

contract someContract {

    uint i;

    function test() pure returns (string) {

      return "Here and Now is Happiness!";

    }

    function love() pure returns(string) {

        i = i +1;

        return "I love " + functionname(i) + " persons" ;
    }

}
</code>```

What is functionname?Thanks!

Body:
In Solidity, is there a way I can convert my int  to string ?

Example:

pragma solidity ^0.4.4;

contract someContract {

    uint i;

    function test() pure returns (string) {

      return "Here and Now is Happiness!";

    }

    function love() pure returns(string) {

        i = i +1;

        return "I love " + functionname(i) + " persons" ;
    }

}

What is functionname?Thanks!

Body:
While the accepted answer seems correct, it is quite inefficient on large numbers.  Here is how I would do it:

function itoa32 (uint x) private pure returns (uint y) {
    unchecked {
        require (x < 1e32);
        y = 0x3030303030303030303030303030303030303030303030303030303030303030;
        y += x % 10; x /= 10;
        y += x % 10 << 8; x /= 10;
        y += x % 10 << 16; x /= 10;
        y += x % 10 << 24; x /= 10;
        y += x % 10 << 32; x /= 10;
        y += x % 10 << 40; x /= 10;
        y += x % 10 << 48; x /= 10;
        y += x % 10 << 56; x /= 10;
        y += x % 10 << 64; x /= 10;
        y += x % 10 << 72; x /= 10;
        y += x % 10 << 80; x /= 10;
        y += x % 10 << 88; x /= 10;
        y += x % 10 << 96; x /= 10;
        y += x % 10 << 104; x /= 10;
        y += x % 10 << 112; x /= 10;
        y += x % 10 << 120; x /= 10;
        y += x % 10 << 128; x /= 10;
        y += x % 10 << 136; x /= 10;
        y += x % 10 << 144; x /= 10;
        y += x % 10 << 152; x /= 10;
        y += x % 10 << 160; x /= 10;
        y += x % 10 << 168; x /= 10;
        y += x % 10 << 176; x /= 10;
        y += x % 10 << 184; x /= 10;
        y += x % 10 << 192; x /= 10;
        y += x % 10 << 200; x /= 10;
        y += x % 10 << 208; x /= 10;
        y += x % 10 << 216; x /= 10;
        y += x % 10 << 224; x /= 10;
        y += x % 10 << 232; x /= 10;
        y += x % 10 << 240; x /= 10;
        y += x % 10 << 248;
    }
}

function itoa (uint x) internal pure returns (string memory s) {
    unchecked {
        if (x == 0) return "0";
        else {
            uint c1 = itoa32 (x % 1e32);
            x /= 1e32;
            if (x == 0) s = string (abi.encode (c1));
            else {
                uint c2 = itoa32 (x % 1e32);
                x /= 1e32;
                if (x == 0) {
                    s = string (abi.encode (c2, c1));
                    c1 = c2;
                } else {
                    uint c3 = itoa32 (x);
                    s = string (abi.encode (c3, c2, c1));
                    c1 = c3;
                }
            }
            uint z = 0;
            if (c1 >> 128 == 0x30303030303030303030303030303030) { c1 <<= 128; z += 16; }
            if (c1 >> 192 == 0x3030303030303030) { c1 <<= 64; z += 8; }
            if (c1 >> 224 == 0x30303030) { c1 <<= 32; z += 4; }
            if (c1 >> 240 == 0x3030) { c1 <<= 16; z += 2; }
            if (c1 >> 248 == 0x30) { z += 1; }
            assembly {
                let l := mload (s)
                s := add (s, z)
                mstore (s, sub (l, z))
            }
        }
    }
}

Explanation

The itoa32 function converts a number below 10^32 into exactly 32 digits, padding it with zeros if necessary.

The itoa function calls the itoa32 up to three times to convert an arbitrary 256-bit number, then concatenates the results and removes leading zeros.  It uses binary search to find out the exact number of leading zeros to be removed and removes leading zeros from a string in-place.


问:
How do I fix this error in Android Studio?
I've been getting this error every now and then, and once I thought it was fixed, it just came back:

```<code>Error while executing: am start -n "com.example.wolfixfinal/com.example.wolfixfinal.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.wolfixfinal/.MainActivity }
Error type 3
Error: Activity class {com.example.wolfixfinal/com.example.wolfixfinal.MainActivity} does not exist.

Error while Launching activity
Failed to launch an application on all devices
</code>```

I've made two or three other questions about this topic and it's getting annoying. I've tried removing the gradle and .gradle folder, removing the .idea folder and then rebuilding the project. I don't know what to do anymore.

How do I keep this from not happening, is it something I have to do all the time everytime I see this error.

答:
Make sure than only ONE of your activities has the LAUNCHER and MAIN properties in your Manifest file. This file can be found under Android Project view: app > manifests > AndroidManifest.xml. The one you want to boot in is the one that should have these properties.

Like this:

```<code><activity
        android:name=".Splash"
        android:exported="true">

        <!--This will be the starting activity you want-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:exported="true"/>
</code>```

NOT like this (2 activities in the manifest both have:

```<code><action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</code>```

):

```<code><activity
        android:name=".Splash"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

Body:
I've been getting this error every now and then, and once I thought it was fixed, it just came back:

Error while executing: am start -n "com.example.wolfixfinal/com.example.wolfixfinal.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.wolfixfinal/.MainActivity }
Error type 3
Error: Activity class {com.example.wolfixfinal/com.example.wolfixfinal.MainActivity} does not exist.

Error while Launching activity
Failed to launch an application on all devices

I've made two or three other questions about this topic and it's getting annoying. I've tried removing the gradle and .gradle folder, removing the .idea folder and then rebuilding the project. I don't know what to do anymore.

How do I keep this from not happening, is it something I have to do all the time everytime I see this error.

Body:
Make sure than only ONE of your activities has the LAUNCHER and MAIN properties in your Manifest file. This file can be found under Android Project view: app > manifests > AndroidManifest.xml. The one you want to boot in is the one that should have these properties.

Like this:

<activity
        android:name=".Splash"
        android:exported="true">

        <!--This will be the starting activity you want-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:exported="true"/>

NOT like this (2 activities in the manifest both have:

<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

):

<activity
        android:name=".Splash"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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


问:
What is the best data structure for a generic step function?
I need to implement a step function (i.e. piecewise constant).  There are a few requirements that it will need to have.

It will have to be evaluated repeatedly at random locations, then evaluated sequentially over an interval.

It Will have to be easily updated, i.e. adding an increase/decrease over an interval.

So my question is what is the best data structure for this sort of thing?  I was thinking that due to the random access nature a Binary tree is the most likely, but I'm hoping I'm not missing something.  Also is there a good implementation already out there for C++.

答:
Yes, since the intervals cannot overlap, binary tree is the right data structure. If you did not need fast updates, it could be as simple as having a sorted sequence of the interval endpoints; querying the function value at a certain location could be done using, for example, one of the STL binary search methods std::lower_bound or std::upper_bound, evaluating over a range using two searches. However, for fast updates a self-balancing binary tree is naturally better.

The standard library does define a container with tree-like access: std::map (although it is not required to be implemented using a binary tree, it usually is).

for completeness, it should be mentioned that Boost ICL library has an interval_map, a std::map-like container that uses intervals as keys and with aggregate on overlap insertion semantics.


问:
Cloudformation AWS CLI Query ALL Stack resources with multiple nested stacks
I know i can get at a stacks resources with:-

```<code>aws cloudformation describe-stack-resources \
                    --stack-name MYSTACKNAME \
                    --query 'StackResources[*].{Type:ResourceType,LogicalID:LogicalResourceId}' \
                    --output table
</code>```

If my stack only consists of NESTED STACKS how can i get at the resources of all the nested stacks of my stack within Cloudformation?

I can see how to query for all the stacks of my parent stack.

```<code>aws cloudformation list-stacks \
                    --query 'StackSummaries[?contains(StackName, `MYSTACKNAME`) && (StackStatus==`CREATE_COMPLETE`||StackStatus==`UPDATE_COMPLETE`)].{Stack:StackName}' \
                    --output json
</code>```

I cant work out how to use this to feed describe-stack-resources which only appears to take an individual value.

I could build this into a python script but thought i would check before i do.

Thanks

答:
There have been some updates to the AWS CLI. Now you can target stack resources directly. If you have the stack name, you will need to use the StackResourcesSummaries

```<code>aws cloudformation list-stack-resources --stack-name soinshane-prd-app-ec2-stack --output text --query 'StackResourceSummaries[?(ResourceStatus!=`CREATE_COMPLETE`&&ResourceStatus!=`UPDATE_COMPLETE`)].[PhysicalResourceId, ResourceStatus]'
</code>```

Great Resource for more info

AWS CLI of Course another one

Body:
I know i can get at a stacks resources with:-

aws cloudformation describe-stack-resources \
                    --stack-name MYSTACKNAME \
                    --query 'StackResources[*].{Type:ResourceType,LogicalID:LogicalResourceId}' \
                    --output table

If my stack only consists of NESTED STACKS how can i get at the resources of all the nested stacks of my stack within Cloudformation?

I can see how to query for all the stacks of my parent stack.

aws cloudformation list-stacks \
                    --query 'StackSummaries[?contains(StackName, `MYSTACKNAME`) && (StackStatus==`CREATE_COMPLETE`||StackStatus==`UPDATE_COMPLETE`)].{Stack:StackName}' \
                    --output json

I cant work out how to use this to feed describe-stack-resources which only appears to take an individual value.

I could build this into a python script but thought i would check before i do.

Thanks

Body:
There have been some updates to the AWS CLI. Now you can target stack resources directly. If you have the stack name, you will need to use the StackResourcesSummaries

aws cloudformation list-stack-resources --stack-name soinshane-prd-app-ec2-stack --output text --query 'StackResourceSummaries[?(ResourceStatus!=`CREATE_COMPLETE`&&ResourceStatus!=`UPDATE_COMPLETE`)].[PhysicalResourceId, ResourceStatus]'

Great Resource for more info

AWS CLI of Course another one


问:
mysql fetching data from server
When get new data from the database, does this mean a new connection? mysql database

Eg:

```<code> SELECT * FROM employees WHERE ID=1
</code>```

Does this mean a new connection on the database server?

答:
If you are not so familiar with SQL, this is an SQL Query. It is a kind of specifying the requirements of data which you are requesting from the database. Database Connection is a different thing.

I recommend you should dig in to SQL to understand bit more, it is very easy to learn..

Title: mysql fetching data from server

Body:
When get new data from the database, does this mean a new connection? mysql database

Eg:

 SELECT * FROM employees WHERE ID=1

Does this mean a new connection on the database server?


问:
How can I debug my add-in when WordEditor's Content property is crashing Outlook?
I have folder full of *.msg files saved from Outlook and I'm trying to convert them to Word.

There is a loop that loads each *.msg as MailItem and saves them.

    public static ConversionResult ConvertEmailsToWord(this Outlook.Application app, string source, string target)
    {
        var word = new Word.Application();

        var emailCounter = 0;
        var otherCounter = 0;

        var directoryTree = new PhysicalDirectoryTree();
        foreach (var node in directoryTree.Walk(source))
        {
            foreach (var fileName in node.FileNames)
            {
                var currentFile = Path.Combine(node.DirectoryName, fileName);
                var branch = Regex.Replace(node.DirectoryName, $"^{Regex.Escape(source)}", string.Empty).Trim('\\');

                Debug.Print($"Processing file: {currentFile}");

                // This is an email. Convert it to Word.
                if (Regex.IsMatch(fileName, @"\.msg$"))
                {
                    if (app.Session.OpenSharedItem(currentFile) is MailItem item)
                    {
                        if (item.SaveAs(word, Path.Combine(target, branch), fileName))
                        {
                            emailCounter++;
                        }
                        item.Close(SaveMode: OlInspectorClose.olDiscard);
                    }
                }
                // This is some other file. Copy it as is.
                else
                {
                    Directory.CreateDirectory(Path.Combine(target, branch));
                    File.Copy(currentFile, Path.Combine(target, branch, fileName), true);
                    otherCounter++;
                }
            }
        }

        word.Quit(SaveChanges: false);

        return new ConversionResult
        {
            EmailCount = emailCounter,
            OtherCount = otherCounter
        };
    }
```
<p>The save method looks likes this:</p>
<pre class="lang-cs prettyprint-override"><code>    public static bool SaveAs(this MailItem mail, Word.Application word, string path, string name)
    {
        Directory.CreateDirectory(path);

        name = Path.Combine(path, $"{Path.GetFileNameWithoutExtension(name)}.docx");
        if (File.Exists(name))
        {
            return false;
        }

        var copy = mail.GetInspector.WordEditor as Word.Document;
        copy.Content.Copy();

        var doc = word.Documents.Add();
        doc.Content.Paste();
        doc.SaveAs2(FileName: name);
        doc.Close();

        return true;
    }
</code>```

It works for most *.msg files but there are some that crash Outlook when I call copy.Content on a Word.Document.

I know you cannot tell me what is wrong with it (or maybe you do?) so I'd like to findit out by myself but the problem is that I am not able to catch the exception. Since a simple try\catch didn't work I tried it with AppDomain.CurrentDomain.UnhandledException this this didn't catch it either.

Are there any other ways to debug it?

The mail that doesn't let me get its content inside a loop doesn't cause any troubles when I open it in a new Outlook window and save it with the same method.

答:
It makes sense to add some delays between Word calls. IO operations takes some time to finish. Also there is no need to create another document in Word for copying the content:

```<code>var copy = mail.GetInspector.WordEditor as Word.Document;
copy.Content.Copy();

var doc = word.Documents.Add();
doc.Content.Paste();
doc.SaveAs2(FileName: name);
doc.Close();
</code>```

Instead, do the required modifications on the original document instance and then save it to the disk. The original mail item will remain unchanged until you call the Save method from the Outlook object model. You may call the Close method passing the olDiscard which discards any changes to the document.

Also consider using the Open XML SDK if you deal with open XML documents only, see Welcome to the Open XML SDK 2.5 for Office for more information.

Body:
I have folder full of *.msg files saved from Outlook and I'm trying to convert them to Word.

There is a loop that loads each *.msg as MailItem and saves them.

    public static ConversionResult ConvertEmailsToWord(this Outlook.Application app, string source, string target)
    {
        var word = new Word.Application();

        var emailCounter = 0;
        var otherCounter = 0;

        var directoryTree = new PhysicalDirectoryTree();
        foreach (var node in directoryTree.Walk(source))
        {
            foreach (var fileName in node.FileNames)
            {
                var currentFile = Path.Combine(node.DirectoryName, fileName);
                var branch = Regex.Replace(node.DirectoryName, $"^{Regex.Escape(source)}", string.Empty).Trim('\\');

                Debug.Print($"Processing file: {currentFile}");

                // This is an email. Convert it to Word.
                if (Regex.IsMatch(fileName, @"\.msg$"))
                {
                    if (app.Session.OpenSharedItem(currentFile) is MailItem item)
                    {
                        if (item.SaveAs(word, Path.Combine(target, branch), fileName))
                        {
                            emailCounter++;
                        }
                        item.Close(SaveMode: OlInspectorClose.olDiscard);
                    }
                }
                // This is some other file. Copy it as is.
                else
                {
                    Directory.CreateDirectory(Path.Combine(target, branch));
                    File.Copy(currentFile, Path.Combine(target, branch, fileName), true);
                    otherCounter++;
                }
            }
        }

        word.Quit(SaveChanges: false);

        return new ConversionResult
        {
            EmailCount = emailCounter,
            OtherCount = otherCounter
        };
    }

The save method looks likes this:

    public static bool SaveAs(this MailItem mail, Word.Application word, string path, string name)
    {
        Directory.CreateDirectory(path);

        name = Path.Combine(path, $"{Path.GetFileNameWithoutExtension(name)}.docx");
        if (File.Exists(name))
        {
            return false;
        }

        var copy = mail.GetInspector.WordEditor as Word.Document;
        copy.Content.Copy();

        var doc = word.Documents.Add();
        doc.Content.Paste();
        doc.SaveAs2(FileName: name);
        doc.Close();

        return true;
    }

It works for most *.msg files but there are some that crash Outlook when I call copy.Content on a Word.Document.

I know you cannot tell me what is wrong with it (or maybe you do?) so I'd like to findit out by myself but the problem is that I am not able to catch the exception. Since a simple try\catch didn't work I tried it with AppDomain.CurrentDomain.UnhandledException this this didn't catch it either.

Are there any other ways to debug it?

The mail that doesn't let me get its content inside a loop doesn't cause any troubles when I open it in a new Outlook window and save it with the same method.

Body:
It makes sense to add some delays between Word calls. IO operations takes some time to finish. Also there is no need to create another document in Word for copying the content:

var copy = mail.GetInspector.WordEditor as Word.Document;
copy.Content.Copy();

var doc = word.Documents.Add();
doc.Content.Paste();
doc.SaveAs2(FileName: name);
doc.Close();

Instead, do the required modifications on the original document instance and then save it to the disk. The original mail item will remain unchanged until you call the Save method from the Outlook object model. You may call the Close method passing the olDiscard which discards any changes to the document.

Also consider using the Open XML SDK if you deal with open XML documents only, see Welcome to the Open XML SDK 2.5 for Office for more information.


问:
C++ Overloading macro on undefined number of arguments
My command uses return codes and a string reference argument instead of exceptions to detect an error in the execution of a function.

We have some invariant checking that looks like this:

```<code>bool format(std::string &error, ...)
{
    // call sprintf on "error" string with all passed arguments
    return false;
}

bool func(std::string &error)
{
    // .......................

    if (!some_expression)
        return format(error, /*some undefined number of args*/);

    // .......................
}

</code>```

I want to write a macro, that will perform this logic in one line like this:

```<code>REQUIRE(expr, functor, "test string");
REQUIRE(expr, functor, "number=%lld", 1ll);
REQUIRE(expr, functor, "number_1=%lld, number_2=%f", 1ll, 2.0);
</code>```

When REQUIRE macro will be this:

```<code>#define REQUIRE(expression, functor, format, ...)   \
{                                                   \
    if (!expression)                                \
        return functor(format, __VA_ARGS__)         \
}
</code>```

But this solution doesn't work, when i pass only format string without any arguments (first case in example). I tryed all solutions from this question:
Overloading Macro on Number of Arguments, but all of them requires writing overloading on all agrs count.

Here is my non-working code code for now:

```<code>#define REQUIRE_1(expression, functor, format)  \
{                                               \
    if (!expression)                            \
        return functor(format);                 \
}

#define REQUIRE_2(expression, functor, format, ...) \
{                                                   \
    if (!expression)                                \
        return functor(format, __VA_ARGS__)         \
}

#define GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define REQUIRE(...) GET_MACRO(__VA_ARGS__, REQUIRE_1, REQUIRE_2)(__VA_ARGS__)

bool functor(const char *format, ...)
{
    // Here is passing args to something like printf

    return false;
}

bool format(std::string &error, ...)
{
    // call sprintf on "error" string with all passed arguments
    return false;
}

bool func(std::string &error)
{
    // .......................

    if (!some_expression)
        return format(error, /*some undefined number of args*/);

    // .......................
}

int main()
{
    REQUIRE(true, func, "test string");
    REQUIRE(true, func, "number=%lld", 1ll);
    REQUIRE(true, func, "number_1=%lld, number_2=%f", 1ll, 2.0);
    // Samples for [5,6,7..infinite] arguments
}
</code>```

How can i achieve needed behaviour?

答:
C++20 made it possible to call #define F(x, y, ...) as F(1, 2), without the comma after the last argument.

If C++20 is available, the only change you need to do is to replace , __VA_ARGS__ with __VA_OPT__(,) __VA_ARGS__ to the remove the comma if no extra arguments are passed.

Otherwise, just combine format and ... parameters into a single ... parameter.

Body:
My command uses return codes and a string reference argument instead of exceptions to detect an error in the execution of a function.

We have some invariant checking that looks like this:

bool format(std::string &error, ...)
{
    // call sprintf on "error" string with all passed arguments
    return false;
}

bool func(std::string &error)
{
    // .......................

    if (!some_expression)
        return format(error, /*some undefined number of args*/);

    // .......................
}

I want to write a macro, that will perform this logic in one line like this:

REQUIRE(expr, functor, "test string");
REQUIRE(expr, functor, "number=%lld", 1ll);
REQUIRE(expr, functor, "number_1=%lld, number_2=%f", 1ll, 2.0);

When REQUIRE macro will be this:

#define REQUIRE(expression, functor, format, ...)   \
{                                                   \
    if (!expression)                                \
        return functor(format, __VA_ARGS__)         \
}

But this solution doesn't work, when i pass only format string without any arguments (first case in example). I tryed all solutions from this question:
Overloading Macro on Number of Arguments, but all of them requires writing overloading on all agrs count.

Here is my non-working code code for now:

#define REQUIRE_1(expression, functor, format)  \
{                                               \
    if (!expression)                            \
        return functor(format);                 \
}

#define REQUIRE_2(expression, functor, format, ...) \
{                                                   \
    if (!expression)                                \
        return functor(format, __VA_ARGS__)         \
}

#define GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define REQUIRE(...) GET_MACRO(__VA_ARGS__, REQUIRE_1, REQUIRE_2)(__VA_ARGS__)

bool functor(const char *format, ...)
{
    // Here is passing args to something like printf

    return false;
}

bool format(std::string &error, ...)
{
    // call sprintf on "error" string with all passed arguments
    return false;
}

bool func(std::string &error)
{
    // .......................

    if (!some_expression)
        return format(error, /*some undefined number of args*/);

    // .......................
}

int main()
{
    REQUIRE(true, func, "test string");
    REQUIRE(true, func, "number=%lld", 1ll);
    REQUIRE(true, func, "number_1=%lld, number_2=%f", 1ll, 2.0);
    // Samples for [5,6,7..infinite] arguments
}

How can i achieve needed behaviour?


问:
Check if a condition is met before pushing a property into array ReactJS
I was wondering if someone knows a method that would allow me to push a data property into an array if a condition is met. For example, the code I'm using fetches data from an api. The data that I'm looking for specifically are the pictures. Here is my code:

```<code>     for (const key in petData.animals) {
        loadedData.push({
          id: key,
          photo: petData.animals[key].photos[0],
          name: petData.animals[key].name,
          description: petData.animals[key].description,
        });
      }
</code>```

My issue stems from the fact that some of the data entries lack photos. So whenever I actually run the app, I get an error saying that photos is undefined. Is it possible to add a condition (and if so, how?) similar to if photo === undefined => use a default picture or if the photo === true => use the photo from the api?

答:
The way to do this previous to the last few years was to check incrementally, like so:

```<code>for (const key in petData.animals) {
  let photo = defaultPhoto;
  if (petData.animals[key].photos && petData.animals[key].photos[0]) {
    photo = petData.animals[key].photos[0];
  }
  loadedData.push({
    id: key,
    photo: photo,
    name: petData.animals[key].name,
    description: petData.animals[key].description,
  });
}
</code>```

However, we now have the optional chaining operator (?.) and nullish coalescing operator (??) so we can do this more concisely, like so:

```<code>for (const key in petData.animals) {
  loadedData.push({
    id: key,
    photo: petData.animals[key]?.photos?.[0] ?? defaultPhoto,
    name: petData.animals[key].name,
    description: petData.animals[key].description,
  });
}
</code>```

Body:
I was wondering if someone knows a method that would allow me to push a data property into an array if a condition is met. For example, the code I'm using fetches data from an api. The data that I'm looking for specifically are the pictures. Here is my code:

     for (const key in petData.animals) {
        loadedData.push({
          id: key,
          photo: petData.animals[key].photos[0],
          name: petData.animals[key].name,
          description: petData.animals[key].description,
        });
      }

My issue stems from the fact that some of the data entries lack photos. So whenever I actually run the app, I get an error saying that photos is undefined. Is it possible to add a condition (and if so, how?) similar to if photo === undefined => use a default picture or if the photo === true => use the photo from the api?

Body:
The way to do this previous to the last few years was to check incrementally, like so:

for (const key in petData.animals) {
  let photo = defaultPhoto;
  if (petData.animals[key].photos && petData.animals[key].photos[0]) {
    photo = petData.animals[key].photos[0];
  }
  loadedData.push({
    id: key,
    photo: photo,
    name: petData.animals[key].name,
    description: petData.animals[key].description,
  });
}

However, we now have the optional chaining operator (?.) and nullish coalescing operator (??) so we can do this more concisely, like so:

for (const key in petData.animals) {
  loadedData.push({
    id: key,
    photo: petData.animals[key]?.photos?.[0] ?? defaultPhoto,
    name: petData.animals[key].name,
    description: petData.animals[key].description,
  });
}


问:
Laravel unique random string number
I would like to make an infinite string with a number. What is the best way to do this here e.g. mt_rand(1000000, 9000000) but if between 1000000 and 9000000 everything is occupied there are no more numbers. The more numbers are used the more often there are errors, and the if else has to rattle through the whole table again and again.

```<code>public function creating(Ticket $ticket)
{
    $randomNumber = mt_rand(1000000, 9000000);

    if(!Ticket::where('number', '=', $randomNumber)->exists()) {
        $ticket->fill(['number' => $randomNumber]);
    } else {
        $this->creating($ticket);
    }
}
</code>```

What is the best way to do this? I want it to be a Unique Numberetic String. Which has no end.

答:
To guarantee a unique number you should instead use created. Whenever a ticket is created, you can prepend some random numbers to the id to generate a unique number. Try this

```<code>public function created(Ticket $ticket) {
    $ticket->number = rand(1000, 9999).str_pad($ticket->id, 3, STR_PAD_LEFT);
    $ticket->save();
}
</code>```

Title: Laravel unique random string number

Body:
I would like to make an infinite string with a number. What is the best way to do this here e.g. mt_rand(1000000, 9000000) but if between 1000000 and 9000000 everything is occupied there are no more numbers. The more numbers are used the more often there are errors, and the if else has to rattle through the whole table again and again.

public function creating(Ticket $ticket)
{
    $randomNumber = mt_rand(1000000, 9000000);

    if(!Ticket::where('number', '=', $randomNumber)->exists()) {
        $ticket->fill(['number' => $randomNumber]);
    } else {
        $this->creating($ticket);
    }
}

What is the best way to do this? I want it to be a Unique Numberetic String. Which has no end.

Body:
To guarantee a unique number you should instead use created. Whenever a ticket is created, you can prepend some random numbers to the id to generate a unique number. Try this

public function created(Ticket $ticket) {
    $ticket->number = rand(1000, 9999).str_pad($ticket->id, 3, STR_PAD_LEFT);
    $ticket->save();
}


问:
How to add favicon to django app with React front end
I'm building a Django app with a React front end, built using react-create-app. I can't get the favicon to show up in production.

I'm using Django 2.10.0.

When I build the React app, the build output files are put in the assets/static/ folder. This includes image files used as backgrounds via css, and all works fine. These are included in the build because they are referenced in the stylesheets. The favicon is referenced from index.html and therefore isn't picked up by the build process.

However I don't know how to get the server to serve up the favicons. If I put them in the frontend/public folder, the Django server doesn't find them.

If I manually copy them into the static/ folder, they show up but that folder is managed by Webpack and the contents are removed when the app is built.

Copying the favicons into the project root doesn't work. They are in the same folder as index.html, which is served up, but Django server won't serve those co-located image files.

The only documentation I can find deals with either Django or create-react-app; I can't find anything that explains how to tie them together for favicons.

In settings.py:

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets/static'),
    os.path.join(BASE_DIR, 'assets'),
]
</code>```

In index.html:

```<code><link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
</code>```

In the browser, this is converted to:

```<code><link rel="shortcut icon" href="/favicon.ico">
</code>```

which doesn't work - the file is not served up. I'm not sure why this doesn't work given that I've added 'assets' to STATICFILES_DIRS in settings.py and have copied the favicons into the root of 'assets'.

All the working css and image links include the static folder, e.g.:

```<code>http://localhost:8000/static/media/private.d7365d01.svg
</code>```

It seems like there are two problems:

how to get the build process to copy the favicon and related files into the assets folder so they can be served up

how to get index.html to look in the right place for the favicon

If I could customise PUBLIC_URL to point to static/ that might do it, but that might break other bits of code that reference it?

I am sure I'm missing something simple. I'd be grateful for any help!

Edit: I have now got the favicon to show up in a built version running on my local machine, but it isn't being served by the production server.

Base.py

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets/static'),
    os.path.join(BASE_DIR, 'assets'),
]
</code>```

index.html

```<code><link rel="shortcut icon" href="%PUBLIC_URL%/static/favicon.ico" />
</code>```

And favicon.ico is in the 'assets' folder. After building my React app and running the development server locally, the url http://localhost:8000/static/favicon.ico displays my favicon. But after deploying this to the server, the url https://example.com/static/favicon.ico finds nothing. I have checked and the favicon.ico file is present on the server, in the assets folder. Settings.py is the same. I can't figure out why the production server isn't serving up the favicon?

Edit: I've tried adding this to my settings.py, but it still doesn't work:

```<code>STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
</code>```

'assets' is the name of the folder on the server that contains my build files. The favicons are in assets, as is index.html, and the React files in assets/static.

Edit: this is my Passenger config file for Nginx:

```<code>server {
    listen 80;
    server_name 178.62.85.245;

    passenger_python /var/www/myappname/venv36/bin/python3.6;

    # Tell Nginx where your app's 'public' directory is
    root /var/www/myappname/myappname/myappname;

    # Turn on Passenger
    passenger_enabled on;

   # Tell Nginx the location of the build output files
    location /static/ {
       autoindex on;
       alias /var/www/myappname/myappname/assets/;
    }
}
</code>```

Nginx finds the file index.html and all the files that React built. I don't know why it can't find the favicon in the same folder!

答:
Per @Little_Brain

Edit: I finally solved this thanks to Sune Kjærgård's help. From reading the Django docs about deployment, I had thought I needed to configure all the static file locations in settings.py. However that seems to be only for the Django development server, even when running with production settings. On the production server I am using Nginx via Passenger to serve the app. It is Nginx that needs to know where all my static files are located. And both 'root' and 'location' need to be set correctly.

Here is my working code. The favicons are served on the production server, and in development on port 3000 when running the frontend separately. I haven't got them served when testing the build locally on port 8000, but I can live with that and maybe find a solution later.

STATIC_ROOT doesn't seem to be required, nor am I running buildstatic.

My favicons are located in frontend/public, the same folder as index.html. The Webpack build process copies them all into the assets folder.

```<code>server {
    listen 80;
    server_name 178.62.85.245;

    passenger_python /var/www/myappname/venv36/bin/python3.6;

    # Tell Nginx where your app's 'public' directory is
    root /var/www/myappname/myappname/assets;

    # Turn on Passenger
    passenger_enabled on;

   # Tell Nginx the location of the build output files
    location /static/ {
       autoindex on;
       alias /var/www/myappname/myappname/assets/;
    }
}
</code>```

In settings.py:

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets/static'),
    os.path.join(BASE_DIR, 'assets'),
]
</code>```

In index.html:

```<code><link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
</code>```

In the browser, this is converted to:

```<code><link rel="shortcut icon" href="/favicon.ico">
</code>```

And I can see the icon in a browser at the address https://example.com/favicon.ico

Happy dance!

Body:
I'm building a Django app with a React front end, built using react-create-app. I can't get the favicon to show up in production.

I'm using Django 2.10.0.

When I build the React app, the build output files are put in the assets/static/ folder. This includes image files used as backgrounds via css, and all works fine. These are included in the build because they are referenced in the stylesheets. The favicon is referenced from index.html and therefore isn't picked up by the build process.

However I don't know how to get the server to serve up the favicons. If I put them in the frontend/public folder, the Django server doesn't find them.

If I manually copy them into the static/ folder, they show up but that folder is managed by Webpack and the contents are removed when the app is built.

Copying the favicons into the project root doesn't work. They are in the same folder as index.html, which is served up, but Django server won't serve those co-located image files.

The only documentation I can find deals with either Django or create-react-app; I can't find anything that explains how to tie them together for favicons.

In settings.py:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets/static'),
    os.path.join(BASE_DIR, 'assets'),
]

In index.html:

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />

In the browser, this is converted to:

<link rel="shortcut icon" href="/favicon.ico">

which doesn't work - the file is not served up. I'm not sure why this doesn't work given that I've added 'assets' to STATICFILES_DIRS in settings.py and have copied the favicons into the root of 'assets'.

All the working css and image links include the static folder, e.g.:

http://localhost:8000/static/media/private.d7365d01.svg

It seems like there are two problems:

how to get the build process to copy the favicon and related files into the assets folder so they can be served up

how to get index.html to look in the right place for the favicon

If I could customise PUBLIC_URL to point to static/ that might do it, but that might break other bits of code that reference it?

I am sure I'm missing something simple. I'd be grateful for any help!

Edit: I have now got the favicon to show up in a built version running on my local machine, but it isn't being served by the production server.

Base.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets/static'),
    os.path.join(BASE_DIR, 'assets'),
]

index.html

<link rel="shortcut icon" href="%PUBLIC_URL%/static/favicon.ico" />

And favicon.ico is in the 'assets' folder. After building my React app and running the development server locally, the url http://localhost:8000/static/favicon.ico displays my favicon. But after deploying this to the server, the url https://example.com/static/favicon.ico finds nothing. I have checked and the favicon.ico file is present on the server, in the assets folder. Settings.py is the same. I can't figure out why the production server isn't serving up the favicon?

Edit: I've tried adding this to my settings.py, but it still doesn't work:

STATIC_ROOT = os.path.join(BASE_DIR, 'assets')

'assets' is the name of the folder on the server that contains my build files. The favicons are in assets, as is index.html, and the React files in assets/static.

Edit: this is my Passenger config file for Nginx:

server {
    listen 80;
    server_name 178.62.85.245;

    passenger_python /var/www/myappname/venv36/bin/python3.6;

    # Tell Nginx where your app's 'public' directory is
    root /var/www/myappname/myappname/myappname;

    # Turn on Passenger
    passenger_enabled on;

   # Tell Nginx the location of the build output files
    location /static/ {
       autoindex on;
       alias /var/www/myappname/myappname/assets/;
    }
}

Nginx finds the file index.html and all the files that React built. I don't know why it can't find the favicon in the same folder!

Body:
Per @Little_Brain

Edit: I finally solved this thanks to Sune Kjærgård's help. From reading the Django docs about deployment, I had thought I needed to configure all the static file locations in settings.py. However that seems to be only for the Django development server, even when running with production settings. On the production server I am using Nginx via Passenger to serve the app. It is Nginx that needs to know where all my static files are located. And both 'root' and 'location' need to be set correctly.

Here is my working code. The favicons are served on the production server, and in development on port 3000 when running the frontend separately. I haven't got them served when testing the build locally on port 8000, but I can live with that and maybe find a solution later.

STATIC_ROOT doesn't seem to be required, nor am I running buildstatic.

My favicons are located in frontend/public, the same folder as index.html. The Webpack build process copies them all into the assets folder.

server {
    listen 80;
    server_name 178.62.85.245;

    passenger_python /var/www/myappname/venv36/bin/python3.6;

    # Tell Nginx where your app's 'public' directory is
    root /var/www/myappname/myappname/assets;

    # Turn on Passenger
    passenger_enabled on;

   # Tell Nginx the location of the build output files
    location /static/ {
       autoindex on;
       alias /var/www/myappname/myappname/assets/;
    }
}

In settings.py:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'assets/static'),
    os.path.join(BASE_DIR, 'assets'),
]

In index.html:

<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />

In the browser, this is converted to:

<link rel="shortcut icon" href="/favicon.ico">

And I can see the icon in a browser at the address https://example.com/favicon.ico

Happy dance!


问:
How to change Azure App Services Github workflow deployment environment name

When you create an app there's no option to customize this, it's just there by default.

This matters because sometimes I don't want github actions to say that I'm deploying to "production", I want it to say I'm deploying to "development". But if I change this property manually, I'll get an error in github actions saying: Error: Deployment Failed with Error: Error: Publish profile is invalid for app-name and slot-name provided. Provide correct publish profile credentials for app. But then as soon as it's changed back the deployment works again, so I need to find a way to change this property in Azure?

答: Always the main slot of the webapp is called production, there is no way to change it.</p>


问:
c++ code structure into html files
I work on unix.
I have my complete source code in unix in the form of building blocks and modules.
Like headers,sources files,make files etc.
I can copy all the files with the same directory structure to windows.
I need some tool which will convert all the source to html tags with all the links to functions,variables,classes,headers.There should be some tool to do this easily.
by this way it would be easy for debugging the code in a fast way.

Is anybody aware of such tool?

答: You can use doxygen to generate your documentation. In its basic form it will generate what you need but to add comments that appear in the final html you will need to use special style comments.</p>

Title: c++ code structure into html files


问:
How do i make my button link to the next page without changing the styling of the code? Where am i getting it wrong?
How do I make my button link to the next page without changing the styling?

Here is the HTML:

```<code>  <div class="image-round-fit">

    <img src="images/pic.jpg" alt="photo" width="300px" height="300px" />

    <span class="caption">Hello World</span></br>

      <a href="#" class="btn btn-info role=button">Click Next</a>

  </div>
</code>```

Here is the CSS

.btn {

```<code>background-color: DodgerBlue;

border: none;

color: white;

margin: 50px;

padding: 12px 30px;

cursor: pointer;

font-size: 20px;

display: flex;

align-items: center;

justify-content: center;
</code>```

}

.btn:hover {

```<code>background-color: rgb(255,94,0);
</code>```

}

答:
Try this:

.btn {
  background-color: DodgerBlue;
  border: none;
  color: white;
  margin: 50px;
  padding: 12px 30px;
  cursor: pointer;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-round-fit">
  Click Next
</div></code>```

It is kind of weird that you added the hover css code, because this is the origin of your problem, can you explain why you did this?

Body:
How do I make my button link to the next page without changing the styling?

Here is the HTML:

    Hello World

      Click Next

Here is the CSS

.btn {

background-color: DodgerBlue;

border: none;

color: white;

margin: 50px;

padding: 12px 30px;

cursor: pointer;

font-size: 20px;

display: flex;

align-items: center;

justify-content: center;

}

.btn:hover {

background-color: rgb(255,94,0);

}

Body:
Try this:

.btn {
  background-color: DodgerBlue;
  border: none;
  color: white;
  margin: 50px;
  padding: 12px 30px;
  cursor: pointer;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

<div class="image-round-fit">
  <a href="#" class="btn btn-info role=button">Click Next</a>
</div>

It is kind of weird that you added the hover css code, because this is the origin of your problem, can you explain why you did this?


问:
I'm trying to print one letter after another
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:</p>
```<code>    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }
</code>```

答:
you can do it like this also

const welcText = 'Welcome!';
let i = 0;
const interval = setInterval(() => {
     if (i >= welcText.length) {
          clearInterval(interval);
      } else {
       document.getElementById('helloword').innerHTML += welcText[i];
        i++;
       }
}, 100);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="helloword"></h1></code>```

Body:
I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it?
Code:

    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }

Body:
you can do it like this also

const welcText = 'Welcome!';
let i = 0;
const interval = setInterval(() => {
     if (i >= welcText.length) {
          clearInterval(interval);
      } else {
       document.getElementById('helloword').innerHTML += welcText[i];
        i++;
       }
}, 100);

<h1 id="helloword"></h1>


问:
In a list of lists, how can I find the mean of the values for each subindex?
I want to find the average of each index in a list of lists. Say I have this:

```<code>import statistics

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]
</code>```

I want to find the average of each interior list index, so:

for index 0, I would have the value of (1 + 4 + 7 + 10)/4

for index 1, I would have the value of (2 + 5 + 8 + 11)/4

for index 2, I would have the value of (3 + 9)/2

and so on. How can I do this? Note that I do not need to save the values, just print them as they are computed.

答:
You want to use itertools.zip_longest. You can group together by index, filter out any None elements returns by zip_longest, and then take the mean.

```<code>from itertools import zip_longest
from statistics import mean

for i, group in enumerate(zip_longest(*my_list)):
    print(f'Index {i} mean:', mean(filter(lambda x: x is not None, group)))

# prints:
Index 0 mean: 5.5
Index 1 mean: 6.5
Index 2 mean: 6
</code>```

Body:
I want to find the average of each index in a list of lists. Say I have this:

import statistics

my_list = [[1, 2, 3], [4, 5], [7, 8, 9], [10, 11]]

I want to find the average of each interior list index, so:

for index 0, I would have the value of (1 + 4 + 7 + 10)/4

for index 1, I would have the value of (2 + 5 + 8 + 11)/4

for index 2, I would have the value of (3 + 9)/2

and so on. How can I do this? Note that I do not need to save the values, just print them as they are computed.

Body:
You want to use itertools.zip_longest. You can group together by index, filter out any None elements returns by zip_longest, and then take the mean.

from itertools import zip_longest
from statistics import mean

for i, group in enumerate(zip_longest(*my_list)):
    print(f'Index {i} mean:', mean(filter(lambda x: x is not None, group)))

# prints:
Index 0 mean: 5.5
Index 1 mean: 6.5
Index 2 mean: 6


问:
I am having trouble making python dictionary or list
I am very new to python and have a script that i wrote in PowerShell that I would like to recreate in python.

in powershell i have created a hashtable:

```<code>   $epBody = @{
                    "escalation_policy"   = @{
                        "type"               =   "escalation_policy"
                        "name"               =   $epName
                        "escalation_rules"   = @(
                            @{
                                "escalation_delay_in_minutes" = 30
                                "targets"                     = @(
                                    @{
                                        "id"    = $userid
                                        "type"  = "user_reference"
                                    }
                                )
                            }
                        )
                    }
                }

</code>```

And trying to figure out the best way to write this in python.

this is what i have (which i know is wrong!):

```<code>ep_payload = {
                "escalation_policy": {
                        "type": "escalation_policy",
                        "name": epName,
                        "escalation_rules": [
                            {
                                "escalation_delay_in_minutes": 30,
                                "targets": [
                                    {
                                        "id": userid
                                        "type": "user_reference"
                                    }
                        ]
                            }
                        ]
                    }
                }
</code>```

I just cannot figure out the correct syntax for this one

cheers,

答: "Let's eat Grandma",  "Lets eat, Grandma"  Commas save lives!</p>

Body:
I am very new to python and have a script that i wrote in PowerShell that I would like to recreate in python.

in powershell i have created a hashtable:

   $epBody = @{
                    "escalation_policy"   = @{
                        "type"               =   "escalation_policy"
                        "name"               =   $epName
                        "escalation_rules"   = @(
                            @{
                                "escalation_delay_in_minutes" = 30
                                "targets"                     = @(
                                    @{
                                        "id"    = $userid
                                        "type"  = "user_reference"
                                    }
                                )
                            }
                        )
                    }
                }

And trying to figure out the best way to write this in python.

this is what i have (which i know is wrong!):

ep_payload = {
                "escalation_policy": {
                        "type": "escalation_policy",
                        "name": epName,
                        "escalation_rules": [
                            {
                                "escalation_delay_in_minutes": 30,
                                "targets": [
                                    {
                                        "id": userid
                                        "type": "user_reference"
                                    }
                        ]
                            }
                        ]
                    }
                }

I just cannot figure out the correct syntax for this one

cheers,


问:
Can I listen for Ctrl+C at the Psychopy console window?
Will it register KeyboardInterrupt exception instead? The application logic assumes there will be at least one Psychopy window active at the time, but the keyboard commands can be input into the console window.

答: You can see my code to capture control-C, an explanation of how/why it works, a trap to avoid in making it work with PsychoPy's waitKeys(), and a pointer to another helpful stackoverflow discussion, here.


问:
What recursive function can I use to substitute the characters in a string by the greatest character on its right?
I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.

If I have a string acbcba the function has to return ccccba.

One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:

```<code>void nextGreatest(char *str, int size)
{
  int max_from_right =  str[size-1];

  str[size-1] = -1;
  for(int i = size-2; i >= 0; i--)
  {
    int temp = str[i];
    str[i] = max_from_right;
    if(max_from_right < temp)
       max_from_right = temp;
  }
}

Output: cccba
</code>```

I think the issue is that it doesn't count the characters that don't have to be replaced.

There was also another example using python I found and tried to change to C (MAX is a macro from here):

```<code>void nextGreatest(char *arr, int rev_i, int maxnum){
        if (rev_i == strlen(arr) - 1){
            arr[0] = maxnum;
            return;
        }
        int i = strlen(arr) - 1 - rev_i;
        arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
        return nextGreatest(arr, rev_i + 1, maxnum);
}

Output: ~bccba
</code>```

答:
This is a simple problem of recursion. The idea is, you MUST cross once over the full string to detect what is the maximum and to keep the index the maximum occurred at, and a the second pass over the string to replace some characters at indexes less than the index of the maximum with the maximum you detected at the first loop.   I wrote this code for you:

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

void
replace_max_char(char*s, char **index, char *max)
{
  if (!*s) return;
  if (*s>=*max)
    *index = s, *max = *s;
  replace_max_char(s+1, index, max);

  if (s<*index)
    *s=*max;
}

int
main(void)
{
  char s[] = "acbcba", *index, max;
  replace_max_char(s, &index, &max);
  printf("%s\n", s);
  return 0;
}
</code>```

Notice the if (s<*index) after the recursive call of replace_max_char(s+1, index, max).  When the recursion finishes, it will start executing the stacked if... and at that moment the maximum is known and also the index the maximum occurred at.

Body:
I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.

If I have a string acbcba the function has to return ccccba.

One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:

void nextGreatest(char *str, int size)
{
  int max_from_right =  str[size-1];

  str[size-1] = -1;
  for(int i = size-2; i >= 0; i--)
  {
    int temp = str[i];
    str[i] = max_from_right;
    if(max_from_right < temp)
       max_from_right = temp;
  }
}

Output: cccba

I think the issue is that it doesn't count the characters that don't have to be replaced.

There was also another example using python I found and tried to change to C (MAX is a macro from here):

void nextGreatest(char *arr, int rev_i, int maxnum){
        if (rev_i == strlen(arr) - 1){
            arr[0] = maxnum;
            return;
        }
        int i = strlen(arr) - 1 - rev_i;
        arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
        return nextGreatest(arr, rev_i + 1, maxnum);
}

Output: ~bccba

Body:
This is a simple problem of recursion. The idea is, you MUST cross once over the full string to detect what is the maximum and to keep the index the maximum occurred at, and a the second pass over the string to replace some characters at indexes less than the index of the maximum with the maximum you detected at the first loop.   I wrote this code for you:

#include <stdio.h>

void
replace_max_char(char*s, char **index, char *max)
{
  if (!*s) return;
  if (*s>=*max)
    *index = s, *max = *s;
  replace_max_char(s+1, index, max);

  if (s<*index)
    *s=*max;
}

int
main(void)
{
  char s[] = "acbcba", *index, max;
  replace_max_char(s, &index, &max);
  printf("%s\n", s);
  return 0;
}

Notice the if (s<*index) after the recursive call of replace_max_char(s+1, index, max).  When the recursion finishes, it will start executing the stacked if... and at that moment the maximum is known and also the index the maximum occurred at.


问:
Can I do another merge of the same feature branch after a merge?
Here's the scenario:

I have finished working on my feature branch A.

I commit my changes and check out in development

I merge the feature branch A into development

before I git push, I realize that I forgot something in the feature Branch
A (delete inline comment)

Can i do again?

check out to feature branch A and delete the comment.

Then commit the change and check out again in development.

Then again merge the feature branch A into development.

Question Is this possible follow steps 1 to 7 or I have to do create a new branch afterwards point 4. to make the changes? Thanks in advence!

答:
The simplest thing, since you have not pushed, is just reset hard to the commit before the merge commit in development. Assuming the merge is the last you thing you did in development, you would say:

```<code>git switch development
git reset --hard @^1
</code>```

So now it is exactly as if you never merged! So then switch to the feature branch, fix it, and do the merge again.

Body:
The simplest thing, since you have not pushed, is just reset hard to the commit before the merge commit in development. Assuming the merge is the last you thing you did in development, you would say:

git switch development
git reset --hard @^1

So now it is exactly as if you never merged! So then switch to the feature branch, fix it, and do the merge again.