问:
MySQL count number of user activities (table a) falling in two login session datetime (table b)
I have a table with all the users activities and another table with all the users login events. Each of them has a datatime field (creation).

I need to count for a specific user with one query how many activities he/she has done falling into the datetime range in between two consecutive logins (assuming that in between a logout or session expiration event has happened) and after the last one.

```<code>CREATE TABLE `STAGING_admin_activities` (
  `id` int(11) UNSIGNED NOT NULL,
  `admin_id` int(11) UNSIGNED DEFAULT NULL,
  `requested_URL_and_data` tinytext DEFAULT NULL,
  `post_data` text DEFAULT NULL,
  `result` tinytext DEFAULT NULL,
  `useragent_referred_URL` tinytext DEFAULT NULL,
  `useragent_browser` tinytext DEFAULT NULL,
  `useragent_browser_version` tinytext DEFAULT NULL,
  `useragent_robot` tinytext DEFAULT NULL,
  `useragent_mobile` tinytext DEFAULT NULL,
  `useragent_platform` tinytext DEFAULT NULL,
  `useragent_languages` tinytext DEFAULT NULL,
  `ip_country_code` varchar(2) DEFAULT NULL,
  `ip` varchar(255) DEFAULT NULL,
  `remarks` tinytext DEFAULT NULL,
  `creation` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `STAGING_admin_login_logout` (
  `id` int(11) UNSIGNED NOT NULL,
  `operation` enum('login','logout') NOT NULL,
  `result` tinyint(1) UNSIGNED DEFAULT NULL,
  `admin_id` int(11) UNSIGNED DEFAULT NULL,
  `ip` varchar(255) DEFAULT NULL,
  `ip_country_code` varchar(2) DEFAULT NULL,
  `creation` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

To simplify the data example keeping just the meaningful fields

STAGING_admin_login_logout

id
admin_id
operation
creation

1
5
login
08/03/2021 17:19

2
5
login
08/03/2021 20:11

3
1
login
09/03/2021 09:09

4
4
login
09/03/2021 10:31

5
5
login
09/03/2021 15:08

6
5
login
09/03/2021 17:01

7
1
login
10/03/2021 14:01

8
5
login
10/03/2021 18:15

STAGING_admin_activities

id
admin_id
creation

1
5
08/03/2021 17:20

2
5
08/03/2021 17:23

3
5
08/03/2021 17:25

4
5
08/03/2021 20:13

5
5
08/03/2021 20:13

6
4
09/03/2021 10:33

7
5
09/03/2021 15:11

8
5
09/03/2021 15:11

9
5
09/03/2021 15:22

10
5
09/03/2021 17:01

11
1
10/03/2021 14:01

12
5
10/03/2021 18:18

13
5
10/03/2021 19:37

the expected result is something similar of this simplified table

expected results filtered on admin_id = 5

admin_id
login_time
last_activity_time
number_of_activities

5
08/03/2021 17:19
08/03/2021 17:25
3

5
08/03/2021 20:11
08/03/2021 20:13
2

5
09/03/2021 15:08
09/03/2021 15:22
3

5
09/03/2021 17:01
09/03/2021 17:01
1

5
10/03/2021 18:15
10/03/2021 19:37
2

As you can see the field last_activity_time come from the activties table "creation" field and is the higher datetime in between two login events. The last column number_of_activities is the desired result, the number of activities including the last one falling in the time range between login_time (originally coming from the 'creation' field of the login events table) and last_activity_time (originally coming from the 'creation' field of the activities table).

In the following image, it is shown the relations on the datetime field of the two tables and how they are considered on creating the resulting one.

Concerning the DB version on PhpMyAdmin I can read this: "Versione del server: 10.3.32-MariaDB - MariaDB Server".

UPDATE 1

Following D-Shih ideas I tryed this

```<code>SELECT *
FROM
( SELECT operation,result,admin_id,creation as login_creation, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_login_time
FROM STAGING_admin_login_logout
WHERE operation = "login" AND admin_id = 5 ) login_logout
INNER JOIN STAGING_admin_activities ON STAGING_admin_activities.admin_id = login_logout.admin_id
WHERE STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time
ORDER BY STAGING_admin_activities.creation ASC
</code>```

that actually gives as many rows as the ativities of user with user_id = 5 and falling in the range of datetime of two consecutive logins. What is in common to all the activities rows in between two logins is the field login_creation that has the same datetime. Now I should count the activities that as the same login_creation field value; I tryed in this way

```<code>SELECT *, COUNT(*) as number_of_activities
FROM
( SELECT operation,result,admin_id,creation as login_creation, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_login_time
FROM STAGING_admin_login_logout
WHERE operation = "login" AND admin_id = 5 ) login_logout
INNER JOIN STAGING_admin_activities ON STAGING_admin_activities.admin_id = login_logout.admin_id
WHERE STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time
GROUP BY login_logout.login_creation
ORDER BY STAGING_admin_activities.creation ASC
</code>```

now checking if it is correct.

UPDATE 2

The query closest to the desired result is the following one, I still have a couple of troubles for which I kind ask for an help

```<code>SELECT *, COUNT(*) as number_of_activities, MAX(STAGING_admin_activities.creation) as last_activity_creation, TIMESTAMPDIFF(MINUTE,login_creation,next_login_time) as time_lenght
FROM
    ( SELECT operation,result,admin_id,creation as login_creation, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_login_time
    FROM STAGING_admin_login_logout
    WHERE operation = "login" AND admin_id = 5 ) login_logout
INNER JOIN STAGING_admin_activities ON STAGING_admin_activities.admin_id = login_logout.admin_id
WHERE STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time AND
      requested_URL_and_data = '/adminPanel/Products/addUpdate' AND
      login_logout.result = 1
GROUP BY login_logout.login_creation
ORDER BY STAGING_admin_activities.creation ASC
</code>```

The first problem is that the last group of activities have a time range equal in between the last login creation datatime and NULL since there is not a next login time that determines the end of the range. I need to extract some how the last/max activity creation datetime, lets call it 'max_activity_creation', and extend the condition on time as following

```<code>WHERE (STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time **OR STAGING_admin_activities.creation >= max_activity_creation**) AND
      requested_URL_and_data = '/adminPanel/Products/addUpdate' AND
      login_logout.result = 1
</code>```

How can I extract this 'max_activity_creation' value?

The second issue is that I should calculate the time length of the activities as the datetime of the last activity before a new login and the datetime of the previous login. Let's call the dateime of this last activity as 'last_activity_creation' as in the initial SELECT.

```<code>SELECT *, COUNT(*) as number_of_activities, MAX(STAGING_admin_activities.creation) as last_activity_creation, TIMESTAMPDIFF(MINUTE,login_creation,next_login_time) as time_lenght
</code>```

actually 'last_activity_creation' is displayed correctly but if I use it in side the TIMESTAMPDIFF

```<code>TIMESTAMPDIFF(MINUTE,login_creation,last_activity_creation)
</code>```

I get an error. Any ideas?

答:
Thanks to @D-Shih here is the solution</p>
```<code>SELECT a.admin_id,
       a.creation login_time,
       MAX(activity.creation) last_activity_time,
       count(*) number_of_activities

FROM (
  SELECT *, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_logout_time
  FROM STAGING_admin_login_logout
) a
INNER JOIN STAGING_admin_activities activity
ON a.admin_id = activity.admin_id AND
activity.creation BETWEEN  a.creation AND coalesce(next_logout_time,'9999/12/31') AND
coalesce(next_logout_time,'9999/12/31')  <> activity.creation
WHERE  a.admin_id = 5
GROUP BY a.admin_id,
       a.creation;
</code>```

Body:
I have a table with all the users activities and another table with all the users login events. Each of them has a datatime field (creation).

I need to count for a specific user with one query how many activities he/she has done falling into the datetime range in between two consecutive logins (assuming that in between a logout or session expiration event has happened) and after the last one.

CREATE TABLE `STAGING_admin_activities` (
  `id` int(11) UNSIGNED NOT NULL,
  `admin_id` int(11) UNSIGNED DEFAULT NULL,
  `requested_URL_and_data` tinytext DEFAULT NULL,
  `post_data` text DEFAULT NULL,
  `result` tinytext DEFAULT NULL,
  `useragent_referred_URL` tinytext DEFAULT NULL,
  `useragent_browser` tinytext DEFAULT NULL,
  `useragent_browser_version` tinytext DEFAULT NULL,
  `useragent_robot` tinytext DEFAULT NULL,
  `useragent_mobile` tinytext DEFAULT NULL,
  `useragent_platform` tinytext DEFAULT NULL,
  `useragent_languages` tinytext DEFAULT NULL,
  `ip_country_code` varchar(2) DEFAULT NULL,
  `ip` varchar(255) DEFAULT NULL,
  `remarks` tinytext DEFAULT NULL,
  `creation` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `STAGING_admin_login_logout` (
  `id` int(11) UNSIGNED NOT NULL,
  `operation` enum('login','logout') NOT NULL,
  `result` tinyint(1) UNSIGNED DEFAULT NULL,
  `admin_id` int(11) UNSIGNED DEFAULT NULL,
  `ip` varchar(255) DEFAULT NULL,
  `ip_country_code` varchar(2) DEFAULT NULL,
  `creation` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

To simplify the data example keeping just the meaningful fields

STAGING_admin_login_logout

id
admin_id
operation
creation

1
5
login
08/03/2021 17:19

2
5
login
08/03/2021 20:11

3
1
login
09/03/2021 09:09

4
4
login
09/03/2021 10:31

5
5
login
09/03/2021 15:08

6
5
login
09/03/2021 17:01

7
1
login
10/03/2021 14:01

8
5
login
10/03/2021 18:15

STAGING_admin_activities

id
admin_id
creation

1
5
08/03/2021 17:20

2
5
08/03/2021 17:23

3
5
08/03/2021 17:25

4
5
08/03/2021 20:13

5
5
08/03/2021 20:13

6
4
09/03/2021 10:33

7
5
09/03/2021 15:11

8
5
09/03/2021 15:11

9
5
09/03/2021 15:22

10
5
09/03/2021 17:01

11
1
10/03/2021 14:01

12
5
10/03/2021 18:18

13
5
10/03/2021 19:37

the expected result is something similar of this simplified table

expected results filtered on admin_id = 5

admin_id
login_time
last_activity_time
number_of_activities

5
08/03/2021 17:19
08/03/2021 17:25
3

5
08/03/2021 20:11
08/03/2021 20:13
2

5
09/03/2021 15:08
09/03/2021 15:22
3

5
09/03/2021 17:01
09/03/2021 17:01
1

5
10/03/2021 18:15
10/03/2021 19:37
2

As you can see the field last_activity_time come from the activties table "creation" field and is the higher datetime in between two login events. The last column number_of_activities is the desired result, the number of activities including the last one falling in the time range between login_time (originally coming from the 'creation' field of the login events table) and last_activity_time (originally coming from the 'creation' field of the activities table).

In the following image, it is shown the relations on the datetime field of the two tables and how they are considered on creating the resulting one.

Concerning the DB version on PhpMyAdmin I can read this: "Versione del server: 10.3.32-MariaDB - MariaDB Server".

UPDATE 1

Following D-Shih ideas I tryed this

SELECT *
FROM
( SELECT operation,result,admin_id,creation as login_creation, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_login_time
FROM STAGING_admin_login_logout
WHERE operation = "login" AND admin_id = 5 ) login_logout
INNER JOIN STAGING_admin_activities ON STAGING_admin_activities.admin_id = login_logout.admin_id
WHERE STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time
ORDER BY STAGING_admin_activities.creation ASC

that actually gives as many rows as the ativities of user with user_id = 5 and falling in the range of datetime of two consecutive logins. What is in common to all the activities rows in between two logins is the field login_creation that has the same datetime. Now I should count the activities that as the same login_creation field value; I tryed in this way

SELECT *, COUNT(*) as number_of_activities
FROM
( SELECT operation,result,admin_id,creation as login_creation, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_login_time
FROM STAGING_admin_login_logout
WHERE operation = "login" AND admin_id = 5 ) login_logout
INNER JOIN STAGING_admin_activities ON STAGING_admin_activities.admin_id = login_logout.admin_id
WHERE STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time
GROUP BY login_logout.login_creation
ORDER BY STAGING_admin_activities.creation ASC

now checking if it is correct.

UPDATE 2

The query closest to the desired result is the following one, I still have a couple of troubles for which I kind ask for an help

SELECT *, COUNT(*) as number_of_activities, MAX(STAGING_admin_activities.creation) as last_activity_creation, TIMESTAMPDIFF(MINUTE,login_creation,next_login_time) as time_lenght
FROM
    ( SELECT operation,result,admin_id,creation as login_creation, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_login_time
    FROM STAGING_admin_login_logout
    WHERE operation = "login" AND admin_id = 5 ) login_logout
INNER JOIN STAGING_admin_activities ON STAGING_admin_activities.admin_id = login_logout.admin_id
WHERE STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time AND
      requested_URL_and_data = '/adminPanel/Products/addUpdate' AND
      login_logout.result = 1
GROUP BY login_logout.login_creation
ORDER BY STAGING_admin_activities.creation ASC

The first problem is that the last group of activities have a time range equal in between the last login creation datatime and NULL since there is not a next login time that determines the end of the range. I need to extract some how the last/max activity creation datetime, lets call it 'max_activity_creation', and extend the condition on time as following

WHERE (STAGING_admin_activities.creation BETWEEN login_logout.login_creation AND login_logout.next_login_time **OR STAGING_admin_activities.creation >= max_activity_creation**) AND
      requested_URL_and_data = '/adminPanel/Products/addUpdate' AND
      login_logout.result = 1

How can I extract this 'max_activity_creation' value?

The second issue is that I should calculate the time length of the activities as the datetime of the last activity before a new login and the datetime of the previous login. Let's call the dateime of this last activity as 'last_activity_creation' as in the initial SELECT.

SELECT *, COUNT(*) as number_of_activities, MAX(STAGING_admin_activities.creation) as last_activity_creation, TIMESTAMPDIFF(MINUTE,login_creation,next_login_time) as time_lenght

actually 'last_activity_creation' is displayed correctly but if I use it in side the TIMESTAMPDIFF

TIMESTAMPDIFF(MINUTE,login_creation,last_activity_creation)

I get an error. Any ideas?

Body:
Thanks to @D-Shih here is the solution

SELECT a.admin_id,
       a.creation login_time,
       MAX(activity.creation) last_activity_time,
       count(*) number_of_activities

FROM (
  SELECT *, LEAD(creation) OVER(PARTITION BY admin_id ORDER BY creation) next_logout_time
  FROM STAGING_admin_login_logout
) a
INNER JOIN STAGING_admin_activities activity
ON a.admin_id = activity.admin_id AND
activity.creation BETWEEN  a.creation AND coalesce(next_logout_time,'9999/12/31') AND
coalesce(next_logout_time,'9999/12/31')  <> activity.creation
WHERE  a.admin_id = 5
GROUP BY a.admin_id,
       a.creation;


来源: stackexchange

问:
Element "align" is obsolete or non-standard: what should I use instead?
I have this HTML code:

```<code><td align="center">
</code>```

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

答:
That would be something like:

```<code><td style="text-align: center;">
</code>```

But it would be even better to move that style out of the html and put it in a separate style-sheet.

ContentLicense: CC BY-SA 4.0

Body:
I have this HTML code:

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

Body:
That would be something like:

<td style="text-align: center;">

But it would be even better to move that style out of the html and put it in a separate style-sheet.

ContentLicense: CC BY-SA 3.0


问:
Powershell download file onedrive/googledrive
I want to download a file to a pc from onedrive/google drive.

After some digging into this subject i found invoke-Webrequest was the best command to use in this subject.

```<code># Download the file $zipFile = "https://xxxxxxmy.sharepoint.com/:u:/g/personal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxfRW5c" Invoke-WebRequest -Uri $zipFile -OutFile "c:\temp\xxxxxx.exe"
</code>```

only to found out the code was working but only downloaded a .exe file of 156kB
This file i wanted to download is 22mb? i get no error's in powershell but maybe you have any idea what is going on?

zipfiles work but then i need to extract a zip file in the code and i dont know the working code for that..? ( expand-archive didnt work).

答:
So there is no login context for the session spawned by your script.  If you open one drive in your browser, once authentication is established and a session exists, the browser is given access to the file.

If you open your file that is  156kb in notepad, you should find it's just a webpage saying the URL is not available.

I believe this will help the situation, but it's more complex:
https://techcommunity.microsoft.com/t5/onedrive-for-business/how-to-download-root-level-files-from-onedrive-using-powershell/m-p/758689

Body:
I want to download a file to a pc from onedrive/google drive.

After some digging into this subject i found invoke-Webrequest was the best command to use in this subject.

# Download the file $zipFile = "https://xxxxxxmy.sharepoint.com/:u:/g/personal/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxfRW5c" Invoke-WebRequest -Uri $zipFile -OutFile "c:\temp\xxxxxx.exe"

only to found out the code was working but only downloaded a .exe file of 156kB
This file i wanted to download is 22mb? i get no error's in powershell but maybe you have any idea what is going on?

zipfiles work but then i need to extract a zip file in the code and i dont know the working code for that..? ( expand-archive didnt work).


问:
Generate a series of numbers that go up in two interweaving intervals
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

```<code>0,5,15,20,30,35,45,50,60,65,75,85,90,100
</code>```

I am aware of

```<code>seq 0 10 100
</code>```

but am looking to jump two different intervals intertwined.

答:
You may use 2 printf statements to generate 2 lists and then sort the combined list using sort -n:

{ printf '%d\n' {0..100..15}; printf '%d\n' {5..100..15}; } | sort -un
0
5
15
20
30
35
45
50
60
65
75
80
90
95
```

Body:
Let's say I want to generate a series of numbers that first jump 5 and then 10 all the way to 100 which would be

0,5,15,20,30,35,45,50,60,65,75,85,90,100

I am aware of

seq 0 10 100

but am looking to jump two different intervals intertwined.


问:
How to migrate pytest to bazel py_test?
I want to convert our integration pytests over to bazel, but it doesn't seem to actually run nor produce the junitxml output I'm expecting:

ARGS = [
    "--verbose",
    "--json-report",
    "--junit-xml=junit.xml",
]

py_test(
    name = "test_something",
    srcs = ["test_something.py"],
    args = ARGS,
    tags = [
        "yourit",
    ],
    deps = [
        requirement("pytest"),
        requirement("pytest-json-report"),
        ":lib",
    ],
)
```

There is a similar question here: How do I use pytest with bazel?.  But it didn't cover the multitude of issues I ran into.

答:
So there were multiple things to address in order to make bazel's py_test work with pytest.

Of course you need the pytest dependency requirement("pytest") added.

The pytest files require a hook being added (note that the args are passed as well sys.argv[1:], so py_test args can be passed on to the pytest file):

if __name__ == "__main__":
   sys.exit(pytest.main(\[__file__\] + sys.argv\[1:\]))
```
</li>
<li><p>Since our pytests are trying to access the host network, we need to tell bazel to allow network traffic outside the sandbox by adding a <code>requires-network</code> tag.</p>
</li>
<li><p>The host network is local, so we need to make sure the test runs locally by adding the <code>local</code> tag.</p>
</li>
<li><p>Bazel py_test will create junitxml under bazel-testlogs, but it only shows if py_test rule passed or failed.  To get more granular junitxml results, we need to tell pytest how to overwrite bazel's py_test results using <code>XML_OUTPUT_FILE</code> environment variable. Note the <code>$$</code> is needed to prevent variable expansion. See https://docs.bazel.build/versions/main/test-encyclopedia.html and https://github.com/bazelbuild/bazel/blob/master/tools/test/test-setup.sh#L67 for more info.</p>
</li>
<li><p>Attempts to write json report output to bazel-testlogs using <code>TEST_UNDECLARED_OUTPUTS_DIR</code> environment variable didn't work.  The report is still written, but inside bazel-out.  There might be a way to scoop up those files, but solving that problem was not a priority.</p>
</li>
<li><p>Note that the <code>ARGS</code> is used to keep it DRY (don't repeat yourself).  We use the same arguments across multiple <code>py_test</code> rules.</p>
</li>
</ol>
<p>So the BUILD now looks like this:</p>
<pre class="lang-yaml prettyprint-override"><code>ARGS = [
    "--verbose",
    "--json-report",
    "--junit-xml=$$XML_OUTPUT_FILE",
]

py_test(
    name = "test_something",
    srcs = ["test_something.py"],
    args = ARGS,
    tags = [
        "local",
        "requires-network",
        "yourit",
    ],
    deps = [
        requirement("pytest"),
        requirement("pytest-json-report"),
        ":lib",
    ],
)
</code>```

Title: How to migrate pytest to bazel py_test?

Body:
I want to convert our integration pytests over to bazel, but it doesn't seem to actually run nor produce the junitxml output I'm expecting:

ARGS = [
    "--verbose",
    "--json-report",
    "--junit-xml=junit.xml",
]

py_test(
    name = "test_something",
    srcs = ["test_something.py"],
    args = ARGS,
    tags = [
        "yourit",
    ],
    deps = [
        requirement("pytest"),
        requirement("pytest-json-report"),
        ":lib",
    ],
)

There is a similar question here: How do I use pytest with bazel?.  But it didn't cover the multitude of issues I ran into.

Body:
So there were multiple things to address in order to make bazel's py_test work with pytest.

Of course you need the pytest dependency requirement("pytest") added.

The pytest files require a hook being added (note that the args are passed as well sys.argv[1:], so py_test args can be passed on to the pytest file):

if __name__ == "__main__":
   sys.exit(pytest.main(\[__file__\] + sys.argv\[1:\]))

Since our pytests are trying to access the host network, we need to tell bazel to allow network traffic outside the sandbox by adding a requires-network tag.

The host network is local, so we need to make sure the test runs locally by adding the local tag.

Bazel py_test will create junitxml under bazel-testlogs, but it only shows if py_test rule passed or failed.  To get more granular junitxml results, we need to tell pytest how to overwrite bazel's py_test results using XML_OUTPUT_FILE environment variable. Note the $$ is needed to prevent variable expansion. See https://docs.bazel.build/versions/main/test-encyclopedia.html and https://github.com/bazelbuild/bazel/blob/master/tools/test/test-setup.sh#L67 for more info.

Attempts to write json report output to bazel-testlogs using TEST_UNDECLARED_OUTPUTS_DIR environment variable didn't work.  The report is still written, but inside bazel-out.  There might be a way to scoop up those files, but solving that problem was not a priority.

Note that the ARGS is used to keep it DRY (don't repeat yourself).  We use the same arguments across multiple py_test rules.

So the BUILD now looks like this:

ARGS = [
    "--verbose",
    "--json-report",
    "--junit-xml=$$XML_OUTPUT_FILE",
]

py_test(
    name = "test_something",
    srcs = ["test_something.py"],
    args = ARGS,
    tags = [
        "local",
        "requires-network",
        "yourit",
    ],
    deps = [
        requirement("pytest"),
        requirement("pytest-json-report"),
        ":lib",
    ],
)


问:
Flutter Scrollbar in vertical and horizontal axis
I have two scrollbars in my flutter project for scrolling the data table. Here are the codes.

```<code>  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                width: MediaQuery.of(context).size.width * (1 / 2),
                height: MediaQuery.of(context).size.height * (1 / 2),
                child: Scrollbar(
                    isAlwaysShown: true,
                    controller: _controllerOne,
                    child: SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        controller: _controllerOne,
                        child: Scrollbar(
                          controller: _controllerTwo,
                          isAlwaysShown: true,
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            controller: _controllerTwo,
                            child: DataTable(
                             ...
                            ),
                          ),
                        ))))));
  }
</code>```

These two scrollbars are working correctly. But I can not see both of them at the same time. I mean if I write the Scrollbar with scrollDirection in vertical first it's like;

```<code>Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                width: MediaQuery.of(context).size.width * (1 / 2),
                height: MediaQuery.of(context).size.height * (1 / 2),
                child: Scrollbar(
                    isAlwaysShown: true,
                    controller: _controllerOne,
                    child: SingleChildScrollView(
                        **scrollDirection: Axis.vertical,**
                        controller: _controllerOne,
                        child: Scrollbar(
                          controller: _controllerTwo,
                          isAlwaysShown: true,
                          child: SingleChildScrollView(
                            **scrollDirection: Axis.horizontal,**
                            controller: _controllerTwo,
                            child: DataTable(
                             ...
                            ),
                          ),
                        ))))));
  }
</code>```

if I write the Scrollbar with scrollDirection in horizontal first it's like;

```<code>Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                width: MediaQuery.of(context).size.width * (1 / 2),
                height: MediaQuery.of(context).size.height * (1 / 2),
                child: Scrollbar(
                    isAlwaysShown: true,
                    controller: _controllerOne,
                    child: SingleChildScrollView(
                        **scrollDirection: Axis.horizontal,**
                        controller: _controllerOne,
                        child: Scrollbar(
                          controller: _controllerTwo,
                          isAlwaysShown: true,
                          child: SingleChildScrollView(
                            **scrollDirection: Axis.vertical,**
                            controller: _controllerTwo,
                            child: DataTable(
                             ...
                            ),
                          ),
                        ))))));
  }
</code>```

When I scroll till the end I can see the other scrollbar for both directions.
But when the table is shown I need to see them both at the same time.

Is there any solution for this?

答:
I was facing the same issue Than I created my own Package for it.
I am personally using it in my Production apps.
It is very easy to use.
Handles the scrollbar and Thumb automatically But worry about that you can customize the scrollbar and Thumb according to your application Theme.
Moreover its Works fine in All Platforms.

```<code>cross_scroll: ^0.0.75
</code>```

You only 3 lines of code use it like below:

```<code>CrossScroll(
      child:///your child
    )
</code>```

Make sure your child has a specific height and width.

Maybe this package will also help you easily customize your thumb and scrolling track both horizontally and vertically

cross scroll package

Body:
I have two scrollbars in my flutter project for scrolling the data table. Here are the codes.

  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                width: MediaQuery.of(context).size.width * (1 / 2),
                height: MediaQuery.of(context).size.height * (1 / 2),
                child: Scrollbar(
                    isAlwaysShown: true,
                    controller: _controllerOne,
                    child: SingleChildScrollView(
                        scrollDirection: Axis.vertical,
                        controller: _controllerOne,
                        child: Scrollbar(
                          controller: _controllerTwo,
                          isAlwaysShown: true,
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            controller: _controllerTwo,
                            child: DataTable(
                             ...
                            ),
                          ),
                        ))))));
  }

These two scrollbars are working correctly. But I can not see both of them at the same time. I mean if I write the Scrollbar with scrollDirection in vertical first it's like;

Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                width: MediaQuery.of(context).size.width * (1 / 2),
                height: MediaQuery.of(context).size.height * (1 / 2),
                child: Scrollbar(
                    isAlwaysShown: true,
                    controller: _controllerOne,
                    child: SingleChildScrollView(
                        **scrollDirection: Axis.vertical,**
                        controller: _controllerOne,
                        child: Scrollbar(
                          controller: _controllerTwo,
                          isAlwaysShown: true,
                          child: SingleChildScrollView(
                            **scrollDirection: Axis.horizontal,**
                            controller: _controllerTwo,
                            child: DataTable(
                             ...
                            ),
                          ),
                        ))))));
  }

if I write the Scrollbar with scrollDirection in horizontal first it's like;

Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Container(
                width: MediaQuery.of(context).size.width * (1 / 2),
                height: MediaQuery.of(context).size.height * (1 / 2),
                child: Scrollbar(
                    isAlwaysShown: true,
                    controller: _controllerOne,
                    child: SingleChildScrollView(
                        **scrollDirection: Axis.horizontal,**
                        controller: _controllerOne,
                        child: Scrollbar(
                          controller: _controllerTwo,
                          isAlwaysShown: true,
                          child: SingleChildScrollView(
                            **scrollDirection: Axis.vertical,**
                            controller: _controllerTwo,
                            child: DataTable(
                             ...
                            ),
                          ),
                        ))))));
  }

When I scroll till the end I can see the other scrollbar for both directions.
But when the table is shown I need to see them both at the same time.

Is there any solution for this?

Body:
I was facing the same issue Than I created my own Package for it.
I am personally using it in my Production apps.
It is very easy to use.
Handles the scrollbar and Thumb automatically But worry about that you can customize the scrollbar and Thumb according to your application Theme.
Moreover its Works fine in All Platforms.

cross_scroll: ^0.0.75

You only 3 lines of code use it like below:

CrossScroll(
      child:///your child
    )

Make sure your child has a specific height and width.

Maybe this package will also help you easily customize your thumb and scrolling track both horizontally and vertically

cross scroll package


问:
ThreeJS Camera Frustrum frustum.containsPoint is always returning true
I am trying to get all the objects that the camera can see because I want to update the position of the objects it can't see.

frustum.containsPoint always returns true which is the biggest issue

any help is much appreciated

camera.updateMatrix();
  camera.updateMatrixWorld();

  var frustum = new THREE.Frustum();
  var projScreenMatrix = new THREE.Matrix4();
  projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);

  // frustum.setFromProjectionMatrix(camera.projectionMatrix);
  frustum.setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));

  for (let index = 0; index < scene.children.length; index++) {
    scene.children[index].updateMatrix(); // make sure plane's local matrix is updated
    scene.children[index].updateMatrixWorld();

    if (frustum.containsPoint(scene.children[index])) {
      //stuff happens...
      if (scene.children[index].name === "coin") {
        scene.children[index].rotation.x += 0.01;
        scene.children[index].position.y -= 0.1;
      }
      // console.log("mesh in view Frustrum");
    } else {
      console.log("mesh not in view Frustrum");
    }
  }```

答:
You are using:

```<code>frustum.containsPoint(scene.children[index])
</code>```

it should be:

```<code>frustum.intersectsObject(scene.children[index])
</code>```

Scene.children does not hold points but 3D objects.

Body:
You are using:

frustum.containsPoint(scene.children[index])

it should be:

frustum.intersectsObject(scene.children[index])

Scene.children does not hold points but 3D objects.


问:
Overriding the three slashes automatic documentation
Is there a way to automatically fill in the XML documentation created by Visual Studio when you type ///?

I want to auto fill the documentation like the variable name separated based on camel casing.

I could write a Visual Studio Add-In and bind it to different key combination, but wanted to see if there is any other way to do so.

答: GhostDoc might be able to help - it's excellent for generating XML comments.</p>


问:
Can someone explain what this bit of code does?
I know it involves some recursion over a list but I'm struggling  with what its adding to the lists and what x22,k and t represents.

```<code>insertM :: Message -> [(Name, Int)] -> [(Name, Int)]
insertM (M x1 x2 m) [] = [(x2, 1)]
insertM (M x1 x2 m) ((x22,k):t) = do
    if x2 == x22 then
        (x22, k+1):t
    else do
        (x22, k): insertM (M x1 x2 m) t
</code>```

This might help

```<code>data Message = M Name Name String deriving (Show)
</code>```

答:
This function inserts Messages in a List of Messages. And if the Message already is in the list increases the Message counter.

So line by line:

```<code>insertM (M x1 x2 m) [] = [(x2, 1)]
</code>```

If the List is empty and you insert a Message, just enter the message with count 1.

```<code>insertM (M x1 x2 m) ((x22,k):t) = do
</code>```

Thats the second case (look up pattern matching if you don't understand), where you insert a message, which looks like this (M x1 x2 m) into a list with the header (x22,k) and a tail t.

```<code>if x2 == x22 then
    (x22, k+1):t
</code>```

This lines checks if the part of the message x2is the same as the x22 of the first element of the list and the increments the counter. If this isn't the case you look up the rest of the list

```<code>  (x22, k): insertM (M x1 x2 m) t
</code>```

(x22,k) is the head of the list, : appends two lists, insertM (M x1 x2 m) t is a recursive call on the tail where you lookup the rest of the list.

For example:

```<code>(insertM (M "A" "B" "chicken") [])         => [("B",1)]
(insertM (M "A" "B" "chicken") [("B",1)])  => [("B",2)]
(insertM (M "A" "C" "chicken") [("B",2)])  => [("B",2),("C",1)]
</code>```

Any further questions?

Body:
I know it involves some recursion over a list but I'm struggling  with what its adding to the lists and what x22,k and t represents.

insertM :: Message -> [(Name, Int)] -> [(Name, Int)]
insertM (M x1 x2 m) [] = [(x2, 1)]
insertM (M x1 x2 m) ((x22,k):t) = do
    if x2 == x22 then
        (x22, k+1):t
    else do
        (x22, k): insertM (M x1 x2 m) t

This might help

data Message = M Name Name String deriving (Show)

Body:
This function inserts Messages in a List of Messages. And if the Message already is in the list increases the Message counter.

So line by line:

insertM (M x1 x2 m) [] = [(x2, 1)]

If the List is empty and you insert a Message, just enter the message with count 1.

insertM (M x1 x2 m) ((x22,k):t) = do

Thats the second case (look up pattern matching if you don't understand), where you insert a message, which looks like this (M x1 x2 m) into a list with the header (x22,k) and a tail t.

if x2 == x22 then
    (x22, k+1):t

This lines checks if the part of the message x2is the same as the x22 of the first element of the list and the increments the counter. If this isn't the case you look up the rest of the list

  (x22, k): insertM (M x1 x2 m) t

(x22,k) is the head of the list, : appends two lists, insertM (M x1 x2 m) t is a recursive call on the tail where you lookup the rest of the list.

For example:

(insertM (M "A" "B" "chicken") [])         => [("B",1)]
(insertM (M "A" "B" "chicken") [("B",1)])  => [("B",2)]
(insertM (M "A" "C" "chicken") [("B",2)])  => [("B",2),("C",1)]

Any further questions?


问:
Selecting specific ID from column names of a matrix based on a data frame column
I have a matrix and data frame like the ones below:

Matrix:

```<code>   A_96_apples_orange | B_92_apples_orange | A_83_bananas_green | B_83_bananas_green

A       5                      .....             ....                 ....
B       10                     ....              ....                 ....
C       8                      ....
D       ....                   ....              ....                 ....
</code>```

Dataframe:

```<code>      Quartile  |   ID
1        1        96_apples_orange
2        3        91_apples_red
3        3        72_grapes_blue
</code>```

Here are the steps I want to take:

remove the prefix "A_" and "B_" from the matrix column names to find and keep only the duplicated names (I have done this successfully).

select only the matrix column name that matches my df ID column

paste prefixes "A_" and "B_" back into the selected matrix column names.

the "..." represent numeric values in the matrix.

Thank you in advance!

答:
We can collapse the df$ID variable into a single pattern for the regex inside grep with paste(sep = "|").

then subset the matrix as usual, but with the argument drop = FALSE to keep the dimensions attributes of the matrix.

A small reprex:

```<code>mtx <-structure(1:6, .Dim = 2:3, .Dimnames = list(NULL, c("A_96_apples_orange",
"B_92_apples_orange", "A_83_bananas_green")))

mtx
     A_96_apples_orange B_92_apples_orange A_83_bananas_green
[1,]                  1                  3                  5
[2,]                  2                  4                  6

df<-data.frame(Quartile = c(1,3,3), ID = c('96_apples_orange', '91_apples_red', '72_grapes_blue'))

df

  Quartile               ID
1        1 96_apples_orange
2        3    91_apples_red
3        3   72_grapes_blue
</code>```

Answer

```<code>mtx[,grep(paste(df$ID, collapse = '|'), colnames(mtx)), drop = FALSE]

     A_96_apples_orange
[1,]                  1
[2,]                  2
</code>```

Body:
I have a matrix and data frame like the ones below:

Matrix:

   A_96_apples_orange | B_92_apples_orange | A_83_bananas_green | B_83_bananas_green

A       5                      .....             ....                 ....
B       10                     ....              ....                 ....
C       8                      ....
D       ....                   ....              ....                 ....

Dataframe:

      Quartile  |   ID
1        1        96_apples_orange
2        3        91_apples_red
3        3        72_grapes_blue

Here are the steps I want to take:

remove the prefix "A_" and "B_" from the matrix column names to find and keep only the duplicated names (I have done this successfully).

select only the matrix column name that matches my df ID column

paste prefixes "A_" and "B_" back into the selected matrix column names.

the "..." represent numeric values in the matrix.

Thank you in advance!

Body:
We can collapse the df$ID variable into a single pattern for the regex inside grep with paste(sep = "|").

then subset the matrix as usual, but with the argument drop = FALSE to keep the dimensions attributes of the matrix.

A small reprex:

mtx <-structure(1:6, .Dim = 2:3, .Dimnames = list(NULL, c("A_96_apples_orange",
"B_92_apples_orange", "A_83_bananas_green")))

mtx
     A_96_apples_orange B_92_apples_orange A_83_bananas_green
[1,]                  1                  3                  5
[2,]                  2                  4                  6

df<-data.frame(Quartile = c(1,3,3), ID = c('96_apples_orange', '91_apples_red', '72_grapes_blue'))

df

  Quartile               ID
1        1 96_apples_orange
2        3    91_apples_red
3        3   72_grapes_blue

Answer

mtx[,grep(paste(df$ID, collapse = '|'), colnames(mtx)), drop = FALSE]

     A_96_apples_orange
[1,]                  1
[2,]                  2


问:
Custom theme datepicker element-ui in vue
I have website with user can choice date_range, so i use datepicker element-ui. But datepicker default theme, how i can change that in vue.</p>

答:
this working for me, Element Plus with Vue 3!

In App.vue

```<code><style lang="scss">
 .el-date-editor {
   --el-date-editor-width: 40% !important;
 }
</style>
</code>```

Body:
this working for me, Element Plus with Vue 3!

In App.vue

<style lang="scss">
 .el-date-editor {
   --el-date-editor-width: 40% !important;
 }
</style>


问:
ReactJS how to close select dropdown on state change
I have doubts how to close the select dropdown on screen orientation change. For now I have  the listener that handles the state when the orientation is changed:

```<code>const [orientation, setOrientation] = useState('portrait');

useEffect(() => {
    window.addEventListener('orientationchange', setScreenOrientation)
    return () => {
      document.removeEventListener('orientationchange', setScreenOrientation)
    }
  }, [])

const setScreenOrientation = () => {
    if(window.matchMedia("(orientation: portrait)").matches){
      console.log('orientation: portrait');
      setOrientation('portrait');
    }

    if(window.matchMedia("(orientation: landscape)").matches){
      console.log('orientation: landscape');
      setOrientation('landscape');
    }
  }

 return (<Dropdown
          options={data}
          center
          onSelect={handleSelect}
          value={data.store_id}
          selected="key"
          screenOrientation={screenOrientation}
        />)
</code>```

Dropdown component

```<code>import React, { useEffect } from 'react';
import classnames from 'classnames';
import styles from './styles.module.scss';

export const Dropdown = ({
  options,
  center,
  onSelect,
  value,
  selected,
  screenOrientation
}) => {

  return (
    <div
      className={classnames(
        styles.dropdown
      )}
    >
      <select
        onChange={onSelect}
        value={value}
      >
        {options &&
          Object.entries(options)
            .map(([k, v]) => (
              <option
                key={v}
                value={selected === 'key' ? k : v}
              >
                {v}
              </option>
            ))}
      </select>
    </div>
  );
};
</code>```

But I don't know how to imlement this functionality when the screen is changed to close the dropdown if it's opened?

Thanks in advance.

答:
First of all, pass the state "orientation" as props to your Dropdown component.

```<code> return (<Dropdown
          options={data}
          center
          onSelect={handleSelect}
          value={data.store_id}
          selected="key"
          orientation={orientation}
        />)
</code>```

Then you will have to add a "ref" to your select component. With the "ref" you will be able to call the .onBlur() method whenever the orientation changes. To do that you will also need an useEffect();

```<code>import React, { useEffect, useRef } from 'react';
import classnames from 'classnames';
import styles from './styles.module.scss';

export const Dropdown = ({
  options,
  center,
  onSelect,
  value,
  selected,
  orientation
}) => {

  const ref = useRef();

  useEffect(() => {
     if(ref.current)
        ref.current.blur();
  }, [orientation]);

  return (
    <div
      className={classnames(
        styles.dropdown
      )}
    >
      <select
        onChange={onSelect}
        value={value}
        ref={ref}
      >
        {options &&
          Object.entries(options)
            .map(([k, v]) => (
              <option
                key={v}
                value={selected === 'key' ? k : v}
              >
                {v}
              </option>
            ))}
      </select>
    </div>
  );
};
</code>```

Body:
I have doubts how to close the select dropdown on screen orientation change. For now I have  the listener that handles the state when the orientation is changed:

const [orientation, setOrientation] = useState('portrait');

useEffect(() => {
    window.addEventListener('orientationchange', setScreenOrientation)
    return () => {
      document.removeEventListener('orientationchange', setScreenOrientation)
    }
  }, [])

const setScreenOrientation = () => {
    if(window.matchMedia("(orientation: portrait)").matches){
      console.log('orientation: portrait');
      setOrientation('portrait');
    }

    if(window.matchMedia("(orientation: landscape)").matches){
      console.log('orientation: landscape');
      setOrientation('landscape');
    }
  }

 return (<Dropdown
          options={data}
          center
          onSelect={handleSelect}
          value={data.store_id}
          selected="key"
          screenOrientation={screenOrientation}
        />)

Dropdown component

import React, { useEffect } from 'react';
import classnames from 'classnames';
import styles from './styles.module.scss';

export const Dropdown = ({
  options,
  center,
  onSelect,
  value,
  selected,
  screenOrientation
}) => {

  return (

      <select
        onChange={onSelect}
        value={value}
      >
        {options &&
          Object.entries(options)
            .map(([k, v]) => (
              <option
                key={v}
                value={selected === 'key' ? k : v}
              >
                {v}
              </option>
            ))}
      </select>

  );
};

But I don't know how to imlement this functionality when the screen is changed to close the dropdown if it's opened?

Thanks in advance.

Body:
First of all, pass the state "orientation" as props to your Dropdown component.

 return (<Dropdown
          options={data}
          center
          onSelect={handleSelect}
          value={data.store_id}
          selected="key"
          orientation={orientation}
        />)

Then you will have to add a "ref" to your select component. With the "ref" you will be able to call the .onBlur() method whenever the orientation changes. To do that you will also need an useEffect();

import React, { useEffect, useRef } from 'react';
import classnames from 'classnames';
import styles from './styles.module.scss';

export const Dropdown = ({
  options,
  center,
  onSelect,
  value,
  selected,
  orientation
}) => {

  const ref = useRef();

  useEffect(() => {
     if(ref.current)
        ref.current.blur();
  }, [orientation]);

  return (
    <div
      className={classnames(
        styles.dropdown
      )}
    >
      <select
        onChange={onSelect}
        value={value}
        ref={ref}
      >
        {options &&
          Object.entries(options)
            .map(([k, v]) => (
              <option
                key={v}
                value={selected === 'key' ? k : v}
              >
                {v}
              </option>
            ))}
      </select>
    </div>
  );
};


问:
There is no json.h in \usr\include\json-c directory ' ../nvme.h:26:10: fatal error: json.h: No such file or directory'
There is no "json.h" in "\usr\include\json-c" directory. Is there an application that I have to install? I have installed "sudo apt-get install libjsoncpp-dev," but it is not working.</p>
```<code>ubuntu@nvme-cli:~/nvme-cli$ ninja -C .build
ninja: Entering directory `.build'
[1/29] Compiling C object nvme.p/fabrics.c.o
FAILED: nvme.p/fabrics.c.o
cc -Invme.p -I. -I.. -Iccan -I../ccan -I/usr/include/json-c -I/usr/include/uuid
-fdiagnostics -color=always -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -std=gnu99 -O3
-fomit-frame-pointer -D_GNU_SOURCE -include config.h -MD -MQ
nvme.p/fabrics.c.o -MF nvme.p/fabrics.c.o.d -o nvme.p/fabrics.c.o -c ../fabrics.c
In file included from ../fabrics.c:41:0:
../nvme.h:26:10: fatal error: json.h: No such file or directory
 #include <json.h>
          ^~~~~~~~

compilation terminated.
[2/29] Compiling C object nvme.p/plugins_intel_intel-nvme.c.o
FAILED: nvme.p/plugins_intel_intel-nvme.c.o
cc -Invme.p -I. -I.. -Iccan -I../ccan -I/usr/include/json-c -I/usr/include/uuid
-fdiagnostics-color=always -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -std=gnu99 -O3
-fomit-frame-pointer -D_GNU_SOURCE -include config.h -MD -MQ
nvme.p/plugins_intel_intel-nvme.c.o -MF nvme.p/plugins_intel_intel-nvme.c.o.d -o nvme.p/plugins_intel_intel-nvme.c.o -c ../plugins/intel/intel-nvme.c
In file included from ../plugins/intel/intel-nvme.c:9:0:
../nvme.h:26:10: fatal error: json.h: No such file or directory
 #include <json.h>
          ^~~~~~~~
</code>```

答:
I have installed libjson-c-dev package and it solved the problem.</p>
```<code>sudo apt install libjson-c-dev
</code>```

Body:
There is no "json.h" in "\usr\include\json-c" directory. Is there an application that I have to install? I have installed "sudo apt-get install libjsoncpp-dev," but it is not working.

ubuntu@nvme-cli:~/nvme-cli$ ninja -C .build
ninja: Entering directory `.build'
[1/29] Compiling C object nvme.p/fabrics.c.o
FAILED: nvme.p/fabrics.c.o
cc -Invme.p -I. -I.. -Iccan -I../ccan -I/usr/include/json-c -I/usr/include/uuid
-fdiagnostics -color=always -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -std=gnu99 -O3
-fomit-frame-pointer -D_GNU_SOURCE -include config.h -MD -MQ
nvme.p/fabrics.c.o -MF nvme.p/fabrics.c.o.d -o nvme.p/fabrics.c.o -c ../fabrics.c
In file included from ../fabrics.c:41:0:
../nvme.h:26:10: fatal error: json.h: No such file or directory
 #include <json.h>
          ^~~~~~~~

compilation terminated.
[2/29] Compiling C object nvme.p/plugins_intel_intel-nvme.c.o
FAILED: nvme.p/plugins_intel_intel-nvme.c.o
cc -Invme.p -I. -I.. -Iccan -I../ccan -I/usr/include/json-c -I/usr/include/uuid
-fdiagnostics-color=always -D_FILE_OFFSET_BITS=64 -Wall -Winvalid-pch -std=gnu99 -O3
-fomit-frame-pointer -D_GNU_SOURCE -include config.h -MD -MQ
nvme.p/plugins_intel_intel-nvme.c.o -MF nvme.p/plugins_intel_intel-nvme.c.o.d -o nvme.p/plugins_intel_intel-nvme.c.o -c ../plugins/intel/intel-nvme.c
In file included from ../plugins/intel/intel-nvme.c:9:0:
../nvme.h:26:10: fatal error: json.h: No such file or directory
 #include <json.h>
          ^~~~~~~~

Body:
I have installed libjson-c-dev package and it solved the problem.

sudo apt install libjson-c-dev


问:
Dictionary KEYS python
```<code>

for key in Roles_dict1.keys:

</code>```

Thanks in Advance

答:
Try the following.

```<code>Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}

print(sorted(User_list.items(), key=lambda x:Roles_dict1[x[1]]))
</code>```

Result:

```<code>[('Jhon', 'CEO'), ('Bill', 'CTO'), ('MATEW', 'Devops')]
</code>```

You can cast this as a dictionary by applying dict(...) to the resulting list.

Title: Dictionary KEYS python

Body:
for key in Roles_dict1.keys:

Thanks in Advance

Body:
Try the following.

Roles_dict1 = {'CEO':1,'CTO':2,'Devops':3}
User_list = {'Jhon':'CEO','MATEW':'Devops','Bill':'CTO'}

print(sorted(User_list.items(), key=lambda x:Roles_dict1[x[1]]))

Result:

[('Jhon', 'CEO'), ('Bill', 'CTO'), ('MATEW', 'Devops')]

You can cast this as a dictionary by applying dict(...) to the resulting list.


问:
how to capture mouseclick in actionscript 3.0
How do I capture the position of a mouseclick from the user in my Flash window using Actionscript 3.0?</p>

答: Location defined by what context? The whole page? One or more specific clickable controls?</p>

OwnerDisplayName: yannick

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: le dorfier


答:
Maybe with CSS?</p>

```<code>text-align:center
</code>```

Title: Element "align" is obsolete or non-standard: what should I use instead?

Body:
I have this HTML code:

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

Body:
Maybe with CSS?

text-align:center


问:
How to import an entire Azure resource group in Terraform's state?
Is there a solution to import an entire Azure resource group into Terraform's state file with one command that would capture all resources within that resource group, without manually targeting each resource (which seems to be the only option based on my researches so far)?</p>

答:
Like @dan-monego mentioned, Terraformer is the way to go.
I used it in the past and it's awesome.
There is no official way to do this with Terraform, unfortunately.

If that's not an option for you, you would need to write custom code to list the resources in your group, parse the output and then run the terraform import command.

This command would output all the information you'll need to build your import statements az resource list -g <resource-group-name>


问:
Does MySQL always run foreign key constraint checks when a row is updated? Or only when a relevant column is changed?
I have this question and I haven't found specific documentation to confirm the behavior and am unaware of how to manually check this myself.

Consider I have table A with b_id foreign key to table B. If I run an update on a row in table A, does mysql always run the foreign key constraint check on table B even if A's b_id goes unchanged or isn't passed in the update statement? such as (select 1 from B where id = ?)

Example:

UPDATE A set A.name = "x", A.b_id = 1 where A.id = 1 I know this runs the foreign key check on B

UPDATE A set A.name = "x" where A.id = 1 But does this also run the foreign key check even though b_id goes unchanged since it was not passed?

UPDATE A set A.name = "x" A.b_id = A.b_id where A.id = 1 And what about this? b_id gets passed in with same existing value. Does the fk check run?

Any supporting documentation or help would be appreciated, as well as tips on how I can test this sort of behavior myself since using EXPLAIN doesn't help.

Edit: this is for INNODB engine and mysql 8.0

答:
Foreign key integrity is checked always when the server detects that the data is changed by fact and needs in save to the disk. It is checked after all BEFORE UPDATE triggers execution (rather than data type check which is performed each time, before and after each separate trigger).

The reason is simple. Server does not store any flag which marks does the value is changed - it is more expensive than direct compare before real, physical, UPDATE execution. The value changing is not tracked. Server does not know does the value to be saved during the update is provided by the query text or, for example, is provided by one of the BEFORE UPDATE triggers in the trigger chain.

small DEMO


问:
How to obtain coefficients for lagged exogenous variable in VAR model? (R)
Hello Stack community,

I am building the vector autoregression model with three endogenous and one exogenous variables. As I obtain the coefficients using summary(model_name) or Bcoef(model_name) commands, the output contains the lagged values for endogenous variables, but only current value (no lags) of exogenous variable.

However, what I am interested in is the effect of exogenous variable, hence the current and lagged coefficients of exogenous variable, but unfortunately no lags are provided.

I would greatly appreciate if someone has an idea how to obtain these coefficients? Is there a separate package for it (as a matter of fact, to draw impulse response function for exogenous variable, separate package is needed)? or if not the package, how else shall I deal with this issue?

答:
Exogenous variable are not affected by lags input in VAR model, so if you want to create and exogenous variable with lagged you will have to introduce each of this one by one, create a data frame with the lagged values:

library(vars)
#> Loading required package: MASS
#> Loading required package: strucchange
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#> Loading required package: urca
#> Loading required package: lmtest
library(magrittr)

data("Canada")

e <- Canada[,1]
prod <- Canada[,2]
rw <- Canada[,3]
exog <- Canada[,4]
exog_1 <- lag(exog,-1)
exog_2 <- lag(exog,-2)

data <- cbind(e,prod,rw,exog,exog_1,exog_2) %>%
  na.omit()

VAR(data[,1:3],exogen = data[,4:6])
#>
#> VAR Estimation Results:
#> =======================
#>
#> Estimated coefficients for equation e:
#> ======================================
#> Call:
#> e = e.l1 + prod.l1 + rw.l1 + const + exog + exog_1 + exog_2
#>
#>         e.l1      prod.l1        rw.l1        const         exog       exog_1
#>   1.02017830   0.05614693  -0.01826264 -34.21688327  -0.93864073   0.79002397
#>       exog_2
#>   0.22434453
#>
#>
#> Estimated coefficients for equation prod:
#> =========================================
#> Call:
#> prod = e.l1 + prod.l1 + rw.l1 + const + exog + exog_1 + exog_2
#>
#>          e.l1       prod.l1         rw.l1         const          exog
#>    0.16469624    0.99378315   -0.05301798 -133.87969507    0.17191734
#>        exog_1        exog_2
#>   -0.30238907    0.60487385
#>
#>
#> Estimated coefficients for equation rw:
#> =======================================
#> Call:
#> rw = e.l1 + prod.l1 + rw.l1 + const + exog + exog_1 + exog_2
#>
#>         e.l1      prod.l1        rw.l1        const         exog       exog_1
#>   0.17297620  -0.07327839   0.92329491 -99.55107991   0.49728306  -0.15506299
#>       exog_2
#>  -0.24236800
```

Created on 2022-02-11 by the reprex package (v1.0.0)

This is posible but not usual, remember to test if exog variable is really exogenous.

Body:
Exogenous variable are not affected by lags input in VAR model, so if you want to create and exogenous variable with lagged you will have to introduce each of this one by one, create a data frame with the lagged values:

library(vars)
#> Loading required package: MASS
#> Loading required package: strucchange
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#>     as.Date, as.Date.numeric
#> Loading required package: sandwich
#> Loading required package: urca
#> Loading required package: lmtest
library(magrittr)

data("Canada")

e <- Canada[,1]
prod <- Canada[,2]
rw <- Canada[,3]
exog <- Canada[,4]
exog_1 <- lag(exog,-1)
exog_2 <- lag(exog,-2)

data <- cbind(e,prod,rw,exog,exog_1,exog_2) %>%
  na.omit()

VAR(data[,1:3],exogen = data[,4:6])
#>
#> VAR Estimation Results:
#> =======================
#>
#> Estimated coefficients for equation e:
#> ======================================
#> Call:
#> e = e.l1 + prod.l1 + rw.l1 + const + exog + exog_1 + exog_2
#>
#>         e.l1      prod.l1        rw.l1        const         exog       exog_1
#>   1.02017830   0.05614693  -0.01826264 -34.21688327  -0.93864073   0.79002397
#>       exog_2
#>   0.22434453
#>
#>
#> Estimated coefficients for equation prod:
#> =========================================
#> Call:
#> prod = e.l1 + prod.l1 + rw.l1 + const + exog + exog_1 + exog_2
#>
#>          e.l1       prod.l1         rw.l1         const          exog
#>    0.16469624    0.99378315   -0.05301798 -133.87969507    0.17191734
#>        exog_1        exog_2
#>   -0.30238907    0.60487385
#>
#>
#> Estimated coefficients for equation rw:
#> =======================================
#> Call:
#> rw = e.l1 + prod.l1 + rw.l1 + const + exog + exog_1 + exog_2
#>
#>         e.l1      prod.l1        rw.l1        const         exog       exog_1
#>   0.17297620  -0.07327839   0.92329491 -99.55107991   0.49728306  -0.15506299
#>       exog_2
#>  -0.24236800

Created on 2022-02-11 by the reprex package (v1.0.0)

This is posible but not usual, remember to test if exog variable is really exogenous.


问:
Simple question about Entity Framework
I have this very simple example:

This generates these straightforward classes:

However, when I access the property Cities of any of my User objects read from the database it is always set to null. I thought that the Entity Framework would fill that property. Am I right? What I'm doing wrong?

Thanks.

EDIT: Just as a note I'm using 3.5, not 4 (looks like there are some key differences)

答:
It is interesting that you are getting null and not a list with 0 entries.

I therefore think that it is a problem with the model definition rather than a lazy loading or an include problem.

Try generating a new model.

Title: Simple question about Entity Framework


问:
Trying to get only cells with certain initials but giving me syntax error? SQL
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

```<code> SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id
</code>```

答:
First, you will need to create a column called Initials. In this case, you can use SUBSTR to get the first letter from you first_name and the first letter from last_name. Then, you will need to CONCAT them together to make it a column.

```<code>CONCAT(SUBSTR(first_name,1,1), '.', SUBSTR(last_name,1,1), '.') AS Initials
</code>```

After that, you need to find out who have the initials with B.W. . You can use LIKE ('B.W.'). Since you have a specific answer, you do not need to use %.

```<code>HAVING Initials LIKE ('B.W.')
</code>```

Body:
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

 SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id

Body:
First, you will need to create a column called Initials. In this case, you can use SUBSTR to get the first letter from you first_name and the first letter from last_name. Then, you will need to CONCAT them together to make it a column.

CONCAT(SUBSTR(first_name,1,1), '.', SUBSTR(last_name,1,1), '.') AS Initials

After that, you need to find out who have the initials with B.W. . You can use LIKE ('B.W.'). Since you have a specific answer, you do not need to use %.

HAVING Initials LIKE ('B.W.')


问:
Iterate through subsets of a dataframe
This is my first time posting on here. I have the code below that should loop through the energies in this dataframe and output the associated cross sections from the energy that falls within that range. However when I print out the cross-sections within the if statement, it prints out all the values in the energy dataframe, rather than a small subset. It should return only 120 cross section values in the end, not just one, as it does now. Does anyone know how I can fix this?</p>
```<code>energy = df.x #pandas dataframe

def crosssection(energy):
    for i in energy:
        if [(i >= .284) & (i <.400)]:
            c0, c1, c2 = 78.1, 18.8, 4.3
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24
            print(i)
            print(cross_section)
        elif [(i >= .400) & (i <.532)]:
            c0, c1, c2 = 71.4, 66.8, -51.4
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= .532) & (i <.707)]:
            c0, c1, c2 = 95.5, 145.8, -61.1
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= .707) & (i <.867)]:
            c0, c1, c2 = 308.9, -380.6, 294.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= .867) & (i <1.303)]:
            c0, c1, c3 = 120.6, 169.3, -47.7
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 1.303) & (i <1.840)]:
            c0, c1, c3 = 141.3, 146.8, -31.5
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 1.840) & (i <2.471)]:
            c0, c1, c3 = 202.7, 104.7, -17.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 2.471) & (i <3.210)]:
            c0, c1, c3 = 342.7, 18.7, 0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 3.210) & (i <4.038)]:
            c0, c1, c3 = 352.2, 18.7, 0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 4.038) & (i <7.111)]:
            c0, c1, c3 = 433.9, -2.4, 0.75
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 7.111) & (i <8.331)]:
            c0, c1, c3 = 629.0, 30.9, 0.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 8.331) & (i <10.0)]:
            c0, c1, c3 = 701.2, 25.2, 0.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 10.0)]:
            c0, c1, c3 = 701.2, 25.2, 0.0
            cross_section = (c0 + c1*i+ c2*i**2)*(i**-3)*10**-24
        return cross_section
</code>```

答:
Your return statement is in the for loop, so after the first energy, it will just return. What you probably want is to aggregate the individual cross_section values per energy and return a list or some collection of them. My example below is shortened but should give you the gist of it

EDIT: comments for clarity

Try:

def cross_section(energy):
    cross_sections = []

    for i in energy:

        if [(i >= .284) & (i <.400)]:
            c0, c1, c2 = 78.1, 18.8, 4.3
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24
            print(i)
            print(cross_section)
        elif [(i >= .400) & (i <.532)]:
            c0, c1, c2 = 71.4, 66.8, -51.4
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        # aggregate the individual cross_sections into a list
        cross_sections.append(cross_section)

    # return the list after looping
    return cross_sections
```

Title: Iterate through subsets of a dataframe

Body:
This is my first time posting on here. I have the code below that should loop through the energies in this dataframe and output the associated cross sections from the energy that falls within that range. However when I print out the cross-sections within the if statement, it prints out all the values in the energy dataframe, rather than a small subset. It should return only 120 cross section values in the end, not just one, as it does now. Does anyone know how I can fix this?

energy = df.x #pandas dataframe

def crosssection(energy):
    for i in energy:
        if [(i >= .284) & (i <.400)]:
            c0, c1, c2 = 78.1, 18.8, 4.3
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24
            print(i)
            print(cross_section)
        elif [(i >= .400) & (i <.532)]:
            c0, c1, c2 = 71.4, 66.8, -51.4
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= .532) & (i <.707)]:
            c0, c1, c2 = 95.5, 145.8, -61.1
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= .707) & (i <.867)]:
            c0, c1, c2 = 308.9, -380.6, 294.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= .867) & (i <1.303)]:
            c0, c1, c3 = 120.6, 169.3, -47.7
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 1.303) & (i <1.840)]:
            c0, c1, c3 = 141.3, 146.8, -31.5
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 1.840) & (i <2.471)]:
            c0, c1, c3 = 202.7, 104.7, -17.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 2.471) & (i <3.210)]:
            c0, c1, c3 = 342.7, 18.7, 0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 3.210) & (i <4.038)]:
            c0, c1, c3 = 352.2, 18.7, 0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 4.038) & (i <7.111)]:
            c0, c1, c3 = 433.9, -2.4, 0.75
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 7.111) & (i <8.331)]:
            c0, c1, c3 = 629.0, 30.9, 0.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 8.331) & (i <10.0)]:
            c0, c1, c3 = 701.2, 25.2, 0.0
            cross_section = (c0 + c1*i + c2*i**2)*(i**-3)*10**-24

        elif [(i >= 10.0)]:
            c0, c1, c3 = 701.2, 25.2, 0.0
            cross_section = (c0 + c1*i+ c2*i**2)*(i**-3)*10**-24
        return cross_section


问:
I wrote a loop that prints only the items in the list that begin with capital letter but islower() method doesnt return True if the item is lower case
```<code>friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
ignoredNames = []
i = 0

while i < len(friends):
    if friends[i].islower != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1

print(f"The Number Of The Ignored Names Is {len(ignoredNames)}")
</code>```

答:
You need to call the method as .islower() rather than .islower. The former calls the method and actually returns the boolean value you want in the check.

For instance:

```<code>friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
i=0
ignoredNames=[]
while i < len(friends):
    if friends[i].islower() != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1

print(ignoredNames)
</code>```

Output:

```<code>Mohamed
Shady
Sherif
['ahmed', 'eman']
</code>```

Body:
You need to call the method as .islower() rather than .islower. The former calls the method and actually returns the boolean value you want in the check.

For instance:

friends = ["Mohamed", "Shady", "ahmed", "eman", "Sherif"]
i=0
ignoredNames=[]
while i < len(friends):
    if friends[i].islower() != True:
        print(friends[i])
    else:
        ignoredNames.append(friends[i])
    i += 1

print(ignoredNames)

Output:

Mohamed
Shady
Sherif
['ahmed', 'eman']


问:
Laravel 9 app (upgraded from 8) lang directory not working as expected
I have upgraded my Laravel 8 application to version 9, and according to the docs: upgrade guide, the resources/lang directory is now located in the root project directory (lang).

I've moved the lang directory to the root directory of my project, but it does not seem to work.

```<code>// config/app.php
'locale' => 'pt-BR',
</code>```

and

```<code>// lang/pt-BR/messages.php
return [
    'welcome' => 'Welcome to the app!',
];
</code>```

Controller

```<code>return response()->json([
    'message' => Lang::get('messages.welcome') // it returns "messages.welcome"
]);
</code>```

But when I change the lang directory back to /resources/lang, it works fine like in previous laravel versions. So I created a new fresh project of Laravel 9, and it worked, which leads me to think that some additional configuration is needed, but it's not documented in the upgrade guide. My composer.json dependencies are precisely the same as the new laravel project. Is there any additional configuration that needs to be done for Laravel to recognize the directory?

答:
You could hardcode your lang path using the useLangPath method in your AppServiceProvider's boot method.

```<code># app/Providers/AppServiceProvider.php

public function boot()
{
    app()->useLangPath(base_path('lang'));

    // or app()->useLangPath(app()->basePath('lang'));
}
</code>```

Body:
I have upgraded my Laravel 8 application to version 9, and according to the docs: upgrade guide, the resources/lang directory is now located in the root project directory (lang).

I've moved the lang directory to the root directory of my project, but it does not seem to work.

// config/app.php
'locale' => 'pt-BR',

and

// lang/pt-BR/messages.php
return [
    'welcome' => 'Welcome to the app!',
];

Controller

return response()->json([
    'message' => Lang::get('messages.welcome') // it returns "messages.welcome"
]);

But when I change the lang directory back to /resources/lang, it works fine like in previous laravel versions. So I created a new fresh project of Laravel 9, and it worked, which leads me to think that some additional configuration is needed, but it's not documented in the upgrade guide. My composer.json dependencies are precisely the same as the new laravel project. Is there any additional configuration that needs to be done for Laravel to recognize the directory?

Body:
You could hardcode your lang path using the useLangPath method in your AppServiceProvider's boot method.

# app/Providers/AppServiceProvider.php

public function boot()
{
    app()->useLangPath(base_path('lang'));

    // or app()->useLangPath(app()->basePath('lang'));
}


问:
Exposing simple types on WSDL with Spyne
We are trying to build a SOAP app with Django + Spyne building specific required endpoints. The exposed WSDL has to precisely match a predetermined XML file, including the custom simpleType definitions. We're currently failing to show the simple type definitions on our WSDL, everything else matches up precisely.

A simple example is the following hello world app:

```<code>import logging
logging.basicConfig(level=logging.DEBUG)
from spyne import Application, rpc, ServiceBase, \
    Integer, Unicode, SimpleModel

from spyne import Iterable
from spyne.protocol.xml import XmlDocument
from spyne.protocol.soap import Soap11
from spyne.interface.wsdl import Wsdl11
from spyne.server.django import DjangoApplication
from django.views.decorators.csrf import csrf_exempt

class IdType(SimpleModel):
    __type_name__ = "IdType"
    __namespace__ = 'spyne.examples.hello'
    __extends__ = Unicode

    class Attributes(Unicode.Attributes):
        out_type = 'TxnIdType'

class HelloWorldService(ServiceBase):
    @rpc(IdType, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, TxnIdType, times):
        for i in range(times):
            yield 'Hello, %s' % TxnIdType

application = Application([HelloWorldService],
    tns='spyne.examples.hello',
    interface = Wsdl11(),
    in_protocol=Soap11(validator = 'lxml'),
    # out_protocol=XmlDocument(validator='schema')
    out_protocol=Soap11()
)

hello_app = csrf_exempt(DjangoApplication(application))
</code>```

Which yields the following WSDL:

```<code><wsdl:definitions xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:plink="http://schemas.xmlsoap.org/ws/2003/05/partner-link/" xmlns:wsdlsoap11="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdlsoap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap11enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope" xmlns:soap12enc="http://www.w3.org/2003/05/soap-encoding" xmlns:wsa="http://schemas.xmlsoap.org/ws/2003/03/addressing" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="spyne.examples.hello/types" xmlns:s0="spyne.examples.hello" targetNamespace="spyne.examples.hello/types" name="Application">
    <wsdl:types>
        <xs:schema targetNamespace="spyne.examples.hello/types" elementFormDefault="qualified">
            <xs:import namespace="spyne.examples.hello" />
            <xs:complexType name="say_helloResponse">
                <xs:sequence>
                    <xs:element name="say_helloResult" type="xs:string" minOccurs="0" nillable="true" />
                </xs:sequence>
            </xs:complexType>
            <xs:complexType name="say_hello">
                <xs:sequence>
                    <xs:element name="IdType" type="s0:IdType" minOccurs="0" nillable="true" />
                    <xs:element name="times" type="xs:integer" minOccurs="0" nillable="true" />
                </xs:sequence>
            </xs:complexType>
            <xs:element name="say_helloResponse" type="tns:say_helloResponse" />
            <xs:element name="say_hello" type="tns:say_hello" />
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="say_hello">
        <wsdl:part name="say_hello" element="tns:say_hello" />
    </wsdl:message>
    <wsdl:message name="say_helloResponse">
        <wsdl:part name="say_helloResponse" element="tns:say_helloResponse" />
    </wsdl:message>
    <wsdl:service name="HelloWorldService">
        <wsdl:port name="Application" binding="tns:Application">
            <wsdlsoap11:address location="http://localhost:8000/gtw/services/HelloWorldService" />
        </wsdl:port>
    </wsdl:service>
    <wsdl:portType name="Application">
        <wsdl:operation name="say_hello" parameterOrder="say_hello">
            <wsdl:input name="say_hello" message="tns:say_hello" />
            <wsdl:output name="say_helloResponse" message="tns:say_helloResponse" />
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="Application" type="tns:Application">
        <wsdlsoap11:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
        <wsdl:operation name="say_hello">
            <wsdlsoap11:operation soapAction="say_hello" style="document" />
            <wsdl:input name="say_hello">
                <wsdlsoap11:body use="literal" />
            </wsdl:input>
            <wsdl:output name="say_helloResponse">
                <wsdlsoap11:body use="literal" />
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
</wsdl:definitions>
</code>```

As you can see, the simpleType "IdType" does not show up. Is there a way to force Spyne to reflect these tags? Currently our output WSDL does not pass the required validation since it does not recognize the custom simpleTypes.

Our expected output is the following:

```<code>        <simpleType name="IdType">
                <restriction base="xsd:string">
                    <xsd:maxLength value="10"/>
                </restriction>
        </simpleType>
</code>```

Any help will be greatly appreciated.

Thanks!

答:
So you're this guy right? https://github.com/arskom/spyne/discussions/681

Pasting my response here as well. Hope you care to reply this time.

=================

Did you read this? http://spyne.io/docs/2.10/manual/03_types.html#customization

IdType = Unicode(10, type_name='IdType')

class HelloWorldService(ServiceBase):
    @rpc(IdType, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, TxnIdType, times):
        for i in range(times):
            yield 'Hello, %s' % TxnIdType
```

Does this produce the wsdl you need?

Body:
We are trying to build a SOAP app with Django + Spyne building specific required endpoints. The exposed WSDL has to precisely match a predetermined XML file, including the custom simpleType definitions. We're currently failing to show the simple type definitions on our WSDL, everything else matches up precisely.

A simple example is the following hello world app:

import logging
logging.basicConfig(level=logging.DEBUG)
from spyne import Application, rpc, ServiceBase, \
    Integer, Unicode, SimpleModel

from spyne import Iterable
from spyne.protocol.xml import XmlDocument
from spyne.protocol.soap import Soap11
from spyne.interface.wsdl import Wsdl11
from spyne.server.django import DjangoApplication
from django.views.decorators.csrf import csrf_exempt

class IdType(SimpleModel):
    __type_name__ = "IdType"
    __namespace__ = 'spyne.examples.hello'
    __extends__ = Unicode

    class Attributes(Unicode.Attributes):
        out_type = 'TxnIdType'

class HelloWorldService(ServiceBase):
    @rpc(IdType, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, TxnIdType, times):
        for i in range(times):
            yield 'Hello, %s' % TxnIdType

application = Application([HelloWorldService],
    tns='spyne.examples.hello',
    interface = Wsdl11(),
    in_protocol=Soap11(validator = 'lxml'),
    # out_protocol=XmlDocument(validator='schema')
    out_protocol=Soap11()
)

hello_app = csrf_exempt(DjangoApplication(application))

Which yields the following WSDL:

<wsdl:definitions xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:plink="http://schemas.xmlsoap.org/ws/2003/05/partner-link/" xmlns:wsdlsoap11="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdlsoap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap11enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap12env="http://www.w3.org/2003/05/soap-envelope" xmlns:soap12enc="http://www.w3.org/2003/05/soap-encoding" xmlns:wsa="http://schemas.xmlsoap.org/ws/2003/03/addressing" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:tns="spyne.examples.hello/types" xmlns:s0="spyne.examples.hello" targetNamespace="spyne.examples.hello/types" name="Application">
    <wsdl:types>
        <xs:schema targetNamespace="spyne.examples.hello/types" elementFormDefault="qualified">
            <xs:import namespace="spyne.examples.hello" />
            <xs:complexType name="say_helloResponse">
                <xs:sequence>
                    <xs:element name="say_helloResult" type="xs:string" minOccurs="0" nillable="true" />
                </xs:sequence>
            </xs:complexType>
            <xs:complexType name="say_hello">
                <xs:sequence>
                    <xs:element name="IdType" type="s0:IdType" minOccurs="0" nillable="true" />
                    <xs:element name="times" type="xs:integer" minOccurs="0" nillable="true" />
                </xs:sequence>
            </xs:complexType>
            <xs:element name="say_helloResponse" type="tns:say_helloResponse" />
            <xs:element name="say_hello" type="tns:say_hello" />
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="say_hello">
        <wsdl:part name="say_hello" element="tns:say_hello" />
    </wsdl:message>
    <wsdl:message name="say_helloResponse">
        <wsdl:part name="say_helloResponse" element="tns:say_helloResponse" />
    </wsdl:message>
    <wsdl:service name="HelloWorldService">
        <wsdl:port name="Application" binding="tns:Application">
            <wsdlsoap11:address location="http://localhost:8000/gtw/services/HelloWorldService" />
        </wsdl:port>
    </wsdl:service>
    <wsdl:portType name="Application">
        <wsdl:operation name="say_hello" parameterOrder="say_hello">
            <wsdl:input name="say_hello" message="tns:say_hello" />
            <wsdl:output name="say_helloResponse" message="tns:say_helloResponse" />
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="Application" type="tns:Application">
        <wsdlsoap11:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
        <wsdl:operation name="say_hello">
            <wsdlsoap11:operation soapAction="say_hello" style="document" />
            <wsdl:input name="say_hello">
                <wsdlsoap11:body use="literal" />
            </wsdl:input>
            <wsdl:output name="say_helloResponse">
                <wsdlsoap11:body use="literal" />
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
</wsdl:definitions>

As you can see, the simpleType "IdType" does not show up. Is there a way to force Spyne to reflect these tags? Currently our output WSDL does not pass the required validation since it does not recognize the custom simpleTypes.

Our expected output is the following:

        <simpleType name="IdType">
                <restriction base="xsd:string">
                    <xsd:maxLength value="10"/>
                </restriction>
        </simpleType>

Any help will be greatly appreciated.

Thanks!

Body:
So you're this guy right? https://github.com/arskom/spyne/discussions/681

Pasting my response here as well. Hope you care to reply this time.

=================

Did you read this? http://spyne.io/docs/2.10/manual/03_types.html#customization

IdType = Unicode(10, type_name='IdType')

class HelloWorldService(ServiceBase):
    @rpc(IdType, Integer, _returns=Iterable(Unicode))
    def say_hello(ctx, TxnIdType, times):
        for i in range(times):
            yield 'Hello, %s' % TxnIdType

Does this produce the wsdl you need?


问:
Element "align" is obsolete or non-standard: what should I use instead?
I have this HTML code:

```<code><td align="center">
</code>```

and I'm getting this error in Visual Studio 2008 from ReSharper:

"Element 'align' is obsolete or nonstandard"

What is the replacement of this code to make it standard?

答:
Use CSS, not element attributes.

```<code><td style="text-align: center;">
</code>```

You can also place this in an external style sheet:

```<code>td {
    text-align: center;
}
</code>```

Body:
Use CSS, not element attributes.

<td style="text-align: center;">

You can also place this in an external style sheet:

td {
    text-align: center;
}


问:
Is there a way to remove businesses from LeafletJS
Is there a way in Leaflet to remove things like businesses from a map and just leave other features? I can't see anything in the API.</p>

答: Use mapbox, you can design you own tiles to use with leaflet</p>


问:
Push to Login page if user is not logged in, else let inside
I want to create a simple Login page that routes me to home page.

In my content page I want the default path to be /, and for login /login. I want to push user to /login route based on a conditional isLoggedIn, at the moment without state manager just for testing purposes. Not sure if I am setting this up correctly, maybe I am doing this completely wrong? I want also to be able to access different routes after being logged in.

function App() {
  const isLoggedIn = true;
  return (
    <Router>
      <Routes>

        {isLoggedIn
        ? <Route path="/" element={<Content />}></Route>
        : <Route path="/login" element={<Login />}></Route>
      }

    </Routes>
    </Router>
  );
}

```
<p>I am getting this error</p>
```index.tsx:19 Uncaught Error: [div] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
```

答:
Well a couple of different factors are at play here.

First of all, the only Route components are allowed as children of the Routes component and so that's the reason you're getting the following error:

index.tsx:19 Uncaught Error: [div] is not a  component. All component children of  must be a  or <React.Fragment>

Next, one way of going about it is to just render a redirect in the element property of the root path if the user is not signed in.

import { Router, Routes, Route, Navigate } from "react-router-dom";

function App() {
  const isLoggedIn = true;
  return (
    <Router>

          {/*The only children of Routes should be Route components*/}
          <Routes>
            <Route path="/login" element={<Login />} />

            {/* Render a redirect to login if the user is not signed in */}
            <Route
              path="/"
              element={isLoggedIn ? <Content /> : <Navigate to="/login" />}
            />
          </Routes>

    </Router>
  );
}
```

Body:
I want to create a simple Login page that routes me to home page.

In my content page I want the default path to be /, and for login /login. I want to push user to /login route based on a conditional isLoggedIn, at the moment without state manager just for testing purposes. Not sure if I am setting this up correctly, maybe I am doing this completely wrong? I want also to be able to access different routes after being logged in.

function App() {
  const isLoggedIn = true;
  return (
    <Router>
      <Routes>

        {isLoggedIn
        ? <Route path="/" element={<Content />}></Route>
        : <Route path="/login" element={<Login />}></Route>
      }

    </Routes>
    </Router>
  );
}

I am getting this error

index.tsx:19 Uncaught Error: [div] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

Body:
Well a couple of different factors are at play here.

First of all, the only Route components are allowed as children of the Routes component and so that's the reason you're getting the following error:

index.tsx:19 Uncaught Error: [div] is not a  component. All component children of  must be a  or <React.Fragment>

Next, one way of going about it is to just render a redirect in the element property of the root path if the user is not signed in.

import { Router, Routes, Route, Navigate } from "react-router-dom";

function App() {
  const isLoggedIn = true;
  return (
    <Router>
      <div className="app">
        <Header />
        <div class="app__body">
          {/*The only children of Routes should be Route components*/}
          <Routes>
            <Route path="/login" element={<Login />} />

            {/* Render a redirect to login if the user is not signed in */}
            <Route
              path="/"
              element={isLoggedIn ? <Content /> : <Navigate to="/login" />}
            />
          </Routes>
        </div>
      </div>
    </Router>
  );
}


问:
Best way to get pub sub json data into bigquery
I am currently trying to ingest numerous types of pub sub-data (JSON format) into GCS and BigQuery using a cloud function. I am just wondering what is the best way to approach this?

At the moment I am just dumping the events to GCS (each even type is on its own directory path) and was trying to create an external table but there are issues since the JSON isn't newline delimited.

Would it be better just to write the data as JSON strings in BQ and do the parsing in BQ?

答:
With BigQuery, you have a brand new type name JSON. It helps you to query more easily JSON data type. It could be the solution if you store your event in BigQuery.

About your questions about the use of Cloud Functions, it depends. If you have a few events, Cloud Functions are great and not so much expensive.

If you have an higher rate of event, Cloud Run can be a good alternative to leverage concurrency and to keep the cost low.

If you have million of event per hour or per minute, consider Dataflow with the pubsub to bigquery template.


问:
Adding server side rendering in AWS Lambda stack for Angular
So before I begin full on coding going down the wrong path, I'm looking into Angular Universal be the SSR and reading on AWS docs to do it. The SSR is mainly for speed and for Googlebot/SEO.

I am reading the white paper here:

AWS Serverless Multi-Tier Architectures with Amazon API Gateway and AWS Lambda

I love this approach but I am missing two things in the diagram that I need research on:

I want to have my own auth with AWS Cognito (and maybe a third-party identity manager like Google or GiHub added latter)

Where does the SSR pages go?

The AWS docs I've read say push it to AWS Lambda with the AWS CLI which includes some TS files (lambda.ts) and such.

does this make the bucket obsolete and not used for the SPA?

can Webpack be used in any way in this AWS methodology to make things easier?

Side note: I haven't use AWS in this full capacity yet and trying to figure out how to integrate the enviornment I want based on my needs outlined above.

答:
I want to have my own auth with AWS Cognito (and maybe a third-party identity manager like Google or GiHub added latter)

AWS API gateway supports integration with AWS Cognito.

For REST API Gateways: Control access to a REST API using Amazon Cognito user pools as authorizer

For HTTP API Gateways: Controlling access to HTTP APIs with JWT authorizers (You can use Amazon Cognito as a JWT issuer: Reference)

Where does the SSR pages go?

The most conventional architecture is to build your Angular project and convert it to static files (using Webpack or other means), upload the static output files to S3, and then serve the static files via CloudFront (recommended) or directly from S3. This is the architecture depicted in the linked AWS Whitepaper and the diagram.

The AWS docs I've read say push it to AWS Lambda with the AWS CLI
which includes some TS files (lambda.ts) and such.

does this make the bucket obsolete and not used for the SPA?

Yes, if you use the approach you are describing here, you won't be using S3. Instead, you would be serving your SPA through API Gateway.