问:
Invalid numeric literal when running jq from script via crontab
I have a shell script that runs fine from the command line but throws a error when it's run from a cronjob. What could be causing this error?

The following includes the cron, the script, and the error I'm getting in /var/spool/mail.

```<code>[jira-svc ~]$ cat jira_trigger_updater.sh
#!/usr/bin/sh

tmp_file=/tmp/merge-issues/$(date --iso-8601=minutes).txt
mkdir -p /tmp/merge-issues

/usr/bin/curl -s -X GET -H "Content-Type: application/json" "https://services-gateway.g054.usdcag.aws.ray.com/project-management/rest/api/2/search?jql=filter%3D14219&fields=key,status,fixVersions" -u jira-svc:${UPDATE_TRIGGER_PASSWORD} > ${tmp_file}
/usr/bin/jq -r '.issues[] | [.key , .fields.status.name , .fields.fixVersions[].name] | join(",")' ${tmp_file} > /rational/triggers/inputs/jira_merge.csv

/usr/bin/chmod 644 /rational/triggers/inputs/jira_merge.csv

#rm -rf /tmp/merge-issues
[jira-svc ~]$ crontab -l
#*/1 * * * * /usr/bin/sh /home/jira-svc/jira_trigger_updater.sh
[jira-svc@ ~]$ tail -25 /var/spool/mail/jira-svc
From jira-svc@cc01-217-136.localdomain  Tue Feb  8 20:10:02 2022
Return-Path: <jira-svc@cc01-217-136.localdomain>
X-Original-To: jira-svc
Delivered-To: jira-svc@cc01-217-136.localdomain
Received: by cc01-217-136.localdomain (Postfix, from userid 1001)
        id 9C40168152B5; Tue,  8 Feb 2022 20:10:02 +0000 (UTC)
From: "(Cron Daemon)" <jira-svc@cc01-217-136.localdomain>
To: jira-svc@cc01-217-136.localdomain
Subject: Cron <jira-svc@cc01-217-136> /usr/bin/sh /home/jira-svc/jira_trigger_updater.sh
Content-Type: text/plain; charset=UTF-8
Auto-Submitted: auto-generated
Precedence: bulk
X-Cron-Env: <XDG_SESSION_ID=2172>
X-Cron-Env: <XDG_RUNTIME_DIR=/run/user/1001>
X-Cron-Env: <LANG=en_US.UTF-8>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/jira-svc>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=jira-svc>
X-Cron-Env: <USER=jira-svc>
Message-Id: <20220208201002.9C40168152B5@cc01-217-136.localdomain>
Date: Tue,  8 Feb 2022 20:10:02 +0000 (UTC)

parse error: Invalid numeric literal at line 13, column 0

[jira-svc ~]$
</code>```

答: Cron runs jobs from a non-ineractive, non-login shell and doesn't load environment variables from files like ~/.bashrc, ~/.bash_profile, /etc/profile, and others. You must source these files if you want to include the environment variables defined in them.

Body:
I have a shell script that runs fine from the command line but throws a error when it's run from a cronjob. What could be causing this error?

The following includes the cron, the script, and the error I'm getting in /var/spool/mail.

[jira-svc ~]$ cat jira_trigger_updater.sh
#!/usr/bin/sh

tmp_file=/tmp/merge-issues/$(date --iso-8601=minutes).txt
mkdir -p /tmp/merge-issues

/usr/bin/curl -s -X GET -H "Content-Type: application/json" "https://services-gateway.g054.usdcag.aws.ray.com/project-management/rest/api/2/search?jql=filter%3D14219&fields=key,status,fixVersions" -u jira-svc:${UPDATE_TRIGGER_PASSWORD} > ${tmp_file}
/usr/bin/jq -r '.issues[] | [.key , .fields.status.name , .fields.fixVersions[].name] | join(",")' ${tmp_file} > /rational/triggers/inputs/jira_merge.csv

/usr/bin/chmod 644 /rational/triggers/inputs/jira_merge.csv

#rm -rf /tmp/merge-issues
[jira-svc ~]$ crontab -l
#*/1 * * * * /usr/bin/sh /home/jira-svc/jira_trigger_updater.sh
[jira-svc@ ~]$ tail -25 /var/spool/mail/jira-svc
From jira-svc@cc01-217-136.localdomain  Tue Feb  8 20:10:02 2022
Return-Path: <jira-svc@cc01-217-136.localdomain>
X-Original-To: jira-svc
Delivered-To: jira-svc@cc01-217-136.localdomain
Received: by cc01-217-136.localdomain (Postfix, from userid 1001)
        id 9C40168152B5; Tue,  8 Feb 2022 20:10:02 +0000 (UTC)
From: "(Cron Daemon)" <jira-svc@cc01-217-136.localdomain>
To: jira-svc@cc01-217-136.localdomain
Subject: Cron <jira-svc@cc01-217-136> /usr/bin/sh /home/jira-svc/jira_trigger_updater.sh
Content-Type: text/plain; charset=UTF-8
Auto-Submitted: auto-generated
Precedence: bulk
X-Cron-Env: <XDG_SESSION_ID=2172>
X-Cron-Env: <XDG_RUNTIME_DIR=/run/user/1001>
X-Cron-Env: <LANG=en_US.UTF-8>
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/home/jira-svc>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=jira-svc>
X-Cron-Env: <USER=jira-svc>
Message-Id: <20220208201002.9C40168152B5@cc01-217-136.localdomain>
Date: Tue,  8 Feb 2022 20:10:02 +0000 (UTC)

parse error: Invalid numeric literal at line 13, column 0

[jira-svc ~]$


来源: stackexchange

问:
How can I stop a css background resizing to fit the browser window?
When using a css background such as in the footer on the page below (in the elements div.footer_head and div.footer_footer), if the browser window is resized to less than about 1000px the divs themselves remain at the full width but scrolling right in the browser causes whitespace to appear where the background should be.

I was sure I'd find a similar question on here but can't seem to word it correctly enough to find it in search.

If someone could point me in the right direction I'm sure I can figure this out.

Look at how the divs with class footer_head and footer_footer behave when you resize the browser to be quite thin and scroll to the right.

screenshot http://printanomics.unbranded-nomads.co.uk/picture-2.jpg

答:
If you have a look at your css file you will see that the footer width is set to 100% and not 1000px as the other divs. This also applies to your background as your background won't be bigger than the div itself.

I don't know if you use this, but Firebug is a very good Firefox plugin to identify troubles in CSS files.

ContentLicense: CC BY-SA 3.0


问:
counting row values with different ids in multidimensional array
I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)

I am trying to achieve something like...

```<code>Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4)
        [1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
        [2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
         )
</code>```

where [0] would be buyer id, 1 is total number of buys and [2] total cost.

My current code:

```<code>if(($s_open = fopen("sales.csv", "r")) !== FALSE)
    {
        $s_count = count(file("sales.csv"));
        while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
        {
            ...
        }
        fclose($s_open);
    }
</code>```

Thanks in advance.

答:
You could group your data by creating an array with the buyer_id as index.

Each time you find a new buyer, you could create a small array ('id','count','amount').

Then, sum the values of the current row into that array.

```<code>const KEY_ID     = 0; // shortcut for array indexes
const KEY_AMOUNT = 1;
const KEY_COUNT  = 2;

$buyers = []; // final array

if (($s_open = fopen("sales.csv", "r")) !== FALSE)
{
    $s_count = count(file("sales.csv"));
    while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
    {
        // Extract data from row:
        [$id, $buyer_id, , $amount] = $sales;

        // If the buyer doesn't exists in the array,
        // create a new array with required format:
        if (!isset($buyers[$buyer_id])) {
            $buyers[$buyer_id] = [
                KEY_ID     => $buyer_id,
                KEY_COUNT  => 0,
                KEY_AMOUNT => 0,
            ];
        }

        // Update values:
        $buyers[$buyer_id][KEY_COUNT]++;
        $buyers[$buyer_id][KEY_AMOUNT] += $amount;
    }
    fclose($s_open);
}

// Re-index values:
$buyers = array_values($buyers);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know there are a lot of topics about this, but just couldn't find any that would actually help me solve the problem.
Ok so i am having a problem with counting rows and values in multidimensional array (imported via .csv)

I am trying to achieve something like...

Array ( [0] => Array ( [0] => 1 [1] => 6278,31 [2] => 4)
        [1] => Array ( [0] => 2 [1] => 2,0 [2] => 2)
        [2] => Array ( [0] => 3 [1] => 3,01 [2] => 3)
         )

where [0] would be buyer id, 1 is total number of buys and [2] total cost.

My current code:

if(($s_open = fopen("sales.csv", "r")) !== FALSE)
    {
        $s_count = count(file("sales.csv"));
        while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
        {
            ...
        }
        fclose($s_open);
    }

Thanks in advance.

Body:
You could group your data by creating an array with the buyer_id as index.

Each time you find a new buyer, you could create a small array ('id','count','amount').

Then, sum the values of the current row into that array.

const KEY_ID     = 0; // shortcut for array indexes
const KEY_AMOUNT = 1;
const KEY_COUNT  = 2;

$buyers = []; // final array

if (($s_open = fopen("sales.csv", "r")) !== FALSE)
{
    $s_count = count(file("sales.csv"));
    while(($sales = fgetcsv($s_open, 100, ";")) !== FALSE)
    {
        // Extract data from row:
        [$id, $buyer_id, , $amount] = $sales;

        // If the buyer doesn't exists in the array,
        // create a new array with required format:
        if (!isset($buyers[$buyer_id])) {
            $buyers[$buyer_id] = [
                KEY_ID     => $buyer_id,
                KEY_COUNT  => 0,
                KEY_AMOUNT => 0,
            ];
        }

        // Update values:
        $buyers[$buyer_id][KEY_COUNT]++;
        $buyers[$buyer_id][KEY_AMOUNT] += $amount;
    }
    fclose($s_open);
}

// Re-index values:
$buyers = array_values($buyers);


问:
How to properly set labels in contourf subplots?
I am trying to get rid of these purple points on the picture below. Here is my code:

```<code>p_values = [0., 0.05, 0.25, 0.5, 1, 1.5, 2, 5, 10, np.inf]
xx, yy = np.meshgrid(np.linspace(-3, 3, num = 101),
                     np.linspace(-3, 3, num = 101))

fig, axes = plt.subplots(ncols = (len(p_values) + 1) // 2,
                         nrows = 2, figsize = (16, 7))

for p, ax in zip(p_values, axes.flat):
    ### BEGIN Solution (do not delete this comment)
    z = np.linalg.norm([xx, yy], ord = p, axis = 0)
    ax.contourf(yy, xx, z, 25, cmap = 'coolwarm')
    ax.contour(yy, xx, z, [1], colors = 'fuchsia', linewidths = 3)
    ax.set_title(f'p = {p}')
    ax.legend([f'$x: |x|_{{{p}}} = 1$']);
    ### END Solution (do not delete this comment)
plt.show()
</code>```

Which parameters should be specified in ax.legend() in order to plot the graph clear.

答:
You could create the legend using an explicit handle.  In this case the fuchsia colored line is stored as the last element of ax.collections. Creating the legend with only labels, when there were no "handles with labels" set, could be the cause of the weird purple dots.

import matplotlib.pyplot as plt
import numpy as np

p_values = [0., 0.05, 0.25, 0.5, 1, 1.5, 2, 5, 10, np.inf]
xx, yy = np.meshgrid(np.linspace(-3, 3, num=101),
                     np.linspace(-3, 3, num=101))

fig, axes = plt.subplots(ncols=(len(p_values) + 1) // 2,
                         nrows=2, figsize=(16, 7))
cmap = plt.get_cmap('magma').copy()
cmap.set_extremes(over='green', under='black', bad='turquoise')
for p, ax in zip(p_values, axes.flat):
    ### BEGIN Solution (do not delete this comment)
    z = np.linalg.norm([xx, yy], ord=p, axis=0)
    cnt = ax.contourf(yy, xx, z, 25, cmap='coolwarm')
    ax.contour(yy, xx, z, [1], colors='fuchsia', linewidths=3)
    ax.set_title(f'p = {p}')
    ax.legend(handles=[ax.collections[-1]], labels=[f'$x: |x|_{{{p}}} = 1$'])
    plt.colorbar(cnt, ax=ax)
    ### END Solution (do not delete this comment)
plt.tight_layout()
plt.show()
```

Body:
I am trying to get rid of these purple points on the picture below. Here is my code:

p_values = [0., 0.05, 0.25, 0.5, 1, 1.5, 2, 5, 10, np.inf]
xx, yy = np.meshgrid(np.linspace(-3, 3, num = 101),
                     np.linspace(-3, 3, num = 101))

fig, axes = plt.subplots(ncols = (len(p_values) + 1) // 2,
                         nrows = 2, figsize = (16, 7))

for p, ax in zip(p_values, axes.flat):
    ### BEGIN Solution (do not delete this comment)
    z = np.linalg.norm([xx, yy], ord = p, axis = 0)
    ax.contourf(yy, xx, z, 25, cmap = 'coolwarm')
    ax.contour(yy, xx, z, [1], colors = 'fuchsia', linewidths = 3)
    ax.set_title(f'p = {p}')
    ax.legend([f'$x: |x|_{{{p}}} = 1$']);
    ### END Solution (do not delete this comment)
plt.show()

Which parameters should be specified in ax.legend() in order to plot the graph clear.


问:
How can i change app bar text to TextField in flutter with a icon buton?
I'm making an app to search courses on firebase. The app bar shows a text: "Home", and it has a search button at the rigth side of the screen:

I want to hide that "Home" text from de app bar at moment to click the search button, and show the field to type the query.

this is my code, i dont know how to implement that.

```<code>appBar: AppBar(
    title: Text(
      "Home",
      style: TextStyle(
        fontSize: 16.0, /*fontWeight: FontWeight.bold*/
      ),
    ),
    centerTitle: true,

 //search icon
 actions: [
  IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      //i want to change the text of the app bar:"Home" to a TextField to type
      AppBar(
        title: TextField(
          style: TextStyle(color: Colors.white),
          decoration: InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
          controller: searchController,
        ),
      );
    },
  ),
],
</code>```

),

答:
I think you want something like this:</p>
```<code>  bool _showSearch=false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _showSearch? TextField(
          controller: searchController,
          style: const TextStyle(color: Colors.white),
          decoration: const InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
        ):const Text(
          "Home",
          style: TextStyle(
            fontSize: 16.0, /*fontWeight: FontWeight.bold*/
          ),
        ),
        centerTitle: true,

        //search icon
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              setState(() {
                _showSearch=!_showSearch;
              });
            },
          ),
        ],
      ),
    );
  }
</code>```

Body:
I'm making an app to search courses on firebase. The app bar shows a text: "Home", and it has a search button at the rigth side of the screen:

I want to hide that "Home" text from de app bar at moment to click the search button, and show the field to type the query.

this is my code, i dont know how to implement that.

appBar: AppBar(
    title: Text(
      "Home",
      style: TextStyle(
        fontSize: 16.0, /*fontWeight: FontWeight.bold*/
      ),
    ),
    centerTitle: true,

 //search icon
 actions: [
  IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      //i want to change the text of the app bar:"Home" to a TextField to type
      AppBar(
        title: TextField(
          style: TextStyle(color: Colors.white),
          decoration: InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
          controller: searchController,
        ),
      );
    },
  ),
],

),

Body:
I think you want something like this:

  bool _showSearch=false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _showSearch? TextField(
          controller: searchController,
          style: const TextStyle(color: Colors.white),
          decoration: const InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
        ):const Text(
          "Home",
          style: TextStyle(
            fontSize: 16.0, /*fontWeight: FontWeight.bold*/
          ),
        ),
        centerTitle: true,

        //search icon
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              setState(() {
                _showSearch=!_showSearch;
              });
            },
          ),
        ],
      ),
    );
  }


问:
how to use sass using in vuejs3/vite
I starting with vite / vuejs 3

after installing sass with npm install -D sass I tried to add my _variables.js file this to vite.config.js

```<code>css: {preprocessorOptions: {scss: {additionalData: `@import" ./src/css/_variables.scss ";`,},},},
</code>```

din't work!

it also worked in vue.config

```<code>css: {
     loaderOptions: {
       sass: {
         sassOptions: {
            prependData: `@import" @ / css / _variables.scss ";`,
         }
       }
     }
   },
</code>```

after this tried to import the file in main.js import "./css/_variables.scss"

Unfortunately, my components cannot find the variables, where is the error

答:
Vite is a litte bit different

    import { defineConfig } from 'vite'

    export default defineConfig({
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: `
              @import "./src/styles/_animations.scss";
              @import "./src/styles/_variables.scss";
              @import "./src/styles/_mixins.scss";
              @import "./src/styles/_helpers.scss";
            `
          }
        }
      }
    })
```

Title: how to use sass using in vuejs3/vite

Body:
I starting with vite / vuejs 3

after installing sass with npm install -D sass I tried to add my _variables.js file this to vite.config.js

css: {preprocessorOptions: {scss: {additionalData: `@import" ./src/css/_variables.scss ";`,},},},

din't work!

it also worked in vue.config

css: {
     loaderOptions: {
       sass: {
         sassOptions: {
            prependData: `@import" @ / css / _variables.scss ";`,
         }
       }
     }
   },

after this tried to import the file in main.js import "./css/_variables.scss"

Unfortunately, my components cannot find the variables, where is the error


问:
How to hide one cell in the ASCIIDOC table?
I have a table with human parameters. I want to hide one column, for example age, if attribute :showall: is not set. How to do that? I can hide only the whole table, but not the one column.</p>
```<code>.Human parameters
:showall:
ifdef::showall[]
[cols="1,1,1,1,1"]
|===
|Name
|Sex
|Age
|Country
|Weight

5+^|Values

|John Daw
|Male
|41
|Algeria
|85
endif::showall[]
</code>```

答:
That's not a built in feature.

You have two options:

For cell content that should be hidden, simply remove it from the table.

If you need show/hide functionality, you'll need to add some custom JavaScript and CSS to make that happen.

For option 2, the technique for including JS/CSS is called Docinfo files.

You'll have to experiment with column show/hide, as there may be browser compatibility or presentation issues that would need to be addressed. That said, this answer might show a technique that would work for you: https://stackoverflow.com/a/34098320/4023764

Body:
I have a table with human parameters. I want to hide one column, for example age, if attribute :showall: is not set. How to do that? I can hide only the whole table, but not the one column.

.Human parameters
:showall:
ifdef::showall[]
[cols="1,1,1,1,1"]
|===
|Name
|Sex
|Age
|Country
|Weight

5+^|Values

|John Daw
|Male
|41
|Algeria
|85
endif::showall[]


问:
How to remove specific QUERY_STRING parameter in .htaccess
I need a proper solution to delete the URL parameter.

Example:

Input: https://www.hostever.com/blackfriday/?fbclid=IwAR3s1aVKUQELAb0EGW9_mh4qyR-i9ZqfNjFFB6xv_MoNRal2cH--lKofqHM

Output: https://www.hostever.com/blackfriday/

So it will delete the fbclid=

```<code>Input: https://www.hostever.com/?s=blogger
Output: https://www.hostever.com/?s=blogger
No need to change other parameters except **fbclid=**
</code>```

I( need to delete only fbclid= this one from the URL.

Now I am using this, but the problem is with many parameters.

```<code><IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{QUERY_STRING} !=""
 RewriteCond %{QUERY_STRING} !^p=.*
 RewriteCond %{QUERY_STRING} !^action=.*
 RewriteCond %{QUERY_STRING} !^s=.*
 RewriteCond %{REQUEST_URI} !^/wp-admin.*
 RewriteRule ^(.*)$ /$1? [R=301,L]
</IfModule>
</code>```

Please help me, How can I delete a specific parameter from the URL with .htaccess?

答:
I think Stephen had the right idea.  But for what it's worth, I only needed one rule to remove three types of trackers:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
  RewriteCond %{QUERY_STRING} ^(.*)(fbclid|gclid|utm_)[^\&]*\&(.*)$
  RewriteRule ^(.*)$ /$1?%1%3 [R=301,L]
</IfModule>
</code>```

I needed this for a Wordpress blog, because when Wordpress tried to process parameters, the bogus ones caused a 404.  (Even when the URI was to a non-Wordpress static page on the site!)

The first set of parentheses matches everything before either of the three bad guys.  The third matches everything after the &.  The condition then puts the first and third together.  Stephen's comment about it depending on the & being present is correct—it does not remove the fbclid! (unless followed by an ampersand).  And yet, for reasons I don't understand, adding this rule made Wordpress stop saying 404 on links from Facebook.

However, my rule will not work if fbclid is in the URI outside of the parameters.  For example, any page on a domain named fbclid-sucks.com  :-)

Body:
I need a proper solution to delete the URL parameter.

Example:

Input: https://www.hostever.com/blackfriday/?fbclid=IwAR3s1aVKUQELAb0EGW9_mh4qyR-i9ZqfNjFFB6xv_MoNRal2cH--lKofqHM

Output: https://www.hostever.com/blackfriday/

So it will delete the fbclid=

Input: https://www.hostever.com/?s=blogger
Output: https://www.hostever.com/?s=blogger
No need to change other parameters except **fbclid=**

I( need to delete only fbclid= this one from the URL.

Now I am using this, but the problem is with many parameters.

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{QUERY_STRING} !=""
 RewriteCond %{QUERY_STRING} !^p=.*
 RewriteCond %{QUERY_STRING} !^action=.*
 RewriteCond %{QUERY_STRING} !^s=.*
 RewriteCond %{REQUEST_URI} !^/wp-admin.*
 RewriteRule ^(.*)$ /$1? [R=301,L]
</IfModule>

Please help me, How can I delete a specific parameter from the URL with .htaccess?

Body:
I think Stephen had the right idea.  But for what it's worth, I only needed one rule to remove three types of trackers:

<IfModule mod_rewrite.c>
RewriteEngine On
  RewriteCond %{QUERY_STRING} ^(.*)(fbclid|gclid|utm_)[^\&]*\&(.*)$
  RewriteRule ^(.*)$ /$1?%1%3 [R=301,L]
</IfModule>

I needed this for a Wordpress blog, because when Wordpress tried to process parameters, the bogus ones caused a 404.  (Even when the URI was to a non-Wordpress static page on the site!)

The first set of parentheses matches everything before either of the three bad guys.  The third matches everything after the &.  The condition then puts the first and third together.  Stephen's comment about it depending on the & being present is correct—it does not remove the fbclid! (unless followed by an ampersand).  And yet, for reasons I don't understand, adding this rule made Wordpress stop saying 404 on links from Facebook.

However, my rule will not work if fbclid is in the URI outside of the parameters.  For example, any page on a domain named fbclid-sucks.com  :-)


问:
React Router V6 Not rendering pages
I am trying to get my routes working from my nav bar but no pages get rendered. My follow is as follows:

App.tsx:

```<code>  <div>
    <Routes>
      <Route path={login} element={<LoginPage />} />
    </Routes>
    <Routes>
      <Route path='/' element={<Dashboard />}/>
    </Routes>
  </div>
</code>```

Dashboard.tsx:

```<code>export default function Dashboard() {

  const mainPanel = React.createRef();

  const getRoutes = (routes: any) => {
    return routes.map((prop: any, key: number) => {
      if (prop.collapse) {
        return getRoutes(prop.views);
      }

      if (prop.layout) {
        console.log(prop.component)
        console.log(key)
        return (
          <Route
            path={prop.layout + prop.path}
            element={prop.component}
            key={key}
          />
        );
      } else {
        return null;
      }
    });
  };

  return (
    <div className="wrapper">
      <Sidebar activeColor={"danger"} protectedRoutes={ProtectedRoutes} LoggedInUser='Test' AccountRoutes={AccountRoute} />
      <div className="main-panel" ref={mainPanel as React.RefObject<HTMLDivElement>}>
        <TopNavbar />
        <Routes>
          {getRoutes(ProtectedRoutes)}
        </Routes>
      </div>
      <Outlet />
    </div>
  );
}
</code>```

and my Routes.ts:

```<code>export const ProtectedRoutes : ProtectedRoute[] = [
    {
        path: "dashboard",
        name: "Dashboard",
        icon: "nc-icon nc-paper",
        component: DashboardPage,
        layout: "/",
    },
]
</code>```

The follow was working but for some reason I am getting redirected to a blank page and in my console it says "No Routes Matched Location /dashboard"

Even without the Nav Bar if I go to the URL directly, it still does not work.

答:
In react-router-dom v6 all paths are always exactly matched. A trailing "*" wildcard character is used to allow path matching of nested routes. <Route path='/' element={<Dashboard />}/> should be <Route path='/*' element={<Dashboard />}/> if you want it to match and render nested route components. Same for any nested routes that render yet more nested routes.

Example:

```<code><div>
  <Routes>
    <Route path={login} element={<LoginPage />} />
    <Route path='/*' element={<Dashboard />}/>
  </Routes>
</div>
</code>```

Title: React Router V6 Not rendering pages

Body:
I am trying to get my routes working from my nav bar but no pages get rendered. My follow is as follows:

App.tsx:

    <Routes>
      <Route path={login} element={<LoginPage />} />
    </Routes>
    <Routes>
      <Route path='/' element={<Dashboard />}/>
    </Routes>

Dashboard.tsx:

export default function Dashboard() {

  const mainPanel = React.createRef();

  const getRoutes = (routes: any) => {
    return routes.map((prop: any, key: number) => {
      if (prop.collapse) {
        return getRoutes(prop.views);
      }

      if (prop.layout) {
        console.log(prop.component)
        console.log(key)
        return (
          <Route
            path={prop.layout + prop.path}
            element={prop.component}
            key={key}
          />
        );
      } else {
        return null;
      }
    });
  };

  return (

      <Sidebar activeColor={"danger"} protectedRoutes={ProtectedRoutes} LoggedInUser='Test' AccountRoutes={AccountRoute} />
      <div className="main-panel" ref={mainPanel as React.RefObject<HTMLDivElement>}>
        <TopNavbar />
        <Routes>
          {getRoutes(ProtectedRoutes)}
        </Routes>

      <Outlet />

  );
}

and my Routes.ts:

export const ProtectedRoutes : ProtectedRoute[] = [
    {
        path: "dashboard",
        name: "Dashboard",
        icon: "nc-icon nc-paper",
        component: DashboardPage,
        layout: "/",
    },
]

The follow was working but for some reason I am getting redirected to a blank page and in my console it says "No Routes Matched Location /dashboard"

Even without the Nav Bar if I go to the URL directly, it still does not work.

Body:
In react-router-dom v6 all paths are always exactly matched. A trailing "*" wildcard character is used to allow path matching of nested routes. <Route path='/' element={<Dashboard />}/> should be <Route path='/*' element={<Dashboard />}/> if you want it to match and render nested route components. Same for any nested routes that render yet more nested routes.

Example:

<div>
  <Routes>
    <Route path={login} element={<LoginPage />} />
    <Route path='/*' element={<Dashboard />}/>
  </Routes>
</div>


问:
Oracle Cloud Infrastructure: How do you specify an Availability-domain in a CLI call to create an instance?
I have tried all ways to specify the availability domain but keep getting the same error:

```<code>"code": "InvalidParameter",
"message": "AvailabilityDomain could not be inferred from the Request.
</code>```

I have tried Ucom:AD-1 Ucom:Sanjose-AD-1 ... all the way to the string that is returned with the oci iam availability-domain list command, which in my case was:
"ocid1.availabilitydomain.oc1..aaaaaaaavi2wyd6rjjffu5nzgb3gjq4thy46k7sgw5ibh7mu5sq5fyie6t5a"

I have tried with and without double quotes around the strings. I am completely lost. Please help.

[UPDATE]

Changing the CLI command to say this:

prasanna@prasanna:~/oci$ oci compute instance launch --availability-domain ZbTG:US-SANJOSE-1-AD-1 -c ocid1.tenancy.oc1..aaaaaaaa4ykdamkrakpivgazyoc7a2gnykwyaf2e56xohzfejag4mfr3idva --shape VM.Standard.E2.1.Micro --subnet-id subnet-20220121-1006 --ssh-authorized-keys-file authkeys --user-data-file ORTest.sh --image-id Oracle-Linux-7.9-2021.12.08-0

gives a different error: 404: "code": "NotAuthorizedOrNotFound",
"message": "Authorization failed or requested resource not found..

It does not say what failed.  So obviously it looks like the availability-domain needs to be specified the way I have it in the last attempt.

答:
Using the CLI, I would recommend using the AD list command to get the exact specification for the availability domain you want.

oci iam availability-domain list

{
  "data": [
    {
      "compartment-id": "ocid1.compartment.oc1..aaaaaaaa[omitted]mlkq",
      "id": "ocid1.availabilitydomain.oc1..aaaaaaaac7[omitted]f7a",
      "name": "Tdhb:PHX-AD-1"
    },
    {
      "compartment-id": "ocid1.compartment.oc1..aaaaaaaa3fg[omitted]lkq",
      "id": "ocid1.availabilitydomain.oc1..aaaaaaaakemzo4y[omitted]ez3j2hbq",
      "name": "Tdhb:PHX-AD-2"
    },
    {
      "compartment-id": "ocid1.compartment.oc1..aaaaaaaa3fgsh55xv[omitted]lkq",
      "id": "ocid1.availabilitydomain.oc1..aaaaa[omitted]t3mbrlq",
      "name": "Tdhb:PHX-AD-3"
    }
  ]
}
```

Body:
I have tried all ways to specify the availability domain but keep getting the same error:

"code": "InvalidParameter",
"message": "AvailabilityDomain could not be inferred from the Request.

I have tried Ucom:AD-1 Ucom:Sanjose-AD-1 ... all the way to the string that is returned with the oci iam availability-domain list command, which in my case was:
"ocid1.availabilitydomain.oc1..aaaaaaaavi2wyd6rjjffu5nzgb3gjq4thy46k7sgw5ibh7mu5sq5fyie6t5a"

I have tried with and without double quotes around the strings. I am completely lost. Please help.

[UPDATE]

Changing the CLI command to say this:

prasanna@prasanna:~/oci$ oci compute instance launch --availability-domain ZbTG:US-SANJOSE-1-AD-1 -c ocid1.tenancy.oc1..aaaaaaaa4ykdamkrakpivgazyoc7a2gnykwyaf2e56xohzfejag4mfr3idva --shape VM.Standard.E2.1.Micro --subnet-id subnet-20220121-1006 --ssh-authorized-keys-file authkeys --user-data-file ORTest.sh --image-id Oracle-Linux-7.9-2021.12.08-0

gives a different error: 404: "code": "NotAuthorizedOrNotFound",
"message": "Authorization failed or requested resource not found..

It does not say what failed.  So obviously it looks like the availability-domain needs to be specified the way I have it in the last attempt.


问:
Node.js: Python not found exception due to node-sass and node-gyp
Suddenly in one of my jenkins environment build has started failing, while in local machine it seems to be working fine as i have python installed,

From the logs i was able to detect that the problem is with internal dependency that is node-gyp v3.5.0 from node-sass v3.8.0 when i researched by visiting this about node-gyp and found the prerequisite that Python needs to be installed.

So my question is that what version of node-sass can i install to bypass this or is there a better solution as my build was running fine till this morning on the same environment.

Node v5.10.1

ERROR LOG

```<code>gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python2 { [Error: not found: python2] code: 'ENOENT' }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python { [Error: not found: python] code: 'ENOENT' }
gyp verb could not find "python". checking python launcher
gyp verb could not find "python". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at Object.failNoPython (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:454:19)
gyp ERR! stack     at Object.<anonymous> (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:480:16)
gyp ERR! stack     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:82:15)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files (x86)\\Jenkins\\jobs\\NdbSite-hot-fix-Manual-PreBuild\\workspace\\src\\NdbSite.UI\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-sass
gyp ERR! node -v v5.10.1
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok
Build failed
</code>```

Any thoughts are much appreciated, Thanks.

答:
I'm on a Windows 11 machine, and to fix it I downloaded python27 myself, using this link: https://www.python.org/download/releases/2.7/.

And after installed I ran this command:

```<code>npm config set python c:\python27\python.exe
</code>```

Body:
Suddenly in one of my jenkins environment build has started failing, while in local machine it seems to be working fine as i have python installed,

From the logs i was able to detect that the problem is with internal dependency that is node-gyp v3.5.0 from node-sass v3.8.0 when i researched by visiting this about node-gyp and found the prerequisite that Python needs to be installed.

So my question is that what version of node-sass can i install to bypass this or is there a better solution as my build was running fine till this morning on the same environment.

Node v5.10.1

ERROR LOG

gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python2 { [Error: not found: python2] code: 'ENOENT' }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\index.js:44:5
gyp verb `which` failed     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\isexe\windows.js:29:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:82:15)
gyp verb `which` failed  python { [Error: not found: python] code: 'ENOENT' }
gyp verb could not find "python". checking python launcher
gyp verb could not find "python". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at Object.failNoPython (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:454:19)
gyp ERR! stack     at Object.<anonymous> (C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-gyp\lib\configure.js:480:16)
gyp ERR! stack     at C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:82:15)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files (x86)\\Jenkins\\jobs\\NdbSite-hot-fix-Manual-PreBuild\\workspace\\src\\NdbSite.UI\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Program Files (x86)\Jenkins\jobs\NdbSite-hot-fix-Manual-PreBuild\workspace\src\NdbSite.UI\node_modules\node-sass
gyp ERR! node -v v5.10.1
gyp ERR! node-gyp -v v3.5.0
gyp ERR! not ok
Build failed

Any thoughts are much appreciated, Thanks.

Body:
I'm on a Windows 11 machine, and to fix it I downloaded python27 myself, using this link: https://www.python.org/download/releases/2.7/.

And after installed I ran this command:

npm config set python c:\python27\python.exe


问:
Query to check configuration properties of running QuestDB instance
I was wondering if there is a way to query QuestDB for its configuration properties through SQL. I have noticed meta functions to see tables and table columns.</p>

答: Querying config variables is not currently supported in the open source version</p>


问:
Android Check Application Status
I have a question about Android application status. I want to know that am I able to check whether application is alive or dead, visible or on background. I need to make a decision according to application status in my broadcast receiver.

Thanks in advance..

答: You determine if your "application" is "alive" by seeing if the data you loaded in your "start up process" exists. If it does, use it. If it does not, run the "start up process".</p>

Title: Android Check Application Status


问:
Web scraping table data using beautiful soup
I am trying to learn web scraping in Python for a project using Beautiful Soup by doing the following:
Scraping Kansas City Chiefs active team player name with the college attended. This is the url used https://www.chiefs.com/team/players-roster/.

After compiling, I get an error saying "IndexError: list index out of range".

I don't know if my set classes are wrong. Help would be appreciated.

```<code>import requests
from bs4 import BeautifulSoup

url = "https://www.chiefs.com/team/players-roster/"

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')

roster_table = soup.find('table', class_ = 'd3-o-table d3-o-table--row-striping d3-o-table--detailed d3-o-table--sortable {sortlist: [[0,0]]}')

for person in roster_table.find_all('tbody'):
    rows = person.find_all('tr')
    for row in rows:
        player_name = row.find('td', class_='sorter-lastname selected"')
        player_university = row.find_all('td', class_='sorter-lastname selected')[7].text
        print(player_name,player_university)
</code>```

答:
I couldn't find a td with class sorter-lastname selected in the source code. You basically need the last td in each row, so this would do:

```<code>for person in roster_table.find_all('tbody'):
    rows = person.find_all('tr')
    for row in rows:
        player_name = row.find('td', class_='sorter-lastname selected"')
        player_university = row.find_all('td')[-1].text
</code>```

PS. scraping tables is extremely easy in pandas:

```<code>import pandas as pd

df = pd.read_html('https://www.chiefs.com/team/players-roster/')
df[0].to_cvs('output.csv')
</code>```

It may take a bit longer, but the output is impressive, for example the print(df[0]):

```<code>               Player     # Pos    HT   WT  Age Exp            College
0       Josh Pederson   NaN  TE   6-5  235   24   R   Louisiana-Monroe
1   Brandin Dandridge   NaN  WR  5-10  180   25   R   Missouri Western
2       Justin Watson   NaN  WR   6-3  215   25   4       Pennsylvania
3    Jonathan Woodard   NaN  DE   6-5  271   28   3   Central Arkansas
4     Andrew Billings   NaN  DT   6-1  311   26   5             Baylor
..                ...   ...  ..   ...  ...  ...  ..                ...
84   James Winchester  41.0  LS   6-3  242   32   7           Oklahoma
85       Travis Kelce  87.0  TE   6-5  256   32   9         Cincinnati
86        Marcus Kemp  85.0  WR   6-4  208   26   4             Hawaii
87        Chris Jones  95.0  DT   6-6  298   27   6  Mississippi State
88    Harrison Butker   7.0   K   6-4  196   26   5       Georgia Tech

[89 rows x 8 columns]
</code>```

Body:
I am trying to learn web scraping in Python for a project using Beautiful Soup by doing the following:
Scraping Kansas City Chiefs active team player name with the college attended. This is the url used https://www.chiefs.com/team/players-roster/.

After compiling, I get an error saying "IndexError: list index out of range".

I don't know if my set classes are wrong. Help would be appreciated.

import requests
from bs4 import BeautifulSoup

url = "https://www.chiefs.com/team/players-roster/"

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')

roster_table = soup.find('table', class_ = 'd3-o-table d3-o-table--row-striping d3-o-table--detailed d3-o-table--sortable {sortlist: [[0,0]]}')

for person in roster_table.find_all('tbody'):
    rows = person.find_all('tr')
    for row in rows:
        player_name = row.find('td', class_='sorter-lastname selected"')
        player_university = row.find_all('td', class_='sorter-lastname selected')[7].text
        print(player_name,player_university)

Body:
I couldn't find a td with class sorter-lastname selected in the source code. You basically need the last td in each row, so this would do:

for person in roster_table.find_all('tbody'):
    rows = person.find_all('tr')
    for row in rows:
        player_name = row.find('td', class_='sorter-lastname selected"')
        player_university = row.find_all('td')[-1].text

PS. scraping tables is extremely easy in pandas:

import pandas as pd

df = pd.read_html('https://www.chiefs.com/team/players-roster/')
df[0].to_cvs('output.csv')

It may take a bit longer, but the output is impressive, for example the print(df[0]):

               Player     # Pos    HT   WT  Age Exp            College
0       Josh Pederson   NaN  TE   6-5  235   24   R   Louisiana-Monroe
1   Brandin Dandridge   NaN  WR  5-10  180   25   R   Missouri Western
2       Justin Watson   NaN  WR   6-3  215   25   4       Pennsylvania
3    Jonathan Woodard   NaN  DE   6-5  271   28   3   Central Arkansas
4     Andrew Billings   NaN  DT   6-1  311   26   5             Baylor
..                ...   ...  ..   ...  ...  ...  ..                ...
84   James Winchester  41.0  LS   6-3  242   32   7           Oklahoma
85       Travis Kelce  87.0  TE   6-5  256   32   9         Cincinnati
86        Marcus Kemp  85.0  WR   6-4  208   26   4             Hawaii
87        Chris Jones  95.0  DT   6-6  298   27   6  Mississippi State
88    Harrison Butker   7.0   K   6-4  196   26   5       Georgia Tech

[89 rows x 8 columns]


问:
Can I use an array as metadata value?
I'm trying to create a product in Stripe (using Next.js + Node) with a metadata of the following format:

metadata: {categories: ['foo', 'bar']}

but it seems I can't workaround string-only values in metadata.

Creating a product in the stripe dashboard with brackets in the metadata value result in, when being retrieved:

categories: "['foo', 'bar']"

Trying to create with Node:

```<code>const new_product = await stripe.products.create({
      name: 'new product',
      metadata: {categories: ['foo', 'bar']}
})
</code>```

resulted in:

Error: Invalid value type: {:"0"=>"foo", :"1"=>"bar"} must be a string

This confirms that the value must be a string. The docs were kind of unclear as to the specific type allowance:

You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long.

But I suppose I'm stuck with string values in the metadata.

What is the best workaround for this?

I know I can loop through an object as long as its keys are indices, but I also will want more metadata keys and values. String delimination using split just sounds like a pain. I'm certain there are more ways to effectively use JS objects, but I'm trying to go as simple as possible, as non-developers will also want to make products that follow this archetype.

Thank you for any help.

EDIT: I ended up leaning into the object nature of metadata, using categories in this way, which worked fine for my products:

```<code>const new_product = await stripe.products.create({
      name: 'new product',
      metadata: {
          category: 'foo',
          categoryAlt: 'bar'
      }
})

</code>```

答:
Stripe stores this data as a single string and AFAIK there is no way around that.

However, when using a Stripe library like the one for Node.js, it does the conversion of the string into an object you can traverse.  I created a product with the same categories as the code you shared and was able to access the .categories property using dot notation.

const getProduct = async (id) => {
  console.log("Fetching product to evaluate metadata");
  const product = await stripe.products.retrieve(id)
  const meta = product.metadata
  // console.log(meta);
  console.log(meta.categories);
}

node test.js
Fetching product to evaluate metadata
["foo", "bar"]
```

Title: Can I use an array as metadata value?

Body:
I'm trying to create a product in Stripe (using Next.js + Node) with a metadata of the following format:

metadata: {categories: ['foo', 'bar']}

but it seems I can't workaround string-only values in metadata.

Creating a product in the stripe dashboard with brackets in the metadata value result in, when being retrieved:

categories: "['foo', 'bar']"

Trying to create with Node:

const new_product = await stripe.products.create({
      name: 'new product',
      metadata: {categories: ['foo', 'bar']}
})

resulted in:

Error: Invalid value type: {:"0"=>"foo", :"1"=>"bar"} must be a string

This confirms that the value must be a string. The docs were kind of unclear as to the specific type allowance:

You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long.

But I suppose I'm stuck with string values in the metadata.

What is the best workaround for this?

I know I can loop through an object as long as its keys are indices, but I also will want more metadata keys and values. String delimination using split just sounds like a pain. I'm certain there are more ways to effectively use JS objects, but I'm trying to go as simple as possible, as non-developers will also want to make products that follow this archetype.

Thank you for any help.

EDIT: I ended up leaning into the object nature of metadata, using categories in this way, which worked fine for my products:

const new_product = await stripe.products.create({
      name: 'new product',
      metadata: {
          category: 'foo',
          categoryAlt: 'bar'
      }
})


问:
Can't import PyAudio to PyCharm project
I can access it in the terminal but when I try to add it to my python project in PyCharm it won't let me
I have tried with both python 3.10 and 3.9

it also shows this when i ask for details on why it doesn't work

```<code>Collecting PyAudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Building wheels for collected packages: PyAudio
  Building wheel for PyAudio (setup.py): started
  Building wheel for PyAudio (setup.py): finished with status 'error'
  Running setup.py clean for PyAudio
Failed to build PyAudio
Installing collected packages: PyAudio
    Running setup.py install for PyAudio: started
    Running setup.py install for PyAudio: finished with status 'error'

  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Lenovo\AppData\Local\Temp\pip-wheel-qtpqe2of'
       cwd: C:\Users\Lenovo\AppData\Local\Temp\pip-install-bl692lay\pyaudio_da329c95486d497b95d33a9225fb1595\
  Complete output (11 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.10
  copying src\pyaudio.py -> build\lib.win-amd64-3.10
  warning: build_py: byte-compiling is disabled, skipping.

  running build_ext
  building '_portaudio' extension
  error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------
  ERROR: Failed building wheel for PyAudio
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Lenovo\AppData\Local\Temp\pip-record-p3n5y632\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\include\site\python3.10\PyAudio'
         cwd: C:\Users\Lenovo\AppData\Local\Temp\pip-install-bl692lay\pyaudio_da329c95486d497b95d33a9225fb1595\
    Complete output (11 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.10
    copying src\pyaudio.py -> build\lib.win-amd64-3.10
    warning: build_py: byte-compiling is disabled, skipping.

    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Lenovo\AppData\Local\Temp\pip-record-p3n5y632\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\include\site\python3.10\PyAudio' Check the logs for full command output.
WARNING: You are using pip version 21.1.2; however, version 22.0.3 is available.
You should consider upgrading via the 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe -m pip install --upgrade pip' command.
</code>```

edit:
now it says:

```<code>Command errored out with exit status 1
</code>```

rather then the warning about c++ visual tools

答: The error indicates error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/. You should install this to proceed.

Title: Can't import PyAudio to PyCharm project

Body:
I can access it in the terminal but when I try to add it to my python project in PyCharm it won't let me
I have tried with both python 3.10 and 3.9

it also shows this when i ask for details on why it doesn't work

Collecting PyAudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Building wheels for collected packages: PyAudio
  Building wheel for PyAudio (setup.py): started
  Building wheel for PyAudio (setup.py): finished with status 'error'
  Running setup.py clean for PyAudio
Failed to build PyAudio
Installing collected packages: PyAudio
    Running setup.py install for PyAudio: started
    Running setup.py install for PyAudio: finished with status 'error'

  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Lenovo\AppData\Local\Temp\pip-wheel-qtpqe2of'
       cwd: C:\Users\Lenovo\AppData\Local\Temp\pip-install-bl692lay\pyaudio_da329c95486d497b95d33a9225fb1595\
  Complete output (11 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.10
  copying src\pyaudio.py -> build\lib.win-amd64-3.10
  warning: build_py: byte-compiling is disabled, skipping.

  running build_ext
  building '_portaudio' extension
  error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
  ----------------------------------------
  ERROR: Failed building wheel for PyAudio
    ERROR: Command errored out with exit status 1:
     command: 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Lenovo\AppData\Local\Temp\pip-record-p3n5y632\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\include\site\python3.10\PyAudio'
         cwd: C:\Users\Lenovo\AppData\Local\Temp\pip-install-bl692lay\pyaudio_da329c95486d497b95d33a9225fb1595\
    Complete output (11 lines):
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.10
    copying src\pyaudio.py -> build\lib.win-amd64-3.10
    warning: build_py: byte-compiling is disabled, skipping.

    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"'; __file__='"'"'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\pip-install-bl692lay\\pyaudio_da329c95486d497b95d33a9225fb1595\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Lenovo\AppData\Local\Temp\pip-record-p3n5y632\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\include\site\python3.10\PyAudio' Check the logs for full command output.
WARNING: You are using pip version 21.1.2; however, version 22.0.3 is available.
You should consider upgrading via the 'C:\Users\Lenovo\PycharmProjects\Alexa2\venv\Scripts\python.exe -m pip install --upgrade pip' command.

edit:
now it says:

Command errored out with exit status 1

rather then the warning about c++ visual tools


问:
How do you sort an Observable<Item[]> in Angular 6 with rxjs 6?
I just want to sort data on an observable of my class type 'Category'.  So Observable < Category[] > I want to sort.

So I upgraded to Angular6 and rxjs6 with it.  One issue that is probably simple Typescript that I do know is how do I just do a 'sort' operation like:

```<code>sort((x,y) => x.description < y.description ? -1 : 1)
</code>```

Inside of the new Angular6?  I used to do this in 5

```<code>var response = this.http.get<Category[]>(this.endpoint);
        .map((result: Response) => this.alphabetize(result));

alphabetize = (result: Response) => this.Categories = result.json()
.sort((x,y) => x.description < y.description ? -1 : 1)
</code>```

And it worked fine.  Now in the HttpCLIENTModule and HttpClient that Angular wants you to use it is simpler:

```<code>var data = this.http.get<Category[]>(this.endpoint);
</code>```

I just put the magic <(object)> before my endpoint and it does it for me.  Cool.  But I am not seeing how you get inside the object easily to sort from it with Source, Pipe, from, of.  I know it is probably something simple I just don't know the syntax for.

答:
For angular12 when I try this solution it give me this error.

```<code>TypeError: Cannot read property ‘sort’ of undefined TypeError: Cannot read property ‘sort’ of undefined
</code>```

To fix this error. I used pipe

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortByDate'
})
export class SortByDatePipe implements PipeTransform {

  transform(value: any, ...args: any[]): any {
    value = [...value]; // fixed to second error

    return value.sort((a, b) => new Date(b.date1).getTime() - new Date(a.date1).getTime());

  }

}
</code>```

At this time it gives this.

```<code>TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’ Error ?
</code>```

I already explain that in code(above)  but you can check here if it doesnt solve the error.

Here is the html code

```<code><div *ngFor="let item of data$ | async | sortByDate">
//your code goes here
</div>
</code>```

Body:
I just want to sort data on an observable of my class type 'Category'.  So Observable < Category[] > I want to sort.

So I upgraded to Angular6 and rxjs6 with it.  One issue that is probably simple Typescript that I do know is how do I just do a 'sort' operation like:

sort((x,y) => x.description < y.description ? -1 : 1)

Inside of the new Angular6?  I used to do this in 5

var response = this.http.get<Category[]>(this.endpoint);
        .map((result: Response) => this.alphabetize(result));

alphabetize = (result: Response) => this.Categories = result.json()
.sort((x,y) => x.description < y.description ? -1 : 1)

And it worked fine.  Now in the HttpCLIENTModule and HttpClient that Angular wants you to use it is simpler:

var data = this.http.get<Category[]>(this.endpoint);

I just put the magic <(object)> before my endpoint and it does it for me.  Cool.  But I am not seeing how you get inside the object easily to sort from it with Source, Pipe, from, of.  I know it is probably something simple I just don't know the syntax for.

Body:
For angular12 when I try this solution it give me this error.

TypeError: Cannot read property ‘sort’ of undefined TypeError: Cannot read property ‘sort’ of undefined

To fix this error. I used pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sortByDate'
})
export class SortByDatePipe implements PipeTransform {

  transform(value: any, ...args: any[]): any {
    value = [...value]; // fixed to second error

    return value.sort((a, b) => new Date(b.date1).getTime() - new Date(a.date1).getTime());

  }

}

At this time it gives this.

TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’ Error ?

I already explain that in code(above)  but you can check here if it doesnt solve the error.

Here is the html code

<div *ngFor="let item of data$ | async | sortByDate">
//your code goes here
</div>


问:
Flutter ReorderableListView -- resizing item on drag and adjusting layout of other items accordingly
I have a ReorderableListView, and I'm using proxyDecorator to detect when an item starts being dragged and then adjust its height, and the height of the underlying Widget which is actually present in ListView (as I assume the widget returned by proxyDecorator is just used to show what is being dragged.) The issue is that the 'space' in the list where the dragged item was, or is being moved to, remains its original size, rather than reflecting the new size of the widget. Once the dragged item is placed, if I disable the code to return it to it's original size, the rest of the listview bunches up to reflect the new size. But I want this to happen as soon as the drag begins. Is this possible? I have tried using a setState call in the proxyDecorator, but this causes an error with triggering a rebuild during a rebuild.

答:
I'm not sure what you meant by proxy decorator, but if you just want to resize an item when it's being dragged, it can be done.

Obviously this is just a quick demo, lots of edge cases are not tested. But if you are interested, here's the full source code used in the above demo:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final colors = [
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.orange,
    Colors.purple,
    Colors.pink,
    Colors.cyan
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ReorderableListView'),
      ),
      body: ReorderableListView(
        children: colors
            .map((color) => Box(
                  key: ValueKey(color),
                  color: color,
                ))
            .toList(),
        onReorder: (int oldIndex, int newIndex) {
          if (newIndex > oldIndex) newIndex--;
          setState(() {
            final color = colors.removeAt(oldIndex);
            colors.insert(newIndex, color);
          });
        },
      ),
    );
  }
}

class Box extends StatefulWidget {
  final Color color;

  const Box({Key? key, required this.color}) : super(key: key);

  @override
  _BoxState createState() => _BoxState();
}

class _BoxState extends State<Box> {
  bool _big = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) => setState(() => _big = true),
      onTapCancel: () => setState(() => _big = false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 200),
        height: _big ? 100 : 50,
        margin: EdgeInsets.all(4.0),
        color: widget.color,
      ),
    );
  }
}
</code>```

Body:
I'm not sure what you meant by proxy decorator, but if you just want to resize an item when it's being dragged, it can be done.

Obviously this is just a quick demo, lots of edge cases are not tested. But if you are interested, here's the full source code used in the above demo:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final colors = [
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.orange,
    Colors.purple,
    Colors.pink,
    Colors.cyan
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ReorderableListView'),
      ),
      body: ReorderableListView(
        children: colors
            .map((color) => Box(
                  key: ValueKey(color),
                  color: color,
                ))
            .toList(),
        onReorder: (int oldIndex, int newIndex) {
          if (newIndex > oldIndex) newIndex--;
          setState(() {
            final color = colors.removeAt(oldIndex);
            colors.insert(newIndex, color);
          });
        },
      ),
    );
  }
}

class Box extends StatefulWidget {
  final Color color;

  const Box({Key? key, required this.color}) : super(key: key);

  @override
  _BoxState createState() => _BoxState();
}

class _BoxState extends State<Box> {
  bool _big = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) => setState(() => _big = true),
      onTapCancel: () => setState(() => _big = false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 200),
        height: _big ? 100 : 50,
        margin: EdgeInsets.all(4.0),
        color: widget.color,
      ),
    );
  }
}


问:
Possible to do join queries in Android (for example to get contacts information)?

Is it possible to make join queries and then iterate through the results ?
How ? all in the same Cursor ?

How to return the results of such a query ?

For example, how should I proceed to get the name, phone number(s)
and email(s) of a contact in one shot?

Body: Try CursorJoiner. http://developer.android.com/reference/android/database/CursorJoiner.html


问:
Create a program to print employee details using structures
The code is not printing for name and salary of employee, also not asking for the salary of the employee, kindly mark the wrong items in the code.</p>
```<code>#include<stdio.h>
#include<string.h>

struct employee{
    int code;
    char name[20];
    int salary;
};

void printEmployeeDetails(struct employee emp);

void printEmployeeDetails(struct employee emp){
    printf("Employee CODE is: %d\n" ,emp.code);
    printf("Employee NAME is: %s\n" ,emp.name);
    printf("Employee SALARy is: %d\n",emp.salary);

}

int main(){
    struct employee e1;
    printf("Enter your CODE\n");
    scanf("%d",&e1.code);

    printf("Enter your NAME\n");
    scanf("%d",&e1.name);

    printf("Enter your SALARY\n");
    scanf("%d",&e1.salary);

    printEmployeeDetails(e1);

    //printf("The Employee Details Are: \n",printEmployeeDetails(e1));
    return 0;
}
</code>```

答:
I take that this is a C++ question. You might have turned off compiler warning when compile; as from the compiler warnings (I used onlinegdb compiler), there are a couple issues with your code

First

printf("Enter your NAME\n");
scanf("%d",&e1.name);
```
<p>You are expecting <code>e1.name</code> to be a string here, so use <code>"%s"</code> instead of <code>"%d"</code></p>
<p>Seconly, when using <code>scanf</code> for a <code>char*</code> variable, you only need to use <code>scanf("%s", e1.name)</code> (no need for the <code>&</code>)</p>
<p>For more details, read here: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)’</p>
<p>Final</p>
<pre class="lang-cpp prettyprint-override"><code>printf("Enter your NAME\n");
scanf("%s",e1.name);
</code>```

Body:
The code is not printing for name and salary of employee, also not asking for the salary of the employee, kindly mark the wrong items in the code.

#include<stdio.h>
#include<string.h>

struct employee{
    int code;
    char name[20];
    int salary;
};

void printEmployeeDetails(struct employee emp);

void printEmployeeDetails(struct employee emp){
    printf("Employee CODE is: %d\n" ,emp.code);
    printf("Employee NAME is: %s\n" ,emp.name);
    printf("Employee SALARy is: %d\n",emp.salary);

}

int main(){
    struct employee e1;
    printf("Enter your CODE\n");
    scanf("%d",&e1.code);

    printf("Enter your NAME\n");
    scanf("%d",&e1.name);

    printf("Enter your SALARY\n");
    scanf("%d",&e1.salary);

    printEmployeeDetails(e1);

    //printf("The Employee Details Are: \n",printEmployeeDetails(e1));
    return 0;
}

Body:
I take that this is a C++ question. You might have turned off compiler warning when compile; as from the compiler warnings (I used onlinegdb compiler), there are a couple issues with your code

First

printf("Enter your NAME\n");
scanf("%d",&e1.name);

You are expecting e1.name to be a string here, so use "%s" instead of "%d"

Seconly, when using scanf for a char* variable, you only need to use scanf("%s", e1.name) (no need for the &)

For more details, read here: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char (*)’

Final

printf("Enter your NAME\n");
scanf("%s",e1.name);


答:
You can use a boolean variable that tells is searching or not.

bool isSearching = false;

appBar: AppBar(
    title: isSearching ? TextField(
          style: TextStyle(color: Colors.white),
          decoration: InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
          controller: searchController,
)

     : Text(
      "Home",
      style: TextStyle(
        fontSize: 16.0, /*fontWeight: FontWeight.bold*/
      ),
    ),
    centerTitle: true,

 //search icon
 actions: [
  IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      setState((){
        isSearching = true;
      });
    },
  ),
],

),
```

Title: How can i change app bar text to TextField in flutter with a icon buton?

Body:
I'm making an app to search courses on firebase. The app bar shows a text: "Home", and it has a search button at the rigth side of the screen:

I want to hide that "Home" text from de app bar at moment to click the search button, and show the field to type the query.

this is my code, i dont know how to implement that.

appBar: AppBar(
    title: Text(
      "Home",
      style: TextStyle(
        fontSize: 16.0, /*fontWeight: FontWeight.bold*/
      ),
    ),
    centerTitle: true,

 //search icon
 actions: [
  IconButton(
    icon: Icon(Icons.search),
    onPressed: () {
      //i want to change the text of the app bar:"Home" to a TextField to type
      AppBar(
        title: TextField(
          style: TextStyle(color: Colors.white),
          decoration: InputDecoration(
              hintText: 'Search Courses',
              hintStyle: TextStyle(color: Colors.white)),
          controller: searchController,
        ),
      );
    },
  ),
],

),


问:
File upload results in file size 0 and error code 0
I'm trying to upload an image to a php script. I have a, non-persistent, bug that results in some of the images uploaded has a file size of 0. I have tried to print the _FILES array to my log file, and it shows the error code being 0, which should be ok.

These lines:

```<code>foreach($_FILES['image_file'] as $key => $val){
      error_log(date('j/n/o H:i:s')." ". $key ." => ".$val. "\n", 3,$log_path);
    }
</code>```

Give me these in the log file:

3/10/2012 12:12:54 name => 59175248636.jpg

3/10/2012 12:12:54 type => image/jpeg

3/10/2012 12:12:54 tmp_name => C:\WINDOWS\Temp\php411F.tmp

3/10/2012 12:12:54 error => 0

3/10/2012 12:12:54 size => 0

As can be read from the log file, this script runs on a Windows machine, of which I have limited knowledge. I have already changed the post_max_size to 10M, as well as upload_max_size to 10M in the php.ini.

I am flabbergasted about this issue. When I test from my own devices, it works fine, but for some reason, when my testers try it out, it fails.

答: Since I run into this from time to time, I guess I'll just post one reason this could happen: Size and error 0 can occur if you try drag and dropping a file from a Windows Explorer view of a zipped file (double click a zipped file and it opens up just like a folder) to your uploader. I use DropzoneJS a lot and by default, it processes these files immediately and pushes it to my server, which ends up seeing a 0 bytes file with no file upload errors. So if your users are doing the above, that could be the reason why you end up with such files.</p>

Body:
I'm trying to upload an image to a php script. I have a, non-persistent, bug that results in some of the images uploaded has a file size of 0. I have tried to print the _FILES array to my log file, and it shows the error code being 0, which should be ok.

These lines:

foreach($_FILES['image_file'] as $key => $val){
      error_log(date('j/n/o H:i:s')." ". $key ." => ".$val. "\n", 3,$log_path);
    }

Give me these in the log file:

3/10/2012 12:12:54 name => 59175248636.jpg

3/10/2012 12:12:54 type => image/jpeg

3/10/2012 12:12:54 tmp_name => C:\WINDOWS\Temp\php411F.tmp

3/10/2012 12:12:54 error => 0

3/10/2012 12:12:54 size => 0

As can be read from the log file, this script runs on a Windows machine, of which I have limited knowledge. I have already changed the post_max_size to 10M, as well as upload_max_size to 10M in the php.ini.

I am flabbergasted about this issue. When I test from my own devices, it works fine, but for some reason, when my testers try it out, it fails.


问:
Rmd file won't output file (LaTeX formatting error?)
I am taking an intro to bayesian statistics class this semester and I decided to take notes with Rmd this last class, not the best idea. After class when I was trying to convert to a pdf, I received the following error messages.

```<code>  ! Missing { inserted.
<to be read again>
                   \mathop
l.204 ...(data|\lambda^q)\pi(\lambda^q)d\lambda^q}
                                                  \)
</code>```

I have no idea what the problem is in the coding that I have done or what this error is trying to tell me what to do. Here is my Rmd code that is relevant to the problem (the rest of my rmd should be good):

```<code>## Finding the Model
- Remember, $P(A\cap B)=P(A)P(B)$ and $P(A\cap B|C)=P(A|C)P(B|C)$
- A = $(X_1=x_1)$, $B=(X_2=x_2)$, $C=(\Lambda=\lambda)$
- $P[(X_1=x_1)\cap(X_2=x_2)|\lambda]=P[(X_1=x_1|\lambda]P[(X_2=x_2)|\lambda]$, which are the product of 2 poisson pmf's.
- This can then be extended to all n observations, or all n RV's.
- iid = "independent and identically distributed as"
### For likelihood:
- shorthand: $X_i|\lambda ~-^{iid}~Pois(\lambda)$
- distribution: $f(x_1,...,x_n|\lambda)=f(data|\lambda)=\Pi_{i=1}^nf(x_i|\lambda)$
- always true for our likelihood of the data as long as it's a random sample
- poisson: $\Pi_{i=1}^n\frac{e^{-\lambda}\lambda^{x_i}}{x_i!}~=~e^{-n\lambda}\lambda^{\sum_{i=1}^nx_i}(\Pi_{i=1}^n\frac{1}{x_i!})$
### For prior:
- $\lambda~-~Gam(\gamma,\phi)$
- $\pi(\lambda)~=~\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda}$
### For Posterior:
- $\pi(\lambda|data)~=~\frac{f(data|\lambda)\pi(\lambda)}{\int_0^\inf(data|\lambda^q)\pi(\lambda^q)d\lambda^q}$
- The denominator is the normalizing constant so it's just a number. For this example we'll make the normalizing constant $\frac{1}{c}$, $\sum_{i=1}^n\frac{1}{x_i!}$ = a (constant), and $\frac{\phi^\gamma}{\Gamma(\phi)}$ = b (constant)
- So, $cf(data|\lambda)\pi(\lambda)~=~c(e^{-n\lambda}\lambda^{\sum_{i=1}^n\frac{1}{x_i!}})(\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda})~=~cab*e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$
- Our posterior kernel $e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$ has new parameters $\gamma^q\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$
- Our constants cab = $\frac{(\phi^q)^{\gamma^q}}{\Gamma(\phi^q)}$
- Shorthand: $\lambda|data~-~Gam(\gamma^q,\phi^q)\mbox{, where}~\gamma^q=\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$
</code>```

Yeah, I realize it would be much easier to write this stuff down, but my laptop pen is dead and I don't own any notebooks, sooo this is my best option right now. I realize it is a ton of stuff, but, any help would be much appreciated especially help with understanding this error message and what it is trying to tell me to do.

If needed, here are my other LaTeX notations that I've used in the document.

```<code>- So, because all objects are randomly selected, we can consider them independent of each other.
- Thus, we can distinguish all n RV's as $X_i$ = count of the $i^{th}$ randomly selected object from the pop.
- $X_1...X_n$ represents the n RV's and $x_1...x_n$ represents the observed n values from "data".
</code>```

答:
It is a really bad habit to write exponents or subscripts without {...} around them, you risk omitting them when necessary.

```<code>---
output:
  pdf_document:
    keep_tex: true
---

## Finding the Model
- Remember, $P(A\cap B)=P(A)P(B)$ and $P(A\cap B|C)=P(A|C)P(B|C)$
- A = $(X_1=x_1)$, $B=(X_2=x_2)$, $C=(\Lambda=\lambda)$
- $P[(X_1=x_1)\cap(X_2=x_2)|\lambda]=P[(X_1=x_1|\lambda]P[(X_2=x_2)|\lambda]$, which are the product of 2 poisson pmf's.
- This can then be extended to all n observations, or all n RV's.
- iid = "independent and identically distributed as"
### For likelihood:
- shorthand: $X_i|\lambda ~-^{iid}~Pois(\lambda)$
- distribution: $f(x_1,...,x_n|\lambda)=f(data|\lambda)=\Pi_{i=1}^nf(x_i|\lambda)$
- always true for our likelihood of the data as long as it's a random sample
- poisson: $\Pi_{i=1}^n\frac{e^{-\lambda}\lambda^{x_i}}{x_i!}~=~e^{-n\lambda}\lambda^{\sum_{i=1}^nx_i}(\Pi_{i=1}^n\frac{1}{x_i!})$
### For prior:
- $\lambda~-~Gam(\gamma,\phi)$
- $\pi(\lambda)~=~\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda}$
### For Posterior:
- $\pi(\lambda|data)~=~\frac{f(data|\lambda)\pi(\lambda)}{\int_{0}^{\inf}(data|\lambda^q)\pi(\lambda^q)d\lambda^q}$
- The denominator is the normalizing constant so it's just a number. For this example we'll make the normalizing constant $\frac{1}{c}$, $\sum_{i=1}^n\frac{1}{x_i!}$ = a (constant), and $\frac{\phi^\gamma}{\Gamma(\phi)}$ = b (constant)
- So, $cf(data|\lambda)\pi(\lambda)~=~c(e^{-n\lambda}\lambda^{\sum_{i=1}^n\frac{1}{x_i!}})(\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda})~=~cab*e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$
- Our posterior kernel $e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$ has new parameters $\gamma^q\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$
- Our constants cab = $\frac{(\phi^q)^{\gamma^q}}{\Gamma(\phi^q)}$
- Shorthand: $\lambda|data~-~Gam(\gamma^q,\phi^q)\mbox{, where}~\gamma^q=\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$
</code>```

You also shouldn't set multi-letter words like "data" or "Gam" in math mode. Use text font to get correct kerning.

Body:
I am taking an intro to bayesian statistics class this semester and I decided to take notes with Rmd this last class, not the best idea. After class when I was trying to convert to a pdf, I received the following error messages.

  ! Missing { inserted.
<to be read again>
                   \mathop
l.204 ...(data|\lambda^q)\pi(\lambda^q)d\lambda^q}
                                                  \)

I have no idea what the problem is in the coding that I have done or what this error is trying to tell me what to do. Here is my Rmd code that is relevant to the problem (the rest of my rmd should be good):

## Finding the Model
- Remember, $P(A\cap B)=P(A)P(B)$ and $P(A\cap B|C)=P(A|C)P(B|C)$
- A = $(X_1=x_1)$, $B=(X_2=x_2)$, $C=(\Lambda=\lambda)$
- $P[(X_1=x_1)\cap(X_2=x_2)|\lambda]=P[(X_1=x_1|\lambda]P[(X_2=x_2)|\lambda]$, which are the product of 2 poisson pmf's.
- This can then be extended to all n observations, or all n RV's.
- iid = "independent and identically distributed as"
### For likelihood:
- shorthand: $X_i|\lambda ~-^{iid}~Pois(\lambda)$
- distribution: $f(x_1,...,x_n|\lambda)=f(data|\lambda)=\Pi_{i=1}^nf(x_i|\lambda)$
- always true for our likelihood of the data as long as it's a random sample
- poisson: $\Pi_{i=1}^n\frac{e^{-\lambda}\lambda^{x_i}}{x_i!}~=~e^{-n\lambda}\lambda^{\sum_{i=1}^nx_i}(\Pi_{i=1}^n\frac{1}{x_i!})$
### For prior:
- $\lambda~-~Gam(\gamma,\phi)$
- $\pi(\lambda)~=~\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda}$
### For Posterior:
- $\pi(\lambda|data)~=~\frac{f(data|\lambda)\pi(\lambda)}{\int_0^\inf(data|\lambda^q)\pi(\lambda^q)d\lambda^q}$
- The denominator is the normalizing constant so it's just a number. For this example we'll make the normalizing constant $\frac{1}{c}$, $\sum_{i=1}^n\frac{1}{x_i!}$ = a (constant), and $\frac{\phi^\gamma}{\Gamma(\phi)}$ = b (constant)
- So, $cf(data|\lambda)\pi(\lambda)~=~c(e^{-n\lambda}\lambda^{\sum_{i=1}^n\frac{1}{x_i!}})(\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda})~=~cab*e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$
- Our posterior kernel $e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$ has new parameters $\gamma^q\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$
- Our constants cab = $\frac{(\phi^q)^{\gamma^q}}{\Gamma(\phi^q)}$
- Shorthand: $\lambda|data~-~Gam(\gamma^q,\phi^q)\mbox{, where}~\gamma^q=\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$

Yeah, I realize it would be much easier to write this stuff down, but my laptop pen is dead and I don't own any notebooks, sooo this is my best option right now. I realize it is a ton of stuff, but, any help would be much appreciated especially help with understanding this error message and what it is trying to tell me to do.

If needed, here are my other LaTeX notations that I've used in the document.

- So, because all objects are randomly selected, we can consider them independent of each other.
- Thus, we can distinguish all n RV's as $X_i$ = count of the $i^{th}$ randomly selected object from the pop.
- $X_1...X_n$ represents the n RV's and $x_1...x_n$ represents the observed n values from "data".

Body:
It is a really bad habit to write exponents or subscripts without {...} around them, you risk omitting them when necessary.

---
output:
  pdf_document:
    keep_tex: true
---

## Finding the Model
- Remember, $P(A\cap B)=P(A)P(B)$ and $P(A\cap B|C)=P(A|C)P(B|C)$
- A = $(X_1=x_1)$, $B=(X_2=x_2)$, $C=(\Lambda=\lambda)$
- $P[(X_1=x_1)\cap(X_2=x_2)|\lambda]=P[(X_1=x_1|\lambda]P[(X_2=x_2)|\lambda]$, which are the product of 2 poisson pmf's.
- This can then be extended to all n observations, or all n RV's.
- iid = "independent and identically distributed as"
### For likelihood:
- shorthand: $X_i|\lambda ~-^{iid}~Pois(\lambda)$
- distribution: $f(x_1,...,x_n|\lambda)=f(data|\lambda)=\Pi_{i=1}^nf(x_i|\lambda)$
- always true for our likelihood of the data as long as it's a random sample
- poisson: $\Pi_{i=1}^n\frac{e^{-\lambda}\lambda^{x_i}}{x_i!}~=~e^{-n\lambda}\lambda^{\sum_{i=1}^nx_i}(\Pi_{i=1}^n\frac{1}{x_i!})$
### For prior:
- $\lambda~-~Gam(\gamma,\phi)$
- $\pi(\lambda)~=~\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda}$
### For Posterior:
- $\pi(\lambda|data)~=~\frac{f(data|\lambda)\pi(\lambda)}{\int_{0}^{\inf}(data|\lambda^q)\pi(\lambda^q)d\lambda^q}$
- The denominator is the normalizing constant so it's just a number. For this example we'll make the normalizing constant $\frac{1}{c}$, $\sum_{i=1}^n\frac{1}{x_i!}$ = a (constant), and $\frac{\phi^\gamma}{\Gamma(\phi)}$ = b (constant)
- So, $cf(data|\lambda)\pi(\lambda)~=~c(e^{-n\lambda}\lambda^{\sum_{i=1}^n\frac{1}{x_i!}})(\frac{\phi^\gamma}{\Gamma(\phi)}\lambda^{\phi-1}e^{-\gamma\lambda})~=~cab*e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$
- Our posterior kernel $e^{-\lambda(n+\phi)}\lambda^{phi+(\sum_{i=1}^nx_i)-1}$ has new parameters $\gamma^q\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$
- Our constants cab = $\frac{(\phi^q)^{\gamma^q}}{\Gamma(\phi^q)}$
- Shorthand: $\lambda|data~-~Gam(\gamma^q,\phi^q)\mbox{, where}~\gamma^q=\gamma+\sum_{i=1}^nx_i~\mbox{and}~\phi^q=\phi+n$

You also shouldn't set multi-letter words like "data" or "Gam" in math mode. Use text font to get correct kerning.


问:
Clean namespace handling with dom4j
We are using dom4j 1.6.1, to parse XML comming from somewhere. Sometime, the balise have mention of the namespace ( eg :  ) and sometime not (  ). And it's make call of Element.selectSingleNode(String s ) fails.

For now we have 3 solutions, and we are not happy with them

1 - Remove all namespace occurence before doing anything with the xml document

```<code>xml = xml .replaceAll("xmlns=\"[^\"]*\"","");
xml = xml .replaceAll("ds:","");
xml = xml .replaceAll("etm:","");
[...] // and so on for each kind of namespace
</code>```

2 - Remove namespace just before getting a node
By calling

```<code>Element.remove(Namespace ns)
</code>```

But it's works only for a node and the first level of child

3 - Clutter the code by

```<code>node = rootElement.selectSingleNode(NameWithoutNameSpace)
if ( node == null )
    node = rootElement.selectSingleNode(NameWithNameSpace)
</code>```

So ... what do you think ? Witch one is the less worse ? Have you other solution to propose ?

答:
I wanted to remove any namespace information(declaration and tag) to ease the xpath evaluation. I end up with this solution :

```<code>String xml = ...
SAXReader reader = new SAXReader();
Document document = reader.read(new ByteArrayInputStream(xml.getBytes()));
document.accept(new NameSpaceCleaner());
return document.asXML();
</code>```

where the NameSpaceCleaner is a dom4j visitor :

```<code>private static final class NameSpaceCleaner extends VisitorSupport {
    public void visit(Document document) {
        ((DefaultElement) document.getRootElement())
                .setNamespace(Namespace.NO_NAMESPACE);
        document.getRootElement().additionalNamespaces().clear();
    }
    public void visit(Namespace namespace) {
        namespace.detach();
    }
    public void visit(Attribute node) {
       if (node.toString().contains("xmlns")
        || node.toString().contains("xsi:")) {
        node.detach();
      }
    }

    public void visit(Element node) {
        if (node instanceof DefaultElement) {
        ((DefaultElement) node).setNamespace(Namespace.NO_NAMESPACE);
        }
         }
 }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Clean namespace handling with dom4j

Body:
We are using dom4j 1.6.1, to parse XML comming from somewhere. Sometime, the balise have mention of the namespace ( eg :  ) and sometime not (  ). And it's make call of Element.selectSingleNode(String s ) fails.

For now we have 3 solutions, and we are not happy with them

1 - Remove all namespace occurence before doing anything with the xml document

xml = xml .replaceAll("xmlns=\"[^\"]*\"","");
xml = xml .replaceAll("ds:","");
xml = xml .replaceAll("etm:","");
[...] // and so on for each kind of namespace

2 - Remove namespace just before getting a node
By calling

Element.remove(Namespace ns)

But it's works only for a node and the first level of child

3 - Clutter the code by

node = rootElement.selectSingleNode(NameWithoutNameSpace)
if ( node == null )
    node = rootElement.selectSingleNode(NameWithNameSpace)

So ... what do you think ? Witch one is the less worse ? Have you other solution to propose ?

Body:
I wanted to remove any namespace information(declaration and tag) to ease the xpath evaluation. I end up with this solution :

String xml = ...
SAXReader reader = new SAXReader();
Document document = reader.read(new ByteArrayInputStream(xml.getBytes()));
document.accept(new NameSpaceCleaner());
return document.asXML();

where the NameSpaceCleaner is a dom4j visitor :

private static final class NameSpaceCleaner extends VisitorSupport {
    public void visit(Document document) {
        ((DefaultElement) document.getRootElement())
                .setNamespace(Namespace.NO_NAMESPACE);
        document.getRootElement().additionalNamespaces().clear();
    }
    public void visit(Namespace namespace) {
        namespace.detach();
    }
    public void visit(Attribute node) {
       if (node.toString().contains("xmlns")
        || node.toString().contains("xsi:")) {
        node.detach();
      }
    }

    public void visit(Element node) {
        if (node instanceof DefaultElement) {
        ((DefaultElement) node).setNamespace(Namespace.NO_NAMESPACE);
        }
         }
 }


问:
How to make sure background fills the whole flex row which overflows?
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main></code>```

答:
You have to disable the stretch alignment by setting align-items:start the consider min-width:100% on the wrapper:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items:start; /* added */
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  min-width:100%; /* added */
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main></code>```

Body:
How to make sure that background-color fills the whole flex row which overflows to the right? Currently, it only fills a portion of it that fits on the screen.

Here's an example:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Content

Body:
You have to disable the stretch alignment by setting align-items:start the consider min-width:100% on the wrapper:

main {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items:start; /* added */
  background-color: white;
  overflow-x: scroll;
}

.wrapper {
  min-width:100%; /* added */
  display: flex;
  flex-direction: row;
}
.wrapper:hover {
  background-color: rgba(0, 0, 0, 0.5);
}
.content {
  min-width: 150px;
  min-height: 20px;
  padding: 20px;
}

<main>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
  <div class='wrapper'>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
    <div class='content'>Content</div>
  </div>
</main>