问:
Object Reference Not Set... Arm Chain Generator Not Working
So this one is a bit convoluted.

It started off with trying to learn kinematics for procedural animation. Then I went on a tangent about generating thicker lines. Now I'm trying to produce a program that generates a chain of inter-connected lines made out of DrawSpheres with variable length/angle/resolution.

I had the original single line functioning perfectly. But I can not get the program to generate more. Each line is generated at the end target of the previous line, but there seems to be no starting object to reference. What do I change?

The individual line code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;

public class Arm
{
    public GameObject joint;

    [Range(0, 10), HideInInspector]
    public float length;

    [Range(-360, 360), HideInInspector]
    public float angle;

    [HideInInspector]
    public Transform origin;

    [Range(0, 2560), HideInInspector]
    public int density;

    [Range(0, 256), HideInInspector]
    public float thickness;

    public Vector3 Target()
    {
        Vector3 target = new Vector3(0, 0, 0);

        target.x = origin.position.x + Mathf.Cos(this.angle) * this.length;
        target.y = origin.position.y + Mathf.Sin(this.angle) * this.length;

        return target;
    }

    public Arm(float length, float angle, Vector3 origin, int resolution, float thickness, Vector3 target)
    {
        this.length = length;
        this.angle = angle;
        this.origin.position = origin;
        this.density = resolution;
        this.thickness = thickness;

    }

    public void GenerateLine()
    {
        Vector3[] lineSegments = new Vector3[density];
        float segmentLength = length / lineSegments.Length;

        lineSegments[0] = (origin.position);

        for(int i = 1; i < lineSegments.Length; i++)
        {
            lineSegments[i].x = lineSegments[i - 1].x + Mathf.Cos(this.angle/57.3f) * segmentLength;
            lineSegments[i].y = lineSegments[i - 1].y + Mathf.Sin(this.angle/57.3f) * segmentLength;

            Gizmos.color = Color.black;
            Gizmos.DrawSphere(lineSegments[i], thickness / 1000);
        }

    }
}

</code>```

The Chain manager code

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArmChain : MonoBehaviour
{
    [Range(0, 5)]
    public int chainLength;

    [Range(0, 10)]
    public float length;

    [Range(-360, 360)]
    public float angle;

    public Transform origin;

    [Range(0, 2560)]
    public int resolution;

    [Range(0, 256)]
    public float thickness;

    public Vector3 Target()
    {
        Vector3 target = new Vector3(0, 0, 0);

        target.x = this.transform.position.x + Mathf.Cos(this.angle) * this.length;
        target.y = this.transform.position.y + Mathf.Sin(this.angle) * this.length;

        return target;
    }

    public Transform jointOrigin;

    [SerializeField, HideInInspector]
    public Arm[] arms;

    private void OnDrawGizmos()
    {
        Initialize();
        GenerateChain();
    }

    void Initialize()
    {
        Arm[] arms = new Arm[chainLength];

        for (int i = 1; i < chainLength; i++)
        {
            arms[i] = new Arm(arms[i - 1].length, arms[i].angle, arms[i - 1].Target(), arms[i - 1].density, arms[i - 1].thickness, arms[i].Target());
        }
    }

    public void GenerateChain()
    {
        foreach (Arm arm in arms)
        {
            arm.GenerateLine();
        }
    }

}

</code>```

答:
you do

```<code>arms[i] = new Arm(arms[i - 1].length, arms[i].angle, arms[i - 1].Target(), arms[i - 1].density, arms[i - 1].thickness, arms[i].Target());
</code>```

well what is arms[0] ..? You never create it so the very first arms[i - 1] already returns null.

and further note the last access to arms[i].Target()

=> if arms[i] has never been set yet (because you are just going to do this) then there won't be anything at arms[i].

Besides that you do

```<code>Arm[] arms = new Arm[chainLength];
</code>```

which hides the class field arms

=> when you call GenerateChain the field arms was never initialized.

You rather would want

```<code>void Initialize()
{
    arms = new Arm[chainLength];

    ...
}
</code>```

Body:
So this one is a bit convoluted.

It started off with trying to learn kinematics for procedural animation. Then I went on a tangent about generating thicker lines. Now I'm trying to produce a program that generates a chain of inter-connected lines made out of DrawSpheres with variable length/angle/resolution.

I had the original single line functioning perfectly. But I can not get the program to generate more. Each line is generated at the end target of the previous line, but there seems to be no starting object to reference. What do I change?

The individual line code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;

public class Arm
{
    public GameObject joint;

    [Range(0, 10), HideInInspector]
    public float length;

    [Range(-360, 360), HideInInspector]
    public float angle;

    [HideInInspector]
    public Transform origin;

    [Range(0, 2560), HideInInspector]
    public int density;

    [Range(0, 256), HideInInspector]
    public float thickness;

    public Vector3 Target()
    {
        Vector3 target = new Vector3(0, 0, 0);

        target.x = origin.position.x + Mathf.Cos(this.angle) * this.length;
        target.y = origin.position.y + Mathf.Sin(this.angle) * this.length;

        return target;
    }

    public Arm(float length, float angle, Vector3 origin, int resolution, float thickness, Vector3 target)
    {
        this.length = length;
        this.angle = angle;
        this.origin.position = origin;
        this.density = resolution;
        this.thickness = thickness;

    }

    public void GenerateLine()
    {
        Vector3[] lineSegments = new Vector3[density];
        float segmentLength = length / lineSegments.Length;

        lineSegments[0] = (origin.position);

        for(int i = 1; i < lineSegments.Length; i++)
        {
            lineSegments[i].x = lineSegments[i - 1].x + Mathf.Cos(this.angle/57.3f) * segmentLength;
            lineSegments[i].y = lineSegments[i - 1].y + Mathf.Sin(this.angle/57.3f) * segmentLength;

            Gizmos.color = Color.black;
            Gizmos.DrawSphere(lineSegments[i], thickness / 1000);
        }

    }
}

The Chain manager code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArmChain : MonoBehaviour
{
    [Range(0, 5)]
    public int chainLength;

    [Range(0, 10)]
    public float length;

    [Range(-360, 360)]
    public float angle;

    public Transform origin;

    [Range(0, 2560)]
    public int resolution;

    [Range(0, 256)]
    public float thickness;

    public Vector3 Target()
    {
        Vector3 target = new Vector3(0, 0, 0);

        target.x = this.transform.position.x + Mathf.Cos(this.angle) * this.length;
        target.y = this.transform.position.y + Mathf.Sin(this.angle) * this.length;

        return target;
    }

    public Transform jointOrigin;

    [SerializeField, HideInInspector]
    public Arm[] arms;

    private void OnDrawGizmos()
    {
        Initialize();
        GenerateChain();
    }

    void Initialize()
    {
        Arm[] arms = new Arm[chainLength];

        for (int i = 1; i < chainLength; i++)
        {
            arms[i] = new Arm(arms[i - 1].length, arms[i].angle, arms[i - 1].Target(), arms[i - 1].density, arms[i - 1].thickness, arms[i].Target());
        }
    }

    public void GenerateChain()
    {
        foreach (Arm arm in arms)
        {
            arm.GenerateLine();
        }
    }

}

Body:
you do

arms[i] = new Arm(arms[i - 1].length, arms[i].angle, arms[i - 1].Target(), arms[i - 1].density, arms[i - 1].thickness, arms[i].Target());

well what is arms[0] ..? You never create it so the very first arms[i - 1] already returns null.

and further note the last access to arms[i].Target()

=> if arms[i] has never been set yet (because you are just going to do this) then there won't be anything at arms[i].

Besides that you do

Arm[] arms = new Arm[chainLength];

which hides the class field arms

=> when you call GenerateChain the field arms was never initialized.

You rather would want

void Initialize()
{
    arms = new Arm[chainLength];

    ...
}


来源: stackexchange

问:
How to use python to workout a simple mathematical problem in python with random operations
This is my code for a calculator that randomly selects a operation and number in between 1-10 and then with that number and operation works out the answer.

https://i.stack.imgur.com/Nys19.png

Now heres what happens when I run the code and put in a number. It dosen't workout the question it tells you the question. How do I make it answer the question.

https://i.stack.imgur.com/dLmaJ.png

Thank You if you help me

答:
In your case, it is safe to use otherwise unsafe function eval for this.

Since the user can only control a number (which is actually converted to int, not just assumed to be a number), he can't enter any code to evaluate.

```<code>answer = eval(f"{yournumber} {operation} {mynumber}")
</code>```

This will create string like 123 + 4 and then evaluate it.

THIS IS NOT A GENERAL ADVICE, supplying eval with user input might cause a vulnerability which just happened to be impossible in your example

ContentLicense: CC BY-SA 4.0

Body:
In your case, it is safe to use otherwise unsafe function eval for this.

Since the user can only control a number (which is actually converted to int, not just assumed to be a number), he can't enter any code to evaluate.

answer = eval(f"{yournumber} {operation} {mynumber}")

This will create string like 123 + 4 and then evaluate it.

THIS IS NOT A GENERAL ADVICE, supplying eval with user input might cause a vulnerability which just happened to be impossible in your example


问:
Get value from pseudo element with python
I would like to get the price value from the pseudo element you see on the picture below. If I hover over the mouse only then I can see some value like the price it costs( that is what I need). I found the "move_to_element" so now I can hover over the mouse with the program but I still cant get the price out of the element.
The problem is that even if I hover over my mouse I cant see the element opening in the inspector tab.

Thank you!

This is the code I would like to get out the :before element from:

```<code><div onclick="Game.UpgradesById[503].click(event);" class="crate upgrade enabled" onmouseout="Game.setOnCrate(0);Game.tooltip.shouldHide=1;" onmouseover="if (!Game.mouseDown) {Game.setOnCrate(this);Game.tooltip.dynamic=1;Game.tooltip.draw(this,function(){return function(){return Game.crateTooltip(Game.UpgradesById[503],'store');}();},'store');Game.tooltip.wobble();}" id="upgrade0" style="background-position:-1056px -1296px;"></div>
</code>```

After this there is an en element ::before and end of the div

答:
For your query on how to extract only the value:

Split the output x with the delimiter of next line: \n and then get it's first index. That would give you the value. Below are the lines.

```<code>spl = int(x.split("\n")[0])
print(f'value: {spl}')
print(type(spl))
</code>```

Output:

```<code>15
???
[owned : 0]
value: 15 # this line is fetched using the above code in this answer. It fetches the value from the `x`
<class 'int'>
</code>```

Body:
I would like to get the price value from the pseudo element you see on the picture below. If I hover over the mouse only then I can see some value like the price it costs( that is what I need). I found the "move_to_element" so now I can hover over the mouse with the program but I still cant get the price out of the element.
The problem is that even if I hover over my mouse I cant see the element opening in the inspector tab.

Thank you!

This is the code I would like to get out the :before element from:

After this there is an en element ::before and end of the div

Body:
For your query on how to extract only the value:

Split the output x with the delimiter of next line: \n and then get it's first index. That would give you the value. Below are the lines.

spl = int(x.split("\n")[0])
print(f'value: {spl}')
print(type(spl))

Output:

15
???
[owned : 0]
value: 15 # this line is fetched using the above code in this answer. It fetches the value from the `x`
<class 'int'>


问:
Python matrices without numpy
I'm trying to learn how to operate on python matrices but it's difficult since online I'm finding nothing but numpy library and it is forbidden to use it on exams, so, do you have any suggestions on where to find a book, a pdf or a site where I can learn more without using numpy??</p>

答:
If I couldn't use numpy I would use bidimensional lists for matrices.

Example:

```<code>a = [[1, 2, 3], [4, 5, 6]]
</code>```

A list that contains list elements that contains numbers.

Numpy is more efficient and if you don't have experience with programming languages like c or c++ some operations could be difficult to implement.

There are a lot of websites to learn with lists, this is a beginner one with clearly and runnable code: https://snakify.org/en/lessons/two_dimensional_lists_arrays/

Title: Python matrices without numpy

Body:
If I couldn't use numpy I would use bidimensional lists for matrices.

Example:

a = [[1, 2, 3], [4, 5, 6]]

A list that contains list elements that contains numbers.

Numpy is more efficient and if you don't have experience with programming languages like c or c++ some operations could be difficult to implement.

There are a lot of websites to learn with lists, this is a beginner one with clearly and runnable code: https://snakify.org/en/lessons/two_dimensional_lists_arrays/


问:
why we need to pass Boolean value to the method
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?</p>

```<code>RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }
</code>```

答:
Looks like a stale old parameter. Delete it.

The method does not return anything.

ContentLicense: CC BY-SA 3.0

Body:
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?

RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }


问:
Javascript - Display a different content if a checkbox is active
I'm trying to set up something in JQuery but at the moment I'm not really sure I'm doing it right.

To keep it simple, I would like to display 4 checkboxes. These checkboxes serve as filters. For the example, let's say the first checkbox is spring, the second is summer, the third is autumn and the fourth is winter.

When I check the "summer" box I would like some text to be displayed. If I tick the autumn one, another text is displayed. Basically, I would like to display different texts depending on what is ticked.

```<code><script type="text/javascript">
    function ShowHideDiv(winter) {
        var winter_list = document.getElementById("winter_list");
        winter_list.style.display = winter.checked ? "block" : "none";
    }
</script>
<script type="text/javascript">
    function ShowHideDiv(summer) {
        var summer_list = document.getElementById("summer_list");
        summer_list.style.display = summer.checked ? "block" : "none";
    }
</script>

<label for="checkWinter">
    <input type="checkbox" id="winter" onclick="ShowHideDiv(winter)" />
    Winter
</label>
<label for="checkSummer">
    <input type="checkbox" id="summer" onclick="ShowHideDiv(summer)" />
    Summer
</label>
<hr />

<!-- For Winter -->
<div id="winter_list" style="display: none">
<p>Text come here</p>
</div>

<!-- For Summer -->
<div id="summer_list" style="display: none">
<p>Text come here for summer</p>
</div>
</code>```

If possible: Can we make it possible to tick more than one box?

I've been following tutorials on StackOverflow but so far without much success, as I haven't found anything in the genre of my same request.

Thanks

答:
You have a mistake in thinking of your code.

The function ShowHideDiv()does exists two times and Javascript overload it. Because your passed an undefined object, the browser choose one of them.

My Suggestion:

First step: Replace the function calls in your input fields by <input type="checkbox" id="summer" onclick="ShowHideDiv(this)" />. The parameter this passes the clicked object to target function.

Second step: Merge all of your function "ShowHideDiv" to one:

```<code>function ShowHideDiv(checkbox) {
   switch (checkbox.id)
   {
      case "summer":
            var summer_list = document.getElementById("summer_list");
             summer_list.style.display = summer.checked ? "block" : "none";
         break;
      case "winter":
          var winter_list = document.getElementById("winter_list");
                winter_list.style.display = winter.checked ? "block" : "none";
          break;
      default:
        //What ever you want do to
        break;
   }
}
</code>```

The argument checkbox.id returns the value from attribute id of passed checkbox.

Switch and case is a smaller form of if() else if() and else().

Body:
I'm trying to set up something in JQuery but at the moment I'm not really sure I'm doing it right.

To keep it simple, I would like to display 4 checkboxes. These checkboxes serve as filters. For the example, let's say the first checkbox is spring, the second is summer, the third is autumn and the fourth is winter.

When I check the "summer" box I would like some text to be displayed. If I tick the autumn one, another text is displayed. Basically, I would like to display different texts depending on what is ticked.

    <input type="checkbox" id="winter" onclick="ShowHideDiv(winter)" />
    Winter

    <input type="checkbox" id="summer" onclick="ShowHideDiv(summer)" />
    Summer

Text come here

Text come here for summer

If possible: Can we make it possible to tick more than one box?

I've been following tutorials on StackOverflow but so far without much success, as I haven't found anything in the genre of my same request.

Thanks

Body:
You have a mistake in thinking of your code.

The function ShowHideDiv()does exists two times and Javascript overload it. Because your passed an undefined object, the browser choose one of them.

My Suggestion:

First step: Replace the function calls in your input fields by <input type="checkbox" id="summer" onclick="ShowHideDiv(this)" />. The parameter this passes the clicked object to target function.

Second step: Merge all of your function "ShowHideDiv" to one:

function ShowHideDiv(checkbox) {
   switch (checkbox.id)
   {
      case "summer":
            var summer_list = document.getElementById("summer_list");
             summer_list.style.display = summer.checked ? "block" : "none";
         break;
      case "winter":
          var winter_list = document.getElementById("winter_list");
                winter_list.style.display = winter.checked ? "block" : "none";
          break;
      default:
        //What ever you want do to
        break;
   }
}

The argument checkbox.id returns the value from attribute id of passed checkbox.

Switch and case is a smaller form of if() else if() and else().


问:
Regex exclude rows in csv that has forbidding word
I've been trying to exclude all the rows that contain 'shirt' and then from that have the rows that have 'cotton' (case insensitive)
for example:

"Cotton Shirt for sale" - don't include

"Cotton Dress for Sale" - Pass

"dress shirt-V-neck-cotton" -fail

"no words relevant" - Fail (no cotton in it)

"cotton-url click" - pass

My regex:

```<code>pattern = re.compile('(?i)^((?!.*shirt).).*(?=.*cotton.*)')
</code>```

But for some reason my rows in csv still remain on a sentence:

"Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look"

my code:

```<code>pattern1 = re.compile("(?i)(.*shirt.*)")
    with open("sample.csv", 'r', encoding="utf-8") as bigCSV:
        csv_reader = csv.reader(bigCSV)
        counterWithout = 0
        counterCheck = 0
        headFlag = True
        for row in csv_reader:
            if headFlag:
                header = row
                headFlag = False
            if any(pattern.match(line) for line in row)://there is a difference in the number of rows here
                if any(pattern1.match(line) for line in row):
                    print(row)
                    counterCheck += 1
                counterWithout += 1
</code>```

Help fix regex please

答:
Would you consider pandas? After you load in your csv file with pd.read_csv(...), you'll presumably get a DataFrame that will look, at a minimum, something like the below:

```<code>import pandas as pd
df = pd.DataFrame({
    "description":["Cotton Shirt for sale",
                    "Cotton Dress for Sale",
                    "dress shirt-V-neck-cotton",
                    "no words relevant",
                    "cotton-url click"]
})
</code>```

Then:

```<code># First step: add a column to keep track of what we're including/excluding. Can set directly to False; see later.
df["include"] = "-"

# Mark every row containing "shirt", case insensitive, as not to include.
df.loc[df["description"].str.contains("shirt", case=False), "include"] = False

# Of the rows that are left, mark as True if they contain "cotton".
df.loc[
    (df["include"]=="-") &
    (df["description"].str.contains("cotton", case=False)), "include"
]=True
</code>```

At this point the DataFrame looks like this:

You can now set any remaining rows marked - to False (I find it easier to debug this way, especially if the conditions get more complicated), or you could have started off by initialising the "include" column to False.

Body:
I've been trying to exclude all the rows that contain 'shirt' and then from that have the rows that have 'cotton' (case insensitive)
for example:

"Cotton Shirt for sale" - don't include

"Cotton Dress for Sale" - Pass

"dress shirt-V-neck-cotton" -fail

"no words relevant" - Fail (no cotton in it)

"cotton-url click" - pass

My regex:

pattern = re.compile('(?i)^((?!.*shirt).).*(?=.*cotton.*)')

But for some reason my rows in csv still remain on a sentence:

"Stone Italian Yarn Fringe Yoke Cable Cotton Shirt New Look"

my code:

pattern1 = re.compile("(?i)(.*shirt.*)")
    with open("sample.csv", 'r', encoding="utf-8") as bigCSV:
        csv_reader = csv.reader(bigCSV)
        counterWithout = 0
        counterCheck = 0
        headFlag = True
        for row in csv_reader:
            if headFlag:
                header = row
                headFlag = False
            if any(pattern.match(line) for line in row)://there is a difference in the number of rows here
                if any(pattern1.match(line) for line in row):
                    print(row)
                    counterCheck += 1
                counterWithout += 1

Help fix regex please

Body:
Would you consider pandas? After you load in your csv file with pd.read_csv(...), you'll presumably get a DataFrame that will look, at a minimum, something like the below:

import pandas as pd
df = pd.DataFrame({
    "description":["Cotton Shirt for sale",
                    "Cotton Dress for Sale",
                    "dress shirt-V-neck-cotton",
                    "no words relevant",
                    "cotton-url click"]
})

Then:

# First step: add a column to keep track of what we're including/excluding. Can set directly to False; see later.
df["include"] = "-"

# Mark every row containing "shirt", case insensitive, as not to include.
df.loc[df["description"].str.contains("shirt", case=False), "include"] = False

# Of the rows that are left, mark as True if they contain "cotton".
df.loc[
    (df["include"]=="-") &
    (df["description"].str.contains("cotton", case=False)), "include"
]=True

At this point the DataFrame looks like this:

You can now set any remaining rows marked - to False (I find it easier to debug this way, especially if the conditions get more complicated), or you could have started off by initialising the "include" column to False.


问:
How do getters and setters work in Python?
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

```<code>class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)
</code>```

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.

答:
You need to tell python how to associate the getter and setter with the actual variable name. To do this you can use the builtin property function like so:

```<code>class Person
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name
    name = property(get_name)
    age = property(get_age, set_age)

    def __str__(self):
        return 'Person[' + self.name + '] is ' + str(self.age)

p1 = Person("Sandeep", 49)
</code>```

Then instead of referring to _name and _age use name and age

Body:
I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name

    def __str__(self):
        return 'Person[' + self._name + '] is ' + str(self._age)

p1 = Person("Sandeep", 49)

I created an object p1 where I set the age 49. As I have made a set_age function so I expect we can change the age of p1 through set_age only, not through the routine way. But it is not happening, I am able to change the age of p1 through , for example, p1._age = 35 as well. Then, what is the advantage to make set_age function, if I am still able to access the attributes directly?

I think, I am missing something, please help.

Body:
You need to tell python how to associate the getter and setter with the actual variable name. To do this you can use the builtin property function like so:

class Person
    def __init__(self, name, age):
        self._name = name
        self._age = age

    def get_age(self):
        return self._age

    def set_age(self, new_age):
        if isinstance(new_age, int) & new_age>0 & new_age<120:
            self._age = new_age

    def get_name(self):
        return self._name
    name = property(get_name)
    age = property(get_age, set_age)

    def __str__(self):
        return 'Person[' + self.name + '] is ' + str(self.age)

p1 = Person("Sandeep", 49)

Then instead of referring to _name and _age use name and age


问:
Pentaho select UUID type fild as UUID and Insert into other table as UUID
I am new to Pentaho, my research end up with nothing
I have a table that has filed with type UUID
I need to copy it to another table where the field has the same UUID.
Table input. has this SQL

I am casting field to UUI filed specifically.
however when I check input fields on the output table it shows as string, how do I cast it to uuid.

Also the same for the output table, it was created with datatype UUID for that field

output table shows datatype as the string

On the run, it throws an error clearly showing that it cannot convert it to UUID

```<code>2022/02/11 10:42:45 - Table output.0 - Caused by: org.postgresql.util.PSQLException: ERROR: column "qr_uuid" is of type uuid but expression is of type character varying
</code>```

I am using Postgres 13 and Pentaho 9

答:
I have found an old thread dealing with the same problem, and there are some hints for the answer. You'll need to edit the database connection for postgres, and in the Options menu add Parameter stringtype with Value unspecified:

How insert UUID values in PostgreSQL table via Kettle?

Body:
I am new to Pentaho, my research end up with nothing
I have a table that has filed with type UUID
I need to copy it to another table where the field has the same UUID.
Table input. has this SQL

I am casting field to UUI filed specifically.
however when I check input fields on the output table it shows as string, how do I cast it to uuid.

Also the same for the output table, it was created with datatype UUID for that field

output table shows datatype as the string

On the run, it throws an error clearly showing that it cannot convert it to UUID

2022/02/11 10:42:45 - Table output.0 - Caused by: org.postgresql.util.PSQLException: ERROR: column "qr_uuid" is of type uuid but expression is of type character varying

I am using Postgres 13 and Pentaho 9


问:
Excel created only fills last columns and rows Android Studio
I am currently trying to create an excel through my android application.
I have a response array that is fetched from the server.
But when the data is inserted into the excel only the last columns are filled for some weird reason. I tried a few solutions I switched from for iterations to for-each to traverse through the array because the for loop was not working the way I intended it to do.

I logged the data received which was supposed to be inserted into the cell at the position and row and the logged data was correct but the output was not.

The below code is for setting values into the cells and logging the position and row. Also attached the image of the output:
[![This is the image of the issue am facing][1]][1]

```<code> private void setData() {
        try {

            int i = 0;
            for (int pos : postions) {
                List<Orderpojo> atttt = Arrays.asList(dataList.get(i).getEmployee());
                int pos1 = pos + 1;
                int pos2 = pos + 2;
                int intimecounter = row_index;
                Log.e(Admin_Att_Report.class.getSimpleName(), "setData: Position" + pos);

                for (Orderpojo Record : atttt) {
                    Row newrow = sheet.createRow(intimecounter);
                    cell = newrow.createCell(pos);
                    cell.setCellValue(Record.getIn_Time());
                    Log.e(Admin_Att_Report.class.getSimpleName(), "setData: Data Inserted at Row " + intimecounter + "\n" +
                            "VALUE User Name " + dataList.get(i).getMgmt_Name()
                            + "\n" +
                            "VALUE " + pos + " : InTime " + Record.getIn_Time()
                            + "\n" +
                            "VALUE " + pos1 + " : OutTime " + Record.getOut_Time()
                            + "\n" +
                            "VALUE " + pos2 + " : Work DOne " + Record.getWork_Done() +
                            "\n");

                    cell = newrow.createCell(pos1);
                    cell.setCellValue(Record.getOut_Time());

                    cell = newrow.createCell(pos2);
                    cell.setCellValue(Record.getWork_Done());

                    Log.e(Admin_Att_Report.class.getSimpleName(), "setData: Data Inserted at Row " + intimecounter + " at Columns :" + pos + " & " + pos1 + " & " + pos2);

                    intimecounter = intimecounter + 1;

                }
                i++;
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }
</code>```

The Data is supposed to be filled in three positions: 'In-Time', 'Out-Time' & 'Work Done'.
Hence the incremental variables such as pos1 and pos2 are used.
The starting position is three and incremented by 3 for every new user. ie 3,9,12,....
Hence filling the positions for the data.

The logged data looks as follows and is correct and verified a dozen times.

```<code>Admin_Att_Report: setData: Data Inserted at Row 6
    VALUE User Name Rohit Borkar
    VALUE 39 : InTime 2022-02-05 09:43:31
    VALUE 40 : OutTime 2022-02-05 18:06:39
    VALUE 41 : Work DOne working on amanora park school drawings with vinay.
</code>```

I hope the logged data is understandable.
[1]: https://i.stack.imgur.com/hrgEa.png

答:
Using apache poi Row.createRow always creates a new empty row. If that row already existed in the sheet, then all cells in that row will be removed.

So if you want to fetch and update already existing rows, you must first try to get those rows with Sheet.getRow. Only if Sheet.getRow returns null because that row doesn't exists yet, create it.

In your example:

```<code>...
Row newrow = sheet.getRow(intimecounter);
if (newrow == null) newrow = sheet.createRow(intimecounter);
...
</code>```

Body:
I am currently trying to create an excel through my android application.
I have a response array that is fetched from the server.
But when the data is inserted into the excel only the last columns are filled for some weird reason. I tried a few solutions I switched from for iterations to for-each to traverse through the array because the for loop was not working the way I intended it to do.

I logged the data received which was supposed to be inserted into the cell at the position and row and the logged data was correct but the output was not.

The below code is for setting values into the cells and logging the position and row. Also attached the image of the output:
[![This is the image of the issue am facing][1]][1]

 private void setData() {
        try {

            int i = 0;
            for (int pos : postions) {
                List<Orderpojo> atttt = Arrays.asList(dataList.get(i).getEmployee());
                int pos1 = pos + 1;
                int pos2 = pos + 2;
                int intimecounter = row_index;
                Log.e(Admin_Att_Report.class.getSimpleName(), "setData: Position" + pos);

                for (Orderpojo Record : atttt) {
                    Row newrow = sheet.createRow(intimecounter);
                    cell = newrow.createCell(pos);
                    cell.setCellValue(Record.getIn_Time());
                    Log.e(Admin_Att_Report.class.getSimpleName(), "setData: Data Inserted at Row " + intimecounter + "\n" +
                            "VALUE User Name " + dataList.get(i).getMgmt_Name()
                            + "\n" +
                            "VALUE " + pos + " : InTime " + Record.getIn_Time()
                            + "\n" +
                            "VALUE " + pos1 + " : OutTime " + Record.getOut_Time()
                            + "\n" +
                            "VALUE " + pos2 + " : Work DOne " + Record.getWork_Done() +
                            "\n");

                    cell = newrow.createCell(pos1);
                    cell.setCellValue(Record.getOut_Time());

                    cell = newrow.createCell(pos2);
                    cell.setCellValue(Record.getWork_Done());

                    Log.e(Admin_Att_Report.class.getSimpleName(), "setData: Data Inserted at Row " + intimecounter + " at Columns :" + pos + " & " + pos1 + " & " + pos2);

                    intimecounter = intimecounter + 1;

                }
                i++;
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

The Data is supposed to be filled in three positions: 'In-Time', 'Out-Time' & 'Work Done'.
Hence the incremental variables such as pos1 and pos2 are used.
The starting position is three and incremented by 3 for every new user. ie 3,9,12,....
Hence filling the positions for the data.

The logged data looks as follows and is correct and verified a dozen times.

Admin_Att_Report: setData: Data Inserted at Row 6
    VALUE User Name Rohit Borkar
    VALUE 39 : InTime 2022-02-05 09:43:31
    VALUE 40 : OutTime 2022-02-05 18:06:39
    VALUE 41 : Work DOne working on amanora park school drawings with vinay.

I hope the logged data is understandable.
[1]: https://i.stack.imgur.com/hrgEa.png

Body:
Using apache poi Row.createRow always creates a new empty row. If that row already existed in the sheet, then all cells in that row will be removed.

So if you want to fetch and update already existing rows, you must first try to get those rows with Sheet.getRow. Only if Sheet.getRow returns null because that row doesn't exists yet, create it.

In your example:

...
Row newrow = sheet.getRow(intimecounter);
if (newrow == null) newrow = sheet.createRow(intimecounter);
...


问:
Transition don't work with min-height property
I tried to make smooth transition while box is changing height, but when i use min-height, which is very important to me, transition dont work, here is example code that i make to make sure that this problem dont show only on my page but everywhere.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: #F4EEA9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 50%;
  min-height: 10vh;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  padding: 20px;
  transition: 0.5s;
}

.box:hover {
  height: 50vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <title>TEST</title>
</head>

<body>
  <div class="main">
    <div class="box">
      <h1>Hello World</h1>
      <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate mollitia numquam est voluptas rem, voluptates dolore a rerum amet eos quae eum laudantium exercitationem quas quasi vel quia perferendis consectetur sit omnis. Placeat, nisi deleniti.
        Facere architecto, possimus veritatis quo molestiae temporibus vero vel recusandae, iusto ullam nostrum quia voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt nesciunt ratione consectetur corrupti laboriosam aliquid,
        beatae atque laborum deleniti adipisci esse blanditiis cum facere sequi voluptatibus, molestias eos sint tempore quia, quo cumque quasi. Repellat quas quaerat soluta officia voluptatum dolorum nobis a iure voluptatem id, cumque corporis voluptas
        nesciunt.</p>
    </div>
  </div>
</body>

</html></code>```

答:
This works :-

```<code>.box{
    width: 50vw;
    max-height: 10vh;
    box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
   padding: 20px;
   transition: all .2s ease-in-out;
   overflow:hidden;
}

.box:hover{
   height: 50vh;
   max-height: 50vh;
}
</code>```

You have to set the min height and the max height so it know that to go to and from, also I have hidden the overflow. Hope this works

Body:
I tried to make smooth transition while box is changing height, but when i use min-height, which is very important to me, transition dont work, here is example code that i make to make sure that this problem dont show only on my page but everywhere.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.main {
  width: 100%;
  height: 100vh;
  background-color: #F4EEA9;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 50%;
  min-height: 10vh;
  box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
  padding: 20px;
  transition: 0.5s;
}

.box:hover {
  height: 50vh;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <link rel="stylesheet" href="style.css">
  <title>TEST</title>

Hello World

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate mollitia numquam est voluptas rem, voluptates dolore a rerum amet eos quae eum laudantium exercitationem quas quasi vel quia perferendis consectetur sit omnis. Placeat, nisi deleniti.
        Facere architecto, possimus veritatis quo molestiae temporibus vero vel recusandae, iusto ullam nostrum quia voluptatibus. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt nesciunt ratione consectetur corrupti laboriosam aliquid,
        beatae atque laborum deleniti adipisci esse blanditiis cum facere sequi voluptatibus, molestias eos sint tempore quia, quo cumque quasi. Repellat quas quaerat soluta officia voluptatum dolorum nobis a iure voluptatem id, cumque corporis voluptas
        nesciunt.

Body:
This works :-

.box{
    width: 50vw;
    max-height: 10vh;
    box-shadow: rgba(0, 0, 0, 0.25) 0px 14px 28px, rgba(0, 0, 0, 0.22) 0px 10px 10px;
   padding: 20px;
   transition: all .2s ease-in-out;
   overflow:hidden;
}

.box:hover{
   height: 50vh;
   max-height: 50vh;
}

You have to set the min height and the max height so it know that to go to and from, also I have hidden the overflow. Hope this works


问:
Switch video source on click
For example:
Section 1 HOME: has a video loop background, "video source 1"
I want to change the video source by clicking on the video in section 1 to "video source 2",

but video2 has only to be played one time and has to switch back again to video1

How do I fix that

答:
You can try something like this:

Create a Boolean for true/false as your "If played once" variable. Set it to = false;...

Give the (background) <video> tag an ID in the tag setup.

Add a "click" listener to the <video> tag.

The click handling function should get video object by ID...

Have an if statement to check If (played_Once == false)

Inside the if, you can set myVideoID.src = "other_video.mp4 and then do also:
 myVideoID.load();
 myVideoID.play();
 played_Once = true;

You also need to add an "on ended" listener to the video object, where the handling function will change src in the same way as the steps above, back to the original video, remove the listener for "ended" at this point

Title: Switch video source on click


问:
Is Amazon Elastic Kubernetes Service can use fargate spot instance?
I'm using Is Amazon Elastic Kubernetes Service, I need to run fargate service on the Spot node.

Is it possible for EKS? Currently, I can find information about ECS only. So what steps I should follow to achieve this?

答: Fargate for EKS does not support spot instance yet. You can upvote here for the feature.


问:
VS Code Python Formatting: Change max line-length with autopep8 / yapf / black
I am experimenting with different python formatters and would like to increase the max line length. Ideally without editing the settings.json file. Is there a way to achieve that?

答:
For all three formatters, the max line length can be increased with additional arguments passed in from settings, i.e.:

autopep8 args: --max-line-length=120

black args: --line-length=120

yapf args: --style={based_on_style: google, column_limit: 120, indent_width: 4}

Hope that helps someone in the future!


问:
Pygame 'DIsplay mode not set'?
I (tried) to create a game menu and placed my GameLoop in the Class = Menü. When I try to start the code it highlights the line pygame.display.update() and tells me that: Display mode not set.

```<code>Class Menü(Highscore):

    def __init__(self):
        Highscore.__init__(self)
        #Fenster erstellen
        self.fenster_height = 1000  # Fensterhöhe definieren
        self.fenster_width = 600  # Fensterbreite definieren
        self.screen = pygame.display.set_mode((self.fenster_height, self.fenster_width))
        self.run = True
        #self.start_img = self.image.load('pong_test.png').convert_alpha()  # Bild für start_img ausw#hlen
        #self.quit_img = self.image.load('pong_test.png').convert_alpha()
        #self.auslesen = Highscore.readHS()

        pygame.display.set_caption('Spielekiste')
        #pygame.start_img = pygame.image.load('pong_test.png').convert_alpha()
        #pygame.quit_img = pygame.image.load('pong_test.png').convert_alpha()
        #self.screen.fill((96, 144, 189))  # Screen mit Farbe (255,255,255) füllen

    def runMenü(self):

        while True:  # Während "run = TRUE"
            for event in pygame.event.get():
                       # fenster schließen
                if event.type == pygame.QUIT:

                    pygame.quit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    print('test')

            pygame.display.update()  # Fenster wird aktualisiert
menu = Menü

menu.runMenü(menu)
</code>```

答:
First of all, in order to create a class in python, we use the class keyword, whereas in your code, you used the word Class, which will throw an error since it isn't a keyword in python.

So replace this line: Class Menü(Highscore): with this line: class Menü(Highscore):

Now to address your issue, see this answer. Basically, there are two ways in which you can prevent the error that you are getting:

The First Way

```<code>run = True
while run:  # Während "run = TRUE"
    for event in pygame.event.get():
               # fenster schließen
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            print('test')

    pygame.display.update()  # Fenster wird aktualisiert

pygame.quit()
</code>```

In your current game loop (the while loop inside the runMenü function), when the pygame.QUIT event is triggered, you immediately quit the program without stopping your game loop. So if you replace the code inside your runMenü function with the code I wrote, you won't get an error.

The Second Way

```<code>while True:  # Während "run = TRUE"
    for event in pygame.event.get():
               # fenster schließen
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
        if event.type == pygame.MOUSEBUTTONDOWN:
            print('test')

    pygame.display.update()  # Fenster wird aktualisiert
</code>```

Here, I'm exiting the program after using pygame.quit() to quit pygame. That way, your program won't throw an error because I'm terminating it with sys.exit(0). Don't forget to add import sys at the top of your code (under import pygame).

I would personally use the first method because it stops the loop and then terminates the program, which I think is better.

Modified Code:

```<code>import pygame
pygame.init()

class Menü(Highscore):
    def __init__(self):
        Highscore.__init__(self)
        #Fenster erstellen
        self.fenster_height = 1000  # Fensterhöhe definieren
        self.fenster_width = 600  # Fensterbreite definieren
        self.screen = pygame.display.set_mode((self.fenster_height, self.fenster_width))
        self.run = True
        #self.start_img = self.image.load('pong_test.png').convert_alpha()  # Bild für start_img ausw#hlen
        #self.quit_img = self.image.load('pong_test.png').convert_alpha()
        #self.auslesen = Highscore.readHS()

        pygame.display.set_caption('Spielekiste')
        #pygame.start_img = pygame.image.load('pong_test.png').convert_alpha()
        #pygame.quit_img = pygame.image.load('pong_test.png').convert_alpha()
        #self.screen.fill((96, 144, 189))  # Screen mit Farbe (255,255,255) füllen

    def runMenü(self):
        run = True
        while run:  # Während "run = TRUE"
            for event in pygame.event.get():
                       # fenster schließen
                if event.type == pygame.QUIT:
                    run = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    print('test')

            pygame.display.update()  # Fenster wird aktualisiert

        pygame.quit()

menu = Menü()
menu.runMenü()
</code>```

Title: Pygame 'DIsplay mode not set'?

Body:
I (tried) to create a game menu and placed my GameLoop in the Class = Menü. When I try to start the code it highlights the line pygame.display.update() and tells me that: Display mode not set.

Class Menü(Highscore):

    def __init__(self):
        Highscore.__init__(self)
        #Fenster erstellen
        self.fenster_height = 1000  # Fensterhöhe definieren
        self.fenster_width = 600  # Fensterbreite definieren
        self.screen = pygame.display.set_mode((self.fenster_height, self.fenster_width))
        self.run = True
        #self.start_img = self.image.load('pong_test.png').convert_alpha()  # Bild für start_img ausw#hlen
        #self.quit_img = self.image.load('pong_test.png').convert_alpha()
        #self.auslesen = Highscore.readHS()

        pygame.display.set_caption('Spielekiste')
        #pygame.start_img = pygame.image.load('pong_test.png').convert_alpha()
        #pygame.quit_img = pygame.image.load('pong_test.png').convert_alpha()
        #self.screen.fill((96, 144, 189))  # Screen mit Farbe (255,255,255) füllen

    def runMenü(self):

        while True:  # Während "run = TRUE"
            for event in pygame.event.get():
                       # fenster schließen
                if event.type == pygame.QUIT:

                    pygame.quit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    print('test')

            pygame.display.update()  # Fenster wird aktualisiert
menu = Menü

menu.runMenü(menu)

Body:
First of all, in order to create a class in python, we use the class keyword, whereas in your code, you used the word Class, which will throw an error since it isn't a keyword in python.

So replace this line: Class Menü(Highscore): with this line: class Menü(Highscore):

Now to address your issue, see this answer. Basically, there are two ways in which you can prevent the error that you are getting:

The First Way

run = True
while run:  # Während "run = TRUE"
    for event in pygame.event.get():
               # fenster schließen
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            print('test')

    pygame.display.update()  # Fenster wird aktualisiert

pygame.quit()

In your current game loop (the while loop inside the runMenü function), when the pygame.QUIT event is triggered, you immediately quit the program without stopping your game loop. So if you replace the code inside your runMenü function with the code I wrote, you won't get an error.

The Second Way

while True:  # Während "run = TRUE"
    for event in pygame.event.get():
               # fenster schließen
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
        if event.type == pygame.MOUSEBUTTONDOWN:
            print('test')

    pygame.display.update()  # Fenster wird aktualisiert

Here, I'm exiting the program after using pygame.quit() to quit pygame. That way, your program won't throw an error because I'm terminating it with sys.exit(0). Don't forget to add import sys at the top of your code (under import pygame).

I would personally use the first method because it stops the loop and then terminates the program, which I think is better.

Modified Code:

import pygame
pygame.init()

class Menü(Highscore):
    def __init__(self):
        Highscore.__init__(self)
        #Fenster erstellen
        self.fenster_height = 1000  # Fensterhöhe definieren
        self.fenster_width = 600  # Fensterbreite definieren
        self.screen = pygame.display.set_mode((self.fenster_height, self.fenster_width))
        self.run = True
        #self.start_img = self.image.load('pong_test.png').convert_alpha()  # Bild für start_img ausw#hlen
        #self.quit_img = self.image.load('pong_test.png').convert_alpha()
        #self.auslesen = Highscore.readHS()

        pygame.display.set_caption('Spielekiste')
        #pygame.start_img = pygame.image.load('pong_test.png').convert_alpha()
        #pygame.quit_img = pygame.image.load('pong_test.png').convert_alpha()
        #self.screen.fill((96, 144, 189))  # Screen mit Farbe (255,255,255) füllen

    def runMenü(self):
        run = True
        while run:  # Während "run = TRUE"
            for event in pygame.event.get():
                       # fenster schließen
                if event.type == pygame.QUIT:
                    run = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    print('test')

            pygame.display.update()  # Fenster wird aktualisiert

        pygame.quit()

menu = Menü()
menu.runMenü()


问:
X11 Copy is returning only returning GDK_SELECTION, for CLIPBOARD Selection
I am writing a component which has to monitor changes in CLIPBOARD for a X11 window.

```<code>auto display = XOpenDisplay(NULL);
auto screen = DefaultScreen(mdisplay);
auto root_window = RootWindow(display, screen);
clipboard = XInternAtom(display, "CLIPBOARD", 0);
window = XCreateSimpleWindow(mdisplay, root_window, 0, 0, 1, 1, 0, 0, 0);
while(true) {
    XEvent event = {0};
    XNextEvent(display, &event);
    switch(event.type) {
        case SelectionNotify: {
            // do something
        }
        break;
        case SelectionRequest: { // triggered after performing copy
            auto target_name = XGetAtomName(display, event.xselectionrequest.target);
            auto selection_name = XGetAtomName(display, event.xselectionrequest.selection);
            auto property_name = XGetAtomName(display, event.xselectionrequest.property);
            Log("Event SelectionRequest: owner: %ld, requestor: %ld, selection: %s, target: %s(%d), property: %s",
                    event.xselectionrequest.owner,
                    event.xselectionrequest.requestor,
                    selection_name,
                    target_name,
                    event.xselectionrequest.target,
                    property_name);

            if(x_event.xselectionrequest.selection != clipboard) {
                Log("%s: Warning: event selection not matching\n", __func__);
                break;
            }
        }
        break;
    }
}
</code>```

Problem is that when I try to check event SelectionRequest all I see is

```<code>Event SelectionRequest: owner: 33554433, requestor: 18874649, selection: CLIPBOARD, target: TARGETS(344), property: GDK_SELECTION
</code>```

The action I am performing is copying some text from Chrome browser. Can anyone tell me why I am not seeing this text, unicode, string types, but rather GDK_SELECTION?

PS:
It happens to be I just saw those formats only once (text, unicode, string types), but never again.

答:
For reading data in clipboard you need:

call XConvertSelection with TARGETS as target atom

wait for SelectionNotify event and read available targets using XGetWindowProperty

call XConvertSelection with preferred target

wait for SelectionNotify event and read available data using XGetWindowProperty

For more info check this answer

Posting hear naive implementation only for describe main idea.

```<code>// gcc -o xclipget xclipget.c -lX11
#include <stdio.h>
#include <limits.h>
#include <X11/Xlib.h>

Bool PrintSelection(Display *display, Window window, const char *bufname, const char *fmtname)
{
  char *result;
  unsigned long ressize, restail;
  int resbits;
  Atom bufid = XInternAtom(display, bufname, False),
       fmtid = XInternAtom(display, fmtname, False),
       propid = XInternAtom(display, "XSEL_DATA", False),
       incrid = XInternAtom(display, "INCR", False);
  XEvent event;

  XConvertSelection(display, bufid, fmtid, propid, window, CurrentTime);
  do {
    XNextEvent(display, &event);
  } while (event.type != SelectionNotify || event.xselection.selection != bufid);

  if (event.xselection.property)
  {
    XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, False, AnyPropertyType,
      &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);

    if (fmtid == incrid)
      printf("Buffer is too large and INCR reading is not implemented yet.\n");
    else
      printf("%.*s", (int)ressize, result);

    XFree(result);
    return True;
  }
  else // request failed, e.g. owner can't convert to the target format
    return False;
}

int main()
{
  Display *display = XOpenDisplay(NULL);
  unsigned long color = BlackPixel(display, DefaultScreen(display));
  Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0, 1,1, 0, color, color);
  Bool result = PrintSelection(display, window, "CLIPBOARD", "UTF8_STRING") ||
                PrintSelection(display, window, "CLIPBOARD", "STRING");
  XDestroyWindow(display, window);
  XCloseDisplay(display);
  return !result;
}
</code>```

Body:
I am writing a component which has to monitor changes in CLIPBOARD for a X11 window.

auto display = XOpenDisplay(NULL);
auto screen = DefaultScreen(mdisplay);
auto root_window = RootWindow(display, screen);
clipboard = XInternAtom(display, "CLIPBOARD", 0);
window = XCreateSimpleWindow(mdisplay, root_window, 0, 0, 1, 1, 0, 0, 0);
while(true) {
    XEvent event = {0};
    XNextEvent(display, &event);
    switch(event.type) {
        case SelectionNotify: {
            // do something
        }
        break;
        case SelectionRequest: { // triggered after performing copy
            auto target_name = XGetAtomName(display, event.xselectionrequest.target);
            auto selection_name = XGetAtomName(display, event.xselectionrequest.selection);
            auto property_name = XGetAtomName(display, event.xselectionrequest.property);
            Log("Event SelectionRequest: owner: %ld, requestor: %ld, selection: %s, target: %s(%d), property: %s",
                    event.xselectionrequest.owner,
                    event.xselectionrequest.requestor,
                    selection_name,
                    target_name,
                    event.xselectionrequest.target,
                    property_name);

            if(x_event.xselectionrequest.selection != clipboard) {
                Log("%s: Warning: event selection not matching\n", __func__);
                break;
            }
        }
        break;
    }
}

Problem is that when I try to check event SelectionRequest all I see is

Event SelectionRequest: owner: 33554433, requestor: 18874649, selection: CLIPBOARD, target: TARGETS(344), property: GDK_SELECTION

The action I am performing is copying some text from Chrome browser. Can anyone tell me why I am not seeing this text, unicode, string types, but rather GDK_SELECTION?

PS:
It happens to be I just saw those formats only once (text, unicode, string types), but never again.

Body:
For reading data in clipboard you need:

call XConvertSelection with TARGETS as target atom

wait for SelectionNotify event and read available targets using XGetWindowProperty

call XConvertSelection with preferred target

wait for SelectionNotify event and read available data using XGetWindowProperty

For more info check this answer

Posting hear naive implementation only for describe main idea.

// gcc -o xclipget xclipget.c -lX11
#include <stdio.h>
#include <limits.h>
#include <X11/Xlib.h>

Bool PrintSelection(Display *display, Window window, const char *bufname, const char *fmtname)
{
  char *result;
  unsigned long ressize, restail;
  int resbits;
  Atom bufid = XInternAtom(display, bufname, False),
       fmtid = XInternAtom(display, fmtname, False),
       propid = XInternAtom(display, "XSEL_DATA", False),
       incrid = XInternAtom(display, "INCR", False);
  XEvent event;

  XConvertSelection(display, bufid, fmtid, propid, window, CurrentTime);
  do {
    XNextEvent(display, &event);
  } while (event.type != SelectionNotify || event.xselection.selection != bufid);

  if (event.xselection.property)
  {
    XGetWindowProperty(display, window, propid, 0, LONG_MAX/4, False, AnyPropertyType,
      &fmtid, &resbits, &ressize, &restail, (unsigned char**)&result);

    if (fmtid == incrid)
      printf("Buffer is too large and INCR reading is not implemented yet.\n");
    else
      printf("%.*s", (int)ressize, result);

    XFree(result);
    return True;
  }
  else // request failed, e.g. owner can't convert to the target format
    return False;
}

int main()
{
  Display *display = XOpenDisplay(NULL);
  unsigned long color = BlackPixel(display, DefaultScreen(display));
  Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0,0, 1,1, 0, color, color);
  Bool result = PrintSelection(display, window, "CLIPBOARD", "UTF8_STRING") ||
                PrintSelection(display, window, "CLIPBOARD", "STRING");
  XDestroyWindow(display, window);
  XCloseDisplay(display);
  return !result;
}


问:
OpenAPI Generator generates generic Parameter names
I'm currently experiencing a struggle with the OpenAPI Generator Plugin in Gradle.
When I generate a new API Interface with the following settings in my build.gradle:

```<code>openApiGenerate {
    generatorName = "spring"
    inputSpec = "$rootDir/src/main/resources/api.yaml".toString()
    outputDir = "$buildDir".toString()
    apiPackage = "<package name>"
    configOptions = [
            interfaceOnly     : "true",
            library           : "spring-cloud",
            skipDefaultInterface: "true",
            modelPackage      : "<package name>",
            apiPackage: "<package name>",
            serializableModel: "true",
            useOptional: "true",
    ]
}
</code>```

The output API Interface uses generic Parameter names. For example var1, var2 and so on.
Example:

ResponseEntity<Void> deleteOrganisationById(@ApiParam(value = "Mandant",required = true) @RequestHeader(value = "MANDANT",required = true) BigDecimal var1, @ApiParam(value = "ID of the organisation to be deleted",required = true) @PathVariable("id") String var2);
```

How can I change this so it uses some kind of talking names for the parameters? E.g. mandant for the MANDANT parameter etc.?

答:
Which version are you using?

Using openapi.generator 5.3.0 with gradle 7.2 the var names match the spec file

```<code>id "org.openapi.generator" version "5.3.0"
</code>```

And the api model.yaml

  parameters:
    - name: mandant
    required: true

```

Body:
I'm currently experiencing a struggle with the OpenAPI Generator Plugin in Gradle.
When I generate a new API Interface with the following settings in my build.gradle:

openApiGenerate {
    generatorName = "spring"
    inputSpec = "$rootDir/src/main/resources/api.yaml".toString()
    outputDir = "$buildDir".toString()
    apiPackage = "<package name>"
    configOptions = [
            interfaceOnly     : "true",
            library           : "spring-cloud",
            skipDefaultInterface: "true",
            modelPackage      : "<package name>",
            apiPackage: "<package name>",
            serializableModel: "true",
            useOptional: "true",
    ]
}

The output API Interface uses generic Parameter names. For example var1, var2 and so on.
Example:

ResponseEntity<Void> deleteOrganisationById(@ApiParam(value = "Mandant",required = true) @RequestHeader(value = "MANDANT",required = true) BigDecimal var1, @ApiParam(value = "ID of the organisation to be deleted",required = true) @PathVariable("id") String var2);

How can I change this so it uses some kind of talking names for the parameters? E.g. mandant for the MANDANT parameter etc.?

Body:
Which version are you using?

Using openapi.generator 5.3.0 with gradle 7.2 the var names match the spec file

id "org.openapi.generator" version "5.3.0"

And the api model.yaml

  parameters:
    - name: mandant
    required: true


问:
(network sockets) bytes stuck in Send Queue for 15 minutes; why?
I have a Java program running on Windows (a Citrix machine), that dispatches a request to Java application servers on Linux; this dispatching mechanism is all custom.

The Windows Java program (let's call it W) opens a listen socket to a port given by the OS, say 1234 to receive results.  Then it invokes a "dispatch" service on the server with a "business request". This service splits the request and sends it to other servers (let's call them S1 ... Sn), and returns the number of jobs to the client synchronously.

In my tests, there are 13 jobs, dispatched to a number of servers and within 2 seconds, all servers have finished processing their jobs and try to send the results back to the W's socket.

I can see in the logs that 9 jobs are received by W (this number varies from test to test). So, I try to look for the 4 remaining jobs.  If I do a netstat on this Windows box, I see that 4 sockets are open:

```<code>TCP    W:4373       S5:48197  ESTABLISHED
TCP    W:4373       S5:48198  ESTABLISHED
TCP    W:4373       S6:57642  ESTABLISHED
TCP    W:4373       S7:48295  ESTABLISHED
</code>```

If I do a thread dump of W, I see 4 threads trying to read from these sockets, and apparently stuck in java.net.SocketInputStream.socketRead0(Native Method).

If I go on each of the S boxes and do a netstat, I see that some bytes are still in the Send Queue. This number of bytes does not move for 15 minutes. (The following is the aggregation of netstats on the different machines):

```<code>Proto Recv-Q Send-Q Local Address               Foreign Addr   State
tcp        0   6385 S1:48197                          W:4373   ESTABLISHED
tcp        0   6005 S1:48198                          W:4373   ESTABLISHED
tcp        0   6868 S6:57642                          W:4373   ESTABLISHED
tcp        0   6787 S7:48295                          W:4373   ESTABLISHED
</code>```

If I do a thread dump of the servers, I see the threads are also stuck in
java.net.SocketInputStream.socketRead0(Native Method).  I would expect a write, but maybe they're waiting for an ACK? (Not sure here; would it show in Java? Shouldn't it be handled by the TCP protocol directly?)

Now, the very strange thing is: after 15 minutes (and it's always 15 minutes), the results are received, sockets are closed, and everything continues as normal.

This used to always work before. The S servers moved to a different data center, so W and S are no longer in the same data center. Also, S is behind a firewall. All ports should be authorized between S and W (I'm told). The mystery is really the 15 minute delay. I thought that it could be some protection against DDOS?

I'm no network expert so I asked for help, but nobody's available to help me. I spent 30 minutes with a guy capturing packets with Wireshark (formerly Ethereal), but for "security reasons," I cannot look at the result. He has to analyze this and get back to me. I asked for the firewall logs; same story.

I'm not root or administrator on these boxes, now I don't know what to do... I'm not expecting a solution from you guys, but some ideas on how to progress would be great!

答:
If it worked ok in your local network, then I don't envisage this being a programming issue (re. the flush() comments).

Is network connectivity between the 2 machines normal otherwise ? Can you transfer similar quantities of data via (say) FTP with no problem. Can you replicate this issue by knocking together a client/server script just to send appropriately sized chunks of data. i.e. is the network connectivity good between W and S ?

Another question. You now have a firewall inbetween. Could this be a possible bottleneck that wasn't there before ? (not sure how that would explain the consistent 15m delay though).

Final question. What are your TCP configuration parameters set up to be (on both W and S - I'm thinking about the OS-level parameters). Is there anything there that would suggest or lead to a 15m figure.

Not sure if that's any help.

OwnerDisplayName: Nicolas

ContentLicense: CC BY-SA 2.5

Body:
I have a Java program running on Windows (a Citrix machine), that dispatches a request to Java application servers on Linux; this dispatching mechanism is all custom.

The Windows Java program (let's call it W) opens a listen socket to a port given by the OS, say 1234 to receive results.  Then it invokes a "dispatch" service on the server with a "business request". This service splits the request and sends it to other servers (let's call them S1 ... Sn), and returns the number of jobs to the client synchronously.

In my tests, there are 13 jobs, dispatched to a number of servers and within 2 seconds, all servers have finished processing their jobs and try to send the results back to the W's socket.

I can see in the logs that 9 jobs are received by W (this number varies from test to test). So, I try to look for the 4 remaining jobs.  If I do a netstat on this Windows box, I see that 4 sockets are open:

TCP    W:4373       S5:48197  ESTABLISHED
TCP    W:4373       S5:48198  ESTABLISHED
TCP    W:4373       S6:57642  ESTABLISHED
TCP    W:4373       S7:48295  ESTABLISHED

If I do a thread dump of W, I see 4 threads trying to read from these sockets, and apparently stuck in java.net.SocketInputStream.socketRead0(Native Method).

If I go on each of the S boxes and do a netstat, I see that some bytes are still in the Send Queue. This number of bytes does not move for 15 minutes. (The following is the aggregation of netstats on the different machines):

Proto Recv-Q Send-Q Local Address               Foreign Addr   State
tcp        0   6385 S1:48197                          W:4373   ESTABLISHED
tcp        0   6005 S1:48198                          W:4373   ESTABLISHED
tcp        0   6868 S6:57642                          W:4373   ESTABLISHED
tcp        0   6787 S7:48295                          W:4373   ESTABLISHED

If I do a thread dump of the servers, I see the threads are also stuck in
java.net.SocketInputStream.socketRead0(Native Method).  I would expect a write, but maybe they're waiting for an ACK? (Not sure here; would it show in Java? Shouldn't it be handled by the TCP protocol directly?)

Now, the very strange thing is: after 15 minutes (and it's always 15 minutes), the results are received, sockets are closed, and everything continues as normal.

This used to always work before. The S servers moved to a different data center, so W and S are no longer in the same data center. Also, S is behind a firewall. All ports should be authorized between S and W (I'm told). The mystery is really the 15 minute delay. I thought that it could be some protection against DDOS?

I'm no network expert so I asked for help, but nobody's available to help me. I spent 30 minutes with a guy capturing packets with Wireshark (formerly Ethereal), but for "security reasons," I cannot look at the result. He has to analyze this and get back to me. I asked for the firewall logs; same story.

I'm not root or administrator on these boxes, now I don't know what to do... I'm not expecting a solution from you guys, but some ideas on how to progress would be great!

LastEditorDisplayName: Eddie

OwnerDisplayName: Brian Agnew


问:
Azure machine learning unable to load pytorch Model from the outputs folder
I am unable to load saved pytorch model from the outputs folder in my other scripts.
I am using following lines of code to save the model:

```<code>    os.makedirs("./outputs/model", exist_ok=True)

    torch.save({
        'model_state_dict': copy.deepcopy(model.state_dict()),
        'optimizer_state_dict': optimizer.state_dict()
        }, './outputs/model/best-model.pth')

    new_run.upload_file("outputs/model/best-model.pth", "outputs/model/best-model.pth")
    saved_model = new_run.register_model(model_name='pytorch-model', model_path='outputs/model/best-model.pth')
</code>```

and using the following code to access it:

```<code>global model
best_model_path = 'outputs/model/best-model.pth'
model_checkpoint = torch.load(best_model_path)
model.load_state_dict(model_checkpoint['model_state_dict'], strict = False)
</code>```

but when I run the above mentioned code, I get this error: No such file or directory: './outputs/model/best-model.pth'

Also I want to know is there a way to get the saved model from Azure Models? I have tried to get it by using following lines of code:

```<code>from azureml.core.model import Model
model = Model(ws, "Pytorch-model")
</code>```

but it returns Model type object which returns error on model.eval() (error: Model has no such attribute eval()).

答:
There is no global output folder. If you want to use a Model in a new script you need to give the script the model as an input or register the model and download the model from the new script.

The Model object form from azureml.core.model import Model is not your pytorch Model. 1

You can use model.register(...) to register your model. And model.download(...) to download you model. Than you can use pytorch to load you model. 2

Body:
I am unable to load saved pytorch model from the outputs folder in my other scripts.
I am using following lines of code to save the model:

    os.makedirs("./outputs/model", exist_ok=True)

    torch.save({
        'model_state_dict': copy.deepcopy(model.state_dict()),
        'optimizer_state_dict': optimizer.state_dict()
        }, './outputs/model/best-model.pth')

    new_run.upload_file("outputs/model/best-model.pth", "outputs/model/best-model.pth")
    saved_model = new_run.register_model(model_name='pytorch-model', model_path='outputs/model/best-model.pth')

and using the following code to access it:

global model
best_model_path = 'outputs/model/best-model.pth'
model_checkpoint = torch.load(best_model_path)
model.load_state_dict(model_checkpoint['model_state_dict'], strict = False)

but when I run the above mentioned code, I get this error: No such file or directory: './outputs/model/best-model.pth'

Also I want to know is there a way to get the saved model from Azure Models? I have tried to get it by using following lines of code:

from azureml.core.model import Model
model = Model(ws, "Pytorch-model")

but it returns Model type object which returns error on model.eval() (error: Model has no such attribute eval()).


问:
Doom-like face system using unity UI
As you can see in the code below , i have a OnGUI  method that "draws" texture depending on the number i give to this method . is there a way to do this by using unity's UI  system instead of GUI ? I've tried to do it myself , but was not able to make a method that would change the image on the screen depending on the given number .</p>
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FaceSystem : MonoBehaviour
{
    // HP = HitPoints, SHT = While Shooting, DMG = While taking damage
    // FW = Forward, L = Left, R = Right
    // Numbers are the HP ranges for the different faces

    public Texture2D HP80100FW;
    public Texture2D HP80100L;
    public Texture2D HP80100R;

    public Texture2D HP6079FW;
    public Texture2D HP6079L;
    public Texture2D HP60790R;

    public Texture2D HP4059FW;
    public Texture2D HP4059L;
    public Texture2D HP4059R;

    public Texture2D HP2039FW;
    public Texture2D HP2039L;
    public Texture2D HP2039R;

    public Texture2D HP119FW;
    public Texture2D HP119L;
    public Texture2D HP119R;

    public Texture2D HP0;

    public Texture2D SHT80100;
    public Texture2D SHT6079;
    public Texture2D SHT4059;
    public Texture2D SHT2039;
    public Texture2D SHT119;

    public Texture2D DMG80100;
    public Texture2D DMG6079;
    public Texture2D DMG4059;
    public Texture2D DMG2039;
    public Texture2D DMG119;

    int pick;

    Texture2D[] imgs;
    int i;
    float timer;

    public PlayerHealth PlayerHealth;
    public Image healthIndicator;
    public Sprite madddead;
    void Start()
    {
        // have every image in an array for easy access

        imgs = new Texture2D[26];

        imgs[0] = HP80100FW;
        imgs[1] = HP80100L;
        imgs[2] = HP80100R;

        imgs[3] = HP6079FW;
        imgs[4] = HP6079L;
        imgs[5] = HP60790R;

        imgs[6] = HP4059FW;
        imgs[7] = HP4059L;
        imgs[8] = HP4059R;

        imgs[9] = HP2039FW;
        imgs[10] = HP2039L;
        imgs[11] = HP2039R;

        imgs[12] = HP119FW;
        imgs[13] = HP119L;
        imgs[14] = HP119R;

        imgs[15] = HP0;

        imgs[16] = SHT80100;
        imgs[17] = SHT6079;
        imgs[18] = SHT4059;
        imgs[19] = SHT2039;
        imgs[20] = SHT119;

        imgs[21] = DMG80100;
        imgs[22] = DMG6079;
        imgs[23] = DMG4059;
        imgs[24] = DMG2039;
        imgs[25] = DMG119;
    }

    void Update()
    {
        Faces();
    }

    public void Faces()
    {
        timer -= Time.deltaTime;

        // modify the timers to your liking

        if (PlayerHealth.health >= 80 & PlayerHealth.health <= 100 || PlayerHealth.health >100)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 16;
            }

            if (PlayerHealth.isDamaged == true)   // add a bool for when damaged in your health script!
            {
                timer = 0.5f;
                pick = 21;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(0, 3);
                }

            }
        }
        if (PlayerHealth.health >= 60 & PlayerHealth.health <= 79)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 17;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 22;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(3, 6);
                }
            }
        }
        if (PlayerHealth.health >= 40 & PlayerHealth.health <= 59)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 18;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 23;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(6, 9);
                }
            }
        }
        if (PlayerHealth.health >= 20 & PlayerHealth.health <= 39)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 19;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 24;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(9, 12);
                }
            }
        }
        if (PlayerHealth.health >= 1 & PlayerHealth.health <= 19)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 20;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 25;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(12, 15);
                }
            }
        }
        if (PlayerHealth.health <= 0)
        {
            pick = 15;
        }
    }

    private void OnGUI()
    {
        if(PlayerHealth.health >0)
        {
             GUI.DrawTexture(new Rect(695,830, 515, 315), imgs[pick]);
        }
        else
        {
            healthIndicator.sprite= madddead;
        }
    }
}
</code>```

答:
Pseudo-algorithm:

create your interface with UI, add either Image or RawImage, depending your input

sprite for Image, texture for RawImage

add in your behavior a property, i.e. Image or RawImage and assign it in the inspector

your behavior now knows which UI control to assign an image to

do your logic and set that UI control image accordingly

https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-Image.html
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-RawImage.html

Title: Doom-like face system using unity UI

Body:
As you can see in the code below , i have a OnGUI  method that "draws" texture depending on the number i give to this method . is there a way to do this by using unity's UI  system instead of GUI ? I've tried to do it myself , but was not able to make a method that would change the image on the screen depending on the given number .

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FaceSystem : MonoBehaviour
{
    // HP = HitPoints, SHT = While Shooting, DMG = While taking damage
    // FW = Forward, L = Left, R = Right
    // Numbers are the HP ranges for the different faces

    public Texture2D HP80100FW;
    public Texture2D HP80100L;
    public Texture2D HP80100R;

    public Texture2D HP6079FW;
    public Texture2D HP6079L;
    public Texture2D HP60790R;

    public Texture2D HP4059FW;
    public Texture2D HP4059L;
    public Texture2D HP4059R;

    public Texture2D HP2039FW;
    public Texture2D HP2039L;
    public Texture2D HP2039R;

    public Texture2D HP119FW;
    public Texture2D HP119L;
    public Texture2D HP119R;

    public Texture2D HP0;

    public Texture2D SHT80100;
    public Texture2D SHT6079;
    public Texture2D SHT4059;
    public Texture2D SHT2039;
    public Texture2D SHT119;

    public Texture2D DMG80100;
    public Texture2D DMG6079;
    public Texture2D DMG4059;
    public Texture2D DMG2039;
    public Texture2D DMG119;

    int pick;

    Texture2D[] imgs;
    int i;
    float timer;

    public PlayerHealth PlayerHealth;
    public Image healthIndicator;
    public Sprite madddead;
    void Start()
    {
        // have every image in an array for easy access

        imgs = new Texture2D[26];

        imgs[0] = HP80100FW;
        imgs[1] = HP80100L;
        imgs[2] = HP80100R;

        imgs[3] = HP6079FW;
        imgs[4] = HP6079L;
        imgs[5] = HP60790R;

        imgs[6] = HP4059FW;
        imgs[7] = HP4059L;
        imgs[8] = HP4059R;

        imgs[9] = HP2039FW;
        imgs[10] = HP2039L;
        imgs[11] = HP2039R;

        imgs[12] = HP119FW;
        imgs[13] = HP119L;
        imgs[14] = HP119R;

        imgs[15] = HP0;

        imgs[16] = SHT80100;
        imgs[17] = SHT6079;
        imgs[18] = SHT4059;
        imgs[19] = SHT2039;
        imgs[20] = SHT119;

        imgs[21] = DMG80100;
        imgs[22] = DMG6079;
        imgs[23] = DMG4059;
        imgs[24] = DMG2039;
        imgs[25] = DMG119;
    }

    void Update()
    {
        Faces();
    }

    public void Faces()
    {
        timer -= Time.deltaTime;

        // modify the timers to your liking

        if (PlayerHealth.health >= 80 & PlayerHealth.health <= 100 || PlayerHealth.health >100)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 16;
            }

            if (PlayerHealth.isDamaged == true)   // add a bool for when damaged in your health script!
            {
                timer = 0.5f;
                pick = 21;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(0, 3);
                }

            }
        }
        if (PlayerHealth.health >= 60 & PlayerHealth.health <= 79)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 17;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 22;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(3, 6);
                }
            }
        }
        if (PlayerHealth.health >= 40 & PlayerHealth.health <= 59)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 18;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 23;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(6, 9);
                }
            }
        }
        if (PlayerHealth.health >= 20 & PlayerHealth.health <= 39)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 19;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 24;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(9, 12);
                }
            }
        }
        if (PlayerHealth.health >= 1 & PlayerHealth.health <= 19)
        {
            if (Input.GetMouseButton(0))
            {
                timer = 1f;
                pick = 20;
            }

            if (PlayerHealth.isDamaged == true)
            {
                timer = 0.5f;
                pick = 25;
            }

            if (timer < 0 & !Input.GetMouseButton(0))
            {
                timer = 1.5f;

                // get a random number not equal to current
                i = pick;
                while (i == pick)
                {
                    pick = Random.Range(12, 15);
                }
            }
        }
        if (PlayerHealth.health <= 0)
        {
            pick = 15;
        }
    }

    private void OnGUI()
    {
        if(PlayerHealth.health >0)
        {
             GUI.DrawTexture(new Rect(695,830, 515, 315), imgs[pick]);
        }
        else
        {
            healthIndicator.sprite= madddead;
        }
    }
}


答: From the code you have posted, it doesn't require the boolean parameter at all, you could remove it from the method signature and see if you code still compiles.</p>

Body:
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?

RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }


问:
Android 12 BLE always returning status 0 on disconnect
When testing with an Android 12 device whenever my Bluetooth device disconnects I receive a status 0 regardless if I disconnect programmatically or the device went out of range. From my understanding in previous Android versions status 0 is programmatically disconnected and status 8 was for device went out of range.

```<code> return object : BluetoothGattCallback() {

            override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
                val name = gatt.device.name
                Log.i("onConnectionStateChange", name + "\t" + status + "\t" + newState)

                when (newState) {
                    BluetoothGatt.STATE_CONNECTED -> {
                        gatt.discoverServices()
                    }
                    BluetoothGatt.STATE_CONNECTING -> {

                    }
                    BluetoothGatt.STATE_DISCONNECTED -> {
                    }
                    BluetoothGatt.STATE_DISCONNECTING ->  {
                        // status 0 (Programmatically disconnected)
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            // Always going in here
                          ...
                        }
                        // Deivce went out of range
                        else if(status == 8){
                           // Never in here
                          ...
                        }
                    }

                }

            }

          override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
                    super.onServicesDiscovered(gatt, status)
            }
}
</code>```

Has anyone face this same problem and figured out how to get the status to show correctly or found another way to determine if it was device out of range or a disconnect programmatically?

答:
This is a general problem/change on Android 12, 12L and 13 DP :(
I have filed a bugreport to AOSP regarding this, but there is not really any feedback from Google.
https://issuetracker.google.com/issues/207323675

If you look in the HCI logs you can still see the disconnect reason, but as you have also found out it is no longer passed on to apps.
Except for status=133 when a direct connect times out.

So maybe Google has started cleaning up the mess of mixing internal status codes (like 133) with BLE disconnect reasons?
The question is of course then: Where can then get the disconnect reasons?

Body:
When testing with an Android 12 device whenever my Bluetooth device disconnects I receive a status 0 regardless if I disconnect programmatically or the device went out of range. From my understanding in previous Android versions status 0 is programmatically disconnected and status 8 was for device went out of range.

 return object : BluetoothGattCallback() {

            override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
                val name = gatt.device.name
                Log.i("onConnectionStateChange", name + "\t" + status + "\t" + newState)

                when (newState) {
                    BluetoothGatt.STATE_CONNECTED -> {
                        gatt.discoverServices()
                    }
                    BluetoothGatt.STATE_CONNECTING -> {

                    }
                    BluetoothGatt.STATE_DISCONNECTED -> {
                    }
                    BluetoothGatt.STATE_DISCONNECTING ->  {
                        // status 0 (Programmatically disconnected)
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            // Always going in here
                          ...
                        }
                        // Deivce went out of range
                        else if(status == 8){
                           // Never in here
                          ...
                        }
                    }

                }

            }

          override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
                    super.onServicesDiscovered(gatt, status)
            }
}

Has anyone face this same problem and figured out how to get the status to show correctly or found another way to determine if it was device out of range or a disconnect programmatically?


问:
jQuery and extending built-in elements
I am just looking into extending built-in elements for the first time and have some basic questions.

Let's say I want to extend a p element, assign it a class, and make it contenteditable. Is the following correct and ready-to-use?

```<code>      customElements.define('p-edit', pedit, { extends: 'p' });

      class pedit extends HTMLParagraphElement {
        constructor() {

            super();

            this.classList.add("foo");
            this.setAttribute("contenteditable",true);

        }
    }

</code>```

And would that pedit element be a valid jQuery selector? And would it be a match if the jQuery selector were 'p[contenteditable="true"]' ?

答:
Ditch Customized Built-In Elements and stick to Autonomous Elements extends HTMLElement.

Unless you want to rely on polyfills forever.

Apple has, since 2016, stated they never will implement Customized Built-In Elements in Safari.

source: https://github.com/WICG/webcomponents/issues/509

Title: jQuery and extending built-in elements

Body:
I am just looking into extending built-in elements for the first time and have some basic questions.

Let's say I want to extend a p element, assign it a class, and make it contenteditable. Is the following correct and ready-to-use?

      customElements.define('p-edit', pedit, { extends: 'p' });

      class pedit extends HTMLParagraphElement {
        constructor() {

            super();

            this.classList.add("foo");
            this.setAttribute("contenteditable",true);

        }
    }

And would that pedit element be a valid jQuery selector? And would it be a match if the jQuery selector were 'p[contenteditable="true"]' ?


问:
How to track at which point a variable gets changed?
I have a BOOL instance variable which -for some reason- some time later always reads NO even if I set it to YES (Yes, I am not so stupid to write or read the wrong variable, trust me). I spent an hour searching my whole project for any possibilities where that variable might be set to NO but can't find it.

Is there a way to trace changes of it's value, i.e. to let the debugger halt at exactly the position where the variable is about to be modified?

答: Can you structure your code so that this BOOL instance variable is a property? You could then write your own setter function for this property and then set a breakpoint in that setter function. The stack trace will tell you what called the setter method. Or you could use Key-Value Observing to watch for changes in that property at runtime in your app, but that adds more complexity.</p>