问:
How to deal with warning : "Workbook contains no default style, apply openpyxl's default "
I have the -current- latest version of pandas, openpyxl, xlrd.

openpyxl : 3.0.6.

pandas : 1.2.2.

xlrd : 2.0.1.

I have a generated excel xlsx- file (export from a webapplication).

I read it in pandas:

```<code>myexcelfile = pd.read_excel(easy_payfile, engine="openpyxl")
</code>```

Everything goes ok, I can successfully read the file.

But I do get a warning:

```<code>/Users/*******/projects/environments/venv/lib/python3.8/site-packages/openpyxl/styles/stylesheet.py:214: UserWarning: Workbook contains no default style, apply openpyxl's default
  warn("Workbook contains no default style, apply openpyxl's default")
</code>```

The documentation doesn't shed too much light on it.

Is there any way I can add an option to avoid this warning?

I prefer not to suppress it.

答: I had the same warning. Just changed the sheet name of my excel file from "sheet_1" to "Sheet1", then the warning disappeared. very similar with Yoan. I think pandas should fix this warning later.</p>

Body:
I have the -current- latest version of pandas, openpyxl, xlrd.

openpyxl : 3.0.6.

pandas : 1.2.2.

xlrd : 2.0.1.

I have a generated excel xlsx- file (export from a webapplication).

I read it in pandas:

myexcelfile = pd.read_excel(easy_payfile, engine="openpyxl")

Everything goes ok, I can successfully read the file.

But I do get a warning:

/Users/*******/projects/environments/venv/lib/python3.8/site-packages/openpyxl/styles/stylesheet.py:214: UserWarning: Workbook contains no default style, apply openpyxl's default
  warn("Workbook contains no default style, apply openpyxl's default")

The documentation doesn't shed too much light on it.

Is there any way I can add an option to avoid this warning?

I prefer not to suppress it.


来源: stackexchange

问:
Joining Data into a Single Column
I have this table in access

Userinfo

userid
Name
dept id

1
JJ
002

2
KK
001

Dept

deptid
Dept Name

001
Testing

002
Sorting

003
Designing

Checkinout

userid
Name
Checktime
Checktype

1
JJ
2/5/2022 7:45:10 AM
1

1
JJ
2/5/2022 18:00:10 PM
0

1
JJ
2/6/2022 6:30:00 AM
1

1
JJ
2/6/2022 18:10:30 PM
0

2
KK
2/6/2022 6:10:30 AM
1

2
KK
2/6/2022 18:20:30 PM
0

But i want to create a Inner join that will show this table

userid
Name
Deptname
In
Out

1
JJ
Sorting
2/5/2022 7:45:10 AM
2/5/2022 18:00:10 PM

1
JJ
Sorting
2/6/2022 6:30:00 AM
2/6/2022 18:10:30 PM

1
KK
Testing
2/6/2022 6:10:30 AM
2/6/2022 18:20:30 PM

This is the SQL that i used but i dont know how to put 0 as Out and 1 as In

```<code>SELECT Userinfo.userid as ID,UserInfo.Name as Name,Dept.DeptName as Dept , Checkinout.Checktime

from ( Userinfo
inner join Checkinout on Userinfo.userid = Checkinout.userid )

inner join  Dept on Userinfo.DeptId =Dept.DeptId ;
</code>```

答:
Starting from the non-normalized Checkinout you can get everything but Out directly.  Then add a calculated field to the query to look up the appropriate Out Checktime for each In Checktime:

```<code>Out: (SELECT TOP 1 q.Checktime FROM  [Checkinout] as q WHERE  (q.userid = [Checkinout].[userid]) AND (q.Checktype = 0) AND  (q.Checktime > [Checkinout].[Checktime])
ORDER BY q.Checktime ASC)

SQL:SELECT Userinfo.userid, Userinfo.Username, Dept.[Dept Name], Checkinout.Checktime AS [In], (SELECT TOP 1 q.Checktime FROM  [Checkinout] as q WHERE  (q.userid = [Checkinout].[userid]) AND (q.Checktype = 0) AND  (q.Checktime > [Checkinout].[Checktime])
ORDER BY q.Checktime ASC) AS Out
FROM (Dept INNER JOIN Userinfo ON Dept.deptid = Userinfo.[dept id]) INNER JOIN Checkinout ON Userinfo.userid = Checkinout.userid
WHERE (((Checkinout.Checktype)=1))

'I used a nested query for the calculated field and calculated Out with the business rules that each user check-in must have a corresponding and later check-out by the same user without any check-in/check-outs between.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Joining Data into a Single Column

Body:
I have this table in access

Userinfo

userid
Name
dept id

1
JJ
002

2
KK
001

Dept

deptid
Dept Name

001
Testing

002
Sorting

003
Designing

Checkinout

userid
Name
Checktime
Checktype

1
JJ
2/5/2022 7:45:10 AM
1

1
JJ
2/5/2022 18:00:10 PM
0

1
JJ
2/6/2022 6:30:00 AM
1

1
JJ
2/6/2022 18:10:30 PM
0

2
KK
2/6/2022 6:10:30 AM
1

2
KK
2/6/2022 18:20:30 PM
0

But i want to create a Inner join that will show this table

userid
Name
Deptname
In
Out

1
JJ
Sorting
2/5/2022 7:45:10 AM
2/5/2022 18:00:10 PM

1
JJ
Sorting
2/6/2022 6:30:00 AM
2/6/2022 18:10:30 PM

1
KK
Testing
2/6/2022 6:10:30 AM
2/6/2022 18:20:30 PM

This is the SQL that i used but i dont know how to put 0 as Out and 1 as In

SELECT Userinfo.userid as ID,UserInfo.Name as Name,Dept.DeptName as Dept , Checkinout.Checktime

from ( Userinfo
inner join Checkinout on Userinfo.userid = Checkinout.userid )

inner join  Dept on Userinfo.DeptId =Dept.DeptId ;

Body:
Starting from the non-normalized Checkinout you can get everything but Out directly.  Then add a calculated field to the query to look up the appropriate Out Checktime for each In Checktime:

Out: (SELECT TOP 1 q.Checktime FROM  [Checkinout] as q WHERE  (q.userid = [Checkinout].[userid]) AND (q.Checktype = 0) AND  (q.Checktime > [Checkinout].[Checktime])
ORDER BY q.Checktime ASC)

SQL:SELECT Userinfo.userid, Userinfo.Username, Dept.[Dept Name], Checkinout.Checktime AS [In], (SELECT TOP 1 q.Checktime FROM  [Checkinout] as q WHERE  (q.userid = [Checkinout].[userid]) AND (q.Checktype = 0) AND  (q.Checktime > [Checkinout].[Checktime])
ORDER BY q.Checktime ASC) AS Out
FROM (Dept INNER JOIN Userinfo ON Dept.deptid = Userinfo.[dept id]) INNER JOIN Checkinout ON Userinfo.userid = Checkinout.userid
WHERE (((Checkinout.Checktype)=1))

'I used a nested query for the calculated field and calculated Out with the business rules that each user check-in must have a corresponding and later check-out by the same user without any check-in/check-outs between.


问:
Spring boot test using @Sql scripts keep fails after last test method execution
I test this code

```<code>@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Sql(scripts = {"/sql/create-member.sql"})
@Transactional
class MemberServiceTest {

    @Autowired
    private MemberRepository memberRepository;

    @ParameterizedTest
    @ValueSource(longs = 1L)
    public void SelectMemberTest_A(Long id) {

        Member member = memberRepository.findById(id).get();

        assertEquals(1L, member.getId());
    }

    @ParameterizedTest
    @ValueSource(longs = 2L)
    public void SelectMemberTest_B(Long id) {

        Member member = memberRepository.findById(id).get();

        assertEquals(2L, member.getId());
    }
}
</code>```

create-member.sql

CREATE TABLE Member
(
    id       int auto_increment
        primary key,
    username varchar(45),
    phone    varchar(45),
    address  varchar(45),
);

INSERT INTO Member (username, phone, address)
VALUES ('John', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('Jane', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('emily', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('chris', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('peter', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('sarah', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('kate', '111-1111-1111', null);
```

I keep fail the last test method which is SelectMemberTest_B(Long id) with exception Table "MEMBER" already exists; SQL statement: ...

I know if I put @TestInstance(TestInstance.Lifecycle.PER_CALSS) annotation on top of class, test Data would be created once and all test methods would share data.

But the last test still keep fail.

test result image

答:
@Sql declared at a class level is run for each test method (default setting is to be run before method execution). You should add another @Sql script that drops the table and specify it to run after method:

```<code>@Sql(scripts = "cleanup.sql", executionPhase = AFTER_TEST_METHOD)
</code>```

Body:
I test this code

@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Sql(scripts = {"/sql/create-member.sql"})
@Transactional
class MemberServiceTest {

    @Autowired
    private MemberRepository memberRepository;

    @ParameterizedTest
    @ValueSource(longs = 1L)
    public void SelectMemberTest_A(Long id) {

        Member member = memberRepository.findById(id).get();

        assertEquals(1L, member.getId());
    }

    @ParameterizedTest
    @ValueSource(longs = 2L)
    public void SelectMemberTest_B(Long id) {

        Member member = memberRepository.findById(id).get();

        assertEquals(2L, member.getId());
    }
}

create-member.sql

CREATE TABLE Member
(
    id       int auto_increment
        primary key,
    username varchar(45),
    phone    varchar(45),
    address  varchar(45),
);

INSERT INTO Member (username, phone, address)
VALUES ('John', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('Jane', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('emily', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('chris', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('peter', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('sarah', '111-1111-1111', null);
INSERT INTO Member (username, phone, address)
VALUES ('kate', '111-1111-1111', null);

I keep fail the last test method which is SelectMemberTest_B(Long id) with exception Table "MEMBER" already exists; SQL statement: ...

I know if I put @TestInstance(TestInstance.Lifecycle.PER_CALSS) annotation on top of class, test Data would be created once and all test methods would share data.

But the last test still keep fail.

test result image

Body:
@Sql declared at a class level is run for each test method (default setting is to be run before method execution). You should add another @Sql script that drops the table and specify it to run after method:

@Sql(scripts = "cleanup.sql", executionPhase = AFTER_TEST_METHOD)


问:
Type mismatch: cannot convert from Agent to Fellow
In my model, various practitioners go to see patients multiple times in one visit. I am trying to ensure the same fellow is used to see a patient over multiple visits after being seized and released multiple times. I continue to receive this Type mismatch. Type Patient is the agent being pushed through the model and type Fellow belongs to a resource pool of 3 fellows.

答:
You must ensure that the variable fellow in your Patient agent type is of type Fellow.

You try to store the Fellow in the Patient.fellow variable but that variable is not of type Fellow, causing the problem.


问:
ie8 var w= window.open() - "Message: Invalid argument."
I have a site that has an IE8-only problem:

The code is:

```<code>var w = window.open(urlstring, wname, wfeatures, 'false');
</code>```

The error is:

Message: Invalid argument.

  Line: 419
  Char: 5

  Code: 0

  URI: http://HOSTNAME/js_context.js

I have confirmed the line number of the code (the "Line" and "URI" are correct), and I understand in later versions of IE8, this is considered accurate.

I have checked all the incoming parameters in the call by dumping alerts, and they all look valid.

This problem does not happen on FF (probably 3).

UPDATE:

The problem appears to be in using assigning the result of window.open() when doing "var w". When I split the line into two statements it works in IE8.

UPDATE2:

Based on:

http://javascript.crockford.com/code.html

When a function is to be invoked
  immediately, the entire invocation
  expression should be wrapped in parens
  so that it is clear that the value
  being produced is the result of the
  function and not the function itself.

This is not exactly what is going on here, but I found that applying the principle solved the problem, in IE8's compatability mode.

```<code>var w = (window.open(urlstring, wname, wfeatures, false));
</code>```

答: What does position four represent, the one that has 'false' as an value? Shouldn't that be false, (i.e. without quotes?). It's possible that earlier versions of IE would coerce the string to a boolean, but newer ones don't.</p>

OwnerDisplayName: benc

ContentLicense: CC BY-SA 3.0

Body:
I have a site that has an IE8-only problem:

The code is:

var w = window.open(urlstring, wname, wfeatures, 'false');

The error is:

Message: Invalid argument.

  Line: 419
  Char: 5

  Code: 0

  URI: http://HOSTNAME/js_context.js

I have confirmed the line number of the code (the "Line" and "URI" are correct), and I understand in later versions of IE8, this is considered accurate.

I have checked all the incoming parameters in the call by dumping alerts, and they all look valid.

This problem does not happen on FF (probably 3).

UPDATE:

The problem appears to be in using assigning the result of window.open() when doing "var w". When I split the line into two statements it works in IE8.

UPDATE2:

Based on:

http://javascript.crockford.com/code.html

When a function is to be invoked
  immediately, the entire invocation
  expression should be wrapped in parens
  so that it is clear that the value
  being produced is the result of the
  function and not the function itself.

This is not exactly what is going on here, but I found that applying the principle solved the problem, in IE8's compatability mode.

var w = (window.open(urlstring, wname, wfeatures, false));

LastEditorDisplayName: benc

ContentLicense: CC BY-SA 2.5


问:
Remove "OK" button from sweet alert dialog
I am using javascript sweetalert2 library.

I want to remove the OK button from the alert box but I did not find any property for not to display this button.

I am using the timer property timer:1000 for closing the alert in one second.
So, I don't think there is a use of the ok button in this matter.

答:
SWEET ALERT 2 | 2022 UPDATE

```<code>Swal.fire({
    ...
    showConfirmButton: false, //hide OK button
    allowOutsideClick: false, //optional, disable outside click for close the modal
    ...
});
</code>```

As new documentation here.

Body:
SWEET ALERT 2 | 2022 UPDATE

Swal.fire({
    ...
    showConfirmButton: false, //hide OK button
    allowOutsideClick: false, //optional, disable outside click for close the modal
    ...
});

As new documentation here.


问:
how we can run multiple queries on Firebase/firestore to get filtered data in flutter?
how we can run multiple queries on  Firebase/ firestore to get filtered data in flutter or any other possible solution? there is a picture storing dummy data in goal and title and wanna users according to the goals and titles filters.

答:
Where() is a function provided by Firebase to query data

```<code>FirebaseFirestore.instance.collection('yourCollectionName').where('field1', isEqual:'value1').where('field2', isEqual: 'value2').get();
</code>```

you can read more about it in the querying section at https://firebase.flutter.dev/docs/firestore/usage/

Body:
Where() is a function provided by Firebase to query data

FirebaseFirestore.instance.collection('yourCollectionName').where('field1', isEqual:'value1').where('field2', isEqual: 'value2').get();

you can read more about it in the querying section at https://firebase.flutter.dev/docs/firestore/usage/


问:
Firebase cloud messaging: Cannot receive notification in React-js
Firebase version: 9.6.6

firebase-messaging.js - inside a src folder

```<code>import firebase from "firebase/compat";
import "firebase/messaging";

const firebaseConfig = {
    //api
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

export const requestForToken = async () => {
    const swRegistration = await navigator.serviceWorker.register(`${process.env.PUBLIC_URL}/firebase-messaging-sw.js`);

    const token = await messaging.getToken({
        serviceWorkerRegistration: swRegistration,
    });

    return token;
};

export const onMessageListener = () =>
    new Promise((resolve) => {
        messaging.onMessage((payload) => {
            resolve(payload);
        });
    });
</code>```

firebase-messaging-sw.js - inside a public folder

```<code>import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

const firebaseApp = initializeApp({
    //api
});

const messaging = getMessaging(firebaseApp);
</code>```

Inside App.js

```<code>useEffect(()=> {
        if (!fcm_token) {
            requestForToken()
                .then(r => {
                    console.log("token: ", r);
                    dispatch(setFCMToken(r));
                })
                .catch(error => {
                    console.log("error while receiver fcm token from firebase: ", error)
                });
        } else {
            console.log("fcm token: ", fcm_token);
        }
    }, [])

onMessageListener()
        .then(value => console.log("notification msg: ", value))
        .catch(err => console.log("error: ", err))
</code>```

When I run the project

```
Failed to register a ServiceWorker for scope ('http://localhost:3000/build/')
with script ('http://localhost:3000/build/firebase-messaging-sw.js'):
ServiceWorker script evaluation failed
```

this error shows up, even though the code is correct according to documentation.

Error persists even if I change the way I import inside firebase-messaging-sw.js file to "importScripts(' ')".
Only after removing everything in firebase-messaging-sw.js file, that error do not show up and I can receive the FCM token.

However, when I send test messages from firebase console to FCM token received in my react app, no messages are showing up in console.

Question: How should I change my code to be able to receive notifications and show them in console or as a notification in browser.

答:
If you're using latest version there is alittle bit modifications in registering service worker file, this is complete process of notification configuration

register service worker as below in your service worker file:

```<code> export const registerServiceWorker = () => {
 if ('serviceWorker' in navigator) {
     navigator.serviceWorker
         .register('firebase-messaging-sw.js')
         .then(function (registration) {
             return registration.scope;
         })
         .catch(function (err) {
             return err;
         });
 }
</code>```

};

import service worker, and call function in your index.js File:

import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import { registerServiceWorker } from './serviceWorker';
    ReactDOM.render(
        <React.StrictMode>
                <App />
        </React.StrictMode>,
        document.getElementById('root')
    );
    registerServiceWorker();```

After this configuration, you will see fire base notification in console, and if  firebase-messaging.js file is configured well with no error, your feature will work

Body:
Firebase version: 9.6.6

firebase-messaging.js - inside a src folder

import firebase from "firebase/compat";
import "firebase/messaging";

const firebaseConfig = {
    //api
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

export const requestForToken = async () => {
    const swRegistration = await navigator.serviceWorker.register(`${process.env.PUBLIC_URL}/firebase-messaging-sw.js`);

    const token = await messaging.getToken({
        serviceWorkerRegistration: swRegistration,
    });

    return token;
};

export const onMessageListener = () =>
    new Promise((resolve) => {
        messaging.onMessage((payload) => {
            resolve(payload);
        });
    });

firebase-messaging-sw.js - inside a public folder

import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";

const firebaseApp = initializeApp({
    //api
});

const messaging = getMessaging(firebaseApp);

Inside App.js

useEffect(()=> {
        if (!fcm_token) {
            requestForToken()
                .then(r => {
                    console.log("token: ", r);
                    dispatch(setFCMToken(r));
                })
                .catch(error => {
                    console.log("error while receiver fcm token from firebase: ", error)
                });
        } else {
            console.log("fcm token: ", fcm_token);
        }
    }, [])

onMessageListener()
        .then(value => console.log("notification msg: ", value))
        .catch(err => console.log("error: ", err))

When I run the project

Failed to register a ServiceWorker for scope ('http://localhost:3000/build/')
with script ('http://localhost:3000/build/firebase-messaging-sw.js'):
ServiceWorker script evaluation failed

this error shows up, even though the code is correct according to documentation.

Error persists even if I change the way I import inside firebase-messaging-sw.js file to "importScripts(' ')".
Only after removing everything in firebase-messaging-sw.js file, that error do not show up and I can receive the FCM token.

However, when I send test messages from firebase console to FCM token received in my react app, no messages are showing up in console.

Question: How should I change my code to be able to receive notifications and show them in console or as a notification in browser.

Body:
If you're using latest version there is alittle bit modifications in registering service worker file, this is complete process of notification configuration

register service worker as below in your service worker file:

 export const registerServiceWorker = () => {
 if ('serviceWorker' in navigator) {
     navigator.serviceWorker
         .register('firebase-messaging-sw.js')
         .then(function (registration) {
             return registration.scope;
         })
         .catch(function (err) {
             return err;
         });
 }

};

import service worker, and call function in your index.js File:

import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import { registerServiceWorker } from './serviceWorker';
    ReactDOM.render(
        <React.StrictMode>
                <App />
        </React.StrictMode>,
        document.getElementById('root')
    );
    registerServiceWorker();

After this configuration, you will see fire base notification in console, and if  firebase-messaging.js file is configured well with no error, your feature will work


问:
How to delete a row from datagrid by selecting a node from treenode?
Iam entering data in datagridview in c# when i draw a rectangle on picturebox, i have an array where i store the rectangle data , whenever i enter a new row, i also create a new childnode in treeview. Now i want to delete a row in datagridview by selecting the corresponding treenode. But my code is not working properly. I mostly get out of range exception errors.

Please help me fix this?

This is my code to delete the row:

```<code>         int pos = (int) treeView1.SelectedNode.Tag;

            if (treeView1.SelectedNode.Name.Contains("Code"))
            {
                if (pos == 0)
                {
                    MessageBox.Show("Cannot delete 1st node");
                }

                else
                {
                    treeView1.SelectedNode.Remove();

                    for (int i = pos; i < rectincr; i++)
                    {
                        PB1CodeRect[i] = PB1CodeRect[i + 1]; //delete rectangle with row and node
                        dataGridView2.Rows[i].Tag = pos;
                        dataGridView2.Rows[poss].Selected = true;

                        foreach (DataGridViewRow item in this.dataGridView2.SelectedRows)
                        {
                            dataGridView2.Rows.RemoveAt(item.Index); //delete dgvrow
                        }
                    }

                }
</code>```

And this is the part of code where dgv and node is inserted.

```<code>       {
       PB1CodeRect[pb1Coderectincr] = new Rectangle(Convert.ToInt32(cibcam1.SelectionRegion.X), Convert.ToInt32(cibcam1.SelectionRegion.Y), Convert.ToInt32(cibcam1.SelectionRegion.Width), Convert.ToInt32(cibcam1.SelectionRegion.Height));
            pb1Coderectincr++;
            this.dataGridView2.Rows.Add(pb1Coderectincr, tabControl2.SelectedTab.Text, "2dCode - " + cibcam1.SelectionRegion.X + "," + cibcam1.SelectionRegion.Y + "," + cibcam1.SelectionRegion.Width + "," + cibcam1.SelectionRegion.Height,0);

            codenodcam1.Name = "Code ROI-" + pb1Coderectincr;
            codenodcam1.Text = "Code ROI-" + pb1Coderectincr;
            codenodcam1.Tag = pb1Coderectincr + 1;
           //var dict = (Dictionary<int, int>)codenodcam1.Nodes[0].Tag;
           // dict[pb1Coderectincr] = pb1Coderectincr;
            mainNode.Nodes.Add(codenodcam1);
            mainNode.ExpandAll();
           }
</code>```

答:
I found the solution.

In reply to JohnG's questions - im building an image processing application where I draw an ROI, the roi rectangle coordinates are saved in the PBRect[] array because there would be multiple rectangles. Each rectangle's coordinates, index, inspection result are stored in a row of DGV. The treeview is to allow the user easy access to manipulate ROI size, delete roi etc. The DGV is hidden from user view.

I made the mistake of adding pb1Coderectincr++ before i updated values, so the increment has to be the last one.

I also updated the DGV index value once a node, rect and row has been deleted so the index is not messed up. Here is the working code to delete node, row and rectangle:

```<code>       int pos = (int)treeView1.SelectedNode.Index;
       if (pos == 0)
                {
                    MessageBox.Show("Cannot delete 1st node");
                }
                else
                {
                    treeView1.SelectedNode.Remove(); //delete node
                    for (int i = pos; i < pb1Coderectincr; i++) //delete rectangle
                    {
                        PB1CodeRect[i] = PB1CodeRect[i + 1];
                    }
                    dataGridView2.Rows[pos].Selected = true;
                    foreach (DataGridViewRow item in this.dataGridView2.SelectedRows) //delete dgv row
                    {
                        dataGridView2.Rows.RemoveAt(item.Index);
                        if (!item.IsNewRow) // update index
                        {
                            item.Cells[0].Value = item.Index + 1;
                        }
                    }
                    treeView1.Focus();
                }
</code>```

Body:
Iam entering data in datagridview in c# when i draw a rectangle on picturebox, i have an array where i store the rectangle data , whenever i enter a new row, i also create a new childnode in treeview. Now i want to delete a row in datagridview by selecting the corresponding treenode. But my code is not working properly. I mostly get out of range exception errors.

Please help me fix this?

This is my code to delete the row:

         int pos = (int) treeView1.SelectedNode.Tag;

            if (treeView1.SelectedNode.Name.Contains("Code"))
            {
                if (pos == 0)
                {
                    MessageBox.Show("Cannot delete 1st node");
                }

                else
                {
                    treeView1.SelectedNode.Remove();

                    for (int i = pos; i < rectincr; i++)
                    {
                        PB1CodeRect[i] = PB1CodeRect[i + 1]; //delete rectangle with row and node
                        dataGridView2.Rows[i].Tag = pos;
                        dataGridView2.Rows[poss].Selected = true;

                        foreach (DataGridViewRow item in this.dataGridView2.SelectedRows)
                        {
                            dataGridView2.Rows.RemoveAt(item.Index); //delete dgvrow
                        }
                    }

                }

And this is the part of code where dgv and node is inserted.

       {
       PB1CodeRect[pb1Coderectincr] = new Rectangle(Convert.ToInt32(cibcam1.SelectionRegion.X), Convert.ToInt32(cibcam1.SelectionRegion.Y), Convert.ToInt32(cibcam1.SelectionRegion.Width), Convert.ToInt32(cibcam1.SelectionRegion.Height));
            pb1Coderectincr++;
            this.dataGridView2.Rows.Add(pb1Coderectincr, tabControl2.SelectedTab.Text, "2dCode - " + cibcam1.SelectionRegion.X + "," + cibcam1.SelectionRegion.Y + "," + cibcam1.SelectionRegion.Width + "," + cibcam1.SelectionRegion.Height,0);

            codenodcam1.Name = "Code ROI-" + pb1Coderectincr;
            codenodcam1.Text = "Code ROI-" + pb1Coderectincr;
            codenodcam1.Tag = pb1Coderectincr + 1;
           //var dict = (Dictionary<int, int>)codenodcam1.Nodes[0].Tag;
           // dict[pb1Coderectincr] = pb1Coderectincr;
            mainNode.Nodes.Add(codenodcam1);
            mainNode.ExpandAll();
           }

Body:
I found the solution.

In reply to JohnG's questions - im building an image processing application where I draw an ROI, the roi rectangle coordinates are saved in the PBRect[] array because there would be multiple rectangles. Each rectangle's coordinates, index, inspection result are stored in a row of DGV. The treeview is to allow the user easy access to manipulate ROI size, delete roi etc. The DGV is hidden from user view.

I made the mistake of adding pb1Coderectincr++ before i updated values, so the increment has to be the last one.

I also updated the DGV index value once a node, rect and row has been deleted so the index is not messed up. Here is the working code to delete node, row and rectangle:

       int pos = (int)treeView1.SelectedNode.Index;
       if (pos == 0)
                {
                    MessageBox.Show("Cannot delete 1st node");
                }
                else
                {
                    treeView1.SelectedNode.Remove(); //delete node
                    for (int i = pos; i < pb1Coderectincr; i++) //delete rectangle
                    {
                        PB1CodeRect[i] = PB1CodeRect[i + 1];
                    }
                    dataGridView2.Rows[pos].Selected = true;
                    foreach (DataGridViewRow item in this.dataGridView2.SelectedRows) //delete dgv row
                    {
                        dataGridView2.Rows.RemoveAt(item.Index);
                        if (!item.IsNewRow) // update index
                        {
                            item.Cells[0].Value = item.Index + 1;
                        }
                    }
                    treeView1.Focus();
                }


问:
How to specify the JAXB version in maven-jaxb2-plugin?
I need to use the latest version jaxb: 2.2.4-1, but maven or maven-jaxb2-plugin seems to pick up the one from the JDK.

I tried specifying the version like this:

```<code><configuration>
    <specVersion>2.2</specVersion>
    ...
</configuration>
</code>```

but the logs read:

```<code>[INFO] [jaxb2:generate {execution: common}]
[INFO] Started execution.
[INFO] JAXB API is loaded from the [jar:file:/opt/jdk1.6.0_24/jre/lib/rt.jar!].
[INFO] Detected JAXB API version [2.1].
</code>```

I tried to add dependencies to the correct versions of javax.xml.bind:jaxb-api and com.sun.xml.bind:jaxb-impl, but that didn't help.

```<code><plugins>
    <plugin>
        <groupId>org.jvnet.jaxb2.maven2</groupId>
        <artifactId>maven-jaxb2-plugin</artifactId>
        <version>0.8.0</version>

        <dependencies>
            <dependency>
                <groupId>javax.xml.bind</groupId>
                <artifactId>jaxb-api</artifactId>
                <version>2.2.4</version>
            </dependency>

            <dependency>
                <groupId>com.sun.xml.bind</groupId>
                <artifactId>jaxb-impl</artifactId>
                <version>2.2.4-1</version>
            </dependency>
        </dependencies>

        <executions>
            <execution>
                <id>common</id>
                <goals>
                    <goal>generate</goal>
                </goals>
                <configuration>
                    <specVersion>2.2</specVersion>
                    ...
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>
</code>```

I also tried using maven-jaxb22-plugin but it also didn't work.

答:
The following code is adapted from the default webapp that netbeans generates. It uses the dependency plugin to copy the jars to a temporary folder and specifies this folder as the endorsed directory to the compiler so it overrides the implementation in the jdk.</p>

```<code><properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
</properties>

...

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax.xml.bind</groupId>
                                <artifactId>jaxb-api</artifactId>
                                <version>2.2.4</version>
                                <type>jar</type>
                            </artifactItem>
                            <artifactItem>
                                <groupId>com.sun.xml.bind</groupId>
                                <artifactId>jaxb-impl</artifactId>
                                <version>2.2.4-1</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

Body:
I need to use the latest version jaxb: 2.2.4-1, but maven or maven-jaxb2-plugin seems to pick up the one from the JDK.

I tried specifying the version like this:

<configuration>
    <specVersion>2.2</specVersion>
    ...
</configuration>

but the logs read:

[INFO] [jaxb2:generate {execution: common}]
[INFO] Started execution.
[INFO] JAXB API is loaded from the [jar:file:/opt/jdk1.6.0_24/jre/lib/rt.jar!].
[INFO] Detected JAXB API version [2.1].

I tried to add dependencies to the correct versions of javax.xml.bind:jaxb-api and com.sun.xml.bind:jaxb-impl, but that didn't help.

<plugins>
    <plugin>
        <groupId>org.jvnet.jaxb2.maven2</groupId>
        <artifactId>maven-jaxb2-plugin</artifactId>
        <version>0.8.0</version>

        <dependencies>
            <dependency>
                <groupId>javax.xml.bind</groupId>
                <artifactId>jaxb-api</artifactId>
                <version>2.2.4</version>
            </dependency>

            <dependency>
                <groupId>com.sun.xml.bind</groupId>
                <artifactId>jaxb-impl</artifactId>
                <version>2.2.4-1</version>
            </dependency>
        </dependencies>

        <executions>
            <execution>
                <id>common</id>
                <goals>
                    <goal>generate</goal>
                </goals>
                <configuration>
                    <specVersion>2.2</specVersion>
                    ...
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>

I also tried using maven-jaxb22-plugin but it also didn't work.

Body:
The following code is adapted from the default webapp that netbeans generates. It uses the dependency plugin to copy the jars to a temporary folder and specifies this folder as the endorsed directory to the compiler so it overrides the implementation in the jdk.

<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
</properties>

...

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax.xml.bind</groupId>
                                <artifactId>jaxb-api</artifactId>
                                <version>2.2.4</version>
                                <type>jar</type>
                            </artifactItem>
                            <artifactItem>
                                <groupId>com.sun.xml.bind</groupId>
                                <artifactId>jaxb-impl</artifactId>
                                <version>2.2.4-1</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


问:
Flutter initialization failed.couldn't find "libflutter.so"
E/FlutterLoader( 4087): Flutter initialization failed.
E/FlutterLoader( 4087): java.util.concurrent.ExecutionException: java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.kmz.TheCounsler-1/base.apk"],nativeLibraryDirectories=[/data/app/com.kmz.TheCounsler-1/lib/arm, /data/app/com.kmz.TheCounsler-1/base.apk!/lib/armeabi-v7a, /system/lib, /vendor/lib]]] couldn't find "libflutter.so"
E/FlutterLoader( 4087):     at java.util.concurrent.FutureTask.report(FutureTask.java:94)
E/FlutterLoader( 4087):     at java.util.concurrent.FutureTask.get(FutureTask.java:164)
E/FlutterLoader( 4087):     at io.flutter.embedding.engine.loader.FlutterLoader.ensureInitializationComplete(FlutterLoader.java:201)
E/FlutterLoader( 4087):     at io.flutter.embedding.engine.FlutterEngine.(FlutterEngine.java:326)
E/FlutterLoader( 4087):     at io.flutter.embedding.engine.FlutterEngine.(FlutterEngine.java:206)
E/FlutterLoader( 4087):     at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.setupFlutterEngine(FlutterActivityAndFragmentDelegate.java:252)
E/FlutterLoader( 4087):     at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach(FlutterActivityAndFragmentDelegate.java:162)
E/FlutterLoader( 4087):     at io.flutter.embedding.android.FlutterActivity.onCreate(FlutterActivity.java:430)
E/FlutterLoader( 4087):     at android.app.Activity.performCreate(Activity.java:6739)
E/FlutterLoader( 4087):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
E/FlutterLoader( 4087):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2619)
E/FlutterLoader( 4087):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
E/FlutterLoader( 4087):     at android.app.ActivityThread.-wrap12(ActivityThread.java)
E/FlutterLoader( 4087):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
E/FlutterLoader( 4087):     at android.os.Handler.dispatchMessage(Handler.java:102)</p>

答:
Add this line to your android/app/build.gradle file</p>
```<code>ndk {
  abiFilters 'armeabi-v7a'
}
</code>```

Body:
Add this line to your android/app/build.gradle file

ndk {
  abiFilters 'armeabi-v7a'
}


问:
how does openGauss choose compression algorithm to compress data?
I learned dev doc. the create table command contains usage parameters. One of them is called [ COMPRESS | NOCOMPRESS ] as this following:

```<code>CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name
    [ (column_name [, ...] ) ]
    [ WITH ( {storage_parameter = value} [, ... ] ) ]
    [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
    [ COMPRESS | NOCOMPRESS ]
    [ TABLESPACE tablespace_name ]
    AS query
    [ WITH [ NO ] DATA ];
</code>```

So when I use it, which compression algorithm would openGauss to choose to use for different data type?

答:
As we know. openGauss supports many kinds of compression algorithms include RLE、DELTA、BYTEPACK/BITPACK、LZ4、ZLIB、LOCAL DICTIONARY.  It would find out suitable algorithm for different data type. detail information is below:

https://opengauss.org/en/docs/2.0.0/docs/CharacteristicDescription/adaptive-compression.html

Body:
I learned dev doc. the create table command contains usage parameters. One of them is called [ COMPRESS | NOCOMPRESS ] as this following:

CREATE [ [ GLOBAL | LOCAL ] [ TEMPORARY | TEMP ] | UNLOGGED ] TABLE table_name
    [ (column_name [, ...] ) ]
    [ WITH ( {storage_parameter = value} [, ... ] ) ]
    [ ON COMMIT { PRESERVE ROWS | DELETE ROWS | DROP } ]
    [ COMPRESS | NOCOMPRESS ]
    [ TABLESPACE tablespace_name ]
    AS query
    [ WITH [ NO ] DATA ];

So when I use it, which compression algorithm would openGauss to choose to use for different data type?


问:
Spring jdbcTemplate retrieve numeric values from query
I have this query for my jdbcTemplate and I wanna get just the long value from the database, what should be fixed here?</p>
```<code>String query = "SELECT size from users where name = ? AND type = ?";
long size = jdbcTemplate.query(query, new Object[]{id, type}, (rs, rowNum) ->
rs.getLong("size"));
</code>```

答:
```<code>long size = jdbcTemplate.queryForObject(query, Long.class);
</code>```

Body:
I have this query for my jdbcTemplate and I wanna get just the long value from the database, what should be fixed here?

String query = "SELECT size from users where name = ? AND type = ?";
long size = jdbcTemplate.query(query, new Object[]{id, type}, (rs, rowNum) ->
rs.getLong("size"));


问:
Attaching components after gltf.InstantiateMainScene through glTFast in Unity3D
I'm loading and instantiating a glTF model using glTFast in Unity. After I load and instantiate the model successfully in runtime, I need to attach a component to the instantiated GameObject through the gameObject.AddComponent<>() method.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Microsoft.MixedReality.Toolkit.UI;

public class ObjectManager : MonoBehaviour
{
    //This runs first
    void OnEnable()
    {
        Debug.Log("OnEnable called");
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    //this runs second
    async void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("OnSceneLoaded: " + scene.name);

        var gltf = new GLTFast.GltfImport();

        var success = await gltf.Load("file://Assets/Models/lounger_armchair/scene.gltf");

        if (success)
        {

            // Instantiate the glTF's main scene
            gltf.InstantiateMainScene(new GameObject("PlacedModel").transform);

        }
        else
        {
            Debug.LogError("Loading glTF failed!");
        }
    }

}
</code>```

答:
Assuming the rest works as expected as I understand you want to attach a component to the PlacedModel object.

You could simply store it beforehand and do

```<code>var placedModel = new GameObject("PlacedModel").transform;
if(gltf.InstantiateMainScene(placedModel))
{
    placedModel.gameObject.AddComponent<SomeComponent>();
}
else
{
    Debug.LogError("Instantiating glTF failed!");
    Destroy (placedModel);
}
</code>```

Or the same if you rather want to attach the component to the first child of that object

```<code>var placedModel = new GameObject("PlacedModel").transform;
if(gltf.InstantiateMainScene(placedModel))
{
    placedModel.GetChild(0).gameObject.AddComponent<SomeComponent>();
}
else
{
    Debug.LogError("Instantiating glTF failed!");
    Destroy (placedModel);
}
</code>```

Body:
I'm loading and instantiating a glTF model using glTFast in Unity. After I load and instantiate the model successfully in runtime, I need to attach a component to the instantiated GameObject through the gameObject.AddComponent<>() method.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Microsoft.MixedReality.Toolkit.UI;

public class ObjectManager : MonoBehaviour
{
    //This runs first
    void OnEnable()
    {
        Debug.Log("OnEnable called");
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    //this runs second
    async void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log("OnSceneLoaded: " + scene.name);

        var gltf = new GLTFast.GltfImport();

        var success = await gltf.Load("file://Assets/Models/lounger_armchair/scene.gltf");

        if (success)
        {

            // Instantiate the glTF's main scene
            gltf.InstantiateMainScene(new GameObject("PlacedModel").transform);

        }
        else
        {
            Debug.LogError("Loading glTF failed!");
        }
    }

}

Body:
Assuming the rest works as expected as I understand you want to attach a component to the PlacedModel object.

You could simply store it beforehand and do

var placedModel = new GameObject("PlacedModel").transform;
if(gltf.InstantiateMainScene(placedModel))
{
    placedModel.gameObject.AddComponent<SomeComponent>();
}
else
{
    Debug.LogError("Instantiating glTF failed!");
    Destroy (placedModel);
}

Or the same if you rather want to attach the component to the first child of that object

var placedModel = new GameObject("PlacedModel").transform;
if(gltf.InstantiateMainScene(placedModel))
{
    placedModel.GetChild(0).gameObject.AddComponent<SomeComponent>();
}
else
{
    Debug.LogError("Instantiating glTF failed!");
    Destroy (placedModel);
}


问:
Microsoft graph API: permission grant for application (app roles) (NOT delegate via Oauth2PermissionGrants)
We are using the Microsoft graph API (.net SDK).

We know that we can use GraphServiceClient.Oauth2PermissionGrants for delegated grant (in Azure AD app it's "Expose an API").

But when it comes to granting admin consent for application type (via app role of other applications), like below:

In the portal, we can just click "Grant admin consent for XXXX".

I could not figure out how to GraphServiceClient.PermissionGrants does not seem to be the one we are after.

答:
Googled around, found the related answer Azure OAuth: Unable to programmatically create app with admin consent for permissions , which leads me to the actual API used https://learn.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignedto?view=graph-rest-1.0&tabs=csharp

In a nutshell, use app role assignment via AppRoleAssignedTo:

```<code>GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var appRoleAssignment = new AppRoleAssignment
{
    PrincipalId = Guid.Parse("THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-NEEDS-ACCESS"),
    ResourceId = Guid.Parse("THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-HAS-THE-APP-ROLE-DEFINED"),
    AppRoleId = Guid.Parse("THE-ID-OF-THE-APP-ROLE-DEFINED-IN-THE-RESOURCE-ID-ABOVE")
};

await graphClient.ServicePrincipals["THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-HAS-THE-APP-ROLE-DEFINED"].AppRoleAssignedTo
    .Request()
    .AddAsync(appRoleAssignment);
</code>```

Body:
Googled around, found the related answer Azure OAuth: Unable to programmatically create app with admin consent for permissions , which leads me to the actual API used https://learn.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignedto?view=graph-rest-1.0&tabs=csharp

In a nutshell, use app role assignment via AppRoleAssignedTo:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var appRoleAssignment = new AppRoleAssignment
{
    PrincipalId = Guid.Parse("THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-NEEDS-ACCESS"),
    ResourceId = Guid.Parse("THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-HAS-THE-APP-ROLE-DEFINED"),
    AppRoleId = Guid.Parse("THE-ID-OF-THE-APP-ROLE-DEFINED-IN-THE-RESOURCE-ID-ABOVE")
};

await graphClient.ServicePrincipals["THE-OBJECT-ID-OF-THE-PRINCIPAL-OF-THE-AZURE-AD-APPLICATION-THAT-HAS-THE-APP-ROLE-DEFINED"].AppRoleAssignedTo
    .Request()
    .AddAsync(appRoleAssignment);


问:
java static method for abstract class
I have a java abstract class that declares the extended class as "JsonSerializable"

public abstract class JsonSerializable {
    private final String path;

    public JsonSerializable(String path) {
        this.path = path;
    }
}
```
<p>Now, if I try to "load" a class that extends <code>JsonSerializable</code> I need to get the "filepath" for the class I want to load.
The way I am currently doing this is as follows:</p>
<pre class="lang-java prettyprint-override"><code>private static <T extends JsonSerializable> T getNew(Class<T> tClass) throws [...] {
        return tClass.getDeclaredConstructor().newInstance();
}
</code>```

But what if the constructing of a new class (of the type I am trying to load) has some side effects (e.g. upon initialization, the class "registers" itself inside another one) or if there IS no constructor with no arguments?

Is there any better way to do this? I don't want to create a "FileRegistry" class that just holds the file paths for each class.

答:
But what if the constructing of a new class (of the type I am trying to load) has some side effects (e.g. upon initialization, the class "registers" itself inside another one)

Constructor#newInstance invokes the constructor. If it has side effects, those things will happen. But note that ideally, constructors should only initialize the object and not have side effects (especially nothing that leak the object/publosh the this-reference before the constructor finishes.

or if there IS no constructor with no arguments?

In that case, getDeclaredConstructor() throws an exception. However, you can get all constructors using Class#getDeclaredConstructors.

However, you can specify that classes extending JsonSerializable must have a no-args-constructor with no side effects in the Javadoc of JsonSerializable.

While you can create new instances without invoking the constructor using Unsafe, this should be avoided as it would leave variables uninitialized likely resulting in future exceptions.

Title: java static method for abstract class

Body:
I have a java abstract class that declares the extended class as "JsonSerializable"

public abstract class JsonSerializable {
    private final String path;

    public JsonSerializable(String path) {
        this.path = path;
    }
}

Now, if I try to "load" a class that extends JsonSerializable I need to get the "filepath" for the class I want to load.
The way I am currently doing this is as follows:

private static <T extends JsonSerializable> T getNew(Class<T> tClass) throws [...] {
        return tClass.getDeclaredConstructor().newInstance();
}

But what if the constructing of a new class (of the type I am trying to load) has some side effects (e.g. upon initialization, the class "registers" itself inside another one) or if there IS no constructor with no arguments?

Is there any better way to do this? I don't want to create a "FileRegistry" class that just holds the file paths for each class.


问:
For how long does Android save a killed activity's state?
I just did a little test: I started my app, went to a certain screen, pressed the home button and killed the process via Advanced Task Killer.

Now, if I go back to my app just a few moments later, I come back to that very screen. I also know that onRestoreInstanceState() is called in this case, as I have played around with this method quite a bit.

However, just out of curiosity, I did all the same, but let my phone lie around for some time (an hour or something). When I restarted my app, it went straight to the main activity.

So my question is: for how long does Android keep the saved state? or what determines if it throws it away or not? I already figured out it had nothing to do with lockscreen on/off.

Kind regards,
jellyfish

答: When you killed an application with Advanced Task Killer for example, the application restart with the main activity the next time. I suppose that the application save the state in file to restore the same activity even if it killed!</p>


问:
Django 4. Invalid block tag on line 45: 'item.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I work on Django 4
I am trying to create a view that will load a template view in django and I am getting the above error.

Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 4.0.2
Exception Type: TemplateSyntaxError
Exception Value:

Invalid block tag on line 45: 'item.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Exception Location: C:\Users\zinnurov.ramil\PycharmProjects\django_full_guide\venv\lib\site-packages\django\template\base.py, line 552, in invalid_block_tag
Python Executable:  C:\Users\zinnurov.ramil\PycharmProjects\django_full_guide\venv\Scripts\python.exe
Python Version: 3.9.4

views.py

def index(request):
    template_name = 'news/index.html'
    news = News.objects.order_by('-created_at')
    categories = Category.objects.all()
    context = {
        'title': 'Список новостей',
        'news': news,
        'categories': categories,
    }
    return render(request, template_name, context)```
</div>
</div>
</p>
<p>model.py</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>class Category(models.Model):
    title = models.CharField(max_length=200, db_index=True,
                             verbose_name='Категории')

    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'
        ordering = ['-title']

    def __str__(self):
        return self.title</code>```

                {% for cat in categories %}
                {% item.title %}
                {% endfor %}

```

enter image description here
Have you got an idea ?

答:
you need {{ item.title }} instead of {% item.title %}. This is a syntax error

Btw it seems like {{ item.title }} will be None. Try {{ cat.title }} since you assigned "cat" in your for loop.

Body:
I work on Django 4
I am trying to create a view that will load a template view in django and I am getting the above error.

Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 4.0.2
Exception Type: TemplateSyntaxError
Exception Value:

Invalid block tag on line 45: 'item.title', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Exception Location: C:\Users\zinnurov.ramil\PycharmProjects\django_full_guide\venv\lib\site-packages\django\template\base.py, line 552, in invalid_block_tag
Python Executable:  C:\Users\zinnurov.ramil\PycharmProjects\django_full_guide\venv\Scripts\python.exe
Python Version: 3.9.4

views.py

def index(request):
    template_name = 'news/index.html'
    news = News.objects.order_by('-created_at')
    categories = Category.objects.all()
    context = {
        'title': 'Список новостей',
        'news': news,
        'categories': categories,
    }
    return render(request, template_name, context)

model.py

class Category(models.Model):
    title = models.CharField(max_length=200, db_index=True,
                             verbose_name='Категории')

    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'
        ordering = ['-title']

    def __str__(self):
        return self.title

                {% for cat in categories %}
                {% item.title %}
                {% endfor %}

enter image description here
Have you got an idea ?


问:
PIL ValueError: not enough image data?
I'm getting an error with its message as above when I tried to fetch an image from a URL and converting the string in its response to Image within App Engine.

```<code>from google.appengine.api import urlfetch

def fetch_img(url):
  try:
    result = urlfetch.fetch(url=url)
    if result.status_code == 200:
      return result.content
  except Exception, e:
    logging.error(e)

url = "http://maps.googleapis.com/maps/api/staticmap?center=Narita+International+Airport,Narita,Chiba+Prefecture,+Japan&zoom=18&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"

img = fetch_img(url)
# As the URL above tells, its size is 512x512
img = Image.fromstring('RGBA', (512, 512), img)
</code>```

According to PIL, size option is suppose to be a tuple of pixels. This I specified. Could anyone point out my misunderstanding?

答:
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.show()
```

It work for my

Title: PIL ValueError: not enough image data?

Body:
I'm getting an error with its message as above when I tried to fetch an image from a URL and converting the string in its response to Image within App Engine.

from google.appengine.api import urlfetch

def fetch_img(url):
  try:
    result = urlfetch.fetch(url=url)
    if result.status_code == 200:
      return result.content
  except Exception, e:
    logging.error(e)

url = "http://maps.googleapis.com/maps/api/staticmap?center=Narita+International+Airport,Narita,Chiba+Prefecture,+Japan&zoom=18&size=512x512&maptype=roadmap&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false"

img = fetch_img(url)
# As the URL above tells, its size is 512x512
img = Image.fromstring('RGBA', (512, 512), img)

According to PIL, size option is suppose to be a tuple of pixels. This I specified. Could anyone point out my misunderstanding?

Body:
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.show()

It work for my


问:
access to variable in c++ inner class
I'm using cairomm, opencv4, box2d(not revealed in below code) to make physics education video.

My plan is like this.
Many Sobject(Scientific obect) constitute a Scene.
So I decided to use inner-class.(I don't know it's best design, I'm newbie to programming)

My problem is in below.

```<code>cv::Mat Surface2Mat(Cairo::RefPtr<Cairo::ImageSurface> surface)
{
    cv::Mat Frame(surface->get_height(), surface->get_width(), CV_8UC4, surface->get_data(), surface->get_stride());
    cv::cvtColor(Frame, Frame, cv::ColorConversionCodes::COLOR_BGRA2BGR);
    return Frame;
}

class Scene
{
private:
    int surface_width = 1920;
    int surface_height = 1080;
    int second = 4;

    cv::Size resolution = {surface_width, surface_height};
    const int mp4 = cv::VideoWriter::fourcc('a', 'v', 'c', '1');
    cv::VideoWriter video;
    double FPS;

public:
    class Sobject
    {
    private:
        double width;
        double height;
        double color[3] = {1, 1, 1};

    public:
        Cairo::RefPtr<Cairo::Context> cr;
        Cairo::RefPtr<Cairo::ImageSurface> surface;
        Sobject()
        {
            surface = Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 1920, 1080);
            cr = Cairo::Context::create(surface);
        }
        void
        set_position(double x = 0, double y = 0)
        {
            cr->move_to(960, 540);
        }
        void drawCircle()
        {
            cr->arc(0, 0, 40, 0.0, 2 * M_PI);
        }
    };

    Scene(int width = 1920, int height = 1080)
    {

        video.open("Scene.mp4", mp4, FPS = 30, resolution, true);
    }
    ~Scene()
    {
        video.release();
    }
    void write()
    {
        for (int i = 0; i < (FPS * second); i++)
        {
            video.write(Surface2Mat(surface));
        }
    }
};
</code>```

The "video.write(Surface2Mat(surface));" at last makes problem.
How can I access to the surface?

答:
You have not created an instance of Sobject. You can do something like:

```<code>class Scene
{
....
public:
    class Sobject
    {...};

    Sobject mSobject; // can have it public or private depending on other requirements

    ....

    void write()
    {
        for (int i = 0; i < (FPS * second); i++)
        {
            // now that you have an instance of Sobject, you can use surface from it
            video.write(Surface2Mat(mSobject.surface));
        }
    }
</code>```

Title: access to variable in c++ inner class

Body:
I'm using cairomm, opencv4, box2d(not revealed in below code) to make physics education video.

My plan is like this.
Many Sobject(Scientific obect) constitute a Scene.
So I decided to use inner-class.(I don't know it's best design, I'm newbie to programming)

My problem is in below.

cv::Mat Surface2Mat(Cairo::RefPtr<Cairo::ImageSurface> surface)
{
    cv::Mat Frame(surface->get_height(), surface->get_width(), CV_8UC4, surface->get_data(), surface->get_stride());
    cv::cvtColor(Frame, Frame, cv::ColorConversionCodes::COLOR_BGRA2BGR);
    return Frame;
}

class Scene
{
private:
    int surface_width = 1920;
    int surface_height = 1080;
    int second = 4;

    cv::Size resolution = {surface_width, surface_height};
    const int mp4 = cv::VideoWriter::fourcc('a', 'v', 'c', '1');
    cv::VideoWriter video;
    double FPS;

public:
    class Sobject
    {
    private:
        double width;
        double height;
        double color[3] = {1, 1, 1};

    public:
        Cairo::RefPtr<Cairo::Context> cr;
        Cairo::RefPtr<Cairo::ImageSurface> surface;
        Sobject()
        {
            surface = Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 1920, 1080);
            cr = Cairo::Context::create(surface);
        }
        void
        set_position(double x = 0, double y = 0)
        {
            cr->move_to(960, 540);
        }
        void drawCircle()
        {
            cr->arc(0, 0, 40, 0.0, 2 * M_PI);
        }
    };

    Scene(int width = 1920, int height = 1080)
    {

        video.open("Scene.mp4", mp4, FPS = 30, resolution, true);
    }
    ~Scene()
    {
        video.release();
    }
    void write()
    {
        for (int i = 0; i < (FPS * second); i++)
        {
            video.write(Surface2Mat(surface));
        }
    }
};

The "video.write(Surface2Mat(surface));" at last makes problem.
How can I access to the surface?

Body:
You have not created an instance of Sobject. You can do something like:

class Scene
{
....
public:
    class Sobject
    {...};

    Sobject mSobject; // can have it public or private depending on other requirements

    ....

    void write()
    {
        for (int i = 0; i < (FPS * second); i++)
        {
            // now that you have an instance of Sobject, you can use surface from it
            video.write(Surface2Mat(mSobject.surface));
        }
    }


问:
Zip deploy azure function from storage account
I'm trying to zip deploy an azure function from a blob storage.

I have set SCM_DO_BUILD_DURING_DEPLOYMENT, to true.
I have also set WEBSITE_RUN_FROM_PACKAGE to the remote url.

I am able to deploy easily if the function is in a remote url. However, I can't seem to do it if I have it as a blob on azure.

The prefarable runtime for this is python.

答:
For having the zip deploy from storage account you need to navigate to your .zip blob in your storage account and get the generated SAS token for that blob.

Then add the same url in your Function App Application settings for WEBSITE_RUN_FROM_PACKAGE.

NOTE:- This option is the only one supported for running from a package on Linux hosted in a Consumption plan.

For more information on this you can refer Run your functions from a package file in Azure


问:
Domain Driven Design - How do I model a Company and Employee use case?
I've been digging into DDD for the first time the last few weeks. I'm developing an HR application and am really struggling with the idea of Aggregate Roots.

So the current entities would be:

Company

Employee

Now given the lifecycle of an Employee, it makes sense at first to include it as a child entity on Company. An Employee can be added to a Company (new hire or existing) and then that Employee could resign or be fired - at which point that Employee record would likely be updated with some kind of status, so it can be differentiated from active Employees.

In regards to domain logic, every Employee at a Company must have a unique email. So if a Company always contained a list of all its Employees, I imagined that could be modeled as:

company.AddEmployee(employee) - This method would contain logic that makes sure the email is unique. In addition, it would update the size property of the Company, based on how many Employees they have. (<100 is small, <500 is medium, etc)

Now the biggest issue I have seen people discuss is concerning large Aggregates. I think this use case would fall under that concern, as a Company could have 10k+ Employees in this HR application. If I'm adding a single Employee at a time, it seems really wasteful to gather all 10k+, even if it's just their emails.

Am I doing the right thing here by making the Company the Aggregate Root, or is there a better way?

答:
"Company" aggregate root makes sense if its only responsibility is to handle "Human Resources" related concerns.

Regarding the "Email Uniqueness". This is an application layer concern. If you run the business on pen and paper, the business side wouldn't care if two employees have the same email.


问:
I cannot see my commit history in gitlab branch because of error
When I want to see my commit history in a specific branch, I only get this error:

I tried login out/in, erasing cache, loading page in different browsers (Brave, Firefox) and nothing seems to work out.

This only happens to newer branches, e.g. I can see commit history of 6 months old branch. Any help would be appreciated :3 .

答:
I would first check if I can clone the GitLab repository at all, and if, locally, those branches are there.

It also depends on if you are using an old private self-hosted GitLab instance, or if you are referring to the (always up-to-date) gitlab.com hosting service.

There was a similar error (about folder content instead of commit data) which was resolved with GitLab 12.8 (Feb. 2020)


问:
Is there a way to pass options values during mod_wsgi server start up in Django app
I am using mod_wsgi to run my Django app. As there are a plethora of options to define when the server run command is fired, I was trying to create some kind of python script to pass the options and their pre-set values.

For example:

Instead of using:

```<code>$python3 manage.py runmodwsgi --processes 3 --threads 1
</code>```

I am trying to use a python script and use it as:

```<code>$python3 runme.py
</code>```

where runme.py is the script file I am trying to use to start the server.

What I have done so far?

Created the script file:

```<code>import os
from django.core.management import execute_from_command_line

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings')
myargs = 'runmodwsgi'
list_of_args = ['', myargs]
execute_from_command_line(list_of_args)
</code>```

As expected the server started with preset options, for example:

Now what I am trying to achieve is the pass values of certain options like:

```<code>--processes 3 --threads 1
</code>```

and so on.

Is there a way I may pass the preset values (as I may be able to define in my script file runme.py), say something like adding to the list of arguments:

```<code>list_of_args = ['', myargs, addl_args]
</code>```

I have been checking SO queries posted in addition to help available on python site, but could not get my head around to the problem.

I tried the following which is not very helpful though:

```<code>import os
import argparse # New import
from django.core.management import execute_from_command_line

# Addition of new code lines
parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument("-p", "--processes", action="store_true")
group.add_argument("-t", "--threads", action="store_true")
parser.add_argument("pint", type=int, help="no. of processes")
parser.add_argument("tint", type=int, help="no. of threads")

args = parser.parse_args()
# End of new code

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings')
myargs = 'runmodwsgi'

# At this line if I add ", args" (like shown below:])
list_of_args = ['', myargs, args]
execute_from_command_line(list_of_args)
</code>```

and run the command, it comes up with error:

```<code>TypeError: 'Namespace' object does not support indexing
</code>```

If I simply run: python3 runme.py, I get the following error:

```<code>usage: runme.py [-h] [-p | -t] pint tint
runme.py: error: the following arguments are required: pint, tint
</code>```

Whereas, using

```<code>python3 runme.py 3 1
</code>```

starts the server but the options integers "3" and "1" does not have any effect (as intended for no. of processes and threads).

If I use:

```<code>python3 runme.py --processes 3 --threads 1
</code>```

I get the following error:

```<code>$python3 runme.py
</code>```0

Tried with a single arg like:

```<code>$python3 runme.py
</code>```1

The server starts at this time but the options value/s are not affected.

How do I define the option values and pass these preset values of options to the run command?

答:
It looks like you're just misunderstanding/misusing argparse.

```<code>import os
import sys
import argparse

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings')
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--processes", type=int, default=1)
parser.add_argument("-t", "--threads", type=int, default=1)
args = parser.parse_args()
from django.core.management import execute_from_command_line

command = [sys.argv[0], 'runmodwsgi', '--processes', str(args.processes), '--threads', str(args.threads)]
execute_from_command_line(command)
</code>```

might be closer to what you want; it will default processes and threads both to 1.

Body:
I am using mod_wsgi to run my Django app. As there are a plethora of options to define when the server run command is fired, I was trying to create some kind of python script to pass the options and their pre-set values.

For example:

Instead of using:

$python3 manage.py runmodwsgi --processes 3 --threads 1

I am trying to use a python script and use it as:

$python3 runme.py

where runme.py is the script file I am trying to use to start the server.

What I have done so far?

Created the script file:

import os
from django.core.management import execute_from_command_line

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings')
myargs = 'runmodwsgi'
list_of_args = ['', myargs]
execute_from_command_line(list_of_args)

As expected the server started with preset options, for example:

Now what I am trying to achieve is the pass values of certain options like:

--processes 3 --threads 1

and so on.

Is there a way I may pass the preset values (as I may be able to define in my script file runme.py), say something like adding to the list of arguments:

list_of_args = ['', myargs, addl_args]

I have been checking SO queries posted in addition to help available on python site, but could not get my head around to the problem.

I tried the following which is not very helpful though:

import os
import argparse # New import
from django.core.management import execute_from_command_line

# Addition of new code lines
parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument("-p", "--processes", action="store_true")
group.add_argument("-t", "--threads", action="store_true")
parser.add_argument("pint", type=int, help="no. of processes")
parser.add_argument("tint", type=int, help="no. of threads")

args = parser.parse_args()
# End of new code

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings')
myargs = 'runmodwsgi'

# At this line if I add ", args" (like shown below:])
list_of_args = ['', myargs, args]
execute_from_command_line(list_of_args)

and run the command, it comes up with error:

TypeError: 'Namespace' object does not support indexing

If I simply run: python3 runme.py, I get the following error:

usage: runme.py [-h] [-p | -t] pint tint
runme.py: error: the following arguments are required: pint, tint

Whereas, using

python3 runme.py 3 1

starts the server but the options integers "3" and "1" does not have any effect (as intended for no. of processes and threads).

If I use:

python3 runme.py --processes 3 --threads 1

I get the following error:

usage: runme.py [-h] [-p | -t] pint tint
runme.py: error: argument -t/--threads: not allowed with argument -p/--processes

Tried with a single arg like:

python3 runme.py --processes 3 1

The server starts at this time but the options value/s are not affected.

How do I define the option values and pass these preset values of options to the run command?

Body:
It looks like you're just misunderstanding/misusing argparse.

import os
import sys
import argparse

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<proj>.settings')
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--processes", type=int, default=1)
parser.add_argument("-t", "--threads", type=int, default=1)
args = parser.parse_args()
from django.core.management import execute_from_command_line

command = [sys.argv[0], 'runmodwsgi', '--processes', str(args.processes), '--threads', str(args.threads)]
execute_from_command_line(command)

might be closer to what you want; it will default processes and threads both to 1.


问:
Read data from multiple sub-collections in Firestore?
I'm stuck on obtaining data from sub-collection from Firestore. I'm attaching my code script below for reference.

Right now I get the data from a specific sub-collection. Using this Query line:

```<code> Query query = db.collection("Users").document("Group").collection("Group_1);
</code>```

It works fine and returns the data also.

But I want to get all data from the Group document.

Below link attached to my database image.

Firestore Database Image

```<code>  Query query = db.collection("Users");

    FirestoreRecyclerOptions<PatientRegister> response = new FirestoreRecyclerOptions.Builder<PatientRegister>()
            .setQuery(query, PatientRegister.class)
            .build();

    adapter = new FirestoreRecyclerAdapter<PatientRegister, RegisterHolder>(response) {
        @Override
        public void onBindViewHolder(RegisterHolder holder, int position, PatientRegister model) {

            holder.text_1.setText(model.getPatient_name());
            holder.text_2.setText(model.getGender());
            holder.text_3.setText(model.getDatetime());

        @Override
        public RegisterHolder onCreateViewHolder(ViewGroup group, int i) {
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.registration_list, group, false);

            return new RegisterHolder(view);
        }

        @Override
        public void onError(FirebaseFirestoreException e) {
            Log.d("000147", e.getMessage());
        }
    };
</code>```

答:
According to my question:

So you want to get all documents from within all collections that exist under the Group document?

And your answer from the comment:

Yes, I want to get all data inside the Group document.

Please note that there is no way you can do that. Queries in Firestore are shallow, which means that will only return documents from the collection that the query is run against. There is no way you can get documents from multiple subcollections that exist under a particular document in a single go.

To solve this, you have to perform either a separate different query for each and every sub-collection, or you can use a collection group query. However, using your actual schema you won't be able to perform such a query since your sub-collections are dynamically added. So the best option that you have is to change your schema a little bit like so:

```<code>Firestore-root
  |
  --- users (collection)
       |
       --- $uid (document)
            |
            --- groups (sub-collection)
                  |
                  --- $groupId (document)
                        |
                        --- name: "Testing"
</code>```

In this way, you can simply get all groups that correspond to all users using:

```<code>FirebaseFirestore db = FirebaseFirestore.getInstance();
Query groupsQuery = db.collectionGroup("groups");
groupsQuery.get().addOnCompleteListener(/* ... */);
</code>```

Body:
I'm stuck on obtaining data from sub-collection from Firestore. I'm attaching my code script below for reference.

Right now I get the data from a specific sub-collection. Using this Query line:

 Query query = db.collection("Users").document("Group").collection("Group_1);

It works fine and returns the data also.

But I want to get all data from the Group document.

Below link attached to my database image.

Firestore Database Image

  Query query = db.collection("Users");

    FirestoreRecyclerOptions<PatientRegister> response = new FirestoreRecyclerOptions.Builder<PatientRegister>()
            .setQuery(query, PatientRegister.class)
            .build();

    adapter = new FirestoreRecyclerAdapter<PatientRegister, RegisterHolder>(response) {
        @Override
        public void onBindViewHolder(RegisterHolder holder, int position, PatientRegister model) {

            holder.text_1.setText(model.getPatient_name());
            holder.text_2.setText(model.getGender());
            holder.text_3.setText(model.getDatetime());

        @Override
        public RegisterHolder onCreateViewHolder(ViewGroup group, int i) {
            View view = LayoutInflater.from(group.getContext())
                    .inflate(R.layout.registration_list, group, false);

            return new RegisterHolder(view);
        }

        @Override
        public void onError(FirebaseFirestoreException e) {
            Log.d("000147", e.getMessage());
        }
    };

Body:
According to my question:

So you want to get all documents from within all collections that exist under the Group document?

And your answer from the comment:

Yes, I want to get all data inside the Group document.

Please note that there is no way you can do that. Queries in Firestore are shallow, which means that will only return documents from the collection that the query is run against. There is no way you can get documents from multiple subcollections that exist under a particular document in a single go.

To solve this, you have to perform either a separate different query for each and every sub-collection, or you can use a collection group query. However, using your actual schema you won't be able to perform such a query since your sub-collections are dynamically added. So the best option that you have is to change your schema a little bit like so:

Firestore-root
  |
  --- users (collection)
       |
       --- $uid (document)
            |
            --- groups (sub-collection)
                  |
                  --- $groupId (document)
                        |
                        --- name: "Testing"

In this way, you can simply get all groups that correspond to all users using:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Query groupsQuery = db.collectionGroup("groups");
groupsQuery.get().addOnCompleteListener(/* ... */);


问:
Insert a node at a specific position in a linked list JAVA
```<code>public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
    if(llist == null) {
        llist =  new SinglyLinkedListNode(data);
        return llist;
    } else {
        for (int i = 0; i < position-1; i++) {
            llist = llist.next;
        }
        SinglyLinkedListNode temp = llist;
        llist.next = new SinglyLinkedListNode(data);
        llist = llist.next;
        llist.next = temp.next;
        return llist;
    }
}
</code>```

This is my code to place a custom index node in LinkedList. But hackerrank is not accepting my code. What's wrong with my algorithm?

答:
The problem requires you to return a linked list. When we are asked to return a linked list, actually we return the first node of the linked list.

So, your problem is the returned value in your code script is not the first node of the linked list.

The simplest solution is that you keep the first node in another variable, and

return that variable after you have done the insert thing.
for example:

```<code>SinglyLinkedListNode dumyNode = llist;
......
return dumyNode;
</code>```

Body:
public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
    if(llist == null) {
        llist =  new SinglyLinkedListNode(data);
        return llist;
    } else {
        for (int i = 0; i < position-1; i++) {
            llist = llist.next;
        }
        SinglyLinkedListNode temp = llist;
        llist.next = new SinglyLinkedListNode(data);
        llist = llist.next;
        llist.next = temp.next;
        return llist;
    }
}

This is my code to place a custom index node in LinkedList. But hackerrank is not accepting my code. What's wrong with my algorithm?

Body:
The problem requires you to return a linked list. When we are asked to return a linked list, actually we return the first node of the linked list.

So, your problem is the returned value in your code script is not the first node of the linked list.

The simplest solution is that you keep the first node in another variable, and

return that variable after you have done the insert thing.
for example:

SinglyLinkedListNode dumyNode = llist;
......
return dumyNode;


问:
In a Java debugger, how to ignore exceptions never passing through my code
I'm currently using IntelliJ IDEA for Java development, but I'm also interested in answers targeting other IDEs or general concepts for debugging Java code. Because this is a feature I've missed in a number of IDEs, I'm unsure if I've missed a workflow concept when transferring my debug habits from other languages.

Let's say I'm writing some code in myapp.* while using framework classes from somelib.*. A typical stack trace may start in either package and may switch several times between them. Let's also say I'm debugging under the assumption that there are bugs in my code and that there aren't any in the library code. An example stack trace (showing only class names):

```<code>somelib.D (current stack frame)
somelib.C
myapp.Y
myapp.X
somelib.B
somelib.A
</code>```

Normally, I'm not interested in the following types of exceptions and do not want the debugger to break on them:

Thrown in somelib.B and caught in somelib.A. Either the library code is throwing exceptions to handle problematic state inside the library or to stop the application. In the latter case, I'm only interested in the exception message which hopefully tells me what's wrong.

Thrown in somelib.D and caught in somelib.C. The library code may use exceptions as a form of logic where a certain action is tried and an alternative route is taken in the case of a problem or where my code is notified by the problem by other means (e.g. returning a null reference where appropriate).

Types of exceptions I am interested in:

Thrown in somelib.C or somelib.D and not caught in somelib.C or somelib.D. Here I want the debugger to break on the line in myapp.Y where I call the code from somelib.C.

Thrown in myapp.X or myapp.Y, either caught or uncaught. Here I want the debugger to break on the line the exception is thrown.

IntelliJ IDEA gives me the options to select wether I want to break on caught or uncaught exceptions, or both and to restrict the location where the exception is thrown to a set of classes. These options don't help much as I normally want to break on any exception, wether caught or uncaught, as long as code I've written is between the place it's thrown and the place it's caught, eventually.

答: In IntelliJ you can define a condition on an exception break point. The condition is just Java code executed at the time the breakpoint is hit, so the exception object would be in-scope during the condition check. You could call getStackTrace() on the exception and decide if it is an exception that you are interested in by looking at each frame on the stack. If you aren't interested, then your condition fails, and the breakpoint is skipped.

Body:
I'm currently using IntelliJ IDEA for Java development, but I'm also interested in answers targeting other IDEs or general concepts for debugging Java code. Because this is a feature I've missed in a number of IDEs, I'm unsure if I've missed a workflow concept when transferring my debug habits from other languages.

Let's say I'm writing some code in myapp.* while using framework classes from somelib.*. A typical stack trace may start in either package and may switch several times between them. Let's also say I'm debugging under the assumption that there are bugs in my code and that there aren't any in the library code. An example stack trace (showing only class names):

somelib.D (current stack frame)
somelib.C
myapp.Y
myapp.X
somelib.B
somelib.A

Normally, I'm not interested in the following types of exceptions and do not want the debugger to break on them:

Thrown in somelib.B and caught in somelib.A. Either the library code is throwing exceptions to handle problematic state inside the library or to stop the application. In the latter case, I'm only interested in the exception message which hopefully tells me what's wrong.

Thrown in somelib.D and caught in somelib.C. The library code may use exceptions as a form of logic where a certain action is tried and an alternative route is taken in the case of a problem or where my code is notified by the problem by other means (e.g. returning a null reference where appropriate).

Types of exceptions I am interested in:

Thrown in somelib.C or somelib.D and not caught in somelib.C or somelib.D. Here I want the debugger to break on the line in myapp.Y where I call the code from somelib.C.

Thrown in myapp.X or myapp.Y, either caught or uncaught. Here I want the debugger to break on the line the exception is thrown.

IntelliJ IDEA gives me the options to select wether I want to break on caught or uncaught exceptions, or both and to restrict the location where the exception is thrown to a set of classes. These options don't help much as I normally want to break on any exception, wether caught or uncaught, as long as code I've written is between the place it's thrown and the place it's caught, eventually.


问:
Generate brackets with steps of 10 from an array and eliminate empty steps
I'm having trouble solving this problem:

I have an array of objects:

```<code>tableList = [
{table_number: 1},
{table_number: 11},
{table_number: 31}
]
</code>```

I'm trying to generate a bracket list in steps of 10 up to the largest 'table_number'.

I'm using a sequence generator function for this:

```<code>// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
</code>```

I'm using Math.max and iterate through the array to find the biggest 'table_number':

```<code>// Search for biggest table number
var max = Math.max.apply(Math, data.map(o => o.table_number));
</code>```

I then generate the bracket array with the sequencing function:

```<code>// Generate brackets up until biggest table number
var brackets = range(0, max, 10);
</code>```

This gives me a bracket array of [0, 10, 20, 30].

Now the question is, how do I evaluate the array of objects to remove the empty bracket step (20) that will not contain any 'table_number'?

Or should I be generating the bracket array differently?

I would really appreciate any help for this, thanks!

答:
Or should I be generating the bracket array differently?

If you're just after an array like [0,10,30] you can follow a different path:

tableList = [
{table_number: 1},
{table_number: 11},
{table_number: 31}
]

const tmpObj = tableList.reduce( (acc,cur) => {
  acc[ Math.floor(cur.table_number/10)*10 ] = true;
  return acc;
} , {})

const brackets = Object.keys(tmpObj).map((x) => parseInt(x));
console.log(brackets);```

But this is taking advantage of how easy is "in steps of 10"

Body:
I'm having trouble solving this problem:

I have an array of objects:

tableList = [
{table_number: 1},
{table_number: 11},
{table_number: 31}
]

I'm trying to generate a bracket list in steps of 10 up to the largest 'table_number'.

I'm using a sequence generator function for this:

// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

I'm using Math.max and iterate through the array to find the biggest 'table_number':

// Search for biggest table number
var max = Math.max.apply(Math, data.map(o => o.table_number));

I then generate the bracket array with the sequencing function:

// Generate brackets up until biggest table number
var brackets = range(0, max, 10);

This gives me a bracket array of [0, 10, 20, 30].

Now the question is, how do I evaluate the array of objects to remove the empty bracket step (20) that will not contain any 'table_number'?

Or should I be generating the bracket array differently?

I would really appreciate any help for this, thanks!

Body:
Or should I be generating the bracket array differently?

If you're just after an array like [0,10,30] you can follow a different path:

tableList = [
{table_number: 1},
{table_number: 11},
{table_number: 31}
]

const tmpObj = tableList.reduce( (acc,cur) => {
  acc[ Math.floor(cur.table_number/10)*10 ] = true;
  return acc;
} , {})

const brackets = Object.keys(tmpObj).map((x) => parseInt(x));
console.log(brackets);

But this is taking advantage of how easy is "in steps of 10"


问:
best practices implementing deep linking in react native
I would like to know best practices implementing deep linking in react native/react navigation, naming conventions for schema, support of multiple deep links etc.</p>

答:
You can pass config as props in NavigationContainer and register multiple screens and configure links for the same.
I would recommend to follow official documentation https://reactnavigation.org/docs/deep-linking/ for setup and
https://reactnavigation.org/docs/configuring-linksfor configuring deep links.

Few scenarios to test for:
i) app is in foreground
ii) app is in background
iii) app is in killed state
and if you have authenticated screens then 3 more scenarios if user is in logged in state or not.

getInitialUrl() is helpful functions to know if app got launched by deep link url or not, because there can be scenarios where user isn't in logged-in state and app got launched using deep link etc. etc.

const link = useLinkTo() and link('yourDeepLink') function will help in passing the deep link as it as argument  and it will be get internally parsed by react-native-navigation to work like .navigate() method. this would be helpful in case app got launched by deep link and user wasn't logged-in but you want to keep the deep link stored somewhere till user logs-in and then you want to land user on the configured deep link screen.

If you go one step ahead and configure universal links for iOS, you have to add support for associated domains and add  apple-app-site-association file in .well-known directory of the domain you want to configure which kinda verifies that this domain is owned by this app. In android you can setup applinks and will have to place assetlinks.json file for the same reason as in ios. For your help https://developer.android.com/training/app-links


问:
Android back button and MediaController
I know how to take control of the back button. I have a VideoView embedded in a FrameLayout. My question is when the video pops up, the video controls are present for a few seconds. Hitting the back button while they are visible hides the video controls. Is there a way to ignore that function and do the next back action as if the video controls weren't visible?

The reason I ask is if I really do want to go back, I must hit the back button twice; once to hide the controls and second to actually go back

答:
In Xamarin.Android, you can deal with this problem like this</p>
```<code>public class CustomMediaController : MediaController
    {
        private FragmentActivity act;
        public CustomMediaController(Context context, FragmentActivity myActivity) : base(context)
        {
            act = myActivity;
        }
        public override bool DispatchKeyEvent(KeyEvent e)
        {
            if(e.KeyCode == Keycode.Back)
            {
                act.OnBackPressed();
            }
            return base.DispatchKeyEvent(e);
        }
    }
</code>```

Title: Android back button and MediaController

Body:
In Xamarin.Android, you can deal with this problem like this

public class CustomMediaController : MediaController
    {
        private FragmentActivity act;
        public CustomMediaController(Context context, FragmentActivity myActivity) : base(context)
        {
            act = myActivity;
        }
        public override bool DispatchKeyEvent(KeyEvent e)
        {
            if(e.KeyCode == Keycode.Back)
            {
                act.OnBackPressed();
            }
            return base.DispatchKeyEvent(e);
        }
    }