问:
How to limit grep to only search the files that you want
We have a rather large and complex file system and I am trying to generate a list of files containing a particular text string. This should be simple, but I need to exclude the './svn' and './pdv' directories (and probably others) and to only look at files of type *.p, *.w or .i.

I can easily do this with a program, but it is proving very slow to run. I want to speed up the process (so that I'm not searching thousands of files repeatedly) as I need to run such searches against a long list of criteria.

Normally, we search the file system using:

```<code>find . -name "*.[!r]*" -exec grep -i -l "search for me" {} \;
</code>```

This is working, but I'm then having to use a program to exclude the unwanted directories , so it is running very slowly.

After looking at the topics here:
Stack Overflow thread

I've decided to try a few other aproaches:

```<code>grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --exclude "!.{p,w,i*}"
</code>```

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

```<code>grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --include "*.p"
</code>```

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

```<code>find . -name "*.[!r]*" -exec grep -i -l ".svn" | grep -i -l "search for me" {} \;
</code>```

I can't even get this (or variations on it) to run successfully.

```<code>find . ! -name "*.svn*" -prune -print -exec grep -i -l "search for me" {} \;
</code>```

Doesn't return anything. It looks like it stops as soon as it finds the .svn directory.

答:
```<code>find . -name "filename_regex"|grep -v '.svn' -v '.pdv'|xargs grep -i 'your search string'
</code>```

Body:
We have a rather large and complex file system and I am trying to generate a list of files containing a particular text string. This should be simple, but I need to exclude the './svn' and './pdv' directories (and probably others) and to only look at files of type *.p, *.w or .i.

I can easily do this with a program, but it is proving very slow to run. I want to speed up the process (so that I'm not searching thousands of files repeatedly) as I need to run such searches against a long list of criteria.

Normally, we search the file system using:

find . -name "*.[!r]*" -exec grep -i -l "search for me" {} \;

This is working, but I'm then having to use a program to exclude the unwanted directories , so it is running very slowly.

After looking at the topics here:
Stack Overflow thread

I've decided to try a few other aproaches:

grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --exclude "!.{p,w,i*}"

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

grep -ilR "search for me" . --exclude ".svn" --excluse "pdv" --include "*.p"

Excludes the './svn', but not the './pdv' directories, Doesn't limit the files looked at.

find . -name "*.[!r]*" -exec grep -i -l ".svn" | grep -i -l "search for me" {} \;

I can't even get this (or variations on it) to run successfully.

find . ! -name "*.svn*" -prune -print -exec grep -i -l "search for me" {} \;

Doesn't return anything. It looks like it stops as soon as it finds the .svn directory.


来源: stackexchange

问:
Transfer docusign draft envelope programmatically
I'm trying to create a envelope in draft status and then programmatically transfer it to a different user than the one I'm impersonating.

I can do this in the web portal but manually after the draft is created (see ui below) but I haven't been able to find a corresponding api method.

Also it doesn't seem like transfer rules can be used to transfer draft envelopes, but I'm not sure if I'm misunderstanding that feature.

答: The solution we ended up using was to add an initial user as an 'editor' user. So the envelope is 'sent' immediately to the user responsible for checking the envelope for correctness.</p>

ContentLicense: CC BY-SA 4.0


问:
Pandas: Skip an arbitrary number of lines in read_csv() before making data frame
I have a file that looks like this:

```<code>##bunch of lines
##lines, lines and more lines
##lines
#Chr  field1  field2  field3
</code>```

I wrote:

```<code>import pandas as pd
df = pd.read_csv(file_name)
</code>```

And I get the error

```<code>Error tokenising data: Expected 1 field in line 2, saw 2
</code>```

I understand the error, that it sees a comma in the second line, but not the first. No matter what delimiter I use, I will always get an error like that because some of the header lines (the ones with ##) have tabs, commas etc.

I actually want to remove all the lines that start with ## anyway (it's a .vcf file), and I want to just start my parsing at the line with #Chr (i.e. I want the rest of the file to be a data frame, where the line #Chr field1 field2 field3 is the header and everything below it is the data frame).

I know you can skip lines in pandas with skiprows, but my problem is that each file I read in will be skipping a different number of ## lines.

Would anyone know of a way to read in csv with pandas, where I can say 'skip all the lines beginning with ##, and then start a dataframe from the line with #Chr and make that line the header?

答:
pd.read_csv() provides with a on_bad_lines argument which should fix your problem

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

Body:
I have a file that looks like this:

##bunch of lines
##lines, lines and more lines
##lines
#Chr  field1  field2  field3

I wrote:

import pandas as pd
df = pd.read_csv(file_name)

And I get the error

Error tokenising data: Expected 1 field in line 2, saw 2

I understand the error, that it sees a comma in the second line, but not the first. No matter what delimiter I use, I will always get an error like that because some of the header lines (the ones with ##) have tabs, commas etc.

I actually want to remove all the lines that start with ## anyway (it's a .vcf file), and I want to just start my parsing at the line with #Chr (i.e. I want the rest of the file to be a data frame, where the line #Chr field1 field2 field3 is the header and everything below it is the data frame).

I know you can skip lines in pandas with skiprows, but my problem is that each file I read in will be skipping a different number of ## lines.

Would anyone know of a way to read in csv with pandas, where I can say 'skip all the lines beginning with ##, and then start a dataframe from the line with #Chr and make that line the header?


问:
Jmeter- Abnormal Response Body
Response Code:200,Actual Response: Get Request Response Body

Response Code:200,Expected Response: HTML format Example-HTML Response Eg

答:
The response doesn't necessary has to be HTML Depending on the response content type it can be:

compressed (i.e. gzipped)

encrypted

binary (i.e. if you're downloading an image or a file)

If you're getting HTML response in the browser and the different one in JMeter - make sure that JMeter sends the same request as the real browser, check:

request URL

request body

request headers

and given you will be sending the same request you will be getting the same response.

Title: Jmeter- Abnormal Response Body


问:
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?
Can IIS supporting ASP.NET and WAMP supporting PHP coexist on the same server?

We already have a WAMP stack setup on a Windows Server 2003 box to support some internal PHP applications, and I want to also setup CI Factory on that box which will try to configure IIS to support it's ASP.NET based dashboard.  I want to make sure that there isn't a big chance of fubarring the WAMP stack that is already there.  Will it be smart enough to handle *.PHP through Apache and *.aspx through IIS ?

Edit: Is there a way to get this to work on the same port?

答:
For example IIS on non-standard port (e.g. 8080) and Apache redirecting traffic to IIS via mod_proxy.

Separate vhosts:

```<code><VirtualHost lamp.example.com>
  # standard vhost configuration
</VirtualHost>

<VirtualHost aspx.example.com>
  ProxyPass / aspx.example.com:8080
</VirtualHost>
</code>```

One vhost:

```<code><VirtualHost www.example.com>
  ProxyPassMatch ^/(.*\.aspx) www.example.com:8080/$1

  # ... standard vhost configuration for LAMP
</VirtualHost>
</code>```

OwnerDisplayName: aaronls

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: aaronls

Body:
For example IIS on non-standard port (e.g. 8080) and Apache redirecting traffic to IIS via mod_proxy.

Separate vhosts:

<VirtualHost lamp.example.com>
  # standard vhost configuration
</VirtualHost>

<VirtualHost aspx.example.com>
  ProxyPass / aspx.example.com:8080
</VirtualHost>

One vhost:

<VirtualHost www.example.com>
  ProxyPassMatch ^/(.*\.aspx) www.example.com:8080/$1

  # ... standard vhost configuration for LAMP
</VirtualHost>

OwnerDisplayName: vartec

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: vartec


问:
Difference between object reference declaration and object construction?
Consider a class named Calculator with the following code:

```<code>class Calc extends Calculator {

    Calculator calculator;                    // [Style 1]

    Calculator calculator = new Calculator(); // [Style 2]
}
</code>```

To my knowledge, no memory has been allocated in [1], but in statement [2] a new Calculator object is created.

Are there any other differences beyond that?

答: Value of the first reference is null, and second one points to the objects. Also, if you have non-default constructor for Calculator class (with some side-effects, like logging, for example), it is not called in the first case.</p>

Body:
Consider a class named Calculator with the following code:

class Calc extends Calculator {

    Calculator calculator;                    // [Style 1]

    Calculator calculator = new Calculator(); // [Style 2]
}

To my knowledge, no memory has been allocated in [1], but in statement [2] a new Calculator object is created.

Are there any other differences beyond that?


问:
Solidity Contract Unused Function/Parameter
```<code>function _postValidatePurchase (
    address _beneficiary,
    uint256 _weiAmount
  )
    pure internal
  {
    // optional override
  }
</code>```

When I compile I get this error in parts of my smart contract that mimic the function above: "Warning: Unused function parameter. Remove or comment out the variable name to silence this warning.uint256 _weiAmount". However, when I comment out the uint and weiAmount, I get these errors :

```<code>DocstringParsingError: Documented parameter "_beneficiary" not found in the parameter list of the function.
DocstringParsingError: Documented parameter "_weiAmount" not found in the parameter list of the function.
libs/openzeppelin/crowdsale/Crowdsale.sol:105:5: TypeError: Wrong argument count for function call: 2 arguments given but expected 0.
_postValidatePurchase(_beneficiary, weiAmount);
</code>```

regarding this line:

```<code> _postValidatePurchase(_beneficiary, weiAmount);
  }
</code>```

答: "Warning: Unused function parameter" is not an error, just a warning. If you have a function with parameters you are not using inside the function, why do you need them? You can just remove them from the input. The only case I can think of is when you are overriding the function. In any case, a warning does not prevent the contract from being compiled. You can just ignore the warning.</p>

Body:
function _postValidatePurchase (
    address _beneficiary,
    uint256 _weiAmount
  )
    pure internal
  {
    // optional override
  }

When I compile I get this error in parts of my smart contract that mimic the function above: "Warning: Unused function parameter. Remove or comment out the variable name to silence this warning.uint256 _weiAmount". However, when I comment out the uint and weiAmount, I get these errors :

DocstringParsingError: Documented parameter "_beneficiary" not found in the parameter list of the function.
DocstringParsingError: Documented parameter "_weiAmount" not found in the parameter list of the function.
libs/openzeppelin/crowdsale/Crowdsale.sol:105:5: TypeError: Wrong argument count for function call: 2 arguments given but expected 0.
_postValidatePurchase(_beneficiary, weiAmount);

regarding this line:

 _postValidatePurchase(_beneficiary, weiAmount);
  }


问:
Laravel get array item by a value matching X in PHP, Google Analytics reporting api
I'm working with the Google Analytics reporting api. I've performed a query and have the data that I need. The reporting api doesn't provide keys for the values returned in each array item, and the order of the items may not always be the same.

Given the attached structure, I'd like to search my scheme key for a value and pull out that one, I've tried using the collect function but couldn't get the right query there.

Data

[
    {
        "date": "2022-02-03",
        "scheme": [
            [
                "Application (journey:continue): form loaded",
                "21"
            ],
            [
                "Application (journey:continue): started",
                "30"
            ],
            [
                "Application (journey:continue): submission:submitted",
                "7"
            ]
        ]
    }
]```

Then, for example:

```php
array_search('form loaded', $data['scheme']);
```
<p>I want:</p>
<pre class="lang-json prettyprint-override"><code>[
    "Application (journey:continue): form loaded",
    "21"
]
</code>```

答:
You can use array_filter function as simple solution:

```<code>$res = array_filter(
    $data[0]['scheme'],
    function($el) {
        return strpos($el[0], 'form loaded') !== false;
    }
);
</code>```

PHP array_filter test online

Body:
I'm working with the Google Analytics reporting api. I've performed a query and have the data that I need. The reporting api doesn't provide keys for the values returned in each array item, and the order of the items may not always be the same.

Given the attached structure, I'd like to search my scheme key for a value and pull out that one, I've tried using the collect function but couldn't get the right query there.

Data

[
    {
        "date": "2022-02-03",
        "scheme": [
            [
                "Application (journey:continue): form loaded",
                "21"
            ],
            [
                "Application (journey:continue): started",
                "30"
            ],
            [
                "Application (journey:continue): submission:submitted",
                "7"
            ]
        ]
    }
]```

Then, for example:

```php
array_search('form loaded', $data['scheme']);

I want:

[
    "Application (journey:continue): form loaded",
    "21"
]

Body:
You can use array_filter function as simple solution:

$res = array_filter(
    $data[0]['scheme'],
    function($el) {
        return strpos($el[0], 'form loaded') !== false;
    }
);

PHP array_filter test online


问:
IF(A2>A3, 1, 0) Excel formula in Pandas
I am trying to create a column with zeros and ones based on values from 1st column.
If the value of upper cell is bigger, then write 1, else 0.
Example code would look like this:

```<code>df = pd.Dataframe({'col1': [1, 2, 1, 3, 0]})
df['col2'] =  ...python version of excel formula IF(A2>A3, 1, 0)...
</code>```

expected output:

I have tried:

```<code>while True:
    for index, rows in df.iterrows():
        df['col1'] = np.where(df['col1'] > df['col1'][index+1], 1, 0)
</code>```

but this is very slow and gives wrong results.
Thanks in advance!

答:
You can use</p>
```<code>df['col2'] = df['col1'].shift().lt(df['col1']).astype(int)
</code>```

Title: IF(A2>A3, 1, 0) Excel formula in Pandas

Body:
I am trying to create a column with zeros and ones based on values from 1st column.
If the value of upper cell is bigger, then write 1, else 0.
Example code would look like this:

df = pd.Dataframe({'col1': [1, 2, 1, 3, 0]})
df['col2'] =  ...python version of excel formula IF(A2>A3, 1, 0)...

expected output:

I have tried:

while True:
    for index, rows in df.iterrows():
        df['col1'] = np.where(df['col1'] > df['col1'][index+1], 1, 0)

but this is very slow and gives wrong results.
Thanks in advance!

Body:
You can use

df['col2'] = df['col1'].shift().lt(df['col1']).astype(int)


问:
How to override Magento2 shipping.html
I'm trying to override shipping.html file, but it's not working. For this, I tried the code as below.

```<code>/app/design/frontend/thema/default/Magento_Checkout/requirejs-config.js
/app/design/frontend/thema/default/Magento_Checkout/web/template/shipping.html

var config = {
paths: {
    'Magento_Checkout/template/shipping': 'Magento_Checkout/template/shipping'
}
};
</code>```

After I run the upgrade and static-conent:deploy, but still it's not working.
Please suggest me where I went wrong?

答:
You don't need to make the change in Magento_Checkout/requirejs-config.js
putting the html in your template is enough

However, you have to flush the cache:
bin/magento cache:flush

Ideally, delete the frontend folder under "pub" to ensure file regeneration
and clear the var/cache - var/page_cache and var/view_processed folders

Title: How to override Magento2 shipping.html

Body:
I'm trying to override shipping.html file, but it's not working. For this, I tried the code as below.

/app/design/frontend/thema/default/Magento_Checkout/requirejs-config.js
/app/design/frontend/thema/default/Magento_Checkout/web/template/shipping.html

var config = {
paths: {
    'Magento_Checkout/template/shipping': 'Magento_Checkout/template/shipping'
}
};

After I run the upgrade and static-conent:deploy, but still it's not working.
Please suggest me where I went wrong?


问:
How to add an item to a list on a separate page in Flutter
I am new to Flutter and currently building an app to log spasms that happens due to spasticity. This is somewhat like a ToDo style app in structure. So I have a list in my home.dart file that a ListViewBuilder to display my Spasm objects. What I want to do is to create a Spasm object in recordSpasm.dart and add it to the list in home.dart. How  do I do that? I´ll post my code here:

home.dart

```<code>import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:spasmlogger/classses/spasm.dart';

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

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  List<Spasm> Spasms = [
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm"),
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm")
  ];

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SpasmLogger"),
        actions: <Widget>[
          IconButton(
            icon: Icon(MdiIcons.help),
            onPressed: () {
              Navigator.pushNamed(context, '/about');
            },
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(MdiIcons.plus),
        onPressed: () {
          Navigator.pushNamed(context, "/recordSpasm");
        }
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        child: ListView.builder(
          itemCount: Spasms.length,
          itemBuilder: (BuildContext context, int index){
            return Card(
              child: ListTile(
                title: Text(Spasms[index].strength + " spasm detected in " + Spasms[index].bodyPart),
                subtitle: Text(Spasms[index].comment)
            )
            );
          },
        )
      ),
    );
  }
}
</code>```

recordSpasm.dart

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

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

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

class _RecordSpasmState extends State<RecordSpasm> {
  @override

  String Strength = "Regular strength";
  List<String> Strengths = ["Regular strength", "Mildly stronger", "Severely Strong", "Extremely strong"];
  String BodyPart = "Lower body";
  List<String> BodyParts = ["Lower body", "Upper body", "Head"];
  TextEditingController comment = new TextEditingController();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Record spasm")

      ),
      body:
      Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget> [
              Text("Spasm strength"),
              DropdownButton(
                value: Strength,
                items: Strengths.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
        );
      }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    Strength = value!;

                  });

                },
                ),
                Text("Part of body"),
                DropdownButton(
                  value: BodyPart,
                  items: BodyParts.map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                  );
                }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    BodyPart = value!;

                  });

                },
                ),
                Text("Comments"),
                TextFormField(
                  maxLines: 5,
                  controller: comment,

                ),
                ElevatedButton(
                  onPressed: () {
                    // Add object to the list in home.dart
                    print(Strength);
                    print(BodyPart);
                    print(comment.text);

                  },
                  child: Text("Record spasm")
                  )

          ]
        )
      )
      )
    );
  }
}
</code>```

答:
first you need to access to you list. you have 2 ways to do that

make the list static like this static List yourListName = [];

for the other way you don't need to do anything right now

so if you use way 1 then you can add something to your list like this:

```<code>import 'thePathFromTheFileThatHaveTheListIn';

...

// here we add something to your list without building the whole class again
TheClassWhereTheListWasIn.yourListName.add(...);
</code>```

and if you use way 2 then you can add something to your list like this:

```<code>import 'thePathFromTheFielThatHaveTheListIn';

...

// here we add something to your list but here we build the whole class again
// and then add something to your list
TheClassWhereTheListIsIn().yourListName.add(...);
</code>```

Body:
I am new to Flutter and currently building an app to log spasms that happens due to spasticity. This is somewhat like a ToDo style app in structure. So I have a list in my home.dart file that a ListViewBuilder to display my Spasm objects. What I want to do is to create a Spasm object in recordSpasm.dart and add it to the list in home.dart. How  do I do that? I´ll post my code here:

home.dart

import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:spasmlogger/classses/spasm.dart';

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

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  List<Spasm> Spasms = [
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm"),
    Spasm("Extremely strong", "Upper body", "Cannot control  left arm")
  ];

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SpasmLogger"),
        actions: <Widget>[
          IconButton(
            icon: Icon(MdiIcons.help),
            onPressed: () {
              Navigator.pushNamed(context, '/about');
            },
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(MdiIcons.plus),
        onPressed: () {
          Navigator.pushNamed(context, "/recordSpasm");
        }
      ),
      body: Padding(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        child: ListView.builder(
          itemCount: Spasms.length,
          itemBuilder: (BuildContext context, int index){
            return Card(
              child: ListTile(
                title: Text(Spasms[index].strength + " spasm detected in " + Spasms[index].bodyPart),
                subtitle: Text(Spasms[index].comment)
            )
            );
          },
        )
      ),
    );
  }
}

recordSpasm.dart

import 'package:flutter/material.dart';
import 'package:spasmlogger/classses/spasm.dart';

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

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

class _RecordSpasmState extends State<RecordSpasm> {
  @override

  String Strength = "Regular strength";
  List<String> Strengths = ["Regular strength", "Mildly stronger", "Severely Strong", "Extremely strong"];
  String BodyPart = "Lower body";
  List<String> BodyParts = ["Lower body", "Upper body", "Head"];
  TextEditingController comment = new TextEditingController();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Record spasm")

      ),
      body:
      Padding(
        padding: EdgeInsets.all(16),
        child: Form(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget> [
              Text("Spasm strength"),
              DropdownButton(
                value: Strength,
                items: Strengths.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
        );
      }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    Strength = value!;

                  });

                },
                ),
                Text("Part of body"),
                DropdownButton(
                  value: BodyPart,
                  items: BodyParts.map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                  );
                }).toList(),
                onChanged: (String? value) {
                  setState(() {
                    BodyPart = value!;

                  });

                },
                ),
                Text("Comments"),
                TextFormField(
                  maxLines: 5,
                  controller: comment,

                ),
                ElevatedButton(
                  onPressed: () {
                    // Add object to the list in home.dart
                    print(Strength);
                    print(BodyPart);
                    print(comment.text);

                  },
                  child: Text("Record spasm")
                  )

          ]
        )
      )
      )
    );
  }
}

Body:
first you need to access to you list. you have 2 ways to do that

make the list static like this static List yourListName = [];

for the other way you don't need to do anything right now

so if you use way 1 then you can add something to your list like this:

import 'thePathFromTheFileThatHaveTheListIn';

...

// here we add something to your list without building the whole class again
TheClassWhereTheListWasIn.yourListName.add(...);

and if you use way 2 then you can add something to your list like this:

import 'thePathFromTheFielThatHaveTheListIn';

...

// here we add something to your list but here we build the whole class again
// and then add something to your list
TheClassWhereTheListIsIn().yourListName.add(...);


问:
How to load xml file with specifc paragraph by xml in Python?
I have a xml file and its structure like that,

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<book>
    <toc>        <tocdiv pagenum="564">
            <title>9thmemo</title>
            <tocdiv pagenum="588">
                <title>b</title>
            </tocdiv>
        </tocdiv></toc>
    <chapter><title>9thmemo</title>
        <para>...</para>
        <para>...</para></chapter>
    <chapter>...</chapter>
    <chapter>...</chapter>
</book>
</code>```

There are several chapters in the <book>...</book>, and each chapter has a title, I only want to read all content of this chapter,"9thmemo"(not others)
I tried to read by following code:

```<code>from xml.dom import minidom

filename = "result.xml"
file = minidom.parse(filename)
chapters = file.getElementsByTagName('chapter')
for i in range(10):
    print(chapters[i])
</code>```

I only get the address of each chapter...
if I add some sub-element like chapters[i].title, it shows cannot find this attribute

答:
I only want to read all content of this chapter,"9thmemo"(not others)

The problem with the code is that it does not try to locate the specific 'chapter' while the answer code uses xpath in order to locate it.

Try the below

```<code>import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<book>
   <toc>
      <tocdiv pagenum="564">
         <title>9thmemo</title>
         <tocdiv pagenum="588">
            <title>b</title>
         </tocdiv>
      </tocdiv>
   </toc>
   <chapter>
      <title>9thmemo</title>
      <para>A</para>
      <para>B</para>
   </chapter>
   <chapter>...</chapter>
   <chapter>...</chapter>
</book>'''

root = ET.fromstring(xml)
chapter = root.find('.//chapter/[title="9thmemo"]')
para_data = ','.join(p.text for p in chapter.findall('para'))
print(para_data)
</code>```

output

```<code>A,B
</code>```

Body:
I have a xml file and its structure like that,

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<book>
    <toc>        <tocdiv pagenum="564">
            <title>9thmemo</title>
            <tocdiv pagenum="588">
                <title>b</title>
            </tocdiv>
        </tocdiv></toc>
    <chapter><title>9thmemo</title>
        <para>...</para>
        <para>...</para></chapter>
    <chapter>...</chapter>
    <chapter>...</chapter>
</book>

There are several chapters in the <book>...</book>, and each chapter has a title, I only want to read all content of this chapter,"9thmemo"(not others)
I tried to read by following code:

from xml.dom import minidom

filename = "result.xml"
file = minidom.parse(filename)
chapters = file.getElementsByTagName('chapter')
for i in range(10):
    print(chapters[i])

I only get the address of each chapter...
if I add some sub-element like chapters[i].title, it shows cannot find this attribute

Body:
I only want to read all content of this chapter,"9thmemo"(not others)

The problem with the code is that it does not try to locate the specific 'chapter' while the answer code uses xpath in order to locate it.

Try the below

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<book>
   <toc>
      <tocdiv pagenum="564">
         <title>9thmemo</title>
         <tocdiv pagenum="588">
            <title>b</title>
         </tocdiv>
      </tocdiv>
   </toc>
   <chapter>
      <title>9thmemo</title>
      <para>A</para>
      <para>B</para>
   </chapter>
   <chapter>...</chapter>
   <chapter>...</chapter>
</book>'''

root = ET.fromstring(xml)
chapter = root.find('.//chapter/[title="9thmemo"]')
para_data = ','.join(p.text for p in chapter.findall('para'))
print(para_data)

output

A,B


问:
One httpClient for many method in one class
I would like to use one httpclient to many method in class.
Below is the simplified code:

public class test{

private readonly HttpClient _httpClient;

```<code>public Test(){
_httpClient = new HttpClient();
}

public void method1(){
using (_httpClient){
//...
}
}

public void method2(){
using (_httpClient){
//...
}
}

public void method3(){
using (_httpClient){
//...
}
}
}
</code>```

Then it calls the method data:

```<code>public async static void TestHttpClient()
        {
            Test test1 = new Test();
            test1.Method1();
            test1.Method2();
            test1.Method3();
        }
</code>```

Method 1 is working. When calling the second one I get the message: "You cannot access a deleted object."

Thanks for helps.

Regards

答:
using calls the Dispose() method after the scope - which destroys the object - keep the instance of your HttpClient within the instance of your object

```<code>public class test : IDisposable
{
    private readonly HttpClient _httpClient;
    public test()
    {
        _httpClient = new HttpClient();
    }

    public void Dispose()
    {
        _httpClient.Dispose();
    }

    public void method1()
    {
        //...
    }
}
</code>```

then you can dispose your object instead of the HttpClient

```<code>using(test myObject = new test())
{
    myObject.method1();
    myObject.method2();
}
</code>```

Body:
I would like to use one httpclient to many method in class.
Below is the simplified code:

public class test{

private readonly HttpClient _httpClient;

public Test(){
_httpClient = new HttpClient();
}

public void method1(){
using (_httpClient){
//...
}
}

public void method2(){
using (_httpClient){
//...
}
}

public void method3(){
using (_httpClient){
//...
}
}
}

Then it calls the method data:

public async static void TestHttpClient()
        {
            Test test1 = new Test();
            test1.Method1();
            test1.Method2();
            test1.Method3();
        }

Method 1 is working. When calling the second one I get the message: "You cannot access a deleted object."

Thanks for helps.

Regards

Body:
using calls the Dispose() method after the scope - which destroys the object - keep the instance of your HttpClient within the instance of your object

public class test : IDisposable
{
    private readonly HttpClient _httpClient;
    public test()
    {
        _httpClient = new HttpClient();
    }

    public void Dispose()
    {
        _httpClient.Dispose();
    }

    public void method1()
    {
        //...
    }
}

then you can dispose your object instead of the HttpClient

using(test myObject = new test())
{
    myObject.method1();
    myObject.method2();
}


问:
How to avoid html encoding of strings in partial view
My goal is to separate js controls into partial views and parametrize them through ViewData. I want to pass a string in ViewData that is used as javascript string value.

Now the problem is that I don't know how to render a string that is not html encoded.

My current attempt is:

```<code>var domAsString = "<%: HttpUtility.HtmlDecode((string)ViewData["domLayout"]) %>"
</code>```

Which renders it as a html-encoded string. How can I avoid this?

答:
You could try:

```<code>var domAsString = "<%= (string)ViewData["domLayout"] %>"
</code>```

The <%: %> syntax is shorthand for <%= Html.Encode( .... ) %>

Body:
My goal is to separate js controls into partial views and parametrize them through ViewData. I want to pass a string in ViewData that is used as javascript string value.

Now the problem is that I don't know how to render a string that is not html encoded.

My current attempt is:

var domAsString = "<%: HttpUtility.HtmlDecode((string)ViewData["domLayout"]) %>"

Which renders it as a html-encoded string. How can I avoid this?

Body:
You could try:

var domAsString = "<%= (string)ViewData["domLayout"] %>"

The <%: %> syntax is shorthand for <%= Html.Encode( .... ) %>


问:
Select if the date is in at least one range, several tables
I have two tables - invoices, with such structure:

InvoiceId
PersonId
Date

1
1
2022-02-01

2
1
2022-02-08

3
2
2022-02-05

4
2
2022-02-09

5
3
2022-02-09

and Activity:

ActivityId
PersonId
SessionStart
SessionEnd

1
1
2022-01-21
2022-02-04

2
1
2022-02-09
2022-02-10

3
2
2022-01-21
2022-02-05

4
2
2022-02-09
2022-02-10

5
3
2022-02-05
2022-02-05

I need to select invoices from Invoice table only if invoice's date is in at least one of range of related person's session ranges in Activity table.

For example, result based on two data sets:

InvoiceId
PersonId
Date

1
1
2022-02-01

3
2
2022-02-05

4
2
2022-02-09

We will receive:

invoice #1, because "2022-02-01" is in the range #1 in Activity table

invoice #3, because "2022-02-05" is in the range #3 in Activity table

invoice #4, because "2022-02-09" is in the range #4 in Activity table

We won't receive:

invoice #2, because "2022-02-08" is not in ranges #1, #2 for person 1

invoice #5, because "2022-02-09" is not in ranges #5 for person 3

Basic query is

SELECT InvoiceID from Invoice invoice
JOIN ON Activity activity on invoice.PersonID = activity.PersonID
```

How can I create a rule "date is in at least one session range for invoice's person"? I tried GROUP BY with HAVING COUNT(case Date is between SessionStart and SessionDate then 1 end) = 0, but it doesn't work.

答:
An EXISTS filter should work:

```<code>SELECT InvoiceID
FROM Invoice invoice
WHERE Exists
(
    SELECT 1
    FROM Activity activity
    WHERE activity.PersonID = invoice.PersonID
    AND invoice.[Date] Between activity.SessionStart And activity.SessionEnd
);
</code>```

Body:
I have two tables - invoices, with such structure:

InvoiceId
PersonId
Date

1
1
2022-02-01

2
1
2022-02-08

3
2
2022-02-05

4
2
2022-02-09

5
3
2022-02-09

and Activity:

ActivityId
PersonId
SessionStart
SessionEnd

1
1
2022-01-21
2022-02-04

2
1
2022-02-09
2022-02-10

3
2
2022-01-21
2022-02-05

4
2
2022-02-09
2022-02-10

5
3
2022-02-05
2022-02-05

I need to select invoices from Invoice table only if invoice's date is in at least one of range of related person's session ranges in Activity table.

For example, result based on two data sets:

InvoiceId
PersonId
Date

1
1
2022-02-01

3
2
2022-02-05

4
2
2022-02-09

We will receive:

invoice #1, because "2022-02-01" is in the range #1 in Activity table

invoice #3, because "2022-02-05" is in the range #3 in Activity table

invoice #4, because "2022-02-09" is in the range #4 in Activity table

We won't receive:

invoice #2, because "2022-02-08" is not in ranges #1, #2 for person 1

invoice #5, because "2022-02-09" is not in ranges #5 for person 3

Basic query is

SELECT InvoiceID from Invoice invoice
JOIN ON Activity activity on invoice.PersonID = activity.PersonID

How can I create a rule "date is in at least one session range for invoice's person"? I tried GROUP BY with HAVING COUNT(case Date is between SessionStart and SessionDate then 1 end) = 0, but it doesn't work.

Body:
An EXISTS filter should work:

SELECT InvoiceID
FROM Invoice invoice
WHERE Exists
(
    SELECT 1
    FROM Activity activity
    WHERE activity.PersonID = invoice.PersonID
    AND invoice.[Date] Between activity.SessionStart And activity.SessionEnd
);


问:
Github Reusable Workflow: How to use the workflow of the last commit (or branch head) instead hardcoding a branch name / release version?
I'm setting up a reusable workflow using GitHub actions: https://docs.github.com/en/actions/learn-github-actions/reusing-workflows

Since the callee workflow and caller workflow are both in the same repo, I want to reference the latest commit of the called workflow inside my calling workflow's uses statement.

Example:

```<code>uses: owner/repo/.github/workflows/called-workflow.yml@${{GITHUB_SHA}}
</code>```

That ${{GITHUB_SHA}} doesn't get interpolated, so I get the following error:

```<code>Invalid workflow file : .github/workflows/calling-workflow.yml#L1
handling usage of workflow "owner/repo/.github/workflows/called-workflow.yml@${{GITHUB_SHA}}": can't obtain workflow file: reference to workflow should be either a valid branch, tag, or commit
</code>```

How can I set the ref to the latest commit when calling a workflow within a workflow?

答:
This is now possible

As of February 2022.

First in January: https://github.blog/changelog/2022-01-25-github-actions-reusable-workflows-can-be-referenced-locally/

Up until today-ish though (2022-Feb-10), there was a bug that prevented it from working on pull_request events; that has now been fixed:
https://github.community/t/ref-head-in-reusable-workflows/203690/74?u=briantist

Example usage:

jobs:
  call-workflow-in-local-repo:
    uses: ./.github/workflows/workflow-2.yml
```

Note: The callee and caller workflow must be in the same repository. (See: here for more info)

Body:
I'm setting up a reusable workflow using GitHub actions: https://docs.github.com/en/actions/learn-github-actions/reusing-workflows

Since the callee workflow and caller workflow are both in the same repo, I want to reference the latest commit of the called workflow inside my calling workflow's uses statement.

Example:

uses: owner/repo/.github/workflows/called-workflow.yml@${{GITHUB_SHA}}

That ${{GITHUB_SHA}} doesn't get interpolated, so I get the following error:

Invalid workflow file : .github/workflows/calling-workflow.yml#L1
handling usage of workflow "owner/repo/.github/workflows/called-workflow.yml@${{GITHUB_SHA}}": can't obtain workflow file: reference to workflow should be either a valid branch, tag, or commit

How can I set the ref to the latest commit when calling a workflow within a workflow?

Body:
This is now possible

As of February 2022.

First in January: https://github.blog/changelog/2022-01-25-github-actions-reusable-workflows-can-be-referenced-locally/

Up until today-ish though (2022-Feb-10), there was a bug that prevented it from working on pull_request events; that has now been fixed:
https://github.community/t/ref-head-in-reusable-workflows/203690/74?u=briantist

Example usage:

jobs:
  call-workflow-in-local-repo:
    uses: ./.github/workflows/workflow-2.yml

Note: The callee and caller workflow must be in the same repository. (See: here for more info)


问:
Determine the file size of PNG from stream
I came across a file with an obscure database format and would like to recover some information from it. After using python to open and read the file as bytes, and use re.search with pattern of b"\x89\x50\x4e\x47" (PNG file header), I found an offset in the file that matches this. Upon further examination, it's likely that this is the starting position of an actual PNG file (the first 16 bytes in hex are 89504e470d0a1a0a0000000d49484452). However, with no information regarding the size of this PNG file, how should I determine it programmatically (using the information from the header)? It would be appreciated if some existing PNG debugging tool can be used.

I already tried output the rest of this database file starting from this offset and save it as a PNG, but it doesn't work as my image viewer report the file is corrupted.

答:
PNG images have footers that you can utilize to determine when to stop.

You can seek up until IEND, then move right 4 bytes to capture the CRC data, and extract all the bytes up to that point.

After which, you should be able to get the full PNG file.


问:
What's the fastest way to ReadProcessMemory?
I'm trying to search for all instances of a null-terminated string the memory of a process. I enumed all the alloced memory areas with VirtualQueryEx, then I read them with ReadProcessMemory to a byte array and search using this algo (which I found here and the author claims to be the fastest)

```<code>    public static unsafe List<long> IndexesOf(byte[] Haystack, byte[] Needle) {
        List<long> Indexes = new List<long>();
        fixed (byte* H = Haystack) fixed (byte* N = Needle) {
            long i = 0;
            for (byte* hNext = H, hEnd = H + Haystack.LongLength; hNext < hEnd; i++, hNext++) {
                bool Found = true;
                for (byte* hInc = hNext, nInc = N, nEnd = N + Needle.LongLength; Found && nInc < nEnd; Found = *nInc == *hInc, nInc++, hInc++) ;
                if (Found) Indexes.Add(i);
            }
            return Indexes;
        }
    }
</code>```

It works, but it's too slow. Is there a way to memory map the process or somehow search faster in its memory?

答:
From an external process, you pretty much have the correct approach. However, if you're looking for a string you probably don't care about certain regions (eg. executable memory) so you can exclude them from your search region. Most likely you are really only interested in PAGE_READONLY and PAGE_READWRITE.

You should read the memory in as big blocks as possible with ReadProcessMemory(). The main bottleneck will be disk IO (from swapping) and there's not much you can do about that really. Multi-threading it will speed it up because then you'll be 'buffering a read' whilst processing the previous read.

If you really need speed, the correct way to do it is not via an external process as you are doing right now. You should inject a DLL so you have direct access to the process' virtual memory space.

In your search algorithm, you can also do little tricks. For example if you know the string is always allocated on a 4 byte alignment then you can just search those. The biggest speedup you'll get is from multi-threading and/or DLL injection.

Body:
I'm trying to search for all instances of a null-terminated string the memory of a process. I enumed all the alloced memory areas with VirtualQueryEx, then I read them with ReadProcessMemory to a byte array and search using this algo (which I found here and the author claims to be the fastest)

    public static unsafe List<long> IndexesOf(byte[] Haystack, byte[] Needle) {
        List<long> Indexes = new List<long>();
        fixed (byte* H = Haystack) fixed (byte* N = Needle) {
            long i = 0;
            for (byte* hNext = H, hEnd = H + Haystack.LongLength; hNext < hEnd; i++, hNext++) {
                bool Found = true;
                for (byte* hInc = hNext, nInc = N, nEnd = N + Needle.LongLength; Found && nInc < nEnd; Found = *nInc == *hInc, nInc++, hInc++) ;
                if (Found) Indexes.Add(i);
            }
            return Indexes;
        }
    }

It works, but it's too slow. Is there a way to memory map the process or somehow search faster in its memory?


问:
Can "maxAge" of "org.apache.tomcat.jdbc.pool.DataSourceFactory" impact active database connection
This is what is our PROD scenario:

We are using org.apache.tomcat.jdbc.pool.DataSourceFactory and having maxAge of 900000 and maxActive of 100.

We have long database operation and it is failing because of database connection closed exception.

When I checked the logs then I found that this exception is occurring after ~15 minutes.

So, this makes me wonder if this is because of maxAge of 900000. I read the docs of Apache and other blogs but no where I could find a clear answer whether maxAge will impact an active database connection or not.

From the docs only thing I am 100% sure of is that maxAge is checked when moving a database connection in or out of the pool, but I not sure on what happens once database connection is in use...

Has anyone having similar experience with this or knows if maxAge impacts an active connection or not?

UPDATE 1:

I am using Tomcat 8.5

答:
According to this it will not close your connection that's already in use. It rather checks for the age before returning it to the pool - after you released the connection. And closes if max age has elapsed.
We went from no-max-age to 10 minutes and didn't see the issue you're reporting.

From the documentation,

When a connection is returned to the pool, the pool will check to see
if the now - time-when-connected > maxAge has been reached, and if so,
it closes the connection rather than returning it to the pool.


问:
JavaScript to get value from HTML table cell
I'm trying to extract the text from a multi-row, multi-column html table. A column from the table is defined below. All the id values are dynamic so I'll need to reference other attributes or tags to fetch it. The value I'm trying to fetch here is "PERS". It is the only cell containing text.

 PERS

```
<p>I was expecting this to work but no such luck ...</p>
<pre class="lang-js prettyprint-override"><code>  var input1rw = document.getElementsByClassName('x-grid-cell x-grid-td x-grid-cell-TIMM103-Block-2-colstate-ResourceCode-0 grid-cell-error-input x-unselectable');
  var input1cl = input1rw[0];
  console.log('result: ', input1cl.innerText);
</code>```

After several hours of failure, I'd greatly appreciate some help from the experts.

答:
Because the IDs were dynamic but the table would always be in the same place, I used the following to get the value:

var tblID = document.getElementsByTagName("table")[15].id;
var tr = document.querySelector('#' + tblID).querySelectorAll('tr')[0];
var div = tr.querySelectorAll('td')[0].querySelector('div').childNodes[1].textContent;
console.log(div);
```

Body:
I'm trying to extract the text from a multi-row, multi-column html table. A column from the table is defined below. All the id values are dynamic so I'll need to reference other attributes or tags to fetch it. The value I'm trying to fetch here is "PERS". It is the only cell containing text.

 PERS

I was expecting this to work but no such luck ...

  var input1rw = document.getElementsByClassName('x-grid-cell x-grid-td x-grid-cell-TIMM103-Block-2-colstate-ResourceCode-0 grid-cell-error-input x-unselectable');
  var input1cl = input1rw[0];
  console.log('result: ', input1cl.innerText);

After several hours of failure, I'd greatly appreciate some help from the experts.


问:
Why my code is not showing the answer when i click button "Show Answer"
EDIT: Add a new 'Show answer' button to display the correct answer to the question. The answer is not visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. Make only one fetch request / question and you can display the answer using conditional rendering, for example. HELP NEEDED

const Trivia = () => {

```<code> const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);

 const fetchQuestion = () => {
     fetch("https://opentdb.com/api.php?amount=1")
     .then((response) => response.json())
     .then((data) => {
      setQuestion(data.results[0].question);

     });
   };

    const answerToggler = () => setShowAnswer(prevAns => !prevAns)
     React.useEffect(() => {
         fetchQuestion();
     }, []);

 return(

 <div>
 <p> {question}</p>
 <button onClick={fetchQuestion}>New Question</button>
 {showAnswer && <h3>Correct Answer</h3>} **<= This is just an example because i don't know what i put there**
<button onClick={answerToggler}>Show Answer </button>

</div>
     );
</code>```

};

The idea is that the code retrieves the answer to the question by pressing the "show answer" button using only one fetch request. It should look like this:

答:
Please do these changings:

```<code> const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);
 const [answer, setAnswer] = React.useState();

 const fetchQuestion = () => {
      setShowAnswer(false);
      fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
      setQuestion(data.results[0].question);
 });
 };

const answerToggler = () => {
      setShowAnswer(true);
      fetch("opentdb.com/api.php?amount=1")
      .then(response => response.json())
      .then((data) => {
            setAnswer(data.result[0].answer);/*I dont sure this be same you want*/
       });
     };
 React.useEffect(() => {
      fetchQuestion();
    }, []);

 return(
      <div>
       <p> {question}</p>
       <button onClick={fetchQuestion}>New Question</button>
       {showAnswer ? <h3>{answer}</h3> : ""}
       <button onClick={answerToggler}>Show Answer </button>
      </div>
   );
 }
</code>```

If this solves you problem, please tell me.

Body:
EDIT: Add a new 'Show answer' button to display the correct answer to the question. The answer is not visible when the question is retrieved but is only displayed when the 'Show answer' button is pressed. Make only one fetch request / question and you can display the answer using conditional rendering, for example. HELP NEEDED

const Trivia = () => {

 const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);

 const fetchQuestion = () => {
     fetch("https://opentdb.com/api.php?amount=1")
     .then((response) => response.json())
     .then((data) => {
      setQuestion(data.results[0].question);

     });
   };

    const answerToggler = () => setShowAnswer(prevAns => !prevAns)
     React.useEffect(() => {
         fetchQuestion();
     }, []);

 return(

 {question}

 <button onClick={fetchQuestion}>New Question</button>
 {showAnswer &&
Correct Answer
} **<= This is just an example because i don't know what i put there**
<button onClick={answerToggler}>Show Answer </button>

     );

};

The idea is that the code retrieves the answer to the question by pressing the "show answer" button using only one fetch request. It should look like this:

Body:
Please do these changings:

 const [question, setQuestion] = React.useState();
 const [showAnswer, setShowAnswer] = React.useState(false);
 const [answer, setAnswer] = React.useState();

 const fetchQuestion = () => {
      setShowAnswer(false);
      fetch("https://opentdb.com/api.php?amount=1")
      .then((response) => response.json())
      .then((data) => {
      setQuestion(data.results[0].question);
 });
 };

const answerToggler = () => {
      setShowAnswer(true);
      fetch("opentdb.com/api.php?amount=1")
      .then(response => response.json())
      .then((data) => {
            setAnswer(data.result[0].answer);/*I dont sure this be same you want*/
       });
     };
 React.useEffect(() => {
      fetchQuestion();
    }, []);

 return(
      <div>
       <p> {question}</p>
       <button onClick={fetchQuestion}>New Question</button>
       {showAnswer ? <h3>{answer}</h3> : ""}
       <button onClick={answerToggler}>Show Answer </button>
      </div>
   );
 }

If this solves you problem, please tell me.


问:
libvlc+qwidget handle mouse event on Win64
I am working on Qt and using libVlc version 2.1.5 for live video streaming.I want to handle mouse press event on vlc frame.But when I click on vlc,it is not able to throw the mouse event.
I have tried with

```<code>libvlc_video_set_mouse_input(libvlcMediaPlayer,false);
</code>```

But it hides the mouse over vlc.
Please help me if anyone knows.

Thanks.

答:
Three Solutions on Windows

Solution One: WS_EX_TRANSPARENT

Note: May not work on Windows 7 or below.

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 23:31
import vlc
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore

def togglePlaying():
    player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
    player.get_state() == vlc.State.Playing and player.pause()
    player.get_state() != vlc.State.Playing and player.play()

def onVideoOut(event):
    hwnd = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
    exStyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
    exStyle |= win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT
    win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exStyle)

app = QtWidgets.QApplication()
window = QtWidgets.QMainWindow()
window.setCentralWidget(QtWidgets.QWidget())
window.centralWidget().mousePressEvent = lambda *args: togglePlaying()
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()

filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(window.centralWidget().winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()

app.exec_()
```
<h2>Solution Two: Low-Level Mouse Hook</h2>
<pre class="lang-py prettyprint-override"><code># Created by BaiJiFeiLong@gmail.com at 2022/2/10 23:31
from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG

import vlc
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore

def genStruct(name="Structure", **kwargs):
    return type(name, (Structure,), dict(
        _fields_=list(kwargs.items()),
        __str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
    ))

@WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
    msg = cast(lParam, POINTER(HookStruct))[0]
    hwnd = win32gui.WindowFromPoint((msg.pt.x, msg.pt.y))
    if hwnd in vlcHwnds:
        win32gui.PostMessage(widget.winId(), wParam, wParam, (msg.pt.y << 16) + msg.pt.x)
    return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))

def togglePlaying():
    print("toggle")
    player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
    player.get_state() == vlc.State.Playing and player.pause()
    player.get_state() != vlc.State.Playing and player.play()

def onVideoOut(event):
    hwnd1 = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
    hwnd2 = win32gui.GetWindow(hwnd1, win32con.GW_CHILD)
    vlcHwnds.append(hwnd1)
    vlcHwnds.append(hwnd2)
    print("vlcHwnds", vlcHwnds)

app = QtWidgets.QApplication()
widget = QtWidgets.QWidget()
widget.mouseReleaseEvent = lambda *args: togglePlaying()
window = QtWidgets.QMainWindow()
window.setCentralWidget(widget)
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()
vlcHwnds = []

HookStruct = genStruct(
    "Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
windll.user32.SetWindowsHookExW(win32con.WH_MOUSE_LL, hookProc, None, 0)

filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(widget.winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()
app.exec_()
</code>```

Solution Three: In-Process Mouse Hook

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 23:31
from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG, HINSTANCE

import vlc
import win32api
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore

def genStruct(name="Structure", **kwargs):
    return type(name, (Structure,), dict(
        _fields_=list(kwargs.items()),
        __str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
    ))

@WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
    msg = cast(lParam, POINTER(HookStruct))[0]
    win32gui.PostMessage(widget.winId(), wParam, wParam, (msg.pt.y << 16) + msg.pt.x)
    return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))

def togglePlaying():
    player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
    player.get_state() == vlc.State.Playing and player.pause()
    player.get_state() != vlc.State.Playing and player.play()

def onVideoOut(event):
    hwnd1 = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
    processId = win32api.GetModuleHandle()
    threadId = windll.user32.GetWindowThreadProcessId(hwnd1, None)
    windll.user32.SetWindowsHookExW(win32con.WH_MOUSE, hookProc, HINSTANCE(processId), threadId)

app = QtWidgets.QApplication()
window = QtWidgets.QMainWindow()
widget = QtWidgets.QWidget()
widget.mouseReleaseEvent = lambda *args: togglePlaying()
window.setCentralWidget(widget)
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()

HookStruct = genStruct(
    "Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(widget.winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()

app.exec_()
```

Body:
I am working on Qt and using libVlc version 2.1.5 for live video streaming.I want to handle mouse press event on vlc frame.But when I click on vlc,it is not able to throw the mouse event.
I have tried with

libvlc_video_set_mouse_input(libvlcMediaPlayer,false);

But it hides the mouse over vlc.
Please help me if anyone knows.

Thanks.

Body:
Three Solutions on Windows

Solution One: WS_EX_TRANSPARENT

Note: May not work on Windows 7 or below.

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 23:31
import vlc
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore

def togglePlaying():
    player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
    player.get_state() == vlc.State.Playing and player.pause()
    player.get_state() != vlc.State.Playing and player.play()

def onVideoOut(event):
    hwnd = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
    exStyle = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
    exStyle |= win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT
    win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exStyle)

app = QtWidgets.QApplication()
window = QtWidgets.QMainWindow()
window.setCentralWidget(QtWidgets.QWidget())
window.centralWidget().mousePressEvent = lambda *args: togglePlaying()
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()

filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(window.centralWidget().winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()

app.exec_()

Solution Two: Low-Level Mouse Hook

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 23:31
from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG

import vlc
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore

def genStruct(name="Structure", **kwargs):
    return type(name, (Structure,), dict(
        _fields_=list(kwargs.items()),
        __str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
    ))

@WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
    msg = cast(lParam, POINTER(HookStruct))[0]
    hwnd = win32gui.WindowFromPoint((msg.pt.x, msg.pt.y))
    if hwnd in vlcHwnds:
        win32gui.PostMessage(widget.winId(), wParam, wParam, (msg.pt.y << 16) + msg.pt.x)
    return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))

def togglePlaying():
    print("toggle")
    player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
    player.get_state() == vlc.State.Playing and player.pause()
    player.get_state() != vlc.State.Playing and player.play()

def onVideoOut(event):
    hwnd1 = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
    hwnd2 = win32gui.GetWindow(hwnd1, win32con.GW_CHILD)
    vlcHwnds.append(hwnd1)
    vlcHwnds.append(hwnd2)
    print("vlcHwnds", vlcHwnds)

app = QtWidgets.QApplication()
widget = QtWidgets.QWidget()
widget.mouseReleaseEvent = lambda *args: togglePlaying()
window = QtWidgets.QMainWindow()
window.setCentralWidget(widget)
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()
vlcHwnds = []

HookStruct = genStruct(
    "Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
windll.user32.SetWindowsHookExW(win32con.WH_MOUSE_LL, hookProc, None, 0)

filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(widget.winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()
app.exec_()

Solution Three: In-Process Mouse Hook

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 23:31
from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG, HINSTANCE

import vlc
import win32api
import win32con
import win32gui
from PySide2 import QtWidgets, QtCore

def genStruct(name="Structure", **kwargs):
    return type(name, (Structure,), dict(
        _fields_=list(kwargs.items()),
        __str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
    ))

@WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
    msg = cast(lParam, POINTER(HookStruct))[0]
    win32gui.PostMessage(widget.winId(), wParam, wParam, (msg.pt.y << 16) + msg.pt.x)
    return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))

def togglePlaying():
    player.get_state() == vlc.State.Ended and player.set_media(player.get_media())
    player.get_state() == vlc.State.Playing and player.pause()
    player.get_state() != vlc.State.Playing and player.play()

def onVideoOut(event):
    hwnd1 = win32gui.GetWindow(player.get_hwnd(), win32con.GW_CHILD)
    processId = win32api.GetModuleHandle()
    threadId = windll.user32.GetWindowThreadProcessId(hwnd1, None)
    windll.user32.SetWindowsHookExW(win32con.WH_MOUSE, hookProc, HINSTANCE(processId), threadId)

app = QtWidgets.QApplication()
window = QtWidgets.QMainWindow()
widget = QtWidgets.QWidget()
widget.mouseReleaseEvent = lambda *args: togglePlaying()
window.setCentralWidget(widget)
window.setWindowFlags(QtCore.Qt.WindowType.WindowCloseButtonHint)
window.resize(854, 480)
window.show()

HookStruct = genStruct(
    "Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
filename = r"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
player = vlc.MediaPlayer(filename)
player.set_hwnd(widget.winId())
player.event_manager().event_attach(vlc.EventType.MediaPlayerVout, onVideoOut)
player.play()

app.exec_()


问:
Can we replace every ColdFusion tag by equivalent cfscript statements?
I wanted to know can my cfml page or cfc components with with only cfscript tag?

Can we use it everywhere? Is there any limitation in its usage?

Edit:

I am curious because I read the following line

In addition to variable setting, other operations tend to be slightly
  faster in CFScript than in tags.

Read it here

答:
Most tags are now implemented as CFScript-ready implementations, but not all of them.  Contrary to what the previous poster said, CFMAIL is one of the ones that has already been done: http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSe9cbe5cf462523a0693d5dae123bcd28f6d-7ff9.html

As far as the other script coverage goes, it's in the docs:
http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-7feb.html

Note, one can definitely write CFCs entirely in script now:
http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSE99A664D-44E3-44d1-92A0-5FDF8D82B55C.html

But I would be cautious about doing this because not all tags are implemented in script yet, and if you suddenly find you need too use one of them in your script-only CFC... you're a bit stuck.

Also I think some constructs like CFQUERY are a more elegant solution than Query.cfc's approach.

As for the comment that CFScript is faster than tag-based code, that hasn't really been the case since the compiler changes in CFMX7.0.  Mostly the code compiles down to pretty much the same thing now.  Some operations are faster in CFScript, some are faster in tag-based code.  That said, these performance gains are going to be minimal compared to tuning your actual code or DB access or memory handling: I'd not refactor tag-based code to script-based code to try to find performance gains.


问:
How to add php 7 extensions using remi on CentOS 7
Please help with php 7 extensions on CentOS 7.

When trying to isntall extension, for example memcache and memcached using the command yum --enablerepo=remi-php74 install php-memcache php-memcached I got the message that this packages are already installed.

php --modules also shows they are present. But I can't find them in /etc/opt/remi/php74/php.d and /opt/remi/php74/root/lib64/php/modules.

I attached screenshot of phpinfo() as well phpinfo, there are no additional extensions...
Please advice what I'm doing wrong, I'm not very strong in this DevOPS things :-)

Also added php --ini response php --ini

答:
For a proper installation please follow the Wizard instructions

If you need a single version, php-* packages are simpler to install and use

If you need multiple versions, php74-php-* are available

You can read the repository FAQ: Difference between php-* and php##-php-* packages ?

So as you are running php74-php you need

```<code>yum install php74-php-pecl-memcache php74-php-pecl-memcached
</code>```

But if you need a single version, probably better to remove all php74* packages and only use php-* ones.

Body:
For a proper installation please follow the Wizard instructions

If you need a single version, php-* packages are simpler to install and use

If you need multiple versions, php74-php-* are available

You can read the repository FAQ: Difference between php-* and php##-php-* packages ?

So as you are running php74-php you need

yum install php74-php-pecl-memcache php74-php-pecl-memcached

But if you need a single version, probably better to remove all php74* packages and only use php-* ones.


问:
TypeError: 'str' object doesn't support item deletion
```<code>x = True
pizza = []
pizza_topping = []

while x:
    pizza_topping = input("Please enter your pizza toppings(type 'quit' to when you're done): ")

    if pizza_topping == 'quit':
        print(f'Thank you for your order. Your pizza toppings are: {pizza}')
        x = False
    else:
        pizza.append(pizza_topping)
        del pizza_topping[0]
</code>```

Dear people,

I get this error:

del pizza_topping[0] TypeError: 'str' object doesn't support item
deletion

What am I doing wrong?

Edit: I changed 'break' to x = False(this was my original code). It got mixed up.

答:
as @Samwise has already said (and the variable x is also not needed) perhaps try something like (which means your code was almost correct):</p>
```<code>pizza = []
while True:
    pizza_topping = input("Please enter your pizza toppings(type 'quit' to when you're done): ")
    if pizza_topping == 'quit':
        print(f'Thank you for your order. Your pizza toppings are: {pizza}')
        break
    else:
        pizza.append(pizza_topping)
</code>```

Body:
x = True
pizza = []
pizza_topping = []

while x:
    pizza_topping = input("Please enter your pizza toppings(type 'quit' to when you're done): ")

    if pizza_topping == 'quit':
        print(f'Thank you for your order. Your pizza toppings are: {pizza}')
        x = False
    else:
        pizza.append(pizza_topping)
        del pizza_topping[0]

Dear people,

I get this error:

del pizza_topping[0] TypeError: 'str' object doesn't support item
deletion

What am I doing wrong?

Edit: I changed 'break' to x = False(this was my original code). It got mixed up.

Body:
as @Samwise has already said (and the variable x is also not needed) perhaps try something like (which means your code was almost correct):

pizza = []
while True:
    pizza_topping = input("Please enter your pizza toppings(type 'quit' to when you're done): ")
    if pizza_topping == 'quit':
        print(f'Thank you for your order. Your pizza toppings are: {pizza}')
        break
    else:
        pizza.append(pizza_topping)


答:
If you want Test to create and reuse a disposable resource (e.g. HttpClient, then Test should implement IDisposable and should dispose of the resource in its Dispose method. That means that the class using Test should use a using block:

```<code>public async static void TestHttpClient()
{
    using (Test test1 = new Test())
    {
        test1.Method1();
        test1.Method2();
        test1.Method3();
    }
}
</code>```

Title: One httpClient for many method in one class

Body:
I would like to use one httpclient to many method in class.
Below is the simplified code:

public class test{

private readonly HttpClient _httpClient;

public Test(){
_httpClient = new HttpClient();
}

public void method1(){
using (_httpClient){
//...
}
}

public void method2(){
using (_httpClient){
//...
}
}

public void method3(){
using (_httpClient){
//...
}
}
}

Then it calls the method data:

public async static void TestHttpClient()
        {
            Test test1 = new Test();
            test1.Method1();
            test1.Method2();
            test1.Method3();
        }

Method 1 is working. When calling the second one I get the message: "You cannot access a deleted object."

Thanks for helps.

Regards

Body:
If you want Test to create and reuse a disposable resource (e.g. HttpClient, then Test should implement IDisposable and should dispose of the resource in its Dispose method. That means that the class using Test should use a using block:

public async static void TestHttpClient()
{
    using (Test test1 = new Test())
    {
        test1.Method1();
        test1.Method2();
        test1.Method3();
    }
}


问:
Multiple y-axis with different sizes
With Apache ECharts, is it possible to change the size of an y-axis, like on the screenshot below?
I was checking the API but couldn't find a way to do this.

答: Echarts has option Grid (https://echarts.apache.org/en/option.html#grid). It's the same as layer. You can make multiple grids and attach each axis to each grid. Next you should define grid coordinates on canvas and set height (https://echarts.apache.org/examples/en/editor.html?c=dataset-series-layout-by)</p>

Title: Multiple y-axis with different sizes


问:
React Native Maps Google pricing
As of 2022, does React Native Maps still free, or does go under any list of Google pricing?

I read this line on Reddit but it's 2 years ago

"Embedding Google Maps through react-native-maps does require an API key, but it is at no cost. Can confirm as I have an app at 100K users and haven't paid a dime for maps."

I am not sure if it is still the same.

This is my way of using it:

```<code>import { StyleSheet, Text, View, Button } from "react-native";
import MapView, {
  PROVIDER_GOOGLE,
  MAP_TYPES,
  PROVIDER_DEFAULT,
  UrlTile,
  Marker,
} from "react-native-maps";
import React, { useEffect } from "react";

export default function Home({ navigation }) {
  let location = {
    latitude: 30.259933,
    longitude: 31.412613,
    latitudeDelta: 0.009,
    longitudeDelta: 0.009,
  };

  return (
    <View style={styles.container}>
      <View style={styles.myMap}>
        <MapView
          style={{ flex: 1 }}
          showsUserLocation
          PROVIDER_GOOGLE
          MAP_TYPES="STANDARD"
        >
          <Marker
            title="Home"
            coordinate={{
              latitude: location.latitude,
              longitude: location.longitude,
            }}
          />
        </MapView>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffd",
    alignItems: "center",
    justifyContent: "center",
  },
  myMap: {
    flex: 2,
    backgroundColor: "white",
    width: "100%",
    marginTop: 30,
    marginBottom: 30,
  },
  map: {
    width: "100%",
    height: "100%",
  },
});
</code>```

I need some clarification

答:
See https://developers.google.com/maps/documentation/android-sdk/usage-and-billing#dynamic-maps

If you use a Map ID you will be charged. (This is new functionality)

Title: React Native Maps Google pricing

Body:
As of 2022, does React Native Maps still free, or does go under any list of Google pricing?

I read this line on Reddit but it's 2 years ago

"Embedding Google Maps through react-native-maps does require an API key, but it is at no cost. Can confirm as I have an app at 100K users and haven't paid a dime for maps."

I am not sure if it is still the same.

This is my way of using it:

import { StyleSheet, Text, View, Button } from "react-native";
import MapView, {
  PROVIDER_GOOGLE,
  MAP_TYPES,
  PROVIDER_DEFAULT,
  UrlTile,
  Marker,
} from "react-native-maps";
import React, { useEffect } from "react";

export default function Home({ navigation }) {
  let location = {
    latitude: 30.259933,
    longitude: 31.412613,
    latitudeDelta: 0.009,
    longitudeDelta: 0.009,
  };

  return (
    <View style={styles.container}>
      <View style={styles.myMap}>
        <MapView
          style={{ flex: 1 }}
          showsUserLocation
          PROVIDER_GOOGLE
          MAP_TYPES="STANDARD"
        >
          <Marker
            title="Home"
            coordinate={{
              latitude: location.latitude,
              longitude: location.longitude,
            }}
          />
        </MapView>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffd",
    alignItems: "center",
    justifyContent: "center",
  },
  myMap: {
    flex: 2,
    backgroundColor: "white",
    width: "100%",
    marginTop: 30,
    marginBottom: 30,
  },
  map: {
    width: "100%",
    height: "100%",
  },
});

I need some clarification


问:
Page refresh removes queryParams Angular Router
I access to an angular component with a route myApp/contact with some query params like so

```<code><div routerLink="../contact" [queryParams]="{ filter: 'myFilter' }"> </div>
</code>```

The query params are saved in a router state (implementation of RouterStateSerializer) so I can access them from my component and then display them.
When I navigate in the component, the url is now myApp/contact?filter=myFilter, which is good.

If I refresh the page, the url is now myApp/contact without the queryParams but I can still see them displayed on the page.

If I now refresh the page a second time, the url is again myApp/contact but now the queryParams are null when displayed on the page (which is logical because they weren't in the url anymore)

I noticed that when the route to myApp/contact is navigated, an another route request is made straight after @ngrx/router-store/navigated (see this 2nd request on capture below). I do not know where this second navigation request comes from, but it is during this one that the queryParams seem to be lost.

The question is, why my queryParams disappear when I refresh the page ? Is it cause of a configuration somewhere ? Why are there two navigation requests ?

These "2 navigation requests" occur only when I refresh this component page => none of my other pages have this behaviour (and I suspect it is because there are queryParams on this page)

I also have another Angular app which has some queryParams on some pages and I don't have the same behaviour when I refresh the page => the queryParams stay in the url, no matter the number of time I refresh the page

答:
I finally found what happened.
The second navigation came from my cookie management (CookieComponent)

```<code>ngAfterViewInit(): void {
    this.router.navigate([{ outlets: { popup: isDisplayed ? 'cookie' : null } }]);
}
</code>```

I don't really get why this second navigation occurs only when there are queryParams on the page. But refactoring this code as follow solved my problem

```<code>ngAfterViewInit(): void {
    if (display) {
      this.router.navigate([{ outlets: { popup: 'cookie' } }]);
    }
}
</code>```

So if you have a weird behaviour with your queryParams on a page, first check in your app if you have some this.router.navigate that may have been called during the page reload !

Body:
I access to an angular component with a route myApp/contact with some query params like so

The query params are saved in a router state (implementation of RouterStateSerializer) so I can access them from my component and then display them.
When I navigate in the component, the url is now myApp/contact?filter=myFilter, which is good.

If I refresh the page, the url is now myApp/contact without the queryParams but I can still see them displayed on the page.

If I now refresh the page a second time, the url is again myApp/contact but now the queryParams are null when displayed on the page (which is logical because they weren't in the url anymore)

I noticed that when the route to myApp/contact is navigated, an another route request is made straight after @ngrx/router-store/navigated (see this 2nd request on capture below). I do not know where this second navigation request comes from, but it is during this one that the queryParams seem to be lost.

The question is, why my queryParams disappear when I refresh the page ? Is it cause of a configuration somewhere ? Why are there two navigation requests ?

These "2 navigation requests" occur only when I refresh this component page => none of my other pages have this behaviour (and I suspect it is because there are queryParams on this page)

I also have another Angular app which has some queryParams on some pages and I don't have the same behaviour when I refresh the page => the queryParams stay in the url, no matter the number of time I refresh the page

Body:
I finally found what happened.
The second navigation came from my cookie management (CookieComponent)

ngAfterViewInit(): void {
    this.router.navigate([{ outlets: { popup: isDisplayed ? 'cookie' : null } }]);
}

I don't really get why this second navigation occurs only when there are queryParams on the page. But refactoring this code as follow solved my problem

ngAfterViewInit(): void {
    if (display) {
      this.router.navigate([{ outlets: { popup: 'cookie' } }]);
    }
}

So if you have a weird behaviour with your queryParams on a page, first check in your app if you have some this.router.navigate that may have been called during the page reload !


问:
pythonic way to access data in file structures
I want to access every value (~10000) in .txt files (~1000) stored in directories (~20) in the most efficient manner possible. When the data is grabbed I would like to place them in a HTML string. I do this in order to display a HTML page with tables for each file. Pseudo:

```<code>    fh=open('MyHtmlFile.html','w')
    fh.write('''<head>Lots of tables</head><body>''')
    for eachDirectory in rootFolder:

        for eachFile in eachDirectory:
            concat=''

            for eachData in eachFile:
               concat=concat+<tr><td>eachData</tr></td>
            table='''
                  <table>%s</table>
                  '''%(concat)
        fh.write(table)
    fh.write('''</body>''')
    fh.close()
</code>```

There must be a better way (I imagine it would take forever)! I've checked out set() and read a bit about hashtables but rather ask the experts before the hole is dug.

Thank you for your time!
/Karl

答:
```<code>import os, os.path
# If you're on Python 2.5 or newer, use 'with'
# needs 'from __future__ import with_statement' on 2.5
fh=open('MyHtmlFile.html','w')
fh.write('<html>\r\n<head><title>Lots of tables</title></head>\r\n<body>\r\n')
# this will recursively descend the tree
for dirpath, dirname, filenames in os.walk(rootFolder):
    for filename in filenames:
        # again, use 'with' on Python 2.5 or newer
        infile = open(os.path.join(dirpath, filename))
        # this will format the lines and join them, then format them into the table
        # If you're on Python 2.6 or newer you could use 'str.format' instead
        fh.write('<table>\r\n%s\r\n</table>' %
                     '\r\n'.join('<tr><td>%s</tr></td>' % line for line in infile))
        infile.close()
fh.write('\r\n</body></html>')
fh.close()
</code>```

Body:
I want to access every value (~10000) in .txt files (~1000) stored in directories (~20) in the most efficient manner possible. When the data is grabbed I would like to place them in a HTML string. I do this in order to display a HTML page with tables for each file. Pseudo:

    fh=open('MyHtmlFile.html','w')
    fh.write('''Lots of tables''')
    for eachDirectory in rootFolder:

        for eachFile in eachDirectory:
            concat=''

            for eachData in eachFile:
               concat=concat+
eachData

            table='''

%s

                  '''%(concat)
        fh.write(table)
    fh.write('''''')
    fh.close()

There must be a better way (I imagine it would take forever)! I've checked out set() and read a bit about hashtables but rather ask the experts before the hole is dug.

Thank you for your time!
/Karl


问:
What do the various convertstore errors mean?
I am trying to convert a 2 tier symbol store into a 3-tier symbol store using the convertstore.exe tool as described by Microsoft.

However, I get error messages which do not tell me much. Depending on which store I want to convert I get the following errors:

Failed initial checks.

Failed to lock Symbol Store. Error 0x00000003.

ERROR: Couldn't create X:\...\index2.txt. Error 0x00000005.

Sometimes convertstore seems to run without error message, but it hasn't converted the store.

What do these error messages mean and how to mitigate them?

答:
Failed initial checks.

Possible causes:

This error can happen if you run convertstore without any arguments.

Mitigation: Use the correct syntax convertstore.exe -s <store>

The symbol store is already a 3-tier store

Mitigation: none, if the symbol store is already a 3-tier store. The tool will only convert in one direction. It cannot convert back and forth.

Mitigation: If it isn't a 3-tier store, delete the file index2.txt.

Failed to lock Symbol Store. Error 0x00000003.

Possible causes:

The symbol store does not have a pingme.txt or 000Admin folder.

Mitigation: specify a symbol store, not an arbitrary folder that happens to contain some symbols.

Mitigation: create a zero byte file pingme.txt and an empty folder 000Admin.

Failed to move <pdb> > <pdb>. Error 0x00000005.

Possible causes:

The file is currently in use.

Mitigation: close other programs that may currently access the file, then delete index2.txt and run the command again.

You don't have write access to the symbol store.

Mitigation: use SysInternals Process Monitor to diagnose the issue. Note that convertstore will not use the drive letters of mapped network shares, but use the SMB share name instead.

Couldn't create index2.txt. Error 0x00000005.

Possible causes:

You don't have write access to the symbol store.

Mitigation: use SysInternals Process Monitor to diagnose the issue. Note that convertstore will not use the drive letters of mapped network shares, but use the SMB share name instead.

Failed to move <pdb> > <pdb>. Error 0x000000B7.

Possible causes:

The destination file already exists in the 3-tier part of the store. Someone worked on the symbol store in the meanwhile and downloaded new symbols, storing them in the 2-tier format. You now have them in two locations: a 2-tier folder and a 3-tier folder.

Mitigation: delete the 2-tier version manually.

No error message

Possible causes:

convertstore x64 version 10.0.22000.1 suffers from an access violation at convertstore!ConvertAdminFileW+0x1c9

Mitigation: submit the crash dump to Microsoft and hope that they will fix this. Then run the x86 (32 bit) version.


问:
How to update buffer?
I would like to know:

If a make two consecutive MPI_Isend requests, and if the destination processor has not yet receive the message inbetween the two calls, will the buffer be updated ?
I mean if I send message "0" for the first request, then send "1" as the second message. Will the receiver receive "0" as message ? I not, how can I do to update the message ?

Thanks

```<code>double message;
int i = 0;
 //First processor
 if (rank == 0)
    {

        for (i = 0; i < 2; i++)
        {
            message = i;
            MPI_Isend(&message, 1, MPI_DOUBLE, 1, 0, PETSC_COMM_WORLD, r_send);

        }

    }

    //Second processor
    if (rank == 1)
    {
            PetscSleep(10); // Make this processor sleep for 10 seconds
            int flag = 0;
            MPI_Irecv(&message, 1, MPI_DOUBLE, 0, 0, PETSC_COMM_WORLD, r_recv);
            MPI_Test(r_recv,&flag, r_status);
            while (!flag)
            {
                MPI_Test(r_recv,&flag, r_status);
            }
            printf("the message is %lf\n",message);

    }
</code>```

This code above will print "the message is 0". I want it to take into account the last update, not the first in-order messages.

答: MPI messages are "non-overtaking", meaning that the first message sent will be received first. So when you post your Irecv, that first message will be received. 2. I don't think the tests after the receive do anything useful. If your test says there is a message, you need a new receive to get it. 3. Why are you using a "ready" send? 4. Neither of your processes is doing a Wait call, so it could be that this whole program is Undefined Behavior.

Title: How to update buffer?

Body:
I would like to know:

If a make two consecutive MPI_Isend requests, and if the destination processor has not yet receive the message inbetween the two calls, will the buffer be updated ?
I mean if I send message "0" for the first request, then send "1" as the second message. Will the receiver receive "0" as message ? I not, how can I do to update the message ?

Thanks

double message;
int i = 0;
 //First processor
 if (rank == 0)
    {

        for (i = 0; i < 2; i++)
        {
            message = i;
            MPI_Isend(&message, 1, MPI_DOUBLE, 1, 0, PETSC_COMM_WORLD, r_send);

        }

    }

    //Second processor
    if (rank == 1)
    {
            PetscSleep(10); // Make this processor sleep for 10 seconds
            int flag = 0;
            MPI_Irecv(&message, 1, MPI_DOUBLE, 0, 0, PETSC_COMM_WORLD, r_recv);
            MPI_Test(r_recv,&flag, r_status);
            while (!flag)
            {
                MPI_Test(r_recv,&flag, r_status);
            }
            printf("the message is %lf\n",message);

    }

This code above will print "the message is 0". I want it to take into account the last update, not the first in-order messages.


问:
How to Do Firebase Special Character Sensitive Search?
https://example.com/foods.json?orderBy="title"&startAt="Yoğurt"&endAt="Yoğurt\uf8ff"

With the above link, I can search the data in Firebase Realtime Database Rest Api using startAt, endAt query parameters.

How can I find the results when searching with similar special characters?

For example, yoğurt and yogurt, kızartma and kizartma

I want to get the same result when written both ways.

If this is not possible with Firebase, is it possible with String methods in Javascript or Dart programming language?

答:
There is nothing built into Firebase for performing this type of search, so you will have to do your own work to allow it.

The simplest way is to store a secondary value for each string that you want to search, where you map each character back to a single representative value you want to search on.

A very common mapping is for example to map all text to a single case (uppercase or lowercase) so that searches become case-insensitive. You can do similar for the accented characters, mapping the ğ to g. So by combining these two tricks, Yoğurt becomes yogurt.

Same for the ı you show (and İ), mapping all four I variants in the Turkish alphabet to i.

Doing this for all special characters gives you a single string value (in addition to the user input, which you should also still store) that you can use for searches.

For more on this, I recommend also reading Dan's answer here.


问:
Query user's Outlook properties to see if they are a member of a specific distribution group in Outlook using Excel VBA
I wish to query a user's Outlook properties via Excel to see if they are a member of a specific distribution list.

We have four teams and also visitors known as Other.

The aim is to query if a user is a member of Team A Operators if so return a string value of Team A, elseif member of Team B operators return a string value of Team B and so on up to Team D. If not a member of any of those then return a string value of Other.

Also what is the user identifier for Outlook? Is it their email address or their login identification?

答: Use AddressEntry.GetExchangeUser.GetMemberOfList (returns AddressEntries collection) - see https://learn.microsoft.com/en-us/office/vba/api/outlook.exchangeuser.getmemberoflist


问:
Primefaces: OrderList fills backend list with String instead of Object
In my backend view, I have a list of some POJO:

BackingView.java

```<code>@Getter @Setter private List<SomePOJO> pojoList = ...
</code>```

SomePojo.java

```<code>@EqualsAndHashCode(callSuper = false, of = {"id"})
public class SomePojo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Getter @Setter private Long id;
    @Getter @Setter private Long date;
    @Getter @Setter private Date name;
    ....

  @Override
  public String toString() {
      return String.format("%s[id=%s]", getClass().getSimpleName(), id);
  }

  //making a readable string-representation of the object to display on the orderList
  public String toStringOrderlistDisplay() {
      return "Pojo with id " + id + "and so on... "
  }
</code>```

This list acts as you would expect in all regards. Recently, I wanted to add a feature to my frontend which allows the user to manually order this list. For that purpose I use Primefaces OrderList, like this:

Frontend.xhtml

```<code><p:orderList id="ordList" widgetVar="ordList"
                                     value="#{backingview.pojoList }" var="rfg"
                                     controlsLocation="left"  responsive="true" itemValue="#{rfg}"
                                     itemLabel="#{rfg.toStringOrderlistDisplay()}">

</p:orderList>
</code>```

As soon as I add the above p:orderList to my .xhtml file, I can see when inspecting in debug mode that pojoList no longer contains instances of PojoClass but rather plain strings (to be more precise, the string representation of the PojoClass-Object (What the toString() method would return)).
If I simply remove the orderList this problem does not occur. What is going on here? How is such a thing even possible in Java?

答:
I tried using a converter as shown here CountryConverter.java, and it worked.

Maybe when you don't specify a convertor, it uses a default .toString() implementation and can't serialize back to a PojoClass.

You can submit an issue here to see if it's a bug.

Body:
In my backend view, I have a list of some POJO:

BackingView.java

@Getter @Setter private List<SomePOJO> pojoList = ...

SomePojo.java

@EqualsAndHashCode(callSuper = false, of = {"id"})
public class SomePojo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Getter @Setter private Long id;
    @Getter @Setter private Long date;
    @Getter @Setter private Date name;
    ....

  @Override
  public String toString() {
      return String.format("%s[id=%s]", getClass().getSimpleName(), id);
  }

  //making a readable string-representation of the object to display on the orderList
  public String toStringOrderlistDisplay() {
      return "Pojo with id " + id + "and so on... "
  }

This list acts as you would expect in all regards. Recently, I wanted to add a feature to my frontend which allows the user to manually order this list. For that purpose I use Primefaces OrderList, like this:

Frontend.xhtml

As soon as I add the above p:orderList to my .xhtml file, I can see when inspecting in debug mode that pojoList no longer contains instances of PojoClass but rather plain strings (to be more precise, the string representation of the PojoClass-Object (What the toString() method would return)).
If I simply remove the orderList this problem does not occur. What is going on here? How is such a thing even possible in Java?


问:
Cookie “pardot” has been rejected because it is already expired
I’ve added pardot tracking script as specified here https://help.salesforce.com/s/articleView?id=000318309&type=1

```<code><script type="text/javascript">
    piAId = '12345';
    piCId = '1234';
    piHostname = 'pi.pardot.com';
    (function() {
        function async_load(){
            var s = document.createElement('script'); s.type = 'text/javascript';
            s.src = ('https:' == document.location.protocol ? 'https://pi' : 'http://cdn') + '.pardot.com/pd.js';
            var c = document.getElementsByTagName('script')[0]; c.parentNode.insertBefore(s, c);
        }
        if(window.attachEvent) {
            window.attachEvent('onload', async_load);
        }
        else {
            window.addEventListener('load', async_load, false);
        }
    })();
</script>
</code>```

This works perfectly on Chrome.

But, when I looked into console log of Mozilla Firefox browser, getting the error as :
Cookie "pardot" has been rejected because it is already expired.

How can I fix this?

Thank you in advance

答:
Check that you're serving a first-party cookie (as opposed to the default third-party deployed with the app. Firefox, Safari and Chrome will all block third-party cookies soon.

Firefox needs to be set to "Accept cookies from sites" from Preferences.  Depending on how your browser is configured

If you've gone thru steps one and two without success, you can actually change the cookie duration in Pardot Settings. You can choose to change a Pardot Cookie duration anywhere from a few months to up to ten year.

Body:
I’ve added pardot tracking script as specified here https://help.salesforce.com/s/articleView?id=000318309&type=1

This works perfectly on Chrome.

But, when I looked into console log of Mozilla Firefox browser, getting the error as :
Cookie "pardot" has been rejected because it is already expired.

How can I fix this?

Thank you in advance