问:
Recyclerview layout in dialog box
I am facing a problem while opening recyclerview in a dialog box. The layout in the recyclerview is overlapping and cutting when I open this in a dialog box same like this:

But, my original layout is look like this:

and here is the code for my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:layout_marginBottom="14dp"
    android:elevation="10dp"
    android:padding="8dp"
    app:cardCornerRadius="8dp">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/corner_layout"
    android:paddingTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/r_field_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Admission No."
        android:textColor="#009EBB"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/r_d_field_name"
        app:layout_constraintStart_toStartOf="@+id/r_d_field_name"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/admission_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="45654"
        android:textColor="#555555"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/st_name"
        app:layout_constraintStart_toStartOf="@+id/st_name"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/r_d_field_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name"
        android:textColor="#009EBB"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toTopOf="@+id/p_a_field_name"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/r_field_name"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/st_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Harikant Sharma"
        android:textColor="#555555"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/st_father_mother_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/r_d_field_name"
        app:layout_constraintTop_toBottomOf="@+id/admission_no" />

    <TextView
        android:id="@+id/p_a_field_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parents Name"
        android:textColor="#009EBB"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/btn_call_st"
        app:layout_constraintStart_toStartOf="@+id/r_d_field_name"
        app:layout_constraintTop_toBottomOf="@+id/r_d_field_name"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/st_father_mother_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Suresh Kumar Sharma"
        android:textColor="#555555"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/btn_view_st_profile"
        app:layout_constraintStart_toStartOf="@+id/st_name"
        app:layout_constraintTop_toBottomOf="@+id/st_name" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_view_st_profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:src="@drawable/view"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/btn_call_st"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.9"
        app:tint="@color/white" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_call_st"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#E10751"
        android:gravity="center"

        android:src="@drawable/phone"
        app:layout_constraintBottom_toBottomOf="@+id/btn_view_st_profile"
        app:layout_constraintEnd_toStartOf="@+id/btn_view_st_profile"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/btn_view_st_profile"
        app:tint="@color/white" />

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>
</code>```

答:
If you constrain both left and right, you need to set width=0dp

```<code>  <TextView
            android:id="@+id/st_name"
            android:layout_width="0dp" <-- change to 0dp
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:text="Harikant Sharma"
            android:textColor="#555555"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/st_father_mother_name"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/r_d_field_name"
            app:layout_constraintTop_toBottomOf="@+id/admission_no" />
</code>```

Title: Recyclerview layout in dialog box

Body:
I am facing a problem while opening recyclerview in a dialog box. The layout in the recyclerview is overlapping and cutting when I open this in a dialog box same like this:

But, my original layout is look like this:

and here is the code for my layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:layout_marginBottom="14dp"
    android:elevation="10dp"
    android:padding="8dp"
    app:cardCornerRadius="8dp">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/corner_layout"
    android:paddingTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/r_field_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Admission No."
        android:textColor="#009EBB"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/r_d_field_name"
        app:layout_constraintStart_toStartOf="@+id/r_d_field_name"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/admission_no"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="45654"
        android:textColor="#555555"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/st_name"
        app:layout_constraintStart_toStartOf="@+id/st_name"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/r_d_field_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Student Name"
        android:textColor="#009EBB"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toTopOf="@+id/p_a_field_name"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/r_field_name"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/st_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:text="Harikant Sharma"
        android:textColor="#555555"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/st_father_mother_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/r_d_field_name"
        app:layout_constraintTop_toBottomOf="@+id/admission_no" />

    <TextView
        android:id="@+id/p_a_field_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parents Name"
        android:textColor="#009EBB"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/btn_call_st"
        app:layout_constraintStart_toStartOf="@+id/r_d_field_name"
        app:layout_constraintTop_toBottomOf="@+id/r_d_field_name"
        tools:ignore="RtlHardcoded" />

    <TextView
        android:id="@+id/st_father_mother_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Suresh Kumar Sharma"
        android:textColor="#555555"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/btn_view_st_profile"
        app:layout_constraintStart_toStartOf="@+id/st_name"
        app:layout_constraintTop_toBottomOf="@+id/st_name" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_view_st_profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="12dp"
        android:gravity="center"
        android:src="@drawable/view"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/btn_call_st"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.9"
        app:tint="@color/white" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_call_st"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#E10751"
        android:gravity="center"

        android:src="@drawable/phone"
        app:layout_constraintBottom_toBottomOf="@+id/btn_view_st_profile"
        app:layout_constraintEnd_toStartOf="@+id/btn_view_st_profile"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/btn_view_st_profile"
        app:tint="@color/white" />

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

Body:
If you constrain both left and right, you need to set width=0dp

  <TextView
            android:id="@+id/st_name"
            android:layout_width="0dp" <-- change to 0dp
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:text="Harikant Sharma"
            android:textColor="#555555"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/st_father_mother_name"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/r_d_field_name"
            app:layout_constraintTop_toBottomOf="@+id/admission_no" />


来源: stackexchange

问:
Linq - Order by deep property from string
I need to order a collection of data dynamically. I have this working at the top level:

```<code>//where prop is a string passed in, ex: "ShoeSize"
_clowns
    .AsEnumerable()
    .OrderBy(x => x.GetType().GetProperty(prop)?.GetValue(x))
    .Select(x => x.Id)
    .ToList();
</code>```

And that works so long as I only need to order by some property of Clowns. But what if I need to order Clowns by a property of their Car? I think I'm close, but can't clear the gap:

```<code>//for prop = "Car.ClownCapcity"
var queryBuilder = _clowns;
var orderProp = prop;
if (prop.Contains(".")){
    string[] props = prop.Split(".");
    foreach(string oneProp in props){
        if (props.Last() != oneProp){
            //this line is wrong for sure
            queryBuilder.Include(x => x.GetType().GetProperty(oneProp));
        } else {
            orderProp = oneProp;
        }
    }
}
queryBuilder.AsEnumerable()
    .OrderBy(x => x.GetType().GetProperty(orderProp)?.GetValue(x))
    .Select(x => x.Id)
    .ToList();
</code>```

This doesn't work because I cannot build up queryBuilder, reassigning at the Include doesn't work because the return type is different. I also haven't figured out how to dynamically go deeper inside the final OrderBy.

Is there a decent way to do this in Linq, or should I go build a SQL string?

There are security concerns, those can be handled elsewhere and aren't terribly relevant to this question

Update

Progress! Got it to work two-levels deep, but only when I explicitly know it's two-levels deep. I haven't figured out the abstraction yet.

```<code>if (prop.Contains(".")){
    string[] props = prop.Split(".");
    string includeProp = props.FirstOrDefault();
    string orderProp = props.LastOrDefault();
    return _Clowns
        .Include(includeProp)
        .AsEnumerable()
        .OrderBy(x => {
            var y = x.GetType().GetProperty(formattedProp)?.GetValue(x);

            return y?.GetType().GetProperty(orderProp)?.GetValue(y);
        })
        .Select(x => x.Id)
        .ToList();
}
</code>```

答:
Answering with my own solution. Please give me a better answer if I'm way over-complicating this.

```<code>if (prop.Contains(".")){
    string[] props = prop.Split(".");
    string includePath = prop.remove(prop.LastIndexOf("."));

    IQueryable<ClownModel> queryBuilder = _clowns.Include(includePath);

    return queryBuilder.
        .AsEnumerable()
        .OrderBy(x => {
            object y = x;
            foreach (var prop in props)
            {
                //avoid unnecessary depth checks if a null is found
                if (y == null)
                {
                    break;
                }
                //if we're dealing with a collection
                if (y?.GetType().Namespace == "System.Collections.Generic")
                {
                    //gets a HashMap<ModelType>
                    var o = (dynamic)y;
                    //can't access this HashMap with [0] or .First() though?
                    foreach(object m in o)
                    {
                        //cheat and iterate
                        y = m;
                        break;
                    }
                }
                y = y?.GetType().GetProperty(prop)?.GetValue(y);
            }
            return y;
        })
        .Select(x => x.Id)
        .ToList();
}
</code>```

My initial workup was wrong, it was still only working for 2-level deep. This works for any levels, and accounts for collections of properties along the way. Intriguingly, the Include function can take a dot-notation string (super handy), but not the OrderBy.

So pass in the Include, then loop through each property level inside the OrderBy, taking the first record if it's a collection.

Bing-bam-boom, you got a baby pachyderm. Back to you, Trent.

ContentLicense: CC BY-SA 4.0

Body:
I need to order a collection of data dynamically. I have this working at the top level:

//where prop is a string passed in, ex: "ShoeSize"
_clowns
    .AsEnumerable()
    .OrderBy(x => x.GetType().GetProperty(prop)?.GetValue(x))
    .Select(x => x.Id)
    .ToList();

And that works so long as I only need to order by some property of Clowns. But what if I need to order Clowns by a property of their Car? I think I'm close, but can't clear the gap:

//for prop = "Car.ClownCapcity"
var queryBuilder = _clowns;
var orderProp = prop;
if (prop.Contains(".")){
    string[] props = prop.Split(".");
    foreach(string oneProp in props){
        if (props.Last() != oneProp){
            //this line is wrong for sure
            queryBuilder.Include(x => x.GetType().GetProperty(oneProp));
        } else {
            orderProp = oneProp;
        }
    }
}
queryBuilder.AsEnumerable()
    .OrderBy(x => x.GetType().GetProperty(orderProp)?.GetValue(x))
    .Select(x => x.Id)
    .ToList();

This doesn't work because I cannot build up queryBuilder, reassigning at the Include doesn't work because the return type is different. I also haven't figured out how to dynamically go deeper inside the final OrderBy.

Is there a decent way to do this in Linq, or should I go build a SQL string?

There are security concerns, those can be handled elsewhere and aren't terribly relevant to this question

Update

Progress! Got it to work two-levels deep, but only when I explicitly know it's two-levels deep. I haven't figured out the abstraction yet.

if (prop.Contains(".")){
    string[] props = prop.Split(".");
    string includeProp = props.FirstOrDefault();
    string orderProp = props.LastOrDefault();
    return _Clowns
        .Include(includeProp)
        .AsEnumerable()
        .OrderBy(x => {
            var y = x.GetType().GetProperty(formattedProp)?.GetValue(x);

            return y?.GetType().GetProperty(orderProp)?.GetValue(y);
        })
        .Select(x => x.Id)
        .ToList();
}

Body:
Answering with my own solution. Please give me a better answer if I'm way over-complicating this.

if (prop.Contains(".")){
    string[] props = prop.Split(".");
    string includePath = prop.remove(prop.LastIndexOf("."));

    IQueryable<ClownModel> queryBuilder = _clowns.Include(includePath);

    return queryBuilder.
        .AsEnumerable()
        .OrderBy(x => {
            object y = x;
            foreach (var prop in props)
            {
                //avoid unnecessary depth checks if a null is found
                if (y == null)
                {
                    break;
                }
                //if we're dealing with a collection
                if (y?.GetType().Namespace == "System.Collections.Generic")
                {
                    //gets a HashMap<ModelType>
                    var o = (dynamic)y;
                    //can't access this HashMap with [0] or .First() though?
                    foreach(object m in o)
                    {
                        //cheat and iterate
                        y = m;
                        break;
                    }
                }
                y = y?.GetType().GetProperty(prop)?.GetValue(y);
            }
            return y;
        })
        .Select(x => x.Id)
        .ToList();
}

My initial workup was wrong, it was still only working for 2-level deep. This works for any levels, and accounts for collections of properties along the way. Intriguingly, the Include function can take a dot-notation string (super handy), but not the OrderBy.

So pass in the Include, then loop through each property level inside the OrderBy, taking the first record if it's a collection.

Bing-bam-boom, you got a baby pachyderm. Back to you, Trent.


问:
check pattern with DictReader in python
i have a csv file like this :

```<code>    vahid,ajorloo,vahidlogin,ajorloo32@gmail.com,12345
    james,statham,jameslogin,jamesmail@gmail.com,1245844
    john,patinson,johnlogin,wrong-email-format,412541
    ali,mahdavi,alilogin,ali@gmail.com
</code>```

i wrote this code :

```<code>import csv

fieldnames = ['first-name', 'last-name', 'login', 'email', 'password']

with open('list.csv', 'r') as f:
    csvreader = csv.DictReader(f, fieldnames)
    for i in csvreader:
     print(i)
</code>```

the result is:

```<code>{'first-name': 'vahid', 'last-name': 'ajorloo', 'login': 'ajorloo32', 'email': 'ajorloo32@gmail.com', 'password': '12345'}
{'first-name': 'james', 'last-name': 'statham', 'login': 'jameslogin', 'email': 'jamesmail@gmail.com', 'password': '1245844'}
{'first-name': 'john', 'last-name': 'patinson', 'login': 'johnlogin', 'email': 'wrong-email-format', 'password': '412541'}
{'first-name': 'ali', 'last-name': 'mahdavi', 'login': 'alilogin', 'email': 'ali@gmail.com', 'password': None}
</code>```

in the third line we have a wrong email format like mymail.com or my@mail without .com or any other wrong format.
in the last line the user didnt provide a password or maybe he just forgot that and leave it blank

i want to write a code that allows the program to tell me which input is missing and if the emails are wrong formatted show them so i can fix them.

im new to the programming world and this is the first program that im writing,i just need some guidance,is there any module for this kind of program that im building?

答:
You can check if the value is missting or not using if statement.

In addition, you can check email validation using regular expression. (You can see how to use regular expression to find email pattern: https://www.c-sharpcorner.com/article/how-to-validate-an-email-address-in-python/)

Following code will print every missing value or invalid email as you want.

```<code>import csv
import re

email_pattern = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
fieldnames = ['first-name', 'last-name', 'login', 'email', 'password']

with open('list.csv', 'r') as f:
    csvreader = csv.DictReader(f, fieldnames)
    for i, item in enumerate(csvreader):
        if not item['first-name']:
            print(f'line {i+1}, No first-name')
        if not item['last-name']:
            print(f'line {i+1}, No last-name')
        if not item['login']:
            print(f'line {i+1}, No login')
        if not item['email']:
            print(f'line {i+1}, No email')
        if not re.search(email_pattern, item['email']):
            print(f'line {i+1}, Invalid Email: {item["email"]}')
        if not item['password']:
            print(f'line {i+1}, No password')

#line 3, Invalid Email: wrong-email-format
#line 4, No password
</code>```

Title: check pattern with DictReader in python

Body:
i have a csv file like this :

    vahid,ajorloo,vahidlogin,ajorloo32@gmail.com,12345
    james,statham,jameslogin,jamesmail@gmail.com,1245844
    john,patinson,johnlogin,wrong-email-format,412541
    ali,mahdavi,alilogin,ali@gmail.com

i wrote this code :

import csv

fieldnames = ['first-name', 'last-name', 'login', 'email', 'password']

with open('list.csv', 'r') as f:
    csvreader = csv.DictReader(f, fieldnames)
    for i in csvreader:
     print(i)

the result is:

{'first-name': 'vahid', 'last-name': 'ajorloo', 'login': 'ajorloo32', 'email': 'ajorloo32@gmail.com', 'password': '12345'}
{'first-name': 'james', 'last-name': 'statham', 'login': 'jameslogin', 'email': 'jamesmail@gmail.com', 'password': '1245844'}
{'first-name': 'john', 'last-name': 'patinson', 'login': 'johnlogin', 'email': 'wrong-email-format', 'password': '412541'}
{'first-name': 'ali', 'last-name': 'mahdavi', 'login': 'alilogin', 'email': 'ali@gmail.com', 'password': None}

in the third line we have a wrong email format like mymail.com or my@mail without .com or any other wrong format.
in the last line the user didnt provide a password or maybe he just forgot that and leave it blank

i want to write a code that allows the program to tell me which input is missing and if the emails are wrong formatted show them so i can fix them.

im new to the programming world and this is the first program that im writing,i just need some guidance,is there any module for this kind of program that im building?

Body:
You can check if the value is missting or not using if statement.

In addition, you can check email validation using regular expression. (You can see how to use regular expression to find email pattern: https://www.c-sharpcorner.com/article/how-to-validate-an-email-address-in-python/)

Following code will print every missing value or invalid email as you want.

import csv
import re

email_pattern = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
fieldnames = ['first-name', 'last-name', 'login', 'email', 'password']

with open('list.csv', 'r') as f:
    csvreader = csv.DictReader(f, fieldnames)
    for i, item in enumerate(csvreader):
        if not item['first-name']:
            print(f'line {i+1}, No first-name')
        if not item['last-name']:
            print(f'line {i+1}, No last-name')
        if not item['login']:
            print(f'line {i+1}, No login')
        if not item['email']:
            print(f'line {i+1}, No email')
        if not re.search(email_pattern, item['email']):
            print(f'line {i+1}, Invalid Email: {item["email"]}')
        if not item['password']:
            print(f'line {i+1}, No password')

#line 3, Invalid Email: wrong-email-format
#line 4, No password


问:
Angular Material Icons Not Rendering Within Component
I've used Angular Material Icons on multiple projects and they work just fine. For some reason they don't currently work on my new project.

Here's my package.json file within node_modules/@angular/material/icons...

```<code>{
  "name": "@angular/material/icon",
  "fesm2020": "../fesm2020/icon.mjs",
  "fesm2015": "../fesm2015/icon.mjs",
  "esm2020": "../esm2020/icon/icon_public_index.mjs",
  "typings": "./icon_public_index.d.ts",
  "module": "../fesm2015/icon.mjs",
  "es2020": "../fesm2020/icon.mjs"
}
</code>```

Here is my app.module...

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule } from './material.module';

import { AppRoutingModule } from './app-routing.module';

import { SharedModule } from './shared/shared.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    AppRoutingModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

Here's my module where I house my material imports...

```<code>import { NgModule } from "@angular/core";

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ]
})
export class MaterialModule {}
</code>```

My component where I'm trying to use icons...

```<code>// The below code simply results in the word "menu" rather than the icon

<mat-toolbar>
    <a routerLink="/home">
        <mat-icon>menu</mat-icon>
    </a>
</mat-toolbar>
</code>```

Here is my index.html...

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Eventer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
  <app-root></app-root>
</body>
</html>

</code>```

UPDATE

This might have something to do with this weird, incomplete installation (since some Material items work, but not the icons). When I create a new project, I'll attempt to go through the Getting Started guide and use ng add @angular/material, but I get the following kick-back...

```<code>$ ng add @angular/material
- Determining package manager...
i Using package manager: npm
- Searching for compatible package version...
ΓêÜ Found compatible package version: @angular/material@13.2.1.
- Loading package information from registry...
ΓêÜ Package information loaded.
No terminal detected. '--skip-confirmation' can be used to bypass installation confirmation. Ensure package name is correct prior to '--skip-confirmation' option usage.
Command aborted.
</code>```

In these cases I have to go through and use npm commands to manually install items and this could be why my Material icons are not working. Anyone have any knowledge on why I'm getting the above message when attempting to use ng add?

Thank you.

答:
Check if you have

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=swap" rel="stylesheet">
</code>```

in the head of your index.html

Body:
I've used Angular Material Icons on multiple projects and they work just fine. For some reason they don't currently work on my new project.

Here's my package.json file within node_modules/@angular/material/icons...

{
  "name": "@angular/material/icon",
  "fesm2020": "../fesm2020/icon.mjs",
  "fesm2015": "../fesm2015/icon.mjs",
  "esm2020": "../esm2020/icon/icon_public_index.mjs",
  "typings": "./icon_public_index.d.ts",
  "module": "../fesm2015/icon.mjs",
  "es2020": "../fesm2020/icon.mjs"
}

Here is my app.module...

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MaterialModule } from './material.module';

import { AppRoutingModule } from './app-routing.module';

import { SharedModule } from './shared/shared.module';

import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';

@NgModule({
  declarations: [
    AppComponent,
    NavComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    MaterialModule,
    AppRoutingModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's my module where I house my material imports...

import { NgModule } from "@angular/core";

import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatIconModule } from '@angular/material/icon';

@NgModule({
    imports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ],
    exports: [
        MatCardModule,
        MatButtonModule,
        MatToolbarModule,
        MatIconModule
    ]
})
export class MaterialModule {}

My component where I'm trying to use icons...

// The below code simply results in the word "menu" rather than the icon

<mat-toolbar>

        <mat-icon>menu</mat-icon>

</mat-toolbar>

Here is my index.html...

<!doctype html>

  <meta charset="utf-8">
  <title>Eventer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <app-root></app-root>

UPDATE

This might have something to do with this weird, incomplete installation (since some Material items work, but not the icons). When I create a new project, I'll attempt to go through the Getting Started guide and use ng add @angular/material, but I get the following kick-back...

$ ng add @angular/material
- Determining package manager...
i Using package manager: npm
- Searching for compatible package version...
ΓêÜ Found compatible package version: @angular/material@13.2.1.
- Loading package information from registry...
ΓêÜ Package information loaded.
No terminal detected. '--skip-confirmation' can be used to bypass installation confirmation. Ensure package name is correct prior to '--skip-confirmation' option usage.
Command aborted.

In these cases I have to go through and use npm commands to manually install items and this could be why my Material icons are not working. Anyone have any knowledge on why I'm getting the above message when attempting to use ng add?

Thank you.

Body:
Check if you have

<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=swap" rel="stylesheet">

in the head of your index.html


问:
Computing hessian with pydrake autodiff
One of Drake's selling points is the easy availability of gradients via AutoDiff, but I'm struggling to see how to easily compute second-order derivatives in pydrake.

Given a function f(x), I know of two ways to compute the Jacobian. The first way uses the forwarddiff.jacobian helper function, e.g.:

```<code>def f(x):
    return x.T@x

x = np.array([1,2,3])
fx = jacobian(f,x)     # = [2,4,6]
</code>```

The second way uses the autodiffutils bindings more directly:

```<code>x = InitializeAutoDiff([1,2,3])
y = f(x)
fx = ExtractGradient(y)   # = [2,4,6]
</code>```

Are there similar ways to get the Hessian? Nested calls to the jacobian helper function don't work, since the second argument can't be an AutoDiffXd type. But perhaps there is some way more analogous to the second method above?

答: The current recommended answer is to use symbolic::Expression instead of AutoDiffXd when you need more than one derivative.  While all of our C++ code should work if it was compiled with AutoDiffX<AutoDiffXd> to provide second derivatives, we currently don't build those as one of our default scalar types in libdrake.so.

Title: Computing hessian with pydrake autodiff

Body:
One of Drake's selling points is the easy availability of gradients via AutoDiff, but I'm struggling to see how to easily compute second-order derivatives in pydrake.

Given a function f(x), I know of two ways to compute the Jacobian. The first way uses the forwarddiff.jacobian helper function, e.g.:

def f(x):
    return x.T@x

x = np.array([1,2,3])
fx = jacobian(f,x)     # = [2,4,6]

The second way uses the autodiffutils bindings more directly:

x = InitializeAutoDiff([1,2,3])
y = f(x)
fx = ExtractGradient(y)   # = [2,4,6]

Are there similar ways to get the Hessian? Nested calls to the jacobian helper function don't work, since the second argument can't be an AutoDiffXd type. But perhaps there is some way more analogous to the second method above?


问:
Can't exclude multiple authors in github search
I'm trying to filter out multiple authors:

```<code>is:pr is:open -author:Marcono1234 -author:rdmarsh2
</code>```

But only the first filter is applied, is it supported? https://github.com/github/codeql/pulls?q=is%3Apr+is%3Aopen+-author%3AMarcono1234+-author%3Ardmarsh2+

答:
Ensure that you are using the full search at the top left box, Otherwise, the search syntax will be severely limited.

Step1:

Step2:

Body:
I'm trying to filter out multiple authors:

is:pr is:open -author:Marcono1234 -author:rdmarsh2

But only the first filter is applied, is it supported? https://github.com/github/codeql/pulls?q=is%3Apr+is%3Aopen+-author%3AMarcono1234+-author%3Ardmarsh2+


问:
How to Update value for multiple Field in Oracle SQL
I have to update field: Number, Tgl, product in Table Detail_product from table Details
with condition:

```<code>If, id on Table Detail Product an Detail is same then
update Detail_product.Tgl using Details.tgl where Details.tgl is null,
update Detail_product.number using Details.number  where Details.number
update Detail_product.product using Details.product  where Details.product
</code>```

I have query merge to update field, but i can't create one query to update multiple field

```<code>MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.tgl = y.tgl WHERE Y.tgl IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.number = y.number WHERE Y.number IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.product = y.product WHERE Y.product IS NOT NULL;
</code>```

What should i do, so the query is sort and the runtime doesn't take long.

答:
You can combine them if you accept some unnecessary column updates (i.e.update the column to it's current value if the new data is null:

```<code>MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
    UPDATE SET x.tgl = coalesce(y.tgl, X.tgl),
        x.number = coalesce(y.number, X.number),
        x.product = coalesce(y.product, X.product)
    WHERE (Y.tgl IS NOT NULL OR Y.number IS NOT NULL OR Y.product IS NOT NULL)
</code>```

It depends on how many updates are there (Is it costlier to do unnecessary updates or the full join?). Also you need to consider if there are triggers associated with these columns to capture changes (and create superfluous audit records).

Body:
I have to update field: Number, Tgl, product in Table Detail_product from table Details
with condition:

If, id on Table Detail Product an Detail is same then
update Detail_product.Tgl using Details.tgl where Details.tgl is null,
update Detail_product.number using Details.number  where Details.number
update Detail_product.product using Details.product  where Details.product

I have query merge to update field, but i can't create one query to update multiple field

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.tgl = y.tgl WHERE Y.tgl IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.number = y.number WHERE Y.number IS NOT NULL;

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
UPDATE SET x.product = y.product WHERE Y.product IS NOT NULL;

What should i do, so the query is sort and the runtime doesn't take long.

Body:
You can combine them if you accept some unnecessary column updates (i.e.update the column to it's current value if the new data is null:

MERGE INTO Detail_product x
USING Details y
ON (x.id = y.id)
  WHEN MATCHED THEN
    UPDATE SET x.tgl = coalesce(y.tgl, X.tgl),
        x.number = coalesce(y.number, X.number),
        x.product = coalesce(y.product, X.product)
    WHERE (Y.tgl IS NOT NULL OR Y.number IS NOT NULL OR Y.product IS NOT NULL)

It depends on how many updates are there (Is it costlier to do unnecessary updates or the full join?). Also you need to consider if there are triggers associated with these columns to capture changes (and create superfluous audit records).


问:
Parquet File datetime value mismatch
While reading a parquet file using pandas the values in the datetime field gets changing. For example the output of the field while reading a parquet file is 2021-02-07 10:43:20.067 but the actual value should be there is 2021-02-07 6:43:20. Same way for few records the datetime columns are seeing +4 and +5 hrs. All the date min and sec is same but only hours field is getting changed.

The below code I am using

```<code>df=pd.read_parquet('filename.parquet')
</code>```

The data type for all the fields in parquet are datetime64[ns].

答:
From your description I suspect that it may have to do with timezones that have daylight saving. if you think this is the reason, then I would do:

```<code>pd.to_datetime(df['datetime'])\
    .dt.tz_localize('UTC')\
    .dt.tz_convert('Europe/Berlin')
</code>```

The first line makes sure the column is in date-time format so the subsequent lines will work.

The second line defines the timezone as used in producing the parquet file.

The third line converts the timezone to the one that you are interested in.

Title: Parquet File datetime value mismatch

Body:
While reading a parquet file using pandas the values in the datetime field gets changing. For example the output of the field while reading a parquet file is 2021-02-07 10:43:20.067 but the actual value should be there is 2021-02-07 6:43:20. Same way for few records the datetime columns are seeing +4 and +5 hrs. All the date min and sec is same but only hours field is getting changed.

The below code I am using

df=pd.read_parquet('filename.parquet')

The data type for all the fields in parquet are datetime64[ns].

Body:
From your description I suspect that it may have to do with timezones that have daylight saving. if you think this is the reason, then I would do:

pd.to_datetime(df['datetime'])\
    .dt.tz_localize('UTC')\
    .dt.tz_convert('Europe/Berlin')

The first line makes sure the column is in date-time format so the subsequent lines will work.

The second line defines the timezone as used in producing the parquet file.

The third line converts the timezone to the one that you are interested in.


问:
DB2 C UDF parameters in array
I'm using DB2 10.5 Linux and I Need to create a C UDF that can get more than 150 arguments ( plus the null indicators ).

It is possible to pass the whole row like  SELECT MYSCHEMA.MYUDF(*) FROM TABLE or is there a way to pass the arguments in an array like PARAMETER STYLE MAIN in procedures ?

I haven't found any example or documentation for this.

答:
is not possible to have more than 90 parameters, however I was able to solve the problem using BLOB as input.

then create the blob on query with (columns are INT)

```<code>HEXTORAW(HEX(COLUM_NAME_1))||HEXTORAW(HEX(COLUM_NAME_2))
</code>```

then in C using a packed structure.

works much faster and reduces the code lines in on the C udf.

Title: DB2 C UDF parameters in array

Body:
is not possible to have more than 90 parameters, however I was able to solve the problem using BLOB as input.

then create the blob on query with (columns are INT)

HEXTORAW(HEX(COLUM_NAME_1))||HEXTORAW(HEX(COLUM_NAME_2))

then in C using a packed structure.

works much faster and reduces the code lines in on the C udf.


问:
Losing props in react native when navigating backwards
I have a simple problem: I have a parent component that navigates to a child component, the child component is supposed to update the state on the parent component when the child navigates backwards (this.props.navigation.navigate("parentComponent", { params }) ). According to the docs this should be easy: https://reactnavigation.org/docs/params/

The navigation action is treated like a goBack action if the screen already exists. However when I do this and try to console.log the props in the parents screen after going back it shows it as empty.

Parent.js

```<code> <View style={styles.availabilitycontainer} visible={true}>
          <View style={styles.titlegroupcontainer}>
            <Text style={styles.abouttitle}>Schedule Availability</Text>
            {/*Redirect to edit schedule*/}
            <TouchableOpacity
              style={styles.cameracantainer}
              onPress={() =>
                this.props.navigation.navigate("ChildComponent")
              }
            >
              <Image source={Editoutline} />
            </TouchableOpacity>
          </View>

          <ProfileAvalability />
        </View>
</code>```

Child.js

```<code>async submitToBackend(){
    /* Code to submit to backend omitted */
  this.props.navigation.navigate('ParentComponent', { params });
}
</code>```

答:
Navigate doesn't really work that way. If it detects the ParentComponent is already there in the stack, it will simply bring it forward and not necessarily rerender/reload.

What I suggest is pass a second param as a function that will perform the changes, eg:

```<code>submitData(data) {
  setState(data)
}
</code>```

then when you call the child:

```<code>props.navigation.navigate("ChildComponent", { submitData })
</code>```

then inside the ChildComponent, when you're done processing, call submitData([insert your data here]), then that function will perform the write on the ParentComponent. This assumes you're using useState().

Body:
I have a simple problem: I have a parent component that navigates to a child component, the child component is supposed to update the state on the parent component when the child navigates backwards (this.props.navigation.navigate("parentComponent", { params }) ). According to the docs this should be easy: https://reactnavigation.org/docs/params/

The navigation action is treated like a goBack action if the screen already exists. However when I do this and try to console.log the props in the parents screen after going back it shows it as empty.

Parent.js

 <View style={styles.availabilitycontainer} visible={true}>
          <View style={styles.titlegroupcontainer}>
            <Text style={styles.abouttitle}>Schedule Availability</Text>
            {/*Redirect to edit schedule*/}
            <TouchableOpacity
              style={styles.cameracantainer}
              onPress={() =>
                this.props.navigation.navigate("ChildComponent")
              }
            >
              <Image source={Editoutline} />
            </TouchableOpacity>
          </View>

          <ProfileAvalability />
        </View>

Child.js

async submitToBackend(){
    /* Code to submit to backend omitted */
  this.props.navigation.navigate('ParentComponent', { params });
}

Body:
Navigate doesn't really work that way. If it detects the ParentComponent is already there in the stack, it will simply bring it forward and not necessarily rerender/reload.

What I suggest is pass a second param as a function that will perform the changes, eg:

submitData(data) {
  setState(data)
}

then when you call the child:

props.navigation.navigate("ChildComponent", { submitData })

then inside the ChildComponent, when you're done processing, call submitData([insert your data here]), then that function will perform the write on the ParentComponent. This assumes you're using useState().


问:
How Can I add date to 1 year. in X++
How Can I add date to 1 year. I have field with date. now i want to add another field which add 1 year to previous field (date)  in X++ code
Ex: 19/10/2010 to 18/10/2011</p>

答:
Maybe:</p>

```<code>TransDate dt = 19\10\2010;
info(strfmt("date is %1",nextYr(dt)));
</code>```

ContentLicense: CC BY-SA 3.0

Title: How Can I add date to 1 year. in X++

Body:
Maybe:

TransDate dt = 19\10\2010;
info(strfmt("date is %1",nextYr(dt)));


问:
Discord.JS TypeError: Cannot read properties of undefined (reading 'get')
Good Morning! I am currently working on a discord bot but I am facing an issue with the event handlers.
There seems to be a problem with the "get" command but I can't seem to find out what it
is, I have given the code below to my message.js

```<code>module.exports = (Discord, client, msg) => {

    const prefix = 'e!';

    if (!msg.content.startsWith(prefix) || msg.author.bot) return;

    const args = msg.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    const cmd = client.commands.get(command)

    if (!cmd){
        msg.channel.send("That is not an available command!")
    };

    if(command) command.execute(client, msg, args, Discord);
};
</code>```

The code below is my index.js

```<code>const Discord = require("discord.js")
const client = new Discord.Client({intents : ["GUILDS", "GUILD_MESSAGES"]});
const button = require('discord-buttons')(client)
const { MessageButton } = require("discord-buttons")

client.commands = new Discord.Collection();
client.events = new Discord.Collection();

['command_handler', 'event_handler'].forEach(handler =>{
    require(`./handlers/${handler}`)(client, Discord);
})

client.login(process.env.token)
</code>```

Any help would be greatly appreciated!

答:
I fixed it! It seems that the order in which Discord and client were (in here).

module.exports = (Discord, client, msg)
```
<p>was wrong! Instead, I swapped <code>Discord</code> around with <code>client</code> and it seems to work!</p>
<pre class="lang-js prettyprint-override"><code>module.exports = (client, Discord, msg)
</code>```

If anyone can tell me why this happens (as I would love to learn more)
You can comment or answer!

There was also an error with the execute command which I also fixed

if(cmd) {
        cmd.execute(client, msg, args, Discord);
}
```

Thanks everyone for their contribution! Really needed your help!

Body:
Good Morning! I am currently working on a discord bot but I am facing an issue with the event handlers.
There seems to be a problem with the "get" command but I can't seem to find out what it
is, I have given the code below to my message.js

module.exports = (Discord, client, msg) => {

    const prefix = 'e!';

    if (!msg.content.startsWith(prefix) || msg.author.bot) return;

    const args = msg.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    const cmd = client.commands.get(command)

    if (!cmd){
        msg.channel.send("That is not an available command!")
    };

    if(command) command.execute(client, msg, args, Discord);
};

The code below is my index.js

const Discord = require("discord.js")
const client = new Discord.Client({intents : ["GUILDS", "GUILD_MESSAGES"]});
const button = require('discord-buttons')(client)
const { MessageButton } = require("discord-buttons")

client.commands = new Discord.Collection();
client.events = new Discord.Collection();

['command_handler', 'event_handler'].forEach(handler =>{
    require(`./handlers/${handler}`)(client, Discord);
})

client.login(process.env.token)

Any help would be greatly appreciated!

Body:
I fixed it! It seems that the order in which Discord and client were (in here).

module.exports = (Discord, client, msg)

was wrong! Instead, I swapped Discord around with client and it seems to work!

module.exports = (client, Discord, msg)

If anyone can tell me why this happens (as I would love to learn more)
You can comment or answer!

There was also an error with the execute command which I also fixed

if(cmd) {
        cmd.execute(client, msg, args, Discord);
}

Thanks everyone for their contribution! Really needed your help!


问:
Unexpected result with weights in spatstat::density.psp()
I am trying to use kernel density smoothing to map the intensity of possible pest escape from vehicle traffic. Each route has been broken down into straight lines with each line having an integer attribute for the number of times the segment was travelled upon. However, when I use this attribute as the weight in kernel density smoothing, the weights don't seem to be used.

I've created a simplified reprex below with two abutting straight lines. Can anyone explain to me how I can make density.psp() account for the fact that one segment has an attribute 2x the magnitude of the other?

Many thanks for your help,

Josh

```<code>    # Load packages
    library(spatstat)

    # Create the data frame. Note that coordinates are projected to the
    # North America Lambert Conformal Conic system. https://epsg.io/102009
    my_lines <- data.frame(
      fx = c(1252365.22479882, 1233600.0015391),
      fy = c(510853.438463705, 626675.859171899),
      tx = c(1233600.0015391, 1218256.03484937),
      ty = c(626675.859171899, 721347.256108354),
      attrib = c(100, 50)
    )

    # Creat the observation window
    my_owin <- owin(
      xrange = c(1200000, 1270000),
      yrange = c(500000,  730000)
    )

    # Create the psp object with 'attrib' as the mark.
    my_psp <- psp(
      x0 = my_lines$fx, y0 = my_lines$fy,
      x1 = my_lines$tx, y1 = my_lines$ty,
      window = my_owin, marks = my_lines$attrib
    )

    # Create the KDS image with 'attrib' as the weights
    kdi_image_weighted <-
      density.psp(
        my_psp,
        kernel = "gaussian",
        sigma = 4000,
        weights = my_psp$attrib,
        edge = FALSE
      )

    # Create the KDS image without weights
    kdi_image_unweighted <-
      density.psp(
        my_psp,
        kernel = "gaussian",
        sigma = 4000,
        edge = FALSE
      )

    # Plot the weighted and unweighted KDS images. Note that they are the same
    # despite one being weighted.
    plot(kdi_image_weighted)
    plot(kdi_image_unweighted)
</code>```

答:
Short answer:

Use marks() to extract the mark values from an object in the spatstat package. Example:

```<code> Z <- density(my_psp, weights=marks(my_psp))
</code>```

Long answer:

This problem is not related to the function density.psp.

Firstly there is a misunderstanding about names of objects. In your example, an object my_psp is created as psp(.... marks=my_lines$attrib). Then the subsequent code expects my_psp to contain an element my_psp$attrib. This is not how evaluation works in R.

When you type the command psp(...., marks=my_lines$attrib), the expression my_lines$attrib will be evaluated (by extracting the element called attrib from the object my_lines). After evaluating these data, the system forgets where it got the data from; the name attrib is forgotten. The resulting data (that was stored in my_lines$attrib) will be passed to the function psp as the argument marks.

Secondly you are using the $ operator to extract data from an object (in this case an object of class "psp" in the spatstat package). This is OK for simple objects such as lists, but for objects created by packages it is unsafe, because the internal structure could change when the package is updated.

Your example code expects the object my_psp to contain an element with a particular name, but there's no reason why it should. The function psp() creates an object of class "psp" which has some weird internal structure, described in help(psp.object).

To extract the mark values from an object in the spatstat package, it is currently possible to use $marks, but this could change, and it is strongly recommended to use the function marks().

Body:
I am trying to use kernel density smoothing to map the intensity of possible pest escape from vehicle traffic. Each route has been broken down into straight lines with each line having an integer attribute for the number of times the segment was travelled upon. However, when I use this attribute as the weight in kernel density smoothing, the weights don't seem to be used.

I've created a simplified reprex below with two abutting straight lines. Can anyone explain to me how I can make density.psp() account for the fact that one segment has an attribute 2x the magnitude of the other?

Many thanks for your help,

Josh

    # Load packages
    library(spatstat)

    # Create the data frame. Note that coordinates are projected to the
    # North America Lambert Conformal Conic system. https://epsg.io/102009
    my_lines <- data.frame(
      fx = c(1252365.22479882, 1233600.0015391),
      fy = c(510853.438463705, 626675.859171899),
      tx = c(1233600.0015391, 1218256.03484937),
      ty = c(626675.859171899, 721347.256108354),
      attrib = c(100, 50)
    )

    # Creat the observation window
    my_owin <- owin(
      xrange = c(1200000, 1270000),
      yrange = c(500000,  730000)
    )

    # Create the psp object with 'attrib' as the mark.
    my_psp <- psp(
      x0 = my_lines$fx, y0 = my_lines$fy,
      x1 = my_lines$tx, y1 = my_lines$ty,
      window = my_owin, marks = my_lines$attrib
    )

    # Create the KDS image with 'attrib' as the weights
    kdi_image_weighted <-
      density.psp(
        my_psp,
        kernel = "gaussian",
        sigma = 4000,
        weights = my_psp$attrib,
        edge = FALSE
      )

    # Create the KDS image without weights
    kdi_image_unweighted <-
      density.psp(
        my_psp,
        kernel = "gaussian",
        sigma = 4000,
        edge = FALSE
      )

    # Plot the weighted and unweighted KDS images. Note that they are the same
    # despite one being weighted.
    plot(kdi_image_weighted)
    plot(kdi_image_unweighted)

Body:
Short answer:

Use marks() to extract the mark values from an object in the spatstat package. Example:

 Z <- density(my_psp, weights=marks(my_psp))

Long answer:

This problem is not related to the function density.psp.

Firstly there is a misunderstanding about names of objects. In your example, an object my_psp is created as psp(.... marks=my_lines$attrib). Then the subsequent code expects my_psp to contain an element my_psp$attrib. This is not how evaluation works in R.

When you type the command psp(...., marks=my_lines$attrib), the expression my_lines$attrib will be evaluated (by extracting the element called attrib from the object my_lines). After evaluating these data, the system forgets where it got the data from; the name attrib is forgotten. The resulting data (that was stored in my_lines$attrib) will be passed to the function psp as the argument marks.

Secondly you are using the $ operator to extract data from an object (in this case an object of class "psp" in the spatstat package). This is OK for simple objects such as lists, but for objects created by packages it is unsafe, because the internal structure could change when the package is updated.

Your example code expects the object my_psp to contain an element with a particular name, but there's no reason why it should. The function psp() creates an object of class "psp" which has some weird internal structure, described in help(psp.object).

To extract the mark values from an object in the spatstat package, it is currently possible to use $marks, but this could change, and it is strongly recommended to use the function marks().


问:
Cannot add a WCF Service Referance on a .Net5 Project
I'm trying to add a service reference to a .NET5 project, and I'm following the directives given on the Microsoft page here, but I run into an error message which is not explanatory at all.

Here are my steps:

I click Next:

Next again:

And at last, I hit Finish and there's the error:

The steps are simple and straightforward, I can add the service through a WebForms application so how can I get past this error with a .NET5 application?

答:
Is your service running successfully?

Do you add an external service or an internal service, and whether the url is automatically generated or manually entered. You can check out this tutorial for more details.

https://learn.microsoft.com/en-us/visualstudio/data-tools/how-to-add-update-or-remove-a-wcf-data-service-reference?view=vs-2022

You can choose to use the dotnet-svcutil tool.

https://learn.microsoft.com/en-us/dotnet/core/additional-tools/dotnet-svcutil-guide?tabs=dotnetsvcutil2x


问:
Spring Data JPA inserting underline character between variable words
Spring Data JPA inserts underscore character between words in variables, that does not happen if second term is not an word:

```<code>@Entity
@Table(name = "table")
public class Entity{
@Id
@GeneratedValue
private Long id;
private String variableA;
private String variableYes;
}
</code>```

For 'variableA' it creates table with variableA SQL text insertion, for 'variableYes' it inserts in SQL variable_Yes, I didn't found documentation for this particularity. Eclipse IDE console:

```<code>create table questao (id bigint not null, variableA char(255), variable_Yes varchar(255), primary key (id));
</code>```

答: CamelCase is used by default. When encountering a capital letter (not last and next letter in lower case) When is considered the beginning of a new word.  You can try variableAA and variableAa, which generate variableaa and variable_aa. It's good practice to explicitly specify a name using @Column(name = "variable_a").

Body:
Spring Data JPA inserts underscore character between words in variables, that does not happen if second term is not an word:

@Entity
@Table(name = "table")
public class Entity{
@Id
@GeneratedValue
private Long id;
private String variableA;
private String variableYes;
}

For 'variableA' it creates table with variableA SQL text insertion, for 'variableYes' it inserts in SQL variable_Yes, I didn't found documentation for this particularity. Eclipse IDE console:

create table questao (id bigint not null, variableA char(255), variable_Yes varchar(255), primary key (id));


问:
Difference between await Task and await Func<Task>()
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

```<code>static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}
</code>```

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10
```
<p>The output of <code>Task2()</code>:</p>
<pre class="lang-none prettyprint-override"><code>-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------
</code>```

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

```<code>static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}
</code>```

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------
```
<p>UPDATE2:
I tried to minimal the example but the following code does not have this problem.</p>
<pre class="lang-c# prettyprint-override"><code>var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);
</code>```

答:
This problem is just like Stephen says in his answer, every time you await a async delegate, a new instance of async task is created and starts from beginning.

This a minimal example to illustrate this problem:

int i = 0;
var ftask = async () =>
{
    Console.WriteLine($"[{i++}] Func<Task>");
    await Task.Yield();
};

await ftask();
await ftask();

//--------------------

int j = 0;
var task = Task.Run(async () =>
{
    Console.WriteLine($"[{j++}] Task.Run()");
    await Task.Yield();
});

await task;
await task;
```
<p>The output:</p>
```[0] Func<Task>
[1] Func<Task>
[0] Task.Run()
```

Body:
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10

The output of Task2():

-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------

UPDATE2:
I tried to minimal the example but the following code does not have this problem.

var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);

Body:
This problem is just like Stephen says in his answer, every time you await a async delegate, a new instance of async task is created and starts from beginning.

This a minimal example to illustrate this problem:

int i = 0;
var ftask = async () =>
{
    Console.WriteLine($"[{i++}] Func<Task>");
    await Task.Yield();
};

await ftask();
await ftask();

//--------------------

int j = 0;
var task = Task.Run(async () =>
{
    Console.WriteLine($"[{j++}] Task.Run()");
    await Task.Yield();
});

await task;
await task;

The output:

[0] Func<Task>
[1] Func<Task>
[0] Task.Run()


问:
Problems with constructor resolution order
Consider the following constructors for T:

```<code>struct T {
    T(const bool) { std::cout << "T(const bool)" << endl; }
    T(const std::string&) { std::cout << "T(const std::string&)" << endl; }
};

T t("");
</code>```

Why does T(const bool) take precedence over T(const std::string&) when constructing t?

Since the above precedence might cause confusion to users expecting T(const std::string&) to be called, what can I do to have T(const std::string&) implicitly called when passing string literals to the constructor of T. For now the only work around I have found is to add another constructor, which takes the highest precedence:

```<code>T(const char* s)
{
    std::cout << "T(const char*)" << endl;
    *this = std::string(s);
}
</code>```

Apart from the above solution, declaring explicit T(const bool) to avoid confusion does not solve the above problem: in this case, although T t = "" is now prohibited, why is the form T t("") is still allowed and does call T(const bool) ?

答:
"" can convert to both std::string and bool.

The question is, which way will it convert?

Conversion to std::string is a user-defined conversion.

Conversion to bool is a standard conversion.

So the answer is, standard conversion has higher precedence over user-defined conversion. So "" will convert to bool.

Example,

```<code>struct A
{
   A(int i) {} //i.e an int can implicity convert to A
};

void f(const A &) { cout << "User-defined conversion won" << endl; }
void f(const bool &) { cout << "Standard conversion won" << endl; }

int main() {
        f (10);
        return 0;
}
</code>```

Output:

```<code>Standard conversion won
</code>```

Online demo : http://www.ideone.com/5Bt0K

In the above demo, 10 can convert to A and bool both. Since converting to bool is a standard conversion, it converts into bool, instead of A.

Body:
Consider the following constructors for T:

struct T {
    T(const bool) { std::cout << "T(const bool)" << endl; }
    T(const std::string&) { std::cout << "T(const std::string&)" << endl; }
};

T t("");

Why does T(const bool) take precedence over T(const std::string&) when constructing t?

Since the above precedence might cause confusion to users expecting T(const std::string&) to be called, what can I do to have T(const std::string&) implicitly called when passing string literals to the constructor of T. For now the only work around I have found is to add another constructor, which takes the highest precedence:

T(const char* s)
{
    std::cout << "T(const char*)" << endl;
    *this = std::string(s);
}

Apart from the above solution, declaring explicit T(const bool) to avoid confusion does not solve the above problem: in this case, although T t = "" is now prohibited, why is the form T t("") is still allowed and does call T(const bool) ?

Body:
"" can convert to both std::string and bool.

The question is, which way will it convert?

Conversion to std::string is a user-defined conversion.

Conversion to bool is a standard conversion.

So the answer is, standard conversion has higher precedence over user-defined conversion. So "" will convert to bool.

Example,

struct A
{
   A(int i) {} //i.e an int can implicity convert to A
};

void f(const A &) { cout << "User-defined conversion won" << endl; }
void f(const bool &) { cout << "Standard conversion won" << endl; }

int main() {
        f (10);
        return 0;
}

Output:

Standard conversion won

Online demo : http://www.ideone.com/5Bt0K

In the above demo, 10 can convert to A and bool both. Since converting to bool is a standard conversion, it converts into bool, instead of A.


问:
Xamarin ListView not show json results from api
same as title,my listview doesn't show me anything,i think my model in that app is not good
help! deseeerialized json in jsonObject then create a list of objectModel but not show me
thanks

```<code>public class Marvel
{
}
public class TextObject
{
    public string type { get; set; }
    public string language { get; set; }
    public string text { get; set; }
}

public class Url
{
    public string type { get; set; }
    public string url { get; set; }
}

public class Series
{
    public string resourceURI { get; set; }
    public string name { get; set; }
}

public class Variant
{
    public string resourceURI { get; set; }
    public string name { get; set; }
}

public class Date
{
    public string type { get; set; }
    public DateTime date { get; set; }
}

public class Price
{
    public string type { get; set; }
    public double price { get; set; }
}

public class Thumbnail
{
    public string path { get; set; }
    public string extension { get; set; }
}

public class Image
{
    public string path { get; set; }
    public string extension { get; set; }
}

public class Item
{
    public string resourceURI { get; set; }
    public string name { get; set; }
    public string role { get; set; }
    public string type { get; set; }
}

public class Creators
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<Item> items { get; set; }
    public int returned { get; set; }
}

public class Characters
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<Item> items { get; set; }
    public int returned { get; set; }
}

public class Stories
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<Item> items { get; set; }
    public int returned { get; set; }
}

public class Events
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<object> items { get; set; }
    public int returned { get; set; }
}

public class Result
{
    public int id { get; set; }
    public int digitalId { get; set; }
    public string title { get; set; }
    public int issueNumber { get; set; }
    public string variantDescription { get; set; }
    public string description { get; set; }
    public DateTime modified { get; set; }
    public string isbn { get; set; }
    public string upc { get; set; }
    public string diamondCode { get; set; }
    public string ean { get; set; }
    public string issn { get; set; }
    public string format { get; set; }
    public int pageCount { get; set; }
    public List<TextObject> textObjects { get; set; }
    public string resourceURI { get; set; }
    public List<Url> urls { get; set; }
    public Series series { get; set; }
    public List<Variant> variants { get; set; }
    public List<object> collections { get; set; }
    public List<object> collectedIssues { get; set; }
    public List<Date> dates { get; set; }
    public List<Price> prices { get; set; }
    public Thumbnail thumbnail { get; set; }
    public List<Image> images { get; set; }
    public Creators creators { get; set; }
    public Characters characters { get; set; }
    public Stories stories { get; set; }
    public Events events { get; set; }
}

public class Data
{
    public int offset { get; set; }
    public int limit { get; set; }
    public int total { get; set; }
    public int count { get; set; }
    public List<Result> results { get; set; }
}

public class Rooto
{
    public int code { get; set; }
    public string status { get; set; }
    public string copyright { get; set; }
    public string attributionText { get; set; }
    public string attributionHTML { get; set; }
    public string etag { get; set; }
    public Data data { get; set; }
}
</code>```

}

mainpage

```<code> private async void Button_Clicked(object sender, EventArgs e)
    {
        var texto = caja.Text;
        var request = new HttpRequestMessage();
        request.RequestUri = new Uri("https://gateway.marvel.com/v1/public/comics?title=hulk&ts=1&apikey=###&hash=###");
        request.Method = HttpMethod.Get;
        request.Headers.Add("Accept", "application/json");

        var client = new HttpClient();

        HttpResponseMessage response = await client.SendAsync(request);

        string content = await response.Content.ReadAsStringAsync();
        Result dataObjects = JsonConvert.DeserializeObject<Result>(content);

        JObject myJObject = JObject.Parse(content);
        Console.WriteLine(myJObject);

        List<Result> parsedFields = new List<Result>();
        parsedFields.Add(dataObjects);

        ListDemo.ItemsSource = parsedFields;
</code>```

my xaml and json

https://gateway.marvel.com/v1/public/comics?title=hulk&ts=1&apikey=ab07bf416406297274b27ca941ba3bee&hash=cf9eb501d7c3775c32b72c61a6a76805

```<code><ContentPage.Content>
    <StackLayout>

        <Label Text="Control ListView"  FontSize="40"

       HorizontalOptions="Center"

       VerticalOptions="CenterAndExpand" />
        <Button Text="Lamado API" Clicked="Button_Clicked"/>
        <Entry x:Name="caja" Text=""/>

        <ListView x:Name="ListDemo">

            <ListView.ItemTemplate>

                <DataTemplate>

                    <ViewCell>

                        <StackLayout Orientation="Horizontal">

                            <Image Source="{Binding resourceURI}"

                               WidthRequest="50"

                               HeightRequest="50"/>

                            <StackLayout Orientation="Vertical">

                                <Label Text="{Binding title}"

                                   FontSize="15" TextColor="Blue"/>

                                <Label Text="{Binding isbn}"

                                   FontSize="12" TextColor="Fuchsia"/>

                            </StackLayout>

                        </StackLayout>

                    </ViewCell>

                </DataTemplate>

            </ListView.ItemTemplate>

        </ListView>

    </StackLayout>
</ContentPage.Content>
</code>```

tnaka

答:
The root level is supposed to be Root not Result class .

Modify your code as below

Root dataObjects = JsonConvert.DeserializeObject<Root>(text);
ListDemo.ItemsSource = dataObjects.data.results;
```

Body:
same as title,my listview doesn't show me anything,i think my model in that app is not good
help! deseeerialized json in jsonObject then create a list of objectModel but not show me
thanks

public class Marvel
{
}
public class TextObject
{
    public string type { get; set; }
    public string language { get; set; }
    public string text { get; set; }
}

public class Url
{
    public string type { get; set; }
    public string url { get; set; }
}

public class Series
{
    public string resourceURI { get; set; }
    public string name { get; set; }
}

public class Variant
{
    public string resourceURI { get; set; }
    public string name { get; set; }
}

public class Date
{
    public string type { get; set; }
    public DateTime date { get; set; }
}

public class Price
{
    public string type { get; set; }
    public double price { get; set; }
}

public class Thumbnail
{
    public string path { get; set; }
    public string extension { get; set; }
}

public class Image
{
    public string path { get; set; }
    public string extension { get; set; }
}

public class Item
{
    public string resourceURI { get; set; }
    public string name { get; set; }
    public string role { get; set; }
    public string type { get; set; }
}

public class Creators
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<Item> items { get; set; }
    public int returned { get; set; }
}

public class Characters
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<Item> items { get; set; }
    public int returned { get; set; }
}

public class Stories
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<Item> items { get; set; }
    public int returned { get; set; }
}

public class Events
{
    public int available { get; set; }
    public string collectionURI { get; set; }
    public List<object> items { get; set; }
    public int returned { get; set; }
}

public class Result
{
    public int id { get; set; }
    public int digitalId { get; set; }
    public string title { get; set; }
    public int issueNumber { get; set; }
    public string variantDescription { get; set; }
    public string description { get; set; }
    public DateTime modified { get; set; }
    public string isbn { get; set; }
    public string upc { get; set; }
    public string diamondCode { get; set; }
    public string ean { get; set; }
    public string issn { get; set; }
    public string format { get; set; }
    public int pageCount { get; set; }
    public List<TextObject> textObjects { get; set; }
    public string resourceURI { get; set; }
    public List<Url> urls { get; set; }
    public Series series { get; set; }
    public List<Variant> variants { get; set; }
    public List<object> collections { get; set; }
    public List<object> collectedIssues { get; set; }
    public List<Date> dates { get; set; }
    public List<Price> prices { get; set; }
    public Thumbnail thumbnail { get; set; }
    public List<Image> images { get; set; }
    public Creators creators { get; set; }
    public Characters characters { get; set; }
    public Stories stories { get; set; }
    public Events events { get; set; }
}

public class Data
{
    public int offset { get; set; }
    public int limit { get; set; }
    public int total { get; set; }
    public int count { get; set; }
    public List<Result> results { get; set; }
}

public class Rooto
{
    public int code { get; set; }
    public string status { get; set; }
    public string copyright { get; set; }
    public string attributionText { get; set; }
    public string attributionHTML { get; set; }
    public string etag { get; set; }
    public Data data { get; set; }
}

}

mainpage

 private async void Button_Clicked(object sender, EventArgs e)
    {
        var texto = caja.Text;
        var request = new HttpRequestMessage();
        request.RequestUri = new Uri("https://gateway.marvel.com/v1/public/comics?title=hulk&ts=1&apikey=###&hash=###");
        request.Method = HttpMethod.Get;
        request.Headers.Add("Accept", "application/json");

        var client = new HttpClient();

        HttpResponseMessage response = await client.SendAsync(request);

        string content = await response.Content.ReadAsStringAsync();
        Result dataObjects = JsonConvert.DeserializeObject<Result>(content);

        JObject myJObject = JObject.Parse(content);
        Console.WriteLine(myJObject);

        List<Result> parsedFields = new List<Result>();
        parsedFields.Add(dataObjects);

        ListDemo.ItemsSource = parsedFields;

my xaml and json

https://gateway.marvel.com/v1/public/comics?title=hulk&ts=1&apikey=ab07bf416406297274b27ca941ba3bee&hash=cf9eb501d7c3775c32b72c61a6a76805

<ContentPage.Content>
    <StackLayout>

        <Button Text="Lamado API" Clicked="Button_Clicked"/>
        <Entry x:Name="caja" Text=""/>

        <ListView x:Name="ListDemo">

            <ListView.ItemTemplate>

                <DataTemplate>

                    <ViewCell>

                        <StackLayout Orientation="Horizontal">

                            <Image Source="{Binding resourceURI}"

                               WidthRequest="50"

                               HeightRequest="50"/>

                            <StackLayout Orientation="Vertical">

                            </StackLayout>

                        </StackLayout>

                    </ViewCell>

                </DataTemplate>

            </ListView.ItemTemplate>

        </ListView>

    </StackLayout>
</ContentPage.Content>

tnaka


问:
pyspark extracting a string using python
Spark dataframe which has column emailID  : ram.shyam.78uy@testing.com. i would like to extract the string between "." and "@"  i.e 78uy and store it in column.
tried

```<code>split_for_alias = split(rs_csv['emailID'],'[.]')
rs_csv_alias= rs_csv.withColumn('alias',split_for_alias.getItem(size(split_for_alias) -2))
</code>```

Its adding 78uy@testing as alias. Another column can be added and chop off the extra values. But is it possible to do in single statement.

答:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First we setup a Pandas DataFrame to test:

import pandas as pd
df = pd.DataFrame({"id":[1,2],"email": ["am.shyam.78uy@testing.com", "j.k.kilo@jom.com"]})
```
<p>Next, we make a native Python function. The logic is clear this way.</p>
<pre class="lang-py prettyprint-override"><code>from typing import List, Dict, Any
def extract(df:List[Dict[str,Any]]) -> List[Dict[str,Any]]:
    for row in df:
        email = row["email"].split("@")[0].split(".")[-1]
        row["new_col"] = email
    return df
</code>```

Then we can test on the Pandas engine:

from fugue import transform
transform(df, extract, schema="*, new_col:str")
```
<p>Because it works, we can bring it to Spark by supplying an engine:</p>
```import fugue_spark
transform(df, extract, schema="*, new_col:str", engine="spark").show()
```
```+---+--------------------+-------+
| id|               email|new_col|
+---+--------------------+-------+
|  1|am.shyam.78uy@tes...|   78uy|
|  2|    j.k.kilo@jom.com|   kilo|
+---+--------------------+-------+
```

Note .show() is needed because Spark evaluates lazily. This transform can take in both Pandas and Spark DataFrames and will output a Spark DataFrame if using the Spark engine.

Body:
Spark dataframe which has column emailID  : ram.shyam.78uy@testing.com. i would like to extract the string between "." and "@"  i.e 78uy and store it in column.
tried

split_for_alias = split(rs_csv['emailID'],'[.]')
rs_csv_alias= rs_csv.withColumn('alias',split_for_alias.getItem(size(split_for_alias) -2))

Its adding 78uy@testing as alias. Another column can be added and chop off the extra values. But is it possible to do in single statement.

Body:
We made the Fugue project to port native Python or Pandas code to Spark or Dask. This lets you can keep the logic very readable by expressing it in native Python. Fugue can then port it to Spark for you with one function call.

First we setup a Pandas DataFrame to test:

import pandas as pd
df = pd.DataFrame({"id":[1,2],"email": ["am.shyam.78uy@testing.com", "j.k.kilo@jom.com"]})

Next, we make a native Python function. The logic is clear this way.

from typing import List, Dict, Any
def extract(df:List[Dict[str,Any]]) -> List[Dict[str,Any]]:
    for row in df:
        email = row["email"].split("@")[0].split(".")[-1]
        row["new_col"] = email
    return df

Then we can test on the Pandas engine:

from fugue import transform
transform(df, extract, schema="*, new_col:str")

Because it works, we can bring it to Spark by supplying an engine:

import fugue_spark
transform(df, extract, schema="*, new_col:str", engine="spark").show()

+---+--------------------+-------+
| id|               email|new_col|
+---+--------------------+-------+
|  1|am.shyam.78uy@tes...|   78uy|
|  2|    j.k.kilo@jom.com|   kilo|
+---+--------------------+-------+

Note .show() is needed because Spark evaluates lazily. This transform can take in both Pandas and Spark DataFrames and will output a Spark DataFrame if using the Spark engine.