问:
C# IntelliSense not working for Visual Studio Code. Not sure what else to try
I am learning Unity and I am trying to get IntelliSense to work for C#, but every time I launch VS Code it gives me an error on the bottom right saying:

Some projects have trouble loading. Please review the output for more details.

Output:

```<code>Starting OmniSharp server at 1/12/2023, 9:54:47 PM
    Target: c:\Users\Super Bub\Desktop\Test_Multiplayer\Test_Multiplayer.sln

OmniSharp server started with .NET 7.0.100
.
    Path: c:\Users\Super Bub\.vscode\extensions\ms-dotnettools.csharp-1.25.2-win32-x64\.omnisharp\1.39.2-net6.0\OmniSharp.dll
    PID: 2360

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 10.0.19044.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        Checking the 'DOTNET_ROOT' environment variable to find a .NET SDK
[info]: OmniSharp.Services.DotNetCliService
        Using the 'dotnet' on the PATH.
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: .NET Core SDK 7.0.100 17.4.0 - "C:\Program Files\dotnet\sdk\7.0.100\"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: .NET Core SDK 7.0.100 17.4.0 - "C:\Program Files\dotnet\sdk\7.0.100\"
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in 'c:\Users\Super Bub\Desktop\Test_Multiplayer'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Did not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in 'c:\Users\Super Bub\Desktop\Test_Multiplayer\Test_Multiplayer.sln'.
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for 'c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj'
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in 'c:\Users\Super Bub\Desktop\Test_Multiplayer'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Did not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location 'c:\Users\Super Bub\Desktop\Test_Multiplayer' on host 20368.
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj
[fail]: OmniSharp.MSBuild.ProjectLoader
        The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj'.
c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj
C:\Program Files\dotnet\sdk\7.0.100\Microsoft.Common.CurrentVersion.targets(1229,5): Error: The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj
[warn]: OmniSharp.Roslyn.CSharp.Services.InlayHints.InlayHintService
        Inlay hints requested for document not in workspace Location { FileName = c:\Users\Super Bub\Desktop\Test_Multiplayer\Assets\Scripts\NetworkManagerUI.cs, Range = Range { Start = Point { Line = 0, Column = 0 }, End = Point { Line = 19, Column = 0 } } }
</code>```

I have the latest version of .NET SDK installed and the C# extension aswell as the rest of my extensions are updated. I have tried re-installing .NET SDK and VS Code but nothing works. omnisharp.useModernNet is set to true in settings and my External Script Editor is set to Visual Studio Code. I am using Windows 10. I got intellisense to work on a different computer that I can't use often, so not having it now is very frustrating.

Thanks for any help.

Body:
I am learning Unity and I am trying to get IntelliSense to work for C#, but every time I launch VS Code it gives me an error on the bottom right saying:

Some projects have trouble loading. Please review the output for more details.

Output:

Starting OmniSharp server at 1/12/2023, 9:54:47 PM
    Target: c:\Users\Super Bub\Desktop\Test_Multiplayer\Test_Multiplayer.sln

OmniSharp server started with .NET 7.0.100
.
    Path: c:\Users\Super Bub\.vscode\extensions\ms-dotnettools.csharp-1.25.2-win32-x64\.omnisharp\1.39.2-net6.0\OmniSharp.dll
    PID: 2360

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 10.0.19044.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        Checking the 'DOTNET_ROOT' environment variable to find a .NET SDK
[info]: OmniSharp.Services.DotNetCliService
        Using the 'dotnet' on the PATH.
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: .NET Core SDK 7.0.100 17.4.0 - "C:\Program Files\dotnet\sdk\7.0.100\"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: .NET Core SDK 7.0.100 17.4.0 - "C:\Program Files\dotnet\sdk\7.0.100\"
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in 'c:\Users\Super Bub\Desktop\Test_Multiplayer'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Did not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in 'c:\Users\Super Bub\Desktop\Test_Multiplayer\Test_Multiplayer.sln'.
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for 'c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj'
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in 'c:\Users\Super Bub\Desktop\Test_Multiplayer'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Did not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location 'c:\Users\Super Bub\Desktop\Test_Multiplayer' on host 20368.
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj
[fail]: OmniSharp.MSBuild.ProjectLoader
        The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj'.
c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj
C:\Program Files\dotnet\sdk\7.0.100\Microsoft.Common.CurrentVersion.targets(1229,5): Error: The reference assemblies for .NETFramework,Version=v4.7.1 were not found. To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application. You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: c:\Users\Super Bub\Desktop\Test_Multiplayer\Assembly-CSharp.csproj
[warn]: OmniSharp.Roslyn.CSharp.Services.InlayHints.InlayHintService
        Inlay hints requested for document not in workspace Location { FileName = c:\Users\Super Bub\Desktop\Test_Multiplayer\Assets\Scripts\NetworkManagerUI.cs, Range = Range { Start = Point { Line = 0, Column = 0 }, End = Point { Line = 19, Column = 0 } } }

I have the latest version of .NET SDK installed and the C# extension aswell as the rest of my extensions are updated. I have tried re-installing .NET SDK and VS Code but nothing works. omnisharp.useModernNet is set to true in settings and my External Script Editor is set to Visual Studio Code. I am using Windows 10. I got intellisense to work on a different computer that I can't use often, so not having it now is very frustrating.

Thanks for any help.


来源: stackexchange

问:
How to call/use a variable in electron main process (index.js) to use in a react component
I am new in electron and currently developing a desktop app using electron with reactjs. I made a url protocol so i can open the app from browser while passing some parameters. I already figured out way to open the app from browser with passing some parameters. Is there any efficient approach to do this?
For example :

I store the protocol to a variable (urlParam).

index.js

```<code>  app.setAsDefaultProtocolClient('openApp');

  urlParam = process.argv[1];
  mainWindow.webContents.openDevTools()
  mainWindow.webContents.executeJavaScript(`console.log("${urlParam}")`)
</code>```

The variable store a value like this openApp://id=12312412&pwd=12312313.

I need to pass and use urlParam to process the parameters in my react component.
For example I want to console.log the value when I click the button.

component.js (scratch)

```<code>export default function LintingTab(props) {

  const getUrl= () => {
    console.log('urlParam');
  }

  return (
    <button onClick={getUrl}>Console log the url param</button>
  )
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new in electron and currently developing a desktop app using electron with reactjs. I made a url protocol so i can open the app from browser while passing some parameters. I already figured out way to open the app from browser with passing some parameters. Is there any efficient approach to do this?
For example :

I store the protocol to a variable (urlParam).

index.js

  app.setAsDefaultProtocolClient('openApp');

  urlParam = process.argv[1];
  mainWindow.webContents.openDevTools()
  mainWindow.webContents.executeJavaScript(`console.log("${urlParam}")`)

The variable store a value like this openApp://id=12312412&pwd=12312313.

I need to pass and use urlParam to process the parameters in my react component.
For example I want to console.log the value when I click the button.

component.js (scratch)

export default function LintingTab(props) {

  const getUrl= () => {
    console.log('urlParam');
  }

  return (
    <button onClick={getUrl}>Console log the url param</button>
  )
}


问:
How can a task list be extracted from a conversational text using NLP?
I have transcript of a conversation and I am trying to extract the tasks/ promises that were made during that conversation. Is there an existing model/ library which can be used to extract such points?</p>


问:
Remove outliers from a data set using the IQR and the sliding window approach
I am trying to remove outliers from a data frame using the IQR and sliding window approach. However, the indices do not seem to show any outliers even though l can see them when l make a plot. What can be wrong?

I created a for loop with a window size of 100 then tried using this window to calculate the IQR after every 100 steps to remove the Outliers. The results are not showing any values even though the outliers are still there.

```<code>index_list=[]

def outliers(df, ft):
    Q1 = df[ft].quantile(0.25)
    Q3 = df[ft].quantile(0.75)
    IQR=Q3-Q1
    lower_bound=Q1-1.5*IQR
    Upper_bound=Q3+1.5*IQR

    ls=df.index[ (df[ft]<lower_bound) | (df[ft]>Upper_bound)]
    return ls

def remove(df,ls):
    ls=sorted(set(ls))
    df=df.drop(ls)
    return df

for i in np.arange(0,900,100):

    for feature in ['Discharge_capacity','cycle_index']:
        index_list.extend(outliers(df3,feature))
        df6_cleaned=remove(df3,index_list)

</code>```

Body:
I am trying to remove outliers from a data frame using the IQR and sliding window approach. However, the indices do not seem to show any outliers even though l can see them when l make a plot. What can be wrong?

I created a for loop with a window size of 100 then tried using this window to calculate the IQR after every 100 steps to remove the Outliers. The results are not showing any values even though the outliers are still there.

index_list=[]

def outliers(df, ft):
    Q1 = df[ft].quantile(0.25)
    Q3 = df[ft].quantile(0.75)
    IQR=Q3-Q1
    lower_bound=Q1-1.5*IQR
    Upper_bound=Q3+1.5*IQR

    ls=df.index[ (df[ft]<lower_bound) | (df[ft]>Upper_bound)]
    return ls

def remove(df,ls):
    ls=sorted(set(ls))
    df=df.drop(ls)
    return df

for i in np.arange(0,900,100):

    for feature in ['Discharge_capacity','cycle_index']:
        index_list.extend(outliers(df3,feature))
        df6_cleaned=remove(df3,index_list)


问:
How do I center widgets in a RowColumn with horizontal orientation in X11/Motif?
I am writing a replacement for xmmix that can switch between the different audio devices.

I would like to know how could I center the widgets. As seen in the image, they are added to the left. In this example, each audio slider control is Managed inside a RowColumn widget manager (see CREATE SLIDE WIDGET CONTAINER in draw_scale()) and each slider control is added to a horizontal RowColumn widget manager (see SLIDES COLUMN in main()). This big container for all the sliders has black background to easily notice that it takes all the width of the window but the inner RowColumns are drawn always on the left. I would like them to be centered.

Also I was expecting each slider container to take all the available height of the outer container because of the XmNbottomAttachment, XmATTACH_FORM, but that is not working.

```<code>#include <Xm/Xm.h>
#include <Xm/PushB.h>
#include <Xm/MainW.h>
#include <Xm/Label.h>
#include <Xm/Form.h>
#include <Xm/Scale.h>
#include <Xm/RowColumn.h>

#include <stdio.h>
#include <stdlib.h>

#include "devices.h"

struct button_data {
   int device_num;
   Widget button;
};

struct scale_data {
   int scale_num;
   Widget slide_widget;
   Widget label;
   Widget scale_container;
   Widget scale_left;
   Widget scale_right;
   Widget lock;
};

/* GLOBAL VARIABLES */
int num_devices;
struct device *devices;
int num_channels;
struct channel *channels;

struct button_data *buttons;
struct scale_data *scales;

void button_callback(Widget widget, XtPointer client_data, XtPointer call_data);
void create_device_buttons(Widget parent, struct device *devices, int num_devices);
void create_channel_scales(Widget parent, struct channel *channels, int num_channels);
void set_rc_background(Widget rc);
void draw_scale(Widget parent, struct scale_data *s, struct channel *c);
void to_upper(char *str);

void to_upper(char *str) {

   int j=0;

   while (str[j]) {
      str[j] = toupper(str[j]);
      j++;
   }

}

void draw_scale(Widget parent, struct scale_data *s, struct channel *c) {

   Arg args[10];
   int n;
   char widget_name_slide[32];
   char widget_name_slide_label[32];
   char widget_name_scale_container[32];
   char widget_name_scale_left[32];
   char widget_name_scale_right[32];
   char widget_name_slide_lock[32];

   sprintf(widget_name_slide,          "slide_%02d", c->number);
   sprintf(widget_name_slide_label,     "slide_label_%02d", c->number);
   sprintf(widget_name_scale_container, "scale_container_%02d", c->number);
   sprintf(widget_name_scale_left,      "scale_left_%02d", c->number);
   sprintf(widget_name_scale_right,     "scale_right_%02d", c->number);
   sprintf(widget_name_slide_lock,      "slide_lock_%02d", c->number);

   /* CREATE SLIDE WIDGET CONTAINER */
   n = 0;
   XtSetArg(args[n], XmNorientation, XmVERTICAL); n++;
   XtSetArg(args[n], XmNentryAlignment, XmALIGNMENT_CENTER); n++;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); n++;
   s->slide_widget = XmCreateRowColumn(parent, widget_name_slide, args, n);
   XtManageChild(s->slide_widget);

   /* CREATE SLIDE LABEL */
   XmString label;
   to_upper(c->description);
   label = XmStringCreateLocalized(c->description);
   n = 0;
   XtSetArg(args[n], XmNlabelString, label); n++;
   s->label = XmCreateLabel(s->slide_widget, widget_name_slide_label, args, n);
   XmStringFree(label);
   XtManageChild(s->label);

   /* CREATE SCALE CONTAINER */
   n = 0;
   XtSetArg(args[n], XmNorientation, XmHORIZONTAL); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); n++;
   s->scale_container = XmCreateRowColumn(s->slide_widget, widget_name_scale_container, args, n);
   XtManageChild(s->scale_container);

   /* CREATE SCALE LEFT */
   n = 0;
   XtSetArg(args[n], XmNshowValue, False); n++;
   XtSetArg(args[n], XmNvalue, c->value_left); n++;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNrightWidget, s->scale_right); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   s->scale_left = XmCreateScale(s->scale_container, widget_name_scale_left, args, n);
   XtManageChild(s->scale_left);

   /* CREATE SCALE RIGHT */
   n = 0;
   XtSetArg(args[n], XmNshowValue, False); n++;
   XtSetArg(args[n], XmNvalue, c->value_right); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNleftWidget, s->scale_left); n++;
   s->scale_right = XmCreateScale(s->scale_container, widget_name_scale_right, args, n);
   XtManageChild(s->scale_right);

}

void create_channel_scales(Widget parent, struct channel *channels, int num_channels) {

   int i;
   Arg args[5];
   int n;

   scales = malloc(num_channels * sizeof(struct scale_data));
   if (scales == NULL) {
      perror("Failed to allocate memory");
      exit(EXIT_FAILURE);
   }

   /* CREATE CHANNEL SLIDERS */
   for (i = 0; i < num_channels; i++) {

      scales[i].scale_num = channels[i].number;
      draw_scale(parent, &(scales[i]), &(channels[i]));

   }
}

void button_callback(Widget widget, XtPointer client_data, XtPointer call_data) {
   int i;
   struct button_data *data = (struct button_data *)client_data;
   int device_num = data->device_num;

   // unclick all other buttons
   for (i = 0; i < num_devices; i++) {
      if (buttons[i].button != widget) {
         XtVaSetValues(buttons[i].button, XmNset, False, NULL);
         XmUpdateDisplay(buttons[i].button);
      }
   }

   // click this button
   XtVaSetValues(widget, XmNset, True, NULL);
   XmUpdateDisplay(widget);

   // set audio device
   set_audio_device(device_num);
}

void create_device_buttons(Widget parent, struct device *devices, int num_devices) {
   int i;
   XmString label;
   Arg args[5];
   int n;

   buttons = malloc(num_devices * sizeof(struct button_data));
   if (buttons == NULL) {
      perror("Failed to allocate memory");
      exit(EXIT_FAILURE);
   }

   /* CREATE DEVICE SELECTOR */
   for (i = 0; i < num_devices; i++) {
      // create button
      n = 0;
      label = XmStringCreateLocalized(devices[i].description);
      XtSetArg(args[n], XmNlabelString, label); n++;
      buttons[i].button = XmCreatePushButton(parent, "device_button", args, n);
      XmStringFree(label);
      XtManageChild(buttons[i].button);

      // set button data
      buttons[i].device_num = devices[i].number;

      // set button callback
      XtAddCallback(buttons[i].button, XmNactivateCallback, button_callback, &buttons[i]);
   }
}

int main(int argc, char *argv[]) {
   XtAppContext app;
   Widget top_level, main_window, button_rowcolumn, slides_rowcolumn;
   Widget scales_pane, devices_pane;
   int default_device;
   int i;

   int n=0;
   Arg args[10];

   //top_level = XtVaOpenApplication(&app, "XAudio", NULL, 0, &argc, argv, NULL, sessionShellWidgetClass, NULL);
   top_level = XtVaAppInitialize(&app, "XAudio", NULL, 0, &argc, argv, NULL, NULL);
   fprintf(stderr, "DEBUG 10\n");

   /* CONTAINER FORM */
   n=0;
   XtSetArg(args[n], XmNresizable, True); n++;
   XtSetArg(args[n], XmNresizePolicy, XmRESIZE_GROW); n++;
   main_window = XmCreateForm(top_level, "main_window", args, n);
   XtManageChild(main_window);

   /* BUTTON ROW */
   n=0;
   XtSetArg(args[n], XmNorientation, XmVERTICAL); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   button_rowcolumn = XmCreateRowColumn(main_window, "button_rowcolumn", args, n);
   XtManageChild(button_rowcolumn);

   /* SLIDES COLUMN */
   n=0;
   XtSetArg(args[n], XmNorientation, XmHORIZONTAL); n++;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNbottomWidget, button_rowcolumn); n++;
   slides_rowcolumn = XmCreateRowColumn(main_window, "slides_rowcolumn", args, n);
   XtManageChild(slides_rowcolumn);
   set_rc_background(slides_rowcolumn);

   /* GET LIST OF DEVICES AND DEFAULT DEVICE */
   default_device = get_default_device(&devices, &num_devices);
   for(i=0; i<num_devices; i++) {
        printf("%d %s\n", devices[i].number, devices[i].description);
   }

   /* GET LIST OF CHANNELS */
   get_mixer_channels(&channels, &num_channels);
   printf("num_channels %d\n", num_channels);
   for(i=0; i<num_channels; i++) {
        printf("%d %s [%03d-%03d]\n", i, channels[i].description, channels[i].value_left, channels[i].value_right);
   }

   create_device_buttons(button_rowcolumn, devices, num_devices);
   create_channel_scales(slides_rowcolumn, channels, num_channels);

   XtRealizeWidget(top_level);

   /* CLICK DEFAULT BUTTON */
   if (default_device >= 0) {
      XtVaSetValues(buttons[default_device].button, XmNset, True, NULL);
        XmUpdateDisplay(buttons[default_device].button);
   }

   XtAppMainLoop(app);

   free(devices);
   free(buttons);

   return 0;
}
</code>```

Body:
I am writing a replacement for xmmix that can switch between the different audio devices.

I would like to know how could I center the widgets. As seen in the image, they are added to the left. In this example, each audio slider control is Managed inside a RowColumn widget manager (see CREATE SLIDE WIDGET CONTAINER in draw_scale()) and each slider control is added to a horizontal RowColumn widget manager (see SLIDES COLUMN in main()). This big container for all the sliders has black background to easily notice that it takes all the width of the window but the inner RowColumns are drawn always on the left. I would like them to be centered.

Also I was expecting each slider container to take all the available height of the outer container because of the XmNbottomAttachment, XmATTACH_FORM, but that is not working.

#include <Xm/Xm.h>
#include <Xm/PushB.h>
#include <Xm/MainW.h>
#include <Xm/Label.h>
#include <Xm/Form.h>
#include <Xm/Scale.h>
#include <Xm/RowColumn.h>

#include <stdio.h>
#include <stdlib.h>

#include "devices.h"

struct button_data {
   int device_num;
   Widget button;
};

struct scale_data {
   int scale_num;
   Widget slide_widget;
   Widget label;
   Widget scale_container;
   Widget scale_left;
   Widget scale_right;
   Widget lock;
};

/* GLOBAL VARIABLES */
int num_devices;
struct device *devices;
int num_channels;
struct channel *channels;

struct button_data *buttons;
struct scale_data *scales;

void button_callback(Widget widget, XtPointer client_data, XtPointer call_data);
void create_device_buttons(Widget parent, struct device *devices, int num_devices);
void create_channel_scales(Widget parent, struct channel *channels, int num_channels);
void set_rc_background(Widget rc);
void draw_scale(Widget parent, struct scale_data *s, struct channel *c);
void to_upper(char *str);

void to_upper(char *str) {

   int j=0;

   while (str[j]) {
      str[j] = toupper(str[j]);
      j++;
   }

}

void draw_scale(Widget parent, struct scale_data *s, struct channel *c) {

   Arg args[10];
   int n;
   char widget_name_slide[32];
   char widget_name_slide_label[32];
   char widget_name_scale_container[32];
   char widget_name_scale_left[32];
   char widget_name_scale_right[32];
   char widget_name_slide_lock[32];

   sprintf(widget_name_slide,          "slide_%02d", c->number);
   sprintf(widget_name_slide_label,     "slide_label_%02d", c->number);
   sprintf(widget_name_scale_container, "scale_container_%02d", c->number);
   sprintf(widget_name_scale_left,      "scale_left_%02d", c->number);
   sprintf(widget_name_scale_right,     "scale_right_%02d", c->number);
   sprintf(widget_name_slide_lock,      "slide_lock_%02d", c->number);

   /* CREATE SLIDE WIDGET CONTAINER */
   n = 0;
   XtSetArg(args[n], XmNorientation, XmVERTICAL); n++;
   XtSetArg(args[n], XmNentryAlignment, XmALIGNMENT_CENTER); n++;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); n++;
   s->slide_widget = XmCreateRowColumn(parent, widget_name_slide, args, n);
   XtManageChild(s->slide_widget);

   /* CREATE SLIDE LABEL */
   XmString label;
   to_upper(c->description);
   label = XmStringCreateLocalized(c->description);
   n = 0;
   XtSetArg(args[n], XmNlabelString, label); n++;
   s->label = XmCreateLabel(s->slide_widget, widget_name_slide_label, args, n);
   XmStringFree(label);
   XtManageChild(s->label);

   /* CREATE SCALE CONTAINER */
   n = 0;
   XtSetArg(args[n], XmNorientation, XmHORIZONTAL); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNpacking, XmPACK_TIGHT); n++;
   s->scale_container = XmCreateRowColumn(s->slide_widget, widget_name_scale_container, args, n);
   XtManageChild(s->scale_container);

   /* CREATE SCALE LEFT */
   n = 0;
   XtSetArg(args[n], XmNshowValue, False); n++;
   XtSetArg(args[n], XmNvalue, c->value_left); n++;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNrightWidget, s->scale_right); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   s->scale_left = XmCreateScale(s->scale_container, widget_name_scale_left, args, n);
   XtManageChild(s->scale_left);

   /* CREATE SCALE RIGHT */
   n = 0;
   XtSetArg(args[n], XmNshowValue, False); n++;
   XtSetArg(args[n], XmNvalue, c->value_right); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNleftWidget, s->scale_left); n++;
   s->scale_right = XmCreateScale(s->scale_container, widget_name_scale_right, args, n);
   XtManageChild(s->scale_right);

}

void create_channel_scales(Widget parent, struct channel *channels, int num_channels) {

   int i;
   Arg args[5];
   int n;

   scales = malloc(num_channels * sizeof(struct scale_data));
   if (scales == NULL) {
      perror("Failed to allocate memory");
      exit(EXIT_FAILURE);
   }

   /* CREATE CHANNEL SLIDERS */
   for (i = 0; i < num_channels; i++) {

      scales[i].scale_num = channels[i].number;
      draw_scale(parent, &(scales[i]), &(channels[i]));

   }
}

void button_callback(Widget widget, XtPointer client_data, XtPointer call_data) {
   int i;
   struct button_data *data = (struct button_data *)client_data;
   int device_num = data->device_num;

   // unclick all other buttons
   for (i = 0; i < num_devices; i++) {
      if (buttons[i].button != widget) {
         XtVaSetValues(buttons[i].button, XmNset, False, NULL);
         XmUpdateDisplay(buttons[i].button);
      }
   }

   // click this button
   XtVaSetValues(widget, XmNset, True, NULL);
   XmUpdateDisplay(widget);

   // set audio device
   set_audio_device(device_num);
}

void create_device_buttons(Widget parent, struct device *devices, int num_devices) {
   int i;
   XmString label;
   Arg args[5];
   int n;

   buttons = malloc(num_devices * sizeof(struct button_data));
   if (buttons == NULL) {
      perror("Failed to allocate memory");
      exit(EXIT_FAILURE);
   }

   /* CREATE DEVICE SELECTOR */
   for (i = 0; i < num_devices; i++) {
      // create button
      n = 0;
      label = XmStringCreateLocalized(devices[i].description);
      XtSetArg(args[n], XmNlabelString, label); n++;
      buttons[i].button = XmCreatePushButton(parent, "device_button", args, n);
      XmStringFree(label);
      XtManageChild(buttons[i].button);

      // set button data
      buttons[i].device_num = devices[i].number;

      // set button callback
      XtAddCallback(buttons[i].button, XmNactivateCallback, button_callback, &buttons[i]);
   }
}

int main(int argc, char *argv[]) {
   XtAppContext app;
   Widget top_level, main_window, button_rowcolumn, slides_rowcolumn;
   Widget scales_pane, devices_pane;
   int default_device;
   int i;

   int n=0;
   Arg args[10];

   //top_level = XtVaOpenApplication(&app, "XAudio", NULL, 0, &argc, argv, NULL, sessionShellWidgetClass, NULL);
   top_level = XtVaAppInitialize(&app, "XAudio", NULL, 0, &argc, argv, NULL, NULL);
   fprintf(stderr, "DEBUG 10\n");

   /* CONTAINER FORM */
   n=0;
   XtSetArg(args[n], XmNresizable, True); n++;
   XtSetArg(args[n], XmNresizePolicy, XmRESIZE_GROW); n++;
   main_window = XmCreateForm(top_level, "main_window", args, n);
   XtManageChild(main_window);

   /* BUTTON ROW */
   n=0;
   XtSetArg(args[n], XmNorientation, XmVERTICAL); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_FORM); n++;
   button_rowcolumn = XmCreateRowColumn(main_window, "button_rowcolumn", args, n);
   XtManageChild(button_rowcolumn);

   /* SLIDES COLUMN */
   n=0;
   XtSetArg(args[n], XmNorientation, XmHORIZONTAL); n++;
   XtSetArg(args[n], XmNtopAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNbottomAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNleftAttachment, XmATTACH_FORM); n++;
   XtSetArg(args[n], XmNrightAttachment, XmATTACH_WIDGET); n++;
   XtSetArg(args[n], XmNbottomWidget, button_rowcolumn); n++;
   slides_rowcolumn = XmCreateRowColumn(main_window, "slides_rowcolumn", args, n);
   XtManageChild(slides_rowcolumn);
   set_rc_background(slides_rowcolumn);

   /* GET LIST OF DEVICES AND DEFAULT DEVICE */
   default_device = get_default_device(&devices, &num_devices);
   for(i=0; i<num_devices; i++) {
        printf("%d %s\n", devices[i].number, devices[i].description);
   }

   /* GET LIST OF CHANNELS */
   get_mixer_channels(&channels, &num_channels);
   printf("num_channels %d\n", num_channels);
   for(i=0; i<num_channels; i++) {
        printf("%d %s [%03d-%03d]\n", i, channels[i].description, channels[i].value_left, channels[i].value_right);
   }

   create_device_buttons(button_rowcolumn, devices, num_devices);
   create_channel_scales(slides_rowcolumn, channels, num_channels);

   XtRealizeWidget(top_level);

   /* CLICK DEFAULT BUTTON */
   if (default_device >= 0) {
      XtVaSetValues(buttons[default_device].button, XmNset, True, NULL);
        XmUpdateDisplay(buttons[default_device].button);
   }

   XtAppMainLoop(app);

   free(devices);
   free(buttons);

   return 0;
}


问:
Values update in variables of Getx controller class is not updating after recreating the controller class Flutter web
I am using Getx arcticterure.I want to load initstate of same class with same API with different parameters after doing a filter.
For that I deleted the controller and load the same screen ,

```<code> FilterTabs(
            title: e['key'].toString(),
            onTap: ()async{
                       await Get.delete<NewsDetailsController>();
                       Get.offAndToNamed('/frontpage');
                          },
            )
</code>```

/frontpage is _WebDashbordViewState

Below code is my controllers,

```<code>class _WebDashbordViewState extends State<WebDashbordView> {
  final NewsDetailsController controller = Get.put(NewsDetailsController());
  final sideViewController = Get.put(SideViewController());
}
</code>```

Inside this class I have an another widget called DashBoardTitleWidget()
In that class I am trying to call NewsDetailsController and SideViewController

```<code>class DashBoardTitleWidget extends StatelessWidget {
   DashBoardTitleWidget({Key? key}) : super(key: key);
    final  sideViewController = Get.put(SideViewController());
   final  controller = Get.put(NewsDetailsController());
  @override
  Widget build(BuildContext context) {
        return
          MouseRegion(
            cursor: SystemMouseCursors.click,
            child: GestureDetector(
              onTap:
                  (){
                try{
                  controller.isRecommendationVisible.value=false;
                  controller.newsTitle.value="";
                  controller.newsUrl.value="";
                  sideViewController.viewAllType.value="";
                  controller.contentSummary.value="";
                  controller.selectedIndexForRec.value = -1;
                  controller.selectedIndexForSimilar.value=-1;
                  controller.selectedIndexForRecommend.value=-1;
                  controller.selectedIndexForAllNews.value=-1;
                  print("vlaus is ${controller.isRecommendationVisible.value}");
                }catch(e){
                  print("exc is $e");
                }

              },
              child: Container(
                decoration: BoxDecoration(
                  color: Color(0xffEAEAEA),
                  shape: BoxShape.circle
                ),
                child:Padding(
                  padding: const EdgeInsets.all(3.0),
                  child: Icon(
                    key:Key('pclose'),
                    Icons.clear,color: Color(0xff222B45),size: 15,),
                ) ,
              ),
            ),
          );
    //   }
    // );
  }
}
</code>```

All value inside ontap is assigned to variable but that is not reflect in UI after filtering

Body:
I am using Getx arcticterure.I want to load initstate of same class with same API with different parameters after doing a filter.
For that I deleted the controller and load the same screen ,

 FilterTabs(
            title: e['key'].toString(),
            onTap: ()async{
                       await Get.delete<NewsDetailsController>();
                       Get.offAndToNamed('/frontpage');
                          },
            )

/frontpage is _WebDashbordViewState

Below code is my controllers,

class _WebDashbordViewState extends State<WebDashbordView> {
  final NewsDetailsController controller = Get.put(NewsDetailsController());
  final sideViewController = Get.put(SideViewController());
}

Inside this class I have an another widget called DashBoardTitleWidget()
In that class I am trying to call NewsDetailsController and SideViewController

class DashBoardTitleWidget extends StatelessWidget {
   DashBoardTitleWidget({Key? key}) : super(key: key);
    final  sideViewController = Get.put(SideViewController());
   final  controller = Get.put(NewsDetailsController());
  @override
  Widget build(BuildContext context) {
        return
          MouseRegion(
            cursor: SystemMouseCursors.click,
            child: GestureDetector(
              onTap:
                  (){
                try{
                  controller.isRecommendationVisible.value=false;
                  controller.newsTitle.value="";
                  controller.newsUrl.value="";
                  sideViewController.viewAllType.value="";
                  controller.contentSummary.value="";
                  controller.selectedIndexForRec.value = -1;
                  controller.selectedIndexForSimilar.value=-1;
                  controller.selectedIndexForRecommend.value=-1;
                  controller.selectedIndexForAllNews.value=-1;
                  print("vlaus is ${controller.isRecommendationVisible.value}");
                }catch(e){
                  print("exc is $e");
                }

              },
              child: Container(
                decoration: BoxDecoration(
                  color: Color(0xffEAEAEA),
                  shape: BoxShape.circle
                ),
                child:Padding(
                  padding: const EdgeInsets.all(3.0),
                  child: Icon(
                    key:Key('pclose'),
                    Icons.clear,color: Color(0xff222B45),size: 15,),
                ) ,
              ),
            ),
          );
    //   }
    // );
  }
}

All value inside ontap is assigned to variable but that is not reflect in UI after filtering


问:
Need help creating poles for Flappy Bird
I've been using NetLogo Programming for a few weeks now, but I'm still a little confused with the syntax. I'm trying to create a NetLogo version of the Flappy Bird game, but I can't seem to make the poles work.

I tried using patches, but the poles don't move very smoothly. When I use turtles, I can't make it stop without stopping the whole program. This is part of my code:

```<code>to top-pole
  crt 1
  [set size 1500
   set color pink + 2.8
    set shape (one-of ["pole 7" "pole 8" "pole 9" "pole 10" "pole 11"])]
  ask turtles with [shape = "pole 7"]
                 [setxy 75 0]
  ask turtles with [shape = "pole 8"]
               [setxy -1 0]
  ask turtles with [shape = "pole 9"]
               [setxy 149 0]
  ask turtles with [shape = "pole 10"]
               [setxy 149 0]
  ask turtles with [shape = "pole 11"]
               [setxy -1 0]
 ;   facexy 0 1]
end

to move-top
  every 10
  [top-pole]
  every 0.05
  [ask turtles with [who > 0]
  [setxy (xcor + x-vel) (ycor + y-vel)
      set x-vel (x-vel - .01)]]
    every 3
    [ask turtles with [(shape = "pole 7") and ((round xcor) >= 155) and ((round xcor) <= 145) ] ;150
                 [die]
  ask turtles with [(shape = "pole 8") and ((round xcor) >= 65) and ((round xcor) <= 80)] ;74
               [die]
  ask turtles with [(shape = "pole 9") and ((round xcor) >= 220) and ((round xcor) <= 230)] ; 225
               [die]
  ask turtles with [(shape = "pole 10") and ((round xcor) >= 220) and ((round xcor) >= 230)] ; 225
               [die]
  ask turtles with [(shape = "pole 11") and ((round xcor) >= 70) and ((round xcor) <= 80)] ; 75
                  [die]]

end
</code>```

Btw, the "pole 7", "pole 8", etc. are just turtles I created:
enter image description here

Also, my world dimensions are currently 300 by 200 and the patch size is 1.

Body:
I've been using NetLogo Programming for a few weeks now, but I'm still a little confused with the syntax. I'm trying to create a NetLogo version of the Flappy Bird game, but I can't seem to make the poles work.

I tried using patches, but the poles don't move very smoothly. When I use turtles, I can't make it stop without stopping the whole program. This is part of my code:

to top-pole
  crt 1
  [set size 1500
   set color pink + 2.8
    set shape (one-of ["pole 7" "pole 8" "pole 9" "pole 10" "pole 11"])]
  ask turtles with [shape = "pole 7"]
                 [setxy 75 0]
  ask turtles with [shape = "pole 8"]
               [setxy -1 0]
  ask turtles with [shape = "pole 9"]
               [setxy 149 0]
  ask turtles with [shape = "pole 10"]
               [setxy 149 0]
  ask turtles with [shape = "pole 11"]
               [setxy -1 0]
 ;   facexy 0 1]
end

to move-top
  every 10
  [top-pole]
  every 0.05
  [ask turtles with [who > 0]
  [setxy (xcor + x-vel) (ycor + y-vel)
      set x-vel (x-vel - .01)]]
    every 3
    [ask turtles with [(shape = "pole 7") and ((round xcor) >= 155) and ((round xcor) <= 145) ] ;150
                 [die]
  ask turtles with [(shape = "pole 8") and ((round xcor) >= 65) and ((round xcor) <= 80)] ;74
               [die]
  ask turtles with [(shape = "pole 9") and ((round xcor) >= 220) and ((round xcor) <= 230)] ; 225
               [die]
  ask turtles with [(shape = "pole 10") and ((round xcor) >= 220) and ((round xcor) >= 230)] ; 225
               [die]
  ask turtles with [(shape = "pole 11") and ((round xcor) >= 70) and ((round xcor) <= 80)] ; 75
                  [die]]

end

Btw, the "pole 7", "pole 8", etc. are just turtles I created:
enter image description here

Also, my world dimensions are currently 300 by 200 and the patch size is 1.


问:
How does memcached C source code use bool?
Memcached source code is written in C but uses bool type and literals (https://github.com/memcached/memcached/blob/master/memcached.c#L155)

```<code>static volatile bool allow_new_conns = true;
</code>```

How is boolean supported in C?

CLion complains about the use of bool. Is there any recommendation on how to configure CLion for memcached?

Body:
Memcached source code is written in C but uses bool type and literals (https://github.com/memcached/memcached/blob/master/memcached.c#L155)

static volatile bool allow_new_conns = true;

How is boolean supported in C?

CLion complains about the use of bool. Is there any recommendation on how to configure CLion for memcached?


问:
ng-select not showing result on search, but after (on clicking other things or on remove)
I am using ng-select for postal code, on search it will search the API and the search functions works for the code and the area name (only different query on the API search).

```<code><ng-select
    formControlName="addressCode"
    placeholder="enter your postal code"
    (search)="search($event)"
    (change)="set($event)"
    [items]="postalCode"
    bindValue="id"
    bindLabel="postalCode"
    labelForId="addressCode"
  >
    <ng-template ng-label-tmp let-item="item">
      <span>{{ item.name+ '  ' + item.code}}</span>
    </ng-template>
    <ng-template ng-option-tmp let-item="item" let-search="searchTerm" let-index="index">
      <span>{{ item.name+ '  ' + item.code}}</span>
    </ng-template>
  </ng-select>
</code>```
```<code>search(event: any) {
    const text = event.term;
    if (!text || text.length < 3) {
      this.postalCode= [];
      return;
    }
    this.searchPostalCode(text)
    .pipe(
      debounceTime(2000)
    )
    .subscribe((result) => {
      console.log(result);
      if (Object.keys(result).length === 0) {
        this.postalCode= [];
      } else {
        this.postalCode= result;
      }
      console.log(this.postalCode);
    });

  }
</code>```

If the input is the postal code, it works just fine. But if the input is a string, the dropdown gives a 'no items found' until you remove your input with the button or closing the ng-select and opening it again

I checked the API, query and data works completely fine. I checked the function and the subscription, the data went through okay (the console.log at the function shows the actual search result). I removed the ng-template display and used the default option, still the same issue.

The expected result is upon search, the dropdown immediately comes up with the searched result. The actual result is it shows no data first, and after next action (clearing input / closing the search and reopen), then the data comes out

Body:
I am using ng-select for postal code, on search it will search the API and the search functions works for the code and the area name (only different query on the API search).

<ng-select
    formControlName="addressCode"
    placeholder="enter your postal code"
    (search)="search($event)"
    (change)="set($event)"
    [items]="postalCode"
    bindValue="id"
    bindLabel="postalCode"
    labelForId="addressCode"
  >
    <ng-template ng-label-tmp let-item="item">
      {{ item.name+ '  ' + item.code}}
    </ng-template>
    <ng-template ng-option-tmp let-item="item" let-search="searchTerm" let-index="index">
      {{ item.name+ '  ' + item.code}}
    </ng-template>
  </ng-select>

search(event: any) {
    const text = event.term;
    if (!text || text.length < 3) {
      this.postalCode= [];
      return;
    }
    this.searchPostalCode(text)
    .pipe(
      debounceTime(2000)
    )
    .subscribe((result) => {
      console.log(result);
      if (Object.keys(result).length === 0) {
        this.postalCode= [];
      } else {
        this.postalCode= result;
      }
      console.log(this.postalCode);
    });

  }

If the input is the postal code, it works just fine. But if the input is a string, the dropdown gives a 'no items found' until you remove your input with the button or closing the ng-select and opening it again

I checked the API, query and data works completely fine. I checked the function and the subscription, the data went through okay (the console.log at the function shows the actual search result). I removed the ng-template display and used the default option, still the same issue.

The expected result is upon search, the dropdown immediately comes up with the searched result. The actual result is it shows no data first, and after next action (clearing input / closing the search and reopen), then the data comes out


问:
Scroll and Click-How to click on each row of a list of items and scroll when needed to click item not in view
I have a scenario in which there are n number of items (rows) on the page (table) and only a certain number of rows are in view the first time we are on the page. I need to click on each row in the list and continue clicking the items that are not in view - basically keep clicking until I reach the end of the page/table (and add assertions as well).

What happens with my code is that it clicks on each row only until the row that is visible, and stops after that.

Someone please help me with this as I am trying for a solution for a week now and finally posting it here.
I have tried using scrollTo and scrollIntoView but they don't work.
Need help with scroll and click iteratively.


问:
Problem with assembly DevExpress.Web-AspxEditor
I have recently installed the DevExpress 22.1.7 package, but I am unable to find the DevExpress.Web.ASPxEditor assembly. I have checked that I have the latest version and I have also checked that the assembly is not in the GAC.

I have also tried to install the package again but it is still missing. Has anyone else experienced this issue or know a solution to this problem?


问:
Generate text from complex Pandas Dataframe Conditions
what's the best way to code Python to evaluate rows of data for 18 distinct logical conditions, and then to generate text accordingly?

I've spent days trying to figure this out. I have a Pandas DataFrame consisting of columns Name, V1, and V2. V1 and V2 are dollar amounts that can either be blank, $0.00, or any dollar and cent amount.

I need to generate text based on this data including referencing the Names that fit the conditions. Thank you for your help.

StackOverflow will not let me submit this question with the tables formatted correctly:

|Name|V1|V2| |-|-|-| |John||| |Mary||| |Thomas||| |Sara||| |Joe|||
|Seth||| |Jonas||| |Sue|||

How to generate text based on 18 separate combinations of conditions with each generating different text? The order of the conditions is in the preferred order.

Conditions |Conditions|V1|V2| |-|-|-| |1|All|0| |2|0|All| |3|All|All| |4|All|1| |5|1|All| |6|All|2| |7|2|All| |8|2|1| |9|1|1|
|10|1|2| |11|All|3+| |12|3+|All| |13|3+|2| |14|2|3+| |15|3+|1|
|16|2|2| |17|1|3+| |18|3+|3+|

Terms

All means each Name has some non-zero and non-blank dollar amount
in the column; i.e., $0.01 or more.

1 means exactly one Name has some non-zero and non-blank dollar amount in the column; i.e., $0.01 or more.

2 means exactly two Names have some non-zero and non-blank dollar amount in the column; i.e., $0.01 or more.

3+ means three or more Names have some non-zero and non-blank dollar amount in the column; i.e., $0.01 or more.

I tried generating the text using np.select(conditions, choices) but I could not get it to work. Here were the conditions I worked on:

```<code>   #1           -           ALL V1 + 0   V2           MinPs = 1
#       P Count = V1 Count
        ((PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
        (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       V2 Count = 0
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 0)),
#2           -           0   V1 + ALL V2           MinPs = 1
#       V1 Count = 0
        ((np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 0) &
#       P Count = V2 Count
        (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0)),
#  3           -           ALL V1 + ALL V2           MinPs = 1
#       P Count = V1 Count
        ((PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
        (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       P Count = V2 Count
        (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0)),
# 4           -           ALL V1 + 1   V2           MinPs = 2
#       P Count = V1 Count
        ((PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
        (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       V2 Count = 1
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1)),
# 5           -           1   V1 + ALL V2           MinPs = 2
#       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
#       P Count = V2 Count
         (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0),
# 6           -           ALL V1 + 2   V2           MinPs = 3
#       P Count = V1 Count
         (PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
# 7           -           2   V1 + ALL V2           MinPs = 3
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       P Count = V2 Count
         (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0),
# 8           -           2   V1 + 1   V2           MinPs = 2
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       V2 Count = 1
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1),
# 9           -           1   V1 + 1   V2           MinPs = 2
#       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
 #       V2 Count = 1
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1),
 # 10          -           1   V1 + 2   V2           MinPs = 2
 #       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
 #       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
 # 11          -           ALL V1 + 3+  V2           MinPs = 4
 #       P Count = V1 Count
         (PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
 #       V1 Count > 0
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
 #       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
 # 12          -           3+  V1 + ALL V2           MinPs = 4
 #       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
 #       P Count = V1 Count
         (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0),
# 13          -           3+  V1 + 2   V2           MinPs = 3
#       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
#       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
# 14          -           2   V1 + 3+  V2           MinPs = 3
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
# 15          -           3+  V1 + 1   V2           MinPs = 3
#       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
#       V2 Count = 1
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1),
# 16          -           2   V1 + 2   V2           MinPs = 3
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
# 17          -           1   V1 + 3+  V2           MinPs = 3
#       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
#       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
# 18          -           3+  V1 + 3+  V2           MinPs = 4
 #       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
 #       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
</code>```

Body:
what's the best way to code Python to evaluate rows of data for 18 distinct logical conditions, and then to generate text accordingly?

I've spent days trying to figure this out. I have a Pandas DataFrame consisting of columns Name, V1, and V2. V1 and V2 are dollar amounts that can either be blank, $0.00, or any dollar and cent amount.

I need to generate text based on this data including referencing the Names that fit the conditions. Thank you for your help.

StackOverflow will not let me submit this question with the tables formatted correctly:

|Name|V1|V2| |-|-|-| |John||| |Mary||| |Thomas||| |Sara||| |Joe|||
|Seth||| |Jonas||| |Sue|||

How to generate text based on 18 separate combinations of conditions with each generating different text? The order of the conditions is in the preferred order.

Conditions |Conditions|V1|V2| |-|-|-| |1|All|0| |2|0|All| |3|All|All| |4|All|1| |5|1|All| |6|All|2| |7|2|All| |8|2|1| |9|1|1|
|10|1|2| |11|All|3+| |12|3+|All| |13|3+|2| |14|2|3+| |15|3+|1|
|16|2|2| |17|1|3+| |18|3+|3+|

Terms

All means each Name has some non-zero and non-blank dollar amount
in the column; i.e., $0.01 or more.

1 means exactly one Name has some non-zero and non-blank dollar amount in the column; i.e., $0.01 or more.

2 means exactly two Names have some non-zero and non-blank dollar amount in the column; i.e., $0.01 or more.

3+ means three or more Names have some non-zero and non-blank dollar amount in the column; i.e., $0.01 or more.

I tried generating the text using np.select(conditions, choices) but I could not get it to work. Here were the conditions I worked on:

   #1           -           ALL V1 + 0   V2           MinPs = 1
#       P Count = V1 Count
        ((PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
        (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       V2 Count = 0
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 0)),
#2           -           0   V1 + ALL V2           MinPs = 1
#       V1 Count = 0
        ((np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 0) &
#       P Count = V2 Count
        (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0)),
#  3           -           ALL V1 + ALL V2           MinPs = 1
#       P Count = V1 Count
        ((PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
        (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       P Count = V2 Count
        (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0)),
# 4           -           ALL V1 + 1   V2           MinPs = 2
#       P Count = V1 Count
        ((PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
        (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       V2 Count = 1
        (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1)),
# 5           -           1   V1 + ALL V2           MinPs = 2
#       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
#       P Count = V2 Count
         (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0),
# 6           -           ALL V1 + 2   V2           MinPs = 3
#       P Count = V1 Count
         (PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
#       V1 Count > 0
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
#       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
# 7           -           2   V1 + ALL V2           MinPs = 3
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       P Count = V2 Count
         (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0),
# 8           -           2   V1 + 1   V2           MinPs = 2
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       V2 Count = 1
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1),
# 9           -           1   V1 + 1   V2           MinPs = 2
#       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
 #       V2 Count = 1
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1),
 # 10          -           1   V1 + 2   V2           MinPs = 2
 #       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
 #       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
 # 11          -           ALL V1 + 3+  V2           MinPs = 4
 #       P Count = V1 Count
         (PCount == np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values)) &
 #       V1 Count > 0
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 0) &
 #       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
 # 12          -           3+  V1 + ALL V2           MinPs = 4
 #       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
 #       P Count = V1 Count
         (PCount == np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values)) &
#       V2 Count > 0
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 0),
# 13          -           3+  V1 + 2   V2           MinPs = 3
#       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
#       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
# 14          -           2   V1 + 3+  V2           MinPs = 3
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
# 15          -           3+  V1 + 1   V2           MinPs = 3
#       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
#       V2 Count = 1
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 1),
# 16          -           2   V1 + 2   V2           MinPs = 3
#       V1 Count = 2
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 2) &
#       V2 Count = 2
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) == 2),
# 17          -           1   V1 + 3+  V2           MinPs = 3
#       V1 Count = 1
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) == 1) &
#       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),
# 18          -           3+  V1 + 3+  V2           MinPs = 4
 #       V1 Count = 3+
         (np.count_nonzero(NamesTbl[‘V1’][NamesTbl[‘V1’] > 0].values) > 2) &
 #       V2 Count = 3+
         (np.count_nonzero(NamesTbl[‘V2’][NamesTbl[‘V2’] > 0].values) > 2),


问:
ChartJS 3 Doesn't Show Data Until A Legend Is Clicked
I get some data from back-end to show. When I inspect element with React Developer Tools, I can see that data is there but not shown in production. ChartJS version is 3.8, not react-chartjs

I was having the same problem in development, too, but solved it by setting a unique key with key={Math.random()}. In development build, it works just fine. Problem occurs in production. I deploy my app on Firebase.

I wait for data before rendering:
{isAnyFetching ? "Loading..." : <BarChart01 data={chartData} width={595} height={248} key={Math.random()} />}

I tried giving an array of zeroes until data is loaded to be sure chartData changed to trigger re-render by changing the state of the chart component. I also tried giving an extraKey prop and change it with useEffect to re-render again.

The whole chart component is:

```<code>function BarChart01({
  data,
  width,
  height
}) {

  const canvas = useRef(null);
  const legend = useRef(null);

  useEffect(() => {
    const ctx = canvas.current;
    // eslint-disable-next-line no-unused-vars
    const chart = new Chart(ctx, {
      type: 'bar',
      data: data,
      options: {
        layout: {
          padding: {
            top: 12,
            bottom: 16,
            left: 20,
            right: 20,
          },
        },
        scales: {
          y: {
            grid: {
              drawBorder: false,
            },
            ticks: {
              maxTicksLimit: 6,
              callback: (value) => formatValue(value),
            },
          },
          x: {
            type: 'time',
            time: {
              parser: 'MM-DD-YYYY',
              unit: 'month',
              displayFormats: {
                month: 'MMM YY',
              },
            },
            grid: {
              display: false,
              drawBorder: false,
            },
          },
        },
        plugins: {
          legend: {
            display: true,
          },
          tooltip: {
            callbacks: {
              title: () => false, // Disable tooltip title
              label: (context) => formatValue(context.parsed.y),
            },
          },
        },
        interaction: {
          intersect: false,
          mode: 'nearest',
        },
        animation: {
          duration: 500,
        },
        maintainAspectRatio: false,
        resizeDelay: 200,
      },
      plugins: [{
        id: 'htmlLegend',
        afterUpdate(c, args, options) {
          const ul = legend.current;
          if (!ul) return;
          // Remove old legend items
          while (ul.firstChild) {
            ul.firstChild.remove();
          }
          // Reuse the built-in legendItems generator
          const items = c.options.plugins.legend.labels.generateLabels(c);
          items.forEach((item) => {
            const li = document.createElement('li');
            li.style.marginRight = tailwindConfig().theme.margin[4];
            // Button element
            const button = document.createElement('button');
            button.style.display = 'inline-flex';
            button.style.alignItems = 'center';
            button.style.opacity = item.hidden ? '.3' : '';
            button.onclick = () => {
              c.setDatasetVisibility(item.datasetIndex, !c.isDatasetVisible(item.datasetIndex));
              c.update();
            };
            // Color box
            const box = document.createElement('span');
            box.style.display = 'block';
            box.style.width = tailwindConfig().theme.width[3];
            box.style.height = tailwindConfig().theme.height[3];
            box.style.borderRadius = tailwindConfig().theme.borderRadius.full;
            box.style.marginRight = tailwindConfig().theme.margin[2];
            box.style.borderWidth = '3px';
            box.style.borderColor = item.fillStyle;
            box.style.pointerEvents = 'none';
            // Label
            const labelContainer = document.createElement('span');
            labelContainer.style.display = 'flex';
            labelContainer.style.alignItems = 'center';
            const value = document.createElement('span');
            value.style.color = tailwindConfig().theme.colors.slate[800];
            value.style.fontSize = tailwindConfig().theme.fontSize['3xl'][0];
            value.style.lineHeight = tailwindConfig().theme.fontSize['3xl'][1].lineHeight;
            value.style.fontWeight = tailwindConfig().theme.fontWeight.bold;
            value.style.marginRight = tailwindConfig().theme.margin[2];
            value.style.pointerEvents = 'none';
            const label = document.createElement('span');
            label.style.color = tailwindConfig().theme.colors.slate[500];
            label.style.fontSize = tailwindConfig().theme.fontSize.sm[0];
            label.style.lineHeight = tailwindConfig().theme.fontSize.sm[1].lineHeight;
            const theValue = c.data.datasets[item.datasetIndex].data.reduce((a, b) => a + b, 0);
            const valueText = document.createTextNode(formatValue(theValue));
            const labelText = document.createTextNode(item.text);
            value.appendChild(valueText);
            label.appendChild(labelText);
            li.appendChild(button);
            button.appendChild(box);
            button.appendChild(labelContainer);
            labelContainer.appendChild(value);
            labelContainer.appendChild(label);
            ul.appendChild(li);
          });
        },
      }],
    });
    chart.update();
    return () => chart.destroy();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  return (
    <>
      <div className="px-5 py-3">
        <ul ref={legend} className="flex flex-wrap"></ul>
      </div>
      <div className="grow">
        <canvas ref={canvas} width={width} height={height}></canvas>
      </div>
    </>
  );
}
</code>```

According to the code, it seems like

```<code>button.onclick = () => {
              c.setDatasetVisibility(item.datasetIndex,!c.isDatasetVisible(item.datasetIndex));
              c.update();
        };
</code>```

part in forEach loop is responsible of this update operation when I click on a label. So it somehow doesn't call update function in production as it should as useEffect listens to data prop.

Body:
I get some data from back-end to show. When I inspect element with React Developer Tools, I can see that data is there but not shown in production. ChartJS version is 3.8, not react-chartjs

I was having the same problem in development, too, but solved it by setting a unique key with key={Math.random()}. In development build, it works just fine. Problem occurs in production. I deploy my app on Firebase.

I wait for data before rendering:
{isAnyFetching ? "Loading..." : <BarChart01 data={chartData} width={595} height={248} key={Math.random()} />}

I tried giving an array of zeroes until data is loaded to be sure chartData changed to trigger re-render by changing the state of the chart component. I also tried giving an extraKey prop and change it with useEffect to re-render again.

The whole chart component is:

function BarChart01({
  data,
  width,
  height
}) {

  const canvas = useRef(null);
  const legend = useRef(null);

  useEffect(() => {
    const ctx = canvas.current;
    // eslint-disable-next-line no-unused-vars
    const chart = new Chart(ctx, {
      type: 'bar',
      data: data,
      options: {
        layout: {
          padding: {
            top: 12,
            bottom: 16,
            left: 20,
            right: 20,
          },
        },
        scales: {
          y: {
            grid: {
              drawBorder: false,
            },
            ticks: {
              maxTicksLimit: 6,
              callback: (value) => formatValue(value),
            },
          },
          x: {
            type: 'time',
            time: {
              parser: 'MM-DD-YYYY',
              unit: 'month',
              displayFormats: {
                month: 'MMM YY',
              },
            },
            grid: {
              display: false,
              drawBorder: false,
            },
          },
        },
        plugins: {
          legend: {
            display: true,
          },
          tooltip: {
            callbacks: {
              title: () => false, // Disable tooltip title
              label: (context) => formatValue(context.parsed.y),
            },
          },
        },
        interaction: {
          intersect: false,
          mode: 'nearest',
        },
        animation: {
          duration: 500,
        },
        maintainAspectRatio: false,
        resizeDelay: 200,
      },
      plugins: [{
        id: 'htmlLegend',
        afterUpdate(c, args, options) {
          const ul = legend.current;
          if (!ul) return;
          // Remove old legend items
          while (ul.firstChild) {
            ul.firstChild.remove();
          }
          // Reuse the built-in legendItems generator
          const items = c.options.plugins.legend.labels.generateLabels(c);
          items.forEach((item) => {
            const li = document.createElement('li');
            li.style.marginRight = tailwindConfig().theme.margin[4];
            // Button element
            const button = document.createElement('button');
            button.style.display = 'inline-flex';
            button.style.alignItems = 'center';
            button.style.opacity = item.hidden ? '.3' : '';
            button.onclick = () => {
              c.setDatasetVisibility(item.datasetIndex, !c.isDatasetVisible(item.datasetIndex));
              c.update();
            };
            // Color box
            const box = document.createElement('span');
            box.style.display = 'block';
            box.style.width = tailwindConfig().theme.width[3];
            box.style.height = tailwindConfig().theme.height[3];
            box.style.borderRadius = tailwindConfig().theme.borderRadius.full;
            box.style.marginRight = tailwindConfig().theme.margin[2];
            box.style.borderWidth = '3px';
            box.style.borderColor = item.fillStyle;
            box.style.pointerEvents = 'none';
            // Label
            const labelContainer = document.createElement('span');
            labelContainer.style.display = 'flex';
            labelContainer.style.alignItems = 'center';
            const value = document.createElement('span');
            value.style.color = tailwindConfig().theme.colors.slate[800];
            value.style.fontSize = tailwindConfig().theme.fontSize['3xl'][0];
            value.style.lineHeight = tailwindConfig().theme.fontSize['3xl'][1].lineHeight;
            value.style.fontWeight = tailwindConfig().theme.fontWeight.bold;
            value.style.marginRight = tailwindConfig().theme.margin[2];
            value.style.pointerEvents = 'none';
            const label = document.createElement('span');
            label.style.color = tailwindConfig().theme.colors.slate[500];
            label.style.fontSize = tailwindConfig().theme.fontSize.sm[0];
            label.style.lineHeight = tailwindConfig().theme.fontSize.sm[1].lineHeight;
            const theValue = c.data.datasets[item.datasetIndex].data.reduce((a, b) => a + b, 0);
            const valueText = document.createTextNode(formatValue(theValue));
            const labelText = document.createTextNode(item.text);
            value.appendChild(valueText);
            label.appendChild(labelText);
            li.appendChild(button);
            button.appendChild(box);
            button.appendChild(labelContainer);
            labelContainer.appendChild(value);
            labelContainer.appendChild(label);
            ul.appendChild(li);
          });
        },
      }],
    });
    chart.update();
    return () => chart.destroy();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  return (
    <>

        <canvas ref={canvas} width={width} height={height}></canvas>

    </>
  );
}

According to the code, it seems like

button.onclick = () => {
              c.setDatasetVisibility(item.datasetIndex,!c.isDatasetVisible(item.datasetIndex));
              c.update();
        };

part in forEach loop is responsible of this update operation when I click on a label. So it somehow doesn't call update function in production as it should as useEffect listens to data prop.


问:
React onClick works on desktop but not on mobile
I have tried cursor: pointer, tappable, ontouch... This code works on desktop but not on mobile.   The hamburger menu works on both.</p>
```<code>import { motion } from "framer-motion";
import React, { useState } from "react";
import styled from "styled-components";

const Toggle = ({ children, title }) => {
  const [toggle, setToggle] = useState(false);

  return (
    <ToggleDiv
      layout
      className="question"
      onClick={() => {
        console.log("onClick event fired");
        setToggle(!toggle);
      }}
    >
      <motion.h4 layout>{title}</motion.h4>
      {toggle ? children : ""}
      <div className="faq-line"></div>
    </ToggleDiv>
  );
};

const ToggleDiv = styled(motion.div)`
  cursor: pointer;
  z-index: 10;
  display: block;
`;

export default Toggle;
</code>```

Body:
I have tried cursor: pointer, tappable, ontouch... This code works on desktop but not on mobile.   The hamburger menu works on both.

import { motion } from "framer-motion";
import React, { useState } from "react";
import styled from "styled-components";

const Toggle = ({ children, title }) => {
  const [toggle, setToggle] = useState(false);

  return (
    <ToggleDiv
      layout
      className="question"
      onClick={() => {
        console.log("onClick event fired");
        setToggle(!toggle);
      }}
    >
      <motion.h4 layout>{title}</motion.h4>
      {toggle ? children : ""}

    </ToggleDiv>
  );
};

const ToggleDiv = styled(motion.div)`
  cursor: pointer;
  z-index: 10;
  display: block;
`;

export default Toggle;


问:
NestJS with language change based on URL
I'm trying to do a language change with NestJS. Example,
if user type in URL:

www.blabla.com/en <-- text in the page will show english

www.blabla.com/cn <-- text in the page will display in chinese font

www.blabla.com/jp <-- text in the page will display in japan font

I read about i18n but not sure how is the logic to do in NestJS. Please kindly help. Thank you.


问:
How to find the right domain name using the query
I have a requirement in my website to auto open new tab of google query search based on a query.

Example: If my query is libro signora in giallo, the google search page should be https://www.google.it/search?q=libro signora in giallo
And if my query is goteros para niños, the search page would be https://www.google.com.mx/search?goteros para niños

Similarly, there are different such marketplaces like in, jp etc etc
My code has to append query to https://www.google.com/search?q= and auto pop
But my concern is how do i find out the right country tld or domain name based on the query so that the auto popup tab searches in the right tld?
This would be in frontend or javascript?
Is there any built in library or functionality to pick the right TLD?


问:
Tensorflow coco-ssd could not load
I'm having a problem saying that my cocossd cant load. Do you know whats the issue?

This is my source code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js" type="text/javascript"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
    <img id="img" src="https://www.cdc.gov/importation/images/cat.jpg?_=18560"/>

    <script>
        const img = document.getElementById('img');
        cocoSsd.load().then(model => {
            model.detect(img).then(predictions => {
                console.log('Predictions: ', predictions);
            });
        });
    </script>
</body>
</html>
</code>```

Title: Tensorflow coco-ssd could not load

Body:
I'm having a problem saying that my cocossd cant load. Do you know whats the issue?

This is my source code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>


问:
How to reset icon set with AppUserModel.RelaunchIconResource?
At some point I have set AppUserModel.RelaunchIconResource ID to 0 and now program doesn't have an icon in taskbar.

Breaking code:

```<code>IPropertyStore propStore = GetWindowPropertyStore(hwnd);
using (PROPVARIANT pv = new PROPVARIANT(0)
    propStore.SetValue(PROPERTYKEY.System.AppUserModel.RelaunchIconResource, pv);
Marshal.ReleaseComObject(propStore);
</code>```

Icon is missing even if I don't set AppUserModel.ID when window is opened.

Icons is also missing if I use AppUserModel.ID that had icon deleted in the past and even if I try setting a new icon

```<code>using (PROPVARIANT pv = new PROPVARIANT(@"C:\path\prog.exe"))
    propStore.SetValue(PROPERTYKEY.System.AppUserModel.RelaunchIconResource, pv);
</code>```

I have tried setting icon without specifying AppUserModel.ID

Icon is OK if I set the AppUserModel.ID to a random string, but not if I omit it or use one of old broken AppUserModel.ID.

How can I get the icon back for already broken AppUserModel.ID or if I don't set AppUserModel.ID at all?

I have tried searching registry for program's full path and also for the broken AppUserModel.ID.

Body:
At some point I have set AppUserModel.RelaunchIconResource ID to 0 and now program doesn't have an icon in taskbar.

Breaking code:

IPropertyStore propStore = GetWindowPropertyStore(hwnd);
using (PROPVARIANT pv = new PROPVARIANT(0)
    propStore.SetValue(PROPERTYKEY.System.AppUserModel.RelaunchIconResource, pv);
Marshal.ReleaseComObject(propStore);

Icon is missing even if I don't set AppUserModel.ID when window is opened.

Icons is also missing if I use AppUserModel.ID that had icon deleted in the past and even if I try setting a new icon

using (PROPVARIANT pv = new PROPVARIANT(@"C:\path\prog.exe"))
    propStore.SetValue(PROPERTYKEY.System.AppUserModel.RelaunchIconResource, pv);

I have tried setting icon without specifying AppUserModel.ID

Icon is OK if I set the AppUserModel.ID to a random string, but not if I omit it or use one of old broken AppUserModel.ID.

How can I get the icon back for already broken AppUserModel.ID or if I don't set AppUserModel.ID at all?

I have tried searching registry for program's full path and also for the broken AppUserModel.ID.


问:
Using @Context HttpServletResponse throws ambiguous dependencies org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge
I have this code on my server

```<code>@POST
@Path("subscribers")
@Consumes(MediaType.APPLICATION_XML)
public void createBook(SubscriberDTO dto, @Context HttpServletResponse response, @Context UriInfo uriInfo)throws Exception{
    System.out.println("Test 1 : "+FILEPATH);
    new SubscriberFileStorage().append(dto.toString(),FILEPATH);
    String baseURL = uriInfo.getBaseUri().toString();
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setHeader(HttpHeaders.LOCATION, baseURL+dto.getTopic()+dto.getUrl());
    try { response.flushBuffer(); }catch(Exception e){}
}
</code>```

I get always the error, when submitting a post request

13-Jan-2023 05:01:56.403 SEVERE [http-nio-9090-exec-59] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [hesge.ch.tp05pubsubhub.HelloApplication] in context with path [/TP05PubSubHub_war_exploded] threw exception [org.jboss.weld.exceptions.AmbiguousResolutionException: WELD-001335: Ambiguous dependencies for type Ref with qualifiers @Default Possible dependencies:

org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@2a0fe65e,
org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@4491cd37] with root cause org.jboss.weld.exceptions.AmbiguousResolutionException: WELD-001335: Ambiguous dependencies for type Ref with qualifiers @Default Possible dependencies:
org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@2a0fe65e,
org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@4491cd37 at org.jboss.weld.bean.builtin.InstanceImpl.checkBeanResolved(InstanceImpl.java:244) at org.jboss.weld.bean.builtin.InstanceImpl.get(InstanceImpl.java:113)

I have checked all dependencies, none works.  Any idea ?  I really appreciate

Body:
I have this code on my server

@POST
@Path("subscribers")
@Consumes(MediaType.APPLICATION_XML)
public void createBook(SubscriberDTO dto, @Context HttpServletResponse response, @Context UriInfo uriInfo)throws Exception{
    System.out.println("Test 1 : "+FILEPATH);
    new SubscriberFileStorage().append(dto.toString(),FILEPATH);
    String baseURL = uriInfo.getBaseUri().toString();
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setHeader(HttpHeaders.LOCATION, baseURL+dto.getTopic()+dto.getUrl());
    try { response.flushBuffer(); }catch(Exception e){}
}

I get always the error, when submitting a post request

13-Jan-2023 05:01:56.403 SEVERE [http-nio-9090-exec-59] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [hesge.ch.tp05pubsubhub.HelloApplication] in context with path [/TP05PubSubHub_war_exploded] threw exception [org.jboss.weld.exceptions.AmbiguousResolutionException: WELD-001335: Ambiguous dependencies for type Ref with qualifiers @Default Possible dependencies:

org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@2a0fe65e,
org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@4491cd37] with root cause org.jboss.weld.exceptions.AmbiguousResolutionException: WELD-001335: Ambiguous dependencies for type Ref with qualifiers @Default Possible dependencies:
org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@2a0fe65e,
org.glassfish.jersey.inject.cdi.se.bean.SupplierInstanceBeanBridge@4491cd37 at org.jboss.weld.bean.builtin.InstanceImpl.checkBeanResolved(InstanceImpl.java:244) at org.jboss.weld.bean.builtin.InstanceImpl.get(InstanceImpl.java:113)

I have checked all dependencies, none works.  Any idea ?  I really appreciate


问:
Azure Translate API Call keeps failing with error failed to open stream: HTTP request failed! HTTP/1.1 401
Created a simple wordpress plugin using php to select a post and send it to Azure Translate API for translation then post the translated text as a draft.

No matter what I do, i get the error Warning: file_get_contents(https://api.cognitive.microsofttranslator.com/translate?api-version=3.0): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

```<code><?php
/*
Plugin Name: Translate Posts
*/

// Add a menu item to the WordPress admin menu
add_action( 'admin_menu', 'translate_posts_menu' );

function translate_posts_menu() {
    add_options_page( 'Translate Posts', 'Translate Posts', 'manage_options', 'translate-posts', 'translate_posts_settings_page' );
}

// Display the settings page
function translate_posts_settings_page() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }

    // Get the list of published posts
    $args = array(
        'post_status' => 'publish',
        'posts_per_page' => -1
    );
    $posts = get_posts( $args );

    // Check if the form has been submitted
    if (isset( $_POST['submit'] )) {
        // Get the selected post IDs
        $selected_post_ids = $_POST['post_ids'];

        // Loop through the selected post IDs
        foreach ( $selected_post_ids as $post_id ) {
            // Get the post object
            $post = get_post( $post_id );

            // Get the post content
            $post_content = $post->post_content;

            // Use the Azure Translator API to translate the post content
            $translated_content = translate_with_azure( $post_content, 'en', 'nl' );

            // Create a new post as a draft
            $new_post = array(
                'post_title' => $post->post_title,
                'post_content' => $translated_content,
                'post_status' => 'draft',
                'post_author' => $post->post_author
            );
            wp_insert_post( $new_post );
        }
    }

    // Display the form
    echo '<form method="post" action="">';
    echo '<table>';
    echo '<tr><th>Select</th><th>Title</th></tr>';

    // Loop through the posts and display checkboxes for each post
    foreach ( $posts as $post ) {
        echo '<tr>';
        echo '<td><input type="checkbox" name="post_ids[]" value="' . $post->ID . '"></td>';
        echo '<td>' . $post->post_title . '</td>';
        echo '</tr>';
    }

    echo '</table>';
    echo '<input type="submit" name="submit" value="Translate">';
    echo '</form>';
}

// Azure Translator API function
function translate_with_azure( $text, $from, $to ) {
    // Your Azure Translator API key
    $api_key = 'MY_API_KEY';
    $location = 'eastus';
    // Azure Translator API endpoint
    $endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0';

    // Build the API request body
    $request_body = array(
    array(
        'Text' => $text,
        'from' => $from,
        'to' => $to
        ),
    );
    $request_body = json_encode($request_body);

    // Build the API request headers
    $headers = array(
        'Content-Type: application/json',
        'Ocp-Apim-Subscription-Key:' . $api_key,
        'Ocp-Apim-Subscription-Region:'. $location,
    );

    // Build the API request options
    $options = array(
        'http' => array(
            'header'  => implode("\r\n", $headers),
            'method'  => 'POST',
            'content' => $request_body,
        ),
    );

    // Send the API request
    $context = stream_context_create($options);
    $response = file_get_contents($endpoint, false, $context);
    $response_data = json_decode($response, true);

    // Return the translated text
    return $response_data[0]['translations'][0]['text'];
}
</code>```

I have tried the API from API Management Services>App>API's>Echo API>Test>Key

Also tried API Management Services>App>Subscription>Key

Also tried modifying the script to use a bearer Token instead but same issue.

Body:
Created a simple wordpress plugin using php to select a post and send it to Azure Translate API for translation then post the translated text as a draft.

No matter what I do, i get the error Warning: file_get_contents(https://api.cognitive.microsofttranslator.com/translate?api-version=3.0): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

<?php
/*
Plugin Name: Translate Posts
*/

// Add a menu item to the WordPress admin menu
add_action( 'admin_menu', 'translate_posts_menu' );

function translate_posts_menu() {
    add_options_page( 'Translate Posts', 'Translate Posts', 'manage_options', 'translate-posts', 'translate_posts_settings_page' );
}

// Display the settings page
function translate_posts_settings_page() {
    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }

    // Get the list of published posts
    $args = array(
        'post_status' => 'publish',
        'posts_per_page' => -1
    );
    $posts = get_posts( $args );

    // Check if the form has been submitted
    if (isset( $_POST['submit'] )) {
        // Get the selected post IDs
        $selected_post_ids = $_POST['post_ids'];

        // Loop through the selected post IDs
        foreach ( $selected_post_ids as $post_id ) {
            // Get the post object
            $post = get_post( $post_id );

            // Get the post content
            $post_content = $post->post_content;

            // Use the Azure Translator API to translate the post content
            $translated_content = translate_with_azure( $post_content, 'en', 'nl' );

            // Create a new post as a draft
            $new_post = array(
                'post_title' => $post->post_title,
                'post_content' => $translated_content,
                'post_status' => 'draft',
                'post_author' => $post->post_author
            );
            wp_insert_post( $new_post );
        }
    }

    // Display the form
    echo '<form method="post" action="">';
    echo '
';
    echo '
Select	Title
';

    // Loop through the posts and display checkboxes for each post
    foreach ( $posts as $post ) {
        echo '
';
        echo '<input type="checkbox" name="post_ids[]" value="' . $post->ID . '">	';
        echo '' . $post->post_title . '	';
        echo '
';
    }

    echo '
';
    echo '<input type="submit" name="submit" value="Translate">';
    echo '</form>';
}

// Azure Translator API function
function translate_with_azure( $text, $from, $to ) {
    // Your Azure Translator API key
    $api_key = 'MY_API_KEY';
    $location = 'eastus';
    // Azure Translator API endpoint
    $endpoint = 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0';

    // Build the API request body
    $request_body = array(
    array(
        'Text' => $text,
        'from' => $from,
        'to' => $to
        ),
    );
    $request_body = json_encode($request_body);

    // Build the API request headers
    $headers = array(
        'Content-Type: application/json',
        'Ocp-Apim-Subscription-Key:' . $api_key,
        'Ocp-Apim-Subscription-Region:'. $location,
    );

    // Build the API request options
    $options = array(
        'http' => array(
            'header'  => implode("\r\n", $headers),
            'method'  => 'POST',
            'content' => $request_body,
        ),
    );

    // Send the API request
    $context = stream_context_create($options);
    $response = file_get_contents($endpoint, false, $context);
    $response_data = json_decode($response, true);

    // Return the translated text
    return $response_data[0]['translations'][0]['text'];
}

I have tried the API from API Management Services>App>API's>Echo API>Test>Key

Also tried API Management Services>App>Subscription>Key

Also tried modifying the script to use a bearer Token instead but same issue.


问:
Excalidraw react component with Collaboration feature
I have created an component in a react app with a drawing canvas with excalidraw
I did the following steps to implement excalidraw.

1.npm i @excalidraw/excalidraw

2.Created a component named excalidrawComponent.js with following code

```<code>import { useState, useEffect } from "react";
export default function Excalidraw(props) {
    const [Comp, setComp] = useState(null);
    useEffect(() => {
        import("@excalidraw/excalidraw").then((comp) => setComp(comp.Excalidraw));
    }, []);

    return <>
    <div className="excalidraw-component">
     {Comp && <Comp />}
    </div>
    </>
}
</code>```

But I am not able to find the collaborate functionality what we can see in excalidraw statdalone project.
You can find below images to check diffrences.

[standalone excalidraw](https://i.stack.imgur.com/DGtLT.png)

[My react application with excalidraw darwing tool]https://i.stack.imgur.com/IVHEq.png)

I need a live collaboration button on top and its feature.
How to achieve this.
Thanks in advance.

Body:
I have created an component in a react app with a drawing canvas with excalidraw
I did the following steps to implement excalidraw.

1.npm i @excalidraw/excalidraw

2.Created a component named excalidrawComponent.js with following code

import { useState, useEffect } from "react";
export default function Excalidraw(props) {
    const [Comp, setComp] = useState(null);
    useEffect(() => {
        import("@excalidraw/excalidraw").then((comp) => setComp(comp.Excalidraw));
    }, []);

    return <>

     {Comp && <Comp />}

    </>
}

But I am not able to find the collaborate functionality what we can see in excalidraw statdalone project.
You can find below images to check diffrences.

[standalone excalidraw](https://i.stack.imgur.com/DGtLT.png)

[My react application with excalidraw darwing tool]https://i.stack.imgur.com/IVHEq.png)

I need a live collaboration button on top and its feature.
How to achieve this.
Thanks in advance.