问:
I need a prefix for powershell to automatically check for elevations and if not present, elevate the powershell and continue the script. Anyone?
I need a prefix for PowerShell that I can insert prior to commands to automatically check for elevations and if not present, elevate the PowerShell (while asking for elevated credentials) and continue the script.  I have found this script below, which works, but is that the best implementation? Environment: Executed on computer joined to domain, PowerShell script executed via mapped drive.

```<code>#===================================================================================================
    #runs powershell as admin and also preserves working directory
    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}

# Your script here
</code>```

Tried these but they didn't work, and I don't understand PowerShell enough to know why.

```<code>#=======================================================================================================================
    #for Batch file powershell calling with elevation:
    @echo off

    set scriptFileName=%~n0
    set scriptFolderPath=%~dp0
    set powershellScriptFileName=%scriptFileName%.ps1

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"
</code>```
```<code>#=======================================================================================================================

    If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {
    #"No Administrative rights, it will display a popup window asking user for Admin rights"

    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments

    break
    }
    #"After user clicked Yes on the popup, your file will be reopened with Admin rights"
    #"Put your code here"
</code>```

Body:
I need a prefix for PowerShell that I can insert prior to commands to automatically check for elevations and if not present, elevate the PowerShell (while asking for elevated credentials) and continue the script.  I have found this script below, which works, but is that the best implementation? Environment: Executed on computer joined to domain, PowerShell script executed via mapped drive.

#===================================================================================================
    #runs powershell as admin and also preserves working directory
    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}

# Your script here

Tried these but they didn't work, and I don't understand PowerShell enough to know why.

#=======================================================================================================================
    #for Batch file powershell calling with elevation:
    @echo off

    set scriptFileName=%~n0
    set scriptFolderPath=%~dp0
    set powershellScriptFileName=%scriptFileName%.ps1

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

#=======================================================================================================================

    If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {
    #"No Administrative rights, it will display a popup window asking user for Admin rights"

    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments

    break
    }
    #"After user clicked Yes on the popup, your file will be reopened with Admin rights"
    #"Put your code here"


来源: stackexchange

问:
File Chooser settings are automatically overwritten on RHEL8
I have RHEL8 with GNOME desktop.
I am trying to make the file chooser to show hidden files and directories.
I discovered gsettings and dconf-editor tools.
Through either of them I can get to org.gtk.Settings.FileChooser and request eaither of them to show and/or set the value of the "show-hidden" property.

By default show-hidden is false.

$ gsettings get  org.gtk.Settings.FileChooser show-hidden false
Same with the dconf-editor. I can change the value to true. It stays true for some time but when I try to open FileChooser I do not see hidden files or directories. And after I close FileChooser the value is overwritten back to "false".
Is it a bug or there is somethign preventign changes to the desktop configuration?

I tried setting the value through dconf-editor or gsettings.
I was expecting the value to stay permanently changed and the FileChooser to respect it and show hidden files and directories.

ContentLicense: CC BY-SA 4.0


问:
ECS Task Definition container_definitions is invalid: Error decoding JSON: invalid character 'f' after object key:value pair
I´m getting: [Error] invalid character 'f' after object key:value pair  How can I tell what is the (f) that is causing the error? is not quite descriptive the output like in some other languages that tells you the line number at least.

```<code>{
  "name": "${name}",
  "ulimits": [
    {
      "name": "nofile",
      "hardLimit": 204800,
      "softLimit": 102400
    }
  ],
  "image": "${ecr_url}/${image_name}:${image_tag}",
  "cpu": "${container_cpu}",
  "memory": null,
  "memoryReservation": "${container_memory}",
  "command": [
  "/bin/sh",
  "-c",
  "export DD_AGENT_HOST=$(curl --silent http://169.254.169.254/latest/meta-data/local-ipv4); /usr/bin/$APPLICATION_ARTIFACTS"
  ],
  "essential": true,
  "mountPoints": [],
  "portMappings": [
    {
      "containerPort": "${container_port}",
      "hostPort": 0,
      "protocol": "tcp"
    }
  ],
  "volumesFrom": [],
  "dockerLabels": {
    "application": "${application}",
    "environment": "${environment}",
    "version": "${image_tag}"
    },
  "logConfiguration": {
    "logDriver": "${log_driver}",
    "options": "${log_configuration}"
    },
  "environment": [
    {
      "name": "AWS_REGION",
      "value": "${task_region}"
    },
    {
      "name": "APPLICATION_ARTIFACTS",
      "value": "${application_artifacts}"
    },
    {
      "name": "ENVIRONMENT",
      "value": "${environment}"
    },
    {
      "name": "VERSION",
      "value": "${image_tag}"
    },
    {
      "name": "SERVER_PORT",
      "value": "${container_port}"
    },
    {
      "name": "DD_TRACE_SAMPLE_RATE",
      "value": "1.0"
    },
    {
      "name": "DD_LOGS_INJECTION",
      "value": "false"
    },
    {
      "name": "DD_ENV",
      "value": "${DD_ENV}"
    },
    {
      "name": "DD_SERVICE",
      "value": "${DD_SERVICE}"
    },
    {
      "name": "TABLE_NAME",
      "value": "${table_name}"
    }
  ]
}
</code>```

I´m getting: [Error] invalid character 'f' after object key:value pair

How can I tell what is the (f) that is causing the error? is not quite descriptive the output like in some other languages that tells you the line number at least.

```<code>Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: invalid character 'f' after object key:value pair

  on deployment/terraform/service-blue.tf line 89, in resource "aws_ecs_task_definition" "default_blue":
  89:   container_definitions = local.require_blue_service ? data.aws_s3_object.container_definition_blue[0].body : data.template_file.container_definitions.rendered
</code>```

Body:
I´m getting: [Error] invalid character 'f' after object key:value pair  How can I tell what is the (f) that is causing the error? is not quite descriptive the output like in some other languages that tells you the line number at least.

{
  "name": "${name}",
  "ulimits": [
    {
      "name": "nofile",
      "hardLimit": 204800,
      "softLimit": 102400
    }
  ],
  "image": "${ecr_url}/${image_name}:${image_tag}",
  "cpu": "${container_cpu}",
  "memory": null,
  "memoryReservation": "${container_memory}",
  "command": [
  "/bin/sh",
  "-c",
  "export DD_AGENT_HOST=$(curl --silent http://169.254.169.254/latest/meta-data/local-ipv4); /usr/bin/$APPLICATION_ARTIFACTS"
  ],
  "essential": true,
  "mountPoints": [],
  "portMappings": [
    {
      "containerPort": "${container_port}",
      "hostPort": 0,
      "protocol": "tcp"
    }
  ],
  "volumesFrom": [],
  "dockerLabels": {
    "application": "${application}",
    "environment": "${environment}",
    "version": "${image_tag}"
    },
  "logConfiguration": {
    "logDriver": "${log_driver}",
    "options": "${log_configuration}"
    },
  "environment": [
    {
      "name": "AWS_REGION",
      "value": "${task_region}"
    },
    {
      "name": "APPLICATION_ARTIFACTS",
      "value": "${application_artifacts}"
    },
    {
      "name": "ENVIRONMENT",
      "value": "${environment}"
    },
    {
      "name": "VERSION",
      "value": "${image_tag}"
    },
    {
      "name": "SERVER_PORT",
      "value": "${container_port}"
    },
    {
      "name": "DD_TRACE_SAMPLE_RATE",
      "value": "1.0"
    },
    {
      "name": "DD_LOGS_INJECTION",
      "value": "false"
    },
    {
      "name": "DD_ENV",
      "value": "${DD_ENV}"
    },
    {
      "name": "DD_SERVICE",
      "value": "${DD_SERVICE}"
    },
    {
      "name": "TABLE_NAME",
      "value": "${table_name}"
    }
  ]
}

I´m getting: [Error] invalid character 'f' after object key:value pair

How can I tell what is the (f) that is causing the error? is not quite descriptive the output like in some other languages that tells you the line number at least.

Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: invalid character 'f' after object key:value pair

  on deployment/terraform/service-blue.tf line 89, in resource "aws_ecs_task_definition" "default_blue":
  89:   container_definitions = local.require_blue_service ? data.aws_s3_object.container_definition_blue[0].body : data.template_file.container_definitions.rendered


问:
C# - Microsoft.AspNetCore.SpaProxy not invoking when debugging
I am trying to upgrade a .net 3.1 Angular (SPA template) app to .net 7.0. I am attempting to move away from the older UseSpa() middleware to the newer way for .net core to interact with Spa frameworks leveraging Microsoft.AspNetCore.SpaProxy. I am trying to update our project by modeling it off what comes out of the box in a new .net 7 Angular Spa template.

The issue I am running into is that the Proxy middleware is not being invoked. I am expecting to see something like:

Launching the SPA proxy...
This page will automatically redirect to http://localhost:44414 when the SPA proxy is ready.

as the Microsoft.AspNetCore.SpaProxy package is supposed to be added middleware to launch the npm command and redirect once the ng serve is ready. But I never see that or the npm script launched.

Here is what I have done so far:

Added the package to the .csproj file:

```<code> <PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="7.0.1" />
</code>```

Updated the LaunchSettings.json to include the environmental variable:

```<code>"environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
</code>```

Updated the project file to include the three Spa properties:

```<code> <SpaRoot>ClientApp\</SpaRoot>
    <SpaProxyServerUrl>http://localhost:4200</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
</code>```

I have tried numerous things to troubleshoot, including making the Program.cs the EXACT same as the template. (to rule out any other middle ware conflicting)

```<code>var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
}

app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();
</code>```

I know the package is installed correclty as I do see a spa.proxy.json in my bin folder. I also tested messing up the environment variable to verify it's taking effect and it does. changing it to:

```<code> "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy_WRONG"
</code>```

Produces the correct error running dotnet run:

```<code>crit: Microsoft.AspNetCore.Hosting.Diagnostics[11]
      Hosting startup assembly exception
      System.InvalidOperationException: Startup assembly Microsoft.AspNetCore.SpaProxy_WRONG failed to execute. See the inner exception for more details.
       ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNetCore.SpaProxy_WRONG, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
      File name: 'Microsoft.AspNetCore.SpaProxy_WRONG, Culture=neutral, PublicKeyToken=null'
         at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext, RuntimeAssembly requestingAssembly, Boolean throwOnFileNotFound)
         at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
         at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.ExecuteHostingStartups()
         --- End of inner exception stack trace ---
</code>```

I am running out of ideas of additional things to try. Has anyone had any experience adding Microsoft.AspNetCore.SpaProxy to a .net7 app, and can think of anything I might have missed?

Thank you.

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

Body:
I am trying to upgrade a .net 3.1 Angular (SPA template) app to .net 7.0. I am attempting to move away from the older UseSpa() middleware to the newer way for .net core to interact with Spa frameworks leveraging Microsoft.AspNetCore.SpaProxy. I am trying to update our project by modeling it off what comes out of the box in a new .net 7 Angular Spa template.

The issue I am running into is that the Proxy middleware is not being invoked. I am expecting to see something like:

Launching the SPA proxy...
This page will automatically redirect to http://localhost:44414 when the SPA proxy is ready.

as the Microsoft.AspNetCore.SpaProxy package is supposed to be added middleware to launch the npm command and redirect once the ng serve is ready. But I never see that or the npm script launched.

Here is what I have done so far:

Added the package to the .csproj file:

 <PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="7.0.1" />

Updated the LaunchSettings.json to include the environmental variable:

"environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }

Updated the project file to include the three Spa properties:

 <SpaRoot>ClientApp\</SpaRoot>
    <SpaProxyServerUrl>http://localhost:4200</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>

I have tried numerous things to troubleshoot, including making the Program.cs the EXACT same as the template. (to rule out any other middle ware conflicting)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
}

app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();

I know the package is installed correclty as I do see a spa.proxy.json in my bin folder. I also tested messing up the environment variable to verify it's taking effect and it does. changing it to:

 "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy_WRONG"

Produces the correct error running dotnet run:

crit: Microsoft.AspNetCore.Hosting.Diagnostics[11]
      Hosting startup assembly exception
      System.InvalidOperationException: Startup assembly Microsoft.AspNetCore.SpaProxy_WRONG failed to execute. See the inner exception for more details.
       ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNetCore.SpaProxy_WRONG, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
      File name: 'Microsoft.AspNetCore.SpaProxy_WRONG, Culture=neutral, PublicKeyToken=null'
         at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext, RuntimeAssembly requestingAssembly, Boolean throwOnFileNotFound)
         at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
         at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.ExecuteHostingStartups()
         --- End of inner exception stack trace ---

I am running out of ideas of additional things to try. Has anyone had any experience adding Microsoft.AspNetCore.SpaProxy to a .net7 app, and can think of anything I might have missed?

Thank you.


问:
pool.querty is not a function. Trying to connect google-cloud mysql instance from local machine
When trying to connect to the mysql instance on gcloud using nodejs and express. I'm getting the error "pool.query" is not a function. Bear with me since this the first time using gcloud and nodejs, i may be missing something obvious. I have already authorized my local ip,

This is my config

```<code>const config = {
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    socketPath: '/cloudsql/'+ process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
  connectionLimit: 5,
  connectTimeout: 10000, // 10 seconds
  waitForConnections: true, // Default: true
  queueLimit: 0, // Default: 0
};

module.exports = config;
</code>```

This is my pool creation method

```<code>//dotenv
require('dotenv').config();

// import mysql2
const mysql = require('mysql2/promise');

// get config
const config = require("./config");

// Connect to database
// createUnixSocketPool initializes a Unix socket connection pool for
// a Cloud SQL instance of MySQL.

async function createUnixSocketPool() {
  return mysql.createPool({...config,});
};

module.exports = {createUnixSocketPool};
</code>```

And lastly my code for connecting

```<code>const path = require('path');

const express = require('express');

const { createUnixSocketPool } = require("./db");

const app = express();

// create mysql pool
const pool = createUnixSocketPool();

app.get('/',async (req,res) => {
    console.log(await pool.query("show tables;"));
    res.send("test");

});

// Listening
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log('App is listening on port '+ PORT));
</code>```

For some reason this says that pool.query doesn't exist? I'm very new to node.js and javascript in general, what am i missing?

Body:
When trying to connect to the mysql instance on gcloud using nodejs and express. I'm getting the error "pool.query" is not a function. Bear with me since this the first time using gcloud and nodejs, i may be missing something obvious. I have already authorized my local ip,

This is my config

const config = {
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    socketPath: '/cloudsql/'+ process.env.INSTANCE_UNIX_SOCKET, // e.g. '/cloudsql/project:region:instance'
  connectionLimit: 5,
  connectTimeout: 10000, // 10 seconds
  waitForConnections: true, // Default: true
  queueLimit: 0, // Default: 0
};

module.exports = config;

This is my pool creation method

//dotenv
require('dotenv').config();

// import mysql2
const mysql = require('mysql2/promise');

// get config
const config = require("./config");

// Connect to database
// createUnixSocketPool initializes a Unix socket connection pool for
// a Cloud SQL instance of MySQL.

async function createUnixSocketPool() {
  return mysql.createPool({...config,});
};

module.exports = {createUnixSocketPool};

And lastly my code for connecting

const path = require('path');

const express = require('express');

const { createUnixSocketPool } = require("./db");

const app = express();

// create mysql pool
const pool = createUnixSocketPool();

app.get('/',async (req,res) => {
    console.log(await pool.query("show tables;"));
    res.send("test");

});

// Listening
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log('App is listening on port '+ PORT));

For some reason this says that pool.query doesn't exist? I'm very new to node.js and javascript in general, what am i missing?


问:
Need Project size of the projects in the sql db
I'm trying to query the specific projects and that project size in whole db, I am able to get the output with project names but I want to know the size of that projects in DB.

I have tried the below query and got the output of the projects which I need:

```<code>qtest=> select name from projects where name like 'MLC%' and issampleproject=false and enddate is null and issampleproject=false;
                     name
----------------------------------------------
MLC Customers
MLC DELIVERY
MLC Delivery - Clone - Copy-Paste Test
MLC (Sydney)
(4 rows)
</code>```

I need the size of the above projects.

Body:
I'm trying to query the specific projects and that project size in whole db, I am able to get the output with project names but I want to know the size of that projects in DB.

I have tried the below query and got the output of the projects which I need:

qtest=> select name from projects where name like 'MLC%' and issampleproject=false and enddate is null and issampleproject=false;
                     name
----------------------------------------------
MLC Customers
MLC DELIVERY
MLC Delivery - Clone - Copy-Paste Test
MLC (Sydney)
(4 rows)

I need the size of the above projects.


问:
What is the reason to select MinMaxScaler or Normalization?
I am working on LSTM model, and i saw different pre-processing for the similar data on the web. Can you please help me to understand difference between them and which one should i select:

1) MinMaxScaler

```<code>X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min
</code>```

2) Normalized to the range of (0 to 1) by Eq.

```<code>x=(Xi-Xmin)/(Xmax-Xmin)
</code>```

3) Normalize

```<code>train_mean = train_df.mean()
train_std = train_df.std()

train_df = (train_df - train_mean) / train_std
val_df = (val_df - train_mean) / train_std
test_df = (test_df - train_mean) / train_std
</code>```

My dataset: min value is 0 and max value is 1600.Almost one third of my dataset is zero. I do not have a negatif value.

thank you !

I tried minmaxscaler

Body:
I am working on LSTM model, and i saw different pre-processing for the similar data on the web. Can you please help me to understand difference between them and which one should i select:

1) MinMaxScaler

X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))
X_scaled = X_std * (max - min) + min

2) Normalized to the range of (0 to 1) by Eq.

x=(Xi-Xmin)/(Xmax-Xmin)

3) Normalize

train_mean = train_df.mean()
train_std = train_df.std()

train_df = (train_df - train_mean) / train_std
val_df = (val_df - train_mean) / train_std
test_df = (test_df - train_mean) / train_std

My dataset: min value is 0 and max value is 1600.Almost one third of my dataset is zero. I do not have a negatif value.

thank you !

I tried minmaxscaler


问:
Add Class to an Element If It's Sibling Has A Specific Class
I am trying to track when a header element contains a specific class or not. The header gets hidden based on scroll down and appears based on scroll up. Several classes get applied to the header during this time period of scrolling up or down. I need the sibling (#main) of header to get a class (scroll-down) added only when the specific class (is-fixed) is applied on the header. Below is the script...

const header = document.querySelector("header");
let lastScroll = 0;

const throttle = (func, time = 100) => {
  let lastTime = 0;
  return () => {
    const now = new Date();
    if (now - lastTime >= time) {
      func();
      time = now;
    }
  };
};

const validateHeader = () => {
  const windowY = window.scrollY;
  const windowH = window.innerHeight;
  if (windowY > windowH) {
    // We passed the first section, set a toggable class
    header.classList.add("is-fixed");
    // Determine is we ready to animate
    if (windowY > windowH + 40) {
      header.classList.add("can-animate");
      if (windowY < lastScroll) {
        // Determine if we scrolling up
        header.classList.add("scroll-up");
      } else {
        header.classList.remove("scroll-up");
      }
    } else {
      header.classList.remove("scroll-up");
    }
  } else {
    header.classList.remove("is-fixed", "can-animate");
  }
  lastScroll = windowY;
};

window.addEventListener("scroll", throttle(validateHeader, 100));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <header id="header" class="fixed-top">stuff</header>
  <section>stuff</section>
  <section>stuff</section>
  <main id="main" class="components">stuff</main>
</body></code>```

--UPDATE--

I edited a couple lines to add or remove a class on #main only when #header gets a specific class... (the purpose is adjusting the position of a side menu (in main) when the header gets hidden/shown).

```<code>  const header = document.querySelector("header");
  let lastScroll = 0;
  const throttle = (func, time = 100) => {
    let lastTime = 0;
    return () => {
      const now = new Date();
      if (now - lastTime >= time) {
        func();
        time = now;
      }
    };
  };
  const validateHeader = () => {
    const windowY = window.scrollY;
    const windowH = window.innerHeight;
    if (windowY > windowH) {
      // Set class on scrolling down
      header.classList.add("is-fixed");
      // Determine ready to animate
      if (windowY > windowH + 0) {
        header.classList.add("can-animate");
        if (windowY < lastScroll) {
          // Determine scrolling up
          header.classList.add("scroll-up");
          main.classList.remove("move-sidenav"); // for side nav
        } else {
          header.classList.remove("scroll-up");
          main.classList.add("move-sidenav"); // for side nav
        }
      } else {
        header.classList.remove("scroll-up");
        main.classList.add("move-sidenav"); // for side nav
      }
    } else {
      header.classList.remove("is-fixed", "can-animate");
      main.classList.remove("move-sidenav"); // for side nav
    }
    lastScroll = windowY;
  };
  window.addEventListener("scroll", throttle(validateHeader, 100));
</code>```

Body:
I am trying to track when a header element contains a specific class or not. The header gets hidden based on scroll down and appears based on scroll up. Several classes get applied to the header during this time period of scrolling up or down. I need the sibling (#main) of header to get a class (scroll-down) added only when the specific class (is-fixed) is applied on the header. Below is the script...

const header = document.querySelector("header");
let lastScroll = 0;

const throttle = (func, time = 100) => {
  let lastTime = 0;
  return () => {
    const now = new Date();
    if (now - lastTime >= time) {
      func();
      time = now;
    }
  };
};

const validateHeader = () => {
  const windowY = window.scrollY;
  const windowH = window.innerHeight;
  if (windowY > windowH) {
    // We passed the first section, set a toggable class
    header.classList.add("is-fixed");
    // Determine is we ready to animate
    if (windowY > windowH + 40) {
      header.classList.add("can-animate");
      if (windowY < lastScroll) {
        // Determine if we scrolling up
        header.classList.add("scroll-up");
      } else {
        header.classList.remove("scroll-up");
      }
    } else {
      header.classList.remove("scroll-up");
    }
  } else {
    header.classList.remove("is-fixed", "can-animate");
  }
  lastScroll = windowY;
};

window.addEventListener("scroll", throttle(validateHeader, 100));

  stuff

stuff

stuff

  stuff

--UPDATE--

I edited a couple lines to add or remove a class on #main only when #header gets a specific class... (the purpose is adjusting the position of a side menu (in main) when the header gets hidden/shown).

  const header = document.querySelector("header");
  let lastScroll = 0;
  const throttle = (func, time = 100) => {
    let lastTime = 0;
    return () => {
      const now = new Date();
      if (now - lastTime >= time) {
        func();
        time = now;
      }
    };
  };
  const validateHeader = () => {
    const windowY = window.scrollY;
    const windowH = window.innerHeight;
    if (windowY > windowH) {
      // Set class on scrolling down
      header.classList.add("is-fixed");
      // Determine ready to animate
      if (windowY > windowH + 0) {
        header.classList.add("can-animate");
        if (windowY < lastScroll) {
          // Determine scrolling up
          header.classList.add("scroll-up");
          main.classList.remove("move-sidenav"); // for side nav
        } else {
          header.classList.remove("scroll-up");
          main.classList.add("move-sidenav"); // for side nav
        }
      } else {
        header.classList.remove("scroll-up");
        main.classList.add("move-sidenav"); // for side nav
      }
    } else {
      header.classList.remove("is-fixed", "can-animate");
      main.classList.remove("move-sidenav"); // for side nav
    }
    lastScroll = windowY;
  };
  window.addEventListener("scroll", throttle(validateHeader, 100));


问:
Sending message from Flask to JS via socketio
I'm trying to wrap my head around this socketio thing and have hit a wall regarding sending a message from my Flask backend to my JavaScript frontend. My app is a consolidated control panel for my church's PTZ camera and OBS Studio. Here are the logical steps I'm trying to implement:

Connect Flask to OBS via the OBS websocket.

Receive notification in Flask when the Graphics source visibility in OBS changes.

Send a message from Flask to my JS frontend to let it know that the Graphics source has changed visibility (making a two-way sync with the button on my control panel and the actual source in OBS).

Steps 1 and 2 are working, but I can't get the 3rd one to work.

Here is my Python where I use the message from OBS to call the function to sync with the JS frontend. (I know the sync_graphics_toggle runs, but the JS never gets the emit message.)

```<code>def on_visibility_change(message):
    if (message.getItemName() == "Graphics"):
        sync_graphics_toggle(message.getItemVisible())

def sync_graphics_toggle(obs_graphics_visible):
    socketio.emit('syncGraphicsToggle', obs_graphics_visible, namespace='/main')
</code>```

In the JavaScript (with just a console log to test):

```<code>$(document).ready(function() {
  const socketMain = io("/main");
  socketMain.on("connect", function() {
    console.log("Made connection in graphics-preview", socketMain.id);
  });
  socketMain.on("syncGraphicsToggle", function(obsGraphicsVisible) {
    console.log("Got syncGraphicsToggle command")
  });
}
</code>```

I have verified that I'm connected, but I don't get the message from Flask.

I have other implementations of socketio in my code that work fine, but those are initiated by actions on the webpage. So, I'm thinking there is something I don't understand about sending messages that are initiated by the server.

Any pointers would be greatly appreciated.

John

Windows 10

Python = 3.10.4

Flask = 2.2.2

Python Socket.IO = 5.7.2

JS Socket.IO = 4.5.3

Body:
I'm trying to wrap my head around this socketio thing and have hit a wall regarding sending a message from my Flask backend to my JavaScript frontend. My app is a consolidated control panel for my church's PTZ camera and OBS Studio. Here are the logical steps I'm trying to implement:

Connect Flask to OBS via the OBS websocket.

Receive notification in Flask when the Graphics source visibility in OBS changes.

Send a message from Flask to my JS frontend to let it know that the Graphics source has changed visibility (making a two-way sync with the button on my control panel and the actual source in OBS).

Steps 1 and 2 are working, but I can't get the 3rd one to work.

Here is my Python where I use the message from OBS to call the function to sync with the JS frontend. (I know the sync_graphics_toggle runs, but the JS never gets the emit message.)

def on_visibility_change(message):
    if (message.getItemName() == "Graphics"):
        sync_graphics_toggle(message.getItemVisible())

def sync_graphics_toggle(obs_graphics_visible):
    socketio.emit('syncGraphicsToggle', obs_graphics_visible, namespace='/main')

In the JavaScript (with just a console log to test):

$(document).ready(function() {
  const socketMain = io("/main");
  socketMain.on("connect", function() {
    console.log("Made connection in graphics-preview", socketMain.id);
  });
  socketMain.on("syncGraphicsToggle", function(obsGraphicsVisible) {
    console.log("Got syncGraphicsToggle command")
  });
}

I have verified that I'm connected, but I don't get the message from Flask.

I have other implementations of socketio in my code that work fine, but those are initiated by actions on the webpage. So, I'm thinking there is something I don't understand about sending messages that are initiated by the server.

Any pointers would be greatly appreciated.

John

Windows 10

Python = 3.10.4

Flask = 2.2.2

Python Socket.IO = 5.7.2

JS Socket.IO = 4.5.3


问:
Subscribed to ROS2 topic but callback was not fired
I'm trying to read the messages send from topic /particlecloud (type PoseArray) and topic /odom (type Odometry).

```<code>class Server(Node):
    def __init__(self):
        super().__init__('minimal_subscriber')
        self.position = Point()
        self.particles = PoseArray()
        self.tolerance = 1
        self.publisher_ = self.create_publisher(Twist, 'cmd_vel', 10)

        self.particle_cloud_subscription = self.create_subscription(PoseArray, 'particlecloud', self.particle_cloud_callback, 10)
        self.odom_subscription = self.create_subscription(Odometry, 'odom', self.odom_callback, 10)

    def odom_callback(self, msg):
        # print("odom message")
        self.position = msg.pose.pose.position

    def particle_cloud_callback(self, msg):
        print("particle message")
        self.particles = msg
</code>```

The odom_callback triggered fine, but not the particle_cloud_callback.
I checked the topic subscriber on terminal after running the node and saw that the topic 'particlecloud' was subscribed by 'minimal_subscriber' also.

There was another topic 'particle_cloud' which also has the same content but different type (ParticleCloud) but the callback was not triggered.

Do you have any suggestions on what I should configure for the subscriber? I think the problem might be the length of the message but don't know how to fix it.

Body:
I'm trying to read the messages send from topic /particlecloud (type PoseArray) and topic /odom (type Odometry).

class Server(Node):
    def __init__(self):
        super().__init__('minimal_subscriber')
        self.position = Point()
        self.particles = PoseArray()
        self.tolerance = 1
        self.publisher_ = self.create_publisher(Twist, 'cmd_vel', 10)

        self.particle_cloud_subscription = self.create_subscription(PoseArray, 'particlecloud', self.particle_cloud_callback, 10)
        self.odom_subscription = self.create_subscription(Odometry, 'odom', self.odom_callback, 10)

    def odom_callback(self, msg):
        # print("odom message")
        self.position = msg.pose.pose.position

    def particle_cloud_callback(self, msg):
        print("particle message")
        self.particles = msg

The odom_callback triggered fine, but not the particle_cloud_callback.
I checked the topic subscriber on terminal after running the node and saw that the topic 'particlecloud' was subscribed by 'minimal_subscriber' also.

There was another topic 'particle_cloud' which also has the same content but different type (ParticleCloud) but the callback was not triggered.

Do you have any suggestions on what I should configure for the subscriber? I think the problem might be the length of the message but don't know how to fix it.


问:
How to fix react/no-unknown-property error?
I have a react application that I use svg as a logo and deploy in vercel. But I am getting the following errors. I don't get this error in my local, but I get it during deploy. Also, if I change the featurekey in my locale, that is, if I make it camelcase, I also get the error in my local. I didn't understand exactly what this is.

```<code>src/components/Logo/index.js
  Line 16:6:  Unknown property 'featurekey' found   react/no-unknown-property
  Line 29:8:  Unknown property 'xmlnsi' found       react/no-unknown-property
  Line 30:8:  Unknown property 'iextraneous' found  react/no-unknown-property
  Line 41:6:  Unknown property 'featurekey' found   react/no-unknown-property
</code>```

I tried using camelcase like featureKey but it didn't work, this time it threw the same error for featureKey. I also tried to add .eslintrc.json this:

```<code>"react/no-unknown-property": ["error", { ignore: ["jsx"] }],
</code>```

but didn't work.

Logo.js

```<code>export function Logo(props) {
    return (
        <svg
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
            version="1.1"
            width="3162.1000925144112"
            height="970.434162445735"
            viewBox="0 0 3162.1000925144112 970.434162445735"
            {...props}
        >
            <g transform="scale(8.105004625720571) translate(10, 10)">
                <defs id="SvgjsDefs8550"></defs>
                <g
                    id="SvgjsG8551"
                    featurekey="7KWit6-0"
                    transform="matrix(0.9144333410065809,0,0,0.9144333410065809,-2.2989350715586716,14.598966612953934)"
                    fill={props.color ? props.color : '#4F46E5'}
                >
                    <switch xmlns="http://www.w3.org/2000/svg">
                        <foreignObject
                            requiredExtensions="http://ns.adobe.com/AdobeIllustrator/10.0/"
                            x="0"
                            y="0"
                            width="1"
                            height="1"
                        ></foreignObject>
                        <g
                            xmlnsi="http://ns.adobe.com/AdobeIllustrator/10.0/"
                            iextraneous="self"
                        >
                            <g>
                                <path d="M48.6,49.7V15c0-2.6-2.1-4.8-4.8-4.8c-11.8,0-23,5-30.9,13.8C5.2,32.8,1.4,44.6,2.8,56.4c2.2,19.4,17.9,34.8,37.4,36.5     c1.2,0.1,2.5,0.2,3.7,0.2c11,0,21.5-4.3,29.3-12.1c1.9-1.9,1.9-4.9,0-6.7L48.6,49.7z M41,83.4C26.2,82.1,13.8,70,12.2,55.3     c-1-9.2,1.8-18.1,7.9-24.9c5-5.6,11.7-9.2,19-10.3v31.1c0,1.6,0.6,3,1.7,4.1l22,22C56.6,81.9,48.8,84.1,41,83.4z"></path>
                                <path d="M60.3,7c-0.9,0-1.8,0.3-2.4,0.9c-0.7,0.6-1,1.5-1,2.4v34.8c0,0.8,0.3,1.6,0.9,2.2l24.6,24.6c0.6,0.6,1.5,1,2.4,1     c0,0,0,0,0.1,0c0.9,0,1.7-0.4,2.3-1c6.7-7.1,10.3-16.5,10.3-26.3C97.5,24.7,81.2,7.7,60.3,7z"></path>
                            </g>
                        </g>
                    </switch>
                </g>
                <g
                    id="SvgjsG8552"
                    featurekey="ewgXDI-0"
                    transform="matrix(3.3958030320267483,0,0,3.3958030320267483,104.87762310498329,13.019631150989738)"
                    fill={props.color ? props.color : '#4F46E5'}
                >
                    <path d="M4.9902 20.19531 c-2.2559 0 -4.0039 -0.88867 -4.3652 -2.793 l2.3535 -0.66406 c0.30273 1.0742 1.0645 1.4941 2.0117 1.4941 c0.69336 0 1.4453 -0.21484 1.4258 -1.0059 c-0.0097656 -1.0449 -1.5918 -1.1328 -3.1836 -1.6992 c-1.2012 -0.41992 -2.3535 -1.0645 -2.3535 -2.7539 c0 -2.0605 1.709 -3.0078 3.9355 -3.0078 c1.9531 0 3.584 0.74219 3.9746 2.6563 l-2.1777 0.48828 c-0.30273 -0.9375 -0.9668 -1.2695 -1.7871 -1.2695 c-0.74219 0 -1.377 0.26367 -1.377 0.88867 c0 0.79102 1.1621 0.94727 2.4219 1.2891 c1.5527 0.41992 3.252 1.0938 3.252 3.2422 c0 2.3047 -1.9629 3.1348 -4.1309 3.1348 z M15.8203 20.19531 c-3.1934 0 -5.498 -1.9434 -5.498 -5.2246 c0 -3.2617 2.2852 -5.2051 5.498 -5.2051 c3.2324 0 5.5078 1.9434 5.5078 5.2051 c0 3.2813 -2.2852 5.2246 -5.5078 5.2246 z M15.791 17.959 c1.6309 0 2.7441 -1.1914 2.7441 -2.9883 s-1.1133 -2.9883 -2.7441 -2.9883 c-1.5723 0 -2.6758 1.1914 -2.6758 2.9883 s1.1035 2.9883 2.6758 2.9883 z M26.113290625 11.5527 c0.50781 -0.88867 1.8262 -1.709 3.2813 -1.709 l0 2.5098 c-2.1289 0 -3.1445 0.625 -3.1445 2.7539 l0 4.8926 l-2.832 0 l0 -10.039 l2.6953 0 l0 1.5918 z M36.94334375 9.766 c2.6367 0 4.8242 1.9531 4.8242 5.2344 s-2.1875 5.2344 -4.8242 5.2344 c-1.3867 0 -2.5977 -0.55664 -3.1641 -1.543 l-0.068359 1.3086 l-2.666 0 l0 -15 l2.8125 0 l0 6.1816 c0.58594 -0.9082 1.7578 -1.416 3.0859 -1.416 z M36.28904375 17.9004 c1.4941 0 2.666 -1.1035 2.666 -2.9004 c0 -1.8066 -1.1719 -2.9102 -2.666 -2.9102 c-1.4844 0 -2.6563 1.1523 -2.6563 2.9102 s1.1621 2.9004 2.6563 2.9004 z M50.537140625 9.961 l2.8125 0 l0 10.039 l-2.666 0 l-0.068359 -1.2109 c-0.70313 0.88867 -1.8164 1.4063 -3.1934 1.4063 c-2.4121 0 -3.7402 -1.2598 -3.7402 -3.4766 l0 -6.7578 l2.8223 0 l0 6.1523 c0 1.3281 0.83008 1.8164 1.8066 1.8164 c1.1621 0 2.2168 -0.58594 2.2266 -2.4316 l0 -5.5371 z M62.1874875 9.766 c2.4121 0 3.7402 1.25 3.7402 3.4766 l0 6.7578 l-2.8223 0 l0 -6.1523 c0 -1.3379 -0.83008 -1.8262 -1.7969 -1.8262 c-1.1621 0 -2.2168 0.58594 -2.2363 2.4414 l0 5.5371 l-2.8125 0 l0 -10.039 l2.8125 0 l0 1.1133 c0.70313 -0.83008 1.7871 -1.3086 3.1152 -1.3086 z M75.302765625 9.961 l2.8125 0 l0 10.039 l-2.666 0 l-0.068359 -1.2109 c-0.70313 0.88867 -1.8164 1.4063 -3.1934 1.4063 c-2.4121 0 -3.7402 -1.2598 -3.7402 -3.4766 l0 -6.7578 l2.8223 0 l0 6.1523 c0 1.3281 0.83008 1.8164 1.8066 1.8164 c1.1621 0 2.2168 -0.58594 2.2266 -2.4316 l0 -5.5371 z"></path>
                </g>
            </g>
        </svg>
    );
}
</code>```

.eslintrc.json

```<code>{
    "env": {
        "browser": true,
        "es2021": true,
        "node": true,
        "jest": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:react-hooks/recommended",
        "plugin:prettier/recommended"
    ],
    "settings": {
        "react": {
            "version": "detect"
        }
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "plugins": ["react", "react-hooks", "prettier"],
    "rules": {
        "react/react-in-jsx-scope": "off",
        "react/prop-types": "off",
        "react/no-unescaped-entities": "off",
        "no-console": "error"
    }
}
</code>```

Body:
I have a react application that I use svg as a logo and deploy in vercel. But I am getting the following errors. I don't get this error in my local, but I get it during deploy. Also, if I change the featurekey in my locale, that is, if I make it camelcase, I also get the error in my local. I didn't understand exactly what this is.

src/components/Logo/index.js
  Line 16:6:  Unknown property 'featurekey' found   react/no-unknown-property
  Line 29:8:  Unknown property 'xmlnsi' found       react/no-unknown-property
  Line 30:8:  Unknown property 'iextraneous' found  react/no-unknown-property
  Line 41:6:  Unknown property 'featurekey' found   react/no-unknown-property

I tried using camelcase like featureKey but it didn't work, this time it threw the same error for featureKey. I also tried to add .eslintrc.json this:

"react/no-unknown-property": ["error", { ignore: ["jsx"] }],

but didn't work.

Logo.js

export function Logo(props) {
    return (
        <svg
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
            version="1.1"
            width="3162.1000925144112"
            height="970.434162445735"
            viewBox="0 0 3162.1000925144112 970.434162445735"
            {...props}
        >
            <g transform="scale(8.105004625720571) translate(10, 10)">
                <defs id="SvgjsDefs8550"></defs>
                <g
                    id="SvgjsG8551"
                    featurekey="7KWit6-0"
                    transform="matrix(0.9144333410065809,0,0,0.9144333410065809,-2.2989350715586716,14.598966612953934)"
                    fill={props.color ? props.color : '#4F46E5'}
                >
                    <switch xmlns="http://www.w3.org/2000/svg">
                        <foreignObject
                            requiredExtensions="http://ns.adobe.com/AdobeIllustrator/10.0/"
                            x="0"
                            y="0"
                            width="1"
                            height="1"
                        ></foreignObject>
                        <g
                            xmlnsi="http://ns.adobe.com/AdobeIllustrator/10.0/"
                            iextraneous="self"
                        >
                            <g>
                                <path d="M48.6,49.7V15c0-2.6-2.1-4.8-4.8-4.8c-11.8,0-23,5-30.9,13.8C5.2,32.8,1.4,44.6,2.8,56.4c2.2,19.4,17.9,34.8,37.4,36.5     c1.2,0.1,2.5,0.2,3.7,0.2c11,0,21.5-4.3,29.3-12.1c1.9-1.9,1.9-4.9,0-6.7L48.6,49.7z M41,83.4C26.2,82.1,13.8,70,12.2,55.3     c-1-9.2,1.8-18.1,7.9-24.9c5-5.6,11.7-9.2,19-10.3v31.1c0,1.6,0.6,3,1.7,4.1l22,22C56.6,81.9,48.8,84.1,41,83.4z"></path>
                                <path d="M60.3,7c-0.9,0-1.8,0.3-2.4,0.9c-0.7,0.6-1,1.5-1,2.4v34.8c0,0.8,0.3,1.6,0.9,2.2l24.6,24.6c0.6,0.6,1.5,1,2.4,1     c0,0,0,0,0.1,0c0.9,0,1.7-0.4,2.3-1c6.7-7.1,10.3-16.5,10.3-26.3C97.5,24.7,81.2,7.7,60.3,7z"></path>
                            </g>
                        </g>
                    </switch>
                </g>
                <g
                    id="SvgjsG8552"
                    featurekey="ewgXDI-0"
                    transform="matrix(3.3958030320267483,0,0,3.3958030320267483,104.87762310498329,13.019631150989738)"
                    fill={props.color ? props.color : '#4F46E5'}
                >
                    <path d="M4.9902 20.19531 c-2.2559 0 -4.0039 -0.88867 -4.3652 -2.793 l2.3535 -0.66406 c0.30273 1.0742 1.0645 1.4941 2.0117 1.4941 c0.69336 0 1.4453 -0.21484 1.4258 -1.0059 c-0.0097656 -1.0449 -1.5918 -1.1328 -3.1836 -1.6992 c-1.2012 -0.41992 -2.3535 -1.0645 -2.3535 -2.7539 c0 -2.0605 1.709 -3.0078 3.9355 -3.0078 c1.9531 0 3.584 0.74219 3.9746 2.6563 l-2.1777 0.48828 c-0.30273 -0.9375 -0.9668 -1.2695 -1.7871 -1.2695 c-0.74219 0 -1.377 0.26367 -1.377 0.88867 c0 0.79102 1.1621 0.94727 2.4219 1.2891 c1.5527 0.41992 3.252 1.0938 3.252 3.2422 c0 2.3047 -1.9629 3.1348 -4.1309 3.1348 z M15.8203 20.19531 c-3.1934 0 -5.498 -1.9434 -5.498 -5.2246 c0 -3.2617 2.2852 -5.2051 5.498 -5.2051 c3.2324 0 5.5078 1.9434 5.5078 5.2051 c0 3.2813 -2.2852 5.2246 -5.5078 5.2246 z M15.791 17.959 c1.6309 0 2.7441 -1.1914 2.7441 -2.9883 s-1.1133 -2.9883 -2.7441 -2.9883 c-1.5723 0 -2.6758 1.1914 -2.6758 2.9883 s1.1035 2.9883 2.6758 2.9883 z M26.113290625 11.5527 c0.50781 -0.88867 1.8262 -1.709 3.2813 -1.709 l0 2.5098 c-2.1289 0 -3.1445 0.625 -3.1445 2.7539 l0 4.8926 l-2.832 0 l0 -10.039 l2.6953 0 l0 1.5918 z M36.94334375 9.766 c2.6367 0 4.8242 1.9531 4.8242 5.2344 s-2.1875 5.2344 -4.8242 5.2344 c-1.3867 0 -2.5977 -0.55664 -3.1641 -1.543 l-0.068359 1.3086 l-2.666 0 l0 -15 l2.8125 0 l0 6.1816 c0.58594 -0.9082 1.7578 -1.416 3.0859 -1.416 z M36.28904375 17.9004 c1.4941 0 2.666 -1.1035 2.666 -2.9004 c0 -1.8066 -1.1719 -2.9102 -2.666 -2.9102 c-1.4844 0 -2.6563 1.1523 -2.6563 2.9102 s1.1621 2.9004 2.6563 2.9004 z M50.537140625 9.961 l2.8125 0 l0 10.039 l-2.666 0 l-0.068359 -1.2109 c-0.70313 0.88867 -1.8164 1.4063 -3.1934 1.4063 c-2.4121 0 -3.7402 -1.2598 -3.7402 -3.4766 l0 -6.7578 l2.8223 0 l0 6.1523 c0 1.3281 0.83008 1.8164 1.8066 1.8164 c1.1621 0 2.2168 -0.58594 2.2266 -2.4316 l0 -5.5371 z M62.1874875 9.766 c2.4121 0 3.7402 1.25 3.7402 3.4766 l0 6.7578 l-2.8223 0 l0 -6.1523 c0 -1.3379 -0.83008 -1.8262 -1.7969 -1.8262 c-1.1621 0 -2.2168 0.58594 -2.2363 2.4414 l0 5.5371 l-2.8125 0 l0 -10.039 l2.8125 0 l0 1.1133 c0.70313 -0.83008 1.7871 -1.3086 3.1152 -1.3086 z M75.302765625 9.961 l2.8125 0 l0 10.039 l-2.666 0 l-0.068359 -1.2109 c-0.70313 0.88867 -1.8164 1.4063 -3.1934 1.4063 c-2.4121 0 -3.7402 -1.2598 -3.7402 -3.4766 l0 -6.7578 l2.8223 0 l0 6.1523 c0 1.3281 0.83008 1.8164 1.8066 1.8164 c1.1621 0 2.2168 -0.58594 2.2266 -2.4316 l0 -5.5371 z"></path>
                </g>
            </g>
        </svg>
    );
}

.eslintrc.json

{
    "env": {
        "browser": true,
        "es2021": true,
        "node": true,
        "jest": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended",
        "plugin:react-hooks/recommended",
        "plugin:prettier/recommended"
    ],
    "settings": {
        "react": {
            "version": "detect"
        }
    },
    "parserOptions": {
        "ecmaFeatures": {
            "jsx": true
        },
        "ecmaVersion": "latest",
        "sourceType": "module"
    },
    "plugins": ["react", "react-hooks", "prettier"],
    "rules": {
        "react/react-in-jsx-scope": "off",
        "react/prop-types": "off",
        "react/no-unescaped-entities": "off",
        "no-console": "error"
    }
}


问:
How to get current variation price in woocommerce single product page using ajax?
On Single product page of a variable product of woocommerce when user selects product options; woocommerce makes an ajax call and shows the variation price and inventory available. I just need to know how can I add my custom math to that ajax response? For example current variation price ajax response was 300 I want to add 30 more to that. Can anybody help plz?

I searched woocommerce files but no luck.


问:
WSO2 MI Validators and Array query parameters for a Data Service
I don't know how to create a validator for 2 variables:

Q1. An user code that needs to be checked if exists prior to running the SQL query. I have an endpoint to check if the user code exists or not, how do I make it into a validator?

Q2. An array of dates, the best I could do was to use a pattern validator. I know there's also the possibility to set a parameter with paramType="array" and sqlType="date", but how can I configure this in the query parameters of the resource?

Please check the Data Service definition below:

<data name="APIDataService" serviceNamespace="" serviceGroup="" transports="http https local">
    <description />

    <config id="postgresDataService">
        <property name="carbon_datasource_name">APIPostgres</property>
    </config>

    <query id="validateUserCode" useConfig="postgresDataService">
        <sql>
            SELECT ( EXISTS ( SELECT 1
                              FROM user
                              WHERE code ILIKE :user_code ) )::INT AS does_user_exist
        </sql>
        <param name="user_code" sqlType="string" />
        <result element="result">
            <element column="does_user_exist" name="doesUserExist" xsdType="integer" />
        </result>
    </query>
    <resource method="GET" path="validateUserCode">
        <call-query href="validateUserCode">
            <with-param name="user_code" query-param="user_code" />
        </call-query>
    </resource>

    <query id="apiReportUserTotalEventsByDay" useConfig="postgresDataService">
        <sql>
            SELECT
                calendar_date,
                record_date,
                user_code,
                event_type_id,
                event_count
            FROM user_event
            WHERE 1=1
                AND calendar_date BETWEEN :calendar_date_start AND :calendar_date_end
                AND record_date = ANY( ('{'||:record_date_array||'}')::DATE[] )
                AND user_code = :user_code
        </sql>

        <param name="user_code"           paramType="scalar" sqlType="string" />

        <param name="calendar_date_start" paramType="scalar" sqlType="date"   />
        <param name="calendar_date_end"   paramType="scalar" sqlType="date"   />

        <param name="record_date_array"   paramType="scalar" sqlType="string"  >
            <validatePattern pattern="\s*\d{4}-\d{2}-\d{2}\s*(,\s*\d{4}-\d{2}-\d{2}\s*)*" />
        </param>

        <result element="result">
            <element column="calendar_date" name="calendar_date" xsdType="string"  />
            <element column="record_date"   name="record_date"   xsdType="string"  />
            <element column="user_code"     name="user_code"     xsdType="string"  />
            <element column="event_type_id" name="event_type_id" xsdType="integer" />
            <element column="event_count"   name="event_count"   xsdType="integer" />
        </result>
    </query>
    <resource method="GET" path="apiReportUserTotalEventsByDay">
        <call-query href="apiReportUserTotalEventsByDay">
            <with-param name="user_code"           query-param="user_code"           />
            <with-param name="calendar_date_start" query-param="calendar_date_start" />
            <with-param name="calendar_date_end"   query-param="calendar_date_end"   />
            <with-param name="record_date_array"   query-param="record_date_array"   />
        </call-query>
    </resource>

</data>
```


问:
How can I change the size of a Widget in a GtkGrid cell
In order to get familiar with GTK I wrote my first simple application that shows three text entries and a Quit button. I use GtkBuilder to construct my UI.

Now, I'm wondering of how to change the size (width) of the textEntry widgets. The grid is creating the spaces always homogeneously. Instead, I want to set the width of txtEntry1 and txtEntry2 manually by myself, for example 10% of the row for txtEntry1 and 90% of the row for txtEntry2.

Any suggestions?

Here is my draft code:

```<code>#include <gtk/gtk.h>
#include <glib/gstdio.h>

static void activate (GtkApplication *app, gpointer user_data) {

  GtkBuilder *builder = gtk_builder_new ();
  gtk_builder_add_from_file (builder, "builder.ui", NULL);

  GObject *window = gtk_builder_get_object (builder, "window");
  GObject *textEntry = gtk_builder_get_object (builder,"txtEntry");
  GObject *textEntry1 = gtk_builder_get_object (builder,"txtEntry1");
  GObject *textEntry2 = gtk_builder_get_object (builder,"txtEntry2");
  GObject *buttonQ = gtk_builder_get_object (builder, "quit");

  gtk_window_set_application (GTK_WINDOW (window), app);
  gtk_widget_show (GTK_WIDGET (window));
}

int main (int argc, char *argv[]) {
    #ifdef GTK_SRCDIR
       g_chdir (GTK_SRCDIR);
    #endif

    GtkApplication *app = gtk_application_new ("org.gtk.example",
    G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);

    int status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}
</code>```

And here is my GtkBuilder code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<interface>
<object id="window" class="GtkWindow">
  <property name="title">Grid</property>
  <child>
  <object id="grid" class="GtkGrid">

  <!-- ====================== Text Entry ============================  -->
    <child>
      <object id="txtEntry" class="GtkEntry">
      <property name="placeholder-text">txtEntry</property>
      <property name="xalign">0.5</property>
        <layout>
          <property name="column">0</property>
          <property name="row">0</property>
          <property name="column-span">4</property>
        </layout>
      </object>
    </child>
  <!-- ====================== Text Entry 2 ==========================  -->
    <child>
      <object id="txtEntry2" class="GtkEntry">
      <property name="placeholder-text">txtEntry 2</property>
      <property name="xalign">0</property>
        <layout>
          <property name="column">0</property>
          <property name="row">1</property>
          <property name="column-span">1</property>
        </layout>
      </object>
    </child>
  <!-- ====================== Text Entry 1 ==========================  -->
    <child>
      <object id="txtEntry1" class="GtkEntry">
      <property name="placeholder-text">txtEntry 1</property>
      <property name="xalign">1</property>
        <layout>
          <property name="column">1</property>
          <property name="row">1</property>
          <property name="column-span">3</property>
        </layout>
      </object>
    </child>
  <!-- ====================== Button Quit ===========================  -->
    <child>
      <object id="quit" class="GtkButton">
        <property name="label">Quit</property>
        <layout>
          <property name="column">0</property>
          <property name="row">2</property>
          <property name="column-span">4</property>
        </layout>
      </object>
    </child>

    </object>
   </child>
  </object>
</interface>
</code>```

Body:
In order to get familiar with GTK I wrote my first simple application that shows three text entries and a Quit button. I use GtkBuilder to construct my UI.

Now, I'm wondering of how to change the size (width) of the textEntry widgets. The grid is creating the spaces always homogeneously. Instead, I want to set the width of txtEntry1 and txtEntry2 manually by myself, for example 10% of the row for txtEntry1 and 90% of the row for txtEntry2.

Any suggestions?

Here is my draft code:

#include <gtk/gtk.h>
#include <glib/gstdio.h>

static void activate (GtkApplication *app, gpointer user_data) {

  GtkBuilder *builder = gtk_builder_new ();
  gtk_builder_add_from_file (builder, "builder.ui", NULL);

  GObject *window = gtk_builder_get_object (builder, "window");
  GObject *textEntry = gtk_builder_get_object (builder,"txtEntry");
  GObject *textEntry1 = gtk_builder_get_object (builder,"txtEntry1");
  GObject *textEntry2 = gtk_builder_get_object (builder,"txtEntry2");
  GObject *buttonQ = gtk_builder_get_object (builder, "quit");

  gtk_window_set_application (GTK_WINDOW (window), app);
  gtk_widget_show (GTK_WIDGET (window));
}

int main (int argc, char *argv[]) {
    #ifdef GTK_SRCDIR
       g_chdir (GTK_SRCDIR);
    #endif

    GtkApplication *app = gtk_application_new ("org.gtk.example",
    G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);

    int status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

And here is my GtkBuilder code:

<?xml version="1.0" encoding="UTF-8"?>
<interface>
<object id="window" class="GtkWindow">
  <property name="title">Grid</property>
  <child>
  <object id="grid" class="GtkGrid">

    <child>
      <object id="txtEntry" class="GtkEntry">
      <property name="placeholder-text">txtEntry</property>
      <property name="xalign">0.5</property>
        <layout>
          <property name="column">0</property>
          <property name="row">0</property>
          <property name="column-span">4</property>
        </layout>
      </object>
    </child>

    <child>
      <object id="txtEntry2" class="GtkEntry">
      <property name="placeholder-text">txtEntry 2</property>
      <property name="xalign">0</property>
        <layout>
          <property name="column">0</property>
          <property name="row">1</property>
          <property name="column-span">1</property>
        </layout>
      </object>
    </child>

    <child>
      <object id="txtEntry1" class="GtkEntry">
      <property name="placeholder-text">txtEntry 1</property>
      <property name="xalign">1</property>
        <layout>
          <property name="column">1</property>
          <property name="row">1</property>
          <property name="column-span">3</property>
        </layout>
      </object>
    </child>

    <child>
      <object id="quit" class="GtkButton">
        <property name="label">Quit</property>
        <layout>
          <property name="column">0</property>
          <property name="row">2</property>
          <property name="column-span">4</property>
        </layout>
      </object>
    </child>

    </object>
   </child>
  </object>
</interface>


问:
Returns both a value and a reference to its internal field in Rust
I am trying to return an object together with a reference to its internal body, e.g.

struct S {
    i: i8,
}

fn ret_ref() -> (S, &i8) {
    let s = S{i: 3};
    (s, &s.i)
}
```

And the lifetime checker recognized that &i8 might have a shorter lifetime than the original value. now if I return s together, is there a way to extend the lifetime of the reference?

Body:
I am trying to return an object together with a reference to its internal body, e.g.

struct S {
    i: i8,
}

fn ret_ref() -> (S, &i8) {
    let s = S{i: 3};
    (s, &s.i)
}

And the lifetime checker recognized that &i8 might have a shorter lifetime than the original value. now if I return s together, is there a way to extend the lifetime of the reference?


问:
How do I get VSCode Vim Extension to Control VSCode Keybindings?
I am new to VSCode from Vim.

I am trying to get Vim to run the VSCode shortcuts and I can't seem to figure out how to get it going.

for example:

In Vim i use <leader>t to open a terminal below. In VSCode this is Ctr+Shift+
or <leader>h and <leader>l to switch between splits is Ctr+1 and Ctr+2 in VSCode

I have tried remapping the Vim keys to the VSCode commands like this:

```<code>    "vim.normalModeKeyBindingsNonRecursive": [
    {
        "before": ["<leader>", "h"],
        "after": ["<C-1>"]
    },
]
</code>```

but it doesn't seem to work.

Any help you can provide would be greatly appreciated!

Body:
I am new to VSCode from Vim.

I am trying to get Vim to run the VSCode shortcuts and I can't seem to figure out how to get it going.

for example:

In Vim i use <leader>t to open a terminal below. In VSCode this is Ctr+Shift+
or <leader>h and <leader>l to switch between splits is Ctr+1 and Ctr+2 in VSCode

I have tried remapping the Vim keys to the VSCode commands like this:

    "vim.normalModeKeyBindingsNonRecursive": [
    {
        "before": ["<leader>", "h"],
        "after": ["<C-1>"]
    },
]

but it doesn't seem to work.

Any help you can provide would be greatly appreciated!


问:
Python Codes using the pyautogui library not working. This if else block is not working, what error am I doing?
```<code>import pyautogui
import time
import keyboard
import python_imagesearch
from python_imagesearch import imagesearch
from time import sleep

donme1 = (-1, 300)
donme2 = (300, 300)

pos = imagesearch.imagesearch('tra.png', 0.7)
print(pos)

def donuszamani():
    pyautogui.moveTo(donme1)
    time.sleep(1)
    pyautogui.moveTo(donme2)
    time.sleep(1)

def sagisin():
    time.sleep(2)
    pyautogui.mouseDown(button='right')
    time.sleep(1)
    pyautogui.mouseUp(button='right')
    time.sleep(1)

def solisin():
    time.sleep(2)
    pyautogui.mouseDown(button='left')
    time.sleep(1)
    pyautogui.mouseUp(button='left')
    time.sleep(1)

if pos:
    if pos[0] != -1:
        print("position : ", pos[0], pos[1])
        pyautogui.moveTo(pos[0]+93, pos[1]+90)
        time.sleep(0.1)
        pyautogui.mouseDown()
        time.sleep(0.1)
        pyautogui.mouseUp()
        sagisin()
        print("Congratulations 1")
    else:
        donuszamani()
        print()
else:
    donuszamani()
    if pos[0] != -1:
        print("position : ", pos[0], pos[1])
        pyautogui.moveTo(pos[0]+93, pos[1]+90)
        time.sleep(0.1)
        pyautogui.mouseDown()
        time.sleep(0.1)
        pyautogui.mouseUp()
        sagisin()
        print("Congratulations")
    else:
        ("Nope")
</code>```

This is how I wrote my Python Codes using the pyautogui library. I'm writing a simple bot. In these codes, the coding ends after the first if else block. He sees the photo when I show him and continues, but when he does not see the photo, I say turn back, but after he returns once, it does not continue. I think I've come up with a dysfunctional code. How do i fix this.

Body:
import pyautogui
import time
import keyboard
import python_imagesearch
from python_imagesearch import imagesearch
from time import sleep

donme1 = (-1, 300)
donme2 = (300, 300)

pos = imagesearch.imagesearch('tra.png', 0.7)
print(pos)

def donuszamani():
    pyautogui.moveTo(donme1)
    time.sleep(1)
    pyautogui.moveTo(donme2)
    time.sleep(1)

def sagisin():
    time.sleep(2)
    pyautogui.mouseDown(button='right')
    time.sleep(1)
    pyautogui.mouseUp(button='right')
    time.sleep(1)

def solisin():
    time.sleep(2)
    pyautogui.mouseDown(button='left')
    time.sleep(1)
    pyautogui.mouseUp(button='left')
    time.sleep(1)

if pos:
    if pos[0] != -1:
        print("position : ", pos[0], pos[1])
        pyautogui.moveTo(pos[0]+93, pos[1]+90)
        time.sleep(0.1)
        pyautogui.mouseDown()
        time.sleep(0.1)
        pyautogui.mouseUp()
        sagisin()
        print("Congratulations 1")
    else:
        donuszamani()
        print()
else:
    donuszamani()
    if pos[0] != -1:
        print("position : ", pos[0], pos[1])
        pyautogui.moveTo(pos[0]+93, pos[1]+90)
        time.sleep(0.1)
        pyautogui.mouseDown()
        time.sleep(0.1)
        pyautogui.mouseUp()
        sagisin()
        print("Congratulations")
    else:
        ("Nope")

This is how I wrote my Python Codes using the pyautogui library. I'm writing a simple bot. In these codes, the coding ends after the first if else block. He sees the photo when I show him and continues, but when he does not see the photo, I say turn back, but after he returns once, it does not continue. I think I've come up with a dysfunctional code. How do i fix this.


问:
show/hide divs based on selecting option
I have a select with some filters, every filter should be connected to a div (in the first moment they are hidden, i think with *ngIf, but im not sure how to integrate the it with my code) with his specific functionality. In my project i have the possibility to select which filter i wanna show.

component.ts:

object with filters:

```<code>filters: Filter[] = [
    {value: 'textSearch', name: 'Denominazione', selected: false},
    {value: 'internalReferent', name: 'Referente interno', selected: false},
    {value: 'supplierSignUpTimestamp', name: 'Data iscrizione', selected: false},
    {value: 'internalReferent', name: 'Merceologia', selected: false},
    {value: 'internalReferent', name: 'Sede operativa', selected: false},
    {value: 'supplierOperationalHQ', name: 'Stato', selected: false},
  ]
</code>```
```<code>constructor(private fb: FormBuilder) {
    this.supplierFilterForm = this.fb.group({

      filter: ['']
    });
  }
</code>```

function for toggle:

```<code>toggleSelected() {
    let filterSelected = this.supplierFilterForm.controls['filter'].value;
    let i = this.filters.findIndex(x => x.name == filterSelected);
    console.log(filterSelected)
    console.log(i)
    if (filterSelected == this.filters[i].name) {
      this.filters[i].selected = !this.filters[i].selected;
    }
  }
</code>```

debugging this function i change in the right way the value of the boolean of each filter, but there is the problem, how can i set an ngIf in my html file with this logic?

component.html

Filter select i have to click on at the start

```<code><div class="col-2 d-flex">
    <mat-form-field>
      <mat-label>{{ 'supplier.showFilters' | translate }}</mat-label>
      <mat-select (selectionChange)="toggleSelected()" formControlName="filter">
        <mat-option *ngFor="let filter of filters; let i = index" [value]="filter.name"
        >
         {{i}} {{filter.name}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </div>
</code>```

Exemple of filter i would like to let appear selecting his own option in the previous select:

```<code><div class="col-2">
    <mat-form-field>
      <mat-label>{{ 'supplier.supplierStatus' | translate }}</mat-label>
      <mat-select formControlName="supplierStatus">
        <mat-option [value]="null">--</mat-option>
        <mat-option *ngFor="let option of selectData.supplierStatus" [value]="option.value">
          {{ option.display | translate }}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </div>
</code>```

at the start of this 'task' i was thinking about declare a global variable instead of a single boolean to each filter but obviously he toggled off/on every filter

p.s. im sorry for my english skills!

Body:
I have a select with some filters, every filter should be connected to a div (in the first moment they are hidden, i think with *ngIf, but im not sure how to integrate the it with my code) with his specific functionality. In my project i have the possibility to select which filter i wanna show.

component.ts:

object with filters:

filters: Filter[] = [
    {value: 'textSearch', name: 'Denominazione', selected: false},
    {value: 'internalReferent', name: 'Referente interno', selected: false},
    {value: 'supplierSignUpTimestamp', name: 'Data iscrizione', selected: false},
    {value: 'internalReferent', name: 'Merceologia', selected: false},
    {value: 'internalReferent', name: 'Sede operativa', selected: false},
    {value: 'supplierOperationalHQ', name: 'Stato', selected: false},
  ]

constructor(private fb: FormBuilder) {
    this.supplierFilterForm = this.fb.group({

      filter: ['']
    });
  }

function for toggle:

toggleSelected() {
    let filterSelected = this.supplierFilterForm.controls['filter'].value;
    let i = this.filters.findIndex(x => x.name == filterSelected);
    console.log(filterSelected)
    console.log(i)
    if (filterSelected == this.filters[i].name) {
      this.filters[i].selected = !this.filters[i].selected;
    }
  }

debugging this function i change in the right way the value of the boolean of each filter, but there is the problem, how can i set an ngIf in my html file with this logic?

component.html

Filter select i have to click on at the start

    <mat-form-field>
      <mat-label>{{ 'supplier.showFilters' | translate }}</mat-label>
      <mat-select (selectionChange)="toggleSelected()" formControlName="filter">
        <mat-option *ngFor="let filter of filters; let i = index" [value]="filter.name"
        >
         {{i}} {{filter.name}}
        </mat-option>
      </mat-select>
    </mat-form-field>

Exemple of filter i would like to let appear selecting his own option in the previous select:

    <mat-form-field>
      <mat-label>{{ 'supplier.supplierStatus' | translate }}</mat-label>
      <mat-select formControlName="supplierStatus">
        <mat-option [value]="null">--</mat-option>
        <mat-option *ngFor="let option of selectData.supplierStatus" [value]="option.value">
          {{ option.display | translate }}
        </mat-option>
      </mat-select>
    </mat-form-field>

at the start of this 'task' i was thinking about declare a global variable instead of a single boolean to each filter but obviously he toggled off/on every filter

p.s. im sorry for my english skills!


问:
Red Pass Filter for Image Processing in C#
I am trying to code a Red Pass filer in C#. I might not be using the correct name for this, but I want to convert all the non-red pixel to black (0,0,0).

So, like how a high pass filter sets all frequencies below a giving setpoint to 0.  I want to set all the non-red pixel to (0,0,0) aka Black.

My problem is that I am using images from a camera, so the red pixels are not (255,0,0) plus because of Light and shades on the object I am taking a picture of some of the red pixels are darker than others. Meaning this [Red Color] (https://i.stack.imgur.com/Hc42q.png) and this Red Color are on the same object in the image.

This is what I have Tried so for:

```<code>public bool IsRed(RGB color)
{
    // The pixel is a shade of red if the red value is greater than the green and blue values
    return color.Red > color.Green && color.Red > color.Blue;
}

public bool IsRed2(RGB color)
{
    // The pixel is a shade of red if the red value is within the range of 128 to 255.
    return color.Red >= 128 && color.Red <= 255;
}

public bool IsRed3(RGB color)
{
    // Convert the RGB values to HSL.
    double hue, saturation, lightness;
    RGBToHSL(color.Red, color.Green, color.Blue, out hue, out saturation, out lightness);

    // The pixel is a shade of red if the hue is within the range of 0 to 30 degrees or 330 to 360 degrees.
    return (hue >= 0 && hue <= 30) || (hue >= 330 && hue <= 360);
}

// Converts the given RGB values to HSL.
private void RGBToHSL(byte red, byte green, byte blue, out double hue, out double saturation, out double lightness)
{
    // Convert the RGB values to the range 0 to 1.
    double r = red / 255.0;
    double g = green / 255.0;
    double b = blue / 255.0;

    // Calculate the maximum and minimum RGB values.
    double max = Math.Max(r, Math.Max(g, b));
    double min = Math.Min(r, Math.Min(g, b));

    // Calculate the lightness.
    lightness = (max + min) / 2;

    // Calculate the saturation.
    if (max == min)
    {
        // The color is a shade of gray.
        hue = 0;
        saturation = 0;
    }
    else
    {
        // The color is not a shade of gray.
        double d = max - min;
        saturation = lightness > 0.5 ? d / (2 - max - min) : d / (max + min);

        // Calculate the hue.
        if (max == r)
        {
            hue = (g - b) / d + (g < b ? 6 : 0);
        }
        else if (max == g)
        {
            hue = (b - r) / d + 2;
        }
        else
        {
            hue = (r - g) / d + 4;
        }

        hue /= 6;
    }
}
</code>```

Update :
This is how I am getting the RGB values from the image:

```<code>  private RGB[,] ImageToRGBByteArray(Bitmap _image, int height, int width)
    {
        Bitmap b = new Bitmap(_image);

        BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);

        /* GetBitsPerPixel just does a switch on the PixelFormat and returns the number */
        BitsPerPixel = GetBitsPerPixel(bData.PixelFormat);

        /*the size of the image in bytes */
        int size = bData.Stride * bData.Height;

        Stride = bData.Stride;
        /*Allocate buffer for image*/
        byte[] data = new byte[size];
        RGB[,] imagematrix = new RGB[height, width];
        int[,] imageData = new int[height, width];
        /*This overload copies data of /size/ into /data/ from location specified (/Scan0/)*/
        Marshal.Copy(bData.Scan0, data, 0, size);
        int i = 0;

        ModifiedHistogram = null;
        ImageData = null;
        ImageRGBData = null;
        Dictionary<RGB, int> modifiedHistogram = new Dictionary<RGB, int>();

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                RGB tempValue = new RGB(data[i], data[i + 1], data[i + 2]);
                imagematrix[y, x] = tempValue;

                imageData[y, x] = (int)((data[i] + data[i + 1] + data[i + 2]) / 3D);

                if (!modifiedHistogram.ContainsKey(tempValue))
                    modifiedHistogram.Add(tempValue, 1);
                else
                    modifiedHistogram[tempValue]++;
                i += BitsPerPixel / 8;
            }
        }

        int maxValue = 0;
        string color = string.Empty;
        foreach (var kvp in modifiedHistogram)
        {
            if (kvp.Value > maxValue)
            {
                maxValue = kvp.Value;
                color = kvp.Key.ColorName;
            }
        }
        ImageData = imageData;
        ImageRGBData = imagematrix;
        ModifiedHistogram = modifiedHistogram;
        return imagematrix;
    }
</code>```

So

```<code>data[i] = Red
data[i+2] = Green
data[i+3] = Blue
</code>```

This is my Color class

```<code>   public class RGB
{
    public  byte Red { get; set; }
    public  byte Green { get; set; }
    public  byte Blue { get; set; }

    public RGB(byte red, byte green, byte blue)
    {
        Red = red;
        Green = green;
        Blue = blue;
        SetColorName();
    }

    public override bool Equals(object obj)
    {
         RGB other = obj as RGB;
        return other != null && other.ColorName == this.ColorName;
    }
}
</code>```

Body:
I am trying to code a Red Pass filer in C#. I might not be using the correct name for this, but I want to convert all the non-red pixel to black (0,0,0).

So, like how a high pass filter sets all frequencies below a giving setpoint to 0.  I want to set all the non-red pixel to (0,0,0) aka Black.

My problem is that I am using images from a camera, so the red pixels are not (255,0,0) plus because of Light and shades on the object I am taking a picture of some of the red pixels are darker than others. Meaning this [Red Color] (https://i.stack.imgur.com/Hc42q.png) and this Red Color are on the same object in the image.

This is what I have Tried so for:

public bool IsRed(RGB color)
{
    // The pixel is a shade of red if the red value is greater than the green and blue values
    return color.Red > color.Green && color.Red > color.Blue;
}

public bool IsRed2(RGB color)
{
    // The pixel is a shade of red if the red value is within the range of 128 to 255.
    return color.Red >= 128 && color.Red <= 255;
}

public bool IsRed3(RGB color)
{
    // Convert the RGB values to HSL.
    double hue, saturation, lightness;
    RGBToHSL(color.Red, color.Green, color.Blue, out hue, out saturation, out lightness);

    // The pixel is a shade of red if the hue is within the range of 0 to 30 degrees or 330 to 360 degrees.
    return (hue >= 0 && hue <= 30) || (hue >= 330 && hue <= 360);
}

// Converts the given RGB values to HSL.
private void RGBToHSL(byte red, byte green, byte blue, out double hue, out double saturation, out double lightness)
{
    // Convert the RGB values to the range 0 to 1.
    double r = red / 255.0;
    double g = green / 255.0;
    double b = blue / 255.0;

    // Calculate the maximum and minimum RGB values.
    double max = Math.Max(r, Math.Max(g, b));
    double min = Math.Min(r, Math.Min(g, b));

    // Calculate the lightness.
    lightness = (max + min) / 2;

    // Calculate the saturation.
    if (max == min)
    {
        // The color is a shade of gray.
        hue = 0;
        saturation = 0;
    }
    else
    {
        // The color is not a shade of gray.
        double d = max - min;
        saturation = lightness > 0.5 ? d / (2 - max - min) : d / (max + min);

        // Calculate the hue.
        if (max == r)
        {
            hue = (g - b) / d + (g < b ? 6 : 0);
        }
        else if (max == g)
        {
            hue = (b - r) / d + 2;
        }
        else
        {
            hue = (r - g) / d + 4;
        }

        hue /= 6;
    }
}

Update :
This is how I am getting the RGB values from the image:

  private RGB[,] ImageToRGBByteArray(Bitmap _image, int height, int width)
    {
        Bitmap b = new Bitmap(_image);

        BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);

        /* GetBitsPerPixel just does a switch on the PixelFormat and returns the number */
        BitsPerPixel = GetBitsPerPixel(bData.PixelFormat);

        /*the size of the image in bytes */
        int size = bData.Stride * bData.Height;

        Stride = bData.Stride;
        /*Allocate buffer for image*/
        byte[] data = new byte[size];
        RGB[,] imagematrix = new RGB[height, width];
        int[,] imageData = new int[height, width];
        /*This overload copies data of /size/ into /data/ from location specified (/Scan0/)*/
        Marshal.Copy(bData.Scan0, data, 0, size);
        int i = 0;

        ModifiedHistogram = null;
        ImageData = null;
        ImageRGBData = null;
        Dictionary<RGB, int> modifiedHistogram = new Dictionary<RGB, int>();

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                RGB tempValue = new RGB(data[i], data[i + 1], data[i + 2]);
                imagematrix[y, x] = tempValue;

                imageData[y, x] = (int)((data[i] + data[i + 1] + data[i + 2]) / 3D);

                if (!modifiedHistogram.ContainsKey(tempValue))
                    modifiedHistogram.Add(tempValue, 1);
                else
                    modifiedHistogram[tempValue]++;
                i += BitsPerPixel / 8;
            }
        }

        int maxValue = 0;
        string color = string.Empty;
        foreach (var kvp in modifiedHistogram)
        {
            if (kvp.Value > maxValue)
            {
                maxValue = kvp.Value;
                color = kvp.Key.ColorName;
            }
        }
        ImageData = imageData;
        ImageRGBData = imagematrix;
        ModifiedHistogram = modifiedHistogram;
        return imagematrix;
    }

So

data[i] = Red
data[i+2] = Green
data[i+3] = Blue

This is my Color class

   public class RGB
{
    public  byte Red { get; set; }
    public  byte Green { get; set; }
    public  byte Blue { get; set; }

    public RGB(byte red, byte green, byte blue)
    {
        Red = red;
        Green = green;
        Blue = blue;
        SetColorName();
    }

    public override bool Equals(object obj)
    {
         RGB other = obj as RGB;
        return other != null && other.ColorName == this.ColorName;
    }
}


问:
Disable @typescript-eslint/naming-convention warning for custom naming convention
Me and my team have a custom naming convention for some of our variables that are causing eslint to generate warnings. Basically, we have around two hundred objects of the same type which we use throughout our app. To keep things organized, we have given each object an identifier with the following naming convention: section_page_objectTitle. This is using a mix of snake_case and camelCase (i.e. objectTitle), so eslint throws an error saying:

Variable name 'section_page_objectTitle' must match one of the following formats: camelCase, PascalCase, UPPER_CASE eslint@typescript-eslint/naming-convention

We have set up this naming convention so that it is easy to identify where the object is used in the app because each part of the id is divided by "_". If we were to switch objectTitle to snake_case to satisfy the eslint rule, then it would be section_page_object_title and we would lose that classification.

I am trying to modify the eslint rule to allow for this naming convention, but the documentation isn't very clear on how to do this.

The list of values that section can be is small, so I was trying to setup a rule to allow for anything that starts with one of the section names followed by an underscore (section_), but I wasn't able to find how to do that.

EDIT: I know that I can just disable that line, but I would prefer not to if possible since we would have to do that for all 200+ objects.


问:
React Router in app served from Google Cloud Storage
I'd like to serve a React app from static file storage (Google Cloud Storage, AWS equivalent is S3).

In the past I've only ever deployed React apps to an NGINX server (or in an NGINX container) where I can configure all requests to point to index.html, regardless of the requested path, so that React Router can handle the routing on the client side.

I'm struggling to understand how this would work in static file storage, by just running npm run build and uploading the built app to Cloud Storage.

Example: To my understanding, if you request <domain>/profile, it will look for a file named "profile" in static file storage and then return the storage provider's 404 page if it doesn't exist. But I want this to be handled by React Router, which means this request still technically returns the index.html page, then the JavaScript on the client side looks at the URL and renders either the profile page component or a soft 404 page component which I can customise from within my React app.


问:
Pyscript: upload txt file make lowercase then download
I am trying to make a simple example of a pyscript/html file that does the following.

Select a txt file

Click convert button. This uploads the file

The contents of the file is made all lowercase

The lowercase text is displayed

Download button to download the lowercase file.

The example below works but is overly complicated.

```<code>    <html>
  <head>
    <title>Make lower case</title>
    <meta charset="iso-8859-1">
    <link rel="icon" type="image/x-icon" href="./favicon.png">
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.4.3.min.js"></script>
    <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.4.3.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@holoviz/panel@0.14.1/dist/panel.min.js"></script>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    <link rel="stylesheet" href="./assets/css/examples.css" />
  </head>
  <body>
   <nav class="navbar" style="background-color: #000000;">
      <div class="app-header">

        <a class="title" href="" style="color: #f0ab3c;">File Reader</a>
      </div>
    </nav>
    <section class="pyscript">
      <div id="simple_app"></div>
      <div id="upload_button"></div>
      <div id="textarea"></div>
      <div id="download"></div>

        <py-config>
          packages = [
            "panel"
            ]

        </py-config>

        <py-script>
          import io
          import panel as pn

          def download_file():
            return io.BytesIO(textarea.value.encode())

          fileInput = pn.widgets.FileInput(accept='.txt')
          uploadButton = pn.widgets.Button(name='Upload', button_type = 'primary')
          textarea = pn.widgets.TextAreaInput(name='File data', width=1000, height=300)
          download = pn.widgets.FileDownload(filename="lowercase.txt", callback=download_file, button_type="primary")

          def process_file(event):
            if fileInput.value is not None:
              textarea.value = fileInput
              textarea.value = fileInput.value.decode().lower()

          pn.Row(fileInput).servable(target='simple_app')
          pn.Row(textarea).servable(target='textarea')
          pn.Row(uploadButton, pn.bind(process_file, uploadButton)).servable(target='upload_button')
          pn.Row(download).servable(target='download')
        </py-script>
    </section>
  </body>
</html>
</code>```

Body:
I am trying to make a simple example of a pyscript/html file that does the following.

Select a txt file

Click convert button. This uploads the file

The contents of the file is made all lowercase

The lowercase text is displayed

Download button to download the lowercase file.

The example below works but is overly complicated.

    <title>Make lower case</title>
    <meta charset="iso-8859-1">
    <link rel="icon" type="image/x-icon" href="./favicon.png">

    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

    <link rel="stylesheet" href="./assets/css/examples.css" />

        File Reader

        <py-config>
          packages = [
            "panel"
            ]

        </py-config>

        <py-script>
          import io
          import panel as pn

          def download_file():
            return io.BytesIO(textarea.value.encode())

          fileInput = pn.widgets.FileInput(accept='.txt')
          uploadButton = pn.widgets.Button(name='Upload', button_type = 'primary')
          textarea = pn.widgets.TextAreaInput(name='File data', width=1000, height=300)
          download = pn.widgets.FileDownload(filename="lowercase.txt", callback=download_file, button_type="primary")

          def process_file(event):
            if fileInput.value is not None:
              textarea.value = fileInput
              textarea.value = fileInput.value.decode().lower()

          pn.Row(fileInput).servable(target='simple_app')
          pn.Row(textarea).servable(target='textarea')
          pn.Row(uploadButton, pn.bind(process_file, uploadButton)).servable(target='upload_button')
          pn.Row(download).servable(target='download')
        </py-script>


问:
Simultaneous Streams With Google Nearby Connections API?
I'm currently working on an app where a hub needs to send a data stream to multiple devices simultaneously. I'm using Google's Nearby Connection API, with the P2P_STAR strategy. I can successfully connect with multiple clients, but the problem comes when I try to send a stream payload to multiple clients.

After just a few seconds after opening the pipe to a second client, the app hangs on the write() command for the second client. I'm using PipedInputStream and PipedOutputStream. I'm assuming that the write command is blocking because nearby connections is not reading from the other end of the pipe. Can I only send one payload at a time, even though I'm connected to multiple clients?

```<code>System.arraycopy(ByteBuffer.allocate(4).putInt(Status.getScroll_position()).array(),
        0,send_bytes,1,4);
send_bytes[0] = -128;
for (RemotePrompter prompter : remotePrompters) {
    prompter.getOutputStream().write(send_bytes);
    prompter.getOutputStream().flush();
}
</code>```

Body:
I'm currently working on an app where a hub needs to send a data stream to multiple devices simultaneously. I'm using Google's Nearby Connection API, with the P2P_STAR strategy. I can successfully connect with multiple clients, but the problem comes when I try to send a stream payload to multiple clients.

After just a few seconds after opening the pipe to a second client, the app hangs on the write() command for the second client. I'm using PipedInputStream and PipedOutputStream. I'm assuming that the write command is blocking because nearby connections is not reading from the other end of the pipe. Can I only send one payload at a time, even though I'm connected to multiple clients?

System.arraycopy(ByteBuffer.allocate(4).putInt(Status.getScroll_position()).array(),
        0,send_bytes,1,4);
send_bytes[0] = -128;
for (RemotePrompter prompter : remotePrompters) {
    prompter.getOutputStream().write(send_bytes);
    prompter.getOutputStream().flush();
}


问:
ANSWERED - how to take the first item from a list cast as a variable and assign a data piece to it
I want to take the first item from the list and make it a variable ad assign it with  a randomly generated number 1-26

using python 3.10

I have gotten the code to be

```<code>def code():
    bank= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
           'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    for i in range(len(bank)):
        var = bank[0].astype()

</code>```

and I am not sure how best to proceed though the answer is probably easy

want it to output something like
a= 4 b=23 c=12
etc.etc

Body:
I want to take the first item from the list and make it a variable ad assign it with  a randomly generated number 1-26

using python 3.10

I have gotten the code to be

def code():
    bank= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
           'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    for i in range(len(bank)):
        var = bank[0].astype()

and I am not sure how best to proceed though the answer is probably easy

want it to output something like
a= 4 b=23 c=12
etc.etc


问:
How do I fix poseDetector code in OpenCV?
My mediapipe version is 0.8.9.1
I have tried redownloading it on a lower version but it doesnt allow me to go past my version.

I am using "PoseModule" code from here: https://www.computervision.zone/lessons/code-files-15/

This is the error i get:

```<code>TypeError: create_bool(): incompatible function arguments. The following argument types are supported:
    1. (arg0: bool) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5
</code>```

Could anyone help me in fixing the code please?

Most answers i saw are regarding "self.mpHands.Hands".
I heard there is something wrong with the init within class poseDetector but I dont know how to rewrite tho code :/

Body:
My mediapipe version is 0.8.9.1
I have tried redownloading it on a lower version but it doesnt allow me to go past my version.

I am using "PoseModule" code from here: https://www.computervision.zone/lessons/code-files-15/

This is the error i get:

TypeError: create_bool(): incompatible function arguments. The following argument types are supported:
    1. (arg0: bool) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5

Could anyone help me in fixing the code please?

Most answers i saw are regarding "self.mpHands.Hands".
I heard there is something wrong with the init within class poseDetector but I dont know how to rewrite tho code :/


问:
How to Host Jupyter Notebook as a website from a terminal only Linux
Given a Terminal Only Mode of Ubuntu, is it possible to host Jupiter notebook and the GUI can be accessed over Http(/s) from another device ?

If not, then, the Jupyter notebook running on the GUI platform of a Linux box , How can the access be made public so that the Jupyter NoteBook on a Linux Box can be used as a Private Cloud service ?


问:
avro4s for scala 3 issue when serializing with schemaV1 but deserializing with schemaV2
I've written sample code to try avro4s for scala 3. I am trying to simulate a schema change, in this case a Pizza's schema evolved to include a vegan:Option[Boolean]:

package examples

import java.io.File
import com.sksamuel.avro4s.{AvroInputStream, AvroOutputStream, AvroSchema}

@main def createAvroFile() =

  val pepperoni = PizzaV1("pepperoni", Seq(Ingredient("pepperoni", 12, 4.4), Ingredient("onions", 1, 0.4)), 598)
  val hawaiian  = PizzaV1("hawaiian", Seq(Ingredient("ham", 1.5, 5.6), Ingredient("pineapple", 5.2, 0.2)), 391)

  val os = AvroOutputStream.binary[PizzaV1].to(new File("/tmp/pizzas.avro")).build()
  os.write(Seq(pepperoni, hawaiian))
  os.flush()
  os.close()

  val pizzaV1Schema = AvroSchema[PizzaV1]
  val in            = AvroInputStream.binary[PizzaV2].from(new File("/tmp/pizzas.avro")).build(pizzaV1Schema)
  println(in.iterator.toList.mkString("\n"))
  in.close()

case class Ingredient(name: String, sugar: Double, fat: Double)
case class PizzaV1(name: String, ingredients: Seq[Ingredient], calories: Int)
case class PizzaV2(name: String, ingredients: Seq[Ingredient], calories: Int, vegan: Option[Boolean])

```
<p>When I run it, it fails:</p>
```Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.avro.Schema$Field.schema()" because "field" is null
    at com.sksamuel.avro4s.decoders.SchemaFieldDecoder.<init>(records.scala:64)
    at com.sksamuel.avro4s.decoders.RecordDecoder.$anonfun$1(records.scala:19)
    at scala.collection.ArrayOps$.map$extension(ArrayOps.scala:932)
    at scala.IArray$package$IArray$.map(IArray.scala:179)
    at com.sksamuel.avro4s.decoders.RecordDecoder.decode(records.scala:20)
    at com.sksamuel.avro4s.AvroBinaryInputStream.<init>(AvroBinaryInputStream.scala:31)
    at com.sksamuel.avro4s.AvroInputStreamBuilderWithSource.build(AvroInputStream.scala:69)
    at examples.CreateAvroFile$package$.createAvroFile(CreateAvroFile.scala:17)
    at examples.createAvroFile.main(CreateAvroFile.scala:6)
```

I debugged it and it seems it tries to find "vegan" field somewhere (in the V1 schema?) but gets a null.

Is this a bug or am I doing something wrong?

Body:
I've written sample code to try avro4s for scala 3. I am trying to simulate a schema change, in this case a Pizza's schema evolved to include a vegan:Option[Boolean]:

package examples

import java.io.File
import com.sksamuel.avro4s.{AvroInputStream, AvroOutputStream, AvroSchema}

@main def createAvroFile() =

  val pepperoni = PizzaV1("pepperoni", Seq(Ingredient("pepperoni", 12, 4.4), Ingredient("onions", 1, 0.4)), 598)
  val hawaiian  = PizzaV1("hawaiian", Seq(Ingredient("ham", 1.5, 5.6), Ingredient("pineapple", 5.2, 0.2)), 391)

  val os = AvroOutputStream.binary[PizzaV1].to(new File("/tmp/pizzas.avro")).build()
  os.write(Seq(pepperoni, hawaiian))
  os.flush()
  os.close()

  val pizzaV1Schema = AvroSchema[PizzaV1]
  val in            = AvroInputStream.binary[PizzaV2].from(new File("/tmp/pizzas.avro")).build(pizzaV1Schema)
  println(in.iterator.toList.mkString("\n"))
  in.close()

case class Ingredient(name: String, sugar: Double, fat: Double)
case class PizzaV1(name: String, ingredients: Seq[Ingredient], calories: Int)
case class PizzaV2(name: String, ingredients: Seq[Ingredient], calories: Int, vegan: Option[Boolean])

When I run it, it fails:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.avro.Schema$Field.schema()" because "field" is null
    at com.sksamuel.avro4s.decoders.SchemaFieldDecoder.<init>(records.scala:64)
    at com.sksamuel.avro4s.decoders.RecordDecoder.$anonfun$1(records.scala:19)
    at scala.collection.ArrayOps$.map$extension(ArrayOps.scala:932)
    at scala.IArray$package$IArray$.map(IArray.scala:179)
    at com.sksamuel.avro4s.decoders.RecordDecoder.decode(records.scala:20)
    at com.sksamuel.avro4s.AvroBinaryInputStream.<init>(AvroBinaryInputStream.scala:31)
    at com.sksamuel.avro4s.AvroInputStreamBuilderWithSource.build(AvroInputStream.scala:69)
    at examples.CreateAvroFile$package$.createAvroFile(CreateAvroFile.scala:17)
    at examples.createAvroFile.main(CreateAvroFile.scala:6)

I debugged it and it seems it tries to find "vegan" field somewhere (in the V1 schema?) but gets a null.

Is this a bug or am I doing something wrong?


问:
search_dropdown with local database flutter
DropdownSearch(
mode: Mode.MENU,
showSelectedItem: true,
items: ["Brazil", "Italia (Disabled)", "Tunisia", 'Canada'],
label: "Menu mode",
hint: "country in menu mode",
popupItemDisabled: (String s) => s.startsWith('I'),
onChanged: print,
selectedItem: "Brazil"),</p>