问:
Bone creation script with bpy on blender
I got big data arrays of bone's, which contains

Bone Name > Parent Bone Name > Children Bone Name

Each of those bones has special coords such as:

```<code>Quaternion(RotationsToParent[i]) # RotationsToParent / Quaternion
Vector(TranslationToParent[i]) # TranslationToParent / Vector3

Quaternion(RotationsToOrigin[i]) # RotationsToOrigin / Quaternion
Vector(TranslationToOrigin[i]) # TranslationToOrigin / Vector3

Quaternion(RotationsToLocal[i]) # RotationsToLocal / Quaternion
Vector(TranslationToLocal[i]) # TranslationToLocal / Vector3
</code>```

The datas from unknown extension file, but the datas enough to create something big!, only hint here is their variable names, and the BPY documentation doesnt explains much about bones, in documentation creation of Head/Tail for bones is declared, but no information i found about how to create/set Quaternion & Vector for bones,

Here's my script (works anormal) to place bone in right place

```<code>
        import bpy
        from bpy.props import *
        from mathutils import Vector, Quaternion

        armature = bpy.data.armatures.new("Armature")
        rig = bpy.data.objects.new("Armature", armature)

        bpy.context.collection.objects.link(rig)
        bpy.context.view_layer.objects.active = rig
        bpy.ops.object.mode_set(mode = 'EDIT')

        BoneNames = [...]
        ChildBoneNames = [...]
        ParentBoneNames = [...]

        # Each bone contains those values
        RotationsToParent = [...] # Quaternion
        TranslationToParent = [...] # Vector3
        RotationsToOrigin = [...] # Quaternion
        TranslationToOrigin = [...] # Vector3
        RotationsToLocal = [...] # Quaternion
        TranslationToLocal = [...] # Vector3

        for i, BONE in enumerate(BoneNames):
            BoneArrIndex = i
            BoneName = BONE

            CurrentRTP = Quaternion(RotationsToParent[BoneArrIndex]) # RotationsToParent / Quaternion
            CurrentTTP = Vector(TranslationToParent[BoneArrIndex]) # TranslationToParent / Vector3

            CurrentRTO = Quaternion(RotationsToOrigin[BoneArrIndex]) # RotationsToOrigin / Quaternion
            CurrentTTO = Vector(TranslationToOrigin[BoneArrIndex]) # TranslationToOrigin / Vector3

            CurrentRTL = Quaternion(RotationsToLocal[BoneArrIndex]) # RotationsToLocal / Quaternion
            CurrentTTL = Vector(TranslationToLocal[BoneArrIndex]) # TranslationToLocal / Vector3

            # create new bone
            current_bone = armature.edit_bones.new(BoneName)
            print("@",BoneName)

            # first bone in chain
            if i == 0:
                print(i)
                # create bone at armature origin and set its length
                current_bone.head = [0, 0, 0]
                length = list(TranslationToParent[ BoneArrIndex + 1 ])[0]
                current_bone.tail = [0, 0, length]

                quat_armature_space = CurrentRTO
                current_bone.transform(quat_armature_space.to_matrix(), scale=True, roll=True)

                # set position
                current_bone.translate(CurrentTTO)

                # save bone, its tail position (next bone will be moved to it) and quaternion rotation
                parent_bone = current_bone
                parent_bone_tail = current_bone.tail
                parent_bone_quat_armature_space = quat_armature_space

            # last bone in chain
            elif i == (len(BoneNames) - 1):

                # create bone at armature origin and set its length
                current_bone.head =  [0, 0, 0]
                current_bone.tail = [0, 0, 1]

                # rotate bone, around origin?
                # like matrices, quaternions can be multiplied to accumulate rotational values
                transform_quat = parent_bone_quat_armature_space @ CurrentRTO
                current_bone.transform(transform_quat.to_matrix(),  scale=True, roll=True)

                # set position, around origin?
                current_bone.translate(parent_bone_tail)

                ## connect
                current_bone.parent = parent_bone
                current_bone.use_connect = True

            else:
                # create bone at armature origin and set its length
                current_bone.head = [0, 0, 0]
                length = list(TranslationToParent[ BoneArrIndex + 1 ])[0]
                current_bone.tail = [0, 0, length]

                # rotate bone, around origin?
                # like matrices, quaternions can be multiplied to accumulate rotational values
                transform_quat = parent_bone_quat_armature_space @ CurrentRTO

                current_bone.transform(transform_quat.to_matrix(),  scale=True, roll=True)

                # set position, around origin?
                current_bone.translate(parent_bone_tail)

                # connect

                current_bone.parent = parent_bone
                current_bone.use_connect = True

                # save bone, its tail position (next bone will be moved to it) and quaternion rotation
                parent_bone = current_bone
                parent_bone_tail = current_bone.tail
                parent_bone_quat_armature_space = transform_quat
</code>```

So, i tried to switch every head/tail variables with other translation variables i declared on top, but didnt work, the results are anormal check the result:
Anormal Bones

And yet i havent figured out whats wrong with my bone placer script, what could be wrong here?

Edit1:
After many hours of searching i've updated the bone creator script, and the results enlightened me a bit, probably all those Quaternion/Vector values should be applied to bone from different axis, heres new result that i got from new bone placer script, all bones placed in same direction but on different lenghts, only RotationToOrigin & TranslateToOrigin coords applied but how do i apply other unused quats/vectors values?

Here are unused cord values in the image below :
(RotationToLocale & TranslationToLocale & RotationToParent),

however each of quat/vector coords probably has to be applied to each bone which is confused me.

Body:
I got big data arrays of bone's, which contains

Bone Name > Parent Bone Name > Children Bone Name

Each of those bones has special coords such as:

Quaternion(RotationsToParent[i]) # RotationsToParent / Quaternion
Vector(TranslationToParent[i]) # TranslationToParent / Vector3

Quaternion(RotationsToOrigin[i]) # RotationsToOrigin / Quaternion
Vector(TranslationToOrigin[i]) # TranslationToOrigin / Vector3

Quaternion(RotationsToLocal[i]) # RotationsToLocal / Quaternion
Vector(TranslationToLocal[i]) # TranslationToLocal / Vector3

The datas from unknown extension file, but the datas enough to create something big!, only hint here is their variable names, and the BPY documentation doesnt explains much about bones, in documentation creation of Head/Tail for bones is declared, but no information i found about how to create/set Quaternion & Vector for bones,

Here's my script (works anormal) to place bone in right place

        import bpy
        from bpy.props import *
        from mathutils import Vector, Quaternion

        armature = bpy.data.armatures.new("Armature")
        rig = bpy.data.objects.new("Armature", armature)

        bpy.context.collection.objects.link(rig)
        bpy.context.view_layer.objects.active = rig
        bpy.ops.object.mode_set(mode = 'EDIT')

        BoneNames = [...]
        ChildBoneNames = [...]
        ParentBoneNames = [...]

        # Each bone contains those values
        RotationsToParent = [...] # Quaternion
        TranslationToParent = [...] # Vector3
        RotationsToOrigin = [...] # Quaternion
        TranslationToOrigin = [...] # Vector3
        RotationsToLocal = [...] # Quaternion
        TranslationToLocal = [...] # Vector3

        for i, BONE in enumerate(BoneNames):
            BoneArrIndex = i
            BoneName = BONE

            CurrentRTP = Quaternion(RotationsToParent[BoneArrIndex]) # RotationsToParent / Quaternion
            CurrentTTP = Vector(TranslationToParent[BoneArrIndex]) # TranslationToParent / Vector3

            CurrentRTO = Quaternion(RotationsToOrigin[BoneArrIndex]) # RotationsToOrigin / Quaternion
            CurrentTTO = Vector(TranslationToOrigin[BoneArrIndex]) # TranslationToOrigin / Vector3

            CurrentRTL = Quaternion(RotationsToLocal[BoneArrIndex]) # RotationsToLocal / Quaternion
            CurrentTTL = Vector(TranslationToLocal[BoneArrIndex]) # TranslationToLocal / Vector3

            # create new bone
            current_bone = armature.edit_bones.new(BoneName)
            print("@",BoneName)

            # first bone in chain
            if i == 0:
                print(i)
                # create bone at armature origin and set its length
                current_bone.head = [0, 0, 0]
                length = list(TranslationToParent[ BoneArrIndex + 1 ])[0]
                current_bone.tail = [0, 0, length]

                quat_armature_space = CurrentRTO
                current_bone.transform(quat_armature_space.to_matrix(), scale=True, roll=True)

                # set position
                current_bone.translate(CurrentTTO)

                # save bone, its tail position (next bone will be moved to it) and quaternion rotation
                parent_bone = current_bone
                parent_bone_tail = current_bone.tail
                parent_bone_quat_armature_space = quat_armature_space

            # last bone in chain
            elif i == (len(BoneNames) - 1):

                # create bone at armature origin and set its length
                current_bone.head =  [0, 0, 0]
                current_bone.tail = [0, 0, 1]

                # rotate bone, around origin?
                # like matrices, quaternions can be multiplied to accumulate rotational values
                transform_quat = parent_bone_quat_armature_space @ CurrentRTO
                current_bone.transform(transform_quat.to_matrix(),  scale=True, roll=True)

                # set position, around origin?
                current_bone.translate(parent_bone_tail)

                ## connect
                current_bone.parent = parent_bone
                current_bone.use_connect = True

            else:
                # create bone at armature origin and set its length
                current_bone.head = [0, 0, 0]
                length = list(TranslationToParent[ BoneArrIndex + 1 ])[0]
                current_bone.tail = [0, 0, length]

                # rotate bone, around origin?
                # like matrices, quaternions can be multiplied to accumulate rotational values
                transform_quat = parent_bone_quat_armature_space @ CurrentRTO

                current_bone.transform(transform_quat.to_matrix(),  scale=True, roll=True)

                # set position, around origin?
                current_bone.translate(parent_bone_tail)

                # connect

                current_bone.parent = parent_bone
                current_bone.use_connect = True

                # save bone, its tail position (next bone will be moved to it) and quaternion rotation
                parent_bone = current_bone
                parent_bone_tail = current_bone.tail
                parent_bone_quat_armature_space = transform_quat

So, i tried to switch every head/tail variables with other translation variables i declared on top, but didnt work, the results are anormal check the result:
Anormal Bones

And yet i havent figured out whats wrong with my bone placer script, what could be wrong here?

Edit1:
After many hours of searching i've updated the bone creator script, and the results enlightened me a bit, probably all those Quaternion/Vector values should be applied to bone from different axis, heres new result that i got from new bone placer script, all bones placed in same direction but on different lenghts, only RotationToOrigin & TranslateToOrigin coords applied but how do i apply other unused quats/vectors values?

Here are unused cord values in the image below :
(RotationToLocale & TranslationToLocale & RotationToParent),

however each of quat/vector coords probably has to be applied to each bone which is confused me.


来源: stackexchange

问:
"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
I'm writing an ASP.NET Web API project with 3 controllers

HomeController

LaureatesController

PrizesController

When I try to call GET method GetPrizes() from Postman or the web, I'm getting this error

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'

My DB and PrizesController:

```<code>private ApplicationDbContext db = new ApplicationDbContext();

public IEnumerable<object> GetPrizes()
{
    var prizes = db.Prizes.ToList()
                   .Select(prize => new
                                    {
                                        prize.PrizeID,
                                        prize.Category,
                                        prize.Year,
                                        Laureates = prize.Laureates.Select(Laureate => new
            {
                Laureate.LaureateID,
                Laureate.Surname,
                Laureate.FirstName,
                Laureate.Gender,
                Laureate.Born,
                Laureate.BornCountry,
                Laureate.Died
            })
        });

    return db.Prizes;
}
</code>```

I have added in the webApiconfig.cs file:

```<code>    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

}
</code>```

and my Global.ASAX contains:

```<code>public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}
</code>```

Do you have any Idea on what is wrong here and I'm getting that error?

ContentLicense: CC BY-SA 4.0

Body:
I'm writing an ASP.NET Web API project with 3 controllers

HomeController

LaureatesController

PrizesController

When I try to call GET method GetPrizes() from Postman or the web, I'm getting this error

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'

My DB and PrizesController:

private ApplicationDbContext db = new ApplicationDbContext();

public IEnumerable<object> GetPrizes()
{
    var prizes = db.Prizes.ToList()
                   .Select(prize => new
                                    {
                                        prize.PrizeID,
                                        prize.Category,
                                        prize.Year,
                                        Laureates = prize.Laureates.Select(Laureate => new
            {
                Laureate.LaureateID,
                Laureate.Surname,
                Laureate.FirstName,
                Laureate.Gender,
                Laureate.Born,
                Laureate.BornCountry,
                Laureate.Died
            })
        });

    return db.Prizes;
}

I have added in the webApiconfig.cs file:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);
        json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

}

and my Global.ASAX contains:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

Do you have any Idea on what is wrong here and I'm getting that error?


问:
react-hot-loader and webpack
I am new in stackoverflow and I am junior in React
I have a question
I installed webpack V5 and then I try to install react-hot-loader.
This is webpack.config.js

`

```<code>const path = require ("path");
const webpack = require ("webpack");

module.exports = {
    module :{
        entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist')
  },
        rules: [
            {
              test: /\.(png|jpg|gif)$/i,
             dependency: { not: ['url'] },
              use: [
                {
                  loader: 'url-loader',
                  options: {
                    limit: 8192,
                  },
                },
              ],
            },
        ],
    },
    resolve :{extensions : ["*" , ".js" , ".jsx"]},
    devServer: {
        // contentBase
        static : {
          directory : path.join(__dirname, "public/")
        },
        port: 3000,
        // publicPath
        devMiddleware:{
           publicPath: "https://localhost:3000/dist/",
        }

      },
};
</code>```

`

I want to install React-hot-loader but it does`nt install and I have error

Title: react-hot-loader and webpack

Body:
I am new in stackoverflow and I am junior in React
I have a question
I installed webpack V5 and then I try to install react-hot-loader.
This is webpack.config.js

`

const path = require ("path");
const webpack = require ("webpack");

module.exports = {
    module :{
        entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist')
  },
        rules: [
            {
              test: /\.(png|jpg|gif)$/i,
             dependency: { not: ['url'] },
              use: [
                {
                  loader: 'url-loader',
                  options: {
                    limit: 8192,
                  },
                },
              ],
            },
        ],
    },
    resolve :{extensions : ["*" , ".js" , ".jsx"]},
    devServer: {
        // contentBase
        static : {
          directory : path.join(__dirname, "public/")
        },
        port: 3000,
        // publicPath
        devMiddleware:{
           publicPath: "https://localhost:3000/dist/",
        }

      },
};

`

I want to install React-hot-loader but it does`nt install and I have error


问:
Problem with $_GET / $_POST when passing variable from Javascript popup to parent window to use in PHP MySQL query
The flow chart of my end goal is essential:

Click the "add" button in the parent window ---> Popup window showing a list to choose an item from.

The user clicks a row from the list & submits that item as an index/ID.

Popup / Child window closes and the variable is passed back to the parent window.

Parent window can use that variable in PHP to query the item ID in MySQL and add the data into a new row.

The parent window is also always open during this process, so I used window.onunload of the child window to trigger the SQL query.

First of all, I understand from similar posts that JS is client-side while PHP is server-side, so it's possible to get a PHP variable in JS using <? php echo ?>, but not the other way around, at least directly.

I used form.submit() to send the data back to the parent window via POST method through a form. However, isset($_POST['itemID'] turns up false, as the predefined value I set for $full_id is still 1.

Child Window

```<code>var txt = window.opener.document.getElementById("txtName");

txt.value = "1chosen";
var submit = window.opener.document.getElementById("submit");
submit.value = str;

document.getElementById('myID').value = str;

var form = document.getElementById('myForm');

form.submit();

window.close();

}

window.onunload = function (e) {

    opener.somefunction(); //or
    }
;

    </script>

</body>

<form action="/combine-quote.php" id="myForm" method="get">
  <input id="myID" name="itemID"><br><br>
  <input type="submit" value="Submit">
</form>
</code>```

Parent Window

```<code>window.somefunction = function(){

var choice = document.getElementById('txtName').value;
var id = document.getElementById('submit').value;

if (choice =="1chosen"){

    if (id != ""){

        <?php
            $xd=1;
            $full_id = "1";
            if (isset($_GET['itemID'])){
            $full_id=$_GET['itemID'];
            }

        ?>

            alert(<?php echo $full_id; ?>);

    }
</code>```

Body:
The flow chart of my end goal is essential:

Click the "add" button in the parent window ---> Popup window showing a list to choose an item from.

The user clicks a row from the list & submits that item as an index/ID.

Popup / Child window closes and the variable is passed back to the parent window.

Parent window can use that variable in PHP to query the item ID in MySQL and add the data into a new row.

The parent window is also always open during this process, so I used window.onunload of the child window to trigger the SQL query.

First of all, I understand from similar posts that JS is client-side while PHP is server-side, so it's possible to get a PHP variable in JS using <? php echo ?>, but not the other way around, at least directly.

I used form.submit() to send the data back to the parent window via POST method through a form. However, isset($_POST['itemID'] turns up false, as the predefined value I set for $full_id is still 1.

Child Window

var txt = window.opener.document.getElementById("txtName");

txt.value = "1chosen";
var submit = window.opener.document.getElementById("submit");
submit.value = str;

document.getElementById('myID').value = str;

var form = document.getElementById('myForm');

form.submit();

window.close();

}

window.onunload = function (e) {

    opener.somefunction(); //or
    }
;

    </script>

<form action="/combine-quote.php" id="myForm" method="get">
  <input id="myID" name="itemID">

  <input type="submit" value="Submit">
</form>

Parent Window

window.somefunction = function(){

var choice = document.getElementById('txtName').value;
var id = document.getElementById('submit').value;

if (choice =="1chosen"){

    if (id != ""){

        <?php
            $xd=1;
            $full_id = "1";
            if (isset($_GET['itemID'])){
            $full_id=$_GET['itemID'];
            }

        ?>

            alert(<?php echo $full_id; ?>);

    }


问:
Icomoon colored icons are not visible in webpage
I'm using Angular 12 and for icons using https://i.icomoon.io/.
Already made many icons with one colour, but now I need icon which should be multicolour.

Like this icon.

When I adding class to a div or span, I can see "icon-coffee" class is set on the element, but not adding :before and :after pseudo elements to it.

It should be like "icon-anguyn" which is adding :before pseudo element to the div.


问:
Filtering jsonb array in postgreSql
I have a table with a jsonb field of the following type:

```<code>[
  {
    "Id": "98f2a810-8f29-4707-9098-759eec83b2d5",
    "Data": {
      "value": 6
    },
    "Created": "2022-12-15T10:04:04.8100461Z"
  },
  {
    "Id": "950df931-abfd-460f-916f-14b00d3e1593",
    "Data": {
      "value": "hello world"
    },
    "Created": "2022-12-15T10:04:04.9270694Z"
  }
]
</code>```

Now I can filter records only by decomposing the jsonb array into separate lines and join them:

```<code>LEFT JOIN LATERAL jsonb_array_elements(""attributes"") as x(attribute) ON TRUE
</code>```

and filter:
WHERE x.attribute ->> 'Id' ILIKE '98f2a810-8f29-4707-9098-759eec83b2d5' and cast(x.attribute -> 'Data' ->> 'value' as numeric) = 6

But if I need filter by two attributes with AND operator it doesn't work(the results exclude each other).

How I can filter jsonb array without separate and join elements?

Title: Filtering jsonb array in postgreSql

Body:
I have a table with a jsonb field of the following type:

[
  {
    "Id": "98f2a810-8f29-4707-9098-759eec83b2d5",
    "Data": {
      "value": 6
    },
    "Created": "2022-12-15T10:04:04.8100461Z"
  },
  {
    "Id": "950df931-abfd-460f-916f-14b00d3e1593",
    "Data": {
      "value": "hello world"
    },
    "Created": "2022-12-15T10:04:04.9270694Z"
  }
]

Now I can filter records only by decomposing the jsonb array into separate lines and join them:

LEFT JOIN LATERAL jsonb_array_elements(""attributes"") as x(attribute) ON TRUE

and filter:
WHERE x.attribute ->> 'Id' ILIKE '98f2a810-8f29-4707-9098-759eec83b2d5' and cast(x.attribute -> 'Data' ->> 'value' as numeric) = 6

But if I need filter by two attributes with AND operator it doesn't work(the results exclude each other).

How I can filter jsonb array without separate and join elements?


问:
How to set flex parameter in div so that it automatically grows while adding elements otherwise removes extra spaces
I have a new div in my page where I am adding different toggle sliders, Currently I have only one slider and if I need to add more sliders my div should adjust based on that without having extra spaces in right. So currently what's happening is my div has extra spaces in right which I am not able to remove those

html

```<code><div class="mycontainer">
 <div class="toggle1">
  <mat-slide-toggle> My Toggle1</mat-slide-toggle>
</div>
</div>
</code>```

css

```<code>.mycontainer{

display: flex;
width: 300px;
height: 30px;
flex: 1 1 70px;
border: 1px solid;
}
</code>```

Body:
I have a new div in my page where I am adding different toggle sliders, Currently I have only one slider and if I need to add more sliders my div should adjust based on that without having extra spaces in right. So currently what's happening is my div has extra spaces in right which I am not able to remove those

html

  <mat-slide-toggle> My Toggle1</mat-slide-toggle>

css

.mycontainer{

display: flex;
width: 300px;
height: 30px;
flex: 1 1 70px;
border: 1px solid;
}


问:
Don't know how to reload window and have different output -Modifying DOM
I have a simple HTML document of three pictures like this-

Now I need to modify the code so that the deleting of images
starts from the beginning, reload the page, and the result like-

Here is code:

```<code>export default () => {

    const button = document.querySelector('#b1');

    const listener = e => {
        const images = document.getElementsByTagName('img');

//        for(let i = 0; i <= images.length; i++) {
        for(let i = images.length - 1; i >= 0; i--) {
            const image = images[i];
            if(image.alt) {
                let text = document.createTextNode(image.alt);
                image.parentNode.replaceChild(text, image);
            }
        }

        const style = `
            color: yellow;
            border: 2px solid yellow;
        `;

        button.setAttribute('style', style);
        button.style.backgroundColor = 'red';

        button.disabled = true;
        button.textContent = 'Disabled';
    };

//    button.onclick = listener;
    button.addEventListener('click', listener);
};
</code>```

Does anybody know what to do?

I tried

```<code> for(let i = images.length - 1; i >= 0; **i=i-2**) {
            const image = images[i];
            if(image.alt) {
                let text = document.createTextNode(image.alt);
                image.parentNode.replaceChild(text, image);
            }
        }
</code>```

And I get the desired look(like in the resulting picture), but I need to reload the page and get the output as shown in the resulting picture.

Body:
I have a simple HTML document of three pictures like this-

Now I need to modify the code so that the deleting of images
starts from the beginning, reload the page, and the result like-

Here is code:

export default () => {

    const button = document.querySelector('#b1');

    const listener = e => {
        const images = document.getElementsByTagName('img');

//        for(let i = 0; i <= images.length; i++) {
        for(let i = images.length - 1; i >= 0; i--) {
            const image = images[i];
            if(image.alt) {
                let text = document.createTextNode(image.alt);
                image.parentNode.replaceChild(text, image);
            }
        }

        const style = `
            color: yellow;
            border: 2px solid yellow;
        `;

        button.setAttribute('style', style);
        button.style.backgroundColor = 'red';

        button.disabled = true;
        button.textContent = 'Disabled';
    };

//    button.onclick = listener;
    button.addEventListener('click', listener);
};

Does anybody know what to do?

I tried

 for(let i = images.length - 1; i >= 0; **i=i-2**) {
            const image = images[i];
            if(image.alt) {
                let text = document.createTextNode(image.alt);
                image.parentNode.replaceChild(text, image);
            }
        }

And I get the desired look(like in the resulting picture), but I need to reload the page and get the output as shown in the resulting picture.


问:
CORS issue with s3 when trying to download images
After weeks of trying to find a solution, I'm giving up. Everything I tried didn't work so far

I uploaded images to an s3 bucket and defined them as public.

When my users try to download them through a JavaScript function on my front-end (using a:href), I get an error because of CORS policies. I tried to use canvas, but I also have a CORS error.

The images are properly displayed in the  tags tho, and when users right-click > save image, it works fine, the issue is when trying to download them automatically.

```<code>I tried this CORS policy:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "Access-Control-Allow-Origin"
        ]
    }
]
</code>```

and probably 5 others, but it did not changed anything.

The result I'm trying to achieve:

Upload image on s3 on my end

Users can click on a button to download it directly on the front end

Any help would be super useful

Body:
After weeks of trying to find a solution, I'm giving up. Everything I tried didn't work so far

I uploaded images to an s3 bucket and defined them as public.

When my users try to download them through a JavaScript function on my front-end (using a:href), I get an error because of CORS policies. I tried to use canvas, but I also have a CORS error.

The images are properly displayed in the  tags tho, and when users right-click > save image, it works fine, the issue is when trying to download them automatically.

I tried this CORS policy:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "Access-Control-Allow-Origin"
        ]
    }
]

and probably 5 others, but it did not changed anything.

The result I'm trying to achieve:

Upload image on s3 on my end

Users can click on a button to download it directly on the front end

Any help would be super useful


问:
Call Alpine js from javascript
I have Alpinajs and Splidejs on page. I want to change aplinajs variable from splide event

document.addEventListener('alpine:init', () => {
  Alpine.data('titles', () => ({
    slidetitle_1: true,
    toggle(n) {
      this["slidetitle_" + n] = true
    }
  }))
})
```
<p>then when in slider event</p>
```var splide = new Splide('.splide').mount();
splide.on( 'active', function (t) {
  // not working
  Alpine.data('titles', () => {
    this["slidetitle_" + 1] = true;
  });
  // not working
  Alpine.$data.titles.toggle(1);
});
```

but none of this working

Title: Call Alpine js from javascript

Body:
I have Alpinajs and Splidejs on page. I want to change aplinajs variable from splide event

document.addEventListener('alpine:init', () => {
  Alpine.data('titles', () => ({
    slidetitle_1: true,
    toggle(n) {
      this["slidetitle_" + n] = true
    }
  }))
})

then when in slider event

var splide = new Splide('.splide').mount();
splide.on( 'active', function (t) {
  // not working
  Alpine.data('titles', () => {
    this["slidetitle_" + 1] = true;
  });
  // not working
  Alpine.$data.titles.toggle(1);
});

but none of this working


问:
udev rule is not applying to all device nodes
Below is my udev rule, it's not getting applied to all device nodes in /dev/dri, i have verified all are having SUBSYSTEM as drm by using 'udevadm info ' command.

```<code>SUBSYSTEM=="drm", GROUP="video", SECLABEL{smack}="*"
</code>```

Below are the permissions of the device nodes

```<code># ls -al /dev/dri
total 0
drwxr-xr-x  3 root root       200 Nov 17 12:29 .
drwxr-xr-x 12 root root      3060 Nov 17 12:29 ..
drwxr-xr-x  2 root root        80 Nov 17 12:29 by-path
crw-rw----  1 root root  226,   0 Jan  1  1970 card0
crw-------  1 root root  226,   1 Jan  1  1970 card1
crw-rw----  1 root video 226,   2 Nov 17 12:29 card2
crw-------  1 root root  226,  64 Jan  1  1970 controlD64
crw-------  1 root root  226,  65 Jan  1  1970 controlD65
crw-rw----  1 root root  226, 128 Jan  1  1970 renderD128
crw-rw----  1 root video 226, 129 Nov 17 12:29 renderD12
</code>```

Body:
Below is my udev rule, it's not getting applied to all device nodes in /dev/dri, i have verified all are having SUBSYSTEM as drm by using 'udevadm info ' command.

SUBSYSTEM=="drm", GROUP="video", SECLABEL{smack}="*"

Below are the permissions of the device nodes

# ls -al /dev/dri
total 0
drwxr-xr-x  3 root root       200 Nov 17 12:29 .
drwxr-xr-x 12 root root      3060 Nov 17 12:29 ..
drwxr-xr-x  2 root root        80 Nov 17 12:29 by-path
crw-rw----  1 root root  226,   0 Jan  1  1970 card0
crw-------  1 root root  226,   1 Jan  1  1970 card1
crw-rw----  1 root video 226,   2 Nov 17 12:29 card2
crw-------  1 root root  226,  64 Jan  1  1970 controlD64
crw-------  1 root root  226,  65 Jan  1  1970 controlD65
crw-rw----  1 root root  226, 128 Jan  1  1970 renderD128
crw-rw----  1 root video 226, 129 Nov 17 12:29 renderD12


问:
Neighbors is not defined
```<code>ac_scores = []

for k in neighbors:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    scores = accuracy_score(y_test, y_pred)
    ac_scores.append(scores)

# changing to misclassification error
MSE = [1 - x for x in ac_scores]

# determining best k
optimal_k = neighbors[MSE.index(min(MSE))]
print("The optimal number of neighbors is %d" % optimal_k)
</code>```

I was trying to find the optimal K neighbors for the model building. error is occuring in the name of 'name: neighbors not defined' in the statement for k in neighbors.

Title: Neighbors is not defined

Body:
ac_scores = []

for k in neighbors:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    scores = accuracy_score(y_test, y_pred)
    ac_scores.append(scores)

# changing to misclassification error
MSE = [1 - x for x in ac_scores]

# determining best k
optimal_k = neighbors[MSE.index(min(MSE))]
print("The optimal number of neighbors is %d" % optimal_k)

I was trying to find the optimal K neighbors for the model building. error is occuring in the name of 'name: neighbors not defined' in the statement for k in neighbors.


问:
Uncaught TypeError: myCheckbox is null, but after I change something in the file and save it, it works normally! (VSCode)
I have a little but annoying problem.
I tried to write this project to improve my knowledge with React.
I have a checkbox that have to change the theme color into dark mode, but if I refresh the page from the browser (Mozilla Firefox) the checkbox is not recognized, but if I change something in the JSX file (anything, doesn't matter if regards the checkbox or not) and save it, is perfectly recognized and it works!
Can you help me, please?

I leave here the JSX component, I used a console.log to find that that was the problem.

```<code>import React from "react";
import '../App.css'

const body = document.querySelector('body')
const logo = document.getElementById('logo')
const myCheckbox = document.getElementById('myButton')

if(myCheckbox){
    console.log('yes')
} else {
    console.log('no')
}

function changeMode(){
    if (myCheckbox.checked === true){
        body.style.backgroundColor = '#111111'
        body.style.transition = '1s'
        logo.style.filter = 'invert(100%)'
    } else {
        body.style.backgroundColor = '#ADFFF1'
        body.style.transition = '1s'
        logo.style.filter = 'invert(0%)'
    }
}

function ButtonMode(){
    return(
        <div id="theme-button">
            <span>
            Dark Theme<input type='checkbox' id="myButton" onClick={changeMode} ></input>
            </span>
        </div>
    )
}

export default ButtonMode;
</code>```

Here is App.js file:

```<code>import './App.css';
import Navbar from './components/navbar';
import ButtonMode from './components/colorTheme';

function App() {
  return (
    <div className="App">
      <Navbar/>
      <ButtonMode/>
    </div>
  );
}

export default App;
</code>```

Body:
I have a little but annoying problem.
I tried to write this project to improve my knowledge with React.
I have a checkbox that have to change the theme color into dark mode, but if I refresh the page from the browser (Mozilla Firefox) the checkbox is not recognized, but if I change something in the JSX file (anything, doesn't matter if regards the checkbox or not) and save it, is perfectly recognized and it works!
Can you help me, please?

I leave here the JSX component, I used a console.log to find that that was the problem.

import React from "react";
import '../App.css'

const body = document.querySelector('body')
const logo = document.getElementById('logo')
const myCheckbox = document.getElementById('myButton')

if(myCheckbox){
    console.log('yes')
} else {
    console.log('no')
}

function changeMode(){
    if (myCheckbox.checked === true){
        body.style.backgroundColor = '#111111'
        body.style.transition = '1s'
        logo.style.filter = 'invert(100%)'
    } else {
        body.style.backgroundColor = '#ADFFF1'
        body.style.transition = '1s'
        logo.style.filter = 'invert(0%)'
    }
}

function ButtonMode(){
    return(

            Dark Theme<input type='checkbox' id="myButton" onClick={changeMode} ></input>

    )
}

export default ButtonMode;

Here is App.js file:

import './App.css';
import Navbar from './components/navbar';
import ButtonMode from './components/colorTheme';

function App() {
  return (

      <Navbar/>
      <ButtonMode/>

  );
}

export default App;


问:
OpenXR Runtime set to Steam is causing performance problems on Oculus Link
I am developing VR game on steam using Unity 2021 and OpenXR. When OpenXR Runtime is set to Oculus like on screenshot, everything is ok, performance in game is perfect.

But when I set OpenXR Runtime on SteamVR the game is laggy as hell. I tested this on other VR games and problem does not occur, only in my game. Do you guys know what can be wrong?


问:
.NET6 high CPU usage after Server transfer
I think that I have a pretty strange problem. I'm running a pretty old Server with Debian 8.11. On this Server there are running 3 docker container: frontend (typescript), backend API (.NET) and Collector that collects data from an MQTT Server (.NET). Nothing was strange there. I had an avarage of 3% CPU Core (6 Core System) usage according to my monitoring System

Now I transfered all those Docker container to a new Server with Debian 11.5. In the beginning, everything worked fine wiht a low CPU usage but after around 4 hours the backend API had a CPU usage of around 52% (4 Core System)

My first idea now is that this somehow has to do with the operating system, since nothing else has adjusted, but I'm a bit undecided at the moment.

I also tried to see with the command strace, what the process is doing. But when I run it now strace -p 1113, it looks like the process is idle, because it returns only a single line and not a huge output like the other processes -> futex(0x5649747a83c4, FUTEX_WAIT_PRIVATE, 0, NULL).

Is there another way to debug, what the Process is actually doing?
Or does anybody else had a similar problem?


问:
Problem with initialization prop custom type in Vue
I use custom prop types in Vue components, like:

import {Employee} from '@models/Employee'
...
props: {
  employee: {
    required: true,
    type: Employee,
  },
},
```
<p>Overall it works as expected, and custom props are there for a while. But suddenly, I ran into <code>Reference Error</code>:</p>
<blockquote>
<p>Uncaught ReferenceError: Cannot access 'Employee' before initialization</p>
</blockquote>
<p>Line that causes error:</p>
<blockquote>
<p>// EXPORTS</p>
<p>__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ Employee_Employee; });</p>
</blockquote>
<p><s>It's weird because it worked before, and props with other custom types are working.</s> That may be related to the update of some npm packages (or node itself?). I need help finding the anchor point.</p>
<p>Update: other classes also stopped working, like: <code>type: UserAvatar</code> etc.</p>
<p><strong>Employee.js</strong>
Employee class looks something like that.</p>
<pre class="lang-js prettyprint-override"><code>const fields = [...]

export class Employee extends Model {

    constructor(data = {}) {
      super(fields, data)
      ...
    }
}
</code>```

Body:
I use custom prop types in Vue components, like:

import {Employee} from '@models/Employee'
...
props: {
  employee: {
    required: true,
    type: Employee,
  },
},

Overall it works as expected, and custom props are there for a while. But suddenly, I ran into Reference Error:

Uncaught ReferenceError: Cannot access 'Employee' before initialization

Line that causes error:

// EXPORTS

__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ Employee_Employee; });

<s>It's weird because it worked before, and props with other custom types are working.</s> That may be related to the update of some npm packages (or node itself?). I need help finding the anchor point.

Update: other classes also stopped working, like: type: UserAvatar etc.

Employee.js
Employee class looks something like that.

const fields = [...]

export class Employee extends Model {

    constructor(data = {}) {
      super(fields, data)
      ...
    }
}


问:
How can we have Multicharacter line separator (line delimiter) in Spark
How can we have multicharacter line separator (line delimiter) in Spark?

Spark 3 allows multicharacter column delimiter but for line separator it only allows one character.

e.g. how to have this: @@@\n as line separator?


问:
How to keep div always in viewport (without overflowing outside) in javascript
how can i make javasript keep a div in the viewport without overflowing?

ex:
User resizes the screen (lets say go to landscape mode without refresh) and now the div is getting cut off due to the viewport getting bigger.

The div is like a tooltip. basically popper without the extra features.

I have tried setting a timeout every 500 ms, to attach the div to the side of the page (which doesnt work at its like a dropdown, needs to be under the button)

ive been using this function to get the out of viewport

```<code>var isOutOfViewport = function (elem) {

    // Get element's bounding
    var bounding = elem.getBoundingClientRect();

    // Check if it's out of the viewport on each side
    var out = {};
    out.top = bounding.top < 0;
    out.left = bounding.left < 0;
    out.bottom = bounding.bottom > (window.innerHeight || document.documentElement.clientHeight);
    out.right = bounding.right > (window.innerWidth || document.documentElement.clientWidth);
    out.any = out.top || out.left || out.bottom || out.right;

    return out;

};var logViewport = function () {
    var isOut = isOutOfViewport(document.querySelector('#in-viewport'));
    if (isOut.any) {
        console.log('Not in the viewport! =(');
    } else {
        console.log('In the viewport! =)');
    }
};
window.addEventListener('scroll', logViewport, false);
window.addEventListener('resize', logViewport, false);
</code>```

My end goal:

Make the div always on screen, without overflowing (like popper js)

Body:
how can i make javasript keep a div in the viewport without overflowing?

ex:
User resizes the screen (lets say go to landscape mode without refresh) and now the div is getting cut off due to the viewport getting bigger.

The div is like a tooltip. basically popper without the extra features.

I have tried setting a timeout every 500 ms, to attach the div to the side of the page (which doesnt work at its like a dropdown, needs to be under the button)

ive been using this function to get the out of viewport

var isOutOfViewport = function (elem) {

    // Get element's bounding
    var bounding = elem.getBoundingClientRect();

    // Check if it's out of the viewport on each side
    var out = {};
    out.top = bounding.top < 0;
    out.left = bounding.left < 0;
    out.bottom = bounding.bottom > (window.innerHeight || document.documentElement.clientHeight);
    out.right = bounding.right > (window.innerWidth || document.documentElement.clientWidth);
    out.any = out.top || out.left || out.bottom || out.right;

    return out;

};var logViewport = function () {
    var isOut = isOutOfViewport(document.querySelector('#in-viewport'));
    if (isOut.any) {
        console.log('Not in the viewport! =(');
    } else {
        console.log('In the viewport! =)');
    }
};
window.addEventListener('scroll', logViewport, false);
window.addEventListener('resize', logViewport, false);

My end goal:

Make the div always on screen, without overflowing (like popper js)


问:
Configuring Windows 10 Update Rings in Intune/MEM using Powershell
I'm working on Configuring Windows 10 Update Rings in Intune/MEM.I'm able to do that from MEM but Is there any way that i can update using Powershell.?

Thanks

Couldn't find any documentation yet.


问:
Block redirects and page reloads within the same tab
Scenario:

I enter a web page

Page shows desired content for a few seconds

It reloads and opens another web page (within the same tab, no new tab is fired - usually an ad)

I press the back button and the desired page opens again

How can i block this behaviour having only the desired page displayed, without reloading.

What actually causes this? I have some extensions for blocking redirects, but they work only on new tab redirects.
I am also a software engineer so a technical explanation would help me, if possible.


问:
Stripe Webhook signature verification error
I'm developing a webhook in my firebase to receveive updates for completed checkouts, the only problem is that it doesn't works, Stripe keeps getting back a 500 response with an empty error body, here is the code:

//index.js

```<code>const webHooks = express();

PaymentController.prototype.bindWebHookEndpoints(webHooks);
exports.webhook = functions.region(REGION).https.onRequest(webHooks);
</code>```

//PaymentController.js

```<code>bindWebHookEndpoints(app) {
    /**
     * Endpoint to receive payments status updates.
     */
    app.post("/payments", express.raw({type: "application/json"}), (request, response) => {
      const signature = request.headers["stripe-signature"];
      console.log({rawBody: request.rawBody});
      return PaymentSystemRemoteService.prototype.postWebHookValidationAsync(request.rawBody.toString(), signature).then((event)=>{
        functions.logger.log({event: event});
        switch (event.type) {
          case "checkout.session.async_payment_failed":

            // Then define and call a function to handle the event checkout.session.async_payment_failed
            break;
          case "checkout.session.async_payment_succeeded":

            // Then define and call a function to handle the event checkout.session.async_payment_succeeded
            break;
          case "checkout.session.completed":

            // Then define and call a function to handle the event checkout.session.completed
            break;

          default:
            console.log(`Unhandled event type ${event.type}`);
        }
        response.status(200).send({});
      }).catch((err)=>{
        functions.logger.log({err: err});
        response.status(500).send(err);
      });
    });
  }
</code>```

//PaymentSystemRemoteService.js

```<code>const endpointSecret = "whsec_..."; (Got from the stripe dev portal)

  postWebHookValidationAsync(body, signature) {
    return new Promise((res, rej)=>{
      return stripe.webhooks.constructEvent(body, signature, endpointSecret).then((event)=>{
        return res(event);
      }).catch((err)=>{
        return rej(err);
      });
    });
  }
</code>```

Any hints? thanks!

Body:
I'm developing a webhook in my firebase to receveive updates for completed checkouts, the only problem is that it doesn't works, Stripe keeps getting back a 500 response with an empty error body, here is the code:

//index.js

const webHooks = express();

PaymentController.prototype.bindWebHookEndpoints(webHooks);
exports.webhook = functions.region(REGION).https.onRequest(webHooks);

//PaymentController.js

bindWebHookEndpoints(app) {
    /**
     * Endpoint to receive payments status updates.
     */
    app.post("/payments", express.raw({type: "application/json"}), (request, response) => {
      const signature = request.headers["stripe-signature"];
      console.log({rawBody: request.rawBody});
      return PaymentSystemRemoteService.prototype.postWebHookValidationAsync(request.rawBody.toString(), signature).then((event)=>{
        functions.logger.log({event: event});
        switch (event.type) {
          case "checkout.session.async_payment_failed":

            // Then define and call a function to handle the event checkout.session.async_payment_failed
            break;
          case "checkout.session.async_payment_succeeded":

            // Then define and call a function to handle the event checkout.session.async_payment_succeeded
            break;
          case "checkout.session.completed":

            // Then define and call a function to handle the event checkout.session.completed
            break;

          default:
            console.log(`Unhandled event type ${event.type}`);
        }
        response.status(200).send({});
      }).catch((err)=>{
        functions.logger.log({err: err});
        response.status(500).send(err);
      });
    });
  }

//PaymentSystemRemoteService.js

const endpointSecret = "whsec_..."; (Got from the stripe dev portal)

  postWebHookValidationAsync(body, signature) {
    return new Promise((res, rej)=>{
      return stripe.webhooks.constructEvent(body, signature, endpointSecret).then((event)=>{
        return res(event);
      }).catch((err)=>{
        return rej(err);
      });
    });
  }

Any hints? thanks!


问:
Need help in solving Remote - SSH problem
Hello guys I am trying to do Remote SSH for quite some time and unable to make it work .

The problem :

Trying to connect to Aws Codecatalyst Dev environment Linux(remote ssh) to my local windows machine and it is in an endless loop of " Setting up SSH Host aws -exampleID".

I had tried it with my remote ubuntu aws workspace and it works flawlessly (ubuntu remote workspace to Aws codecatalyst Dev Environment) so it seems like some issue with my local machine .

Things I have tried:

When comparing the logs of failed vs successful I have noted that the remote.SSH.useLocalServer was true in my success log. So tried to add this to the settings.json but during run time it automatically changes from true to false .

Also tried clean uninstall and install couple of times (remove appData and ssh config files)

I have added an image of log of the failed Remote SSH .

Would appreciate if Remote SSH users can take a look into the logs and give their insights .

log of Remote SSH


问:
How to delete route53 Alias record with boto3 python
Hello I am trying to delete an Alias DNS records through boto3 python but getting issue.

Here is my code

```<code>route53.change_resource_record_sets(
    HostedZoneId='393EFADF12',
    ChangeBatch={
        'Changes': [
            {
                'Action': 'DELETE',
                'ResourceRecordSet': {
                    'Name': 'mytestrd.mydomain.com',
                    'Region': 'us-west-1',
                    'Type': 'A',
                    'SetIdentifier': 'Simple',
                    'AliasTarget': {
                        'HostedZoneId': '393EFADF12',
                        'DNSName': 'mystack.dev-96436750.us-west-1.elb.amazonaws.com.',
                        'EvaluateTargetHealth': False
                    }
                }
            }]
})
</code>```

Here is the error that is appear

{
"message": "An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: [Tried to delete resource record set [name='mytestrd.mydomain.com.', type='A', set-identifier='simple'] but it was not found]"
}

Would you please help to fix this issue.

Body:
Hello I am trying to delete an Alias DNS records through boto3 python but getting issue.

Here is my code

route53.change_resource_record_sets(
    HostedZoneId='393EFADF12',
    ChangeBatch={
        'Changes': [
            {
                'Action': 'DELETE',
                'ResourceRecordSet': {
                    'Name': 'mytestrd.mydomain.com',
                    'Region': 'us-west-1',
                    'Type': 'A',
                    'SetIdentifier': 'Simple',
                    'AliasTarget': {
                        'HostedZoneId': '393EFADF12',
                        'DNSName': 'mystack.dev-96436750.us-west-1.elb.amazonaws.com.',
                        'EvaluateTargetHealth': False
                    }
                }
            }]
})

Here is the error that is appear

{
"message": "An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation: [Tried to delete resource record set [name='mytestrd.mydomain.com.', type='A', set-identifier='simple'] but it was not found]"
}

Would you please help to fix this issue.


问:
Avoid pandas FutureWarning object-dtype columns with all-bool values when possible values are bool and NaN
I have ~1 million pandas dataframes containing 0-10,000 rows and 160 columns. In a dataframe 5-10 columns may have values [False, True, np.nan] and are 'object' or 'bool' dtype. Some 'object' dtype columns contain only True or False. I handle all these columns as if they could contain [False, True, np.nan], so no df.loc[df['col']] but df.loc[df['col'] == True], etc.

When I do a concat on a collection of these frames, occasionally I get In a future version, object-dtype columns with all-bool values will not be included in reductions with bool_only=True. Explicitly cast to bool dtype instead.

Both concats below trigger the warning because df2 has a bool-only column with dtype object:

```<code>df1 = pd.DataFrame({'foo': np.zeros((2, ), dtype='bool')}, index=[0,1])
df2 = pd.DataFrame({'foo': np.ones((2, ), dtype='bool').astype('object')}, index=[2,3])
df3 = pd.DataFrame({'foo': np.array([np.nan, np.nan])}, index=[6,7])

df_ = pd.concat([df1, df2])
df_ = pd.concat([df2, df3])
</code>```

I have two questions:

Is df = df.infer_objects() the appropriate way to handle this, or would it be better to convert the columns to categorical? Two of my object columns are image thumbnails, but I assume the amount of data in a column has no impact on speed.

Why do I get this warning when concatenating?
In the pandas release notes for 1.5.0 the change is described as Deprecated treating all-bool object-dtype columns as bool-like in DataFrame.any() and DataFrame.all() with bool_only=True, explicitly cast to bool instead (GH46188). How does concat use any()/all()?

Pandas 1.5.2, python 3.8.15

Slightly related Bool and missing values in pandas

Body:
I have ~1 million pandas dataframes containing 0-10,000 rows and 160 columns. In a dataframe 5-10 columns may have values [False, True, np.nan] and are 'object' or 'bool' dtype. Some 'object' dtype columns contain only True or False. I handle all these columns as if they could contain [False, True, np.nan], so no df.loc[df['col']] but df.loc[df['col'] == True], etc.

When I do a concat on a collection of these frames, occasionally I get In a future version, object-dtype columns with all-bool values will not be included in reductions with bool_only=True. Explicitly cast to bool dtype instead.

Both concats below trigger the warning because df2 has a bool-only column with dtype object:

df1 = pd.DataFrame({'foo': np.zeros((2, ), dtype='bool')}, index=[0,1])
df2 = pd.DataFrame({'foo': np.ones((2, ), dtype='bool').astype('object')}, index=[2,3])
df3 = pd.DataFrame({'foo': np.array([np.nan, np.nan])}, index=[6,7])

df_ = pd.concat([df1, df2])
df_ = pd.concat([df2, df3])

I have two questions:

Is df = df.infer_objects() the appropriate way to handle this, or would it be better to convert the columns to categorical? Two of my object columns are image thumbnails, but I assume the amount of data in a column has no impact on speed.

Why do I get this warning when concatenating?
In the pandas release notes for 1.5.0 the change is described as Deprecated treating all-bool object-dtype columns as bool-like in DataFrame.any() and DataFrame.all() with bool_only=True, explicitly cast to bool instead (GH46188). How does concat use any()/all()?

Pandas 1.5.2, python 3.8.15

Slightly related Bool and missing values in pandas


问:
Can cell values be saved in different columns every time I refresh the sheet?
I need to save stock levels of different items in consecutive columns every week when I manually refresh the worksheet.

This will allow me to build a data base for each item and better manage my stock levels.

I have tried many VBA codes and formula in the worksheet itself.

The closest I came was to store a cell's previous value in the same column over and over, but I obviously requrie this to be saved in differernt columns rather than just one. See below code used.

```<code>Dim xRg As Range
Dim xChangeRg As Range
Dim xDependRg As Range
Dim xDic As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Long
    Dim xCell As Range
    Dim xDCell As Range
    Dim xHeader As String
    Dim xCommText As String
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    xHeader = "Previous value :"
    x = xDic.Keys
    For I = 0 To UBound(xDic.Keys)
        Set xCell = Range(xDic.Keys(I))
        Set xDCell = Cells(xCell.Row, 7)
        xDCell.Value = ""
        xDCell.Value = xDic.Items(I)
    Next
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim I, J As Long
    Dim xRgArea As Range
    On Error GoTo Label1
    If Target.Count > 1 Then Exit Sub
    Application.EnableEvents = False
    Set xDependRg = Target.Dependents
    If xDependRg Is Nothing Then GoTo Label1
    If Not xDependRg Is Nothing Then
        Set xDependRg = Intersect(xDependRg, Range("C:C"))
    End If
Label1:
    Set xRg = Intersect(Target, Range("C:C"))
    If (Not xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = Union(xRg, xDependRg)
    ElseIf (xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = xDependRg
    ElseIf (Not xRg Is Nothing) And (xDependRg Is Nothing) Then
        Set xChangeRg = xRg
    Else
        Application.EnableEvents = True
        Exit Sub
    End If
    xDic.RemoveAll
    For I = 1 To xChangeRg.Areas.Count
        Set xRgArea = xChangeRg.Areas(I)
        For J = 1 To xRgArea.Count
            xDic.Add xRgArea(J).Address, xRgArea(J).Formula
        Next
    Next
    Set xChangeRg = Nothing
    Set xRg = Nothing
    Set xDependRg = Nothing
    Application.EnableEvents = True
End Sub
</code>```

Body:
I need to save stock levels of different items in consecutive columns every week when I manually refresh the worksheet.

This will allow me to build a data base for each item and better manage my stock levels.

I have tried many VBA codes and formula in the worksheet itself.

The closest I came was to store a cell's previous value in the same column over and over, but I obviously requrie this to be saved in differernt columns rather than just one. See below code used.

Dim xRg As Range
Dim xChangeRg As Range
Dim xDependRg As Range
Dim xDic As New Dictionary
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim I As Long
    Dim xCell As Range
    Dim xDCell As Range
    Dim xHeader As String
    Dim xCommText As String
    On Error Resume Next
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    xHeader = "Previous value :"
    x = xDic.Keys
    For I = 0 To UBound(xDic.Keys)
        Set xCell = Range(xDic.Keys(I))
        Set xDCell = Cells(xCell.Row, 7)
        xDCell.Value = ""
        xDCell.Value = xDic.Items(I)
    Next
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim I, J As Long
    Dim xRgArea As Range
    On Error GoTo Label1
    If Target.Count > 1 Then Exit Sub
    Application.EnableEvents = False
    Set xDependRg = Target.Dependents
    If xDependRg Is Nothing Then GoTo Label1
    If Not xDependRg Is Nothing Then
        Set xDependRg = Intersect(xDependRg, Range("C:C"))
    End If
Label1:
    Set xRg = Intersect(Target, Range("C:C"))
    If (Not xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = Union(xRg, xDependRg)
    ElseIf (xRg Is Nothing) And (Not xDependRg Is Nothing) Then
        Set xChangeRg = xDependRg
    ElseIf (Not xRg Is Nothing) And (xDependRg Is Nothing) Then
        Set xChangeRg = xRg
    Else
        Application.EnableEvents = True
        Exit Sub
    End If
    xDic.RemoveAll
    For I = 1 To xChangeRg.Areas.Count
        Set xRgArea = xChangeRg.Areas(I)
        For J = 1 To xRgArea.Count
            xDic.Add xRgArea(J).Address, xRgArea(J).Formula
        Next
    Next
    Set xChangeRg = Nothing
    Set xRg = Nothing
    Set xDependRg = Nothing
    Application.EnableEvents = True
End Sub


问:
Draw circles in an interval of radial coordinate in polar projection in python
I'm trying to do plot of circles in polar projection. I'm doing it with the following lines of code:

```<code>for i in range(len(xv)):
    circle = plt.Circle((xv[i], yv[i]), radion[i],  transform=ax.transData._b, color='r', fill=False)
    ax.add_artist(circle)
</code>```

where xv[i], yv[i] are the cartesian coordinates of the center of each circle, radion[i] its center. I've seen in internet that the part 'transform=ax.transData._b' has to be written in order to do the polar projection properly. The output I get is the following image, which is great, but there's a lot of empty space and I would like to remove if changing the range of the radial coordinate.

Output:

However, if I try to change the range of the radial coordinate  writting the following lines above the previous ones:

```<code>ax.set_thetamin(115)
ax.set_thetamax(240)

ax.set_rmin(1000)
ax.set_rmax(1850)
</code>```

the circles are gone. The output now is the following:

I guess this is because of the 'transform=...' part. How can I fix this?

Thanks.

Body:
I'm trying to do plot of circles in polar projection. I'm doing it with the following lines of code:

for i in range(len(xv)):
    circle = plt.Circle((xv[i], yv[i]), radion[i],  transform=ax.transData._b, color='r', fill=False)
    ax.add_artist(circle)

where xv[i], yv[i] are the cartesian coordinates of the center of each circle, radion[i] its center. I've seen in internet that the part 'transform=ax.transData._b' has to be written in order to do the polar projection properly. The output I get is the following image, which is great, but there's a lot of empty space and I would like to remove if changing the range of the radial coordinate.

Output:

However, if I try to change the range of the radial coordinate  writting the following lines above the previous ones:

ax.set_thetamin(115)
ax.set_thetamax(240)

ax.set_rmin(1000)
ax.set_rmax(1850)

the circles are gone. The output now is the following:

I guess this is because of the 'transform=...' part. How can I fix this?

Thanks.


问:
Serve react app project locally over https after build?
In create-react-app, you can run your project over HTTPS locally by setting the HTTPS environment variable to true:

On Linux, or Mac (Bash)

```<code>HTTPS=true npm start
</code>```

On Windows (cmd.exe)

```<code>set HTTPS=true && npm start
</code>```

This works great in development mode,

but after building your project with

```<code>npm run build
</code>```

create-react-app prints this in the console:

and if you run, as it's saying:

```<code>npx serve -s ./build
</code>```

It serves the project on HTTP.

Now, how to serve the project after build on HTTPS instead? Locally on my computer, not after deploying it on the cloud.

Body:
In create-react-app, you can run your project over HTTPS locally by setting the HTTPS environment variable to true:

On Linux, or Mac (Bash)

HTTPS=true npm start

On Windows (cmd.exe)

set HTTPS=true && npm start

This works great in development mode,

but after building your project with

npm run build

create-react-app prints this in the console:

and if you run, as it's saying:

npx serve -s ./build

It serves the project on HTTP.

Now, how to serve the project after build on HTTPS instead? Locally on my computer, not after deploying it on the cloud.


问:
Python List Comprehension if statement how to minimise the number of function calls
I am trying to use list comprehension and the code currently looks like this:

lst = [f(id) for id in df["id"] if f(id) != None]

In my case f(x) takes a while to compute, and if i'm not mistaken this code results in f(id) being computed twice.

I'm wondering if there's a way to use list comprehension but only call the function once?


问:
Getting bad indentation of a mapping entry when adding properties to API Gateway v1 REST API parameters in serverless.yml
I want to JSON object details in the serverless.yml function's parameters. Something like this:

```<code>functions:
  alert:
    handler: alert.main
    description: "Alert Function"
    events:
      - http:
          path: /alert
          method: get
          cors: true
          request:
            parameters:
              querystrings:
                name: true
                email: false
                  properties:
                    enabled: true
                    address: false
                    subject: false
                    body: false
                    isHtml: false
</code>```

But it is not working

I tried the above template but it gives error:
bad indentation of a mapping entry in "serverless.yml".And it then points to "enabled: true" for the possible cause

enter image description here

Can I know what is the correct way of adding  object properties to the query parameter?

Body:
I want to JSON object details in the serverless.yml function's parameters. Something like this:

functions:
  alert:
    handler: alert.main
    description: "Alert Function"
    events:
      - http:
          path: /alert
          method: get
          cors: true
          request:
            parameters:
              querystrings:
                name: true
                email: false
                  properties:
                    enabled: true
                    address: false
                    subject: false
                    body: false
                    isHtml: false

But it is not working

I tried the above template but it gives error:
bad indentation of a mapping entry in "serverless.yml".And it then points to "enabled: true" for the possible cause

enter image description here

Can I know what is the correct way of adding  object properties to the query parameter?


问:
How can the x-axis size of the tile be adjusted in the react-leaflet?
I want to use CRS4326 in react-leaflet.
But there is a big problem. This is because the coordinates cannot be set properly.
Not only that, but also the images of the map do not appear continuously.
When checking the image, it is expected that the desired image will be obtained if each tile is doubled on the x-axis.
But I have no idea how to do it.

```<code>               <MapContainer
                center={[0, 0]}
                zoom={2}
                scrollWheelZoom={true}
                zoomControl={false}
                style={{ width: "100%", height: "100%" }}
                minZoom={1}
                maxZoom={5}
                doubleClickZoom={false}
                crs={CRS.EPSG4326}
                >
                   <TileLayer
                        attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                </MapContainer>
</code>```

The corresponding points are [-90,-180], [0,0], and [90,180], respectively.

Body:
I want to use CRS4326 in react-leaflet.
But there is a big problem. This is because the coordinates cannot be set properly.
Not only that, but also the images of the map do not appear continuously.
When checking the image, it is expected that the desired image will be obtained if each tile is doubled on the x-axis.
But I have no idea how to do it.

               <MapContainer
                center={[0, 0]}
                zoom={2}
                scrollWheelZoom={true}
                zoomControl={false}
                style={{ width: "100%", height: "100%" }}
                minZoom={1}
                maxZoom={5}
                doubleClickZoom={false}
                crs={CRS.EPSG4326}
                >
                   <TileLayer
                        attribution='© OpenStreetMap contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                </MapContainer>

The corresponding points are [-90,-180], [0,0], and [90,180], respectively.


问:
WPF TreeView: No vertical scrollbar when VirtualizingStackPanel.IsVirtualizing="False"
I am working on a WPF Application containing a TreeView. Since I disabled the Virtualization using

```<code>VirtualizingStackPanel.IsVirtualizing="False"
</code>```

the vertical scrollbar is not displayed any more. Even if I set a MaxHeight to the TreeView (to avoid that the outer container will give unlimited space to the tree), no scrollbar will be displayed after expanding the items in the way, that the content will not fit any longer into the available vertical space.

Until I disabled the Virtualization, the scrollbar was shown when needed according to the set

```<code>ScrollViewer.VerticalScrollBarVisibility="Auto"
</code>```

Can anyone help me, please?

Body:
I am working on a WPF Application containing a TreeView. Since I disabled the Virtualization using

VirtualizingStackPanel.IsVirtualizing="False"

the vertical scrollbar is not displayed any more. Even if I set a MaxHeight to the TreeView (to avoid that the outer container will give unlimited space to the tree), no scrollbar will be displayed after expanding the items in the way, that the content will not fit any longer into the available vertical space.

Until I disabled the Virtualization, the scrollbar was shown when needed according to the set

ScrollViewer.VerticalScrollBarVisibility="Auto"

Can anyone help me, please?


问:
React composite components cause linting error in mdxjs
I am writing some documentation in .mdx (mdxjs) using Storybook js for a React composite component.

When I import the component into the mdx file and try to reference the composite child the linter ("eslint-plugin-mdx": "^2.0.5") complains it is undefined - but the output in Storybook does work as expected.

```<code>### CompositeComponent

Some copy about the component.

<Canvas isExpanded={true}>
  <>
    <GlobalStyle />
    <CompositeComponent>
      <CompositeComponent.Child>item</CompositeComponent.Child>
      <CompositeComponent.Child>item</CompositeComponent.Child>
    </CompositeComponent>
  </>
</Canvas>
</code>```

Obviously I can turn off the rule for the this file but I would ideally like it to work or at least understand why it does not.

Body:
I am writing some documentation in .mdx (mdxjs) using Storybook js for a React composite component.

When I import the component into the mdx file and try to reference the composite child the linter ("eslint-plugin-mdx": "^2.0.5") complains it is undefined - but the output in Storybook does work as expected.

### CompositeComponent

Some copy about the component.

<Canvas isExpanded={true}>
  <>
    <GlobalStyle />
    <CompositeComponent>
      <CompositeComponent.Child>item</CompositeComponent.Child>
      <CompositeComponent.Child>item</CompositeComponent.Child>
    </CompositeComponent>
  </>
</Canvas>

Obviously I can turn off the rule for the this file but I would ideally like it to work or at least understand why it does not.


问:
HLS Streaming not working on React Libraries
I was setting up Raspberry Pi 4 to stream video to connected device. So, I used picamera2 for capturing and streaming the video on network. Internally Picamera2 uses ffmpeg to form m3u8 files for hls streaming. Along with picamera2, I used http.server to host static hls files.

I tested out the hls streaming using the following html code:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>Your title</title>

    <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
    <script src="https://unpkg.com/video.js/dist/video.js"></script>
    <script
      src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
  </head>
  <body>
    <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls
      preload="auto"
      data-setup='{}'>
      <source src="http://192.168.1.8:8000/live/stream.m3u8"
        type="application/x-mpegURL">
    </video>

    <script>
var player = videojs('my_video_1');
player.play();
</script>

  </body>
</html>
</code>```

It ran fine. Started streaming video onto other devices.

But I am not able to do the same using react frontend. I am using ReactPlayer in the following code. Tested out with online hls streaming link, it worked out well. But it is not streaming the following RPI stream on the browser. I have also checked out video.js, react-has-player and ReactPlayer worked best on online hls stream and multiple browser.

```<code>import * as React from 'react';
import { useContext } from "react";
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardContent from '@mui/material/CardContent';
import Avatar from '@mui/material/Avatar';
import { red } from '@mui/material/colors';
import VideoCameraBackIcon from '@mui/icons-material/VideoCameraBack';
import ReactPlayer from 'react-player/lazy'
import { Typography } from '@mui/material';
// import { UserContext } from "./context/UserContext";

export default function VideoCard({ alerter }) {
    var url = "http://192.168.1.8:8000/live/stream.m3u8"
    return (
        <Card sx={{ height: '820px' }} variant="outlined">
            <CardHeader
                avatar={
                    <Avatar sx={{ bgcolor: red[500] }} >
                        <VideoCameraBackIcon />
                    </Avatar>
                }
                title={<Typography component="div" variant="h6">
                    Video Stream
                </Typography>}
                subheader="from Camera"
            />
            <CardContent>
                <div >
                    <ReactPlayer
                        playing
                        url={url}
                        controls={true}
                        width="100%"
                        height="100%" />
                </div>
            </CardContent>
        </Card>
    );
}
</code>```

In this react ui, it keeps on loading and then Please suggest the solution to make react code work!

I have tried multiple libraries related to hls in react and now asking for help. I think I may be doing silly mistake and that's what I am expecting as a solution to this problem.

Body:
I was setting up Raspberry Pi 4 to stream video to connected device. So, I used picamera2 for capturing and streaming the video on network. Internally Picamera2 uses ffmpeg to form m3u8 files for hls streaming. Along with picamera2, I used http.server to host static hls files.

I tested out the hls streaming using the following html code:

<!DOCTYPE html>

    <meta charset=utf-8 />
    <title>Your title</title>

    <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">

    <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls
      preload="auto"
      data-setup='{}'>
      <source src="http://192.168.1.8:8000/live/stream.m3u8"
        type="application/x-mpegURL">
    </video>

It ran fine. Started streaming video onto other devices.

But I am not able to do the same using react frontend. I am using ReactPlayer in the following code. Tested out with online hls streaming link, it worked out well. But it is not streaming the following RPI stream on the browser. I have also checked out video.js, react-has-player and ReactPlayer worked best on online hls stream and multiple browser.

import * as React from 'react';
import { useContext } from "react";
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardContent from '@mui/material/CardContent';
import Avatar from '@mui/material/Avatar';
import { red } from '@mui/material/colors';
import VideoCameraBackIcon from '@mui/icons-material/VideoCameraBack';
import ReactPlayer from 'react-player/lazy'
import { Typography } from '@mui/material';
// import { UserContext } from "./context/UserContext";

export default function VideoCard({ alerter }) {
    var url = "http://192.168.1.8:8000/live/stream.m3u8"
    return (
        <Card sx={{ height: '820px' }} variant="outlined">
            <CardHeader
                avatar={
                    <Avatar sx={{ bgcolor: red[500] }} >
                        <VideoCameraBackIcon />
                    </Avatar>
                }
                title={<Typography component="div" variant="h6">
                    Video Stream
                </Typography>}
                subheader="from Camera"
            />
            <CardContent>

                    <ReactPlayer
                        playing
                        url={url}
                        controls={true}
                        width="100%"
                        height="100%" />

            </CardContent>
        </Card>
    );
}

In this react ui, it keeps on loading and then Please suggest the solution to make react code work!

I have tried multiple libraries related to hls in react and now asking for help. I think I may be doing silly mistake and that's what I am expecting as a solution to this problem.


问:
how to export pie chart to excel using javascript
Is there a way to export this pie chart [the image] which is created using D3js to excel?


问:
JavaScript mediaQueryList does not trigger on `change` event when printing
I'm debugging some JavaScript code in Firefox 102.6.0esr that should set a variable depending on whether is output will be printed or not, but I'm a bloody JavaScript beginner.
Before going into further details, here is the code (extracted from longer code):

// is media "print"?
const mq_print = 'print'; // media query "print"?
var print_mql;
var media_print;

const ev_change = 'change'; // event "change"

function checkMedia(e) {
    media_print = e.matches;
    console.log("media_print is " + media_print);
}

document.addEventListener('DOMContentLoaded', (e) => {
    console.log("DOMContentLoaded: " + e.type);
    print_mql = window.matchMedia(mq_print);
    media_print = print_mql.matches;
    print_mql.addEventListener(ev_change, checkMedia);
});
```

The problem is that media_print never becomes true, specifically when I use Cntrl+P to print the page:
In the print preview the page is rendered as if the variable is not set, and according to the browser console it is not (However I see the DOMContentLoaded being processed).
Also @media print based CSS rules work correctly in the print preview.

I had also tried the variant print_mql.addListener(checkMedia) without any change.

Body:
I'm debugging some JavaScript code in Firefox 102.6.0esr that should set a variable depending on whether is output will be printed or not, but I'm a bloody JavaScript beginner.
Before going into further details, here is the code (extracted from longer code):

// is media "print"?
const mq_print = 'print'; // media query "print"?
var print_mql;
var media_print;

const ev_change = 'change'; // event "change"

function checkMedia(e) {
    media_print = e.matches;
    console.log("media_print is " + media_print);
}

document.addEventListener('DOMContentLoaded', (e) => {
    console.log("DOMContentLoaded: " + e.type);
    print_mql = window.matchMedia(mq_print);
    media_print = print_mql.matches;
    print_mql.addEventListener(ev_change, checkMedia);
});

The problem is that media_print never becomes true, specifically when I use Cntrl+P to print the page:
In the print preview the page is rendered as if the variable is not set, and according to the browser console it is not (However I see the DOMContentLoaded being processed).
Also @media print based CSS rules work correctly in the print preview.

I had also tried the variant print_mql.addListener(checkMedia) without any change.


问:
My alerts and form isn't redirecting when submit button is clicked
For some reason when my submit button is clicked, it does not redirect to the site, or have any alerts that tell me if username is empty, or password is invalid etc.... I have blocked out the recaptcha key for privacy reasons.
This is the html code

HTML 1
HTML 2

This is the javascript and html code

document.getElementById('form').addEventListener("submit", handleFormSubmit);

function handleFormSubmit(event){

   event.preventDefault();

let Username = document.getElementById("username").value;
let Password = document.getElementById("password").value;
let reconfirmPassword= document.getElementById("ConfirmPassword").value;
let email = document.getElementById("email").value;
let reconfirmEmail = document.getElementById("reconfirmEmail").value;
let maleRadio = document.querySelector('input[value="male"]');
const femaleRadio = document.querySelector('input[value="female"]');

    if(Username === ''){
        alert("Please enter a username");
    }

    if(Username.length < 4){
        alert("Username is too short");
    }

    if(Password === ''){
        alert("Please enter a password");
    }
    if(Enzoic.currentPasswordScore < Enzoic.PASSWORD_STRENGTH.Medium){
        alert("Password not strong enough");
    }

    if(Password !== reconfirmPassword){
        alert("Passwords do not match");
    }

    if(reconfirmPassword !== Password){
        alert("Passwords do not match");
    }

    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if(email === ''){
        alert("Please enter a email");
    } else if(!regex.test(email)){
        alert("Invalid email address");
    } else if( email != reconfirmEmail){
        alert("Email do not match")
    }

    if(reconfirmEmail !== email){
        alert("Email does not match");
    }

    if((!maleRadio.checked) && (!femaleRadio.checked)){
        alert("Please select a gender");
    }

    const recaptchaResponse = grecaptcha.getResponse();
    if(recaptchaResponse === ''){
        alert("Please complete the captcha");
    }

    window.location.replace('https://www.google.com');

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>

<head>

<link rel="stylesheet" href="styles.css">
<link href="/Merriweather_Sans/MerriweatherSans-VariableFont_wght.ttf">
<link href="fonts/Roboto/Roboto-Bold.ttf">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap" rel="stylesheet">
<script src="https://www.google.com/recaptcha/api.js">

function onSubmit(token) {
     document.getElementById("form").submit();
   }

</script>
<script async type="text/javascript" src="https://cdn.enzoic.com/js/enzoic.min.js">
  </script>

</head>
<body>
  <header>
    <h1>Create Your User</h1>
  </header>
<form id="form" method="post">
<label>Username</label>
<input type="name" id="username"/><br>
<br>
<label>Password</label>
<input type="password" id="password" enz-enable enz-theme='light'><br>
<br>
<label  id="confirmPassLabel">Reconfirm Password</label>
<input type="password" id="ConfirmPassword"><br>
<br>
<label for="email">Email</label>
<input type="name" id="email" type="email">
<div>
<label for="reconfirmEmail">Confirm email</label>
<input type="name" id="reconfirmEmail" type="email"><br>
<label>Male </label>
<input type="radio" id="male">
<label>Female</label>
<input type="radio" id="female">
<div  class="g-recaptcha" data-sitekey="6LeM8o4jAAAAAObqejc6i8IdWV15fTHM7w1ORVI7"></div>
</div>
<input type="submit" value="Submit"  id = "submit" class="g-recaptcha"
data-sitekey="6Lf43Y4jAAAAADZXBGovIWO1DqYJStERrJxwg4Yj"
data-callback='onSubmit'
data-action='submit'>
<script src="formFunctions.js"></script>
</form>

</body></code>```

This is the javascript code:

[[JAVASCRIPT]
Javascript 2

I tried seeing if the eventlistener at the top of the js file was a problem by just replacing the action after 'submit' to window.location.assign("https://somewebsite.com"). That worked but just linking everything up with the button is not working.

Body:
For some reason when my submit button is clicked, it does not redirect to the site, or have any alerts that tell me if username is empty, or password is invalid etc.... I have blocked out the recaptcha key for privacy reasons.
This is the html code

HTML 1
HTML 2

This is the javascript and html code

document.getElementById('form').addEventListener("submit", handleFormSubmit);

function handleFormSubmit(event){

   event.preventDefault();

let Username = document.getElementById("username").value;
let Password = document.getElementById("password").value;
let reconfirmPassword= document.getElementById("ConfirmPassword").value;
let email = document.getElementById("email").value;
let reconfirmEmail = document.getElementById("reconfirmEmail").value;
let maleRadio = document.querySelector('input[value="male"]');
const femaleRadio = document.querySelector('input[value="female"]');

    if(Username === ''){
        alert("Please enter a username");
    }

    if(Username.length < 4){
        alert("Username is too short");
    }

    if(Password === ''){
        alert("Please enter a password");
    }
    if(Enzoic.currentPasswordScore < Enzoic.PASSWORD_STRENGTH.Medium){
        alert("Password not strong enough");
    }

    if(Password !== reconfirmPassword){
        alert("Passwords do not match");
    }

    if(reconfirmPassword !== Password){
        alert("Passwords do not match");
    }

    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
    if(email === ''){
        alert("Please enter a email");
    } else if(!regex.test(email)){
        alert("Invalid email address");
    } else if( email != reconfirmEmail){
        alert("Email do not match")
    }

    if(reconfirmEmail !== email){
        alert("Email does not match");
    }

    if((!maleRadio.checked) && (!femaleRadio.checked)){
        alert("Please select a gender");
    }

    const recaptchaResponse = grecaptcha.getResponse();
    if(recaptchaResponse === ''){
        alert("Please complete the captcha");
    }

    window.location.replace('https://www.google.com');

}

<!DOCTYPE html>

<link rel="stylesheet" href="styles.css">
<link href="/Merriweather_Sans/MerriweatherSans-VariableFont_wght.ttf">
<link href="fonts/Roboto/Roboto-Bold.ttf">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&display=swap" rel="stylesheet">

Create Your User

<form id="form" method="post">
Username
<input type="name" id="username"/>

Password
<input type="password" id="password" enz-enable enz-theme='light'>

Reconfirm Password
<input type="password" id="ConfirmPassword">

Email
<input type="name" id="email" type="email">

Confirm email
<input type="name" id="reconfirmEmail" type="email">

Male
<input type="radio" id="male">
Female
<input type="radio" id="female">

<input type="submit" value="Submit"  id = "submit" class="g-recaptcha"
data-sitekey="6Lf43Y4jAAAAADZXBGovIWO1DqYJStERrJxwg4Yj"
data-callback='onSubmit'
data-action='submit'>

</form>

This is the javascript code:

[[JAVASCRIPT]
Javascript 2

I tried seeing if the eventlistener at the top of the js file was a problem by just replacing the action after 'submit' to window.location.assign("https://somewebsite.com"). That worked but just linking everything up with the button is not working.


问:
How to pass data between Nextjs server files
Assume this code

```<code>// puppeteer-manager.ts

import { Browser, executablePath, Page } from "puppeteer";
import puppeteerExtra from "puppeteer-extra";
import stealthPlugin from "puppeteer-extra-plugin-stealth";

puppeteerExtra.use(stealthPlugin());

interface PuppeteerInstance {
  browser: Browser;
  page: Page;
}

let instances: { [sessionId: string]: PuppeteerInstance } = {};

async function createPuppeteerInstance(
  sessionId: string
): Promise<PuppeteerInstance> {
  if (!instances[sessionId]) {
    const browser = await puppeteerExtra.launch({
      args: ["--no-sandbox"],
      headless: false,
      ignoreHTTPSErrors: true,
      executablePath: executablePath(),
    });
    const page = await browser.newPage();
    instances[sessionId] = { browser, page };
  }
  return instances[sessionId];
}

async function closePuppeteerInstance(sessionId: string): Promise<void> {
  if (instances[sessionId]) {
    const { browser } = instances[sessionId];
    await browser.close();
    delete instances[sessionId];
  }
}

export { createPuppeteerInstance, closePuppeteerInstance };

</code>```

So this code is responsible for creating new instances of puppeteer and storing them in a variable called instances and sessionId as the key.

So I'm building a NextJS app that let every connected user have their own puppeteer instance to achieve what the app is intended to.

So I will assume if I call createPuppeteerInstance in file A and pass it sessionId 1234 as session iD I will assume when I run createPuppeteerInstance in file B with the same sessionId I should get the same instance of puppeteer but for some reason, the variable instances in puppeteer-manager.ts not storing the different instance and createPuppeteerInstance keeps on creating a new instance every time I call it. I know this will just work in Express server so I'm asking/wondering could the problem be with NextJS that causes instances variable to go back to an empty object.

Body:
Assume this code

// puppeteer-manager.ts

import { Browser, executablePath, Page } from "puppeteer";
import puppeteerExtra from "puppeteer-extra";
import stealthPlugin from "puppeteer-extra-plugin-stealth";

puppeteerExtra.use(stealthPlugin());

interface PuppeteerInstance {
  browser: Browser;
  page: Page;
}

let instances: { [sessionId: string]: PuppeteerInstance } = {};

async function createPuppeteerInstance(
  sessionId: string
): Promise<PuppeteerInstance> {
  if (!instances[sessionId]) {
    const browser = await puppeteerExtra.launch({
      args: ["--no-sandbox"],
      headless: false,
      ignoreHTTPSErrors: true,
      executablePath: executablePath(),
    });
    const page = await browser.newPage();
    instances[sessionId] = { browser, page };
  }
  return instances[sessionId];
}

async function closePuppeteerInstance(sessionId: string): Promise<void> {
  if (instances[sessionId]) {
    const { browser } = instances[sessionId];
    await browser.close();
    delete instances[sessionId];
  }
}

export { createPuppeteerInstance, closePuppeteerInstance };

So this code is responsible for creating new instances of puppeteer and storing them in a variable called instances and sessionId as the key.

So I'm building a NextJS app that let every connected user have their own puppeteer instance to achieve what the app is intended to.

So I will assume if I call createPuppeteerInstance in file A and pass it sessionId 1234 as session iD I will assume when I run createPuppeteerInstance in file B with the same sessionId I should get the same instance of puppeteer but for some reason, the variable instances in puppeteer-manager.ts not storing the different instance and createPuppeteerInstance keeps on creating a new instance every time I call it. I know this will just work in Express server so I'm asking/wondering could the problem be with NextJS that causes instances variable to go back to an empty object.


问:
SSRS output list
I am new to SSRS and I cannot find how to output stuff into the list, every tutorial is for parameters.

Currently, I have a string in the textbox which looks ugly and I would like to put it to the list so users have a dropdown button.

The string is like "value1,value2,value3,value4,...." and it is all in one textbox.
I want somehow to put values in the column, but in one cell, so that users can collapse that.

THANKS!

Title: SSRS output list